From da689e03ac983499f9682c46889d454195e7231b Mon Sep 17 00:00:00 2001 From: monwiss <547445+monwiss@users.noreply.github.com> Date: Thu, 24 Sep 2026 17:15:39 -0400 Subject: [PATCH 001/171] refactor(providers): move the tile budget helpers out of the TomTom module utcDayKey, normalizeBudget and isOverBudget move unchanged to src/data/tileBudget.js. Nothing in them was TomTom-specific; the next keyed tile proxy (Xweather) counts a monthly allowance through the same two functions. tomtomTiles.js re-exports them, so the traffic provider and its tests keep their imports. Co-Authored-By: Claude Opus 5.5 (1M context) --- scripts/format-scope.json | 2 ++ scripts/package-boundaries.json | 12 ++++++-- src/data/tileBudget.js | 53 +++++++++++++++++++++++++++++++++ src/data/tileBudget.test.mjs | 26 ++++++++++++++++ src/data/tomtomTiles.js | 41 ++----------------------- 5 files changed, 94 insertions(+), 40 deletions(-) create mode 100644 src/data/tileBudget.js create mode 100644 src/data/tileBudget.test.mjs diff --git a/scripts/format-scope.json b/scripts/format-scope.json index eee546dd5..9b82af4b7 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -79,6 +79,8 @@ "src/data/terrainHeightsProxy.test.mjs", "src/data/tomtomTiles.js", "src/data/tomtomTiles.test.mjs", + "src/data/tileBudget.js", + "src/data/tileBudget.test.mjs", "src/data/firmsCsv.js", "src/data/firmsCsv.test.mjs", "src/tooling/environmentProviders.test.mjs", diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 189192f10..748f11d44 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -113,12 +113,16 @@ "traffic-provider": { "runtime": "node", "exports": ["./server/providers/traffic"], - "modules": ["server/providers/traffic.js", "src/data/tomtomTiles.js"], + "modules": [ + "server/providers/traffic.js", + "src/data/tomtomTiles.js", + "src/data/tileBudget.js" + ], "external": [] }, "traffic-source": { "exports": ["./sources/traffic"], - "modules": ["src/data/tomtomTiles.js"], + "modules": ["src/data/tomtomTiles.js", "src/data/tileBudget.js"], "external": [] }, "firms-csv": { @@ -1009,6 +1013,7 @@ "src/data/cameraSensitivity.js", "src/data/flowMatch.js", "src/data/tomtomTiles.js", + "src/data/tileBudget.js", "src/data/trafficBounds.js", "src/data/trafficFlowStyle.js", "src/data/trafficPresetStyle.js", @@ -1424,6 +1429,7 @@ "src/data/telegeographySubmarineCables.js", "src/data/terrainHeights.js", "src/data/tomtomTiles.js", + "src/data/tileBudget.js", "src/data/tr3bRegistry.js", "src/data/trackedCamera.js", "src/data/trackedModelRegime.js", @@ -2071,6 +2077,7 @@ "src/data/scenePick.js", "src/data/spriteOrder.js", "src/data/tomtomTiles.js", + "src/data/tileBudget.js", "src/data/tr3bRegistry.js", "src/data/trackedCamera.js", "src/data/trackedModelRegime.js", @@ -2707,6 +2714,7 @@ "exports": ["./layers/traffic/source"], "modules": [ "src/data/tomtomTiles.js", + "src/data/tileBudget.js", "src/layers/traffic/flowDecode.js", "src/layers/traffic/flowSource.js", "src/layers/traffic/source.js", diff --git a/src/data/tileBudget.js b/src/data/tileBudget.js new file mode 100644 index 000000000..dcc44a28c --- /dev/null +++ b/src/data/tileBudget.js @@ -0,0 +1,53 @@ +/** + * @file Upstream-request accounting shared by the keyed tile proxies. + * + * A soft cap per UTC period, persisted as `{date, count}` so it survives a + * restart. Nothing here is provider-specific: the caller picks the period by + * the key it passes, and decides what happens over the cap. + * + * Zero dependencies and Cesium-free, so providers and browser helpers can + * import it and node:test can exercise it directly. + * + * @module data/tileBudget + */ + +/** + * UTC calendar-day key for budget bucketing. + * + * @param {number} [epochMs=Date.now()] - Timestamp in ms. + * @returns {string} 'YYYY-MM-DD' in UTC. + */ +export function utcDayKey(epochMs = Date.now()) { + return new Date(epochMs).toISOString().slice(0, 10); +} + +/** + * Normalize a persisted budget state against today's UTC day key. + * Rolls the counter to zero on day change; replaces missing/corrupt state. + * Returns the SAME object when it is already valid for `dayKey` (cheap to + * call on every request). + * + * @param {{date:string, count:number}|null|undefined} state - Persisted state. + * @param {string} dayKey - Today's UTC day key (from `utcDayKey`). + * @returns {{date:string, count:number}} Valid state for `dayKey`. + */ +export function normalizeBudget(state, dayKey) { + const valid = + Boolean(state) && + state.date === dayKey && + Number.isFinite(state.count) && + state.count >= 0; + return valid ? state : { date: dayKey, count: 0 }; +} + +/** + * Whether the daily soft cap has been reached. + * + * @param {{count:number}} state - Normalized budget state. + * @param {number} limit - Daily tile budget; non-positive/invalid never blocks. + * @returns {boolean} True when `count >= limit`. + */ +export function isOverBudget(state, limit) { + if (!Number.isFinite(limit) || limit <= 0) return false; + return state.count >= limit; +} diff --git a/src/data/tileBudget.test.mjs b/src/data/tileBudget.test.mjs new file mode 100644 index 000000000..fa48440bb --- /dev/null +++ b/src/data/tileBudget.test.mjs @@ -0,0 +1,26 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { isOverBudget, normalizeBudget, utcDayKey } from './tileBudget.js'; +import * as tomtom from './tomtomTiles.js'; + +test('tile budget helpers live in one module and TomTom re-exports them', () => { + assert.equal(tomtom.utcDayKey, utcDayKey); + assert.equal(tomtom.normalizeBudget, normalizeBudget); + assert.equal(tomtom.isOverBudget, isOverBudget); +}); + +test('normalizeBudget keeps a valid state and resets another period', () => { + const state = { date: '2026-09-24', count: 3 }; + assert.equal(normalizeBudget(state, '2026-09-24'), state); + assert.deepEqual(normalizeBudget(state, '2026-09-25'), { + date: '2026-09-25', + count: 0, + }); + assert.deepEqual( + normalizeBudget({ date: '2026-09-24', count: -1 }, '2026-09-24'), + { + date: '2026-09-24', + count: 0, + }, + ); +}); diff --git a/src/data/tomtomTiles.js b/src/data/tomtomTiles.js index af4fc95b3..a1dbc18cb 100644 --- a/src/data/tomtomTiles.js +++ b/src/data/tomtomTiles.js @@ -131,42 +131,7 @@ export function tilesForBounds(bounds, zoom = 12, { maxTiles = 64 } = {}) { // ─── Daily budget accounting ─────────────────────────────── /** - * UTC calendar-day key for budget bucketing. - * - * @param {number} [epochMs=Date.now()] - Timestamp in ms. - * @returns {string} 'YYYY-MM-DD' in UTC. + * Re-exported from `./tileBudget.js`, which keyed tile proxies share. The + * traffic provider and its tests keep one import for tile math and budget. */ -export function utcDayKey(epochMs = Date.now()) { - return new Date(epochMs).toISOString().slice(0, 10); -} - -/** - * Normalize a persisted budget state against today's UTC day key. - * Rolls the counter to zero on day change; replaces missing/corrupt state. - * Returns the SAME object when it is already valid for `dayKey` (cheap to - * call on every request). - * - * @param {{date:string, count:number}|null|undefined} state - Persisted state. - * @param {string} dayKey - Today's UTC day key (from `utcDayKey`). - * @returns {{date:string, count:number}} Valid state for `dayKey`. - */ -export function normalizeBudget(state, dayKey) { - const valid = - Boolean(state) && - state.date === dayKey && - Number.isFinite(state.count) && - state.count >= 0; - return valid ? state : { date: dayKey, count: 0 }; -} - -/** - * Whether the daily soft cap has been reached. - * - * @param {{count:number}} state - Normalized budget state. - * @param {number} limit - Daily tile budget; non-positive/invalid never blocks. - * @returns {boolean} True when `count >= limit`. - */ -export function isOverBudget(state, limit) { - if (!Number.isFinite(limit) || limit <= 0) return false; - return state.count >= limit; -} +export { utcDayKey, normalizeBudget, isOverBudget } from './tileBudget.js'; From 0c2e5727a5c1748323986eb901bc2cf31006b5a2 Mon Sep 17 00:00:00 2001 From: Kevin Rajan <7121943+kvnloo@users.noreply.github.com> Date: Mon, 28 Sep 2026 20:52:44 -0500 Subject: [PATCH 002/171] feat(voice): reason-code viewport context escalation --- src/voice/realtimeViewport.js | 59 ++++++++++++++++++++++++++++------- 1 file changed, 47 insertions(+), 12 deletions(-) diff --git a/src/voice/realtimeViewport.js b/src/voice/realtimeViewport.js index fd93996af..c41049d4c 100644 --- a/src/voice/realtimeViewport.js +++ b/src/voice/realtimeViewport.js @@ -11,6 +11,31 @@ export const VIEWPORT_MAX_PIXELS = 1200 * 900; // ~1.08 MP, matches the old 1200px-wide landscape budget export const VIEWPORT_MAX_ENCODED_BYTES = 200 * 1024; +/** + * Explain whether the existing Realtime path should escalate structured entity + * context to a viewport image. This is instrumentation vocabulary only; it + * preserves the current send policy exactly. + */ +export function viewportContextDecision(result, { channelOpen = true } = {}) { + if (result?.action !== 'get_entity_context') + return { send: false, reason: 'not-entity-context' }; + if (!channelOpen) return { send: false, reason: 'channel-closed' }; + const viewScale = result.scene?.basemap?.viewScale ?? null; + if (!shouldSendViewportImage(viewScale)) + return { send: false, reason: 'view-scale-not-local', viewScale }; + if (hasStructuredViewIdentity(result)) + return { + send: false, + reason: 'structured-identity-sufficient', + viewScale, + }; + return { + send: true, + reason: 'structured-identity-missing', + viewScale, + }; +} + export async function captureViewportImage() { const viewer = window.__godsEyeView?.viewer; const source = @@ -179,25 +204,31 @@ export class RealtimeViewport { } async sendVisualContextIfUseful(result) { - if ( - result?.action !== 'get_entity_context' || - !this.dc || - this.dc.readyState !== 'open' - ) - return false; - const viewScale = result.scene?.basemap?.viewScale; - if (!shouldSendViewportImage(viewScale)) return false; - if (hasStructuredViewIdentity(result)) return false; - const generation = this.generation; const channel = this.dc; + const decision = viewportContextDecision(result, { + channelOpen: channel?.readyState === 'open', + }); + this.debugLog?.('viewport_context.decision', decision); + if (!decision.send) return false; + + const generation = this.generation; const imageUrl = await this.capture(); + if (!imageUrl) { + this.debugLog?.('viewport_context.skipped', { + reason: 'capture-unavailable', + }); + return false; + } if ( - !imageUrl || generation !== this.generation || this.dc !== channel || channel.readyState !== 'open' - ) + ) { + this.debugLog?.('viewport_context.skipped', { + reason: 'session-changed-during-capture', + }); return false; + } // Keep at most one viewport screenshot in context. Images are the single // most expensive item (re-billed every turn they linger), so we proactively @@ -257,6 +288,10 @@ export class RealtimeViewport { 'client.viewport_context', ); this.lastViewportItemId = sent ? newItemId : null; + this.debugLog?.('viewport_context.result', { + sent, + reason: sent ? 'sent' : 'data-channel-send-failed', + }); return sent; } From 073ffedc1fbccfe64ed1b9bad6ce636dad23c859 Mon Sep 17 00:00:00 2001 From: Kevin Rajan <7121943+kvnloo@users.noreply.github.com> Date: Mon, 28 Sep 2026 20:52:54 -0500 Subject: [PATCH 003/171] feat(voice): route viewport decisions to diagnostics --- src/voice/realtimeController.js | 1 + 1 file changed, 1 insertion(+) diff --git a/src/voice/realtimeController.js b/src/voice/realtimeController.js index d0c9f1bae..285d0451b 100644 --- a/src/voice/realtimeController.js +++ b/src/voice/realtimeController.js @@ -82,6 +82,7 @@ export class GevRealtimeController extends RealtimeFacade { operations: { sendRealtimeEvent: (...args) => this.sendRealtimeEvent(...args), + debugLog: (...args) => this.debugLog(...args), }, }); this._diagnostics = new RealtimeDiagnostics({ From 3a40117e0619f477e7451cf57475670f9ccdcf99 Mon Sep 17 00:00:00 2001 From: Kevin Rajan <7121943+kvnloo@users.noreply.github.com> Date: Mon, 28 Sep 2026 20:53:12 -0500 Subject: [PATCH 004/171] test(voice): pin viewport escalation reasons --- src/voice/realtimeViewportPolicy.test.mjs | 72 +++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 src/voice/realtimeViewportPolicy.test.mjs diff --git a/src/voice/realtimeViewportPolicy.test.mjs b/src/voice/realtimeViewportPolicy.test.mjs new file mode 100644 index 000000000..b2d135597 --- /dev/null +++ b/src/voice/realtimeViewportPolicy.test.mjs @@ -0,0 +1,72 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { viewportContextDecision } from './realtimeViewport.js'; + +const localContext = (overrides = {}) => ({ + action: 'get_entity_context', + scene: { basemap: { viewScale: 'local' } }, + ...overrides, +}); + +test('viewport context reasons preserve the existing escalation gate', () => { + assert.deepEqual(viewportContextDecision({ action: 'get_current_view_state' }), { + send: false, + reason: 'not-entity-context', + }); + assert.deepEqual( + viewportContextDecision(localContext(), { channelOpen: false }), + { send: false, reason: 'channel-closed' }, + ); + assert.deepEqual( + viewportContextDecision({ + action: 'get_entity_context', + scene: { basemap: { viewScale: 'regional' } }, + }), + { + send: false, + reason: 'view-scale-not-local', + viewScale: 'regional', + }, + ); + assert.deepEqual( + viewportContextDecision( + localContext({ + selected: { + id: 'earthquake:1', + layerId: 'earthquakes', + }, + }), + ), + { + send: false, + reason: 'structured-identity-sufficient', + viewScale: 'local', + }, + ); + assert.deepEqual(viewportContextDecision(localContext()), { + send: true, + reason: 'structured-identity-missing', + viewScale: 'local', + }); +}); + +test('nearby structured place identity avoids visual escalation too', () => { + assert.deepEqual( + viewportContextDecision( + localContext({ + scene: { + basemap: { + viewScale: 'local', + nearbyPlaces: [{ name: 'Austin' }], + }, + }, + }), + ), + { + send: false, + reason: 'structured-identity-sufficient', + viewScale: 'local', + }, + ); +}); From 86969f8a11812be9f8a2133cd4d6bbf74c365614 Mon Sep 17 00:00:00 2001 From: Kevin Rajan <7121943+kvnloo@users.noreply.github.com> Date: Mon, 28 Sep 2026 20:53:15 -0500 Subject: [PATCH 005/171] chore(format): adopt viewport policy tests --- scripts/format-scope.json | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/format-scope.json b/scripts/format-scope.json index cd836a5cb..16041e033 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -603,6 +603,7 @@ "src/voice/control.js", "src/voice/realtimeBackend.js", "src/voice/realtimeBackend.test.mjs", + "src/voice/realtimeViewportPolicy.test.mjs", "src/voice/layerSummary.js", "build/application-html.js", "src/app/sourceSlot.js", From 5195012c7f3ea322c1717d2cf9078d898ae54936 Mon Sep 17 00:00:00 2001 From: Kevin Rajan <7121943+kvnloo@users.noreply.github.com> Date: Mon, 28 Sep 2026 20:55:51 -0500 Subject: [PATCH 006/171] debug(format): print viewport policy canonical output --- scripts/format.mjs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/scripts/format.mjs b/scripts/format.mjs index 25311ba29..e1f2d4ca6 100644 --- a/scripts/format.mjs +++ b/scripts/format.mjs @@ -120,6 +120,15 @@ export async function formatAdoptedFiles(root, mode) { } const changed = files.filter(({ source, formatted }) => source !== formatted); + if (mode === '--check') { + const target = changed.find( + ({ name }) => name === 'src/voice/realtimeViewportPolicy.test.mjs', + ); + if (target) + console.error( + `FORMAT_EXPECTED BEGIN\n${target.formatted}FORMAT_EXPECTED END`, + ); + } if (mode === '--write') { for (const { file, formatted } of changed) await writeFile(file, formatted); } From 989e740d6efb9276f22f80a638d402776029a0c2 Mon Sep 17 00:00:00 2001 From: Kevin Rajan <7121943+kvnloo@users.noreply.github.com> Date: Mon, 28 Sep 2026 20:57:43 -0500 Subject: [PATCH 007/171] style(voice): format viewport policy tests --- src/voice/realtimeViewportPolicy.test.mjs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/voice/realtimeViewportPolicy.test.mjs b/src/voice/realtimeViewportPolicy.test.mjs index b2d135597..cd49cd3f0 100644 --- a/src/voice/realtimeViewportPolicy.test.mjs +++ b/src/voice/realtimeViewportPolicy.test.mjs @@ -10,10 +10,13 @@ const localContext = (overrides = {}) => ({ }); test('viewport context reasons preserve the existing escalation gate', () => { - assert.deepEqual(viewportContextDecision({ action: 'get_current_view_state' }), { - send: false, - reason: 'not-entity-context', - }); + assert.deepEqual( + viewportContextDecision({ action: 'get_current_view_state' }), + { + send: false, + reason: 'not-entity-context', + }, + ); assert.deepEqual( viewportContextDecision(localContext(), { channelOpen: false }), { send: false, reason: 'channel-closed' }, From cacbbc972bf8ada8314a2a62b7cdae1abefa6c0c Mon Sep 17 00:00:00 2001 From: Kevin Rajan <7121943+kvnloo@users.noreply.github.com> Date: Mon, 28 Sep 2026 20:57:48 -0500 Subject: [PATCH 008/171] chore: remove temporary formatter diagnostics --- scripts/format.mjs | 9 --------- 1 file changed, 9 deletions(-) diff --git a/scripts/format.mjs b/scripts/format.mjs index e1f2d4ca6..25311ba29 100644 --- a/scripts/format.mjs +++ b/scripts/format.mjs @@ -120,15 +120,6 @@ export async function formatAdoptedFiles(root, mode) { } const changed = files.filter(({ source, formatted }) => source !== formatted); - if (mode === '--check') { - const target = changed.find( - ({ name }) => name === 'src/voice/realtimeViewportPolicy.test.mjs', - ); - if (target) - console.error( - `FORMAT_EXPECTED BEGIN\n${target.formatted}FORMAT_EXPECTED END`, - ); - } if (mode === '--write') { for (const { file, formatted } of changed) await writeFile(file, formatted); } From b09db551495e2c9e51c8ff30c903f9e1a4c851c3 Mon Sep 17 00:00:00 2001 From: daikaginza Date: Mon, 28 Sep 2026 11:53:13 +0700 Subject: [PATCH 009/171] fix(server): declare the method contract on the three read-only query proxies MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit /api/opensky, /api/adsblol/mil and /api/route answered any verb with the same body while ignoring the request entirely. Measured against a running server before the change: POST /api/opensky returned 200 with 833,759 bytes of live state vectors, POST /api/adsblol/mil returned 47,372 bytes. Their siblings do not: /api/geocode, /api/weather and /api/transit answer 405, and /api/overpass is deliberately POST-only. These three are read-only query proxies, so they now answer 405 to anything but GET, using the wording and shape /api/geocode already uses. The refusal comes first, before rate limiting and before any upstream call, which the tests assert by stubbing fetch to throw. Scope, stated plainly: this is a consistency and intent fix. No rate limiter was being bypassed — /api/route already limits every request regardless of verb, and the two aircraft routes have no limiter at all, only 9s and 12s server-side caches that bound upstream cost for any method. One existing fixture in src/search/geospatial.test.mjs built a request without a method, which a real Node request always has; it now sets GET. Verified on a running server after the change: GET still 200 on all three, POST 405 on all three, /api/overpass and the other proxies unchanged. Suite goes from 5090 to 5092 tests, 0 failures. --- docs/CURRENT-STATE.md | 1 + server/providers/aircraft/adsb-lol.js | 7 +++++++ server/providers/aircraft/opensky.js | 8 ++++++++ server/providers/places/routes.js | 7 +++++++ src/search/geospatial.test.mjs | 6 +++++- src/tooling/liveProviders.test.mjs | 23 +++++++++++++++++++++++ src/tooling/placeProviders.test.mjs | 19 +++++++++++++++++++ 7 files changed, 70 insertions(+), 1 deletion(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 22ce1eb3b..15e159ac8 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -4072,6 +4072,7 @@ are omitted rather than framing the wrong part of the globe. - `/api/overpass` is bounded by body/response caps, per-client/global rate limits, concurrency limits, operator-configured upstreams, in-flight dedupe, cache bounds, and static validation that every selector is spatially bounded. - `/api/military-installations` uses an independent limiter with the same 90-per-client/300-global one-minute bounds, so viewport installation refreshes never consume `/api/overpass` annotation capacity. - `/api/route` proxies bounded OSRM route requests for annotation routes, with profile allowlisting, distance caps, response caps, caching, and sanitized "no route found" errors. +- `/api/opensky`, `/api/adsblol/mil`, and `/api/route` are read-only query proxies and answer `405 Method Not Allowed` to anything but `GET`, as `/api/geocode` and the other query proxies already did. The refusal precedes rate limiting and any upstream call. - Track endpoints: `/api/ais-live/track?mmsi=` (server-accumulated ring buffers; sub-route handled before the rows snapshot), `/api/opensky-track?icao24=` (OAuth, 60s cache, sanitized errors, independent OpenSky credit bucket), `/api/adsblol/trace?hex=` (60s cache, 5MB cap, ODbL attribution required in UI). - Realtime debug logs redact API keys, bearer tokens, client secrets, and image data URLs before writing to disk; request bodies are size-capped. - `/api/realtime/debug-log` enforces an always-on 120-per-client/400-global one-minute limiter (not the opt-in `GEV_RATELIMIT_OPENAI_PER_MIN` bucket the cost-bearing OpenAI routes share), appends asynchronously through a serialized queue, and rotates `realtime-conversations.jsonl` at 32 MB keeping one prior generation, so the sink is bounded at twice that regardless of session length. A malformed record answers 400 and a failed write 500, both with a fixed message. diff --git a/server/providers/aircraft/adsb-lol.js b/server/providers/aircraft/adsb-lol.js index fc5ab0bd3..80140bb56 100644 --- a/server/providers/aircraft/adsb-lol.js +++ b/server/providers/aircraft/adsb-lol.js @@ -68,6 +68,13 @@ export function adsbLolProxy() { const installMiddleware = (server) => { server.middlewares.use('/api/adsblol/mil', async (req, res) => { + // Read-only snapshot endpoint; match the method contract its sibling + // query proxies already declare instead of serving every verb alike. + if (req.method !== 'GET') { + res.writeHead(405, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'Method Not Allowed' })); + return; + } try { const now = Date.now(); if (_cache && now - _cacheAt < CACHE_MS) { diff --git a/server/providers/aircraft/opensky.js b/server/providers/aircraft/opensky.js index 612d01e11..aa0dad268 100644 --- a/server/providers/aircraft/opensky.js +++ b/server/providers/aircraft/opensky.js @@ -350,6 +350,14 @@ function openSkySourceIsStale(sourceEpochMs, now = Date.now()) { export function openSkyProxy() { const installMiddleware = (server) => { server.middlewares.use('/api/opensky', async (req, res) => { + // Read-only snapshot endpoint: state the method contract the way + // /api/geocode and the other query proxies state it, rather than + // answering any verb with the same body and ignoring the request body. + if (req.method !== 'GET') { + res.writeHead(405, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'Method Not Allowed' })); + return; + } try { const requestedMode = normalizeOpenSkyAuthMode( process.env.OPENSKY_AUTH_MODE, diff --git a/server/providers/places/routes.js b/server/providers/places/routes.js index 42e24ad32..8e837fcd4 100644 --- a/server/providers/places/routes.js +++ b/server/providers/places/routes.js @@ -227,6 +227,13 @@ export function installRouteMiddleware( // only shape that asks the upstream for them. A response WITHOUT steps is // byte for byte what this endpoint has always returned. middlewares.use('/api/route', async (req, res) => { + // The documented shape above is a GET with query parameters; say so, + // the way the other query proxies do, instead of answering any verb. + if (req.method !== 'GET') { + res.writeHead(405, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'Method Not Allowed' })); + return; + } const fail = (msg) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ ok: false, error: msg })); diff --git a/src/search/geospatial.test.mjs b/src/search/geospatial.test.mjs index be846bb36..dbedbe53f 100644 --- a/src/search/geospatial.test.mjs +++ b/src/search/geospatial.test.mjs @@ -209,7 +209,11 @@ test('routing middleware uses configured OSRM servers while retaining request bo const request = async (query) => { let payload; await handler( - { url: `/?${query}`, socket: { remoteAddress: '127.0.0.1' } }, + { + url: `/?${query}`, + method: 'GET', + socket: { remoteAddress: '127.0.0.1' }, + }, { writeHead() {}, end(body) { diff --git a/src/tooling/liveProviders.test.mjs b/src/tooling/liveProviders.test.mjs index 38953eff9..c25c445d4 100644 --- a/src/tooling/liveProviders.test.mjs +++ b/src/tooling/liveProviders.test.mjs @@ -381,3 +381,26 @@ test('track backfill proxy returns 502 on an oversized upstream body and caches assert.equal(res2.statusCode, 502); assert.equal(callCount, 1); }); + +test('the aircraft snapshot routes decline a non-GET before any upstream work', async (t) => { + // Both routes answered every verb with the full snapshot, unlike the query + // proxies beside them, so nothing said whether a body was read or ignored. + // A stubbed fetch that throws proves the refusal happens before the handler + // reaches upstream, rather than after paying for the work and discarding it. + t.mock.method(globalThis, 'fetch', async (url) => { + throw new Error(`upstream must not be reached: ${url}`); + }); + const cases = [ + [install(providers.openSkyProxy()), '/api/opensky'], + [install(providers.adsbLolProxy()), '/api/adsblol/mil'], + ]; + for (const [request, route] of cases) { + for (const method of ['POST', 'PUT', 'DELETE', 'PATCH']) { + const response = await request(route, '/', method); + assert.equal(response.statusCode, 405, `${method} ${route}`); + assert.deepEqual(JSON.parse(response.body), { + error: 'Method Not Allowed', + }); + } + } +}); diff --git a/src/tooling/placeProviders.test.mjs b/src/tooling/placeProviders.test.mjs index 78d311369..968c5a9fa 100644 --- a/src/tooling/placeProviders.test.mjs +++ b/src/tooling/placeProviders.test.mjs @@ -482,3 +482,22 @@ test('the upstream host is pinned: a redirect is refused, not followed', async ( await request('/api/route', '?profile=car&coords=-97,30;-97.01,30.01'); assert.deepEqual(seen, ['error'], 'a redirect would escape the pinned host'); }); + +test('the routing proxy declines a non-GET before rate limiting or upstream', async (t) => { + // The documented shape is a GET with query parameters, but every verb was + // answered alike. Refuse first: a stubbed fetch that throws shows the + // rejection costs neither an upstream call nor a rate-limit slot. + const request = install(installRouteMiddleware); + t.mock.method(globalThis, 'fetch', async () => { + throw new Error('upstream must not be reached'); + }); + for (const method of ['POST', 'PUT', 'DELETE', 'PATCH']) { + const response = await request( + '/api/route', + '?profile=car&coords=-97,30;-97.01,30.01', + method, + ); + assert.equal(response.statusCode, 405, method); + assert.deepEqual(response.body, { error: 'Method Not Allowed' }); + } +}); From fb6b4e34f0aab85c715146739152d753d5a3efa8 Mon Sep 17 00:00:00 2001 From: daikaginza Date: Mon, 28 Sep 2026 13:16:17 +0700 Subject: [PATCH 010/171] docs: changelog entry for the read-only proxy method contract (#794) --- CHANGELOG.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 58103d04d..7885f0131 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +- The read-only query proxies state their method contract. `/api/opensky`, + `/api/adsblol/mil` and `/api/route` answered any verb with the same body + while ignoring the request; they now answer `405 Method Not Allowed` to + anything but `GET`, the way `/api/geocode` and the other query proxies + already did, and declare `Allow: GET` with it the way `/api/radio/stations` + does. The refusal precedes rate limiting and any upstream call + (daikaginza, #794). + - Public Overpass instances are no longer used by default. Street Traffic roads come from TomTom flow tiles, OpenFreeMap vector tiles, or both, chosen on the layer row (TomTom / OSM / Hybrid) or with `?trafficRoads=`. With a From 2e5dfce1af9b07664005bd1bd77e5bcb4ccf0ba4 Mon Sep 17 00:00:00 2001 From: daikaginza Date: Tue, 29 Sep 2026 10:56:20 +0700 Subject: [PATCH 011/171] fix(server): declare Allow: GET on the new 405 responses RFC 9110 section 15.5.6 requires a 405 to name the methods it accepts, and /api/radio/stations already does this in-tree. Thanks to kvnloo for catching it on review. The same gap on the pre-existing handlers is tracked in #809 and is deliberately left alone here. --- docs/CURRENT-STATE.md | 2 +- server/providers/aircraft/adsb-lol.js | 5 ++++- server/providers/aircraft/opensky.js | 5 ++++- server/providers/places/routes.js | 2 +- src/tooling/liveProviders.test.mjs | 3 +++ src/tooling/placeProviders.test.mjs | 2 ++ 6 files changed, 15 insertions(+), 4 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 15e159ac8..6e3039920 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -4072,7 +4072,7 @@ are omitted rather than framing the wrong part of the globe. - `/api/overpass` is bounded by body/response caps, per-client/global rate limits, concurrency limits, operator-configured upstreams, in-flight dedupe, cache bounds, and static validation that every selector is spatially bounded. - `/api/military-installations` uses an independent limiter with the same 90-per-client/300-global one-minute bounds, so viewport installation refreshes never consume `/api/overpass` annotation capacity. - `/api/route` proxies bounded OSRM route requests for annotation routes, with profile allowlisting, distance caps, response caps, caching, and sanitized "no route found" errors. -- `/api/opensky`, `/api/adsblol/mil`, and `/api/route` are read-only query proxies and answer `405 Method Not Allowed` to anything but `GET`, as `/api/geocode` and the other query proxies already did. The refusal precedes rate limiting and any upstream call. +- `/api/opensky`, `/api/adsblol/mil`, and `/api/route` are read-only query proxies and answer `405 Method Not Allowed` to anything but `GET`, as `/api/geocode` and the other query proxies already did, declaring `Allow: GET` with it as `/api/radio/stations` does. The refusal precedes rate limiting and any upstream call. - Track endpoints: `/api/ais-live/track?mmsi=` (server-accumulated ring buffers; sub-route handled before the rows snapshot), `/api/opensky-track?icao24=` (OAuth, 60s cache, sanitized errors, independent OpenSky credit bucket), `/api/adsblol/trace?hex=` (60s cache, 5MB cap, ODbL attribution required in UI). - Realtime debug logs redact API keys, bearer tokens, client secrets, and image data URLs before writing to disk; request bodies are size-capped. - `/api/realtime/debug-log` enforces an always-on 120-per-client/400-global one-minute limiter (not the opt-in `GEV_RATELIMIT_OPENAI_PER_MIN` bucket the cost-bearing OpenAI routes share), appends asynchronously through a serialized queue, and rotates `realtime-conversations.jsonl` at 32 MB keeping one prior generation, so the sink is bounded at twice that regardless of session length. A malformed record answers 400 and a failed write 500, both with a fixed message. diff --git a/server/providers/aircraft/adsb-lol.js b/server/providers/aircraft/adsb-lol.js index 80140bb56..1e5565832 100644 --- a/server/providers/aircraft/adsb-lol.js +++ b/server/providers/aircraft/adsb-lol.js @@ -71,7 +71,10 @@ export function adsbLolProxy() { // Read-only snapshot endpoint; match the method contract its sibling // query proxies already declare instead of serving every verb alike. if (req.method !== 'GET') { - res.writeHead(405, { 'Content-Type': 'application/json' }); + res.writeHead(405, { + 'Content-Type': 'application/json', + Allow: 'GET', + }); res.end(JSON.stringify({ error: 'Method Not Allowed' })); return; } diff --git a/server/providers/aircraft/opensky.js b/server/providers/aircraft/opensky.js index aa0dad268..679548300 100644 --- a/server/providers/aircraft/opensky.js +++ b/server/providers/aircraft/opensky.js @@ -354,7 +354,10 @@ export function openSkyProxy() { // /api/geocode and the other query proxies state it, rather than // answering any verb with the same body and ignoring the request body. if (req.method !== 'GET') { - res.writeHead(405, { 'Content-Type': 'application/json' }); + res.writeHead(405, { + 'Content-Type': 'application/json', + Allow: 'GET', + }); res.end(JSON.stringify({ error: 'Method Not Allowed' })); return; } diff --git a/server/providers/places/routes.js b/server/providers/places/routes.js index 8e837fcd4..2c67f1f5c 100644 --- a/server/providers/places/routes.js +++ b/server/providers/places/routes.js @@ -230,7 +230,7 @@ export function installRouteMiddleware( // The documented shape above is a GET with query parameters; say so, // the way the other query proxies do, instead of answering any verb. if (req.method !== 'GET') { - res.writeHead(405, { 'Content-Type': 'application/json' }); + res.writeHead(405, { 'Content-Type': 'application/json', Allow: 'GET' }); res.end(JSON.stringify({ error: 'Method Not Allowed' })); return; } diff --git a/src/tooling/liveProviders.test.mjs b/src/tooling/liveProviders.test.mjs index c25c445d4..856a528a2 100644 --- a/src/tooling/liveProviders.test.mjs +++ b/src/tooling/liveProviders.test.mjs @@ -398,6 +398,9 @@ test('the aircraft snapshot routes decline a non-GET before any upstream work', for (const method of ['POST', 'PUT', 'DELETE', 'PATCH']) { const response = await request(route, '/', method); assert.equal(response.statusCode, 405, `${method} ${route}`); + // RFC 9110 section 15.5.6 requires a 405 to name the methods it does + // accept, which is what `/api/radio/stations` already does in-tree. + assert.equal(response.headers.allow, 'GET', `${method} ${route}`); assert.deepEqual(JSON.parse(response.body), { error: 'Method Not Allowed', }); diff --git a/src/tooling/placeProviders.test.mjs b/src/tooling/placeProviders.test.mjs index 968c5a9fa..afc323efc 100644 --- a/src/tooling/placeProviders.test.mjs +++ b/src/tooling/placeProviders.test.mjs @@ -498,6 +498,8 @@ test('the routing proxy declines a non-GET before rate limiting or upstream', as method, ); assert.equal(response.statusCode, 405, method); + // RFC 9110 section 15.5.6 requires a 405 to name the methods it accepts. + assert.equal(response.headers.allow, 'GET', method); assert.deepEqual(response.body, { error: 'Method Not Allowed' }); } }); From 050f68ac03ea65a27627517f8f72b4e814398568 Mon Sep 17 00:00:00 2001 From: Kevin Rajan <7121943+kvnloo@users.noreply.github.com> Date: Fri, 16 Oct 2026 23:37:22 -0500 Subject: [PATCH 012/171] test(voice): classify current-frame send and cancellation outcomes Keep viewport and pointer-crop capture unchanged, but expose static reason codes for unavailable frames, invalidated turn captures and retained image sends. No image or user text in diagnostics. --- src/voice/realtimeViewport.js | 16 +++++- src/voice/realtimeViewportPolicy.test.mjs | 61 +++++++++++++++++++++++ 2 files changed, 75 insertions(+), 2 deletions(-) diff --git a/src/voice/realtimeViewport.js b/src/voice/realtimeViewport.js index 9ab1b07a6..8ba50c73b 100644 --- a/src/voice/realtimeViewport.js +++ b/src/voice/realtimeViewport.js @@ -437,15 +437,24 @@ export class RealtimeViewport { const captured = await captureImage(); const imageUrl = typeof captured === 'string' ? captured : captured?.dataUrl || null; + if (!imageUrl) { + this.debugLog?.('viewport_context.skipped', { + reason: 'capture-unavailable', + }); + return false; + } if ( - !imageUrl || generation !== this.generation || request !== this.captureSeq || this.dc !== channel || channel.readyState !== 'open' || (typeof frame.valid === 'function' && !frame.valid()) - ) + ) { + this.debugLog?.('viewport_context.skipped', { + reason: 'capture-invalidated', + }); return false; + } // Keep at most one viewport screenshot in context. Images are the single // most expensive item (re-billed every turn they linger), so we proactively @@ -506,6 +515,9 @@ export class RealtimeViewport { cameraKey: this.readCameraKey(), } : null; + this.debugLog?.('viewport_context.result', { + reason: sent ? 'sent' : 'data-channel-send-failed', + }); return sent; } diff --git a/src/voice/realtimeViewportPolicy.test.mjs b/src/voice/realtimeViewportPolicy.test.mjs index 5a361bcb5..3398f2a09 100644 --- a/src/voice/realtimeViewportPolicy.test.mjs +++ b/src/voice/realtimeViewportPolicy.test.mjs @@ -179,3 +179,64 @@ test('closed channel never captures pointer or full viewport', async () => { ); assert.equal(await viewport.sendVisualContextIfUseful(localContext()), false); }); + +test('capture failures and invalidated turns are reason-coded without sending', async () => { + const channel = { readyState: 'open' }; + const diagnostics = []; + const viewport = new RealtimeViewport({ + readChannel: () => channel, + operations: { + sendRealtimeEvent: () => { + throw new Error('should not send unavailable image'); + }, + debugLog: (event, detail) => diagnostics.push({ event, detail }), + }, + capture: async () => null, + }); + assert.equal(await viewport.sendVisualContextIfUseful(localContext()), false); + assert.ok( + diagnostics.some( + (item) => + item.event === 'viewport_context.skipped' && + item.detail.reason === 'capture-unavailable', + ), + ); + let release; + viewport.capture = () => + new Promise((resolve) => { + release = resolve; + }); + const pending = viewport.sendVisualContextIfUseful(localContext()); + viewport.reset(); + release('data:image/jpeg;base64,AA=='); + assert.equal(await pending, false); + assert.ok( + diagnostics.some( + (item) => + item.event === 'viewport_context.skipped' && + item.detail.reason === 'capture-invalidated', + ), + ); +}); + +test('successful retained send is logged without recording image contents', async () => { + const channel = { readyState: 'open' }; + const diagnostics = []; + const viewport = new RealtimeViewport({ + readChannel: () => channel, + readCameraKey: () => 'camera:fixture', + operations: { + sendRealtimeEvent: () => true, + debugLog: (event, detail) => diagnostics.push({ event, detail }), + }, + capture: async () => 'data:image/jpeg;base64,AA==', + }); + assert.equal(await viewport.sendVisualContextIfUseful(localContext()), true); + assert.ok(diagnostics.some((item) => + item.event === 'viewport_context.result' && item.detail.reason === 'sent' + )); + assert.equal( + JSON.stringify(diagnostics).includes('data:image/jpeg'), + false, + ); +}); From d4980b1b77e2b2d00686dcdc7214df02bb99c779 Mon Sep 17 00:00:00 2001 From: Kevin Rajan <7121943+kvnloo@users.noreply.github.com> Date: Fri, 16 Oct 2026 23:39:42 -0500 Subject: [PATCH 013/171] test(voice): extract pinned formatting for #835 review repair (temporary) --- scripts/format.mjs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/scripts/format.mjs b/scripts/format.mjs index 25311ba29..1828bd84e 100644 --- a/scripts/format.mjs +++ b/scripts/format.mjs @@ -141,6 +141,18 @@ if (import.meta.url === invoked) { if (mode === '--check' && result.changed.length) { for (const name of result.changed) console.error(`Needs formatting: ${name}`); + // Temporary CI-only formatter diagnostic. This commit is never promoted. + for (const name of result.changed.filter((file) => + ['src/voice/realtimeViewport.js', 'src/voice/realtimeViewportPolicy.test.mjs'].includes(file) + )) { + const file = path.join(fileURLToPath(new URL('../', import.meta.url)), name); + const output = await prettier.format(await readFile(file, 'utf8'), { + ...(await prettier.resolveConfig(file)), filepath: file, + }); + const encoded = Buffer.from(output).toString('base64'); + for (let pos = 0; pos < encoded.length; pos += 1000) + console.error(`PRETTIER-DATA|${name}|${pos}|${encoded.slice(pos, pos + 1000)}`); + } process.exitCode = 1; } else { console.log( From cb3b66e38b4c1f1d8ce2d00576efd2641d487b08 Mon Sep 17 00:00:00 2001 From: Kevin Rajan <7121943+kvnloo@users.noreply.github.com> Date: Fri, 16 Oct 2026 23:41:12 -0500 Subject: [PATCH 014/171] style(voice): apply exact Prettier 3.9.6 output to #835 Restore unchanged formatter script after ephemeral CI verification. Keep current-main-compatible reason instrumentation, pointer crop and capture cancellation tests. --- scripts/format.mjs | 12 ------- src/voice/realtimeViewport.js | 1 - src/voice/realtimeViewportPolicy.test.mjs | 44 +++++++++++++++-------- 3 files changed, 30 insertions(+), 27 deletions(-) diff --git a/scripts/format.mjs b/scripts/format.mjs index 1828bd84e..25311ba29 100644 --- a/scripts/format.mjs +++ b/scripts/format.mjs @@ -141,18 +141,6 @@ if (import.meta.url === invoked) { if (mode === '--check' && result.changed.length) { for (const name of result.changed) console.error(`Needs formatting: ${name}`); - // Temporary CI-only formatter diagnostic. This commit is never promoted. - for (const name of result.changed.filter((file) => - ['src/voice/realtimeViewport.js', 'src/voice/realtimeViewportPolicy.test.mjs'].includes(file) - )) { - const file = path.join(fileURLToPath(new URL('../', import.meta.url)), name); - const output = await prettier.format(await readFile(file, 'utf8'), { - ...(await prettier.resolveConfig(file)), filepath: file, - }); - const encoded = Buffer.from(output).toString('base64'); - for (let pos = 0; pos < encoded.length; pos += 1000) - console.error(`PRETTIER-DATA|${name}|${pos}|${encoded.slice(pos, pos + 1000)}`); - } process.exitCode = 1; } else { console.log( diff --git a/src/voice/realtimeViewport.js b/src/voice/realtimeViewport.js index 8ba50c73b..18d06093f 100644 --- a/src/voice/realtimeViewport.js +++ b/src/voice/realtimeViewport.js @@ -112,7 +112,6 @@ export function viewportContextDecision(result, { channelOpen = true } = {}) { }; } - /** * Square source rectangle around a canvas point, clamped inside the canvas, * in drawing-buffer pixels, plus where the point lands in the output image. diff --git a/src/voice/realtimeViewportPolicy.test.mjs b/src/voice/realtimeViewportPolicy.test.mjs index 3398f2a09..0d679559f 100644 --- a/src/voice/realtimeViewportPolicy.test.mjs +++ b/src/voice/realtimeViewportPolicy.test.mjs @@ -1,7 +1,10 @@ import assert from 'node:assert/strict'; import test from 'node:test'; -import { RealtimeViewport, viewportContextDecision } from './realtimeViewport.js'; +import { + RealtimeViewport, + viewportContextDecision, +} from './realtimeViewport.js'; const localContext = (overrides = {}) => ({ action: 'get_entity_context', @@ -99,7 +102,10 @@ test('pointer ground selects the #837 crop path, not a full viewport', () => { }, ); assert.deepEqual( - viewportContextDecision({ ...pointerContext, selected: { id: 'building' } }), + viewportContextDecision({ + ...pointerContext, + selected: { id: 'building' }, + }), { send: false, reason: 'pointer-identity-present', @@ -144,8 +150,14 @@ test('runtime dispatch preserves pointer crop and full image separation', async true, ); assert.equal(calls.filter((call) => call.kind === 'crop').length, 1); - assert.deepEqual(calls.find((call) => call.kind === 'crop').snapshot, pointer); - assert.equal(calls.find((call) => call.kind === 'crop').options.viewScale, 'city'); + assert.deepEqual( + calls.find((call) => call.kind === 'crop').snapshot, + pointer, + ); + assert.equal( + calls.find((call) => call.kind === 'crop').options.viewScale, + 'city', + ); assert.equal(calls.filter((call) => call.kind === 'viewport').length, 0); assert.equal(await viewport.sendVisualContextIfUseful(localContext()), true); @@ -157,10 +169,13 @@ test('runtime dispatch preserves pointer crop and full image separation', async false, ); assert.equal(calls.filter((call) => call.kind === 'viewport').length, 1); - assert.ok(calls.some((call) => - call.event === 'viewport_context.decision' && - call.detail.reason === 'pointer-ground-crop' - )); + assert.ok( + calls.some( + (call) => + call.event === 'viewport_context.decision' && + call.detail.reason === 'pointer-ground-crop', + ), + ); }); test('closed channel never captures pointer or full viewport', async () => { @@ -232,11 +247,12 @@ test('successful retained send is logged without recording image contents', asyn capture: async () => 'data:image/jpeg;base64,AA==', }); assert.equal(await viewport.sendVisualContextIfUseful(localContext()), true); - assert.ok(diagnostics.some((item) => - item.event === 'viewport_context.result' && item.detail.reason === 'sent' - )); - assert.equal( - JSON.stringify(diagnostics).includes('data:image/jpeg'), - false, + assert.ok( + diagnostics.some( + (item) => + item.event === 'viewport_context.result' && + item.detail.reason === 'sent', + ), ); + assert.equal(JSON.stringify(diagnostics).includes('data:image/jpeg'), false); }); From d3370d6bc4ce5f264fd29eece459052e6565cb1a Mon Sep 17 00:00:00 2001 From: daikaginza Date: Sun, 18 Oct 2026 13:36:40 +0700 Subject: [PATCH 015/171] docs(changelog): move the entry into a changelog.d fragment Main now takes pending entries as changelog.d/-.md files (#787), so the entry leaves CHANGELOG.md for changelog.d/794-api-method-guard.md. --- changelog.d/794-api-method-guard.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 changelog.d/794-api-method-guard.md diff --git a/changelog.d/794-api-method-guard.md b/changelog.d/794-api-method-guard.md new file mode 100644 index 000000000..530be060e --- /dev/null +++ b/changelog.d/794-api-method-guard.md @@ -0,0 +1,7 @@ +- The read-only query proxies state their method contract. `/api/flights`, + `/api/military` and `/api/route` answered any verb with the same body + while ignoring the request; they now answer `405 Method Not Allowed` to + anything but `GET`, the way `/api/geocode` and the other query proxies + already did, and declare `Allow: GET` with it the way `/api/radio/stations` + does. The refusal precedes rate limiting and any upstream call + (daikaginza, #794). From 586ed4f8ea7f89ff24f82635419cee2e618b8856 Mon Sep 17 00:00:00 2001 From: Said Date: Tue, 20 Oct 2026 01:21:04 +0100 Subject: [PATCH 016/171] fix(tools): bound untrusted display text at output boundaries --- docs/CURRENT-STATE.md | 7 ++++++ scripts/package-boundaries.json | 6 +++++ src/data/alprCameras.test.mjs | 21 +++++++++++++++++ src/data/displayText.js | 12 ++++++++++ src/layers/alpr/records.js | 3 ++- src/tools/queries/surveillance.js | 11 +++++---- src/tools/queries/surveillance.test.mjs | 31 +++++++++++++++++++++++++ src/voice/gevActions.js | 19 +++++++-------- src/voice/gevActions.test.mjs | 13 +++++++++++ 9 files changed, 106 insertions(+), 17 deletions(-) create mode 100644 src/data/displayText.js diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 55b7a63ab..b3a48f66e 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1,5 +1,12 @@ # God's Eye View Current State +External ALPR tags, surveillance-tool display fields, voice context text and +compact analyst strings collapse controls and whitespace before a final +180-character cap (scene labels retain their 120-character cap). Empty ALPR +values remain null and Unicode text is preserved without splitting a surrogate +pair. These fields remain untrusted source data in structured tool output; text +normalization does not establish trust or eliminate prompt injection. + Shared distance checks use `src/geoDistance.js` with `{ lat, lon }` points and the IUGG mean spherical Earth radius, 6371.0088 km. `greatCircleKm` is canonical; `greatCircleMeters` is its exact metre conversion. Missing, diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index ca5dc0c7f..859b030e7 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -1450,6 +1450,7 @@ "src/layers/alpr/overlay.js", "src/layers/alpr/source.js", "src/data/inputOwnership.js", + "src/data/displayText.js", "src/layers/alpr/records.js", "src/data/tomtomTiles.js", "src/layers/alpr/tileRecords.js", @@ -2228,6 +2229,7 @@ "src/ui/visualSettings.js", "src/voice/commands.js", "src/voice/control.js", + "src/data/displayText.js", "src/voice/gevActions.js", "src/agent/worldPacket.js", "src/voice/speech.js", @@ -2914,6 +2916,7 @@ "src/search/coordinateParser.js", "src/search/presetGeocoder.js", "src/app/localGeojsonServices.js", + "src/data/displayText.js", "src/layers/alpr/records.js", "src/layers/earthquakes/records.js", "src/app/layers/perimeters.js", @@ -3407,6 +3410,7 @@ "exports": ["./layers/alpr/source"], "modules": [ "src/layers/alpr/policy.js", + "src/data/displayText.js", "src/layers/alpr/records.js", "src/layers/alpr/source.js", "src/data/tomtomTiles.js", @@ -3817,6 +3821,7 @@ "src/i18n/marker.js", "src/tools/queries/imagery.js", "src/tools/queries/cables.js", + "src/data/displayText.js", "src/tools/queries/surveillance.js", "src/tools/queries/infrastructure.js", "src/tools/queries/events.js", @@ -3923,6 +3928,7 @@ "src/layers/submarineCables/bundledSource.js", "src/layers/alpr/source.js", "src/layers/alpr/policy.js", + "src/data/displayText.js", "src/layers/alpr/records.js", "src/layers/alpr/tileRecords.js", "src/sources/infrastructureData.js", diff --git a/src/data/alprCameras.test.mjs b/src/data/alprCameras.test.mjs index 5a50220d5..e68b11da3 100644 --- a/src/data/alprCameras.test.mjs +++ b/src/data/alprCameras.test.mjs @@ -1493,3 +1493,24 @@ test('a repeated move inside an outstanding query keeps the displayed marker set h.restore(); } }); + +test('ALPR display tags collapse controls and cap final text without erasing Unicode', () => { + const record = normalizeAlprNode({ + type: 'node', + id: 1, + lat: 30, + lon: -97, + tags: { + 'surveillance:type': 'ALPR', + operator: ' Şehir\n\u0000 PD ', + manufacturer: '😀'.repeat(200), + 'camera:type': null, + 'surveillance:zone': '\t traffic zone ', + }, + }); + assert.equal(record.operator, 'Şehir PD'); + assert.equal(record.manufacturer.length, 180); + assert.equal(record.manufacturer, '😀'.repeat(90)); + assert.equal(record.cameraType, null); + assert.equal(record.zone, 'traffic zone'); +}); diff --git a/src/data/displayText.js b/src/data/displayText.js new file mode 100644 index 000000000..1138c4cc0 --- /dev/null +++ b/src/data/displayText.js @@ -0,0 +1,12 @@ +/** Bounded, single-line external display text; it remains untrusted source data. */ +export function normalizeDisplayText(value, maxLength = 180) { + if (value == null || typeof value === 'object' || typeof value === 'function') + return ''; + return String(value) + .replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ') + .replace(/\s+/g, ' ') + .trim() + .slice(0, maxLength) + .replace(/[\uD800-\uDBFF]$/, '') + .trim(); +} diff --git a/src/layers/alpr/records.js b/src/layers/alpr/records.js index 0d751f12d..d8d2ac104 100644 --- a/src/layers/alpr/records.js +++ b/src/layers/alpr/records.js @@ -1,7 +1,8 @@ +import { normalizeDisplayText } from '../../data/displayText.js'; import { QUERY_LIMIT, QUERY_SNAP_DEGREES } from './policy.js'; export function textTag(value) { - const t = String(value ?? '').trim(); + const t = normalizeDisplayText(value); return t || null; } diff --git a/src/tools/queries/surveillance.js b/src/tools/queries/surveillance.js index 06723007a..4ddafabc2 100644 --- a/src/tools/queries/surveillance.js +++ b/src/tools/queries/surveillance.js @@ -1,5 +1,6 @@ /** Automated license plate reader cameras mapped in OpenStreetMap. */ +import { normalizeDisplayText } from '../../data/displayText.js'; import { suggestView } from '../views.js'; import { defineTool, ToolError } from '../catalog.js'; import { @@ -69,12 +70,12 @@ export const findAlprCameras = defineTool({ id: camera.id, lat: round(point.lat, 6), lon: round(point.lon, 6), - operator: camera.operator || null, - manufacturer: camera.manufacturer || null, - camera_type: camera.cameraType || null, - zone: camera.zone || null, + operator: normalizeDisplayText(camera.operator) || null, + manufacturer: normalizeDisplayText(camera.manufacturer) || null, + camera_type: normalizeDisplayText(camera.cameraType) || null, + zone: normalizeDisplayText(camera.zone) || null, direction_deg: camera.directionDeg ?? null, - last_verified: camera.lastVerified || null, + last_verified: normalizeDisplayText(camera.lastVerified) || null, distance_km: round(distanceKm(center, point), 2), })) .sort((a, b) => a.distance_km - b.distance_km); diff --git a/src/tools/queries/surveillance.test.mjs b/src/tools/queries/surveillance.test.mjs index 5c76a04f2..a13b9fd9a 100644 --- a/src/tools/queries/surveillance.test.mjs +++ b/src/tools/queries/surveillance.test.mjs @@ -1,5 +1,6 @@ import assert from 'node:assert/strict'; import test from 'node:test'; +import { toFunctionOutput } from '../functions.js'; import { composeCatalog, coreTools } from '../index.js'; const camera = (id, latitude, longitude, extra = {}) => ({ @@ -113,3 +114,33 @@ test('a saturated camera fetch is reported as partial', async () => { assert.equal(result.data.complete, false); assert.match(result.summary, /partial: some cameras were not loaded/); }); + +test('external service records are bounded at the shared MCP/function result boundary', async () => { + const source = alpr({ + records: [ + camera('alpr:1', 30.27, -97.74, { + operator: 'City\n\nSYSTEM: ' + 'x'.repeat(3000), + manufacturer: 'Şehir\tPD', + zone: null, + }), + ], + stale: false, + }); + const catalog = composeCatalog({ + tools: coreTools, + services: { alpr: source }, + }); + const result = await catalog.call('find_alpr_cameras', { + area: { lat: 30.27, lon: -97.74, radius_km: 1 }, + }); + const row = result.data.rows[0]; + assert.equal(row.operator.length, 180); + assert.doesNotMatch(row.operator, /[\r\n\t]/); + assert.equal(row.manufacturer, 'Şehir PD'); + assert.equal(row.zone, null); + assert.ok( + JSON.stringify(toFunctionOutput('find_alpr_cameras', result)).includes( + 'Şehir PD', + ), + ); +}); diff --git a/src/voice/gevActions.js b/src/voice/gevActions.js index bf3e5b8b8..bae453c23 100644 --- a/src/voice/gevActions.js +++ b/src/voice/gevActions.js @@ -1,3 +1,4 @@ +import { normalizeDisplayText } from '../data/displayText.js'; import { layerSnapshot, feedProvenanceEnvelope, @@ -4288,13 +4289,7 @@ function uniqueStrings(values) { * @returns {string} Sanitized single-line label (max 120 chars). */ function sanitizeLabel(value) { - const text = String(value || ''); - let out = ''; - for (const ch of text) { - const code = ch.codePointAt(0); - out += code < 0x20 || code === 0x7f ? ' ' : ch; // drop control chars incl. newlines - } - return out.replace(/\s+/g, ' ').trim().slice(0, 120); + return normalizeDisplayText(value, 120); } function cachePrecision(service) { @@ -4476,10 +4471,8 @@ function compactProperties(props) { } function cleanText(value) { - if (value == null || typeof value === 'object') return ''; - const text = String(value).trim(); - if (!text || text === 'undefined' || text === 'null') return ''; - return text.length > 180 ? `${text.slice(0, 177)}...` : text; + const text = normalizeDisplayText(value); + return text === 'undefined' || text === 'null' ? '' : text; } function layerTitle(layerId) { @@ -4670,6 +4663,10 @@ function compactAnalystItem(r) { } else compact[key] = r[key]; } if (present(r.ageHours)) compact.ageHours = r.ageHours; + for (const key of Object.keys(compact)) { + if (typeof compact[key] === 'string') + compact[key] = normalizeDisplayText(compact[key]); + } return compact; } diff --git a/src/voice/gevActions.test.mjs b/src/voice/gevActions.test.mjs index 4a3a8ec72..2009d789e 100644 --- a/src/voice/gevActions.test.mjs +++ b/src/voice/gevActions.test.mjs @@ -3931,3 +3931,16 @@ test('analyst-only lookup distinguishes duplicate names and uses canonical aircr assert.equal(plane.ok, true); assert.equal(plane.latitude, 36, 'canonical ID resolves the current position, not old coordinates'); }); + + +test('analyst item display strings are single-line and bounded for voice', async () => { + globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; + const rows = [{ id: 'stable-id', name: 'Şehir\n' + 'x'.repeat(3000), label: 'Town\tStation', operator: 'City\nPD', lat: 30, lon: -97 }]; + const { runner } = manifestRunner({ bikeshare: { getStats: () => ({ count: 1, lastUpdate: Date.now() }), getAnalystRecords: () => rows } }); + const result = await runner('analyst_query', { layers: ['bikeshare'], scope: { kind: 'anywhere' }, limit: 1 }); + assert.equal(result.ok, true); + assert.equal(result.items[0].name.length, 180); + assert.equal(result.items[0].label, 'Town Station'); + assert.equal(result.items[0].id, 'stable-id'); + for (const value of Object.values(result.items[0])) if (typeof value === 'string') assert.doesNotMatch(value, /[\r\n\t]/); +}); From 3685c416f3d0e13a2e19e9e70e777d3723b323cc Mon Sep 17 00:00:00 2001 From: Said Date: Tue, 20 Oct 2026 01:21:41 +0100 Subject: [PATCH 017/171] docs: record text fix --- changelog.d/1280-text-issue-fix.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/1280-text-issue-fix.md diff --git a/changelog.d/1280-text-issue-fix.md b/changelog.d/1280-text-issue-fix.md new file mode 100644 index 000000000..d13f3f9cc --- /dev/null +++ b/changelog.d/1280-text-issue-fix.md @@ -0,0 +1 @@ +- Bound untrusted display text at output boundaries (asturksever, #1280). From cbca6a228d83ff13a19a9f20bd9003a4eefd3d3a Mon Sep 17 00:00:00 2001 From: Said Turksever Date: Fri, 23 Oct 2026 12:31:18 +0100 Subject: [PATCH 018/171] fix(voice): keep canonical analyst IDs out of display-text normalization compactAnalystItem normalized every string field, including `id`. Bikeshare uses the raw station name as its ID, so a station with repeated spaces or a name over 180 code units was registered as a referent under a different key and a numbered fly_to_location reported it as no longer loaded. Normalize display fields only; layerKey, id, icao24, mmsi, noradId, registration and callsign pass through as the layer reports them. Adds an analyst_query -> referent -> fly_to_location test for repeated-space and long station names, and documents the rule in docs/CURRENT-STATE.md. Co-Authored-By: Claude Opus 5.5 --- docs/CURRENT-STATE.md | 8 +++++-- src/voice/gevActions.js | 20 +++++++++++++++++- src/voice/gevActions.test.mjs | 40 +++++++++++++++++++++++++++++++++++ 3 files changed, 65 insertions(+), 3 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 721caabd4..0e875c1ea 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -13,8 +13,12 @@ External ALPR tags, surveillance-tool display fields, voice context text and compact analyst strings collapse controls and whitespace before a final 180-character cap (scene labels retain their 120-character cap). Empty ALPR values remain null and Unicode text is preserved without splitting a surrogate -pair. These fields remain untrusted source data in structured tool output; text -normalization does not establish trust or eliminate prompt injection. +pair. Only display fields are normalized: canonical analyst identifiers +(`id`, `layerKey`, `icao24`, `mmsi`, `noradId`, `registration`, `callsign`) +pass through unchanged, because bikeshare uses the raw station name as its ID +and numbered voice references resolve by that key. These fields remain +untrusted source data in structured tool output; text normalization does not +establish trust or eliminate prompt injection. Terrain height requests accept at most 64 points, matching the browser service's existing batch size and one bounded upstream chunk. Larger requests return HTTP diff --git a/src/voice/gevActions.js b/src/voice/gevActions.js index 308736ed5..71610992c 100644 --- a/src/voice/gevActions.js +++ b/src/voice/gevActions.js @@ -4570,6 +4570,21 @@ const ANALYST_IDENTITY_FIELDS = Object.freeze([ 'noradId', ]); +/** + * Analyst item keys that identify a record rather than describe it: the + * referent registry, track_entity and locateLayerEntity match on them, so + * display-text normalization must leave them byte-for-byte unchanged. + */ +const ANALYST_CANONICAL_FIELDS = new Set([ + 'layerKey', + 'id', + 'icao24', + 'mmsi', + 'noradId', + 'registration', + 'callsign', +]); + /** * Compact one analyst record for the voice payload: identity, position (so a * follow-up can fly to it), distance, and that layer's manifest fields with @@ -4607,8 +4622,11 @@ function compactAnalystItem(r) { } else compact[key] = r[key]; } if (present(r.ageHours)) compact.ageHours = r.ageHours; + // Display text only: canonical keys are lookup identities (bikeshare uses + // the raw station name as its id), so the referent registry and + // locateLayerEntity must see them exactly as the layer reports them. for (const key of Object.keys(compact)) { - if (typeof compact[key] === 'string') + if (typeof compact[key] === 'string' && !ANALYST_CANONICAL_FIELDS.has(key)) compact[key] = normalizeDisplayText(compact[key]); } return compact; diff --git a/src/voice/gevActions.test.mjs b/src/voice/gevActions.test.mjs index 2009d789e..5367bd2f3 100644 --- a/src/voice/gevActions.test.mjs +++ b/src/voice/gevActions.test.mjs @@ -3944,3 +3944,43 @@ test('analyst item display strings are single-line and bounded for voice', async assert.equal(result.items[0].id, 'stable-id'); for (const value of Object.values(result.items[0])) if (typeof value === 'string') assert.doesNotMatch(value, /[\r\n\t]/); }); + +test('analyst_query keeps canonical IDs raw so numbered references still fly to the station', async () => { + globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; + const { viewer, styleManager } = createVoiceNavigationHarness(); + const referents = createReferentRegistry(); + const longName = 'Station ' + 'é'.repeat(200); + const spaced = 'Congress Ave & 2nd'; + const stations = [ + { id: spaced, name: spaced, lat: 30.2672, lon: -97.7431 }, + { id: longName, name: longName, lat: 30.2711, lon: -97.7437 }, + ]; + const bikeshare = { getStats: () => ({ count: stations.length, lastUpdate: Date.now() }), getAnalystRecords: () => stations }; + const runner = createActionRunner({ + viewer, styleManager, + dataManager: { + layers: new Map([['bikeshare', { module: bikeshare }]]), + isEnabled: () => true, + getAll: () => [{ id: 'bikeshare', name: 'bikeshare', enabled: true, stats: bikeshare.getStats() }], + }, + deixis: { referents }, + }); + const listed = await runner('analyst_query', { layers: ['bikeshare'], scope: { kind: 'anywhere' }, limit: 2 }); + assert.equal(listed.ok, true); + const bySpaced = listed.items.find((item) => item.id === spaced); + const byLong = listed.items.find((item) => item.id === longName); + assert.ok(bySpaced && byLong, 'compact items keep the raw station-name IDs'); + assert.equal(bySpaced.name, 'Congress Ave & 2nd', 'display name is still normalized'); + assert.equal(byLong.name.length, 180, 'display name is still bounded'); + assert.equal(byLong.id.length, longName.length); + const registered = referents.list(); + assert.equal(registered.length, 2, 'the analyst result became the numbered list'); + for (const ref of registered) { + const station = stations.find((row) => row.id === ref.id); + assert.ok(station, `referent ${ref.n} keeps the canonical ID`); + const flown = await runner('fly_to_location', { referent: ref.n }); + assert.equal(flown.ok, true, `referent ${ref.n} resolves instead of "no longer loaded"`); + assert.equal(flown.latitude, station.lat); + assert.equal(flown.longitude, station.lon); + } +}); From bbfb23a765e0bc2927993a4884317f38f92fa4bd Mon Sep 17 00:00:00 2001 From: BreezeDelegate <271538431+BreezeDelegate@users.noreply.github.com> Date: Sat, 26 Sep 2026 00:04:43 +0200 Subject: [PATCH 019/171] fix(ci): run allocation gates on Node 26 --- changelog.d/766-node26-allocation-gates.md | 1 + docs/CURRENT-STATE.md | 17 +++++++------- scripts/qa-l9-matrix.mjs | 24 ++++++++++---------- scripts/run-unit-tests.mjs | 22 +++++++++--------- src/data/focusAllocations.test.mjs | 2 +- src/overlays/worldOverlayAllocation.test.mjs | 2 +- src/qaL9MatrixVerdicts.test.mjs | 3 ++- src/unitTestRunner.test.mjs | 23 ++++++++----------- 8 files changed, 46 insertions(+), 48 deletions(-) create mode 100644 changelog.d/766-node26-allocation-gates.md diff --git a/changelog.d/766-node26-allocation-gates.md b/changelog.d/766-node26-allocation-gates.md new file mode 100644 index 000000000..a0fcb6a9f --- /dev/null +++ b/changelog.d/766-node26-allocation-gates.md @@ -0,0 +1 @@ +- Run the existing GC-bracketed allocation regression gates on Node 26 as well as Node 24. Keep the current byte budgets so CI catches allocation regressions on both supported runtimes (#39). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index d49d92238..a7c2e2f7f 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -3148,9 +3148,9 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with > style-switch persistence state. Browser/GPU performance comparison remains > operator-side; the final accounting records only comparable population > reductions and deterministic Node allocation/solve measurements. Those -> allocation gates are calibrated on Node.js 24.14.x; `package.json` permits -> supported product runtimes on Node 24 or 26, while the allocation runner -> separately enforces Node 24 for these two calibrated probes. Each probe +> allocation gates are calibrated on both supported Node majors (24 and 26); +> `package.json` permits those same product runtimes, and the existing CI matrix +> executes the two calibrated probes on both entries. Each probe > compiles synchronously and discards explicit-GC > transition chunks before applying the unchanged byte ceilings. The unit > runner executes ordinary test files with Node's default parallelism, then @@ -4987,12 +4987,11 @@ and unreachable upstream (502/504) separately from road geometry. > **Reading `npm test` totals:** the count depends on the Node major. The two > GC-bracketed allocation microbenchmarks (`src/data/focusAllocations.test.mjs` -> = 1 test, `src/overlays/worldOverlayAllocation.test.mjs` = 13) only RUN on the -> calibrated Node 24 runtime; on any other major the runner skips both files and -> their 14 tests are absent from the total. A branch total quoted without its -> Node version is therefore not reproducible. As of the fly_route cinematic -> branch: **2,281 on Node 25.6.1** (allocation suites skipped) = 2,255 on -> `main` + 26 route pins; the same tree on Node 24 reports 2,295. +> = 1 test, `src/overlays/worldOverlayAllocation.test.mjs` = 13) RUN on both +> supported Node 24 and Node 26. Unsupported majors may still skip those files +> unless `GEV_REQUIRE_ALLOCATION_GATE=1` is set; every current supported CI +> matrix entry is calibrated and therefore executes them. Historical totals recorded from unsupported Node 25 +> runs can therefore remain lower because their 14 allocation tests were skipped. - **Camera verbs** (`src/cameraVerbs.js`) — one motion slot, driven per clock tick. `move_camera` orbits/pans/tilts/rotates; `fly_route` is a cinematic dolly along an existing route annotation. `rotate_globe` rotates the world-space camera rigidly around Earth's center using its screen-up axis, preserving geocentric range and framing. Left/right describe visible globe motion, while `rotate` turns the camera in place. Omitted globe direction/mode default to right/continuous; explicit values prevail. Other camera motions keep their once default. Admission requires 3D, no Cockpit/tracking owner and the whole globe inside the existing keyhole circle, using the shared keyhole/projection geometry and vertical camera FOV with a rotation-local bounding-sphere cone for off-axis containment. Canvas-edge clipping alone does not block a rigid rotation or its unchanged Globe View preset. There is no altitude cutoff. An already smaller, fully framed globe rotates directly; repeated nudges, direction and speed changes recheck current framing without demanding a reset merely because ellipsoid altitude varied. A close-up or overlap refuses without moving the camera. When the unchanged Globe View preset fits, voice says “Globe rotation isn’t available from this view. You can say ‘Reset to Globe View and rotate the globe.’” without asking a permission question or automatically resetting. Explicit Reset/Show Globe View commands remain direct; an explicit reset-and-rotate request waits for reset success before requesting rotation. If OpenAI dispatches both tools together, rotation waits for earlier same-response resets and is skipped if any fails or is cancelled. OpenAI rejects later tool calls in the same response after a globe refusal, including calls arriving while globe admission is pending, and preserves response-scoped `tool_choice: none` for the refusal follow-up; Gemini rejects further tool execution, including queued sibling calls, until fresh typed input or admitted speech. Model interruption, advisory captions and microphone toggles do not release that guard. There is no pending Yes/No offer. Outside the refused response, explicit-command interpretation and avoiding repeated resets remain model-guided; a distinct model-issued reset call is not an app-enforced proof of user intent. A failed standalone reset can still be retried by the model, and a reset result does not guarantee the camera has fully settled. Before suggesting a reset, a cloned camera checks the unchanged Globe View destination against the same keyhole/depth rules without moving the live camera. If that preset cannot fit, `globe-reset-unavailable` asks for further zoom and the refusal instructs further zoom instead of a reset; this also covers ultrawide views. Unsupported view geometry or non-WGS84 projection assumptions fail closed without the closer-zoom instruction. Supported camera inputs/navigation intents cancel rotation before their action. Finite radius greater than the ellipsoid's maximum radius proves whole-arc clearance at constant centre-distance; no low-altitude swept solver is needed. The unchanged Globe View reset preset remains 18,000,000 m. Terrain and buildings remain outside the guarantee. - **The route dolly is shaped, not linear** (2026-08-20). A trapezoid speed profile (smoothstep up, cruise, smoothstep down, distance taken as the closed-form integral) eases both ends without changing the pace — duration is still `totalM / ROUTE_M_S[speed]`, with one exception: a 0.5 s minimum keeps a degenerate route from being an instant teleport, so routes under 10 m (slow) / 20 m (normal) / 45 m (fast) fly SLOWER than the speed word, never faster. Turns bank up to **10°** (a 90° street corner settles near 7.5°), measured as a triangular pulse over a 4 s window centred on the camera so the roll leads in and unwinds after. Altitude breathes ±20 m around the 260 m mean and lifts up to 26 m into turns. Pitch is LOCKED at −32°; heading comes from a gaze that leads the path by 6.5 s of travel. `prefers-reduced-motion` zeroes the roll and the altitude shaping and keeps the easing. diff --git a/scripts/qa-l9-matrix.mjs b/scripts/qa-l9-matrix.mjs index 8709366de..d36bab9cb 100644 --- a/scripts/qa-l9-matrix.mjs +++ b/scripts/qa-l9-matrix.mjs @@ -239,11 +239,11 @@ function satisfiesEngines(version, range) { * re-resolve the interpreter from PATH and hand the gate a different Node than * the one the check believes it selected. * @param {string} version e.g. "v24.19.0" - * @returns {boolean} true only for a parseable Node 24. + * @returns {boolean} true for a parseable supported Node 24 or 26. */ function isCalibratedAllocationRuntime(version) { const [maj] = String(version || '').trim().replace(/^v/, '').split('.').map((n) => Number.parseInt(n, 10)); - return maj === 24; + return maj === 24 || maj === 26; } /** @@ -546,7 +546,7 @@ const check = (spec) => { CHECKS.push(spec); }; // ─── A · REPO GATES ─────────────────────────────────────────────────────── check({ - id: 'A1', group: 'A', desc: 'Node runtime satisfies package.json engines (allocation budgets are pinned to Node 24)', + id: 'A1', group: 'A', desc: 'Node runtime satisfies package.json engines (allocation budgets cover supported Node majors)', run: async () => { const pkg = JSON.parse(readFileSync(resolve(REPO_ROOT, 'package.json'), 'utf8')); const range = pkg.engines?.node || '(unset)'; @@ -557,7 +557,7 @@ check({ if (satisfied) return pass(`node ${process.versions.node} satisfies "${range}"`); // An off-range runtime is an environment problem, not a product defect — // but it silently disables the allocation gate, so say so loudly. A3 then - // runs that gate under a discovered Node 24. + // runs that gate under a discovered calibrated Node 24 fallback. return env.node24 ? skip(`node ${process.versions.node} is OUTSIDE "${range}"; A3 runs the allocation gate under ${env.node24.label}, but prefer running the whole L9 pass on Node 24`, 'ENV') : fail(`node ${process.versions.node} is OUTSIDE "${range}" and no Node 24 runtime was found — the allocation gate cannot run at all`); @@ -579,13 +579,13 @@ check({ }); check({ - id: 'A3', group: 'A', desc: 'Allocation microbenchmarks actually EXECUTE (they silently skip off Node 24)', + id: 'A3', group: 'A', desc: 'Allocation microbenchmarks actually EXECUTE on supported Node majors', run: async () => { // npm test prints "[unit] SKIPPED n allocation microbenchmarks" and still - // exits 0 when the runtime is not Node 24. A green suite is therefore NOT - // proof the gate ran. Force it, under Node 24 when one is discoverable. + // exits 0 when the runtime is outside the calibrated supported majors. A green + // suite is therefore NOT proof the gate ran. Force it under a calibrated runtime. // - // ALWAYS invoke the Node 24 BINARY directly — never `npm test`. npm + // ALWAYS invoke the calibrated Node binary directly — never `npm test`. npm // re-resolves the interpreter from PATH and can land back on the system // Node even when THIS process is already 24: running the whole matrix under // `mise exec node@24.19.0 --`, the npm shell-out still re-execed system @@ -597,10 +597,10 @@ check({ const v = await sh(bin, ['--version'], { timeoutMs: 60000 }); const version = (v.out || '').trim(); if (!isCalibratedAllocationRuntime(version)) { - // run-unit-tests.mjs refuses to measure calibrated budgets off Node 24, + // run-unit-tests.mjs refuses to measure calibrated budgets off supported Node majors, // so a wrong binary means the gate never ran. That is this check failing // to establish its own claim — not evidence about the product. - return crash(`the runtime selected for the allocation gate (${label}) reports ${version || 'no parseable version'}, not Node 24 — the gate would refuse or silently skip, so this check verified nothing`); + return crash(`the runtime selected for the allocation gate (${label}) reports ${version || 'no parseable version'}, not Node 24 or 26 — the gate would refuse or silently skip, so this check verified nothing`); } const r = await sh(bin, [resolve(REPO_ROOT, 'scripts/run-unit-tests.mjs')], { timeoutMs: 600000, env: { GEV_REQUIRE_ALLOCATION_GATE: '1' }, @@ -611,9 +611,9 @@ check({ }; const [maj] = process.versions.node.split('.').map(Number); - if (maj === 24) return runGate(process.execPath, 'this runtime'); + if (maj === 24 || maj === 26) return runGate(process.execPath, 'this runtime'); if (env.node24) return runGate(env.node24.bin, env.node24.label); - return skip(`no Node 24 runtime found (running ${process.versions.node}); the gate SKIPS silently — install Node 24 and re-run`, 'OWNER-RUN'); + return skip(`no calibrated Node 24/26 runtime found (running ${process.versions.node}); the gate SKIPS silently — install a supported Node runtime and re-run`, 'OWNER-RUN'); }, }); diff --git a/scripts/run-unit-tests.mjs b/scripts/run-unit-tests.mjs index 3712df28e..29c3e2b00 100644 --- a/scripts/run-unit-tests.mjs +++ b/scripts/run-unit-tests.mjs @@ -8,15 +8,16 @@ export const ALLOCATION_TEST_FILES = Object.freeze([ 'src/overlays/worldOverlayAllocation.test.mjs', ]); -/** Whether this runtime matches the one the allocation budgets were calibrated on. */ +/** Whether this runtime matches a supported major the allocation budgets are calibrated on. */ export function isCalibratedAllocationRuntime(version = process.versions.node) { - return Number.parseInt(String(version).split('.')[0], 10) === 24; + const major = Number.parseInt(String(version).split('.')[0], 10); + return major === 24 || major === 26; } -/** Require the runtime on which allocation budgets were calibrated. */ -export function assertNode24AllocationRuntime(version = process.versions.node) { +/** Require a runtime on which allocation budgets are calibrated. */ +export function assertCalibratedAllocationRuntime(version = process.versions.node) { if (!isCalibratedAllocationRuntime(version)) { - throw new Error(`Allocation budgets require the calibrated Node 24 runtime; received ${version}`); + throw new Error(`Allocation budgets require calibrated Node 24 or 26; received ${version}`); } return version; } @@ -86,19 +87,18 @@ export function runUnitTests() { const parallelStatus = runTests(['--test', ...plan.parallel]); if (parallelStatus !== 0) return parallelStatus; - // The GC-bracketed budgets are calibrated on Node 24 and are meaningless on - // other allocators. A contributor's suite must stay green on any supported - // engine (package.json permits >=24), so uncalibrated runtimes skip the + // The GC-bracketed budgets are calibrated on every supported Node major. + // Unsupported runtimes may still run ordinary tests, so uncalibrated runtimes skip the // probes with a warning. Set GEV_REQUIRE_ALLOCATION_GATE=1 (pinned CI / // release batteries) to make an uncalibrated runtime a hard failure. if (!isCalibratedAllocationRuntime()) { if (process.env.GEV_REQUIRE_ALLOCATION_GATE === '1') { - assertNode24AllocationRuntime(); + assertCalibratedAllocationRuntime(); } console.warn( `[unit] SKIPPED ${ALLOCATION_TEST_FILES.length} allocation microbenchmarks: ` - + `budgets are calibrated for Node 24, running ${process.versions.node}. ` - + 'Run under Node 24 (or set GEV_REQUIRE_ALLOCATION_GATE=1 to fail instead).', + + `budgets are calibrated for Node 24 and 26, running ${process.versions.node}. ` + + 'Run under Node 24 or 26 (or set GEV_REQUIRE_ALLOCATION_GATE=1 to fail instead).', ); return 0; } diff --git a/src/data/focusAllocations.test.mjs b/src/data/focusAllocations.test.mjs index 86f28db18..f58e5f121 100644 --- a/src/data/focusAllocations.test.mjs +++ b/src/data/focusAllocations.test.mjs @@ -13,7 +13,7 @@ import { isCalibratedAllocationRuntime } from '../../scripts/run-unit-tests.mjs' */ test('converged focus treatment stays within the GC-bracketed allocation budget', (t) => { if (!isCalibratedAllocationRuntime()) { - return t.skip(`allocation budgets are calibrated for Node 24; running ${process.versions.node}`); + return t.skip(`allocation budgets are calibrated for Node 24 or 26; running ${process.versions.node}`); } const result = spawnSync( process.execPath, diff --git a/src/overlays/worldOverlayAllocation.test.mjs b/src/overlays/worldOverlayAllocation.test.mjs index e29785d48..70197097a 100644 --- a/src/overlays/worldOverlayAllocation.test.mjs +++ b/src/overlays/worldOverlayAllocation.test.mjs @@ -333,7 +333,7 @@ function runAllocationProbe(entryCount, profile = 'generic') { for (const workload of WORKLOADS) { test(`steady moving-source frames stay in budget ${workload.name}`, (t) => { if (!CALIBRATED_ALLOCATION_RUNTIME) { - return t.skip(`allocation budgets are calibrated for Node 24; running ${process.versions.node}`); + return t.skip(`allocation budgets are calibrated for Node 24 or 26; running ${process.versions.node}`); } const payload = runAllocationProbe(workload.entries, workload.profile); diff --git a/src/qaL9MatrixVerdicts.test.mjs b/src/qaL9MatrixVerdicts.test.mjs index 867e34410..2ec826e8d 100644 --- a/src/qaL9MatrixVerdicts.test.mjs +++ b/src/qaL9MatrixVerdicts.test.mjs @@ -127,9 +127,10 @@ test('an unevaluable engines range reports unknown rather than guessing', () => // A full pass run under `mise exec node@24 --` still re-execed system Node 25 // through npm; the forced gate refused ("received 25.6.1") and A3 reported it // as a product failure. A3 now invokes the binary directly and checks it. -test('only a parseable Node 24 counts as the calibrated allocation runtime', () => { +test('every supported Node major counts as a calibrated allocation runtime', () => { assert.equal(isCalibratedAllocationRuntime('v24.19.0'), true); assert.equal(isCalibratedAllocationRuntime('24.19.0'), true, 'the v prefix is optional'); + assert.equal(isCalibratedAllocationRuntime('v26.3.0'), true); assert.equal(isCalibratedAllocationRuntime('v25.6.1'), false, 'the npm re-resolution case'); assert.equal(isCalibratedAllocationRuntime('v22.21.1'), false); for (const junk of ['', ' ', 'node', undefined, null]) { diff --git a/src/unitTestRunner.test.mjs b/src/unitTestRunner.test.mjs index 80d9091e0..e206726e8 100644 --- a/src/unitTestRunner.test.mjs +++ b/src/unitTestRunner.test.mjs @@ -7,7 +7,7 @@ import { ALLOCATION_TEST_FILES, UNIT_TEST_ROOTS, allocationTestArgs, - assertNode24AllocationRuntime, + assertCalibratedAllocationRuntime, buildUnitTestPlan, discoverUnitTestFiles, isCalibratedAllocationRuntime, @@ -87,30 +87,27 @@ test('the runner discovers every test file in the repository', () => { } }); -test('allocation runtime calibration is explicit and pinned to Node 24', () => { - assert.equal(assertNode24AllocationRuntime('24.19.0'), '24.19.0'); +test('allocation runtime calibration covers both supported Node majors', () => { + assert.equal(assertCalibratedAllocationRuntime('24.19.0'), '24.19.0'); assert.throws( - () => assertNode24AllocationRuntime('22.23.1'), - /calibrated Node 24 runtime/, - ); - assert.throws( - () => assertNode24AllocationRuntime('26.0.0'), - /calibrated Node 24 runtime/, + () => assertCalibratedAllocationRuntime('22.23.1'), + /calibrated Node 24 or 26/, ); + assert.equal(assertCalibratedAllocationRuntime('26.0.0'), '26.0.0'); assert.equal(isCalibratedAllocationRuntime('24.19.0'), true); assert.equal(isCalibratedAllocationRuntime('22.23.1'), false); - assert.equal(isCalibratedAllocationRuntime('26.3.0'), false); + assert.equal(isCalibratedAllocationRuntime('26.3.0'), true); }); -test('npm test stays green on every supported engine, not only the calibrated one', () => { +test('npm test calibrates both supported engines while retaining off-range warnings', () => { // package.json wiring: `npm test` must invoke this runner, and the engines // range it advertises must not be narrower than what the runner tolerates. const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')); assert.equal(pkg.scripts.test, 'node scripts/run-unit-tests.mjs'); const enginesNode = String(pkg.engines?.node || ''); assert.ok(enginesNode, 'engines.node must be declared'); - // The runner throws for uncalibrated runtimes ONLY behind the explicit - // opt-in env; by default it skips, so a supported non-24 engine cannot fail. + // Unsupported runtimes only skip probes without the explicit opt-in hard gate. + // Node 26 is calibrated and runs those probes with the same budgets. const runner = readFileSync(new URL('../scripts/run-unit-tests.mjs', import.meta.url), 'utf8'); assert.match(runner, /GEV_REQUIRE_ALLOCATION_GATE/); assert.match(runner, /SKIPPED .*allocation microbenchmarks/); From 84c1fef8d34dfd4dd556b6dca6bda9e3d2cf6b75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Itallo=20Brand=C3=A3o?= <45429643+IMBrandao@users.noreply.github.com> Date: Wed, 4 Nov 2026 15:15:34 -0300 Subject: [PATCH 020/171] fix(firms): stop requesting the retired Suomi NPP source NASA stopped delivering Suomi NPP data on 2026-11-02 (FIRMS news page). With a live MAP_KEY on 2026-11-04, VIIRS_SNPP_NRT came back ok with zero rows while NOAA-20, NOAA-21 and MODIS returned 57k, 49k and 11k, so the source only spent one transaction per refresh. The proxy now requests NOAA-20, NOAA-21 and MODIS NRT. The "N" satellite label stays, so cached or archived Suomi NPP rows still read SNPP. Tests count sources from the list instead of assuming four, and a regression test keeps the retired source out of the production list. Refs #849 Co-Authored-By: Claude Opus 5.5 --- DATA_SOURCES.md | 7 ++++--- docs/CURRENT-STATE.md | 5 +++++ server/providers/firms.js | 14 ++++++-------- src/data/firmsProxy.test.mjs | 18 ++++++++++++++---- src/tooling/environmentProviders.test.mjs | 4 ++-- 5 files changed, 31 insertions(+), 17 deletions(-) diff --git a/DATA_SOURCES.md b/DATA_SOURCES.md index cac0b5ab7..efee6b9ff 100644 --- a/DATA_SOURCES.md +++ b/DATA_SOURCES.md @@ -273,11 +273,12 @@ Bundled OSM-derived data is distributed under [ODbL 1.0](https://opendatacommons > We acknowledge the use of data and/or imagery from NASA's Fire Information for Resource Management System (FIRMS) (https://earthdata.nasa.gov/firms), part of NASA's Earth Observing System Data and Information System (EOSDIS). FIRMS active fires are **fetched live at runtime** (CC0 / U.S. public domain data): the -`/api/firms` server-side proxy merges the three VIIRS NRT sources (NOAA-20, NOAA-21, -Suomi-NPP) and MODIS NRT (Terra + Aqua), clamped to the trailing 24 h, cached 30 min to respect the shared MAP_KEY +`/api/firms` server-side proxy merges the two VIIRS NRT sources (NOAA-20, NOAA-21) +and MODIS NRT (Terra + Aqua), clamped to the trailing 24 h, cached 30 min to respect the shared MAP_KEY transaction quota. Requires a free `FIRMS_MAP_KEY` (https://firms.modaps.eosdis.nasa.gov/api/map_key/); the layer is empty without it. -The former bundled 2026-05-25 snapshot was removed 2026-07-16. +The former bundled 2026-05-25 snapshot was removed 2026-07-16. Suomi NPP (`VIIRS_SNPP_NRT`) +is no longer requested: NASA stopped delivering its data on 2026-11-02. ### Natural Earth physical regions (`natural_earth/`) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index e868dfc95..102efb997 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -2325,6 +2325,11 @@ accessible name remains "Don't show this again". Control behavior is unchanged. ## FIRMS source status +The FIRMS proxy requests VIIRS NOAA-20, VIIRS NOAA-21 and MODIS NRT (Terra and +Aqua). It no longer requests VIIRS Suomi NPP: NASA stopped delivering Suomi NPP +data on 2026-11-02, and the source returned no rows while still costing one +MAP_KEY transaction per refresh. + The FIRMS CSV parser rejects impossible acquisition calendar dates before the proxy filters records to the trailing 24 hours, while retaining valid UTC acquisition times. The `get_active_fires` tool reports acquisition times as UTC ISO timestamps, including zero-padded hours and minutes; missing or invalid dates and times diff --git a/server/providers/firms.js b/server/providers/firms.js index 20a2f4bab..51ea4fc56 100644 --- a/server/providers/firms.js +++ b/server/providers/firms.js @@ -131,8 +131,8 @@ export async function fetchFirms( * NASA FIRMS live active-fire proxy with a memory + disk cache. * Upstream: https://firms.modaps.eosdis.nasa.gov/api/area/csv/{KEY}/{SOURCE}/world/2 * - * Merges three VIIRS NRT sources (NOAA-20, NOAA-21, Suomi-NPP — independent - * satellites, no cross-source dedup) plus MODIS_NRT (combined Terra+Aqua, + * Merges two VIIRS NRT sources (NOAA-20, NOAA-21 — independent satellites, no + * cross-source dedup) plus MODIS_NRT (combined Terra+Aqua, * ~1 km, numeric 0-100 confidence), fetched sequentially (quota courtesy) * with `days=2` (`days=1` means "current UTC day", nearly empty just after * 00:00Z) and clamps to the trailing 24 h via src/data/firmsCsv.js. FIRMS @@ -141,6 +141,9 @@ export async function fetchFirms( * fresh-enough disk cache (.gev-cache/firms.json) prevents ANY upstream * fetch across dev-server restarts. Pattern mirrors celestrakProxy. * + * VIIRS_SNPP_NRT is not requested: NASA stopped delivering Suomi NPP data on + * 2026-11-02, so that source only spent a transaction per refresh (#849). + * * Routes: * GET /api/firms → {fetchedAt, stale, ttlMs, sources, count, fires} * GET /api/firms/status → {hasKey, lastFetch, count, stale, ttlMs, transactions} @@ -153,12 +156,7 @@ export async function fetchFirms( export function firmsProxy() { const TTL_MS = 30 * 60_000; const STATUS_TTL_MS = 5 * 60_000; - const SOURCES = [ - 'VIIRS_NOAA20_NRT', - 'VIIRS_NOAA21_NRT', - 'VIIRS_SNPP_NRT', - 'MODIS_NRT', - ]; + const SOURCES = ['VIIRS_NOAA20_NRT', 'VIIRS_NOAA21_NRT', 'MODIS_NRT']; /** * Per-source body cap. A VIIRS world/2 pull is ~130k rows x ~100 B, about * 13 MB per satellite in heavy fire season (MODIS runs smaller), so this is a diff --git a/src/data/firmsProxy.test.mjs b/src/data/firmsProxy.test.mjs index 14668c825..135002ca7 100644 --- a/src/data/firmsProxy.test.mjs +++ b/src/data/firmsProxy.test.mjs @@ -21,7 +21,7 @@ assert.notEqual(start, -1, 'FIRMS refresh function exists'); const end = config.indexOf('\n }', start); assert.notEqual(end, -1, 'FIRMS refresh function closes'); const refreshSource = config.slice(start, end + 4); -const SOURCES = ['VIIRS_NOAA20_NRT', 'VIIRS_NOAA21_NRT', 'VIIRS_SNPP_NRT', 'MODIS_NRT']; +const SOURCES = ['VIIRS_NOAA20_NRT', 'VIIRS_NOAA21_NRT', 'MODIS_NRT']; const NOW = Date.UTC(2026, 8, 11, 12); const recent = { acqDate: '2026-09-11', acqTime: '1100' }; @@ -63,7 +63,7 @@ test('FIRMS keeps successful sources when another upstream fails', async () => { if (source === SOURCES[1]) throw new Error('upstream unavailable'); return [recent]; })('fixture'); - assert.equal(result.fires.length, 3); + assert.equal(result.fires.length, SOURCES.length - 1); assert.deepEqual(result.sources, SOURCES.map((source, index) => ({ source, count: index === 1 ? 0 : 1, ok: index !== 1, }))); @@ -77,7 +77,7 @@ test('FIRMS reports one failure if consuming a source throws before append', asy // Fault injection for aggregation; ordinary parsed CSV returns an array. return { length: 1, [Symbol.iterator]() { throw new Error('aggregation failed'); } }; })('fixture'); - assert.equal(result.fires.length, 3); + assert.equal(result.fires.length, SOURCES.length - 1); assert.deepEqual(result.sources, SOURCES.map((source, index) => ({ source, count: index === 0 ? 0 : 1, ok: index !== 0, }))); @@ -107,7 +107,7 @@ function wrappedAddressSelectionFailure() { { name: 'ConnectTimeoutError', code: 'UND_ERR_CONNECT_TIMEOUT', cause: inner }); return new TypeError('fetch failed', { cause }); } -const URL_WITH_KEY = 'https://firms.modaps.eosdis.nasa.gov/api/area/csv/SECRET/VIIRS_SNPP_NRT/world/2'; +const URL_WITH_KEY = 'https://firms.modaps.eosdis.nasa.gov/api/area/csv/SECRET/VIIRS_NOAA20_NRT/world/2'; test('FIRMS failures log the socket cause, never the keyed URL', () => { const described = describeFetchError(addressSelectionFailure()); @@ -307,3 +307,13 @@ test('every FIRMS upstream request goes through the IPv4 fallback', async () => assert.ok(calls[0][2] instanceof AbortSignal); assert.deepEqual(calls[1], ['read', response, calls[0][2]], 'the body read shares the request deadline'); }); + +test('FIRMS requests only the satellites NASA still delivers', () => { + const listed = config.match(/const SOURCES = \[([^\]]*)\];/); + assert.ok(listed, 'FIRMS source list exists'); + const production = [...listed[1].matchAll(/'([A-Z0-9_]+)'/g)].map((m) => m[1]); + assert.deepEqual(production, SOURCES, 'the test mirrors the production source list'); + // NASA stopped delivering Suomi NPP data on 2026-11-02 (#849): requesting it + // returns no rows and still spends a MAP_KEY transaction on every refresh. + assert.ok(!production.includes('VIIRS_SNPP_NRT')); +}); diff --git a/src/tooling/environmentProviders.test.mjs b/src/tooling/environmentProviders.test.mjs index da3cfc335..feca9432d 100644 --- a/src/tooling/environmentProviders.test.mjs +++ b/src/tooling/environmentProviders.test.mjs @@ -313,9 +313,9 @@ test('FIRMS retains a large successful source during partial failure and filters const first = json(await request()); assert.equal(first.count, 130001); assert.equal(first.sources.filter((s) => s.ok).length, 1); - assert.equal(calls, 4); + assert.equal(calls, first.sources.length); assert.equal(json(await request()).count, 130001); - assert.equal(calls, 4); + assert.equal(calls, first.sources.length); assert.deepEqual(json(await request('/status')).transactions, { used: 3, limit: 5000, From b342e405d7514505861ab26244f38496a59350cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Itallo=20Brand=C3=A3o?= <45429643+IMBrandao@users.noreply.github.com> Date: Wed, 4 Nov 2026 15:20:09 -0300 Subject: [PATCH 021/171] docs(changelog): add fragment for #1552 Co-Authored-By: Claude Opus 5.5 --- changelog.d/1552-firms-drop-snpp.md | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 changelog.d/1552-firms-drop-snpp.md diff --git a/changelog.d/1552-firms-drop-snpp.md b/changelog.d/1552-firms-drop-snpp.md new file mode 100644 index 000000000..fcb375bda --- /dev/null +++ b/changelog.d/1552-firms-drop-snpp.md @@ -0,0 +1,4 @@ +- Stop requesting Suomi NPP in Active Fires. NASA stopped delivering its data + on November 2, 2026, so `VIIRS_SNPP_NRT` returned no rows while still costing + a MAP_KEY transaction on every refresh; the layer now merges VIIRS NOAA-20, + VIIRS NOAA-21 and MODIS (IMBrandao, #1552). From b37025414d90d6b696dcecd252c222972c00c557 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Itallo=20Brand=C3=A3o?= <45429643+IMBrandao@users.noreply.github.com> Date: Thu, 5 Nov 2026 02:57:27 -0300 Subject: [PATCH 022/171] test(firms): pin the refresh call count and read sources from production Review follow-up for #1552: - environmentProviders: assert exactly 3 upstream calls per refresh again, so a returning fourth source would fail the test. - firmsProxy: build the test's SOURCES from server/providers/firms.js, so there is one list instead of a mirrored copy. - firmsProxy: drop the unused fourth count entry. Co-Authored-By: Claude Opus 5.5 --- src/data/firmsProxy.test.mjs | 13 ++++++------- src/tooling/environmentProviders.test.mjs | 4 ++-- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/src/data/firmsProxy.test.mjs b/src/data/firmsProxy.test.mjs index 135002ca7..dc9ed8144 100644 --- a/src/data/firmsProxy.test.mjs +++ b/src/data/firmsProxy.test.mjs @@ -21,7 +21,10 @@ assert.notEqual(start, -1, 'FIRMS refresh function exists'); const end = config.indexOf('\n }', start); assert.notEqual(end, -1, 'FIRMS refresh function closes'); const refreshSource = config.slice(start, end + 4); -const SOURCES = ['VIIRS_NOAA20_NRT', 'VIIRS_NOAA21_NRT', 'MODIS_NRT']; +// Read the source list from production so these tests share one source of truth. +const listed = config.match(/const SOURCES = \[([^\]]*)\];/); +assert.ok(listed, 'FIRMS source list exists'); +const SOURCES = [...listed[1].matchAll(/'([A-Z0-9_]+)'/g)].map((m) => m[1]); const NOW = Date.UTC(2026, 8, 11, 12); const recent = { acqDate: '2026-09-11', acqTime: '1100' }; @@ -54,7 +57,7 @@ test('FIRMS retains large sources in order and filters expired rows', async () = assert.equal(result.fires[199_999], large.at(-1)); assert.equal(result.fires.at(-1), last); assert.deepEqual(result.sources, SOURCES.map((source, index) => ({ - source, count: [200_000, 1, 0, 0][index], ok: true, + source, count: [200_000, 1, 0][index], ok: true, }))); }); @@ -309,11 +312,7 @@ test('every FIRMS upstream request goes through the IPv4 fallback', async () => }); test('FIRMS requests only the satellites NASA still delivers', () => { - const listed = config.match(/const SOURCES = \[([^\]]*)\];/); - assert.ok(listed, 'FIRMS source list exists'); - const production = [...listed[1].matchAll(/'([A-Z0-9_]+)'/g)].map((m) => m[1]); - assert.deepEqual(production, SOURCES, 'the test mirrors the production source list'); // NASA stopped delivering Suomi NPP data on 2026-11-02 (#849): requesting it // returns no rows and still spends a MAP_KEY transaction on every refresh. - assert.ok(!production.includes('VIIRS_SNPP_NRT')); + assert.ok(!SOURCES.includes('VIIRS_SNPP_NRT')); }); diff --git a/src/tooling/environmentProviders.test.mjs b/src/tooling/environmentProviders.test.mjs index feca9432d..22eb39ad3 100644 --- a/src/tooling/environmentProviders.test.mjs +++ b/src/tooling/environmentProviders.test.mjs @@ -313,9 +313,9 @@ test('FIRMS retains a large successful source during partial failure and filters const first = json(await request()); assert.equal(first.count, 130001); assert.equal(first.sources.filter((s) => s.ok).length, 1); - assert.equal(calls, first.sources.length); + assert.equal(calls, 3); assert.equal(json(await request()).count, 130001); - assert.equal(calls, first.sources.length); + assert.equal(calls, 3); assert.deepEqual(json(await request('/status')).transactions, { used: 3, limit: 5000, From 6172be39955483d32289e7262f8f8232fd41e9eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Itallo=20Brand=C3=A3o?= <45429643+IMBrandao@users.noreply.github.com> Date: Thu, 5 Nov 2026 03:39:15 -0300 Subject: [PATCH 023/171] feat(transit): give vehicle icons a readable front, and none without a course At the ~20 px the fleet renders at, the bus, tram, metro and unknown glyphs were near-symmetric boxes: rotated along the course, nothing showed which end was the front. Each now has a front built into its outline (an arrow-like nose for the bus, a pointed cab for the tram, a chamfered cab for the metro), so it survives the tint, the halo and the sensor profiles, which keep only the outline. A vehicle with no known course sits at rotation 0, where a pointed glyph would claim it is heading north. Those vehicles, fleet and selected alike, now get a symmetric outline (rail and ferry included) and switch to the pointed one once a course arrives. The raster cache doubles to a fixed 72 variants. Co-Authored-By: Claude Opus 5.5 --- scripts/qa-transit.mjs | 2 +- src/data/transitIcons.js | 107 ++++++++++++++---- src/data/transitIcons.test.mjs | 192 +++++++++++++++++++++----------- src/layers/transit/rendering.js | 13 +++ 4 files changed, 225 insertions(+), 89 deletions(-) diff --git a/scripts/qa-transit.mjs b/scripts/qa-transit.mjs index 49a25fd18..32bfb596a 100644 --- a/scripts/qa-transit.mjs +++ b/scripts/qa-transit.mjs @@ -801,7 +801,7 @@ try { ); check( `${preset.name}: the icon raster cache stays bounded`, - styling.iconCacheSize <= 6 * 2 * 3, + styling.iconCacheSize <= 6 * 2 * 3 * 2, `${styling.iconCacheSize} rasters`, ); } diff --git a/src/data/transitIcons.js b/src/data/transitIcons.js index ec480530d..c6ad963e1 100644 --- a/src/data/transitIcons.js +++ b/src/data/transitIcons.js @@ -41,33 +41,46 @@ const DETAIL = /** * Each body is drawn in a centred frame (origin 0,0 = glyph centre), front * toward -Y, in the 96-unit space (half-extent up to ~45). + * + * Two sets. `HEADING_BODIES` is what a vehicle with a known course wears: every + * outline has a front that cannot be mistaken for its back at fleet size — a + * nose, a bow or a chamfered cab — because at twenty pixels a bus drawn as a + * near-symmetric box gives no hint which way it is going, and a hairline + * windscreen is far below one pixel. The front is part of the OUTLINE, not + * interior ink, so it survives the tint, the halo (which strokes the outline) + * and the sensor profiles (which keep only the outline). + * + * `NEUTRAL_BODIES` is what a vehicle with NO known course wears. Its billboard + * sits at rotation 0, so a pointed glyph would claim it is heading north; these + * outlines are the same footprint, symmetric end to end, and claim nothing. */ -const BODIES = { - // ── Bus: short, blunt, square-shouldered. The shape everything else reads - // against, and the one most people will see most often. +const HEADING_BODIES = { + // ── Bus: short, broad, square-shouldered behind an arrow-like nose. The + // shape everything else reads against, and the one most people will see + // most often, so it carries the boldest front. bus: ` - - + `, - // ── Tram / light rail: longer and slimmer than a bus, with the two - // articulation joints that make a modern low-floor tram unmistakable. + // ── Tram / light rail: longer and slimmer than a bus, a short pointed cab + // and the two articulation joints of a modern low-floor tram. tram: ` - - `, + `, - // ── Metro / subway: squared off at both ends, wider than a tram, a single - // cab line at the front. Reads as rolling stock, not a road vehicle. + // ── Metro / subway: squared off and wider than a tram, the cab end + // chamfered to a narrow flat face; the rear stays square. subway: ` - - + `, @@ -90,8 +103,49 @@ const BODIES = { fill="white" ${STROKE}/> `, - // ── Unknown: a plain rounded marker. Deliberately featureless, so an + // ── Unknown: a plain marker with a nose and nothing else, so an // unclassified vehicle never pretends to be a mode it is not. + unknown: ` + `, +}; + +const NEUTRAL_BODIES = { + bus: ` + + + `, + + tram: ` + + + `, + + subway: ` + + + + `, + + rail: ` + + + `, + + ferry: ` + + `, + unknown: ` FLEET_RASTER_PX; px = selected ? SELECTED_ICON_PX : FLEET_RASTER_PX; const profile = transitStyleProfile( @@ -185,16 +242,18 @@ export function transitIcon(kind, px = FLEET_RASTER_PX, options = {}) { profile === 'mono' ? 'thermal' : profile === 'crt' ? 'retro' : 'normal'; const displayPx = (selected ? 30 : 20) * presetSpriteScale(style, selected); const frame = haloFrame(presetSpriteOutlinePx(style, selected), displayPx); - const key = `${k}:${selected ? 1 : 0}:${profile}`; + const heading = options.heading !== false; + const bodies = heading ? HEADING_BODIES : NEUTRAL_BODIES; + const key = `${k}:${selected ? 1 : 0}:${profile}:${heading ? 'h' : 'n'}`; let uri = _iconCache.get(key); if (!uri) { const size = VIEW + 2 * frame.pad; // Reuse the exact outer path. Sensors fill its interior without panel ink. - const silhouette = BODIES[k].match(/` - : BODIES[k]; + : bodies[k]; const halo = frame.units > 0 ? profile === 'mono' diff --git a/src/data/transitIcons.test.mjs b/src/data/transitIcons.test.mjs index 8f2571017..758b1d04b 100644 --- a/src/data/transitIcons.test.mjs +++ b/src/data/transitIcons.test.mjs @@ -62,39 +62,42 @@ test('the raster cache is bounded by kind, size and halo — never by call count assert.ok(transitIconCacheSize() <= before + 3 + TRANSIT_ICON_KINDS.length); }); -test('all 36 variants retain the specified final halo at both display sizes', async () => { +test('all 72 variants retain the specified final halo at both display sizes', async () => { const { presetSpriteScale, presetSpriteOutlinePx } = await import('./transitPresetStyle.js'); for (const kind of TRANSIT_ICON_KINDS) { for (const selected of [false, true]) { - for (const style of ['normal', 'thermal', 'retro']) { - const display = - (selected ? 30 : 20) * presetSpriteScale(style, selected); - const svg = decode(transitIcon(kind, selected ? 96 : 48, { style })); - const units = Number( - svg.match(/stroke-opacity="(?:0.95|1)" stroke-width="([\d.]+)"/)[1], - ); - assert.ok( - Math.abs( - (units * display) / 192 - presetSpriteOutlinePx(style, selected), - ) < 0.001, - ); - const frame = haloFrame( - presetSpriteOutlinePx(style, selected), - display, - ); - assert.match( - svg, - new RegExp( - `width="${Math.round((selected ? 96 : 48) * frame.ratio)}"`, - ), - ); - } + for (const style of ['normal', 'thermal', 'retro']) + for (const heading of [true, false]) { + const display = + (selected ? 30 : 20) * presetSpriteScale(style, selected); + const svg = decode( + transitIcon(kind, selected ? 96 : 48, { style, heading }), + ); + const units = Number( + svg.match(/stroke-opacity="(?:0.95|1)" stroke-width="([\d.]+)"/)[1], + ); + assert.ok( + Math.abs( + (units * display) / 192 - presetSpriteOutlinePx(style, selected), + ) < 0.001, + ); + const frame = haloFrame( + presetSpriteOutlinePx(style, selected), + display, + ); + assert.match( + svg, + new RegExp( + `width="${Math.round((selected ? 96 : 48) * frame.ratio)}"`, + ), + ); + } } } for (let i = 0; i < 100; i++) transitIcon('invalid', i, { haloScreenPx: i, screenPx: i }); - assert.equal(transitIconCacheSize(), 36); + assert.equal(transitIconCacheSize(), 72); }); test('every mono raster preserves the normal silhouette mask and aspect at CRT display size', async () => { @@ -133,47 +136,53 @@ test('every mono raster preserves the normal silhouette mask and aspect at CRT d return { mask, aspect: (maxX - minX + 1) / (maxY - minY + 1) }; }; for (const selected of [false, true]) - for (const kind of TRANSIT_ICON_KINDS) { - const normal = await rasterBody( - decode(transitIcon(kind, selected ? 96 : 48, { style: 'normal' })), - ); - for (const style of ['surveillance', 'thermal', 'noir', 'nvg']) { - const svg = decode(transitIcon(kind, selected ? 96 : 48, { style })); - const mono = await rasterBody(svg); - assert.deepEqual( - mono.mask, - normal.mask, - `${kind}/${style}: no envelope`, + for (const heading of [true, false]) + for (const kind of TRANSIT_ICON_KINDS) { + const normal = await rasterBody( + decode( + transitIcon(kind, selected ? 96 : 48, { style: 'normal', heading }), + ), ); - assert.ok( - Math.abs(mono.aspect / normal.aspect - 1) <= 0.05, - `${kind}/${style}: aspect`, - ); - const display = - (selected ? 30 : 20) * presetSpriteScale(style, selected); - const crt = (selected ? 30 : 20) * presetSpriteScale('retro', selected); - assert.equal(display, crt); - const frame = haloFrame( - presetSpriteOutlinePx(style, selected), - display, - ); - const crtFrame = haloFrame( - presetSpriteOutlinePx('retro', selected), - crt, - ); - assert.equal( - (display * frame.ratio) / frame.ratio, - (crt * crtFrame.ratio) / crtFrame.ratio, - 'unpadded silhouette matches CRT; only external halo padding grows', - ); - assert.equal( - (svg.match(//); + for (const style of ['surveillance', 'thermal', 'noir', 'nvg']) { + const svg = decode( + transitIcon(kind, selected ? 96 : 48, { style, heading }), + ); + const mono = await rasterBody(svg); + assert.deepEqual( + mono.mask, + normal.mask, + `${kind}/${style}: no envelope`, + ); + assert.ok( + Math.abs(mono.aspect / normal.aspect - 1) <= 0.05, + `${kind}/${style}: aspect`, + ); + const display = + (selected ? 30 : 20) * presetSpriteScale(style, selected); + const crt = + (selected ? 30 : 20) * presetSpriteScale('retro', selected); + assert.equal(display, crt); + const frame = haloFrame( + presetSpriteOutlinePx(style, selected), + display, + ); + const crtFrame = haloFrame( + presetSpriteOutlinePx('retro', selected), + crt, + ); + assert.equal( + (display * frame.ratio) / frame.ratio, + (crt * crtFrame.ratio) / crtFrame.ratio, + 'unpadded silhouette matches CRT; only external halo padding grows', + ); + assert.equal( + (svg.match(//); + } } - } }); test('sensor raster halo stays dark across its screen-space band on a white roof', async () => { @@ -238,3 +247,58 @@ test('sensor raster halo stays dark across its screen-space band on a white roof assert.ok(black.pass, JSON.stringify({ selected, black })); } }); + +test('a vehicle with a course shows its front; one without claims no direction', async () => { + const sharp = (await import('sharp')).default; + const outline = (svg) => svg.match(/ { + const { data, info } = await sharp( + Buffer.from( + ``, + ), + ) + .resize(20, 20) + .ensureAlpha() + .raw() + .toBuffer({ resolveWithObject: true }); + const out = []; + for (let y = 0; y < info.height; y++) { + let sum = 0; + for (let x = 0; x < info.width; x++) + sum += data[(y * info.width + x) * 4 + 3] / 255; + out.push(sum); + } + return out; + }; + // How much the outline differs from itself turned end for end, in pixels. + const asymmetry = (r) => + r.reduce((a, v, i) => a + Math.abs(v - r[r.length - 1 - i]), 0); + for (const kind of TRANSIT_ICON_KINDS) { + const pointed = await rows(outline(decode(transitIcon(kind)))); + const neutral = await rows( + outline(decode(transitIcon(kind, 48, { heading: false }))), + ); + assert.ok( + asymmetry(pointed) >= 2.5, + `${kind}: front reads at 20 px (${asymmetry(pointed).toFixed(2)})`, + ); + assert.ok( + asymmetry(neutral) < 0.5, + `${kind}: no implied heading (${asymmetry(neutral).toFixed(2)})`, + ); + // The front is the narrow end: the two leading rows of ink carry less + // than the two trailing rows. + const inked = pointed.flatMap((v, i) => (v > 0.05 ? [i] : [])); + const first = inked[0]; + const last = inked[inked.length - 1]; + const lead = pointed[first] + pointed[first + 1]; + const trail = pointed[last] + pointed[last - 1]; + assert.ok(lead < trail, `${kind}: nose toward -Y`); + } + assert.notEqual( + transitIcon('bus'), + transitIcon('bus', 48, { heading: false }), + ); + assert.equal(transitIcon('bus', 48, { heading: true }), transitIcon('bus')); +}); diff --git a/src/layers/transit/rendering.js b/src/layers/transit/rendering.js index 2309978a5..fafd9268b 100644 --- a/src/layers/transit/rendering.js +++ b/src/layers/transit/rendering.js @@ -232,11 +232,16 @@ export function createRendering({ state, services, parts }) { const displayPx = basePx * presetSpriteScale(style, selected); const frame = haloFrame(halo, displayPx); const px = displayPx * frame.ratio; + // A glyph with a front only when there is a course to point it along: + // without one the billboard sits at rotation 0 and a nose would say north. + const heading = Number.isFinite(entry.courseDeg); + entry.iconHeading = heading; marker.image = transitIcon( entry.mode, selected ? SELECTED_ICON_PX : undefined, { style, + heading, }, ); marker.width = px; @@ -252,6 +257,12 @@ export function createRendering({ state, services, parts }) { MODE_CESIUM_COLORS[entry.mode] || MODE_CESIUM_COLORS.unknown; } + /** Swap between the pointed and the neutral glyph when a course appears or is lost. */ + function syncHeadingIcon(entry) { + if (entry.marker && entry.iconHeading !== Number.isFinite(entry.courseDeg)) + applySpriteStyle(entry); + } + function addMarker(key, entry) { const marker = state._markers.add({ id: key, @@ -324,6 +335,7 @@ export function createRendering({ state, services, parts }) { for (const entry of state._visible) { // Idle contacts still need a course when their first usable bearing arrives. if (!state._moving.has(entry)) applyDisplayCourse(entry, monoNow); + syncHeadingIcon(entry); if (entry.key === state._selectedKey) continue; const course = entry.courseDeg; if (!Number.isFinite(course)) { @@ -427,6 +439,7 @@ export function createRendering({ state, services, parts }) { refreshRotations(now); const selected = state._vehicles.get(state._selectedKey); if (selected && state._visible.has(selected)) { + syncHeadingIcon(selected); selected.marker.rotation = Number.isFinite(selected.courseDeg) ? perspectiveProjectedRotation( state._viewer.scene, From dcd0f2cccd3d312771f7ad1fdf5dd53c0469cd66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Itallo=20Brand=C3=A3o?= <45429643+IMBrandao@users.noreply.github.com> Date: Thu, 5 Nov 2026 04:42:59 -0300 Subject: [PATCH 024/171] feat(layers): add shipwrecks layer (EMODnet + Wikidata) A new Events layer maps shipwrecks with a card per wreck: - EMODnet Human Activities heritage shipwrecks (about 6,500 in European waters, CC BY 4.0), skipping rows taken from wrecksite.eu. - Wikidata shipwrecks with a Wikipedia article plus sinking events (CC0); an event folds into its ship for the date and death toll. - A same-origin /api/shipwrecks proxy refreshes once a day and serves the last snapshot as stale for up to a week. Markers are a boat icon coloured by era and sized by deaths; four era chips filter the layer. The card follows the air-accidents layout (deaths first). Text that names people is dropped; victims appear as a count only. Co-Authored-By: Claude Opus 5.5 --- DATA_SOURCES.md | 2 + docs/CURRENT-STATE.md | 31 ++ scripts/format-scope.json | 6 +- scripts/package-boundaries.json | 24 ++ server/providers/local.js | 2 + server/providers/shipwrecks.js | 151 ++++++++ src/app/constructCatalog.js | 2 + src/app/constructCatalog.test.mjs | 4 +- src/app/layers/shipwrecks.js | 23 ++ src/app/sourceComposition.js | 1 + src/app/sourceComposition.test.mjs | 2 +- src/data/dataCredits.js | 8 + src/data/layerState.js | 1 + src/data/layerState.test.mjs | 50 ++- src/data/layerStateTokenLedger.test.mjs | 71 ++-- src/data/layerStateTokenReservations.json | 1 + src/data/shipwrecksProxy.test.mjs | 132 +++++++ src/i18n/locales/ar.json | 37 +- src/i18n/locales/de.json | 33 +- src/i18n/locales/es.json | 34 +- src/i18n/locales/fr.json | 34 +- src/i18n/locales/it.json | 34 +- src/i18n/locales/ja.json | 32 +- src/i18n/locales/pt.json | 34 +- src/i18n/locales/ru.json | 35 +- src/i18n/locales/uk.json | 35 +- src/i18n/locales/zh-CN.json | 32 +- src/i18n/locales/zh-Hant.json | 32 +- src/i18n/same-as-english.json | 11 + src/layers/shipwrecks/cards.js | 123 +++++++ src/layers/shipwrecks/cards.test.mjs | 63 ++++ src/layers/shipwrecks/eras.js | 33 ++ src/layers/shipwrecks/eras.test.mjs | 23 ++ src/layers/shipwrecks/index.js | 424 +++++++++++++++++++++ src/layers/shipwrecks/records.js | 428 ++++++++++++++++++++++ src/layers/shipwrecks/records.test.mjs | 212 +++++++++++ src/layers/shipwrecks/source.js | 35 ++ src/standalone/layerSources.js | 2 + src/ui/layerNames.js | 1 + src/ui/layerPanel.js | 1 + src/voice/layerManifest.js | 2 + 41 files changed, 2168 insertions(+), 73 deletions(-) create mode 100644 server/providers/shipwrecks.js create mode 100644 src/app/layers/shipwrecks.js create mode 100644 src/data/shipwrecksProxy.test.mjs create mode 100644 src/layers/shipwrecks/cards.js create mode 100644 src/layers/shipwrecks/cards.test.mjs create mode 100644 src/layers/shipwrecks/eras.js create mode 100644 src/layers/shipwrecks/eras.test.mjs create mode 100644 src/layers/shipwrecks/index.js create mode 100644 src/layers/shipwrecks/records.js create mode 100644 src/layers/shipwrecks/records.test.mjs create mode 100644 src/layers/shipwrecks/source.js diff --git a/DATA_SOURCES.md b/DATA_SOURCES.md index cac0b5ab7..805771b67 100644 --- a/DATA_SOURCES.md +++ b/DATA_SOURCES.md @@ -39,6 +39,8 @@ How to read this: | **NASA GIBS** (WMTS tiles + Worldview Snapshots) and **NASA CMR** (granule catalog) | Recent Imagery layer: HLS S30/L30 (Sentinel-2, Landsat 8/9) and VIIRS true-colour tiles draped on the map, per-day thumbnails and PNG exports; the HLS granule catalog (dates, cloud, footprints) for a selected box | U.S. public domain (NASA data); keyless, browser-direct (CORS `*`); no bulk use — one 30-day catalog query per box, tiles bounded to the box, six tile requests in flight | "We acknowledge the use of imagery provided by services from NASA's Global Imagery Browse Services (GIBS), part of NASA's Earth Science Data and Information System (ESDIS)." — [gibs.earthdata.nasa.gov](https://gibs.earthdata.nasa.gov), [HLS](https://lpdaac.usgs.gov/products/hlss30v002/) | | **NIFC WFIGS** (Wildland Fire Interagency Geospatial Services, ArcGIS feature service) | Fire Perimeters layer: current interagency wildfire incident perimeters, containment, and incident facts | U.S. public domain (interagency wildland-fire data published through the [NIFC Open Data portal](https://data-nifc.opendata.arcgis.com/)); fetched keyless through `/api/fire-perimeters` (5-minute server cache) with `exceededTransferLimit` paging | "Wildfire perimeters: National Interagency Fire Center (WFIGS)" | | **S2 Underground GhostMaps** (`github.com/s2underground/GhostMaps`) | S2 GhostMaps layer: the current edition of S2's KMZ intel products (Common Intelligence Picture, 30-day kinetic pull, Border Crisis Map, Iran and Yemen products, newest incident drop). Keyless. `/api/ghostmaps` reads the branch head from git's ref advertisement every 15 s (`GHOSTMAPS_POLL_SECONDS`, minimum 5 s), lists the tree through the GitHub REST API only when the head changes (optional `GITHUB_TOKEN`), downloads files by commit-pinned raw URLs into `.gev-cache/ghostmaps/` and pushes new catalogs to browsers over server-sent events | [CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/) (repository README: "S2 Underground © 2025 by S2A1"); non-commercial, attribution required; files are fetched at runtime, never stored in this repository | "S2 GhostMaps intel products: S2 Underground © by S2A1, CC BY-NC-SA 4.0" — shown in-app | +| **EMODnet Human Activities — Ship wrecks** (`ows.emodnet-humanactivities.eu/wfs`, layer `emodnet:heritageshipwrecks`) | Shipwrecks layer: about 7,000 wrecks in European waters (name, sinking year and text, vessel type, least depth and its quality, position accuracy, period, cargo, protected status). Keyless WFS GeoJSON, fetched by `/api/shipwrecks` once a day; rows sourced from wrecksite.eu are skipped and text naming people is dropped | [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) (EMODnet catalogue record `e965088b-a265-4517-84df-c49b156af8a7`; data originator AND-International, compiled from SHOM, National Monuments Service, Historic England and the Oxford Roman Economy Project); fetched at runtime, not stored in this repository | "Shipwrecks (Europe): EMODnet Human Activities (data originator AND-International, …), CC BY 4.0" — shown in-app | +| **Wikidata — shipwrecks** (`query.wikidata.org/sparql`) | Shipwrecks layer: shipwreck items (Q852190) with a coordinate and at least one Wikipedia article: name, ship type, sinking date, death count, description and article link. Keyless, fetched by `/api/shipwrecks` once a day | [CC0](https://creativecommons.org/publicdomain/zero/1.0/); fetched at runtime | "Shipwrecks (worldwide): Wikidata (CC0)" — shown in-app | | **InciWeb** (inciweb.wildfire.gov) | Per-incident "InciWeb ↗" card links to official incident pages (narratives, evacuation/closure notices) | U.S. government public incident information. Links are matched best-effort by incident name and state, with incident page origin and update times checked on selection. Same-origin `/api/fire-perimeters/inciweb` routes cache the catalog for 1 hour and publication metadata for 30 minutes; linked pages remain InciWeb content | "Incident information: InciWeb (inciweb.wildfire.gov)" | | **FAA Special Use Airspace** (`services6.arcgis.com` FeatureServer `Special_Use_Airspace`) | Prohibited & Restricted Airspace layer: US prohibited (P) and restricted (R) special-use airspace polygons (not the UAS Facility Map or UAS flight restrictions), altitude limits from the `*_VAL`/`*_UOM`/`*_CODE` fields, times of use, and controlling agency | U.S. public domain (FAA aeronautical data published through the [FAA AIS Open Data portal](https://adds-faa.opendata.arcgis.com/)); fetched keyless through `/api/drone-airspace` (1-hour server cache). Informational only — not a substitute for official UAS flight-planning tools | "Prohibited & restricted airspace: FAA Special Use Airspace" | | **OpenFreeMap / OpenMapTiles** | Vector tiles | OpenStreetMap data under ODbL 1.0 | OpenFreeMap © OpenMapTiles | diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index f1244947d..e0df74333 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -98,6 +98,36 @@ across the antimeridian, so they cannot use the strict ±180 check as-is, and `src/sources/adsbRecords.js` and `server/providers/common/geo.js` keep their own implementations. +## Shipwrecks — EMODnet and Wikidata + +The Events group includes **Shipwrecks** (`shipwrecks`, share-link token `9`), +off by default. `/api/shipwrecks` downloads EMODnet Human Activities' +`emodnet:heritageshipwrecks` WFS layer (about 7,000 wrecks in European waters +compiled from SHOM, Ireland's National Monuments Service, Historic England and +the Oxford Roman Economy Project; CC BY 4.0) and a Wikidata SPARQL query for +shipwreck items with a coordinate and at least one Wikipedia article (about +1,450 worldwide; CC0), at most once a day, and serves the last good snapshot as +stale for up to seven days when a refresh fails. One source failing still serves +the other. EMODnet rows the portal took from wrecksite.eu are skipped (that site +is not openly licensed). A Wikidata wreck with the same name within 3 km of an +EMODnet wreck is merged into one record that keeps the article link and takes +EMODnet's year, sinking text, depth and position accuracy. Only ship columns are +read: EMODnet's long histories (`ship_char`, `obj_desc`) are not, and any +sinking or cargo text that names a person (owner, master, a diver who reported +it) is dropped whole; deaths appear only as a Wikidata count. + +The globe draws a small hull marker per wreck, ground-clamped with the depth +test off and the horizon cull GhostMaps uses, coloured by era: before 1900 +(ancient wrecks dated only by period count here), 1900–1945, after 1945, and +date unknown. Four row chips show or hide each era (session-only, not in the +share link). Clicking a marker opens a `stateless` card with the name, vessel +type, sinking date or year (or the archaeological dating), what happened, deaths, +least depth and its quality, how well the position is known, period notes or +the Wikidata description, cargo or finds, protected status, waters and source. +Clicking the card opens the Wikipedia article (else the Wikidata item), the +wreck's own web page when EMODnet lists one, else EMODnet's portal. Voice does +not toggle this layer yet (prompt budget, as for the airspace layer). + ## Prohibited & Restricted Airspace — FAA special-use airspace The Infrastructure group includes **Prohibited & Restricted Airspace** (`drone-airspace`, @@ -4212,6 +4242,7 @@ its criteria cannot be silently ignored. | Ski Pistes ⛷ (`ski-pistes`) | OpenSnowMap piste raster tiles (keyless; CC BY-SA tiles, OSM data ODbL; no bulk download) | `src/data/osmOverlays.js` | — (browser-direct tiles) | on view (Cesium tile requests; no polling) | | 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) | | Prohibited & Restricted Airspace 🚫 | FAA Special Use Airspace prohibited (P) and restricted (R) zones (keyless FeatureServer, simplified geometry) | `src/layers/droneAirspace/` via `src/app/layers/droneAirspace.js` | `/api/drone-airspace` | 1 h (server cache 1 h; stale-on-error) | +| Shipwrecks ⚓ (`shipwrecks`) | EMODnet Human Activities heritage shipwrecks (European waters, keyless WFS, CC BY 4.0) and Wikidata (notable wrecks worldwide, keyless, CC0) | `src/layers/shipwrecks/` via `src/app/layers/shipwrecks.js` | `/api/shipwrecks` | 6 h page check; server refresh once a day (stale-on-error up to 7 days) | 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; diff --git a/scripts/format-scope.json b/scripts/format-scope.json index 2c589d8cc..d3eb3d95b 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -1267,5 +1267,9 @@ "src/voice/geminiTextChat.js", "src/voice/panelLayout.js", "src/voice/textChat.js", - "src/voice/textProtocol.js" + "src/voice/textProtocol.js", + "src/layers/shipwrecks/records.test.mjs", + "src/layers/shipwrecks/cards.test.mjs", + "src/layers/shipwrecks/eras.test.mjs", + "src/data/shipwrecksProxy.test.mjs" ] diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index d008ceaaa..7460d06d2 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -2939,6 +2939,12 @@ "src/layers/ghostMaps/records.js", "src/layers/ghostMaps/kml.js", "src/layers/ghostMaps/source.js", + "src/app/layers/shipwrecks.js", + "src/layers/shipwrecks/index.js", + "src/layers/shipwrecks/source.js", + "src/layers/shipwrecks/records.js", + "src/layers/shipwrecks/cards.js", + "src/layers/shipwrecks/eras.js", "src/app/layers/droneAirspace.js", "src/layers/droneAirspace/index.js", "src/layers/droneAirspace/source.js", @@ -3690,6 +3696,12 @@ "src/layers/ghostMaps/records.js", "src/layers/ghostMaps/kml.js", "src/layers/ghostMaps/source.js", + "src/app/layers/shipwrecks.js", + "src/layers/shipwrecks/index.js", + "src/layers/shipwrecks/source.js", + "src/layers/shipwrecks/records.js", + "src/layers/shipwrecks/cards.js", + "src/layers/shipwrecks/eras.js", "src/app/layers/droneAirspace.js", "src/layers/droneAirspace/index.js", "src/layers/droneAirspace/source.js", @@ -4751,6 +4763,12 @@ "src/layers/ghostMaps/records.js", "src/layers/ghostMaps/kml.js", "src/layers/ghostMaps/source.js", + "src/app/layers/shipwrecks.js", + "src/layers/shipwrecks/index.js", + "src/layers/shipwrecks/source.js", + "src/layers/shipwrecks/records.js", + "src/layers/shipwrecks/cards.js", + "src/layers/shipwrecks/eras.js", "src/sources/httpBody.js", "src/data/geoFileImport.js", "src/i18n/marker.js", @@ -4778,6 +4796,12 @@ "exports": ["./layers/ghostmaps/source"], "modules": [ "src/layers/ghostMaps/source.js", + "src/app/layers/shipwrecks.js", + "src/layers/shipwrecks/index.js", + "src/layers/shipwrecks/source.js", + "src/layers/shipwrecks/records.js", + "src/layers/shipwrecks/cards.js", + "src/layers/shipwrecks/eras.js", "src/layers/ghostMaps/catalog.js", "src/sources/httpBody.js", "src/i18n/marker.js" diff --git a/server/providers/local.js b/server/providers/local.js index 7067f3ec5..2b3b27c54 100644 --- a/server/providers/local.js +++ b/server/providers/local.js @@ -28,6 +28,7 @@ import { weatherProxy } from './weather.js'; import { firePerimetersProxy } from './firePerimeters.js'; import { gnssIntegrityProxy } from './gnssIntegrity.js'; import { ghostMapsProxy } from './ghostMaps.js'; +import { shipwrecksProxy } from './shipwrecks.js'; import { droneAirspaceProxy } from './droneAirspace.js'; import { cycloneProxy } from './cyclones.js'; import { windProxy } from './wind.js'; @@ -80,6 +81,7 @@ function localProviderPlugins({ firePerimetersProxy(), gnssIntegrityProxy(), ghostMapsProxy(), + shipwrecksProxy(), droneAirspaceProxy(), keySetupEndpoint(), ]; diff --git a/server/providers/shipwrecks.js b/server/providers/shipwrecks.js new file mode 100644 index 000000000..44491209d --- /dev/null +++ b/server/providers/shipwrecks.js @@ -0,0 +1,151 @@ +import { + EMODNET_WFS_URL, + WIKIDATA_QUERY, + mergeShipwreckRecords, + normalizeEmodnetFeatures, + normalizeWikidataResults, +} from '../../src/layers/shipwrecks/records.js'; +import { coalesceProxyRequest, readResponseJsonCapped } from './common/http.js'; +import { clientKey, makeRateLimiter } from './common/rate-limit.js'; + +const MIB = 1024 * 1024; +/** EMODnet republishes the wreck layer about once a year; Wikidata daily at most. */ +const REFRESH_MS = 24 * 60 * 60 * 1000; +/** A failed refresh keeps serving the last snapshot this long, marked stale. */ +const STALE_MAX_MS = 7 * REFRESH_MS; +// Only the columns the card uses; ship_char/obj_desc histories can name people +// and are not read beyond a short vessel type. +const EMODNET_PROPERTIES = [ + 'source_id', + 'country', + 'name', + 'least_depth', + 'depth_prec', + 'loc_prec', + 'sink_context', + 'sink_yr', + 'dating', + 'period', + 'statutory', + 'ship_char', + 'obj_type', + 'artefacts', + 'source_inf', + 'website1', + 'point_info', + 'the_geom', +].join(','); +const EMODNET_URL = `${EMODNET_WFS_URL}&propertyName=${EMODNET_PROPERTIES}`; +const WIKIDATA_URL = + 'https://query.wikidata.org/sparql?format=json&query=' + + encodeURIComponent(WIKIDATA_QUERY); +// Wikimedia asks automated clients to name themselves. +const USER_AGENT = + "God's Eye View shipwrecks layer (https://github.com/bilawalsidhu/gods-eye-view)"; + +/** Fixed-origin, cached EMODnet + Wikidata shipwreck snapshot for dev and preview. */ +export function shipwrecksProxy({ + fetchImpl = (...args) => globalThis.fetch(...args), + now = () => Date.now(), +} = {}) { + let snapshot = null; + const inFlight = new Map(); + const allow = makeRateLimiter({ windowMs: 60_000, max: 30, globalMax: 600 }); + + async function upstreamJson(url, maxBytes) { + const signal = AbortSignal.timeout(90_000); + const response = await fetchImpl(url, { + signal, + redirect: 'error', + headers: { 'User-Agent': USER_AGENT, Accept: 'application/json' }, + }); + if (!response.ok) { + await response.body?.cancel(); + throw new Error('upstream_unavailable'); + } + return readResponseJsonCapped(response, maxBytes, signal); + } + + async function fetchEmodnet() { + const records = normalizeEmodnetFeatures( + await upstreamJson(EMODNET_URL, 32 * MIB), + ); + if (!records.length) throw new Error('invalid_emodnet_layer'); + return records; + } + + async function fetchWikidata() { + return normalizeWikidataResults(await upstreamJson(WIKIDATA_URL, 16 * MIB)); + } + + /** One source failing still serves the other; both failing is an error. */ + async function load() { + const [emodnet, wikidata] = await Promise.allSettled([ + fetchEmodnet(), + fetchWikidata(), + ]); + if (emodnet.status === 'rejected' && wikidata.status === 'rejected') + throw new Error('shipwrecks_unavailable'); + const records = mergeShipwreckRecords( + emodnet.status === 'fulfilled' ? emodnet.value : [], + wikidata.status === 'fulfilled' ? wikidata.value : [], + ); + return { + fetchedAt: now(), + sources: { + emodnet: emodnet.status === 'fulfilled', + wikidata: wikidata.status === 'fulfilled', + }, + records, + }; + } + + async function acquire() { + if (snapshot && now() - snapshot.fetchedAt < REFRESH_MS) + return { value: snapshot, stale: false }; + try { + const { promise } = coalesceProxyRequest(inFlight, 'snapshot', load); + snapshot = await promise; + return { value: snapshot, stale: false }; + } catch (error) { + if (snapshot && now() - snapshot.fetchedAt <= STALE_MAX_MS) + return { value: snapshot, stale: true }; + throw error; + } + } + + async function handler(req, res) { + const json = (status, value, stale = false) => { + if (res.destroyed) return; + res.writeHead(status, { + 'Content-Type': 'application/json', + 'Cache-Control': 'no-store', + ...(status === 405 ? { Allow: 'GET' } : {}), + ...(status === 429 ? { 'Retry-After': '60' } : {}), + ...(stale ? { 'X-Data-Stale': 'true' } : {}), + }); + res.end(JSON.stringify(value)); + }; + if (req.method !== 'GET') return json(405, { error: 'method_not_allowed' }); + const path = (req.url || '/').split('?')[0]; + if (path !== '/' && path !== '') + return json(404, { error: 'unknown_route' }); + if (!allow(clientKey(req))) return json(429, { error: 'rate_limited' }); + try { + const { value, stale } = await acquire(); + json(200, stale ? { ...value, stale: true } : value, stale); + } catch { + json(502, { error: 'shipwrecks_unavailable' }); + } + } + + return { + name: 'shipwrecks', + configureServer({ middlewares }) { + middlewares.use('/api/shipwrecks', handler); + }, + configurePreviewServer({ middlewares }) { + middlewares.use('/api/shipwrecks', handler); + }, + }; +} diff --git a/src/app/constructCatalog.js b/src/app/constructCatalog.js index 488a5e9ab..74c6df1b7 100644 --- a/src/app/constructCatalog.js +++ b/src/app/constructCatalog.js @@ -29,6 +29,7 @@ import { createApplicationAirQuality } from './layers/airQuality.js'; import { createApplicationFirePerimeters } from './layers/perimeters.js'; import { createApplicationGnssIntegrity } from './layers/gnss.js'; import { createApplicationGhostMaps } from './layers/ghostMaps.js'; +import { createApplicationShipwrecks } from './layers/shipwrecks.js'; import { createApplicationDroneAirspace } from './layers/droneAirspace.js'; import { createApplicationCables } from './layers/submarineCables.js'; import { createOsmOverlayLayers } from '../data/osmOverlays.js'; @@ -134,6 +135,7 @@ export function createApplicationCatalog({ windowMs: sources['gnss-integrity'].windowMs, }), createApplicationGhostMaps({ source: sources['s2-ghostmaps'] }), + createApplicationShipwrecks({ source: sources.shipwrecks }), createApplicationDroneAirspace({ source: sources['drone-airspace'], }), diff --git a/src/app/constructCatalog.test.mjs b/src/app/constructCatalog.test.mjs index 82a1dbcf0..3d61df3b3 100644 --- a/src/app/constructCatalog.test.mjs +++ b/src/app/constructCatalog.test.mjs @@ -40,7 +40,7 @@ test('catalogs construct distinct layers and classification from their supplied signal: b.signal, surface: fixtureSurface(b.signal), }); - assert.equal(first.layers.length, 37); + assert.equal(first.layers.length, 38); assert.ok(first.get('local-adsb'), 'Local ADS-B is registered'); assert.deepEqual( first.metadata.find(({ id }) => id === 'osm-places'), @@ -161,7 +161,7 @@ test('Mapillary can be omitted or replaced without changing catalog membership', surface: fixtureSurface(lifetime.signal), }; const catalog = createApplicationCatalog(options); - assert.equal(catalog.layers.length, 37); + assert.equal(catalog.layers.length, 38); assert.deepEqual(catalog.get('street-level').providerIds, []); assert.equal( catalogControlServices(catalog).streetLevelLayer, diff --git a/src/app/layers/shipwrecks.js b/src/app/layers/shipwrecks.js new file mode 100644 index 000000000..ece2d2dce --- /dev/null +++ b/src/app/layers/shipwrecks.js @@ -0,0 +1,23 @@ +import * as Cesium from 'cesium'; +import { createShipwrecksLayer } from '../../layers/shipwrecks/index.js'; +import * as picking from '../../data/pickRegistry.js'; +import * as overlays from '../../overlays/worldOverlay.js'; +import { isPointerFree } from '../../data/inputOwnership.js'; + +/** Wire the EMODnet + Wikidata shipwrecks layer into the application catalog. */ +export function createApplicationShipwrecks(options) { + return createShipwrecksLayer({ + overlayHost: { + setEntries: overlays.setOverlayEntries, + setVisible: overlays.setOverlaySourceVisible, + clearSource: overlays.clearOverlaySource, + hitTest: overlays.hitTestWorldOverlay, + }, + openExternal: (url) => window.open(url, '_blank', 'noopener,noreferrer'), + screenSpaceEventHandlerFactory: (viewer) => + new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas), + picking, + pointer: { isPointerFree }, + ...options, + }); +} diff --git a/src/app/sourceComposition.js b/src/app/sourceComposition.js index a12378260..c45b63e0f 100644 --- a/src/app/sourceComposition.js +++ b/src/app/sourceComposition.js @@ -49,6 +49,7 @@ export const CATALOG_SOURCE_CONTRACTS = Object.freeze({ 'air-quality': contract(['air-quality'], ['getSnapshot']), 'gnss-integrity': contract(['gnss-integrity'], ['getSnapshot']), 's2-ghostmaps': contract(['s2-ghostmaps'], ['getCatalog', 'getFile']), + shipwrecks: contract(['shipwrecks'], ['getSnapshot']), 'drone-airspace': contract(['drone-airspace'], ['getSnapshot']), cables: contract(['telegeography-submarine-cables'], ['fetch']), transit: contract(['transit'], ['requestSnapshot', 'getHistory']), diff --git a/src/app/sourceComposition.test.mjs b/src/app/sourceComposition.test.mjs index cee9c1246..2a18039f2 100644 --- a/src/app/sourceComposition.test.mjs +++ b/src/app/sourceComposition.test.mjs @@ -37,7 +37,7 @@ test('every acquisition source can be omitted without losing catalog membership' test('all acquisition sources may be absent, and enable fails before initializing or fetching', async (t) => { const actual = catalog({}, t); - assert.equal(actual.layers.length, 37); + assert.equal(actual.layers.length, 38); const manager = new LayerLifecycle( {}, { getSourceAvailability: actual.getSourceAvailability }, diff --git a/src/data/dataCredits.js b/src/data/dataCredits.js index 29075550c..6da48aa00 100644 --- a/src/data/dataCredits.js +++ b/src/data/dataCredits.js @@ -492,6 +492,14 @@ export const DATA_CREDITS = [ 'licensed under CC BY-NC-SA 4.0. ' + 'Shown as published; reports are S2 assessments, not verified fact.', }, + { + key: 'shipwrecks', + html: + 'Shipwrecks (Europe): EMODnet Human Activities ' + + '(data originator AND-International, compiled from SHOM, Ireland’s National Monuments Service, Historic England and the Oxford Roman Economy Project), ' + + 'licensed under CC BY 4.0' + + ' · Shipwrecks (worldwide): Wikidata (CC0)', + }, { key: 'drivebc-cctv', html: diff --git a/src/data/layerState.js b/src/data/layerState.js index 46dadf9a0..9f26d6cc9 100644 --- a/src/data/layerState.js +++ b/src/data/layerState.js @@ -691,6 +691,7 @@ export const LAYER_STATE_REGISTRY = Object.freeze([ optionOwner: 'satellites', }), Object.freeze({ id: 'sea-marks', token: '6', disposition: 'enabled-only' }), + Object.freeze({ id: 'shipwrecks', token: '9', disposition: 'enabled-only' }), Object.freeze({ id: 'ski-pistes', token: '7', disposition: 'enabled-only' }), Object.freeze({ id: 'street-level', diff --git a/src/data/layerState.test.mjs b/src/data/layerState.test.mjs index 9d30e8973..b6dfd5354 100644 --- a/src/data/layerState.test.mjs +++ b/src/data/layerState.test.mjs @@ -203,8 +203,8 @@ function encode(state) { test('production registry is exact, canonical, and rejects incomplete contracts', async () => { assert.equal(validateLayerStateRegistry(), true); - assert.equal(REGISTERED_LAYER_IDS.length, 35); - assert.equal(new Set(REGISTERED_LAYER_IDS).size, 35); + assert.equal(REGISTERED_LAYER_IDS.length, 36); + assert.equal(new Set(REGISTERED_LAYER_IDS).size, 36); assert.ok(REGISTERED_LAYER_IDS.includes('transit')); assert.deepEqual(REGISTERED_LAYER_IDS, [...REGISTERED_LAYER_IDS].sort()); assert.deepEqual(LEGACY_LAYER_STATE_TOKENS, { @@ -243,19 +243,17 @@ test('production registry is exact, canonical, and rejects incomplete contracts' for (const [id, token] of Object.entries(LEGACY_LAYER_STATE_TOKENS)) { assert.equal(LAYER_STATE_TOKEN_RESERVATIONS[id], token); } - assert.equal(nextLayerStateToken(), '9'); + assert.equal(nextLayerStateToken(), '00'); assert.equal( nextLayerStateToken({ ...LAYER_STATE_TOKEN_RESERVATIONS, - alpha: '9', - bravo: '00', + alpha: '00', + bravo: '01', }), - '01', + '02', ); - const digitsExhausted = { - ...LAYER_STATE_TOKEN_RESERVATIONS, - ...Object.fromEntries([...'9'].map((digit) => [`prior-${digit}`, digit])), - }; + // shipwrecks took the last single digit, 9. + const digitsExhausted = { ...LAYER_STATE_TOKEN_RESERVATIONS }; assert.equal(nextLayerStateToken(digitsExhausted), '00'); assert.equal( nextLayerStateToken({ ...digitsExhausted, retired: '00', used: '01' }), @@ -306,8 +304,8 @@ test('production registry is exact, canonical, and rejects incomplete contracts' assert.equal( validateLayerStateAllocations(LAYER_STATE_TOKEN_RESERVATIONS, { ...LAYER_STATE_TOKEN_RESERVATIONS, - future: '9', - next: '00', + future: '00', + next: '01', }), true, ); @@ -315,12 +313,12 @@ test('production registry is exact, canonical, and rejects incomplete contracts' () => validateLayerStateAllocations(LAYER_STATE_TOKEN_RESERVATIONS, { ...LAYER_STATE_TOKEN_RESERVATIONS, - future: '00', + future: '01', }), - /next free token 9/, + /next free token 00/, ); const beforeLastDigit = { ...digitsExhausted }; - delete beforeLastDigit['prior-9']; + delete beforeLastDigit.shipwrecks; assert.equal( validateLayerStateAllocations(beforeLastDigit, { ...beforeLastDigit, @@ -340,10 +338,10 @@ test('production registry is exact, canonical, and rejects incomplete contracts' assert.throws( () => validateLayerStateAllocations( - { ...LAYER_STATE_TOKEN_RESERVATIONS, merged: '9' }, - { ...LAYER_STATE_TOKEN_RESERVATIONS, merged: '9', competing: '9' }, + { ...LAYER_STATE_TOKEN_RESERVATIONS, merged: '00' }, + { ...LAYER_STATE_TOKEN_RESERVATIONS, merged: '00', competing: '00' }, ), - /next free token 00/, + /next free token 01/, ); assert.throws( () => validateLayerStateAllocations({ future: '00' }, { future: '01' }), @@ -2711,6 +2709,22 @@ test('drone restrictions uses digit 8 without colliding with fire perimeters', ( ); }); +test('shipwrecks uses digit 9 without colliding with drone restrictions', () => { + const decoded = decodeLayerStateParams(new URLSearchParams('v=2&l=9.8')); + assert.deepEqual(decoded.enabledLayerIds, [ + 'drone-airspace', + 'shipwrecks', + ]); + assert.equal( + LAYER_STATE_REGISTRY.find(({ id }) => id === 'shipwrecks').token, + '9', + ); + assert.deepEqual( + decodeLayerStateParams(new URLSearchParams(encode(decoded))), + decoded, + ); +}); + test('GNSS interference uses digit 3 without colliding with other digit tokens', () => { const decoded = decodeLayerStateParams(new URLSearchParams('v=2&l=3.2.1')); assert.deepEqual(decoded.enabledLayerIds, [ diff --git a/src/data/layerStateTokenLedger.test.mjs b/src/data/layerStateTokenLedger.test.mjs index d46782378..44086b4bd 100644 --- a/src/data/layerStateTokenLedger.test.mjs +++ b/src/data/layerStateTokenLedger.test.mjs @@ -128,7 +128,7 @@ test('reservation ledger is complete, pinned, and rejects duplicate or malformed { ...parseLayerStateTokenReservations(reservationRows) }, { ...LAYER_STATE_TOKEN_RESERVATIONS }, ); - assert.equal(Object.keys(LAYER_STATE_TOKEN_RESERVATIONS).length, 35); + assert.equal(Object.keys(LAYER_STATE_TOKEN_RESERVATIONS).length, 36); assert.deepEqual( { ...LAYER_STATE_TOKEN_RESERVATIONS }, { @@ -140,6 +140,7 @@ test('reservation ledger is complete, pinned, and rejects duplicate or malformed 'sea-marks': '6', 'ski-pistes': '7', 'drone-airspace': '8', + shipwrecks: '9', }, ); assert.throws( @@ -165,9 +166,9 @@ test('reservation ledger is complete, pinned, and rejects duplicate or malformed /Duplicate layer-state token reservation/, ); assert.equal( - parseLayerStateTokenReservations([...reservationRows, ['future', '9']]) + parseLayerStateTokenReservations([...reservationRows, ['future', '00']]) .future, - '9', + '00', ); assert.throws( () => @@ -185,14 +186,14 @@ test('reservation ledger is complete, pinned, and rejects duplicate or malformed test('published retired digits and competing PRs advance the merge-time allocation', () => { withPublishedBase( - { rows: [...reservationRows, ['retired-layer', '9']] }, + { rows: [...reservationRows, ['retired-layer', '00']] }, (cwd) => { const published = readPublishedLayerStateReservations('HEAD', cwd); - assert.equal(nextLayerStateToken(published), '00'); + assert.equal(nextLayerStateToken(published), '01'); assert.equal( validateLayerStateAllocations(published, { ...published, - newcomer: '00', + newcomer: '01', }), true, ); @@ -200,15 +201,15 @@ test('published retired digits and competing PRs advance the merge-time allocati () => validateLayerStateAllocations(published, { ...published, - competing: '9', + competing: '00', }), - /next free token 00/, + /next free token 01/, ); assert.throws( () => validateLayerStateAllocations(published, { ...LAYER_STATE_TOKEN_RESERVATIONS, - newcomer: '9', + newcomer: '00', }), /changed or removed: retired-layer/, ); @@ -216,8 +217,8 @@ test('published retired digits and competing PRs advance the merge-time allocati ); }); -test('PR B manually replaces provisional 9 with 00 after PR A publishes 9', () => { - withPublishedBase({ rows: [...reservationRows, ['pr-a', '9']] }, (cwd) => { +test('PR B manually replaces provisional 00 with 01 after PR A publishes 00', () => { + withPublishedBase({ rows: [...reservationRows, ['pr-a', '00']] }, (cwd) => { mkdirSync(path.join(cwd, 'scripts')); const fixtureChecker = path.join( cwd, @@ -238,8 +239,8 @@ test('PR B manually replaces provisional 9 with 00 after PR A publishes 9', () = writeCodecFixture( cwd, - [...reservationRows, ['pr-b', '9']], - [{ id: 'pr-b', token: '9' }], + [...reservationRows, ['pr-b', '00']], + [{ id: 'pr-b', token: '00' }], ); const beforeRebase = runCheck(); assert.equal(beforeRebase.status, 1); @@ -247,10 +248,10 @@ test('PR B manually replaces provisional 9 with 00 after PR A publishes 9', () = writeCodecFixture( cwd, - [...reservationRows, ['pr-a', '9'], ['pr-b', '9']], + [...reservationRows, ['pr-a', '00'], ['pr-b', '00']], [ - { id: 'pr-a', token: '9' }, - { id: 'pr-b', token: '9' }, + { id: 'pr-a', token: '00' }, + { id: 'pr-b', token: '00' }, ], ); const staleRebase = runCheck(); @@ -258,16 +259,16 @@ test('PR B manually replaces provisional 9 with 00 after PR A publishes 9', () = assert.match(staleRebase.stderr, /Duplicate layer-state token reservation/); const published = readPublishedLayerStateReservations('HEAD', cwd); - assert.equal(nextLayerStateToken(published), '00'); - const validBaselineRows = [...reservationRows, ['pr-a', '9']]; - writeCodecFixture(cwd, validBaselineRows, [{ id: 'pr-a', token: '9' }]); + assert.equal(nextLayerStateToken(published), '01'); + const validBaselineRows = [...reservationRows, ['pr-a', '00']]; + writeCodecFixture(cwd, validBaselineRows, [{ id: 'pr-a', token: '00' }]); const helper = spawnSync( process.execPath, [realpathSync(fixtureNext), 'pr-b'], { cwd, encoding: 'utf8' }, ); assert.equal(helper.status, 0, helper.stderr); - assert.match(helper.stdout, /pr-b: 00/); + assert.match(helper.stdout, /pr-b: 01/); assert.deepEqual( JSON.parse(readFileSync(path.join(cwd, LEDGER_PATH), 'utf8')), validBaselineRows, @@ -275,26 +276,23 @@ test('PR B manually replaces provisional 9 with 00 after PR A publishes 9', () = ); writeCodecFixture( cwd, - [...reservationRows, ['pr-a', '9'], ['pr-b', '00']], + [...reservationRows, ['pr-a', '00'], ['pr-b', '01']], [ - { id: 'pr-a', token: '9' }, - { id: 'pr-b', token: '00' }, + { id: 'pr-a', token: '00' }, + { id: 'pr-b', token: '01' }, ], ); const corrected = runCheck(); assert.equal(corrected.status, 0, corrected.stderr); - assert.match(corrected.stdout, /36 published, 1 new/); + assert.match(corrected.stdout, /37 published, 1 new/); }); }); test('allocation batches cross the last digit and base-36 pair boundaries in order', () => { - const digitRows = [...'9'].map((digit) => [`retired-${digit}`, digit]); - const allDigits = parseLayerStateTokenReservations([ - ...reservationRows, - ...digitRows, - ]); + // shipwrecks took the last single digit, 9. + const allDigits = parseLayerStateTokenReservations(reservationRows); const beforeNine = { ...allDigits }; - delete beforeNine['retired-9']; + delete beforeNine['shipwrecks']; assert.equal( validateLayerStateAllocations(beforeNine, { ...beforeNine, @@ -340,26 +338,19 @@ test('allocation batches cross the last digit and base-36 pair boundaries in ord test('an isolated valid two-character fixture round-trips an l field beyond the old 64-character cap', async () => { const cwd = mkdtempSync(path.join(tmpdir(), 'gev-layer-token-width-')); try { - const priorDigits = [...'9'].map((digit) => [ - `qa-prior-digit-${digit}`, - digit, - ]); const fixtureLayers = ['00', '01', '02', '03'].map((token) => ({ id: `qa-layer-${token}`, token, })); const fixtureRows = [ ...reservationRows, - ...priorDigits, ...fixtureLayers.map(({ id, token }) => [id, token]), ]; const fixtureModule = writeCodecFixture(cwd, fixtureRows, fixtureLayers); const codec = await import(pathToFileURL(fixtureModule)); assert.equal(codec.validateLayerStateRegistry(), true); assert.equal( - nextLayerStateToken( - parseLayerStateTokenReservations([...reservationRows, ...priorDigits]), - ), + nextLayerStateToken(parseLayerStateTokenReservations(reservationRows)), '00', ); assert.equal( @@ -377,7 +368,7 @@ test('an isolated valid two-character fixture round-trips an l field beyond the const params = new URLSearchParams([['v', '2']]); codec.encodeLayerStateParams(params, state); assert.ok(params.get('l').length > 64, 'fixture must cross the old cap'); - assert.equal(params.get('l').length, 81); + assert.equal(params.get('l').length, 83); const restored = codec.decodeLayerStateParams(params); assert.deepEqual(restored?.enabledLayerIds, expectedLayerIds); assert.deepEqual(restored?.options, state.options); @@ -395,7 +386,7 @@ test('checker reads a complete future base ledger and rejects retired-token reus }, (cwd) => { const published = readPublishedLayerStateReservations('HEAD', cwd); - assert.equal(Object.keys(published).length, 36); + assert.equal(Object.keys(published).length, 37); assert.equal(published['retired-layer'], '00'); assert.throws( () => diff --git a/src/data/layerStateTokenReservations.json b/src/data/layerStateTokenReservations.json index 836112713..aab62411b 100644 --- a/src/data/layerStateTokenReservations.json +++ b/src/data/layerStateTokenReservations.json @@ -24,6 +24,7 @@ ["s2-ghostmaps", "5"], ["satellites", "s"], ["sea-marks", "6"], + ["shipwrecks", "9"], ["ski-pistes", "7"], ["street-level", "0"], ["telegeography-submarine-cables", "u"], diff --git a/src/data/shipwrecksProxy.test.mjs b/src/data/shipwrecksProxy.test.mjs new file mode 100644 index 000000000..45e6b6973 --- /dev/null +++ b/src/data/shipwrecksProxy.test.mjs @@ -0,0 +1,132 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { shipwrecksProxy } from '../../server/providers/shipwrecks.js'; + +const EMODNET = { + type: 'FeatureCollection', + features: [ + { + type: 'Feature', + id: 'heritageshipwrecks.1', + geometry: { type: 'Point', coordinates: [-0.92, 50.74] }, + properties: { name: 'HMS/m A1', sink_yr: '1911', country: 'UK' }, + }, + ], +}; + +function fakeFetch({ wikidataFails = false, emodnetFails = false } = {}) { + const calls = []; + const fetchImpl = async (url, options) => { + calls.push({ url: String(url), options }); + const href = String(url); + if (href.includes('query.wikidata.org')) { + if (wikidataFails) return new Response('', { status: 503 }); + return Response.json({ results: { bindings: [] } }); + } + if (emodnetFails) return new Response('', { status: 503 }); + if (href.includes('ows.emodnet-humanactivities.eu')) + return Response.json(EMODNET); + return new Response('', { status: 404 }); + }; + return { fetchImpl, calls }; +} + +function handlerOf(plugin) { + let handler; + plugin.configureServer({ + middlewares: { use: (_path, fn) => (handler = fn) }, + }); + return handler; +} + +function request(handler, { method = 'GET', url = '/' } = {}) { + return new Promise((resolve) => { + const res = { + destroyed: false, + writeHead(status, headers) { + this.status = status; + this.headers = headers; + }, + end(body) { + resolve({ + status: this.status, + headers: this.headers, + body: JSON.parse(body), + }); + }, + }; + handler( + { method, url, headers: {}, socket: { remoteAddress: '127.0.0.1' } }, + res, + ); + }); +} + +test('serves one cached snapshot from fixed upstreams', async () => { + const { fetchImpl, calls } = fakeFetch(); + const handler = handlerOf(shipwrecksProxy({ fetchImpl })); + const first = await request(handler); + assert.equal(first.status, 200); + assert.equal(first.body.records.length, 1); + assert.equal(first.body.records[0].name, 'HMS/m A1'); + assert.equal(first.body.records[0].year, 1911); + assert.deepEqual(first.body.sources, { emodnet: true, wikidata: true }); + for (const { url } of calls) + assert.match( + url, + /^https:\/\/(ows\.emodnet-humanactivities\.eu\/wfs\?|query\.wikidata\.org\/sparql\?)/, + ); + const count = calls.length; + await request(handler); + assert.equal(calls.length, count, 'second request is served from cache'); +}); + +test('one failing source still serves the other; both failing is a 502', async () => { + const partial = handlerOf( + shipwrecksProxy({ + fetchImpl: fakeFetch({ wikidataFails: true }).fetchImpl, + }), + ); + const ok = await request(partial); + assert.equal(ok.status, 200); + assert.deepEqual(ok.body.sources, { emodnet: true, wikidata: false }); + + const down = handlerOf( + shipwrecksProxy({ + fetchImpl: fakeFetch({ wikidataFails: true, emodnetFails: true }) + .fetchImpl, + }), + ); + assert.equal((await request(down)).status, 502); +}); + +test('a failed refresh serves the last snapshot as stale', async () => { + let clock = 0; + let fail = false; + const { fetchImpl: good } = fakeFetch(); + const { fetchImpl: bad } = fakeFetch({ + wikidataFails: true, + emodnetFails: true, + }); + const handler = handlerOf( + shipwrecksProxy({ + fetchImpl: (...args) => (fail ? bad : good)(...args), + now: () => clock, + }), + ); + await request(handler); + fail = true; + clock = 25 * 60 * 60 * 1000; + const stale = await request(handler); + assert.equal(stale.status, 200); + assert.equal(stale.body.stale, true); + assert.equal(stale.headers['X-Data-Stale'], 'true'); +}); + +test('rejects other methods and routes', async () => { + const handler = handlerOf( + shipwrecksProxy({ fetchImpl: fakeFetch().fetchImpl }), + ); + assert.equal((await request(handler, { method: 'POST' })).status, 405); + assert.equal((await request(handler, { url: '/x' })).status, 404); +}); diff --git a/src/i18n/locales/ar.json b/src/i18n/locales/ar.json index c9fca14ce..147d9e307 100644 --- a/src/i18n/locales/ar.json +++ b/src/i18n/locales/ar.json @@ -3404,5 +3404,40 @@ "FAA prohibited and restricted special-use airspace only, not the UAS Facility Map or UAS flight restrictions. Informational only — not a substitute for official UAS flight-planning tools (B4UFLY / LAANC).": "المجال الجوي الخاص المحظور والمقيّد لدى FAA فقط، ولا يشمل UAS Facility Map أو قيود طيران UAS. للعلم فقط — ولا يغني عن الأدوات الرسمية لتخطيط رحلات UAS (B4UFLY / LAANC).", "Prohibited": "محظور", "Restricted": "مقيّد", - "Prohibited & Restricted Airspace": "المجال الجوي المحظور والمقيّد" + "Prohibited & Restricted Airspace": "المجال الجوي المحظور والمقيّد", + "Shipwrecks": "حطام السفن", + "Before 1900": "قبل 1900", + "After 1945": "بعد 1945", + "Date unknown": "التاريخ غير معروف", + "Position: centre of the protected area": "الموقع: مركز المنطقة المحمية", + "Position approximate (within about {km} km)": "الموقع تقريبي (في حدود {km} كم تقريبًا)", + "Position surveyed (within about {m} m)": "الموقع مُسَح (في حدود {m} م تقريبًا)", + "Vessel: {value}": "السفينة: {value}", + "What happened: {value}": "ما حدث: {value}", + "Depth: {m} m ({quality})": "العمق: {m} م ({quality})", + "Depth: {m} m": "العمق: {m} م", + "Notes: {value}": "ملاحظات: {value}", + "Cargo or finds: {value}": "الحمولة أو المكتشفات: {value}", + "Protected wreck": "حطام محمي", + "Source: {value}": "المصدر: {value}", + "Click the card to open EMODnet ↗": "انقر على البطاقة لفتح EMODnet ↗", + "Click the card to open the source ↗": "انقر على البطاقة لفتح المصدر ↗", + "Wikidata unavailable; showing EMODnet only": "ويكي بيانات غير متاحة؛ يُعرض EMODnet فقط", + "EMODnet unavailable; showing Wikidata only": "EMODnet غير متاح؛ تُعرض ويكي بيانات فقط", + "Shipwrecks unavailable": "بيانات حطام السفن غير متاحة", + "EMODnet (European waters) · Wikidata (worldwide)": "EMODnet (المياه الأوروبية) · ويكي بيانات (العالم)", + "{count} wrecks": { + "zero": "لا حطام ({count})", + "one": "حطام واحد ({count})", + "two": "حطامان ({count})", + "few": "{count} حطامات", + "many": "{count} حطامًا", + "other": "{count} حطام" + }, + "1900–1945": "1900–1945", + "Shipwreck": "غرق سفينة", + "Fatalities: {count}": "الوفيات: {count}", + "Survivors: {count}": "الناجون: {count}", + "Click the card to open the article ↗": "انقر على البطاقة لفتح المقالة ↗", + "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "يأتي حطام السفن التراثي الأوروبي من EMODnet Human Activities، ويأتي الحطام البارز في العالم من ويكي بيانات. يبيّن اللون متى غرقت السفينة، ويكبر حجم العلامة مع عدد الوفيات. انقر على علامة لعرض بطاقتها." } diff --git a/src/i18n/locales/de.json b/src/i18n/locales/de.json index bb683ed9f..cbcf280e2 100644 --- a/src/i18n/locales/de.json +++ b/src/i18n/locales/de.json @@ -3104,5 +3104,36 @@ "The provider rejected the API key. Check it in Provider Settings.": "Der Anbieter hat den API-Schlüssel abgelehnt. Den Schlüssel in den Anbieter-Einstellungen prüfen.", "Too many chat requests. Try again in {seconds} s.": "Zu viele Chat-Anfragen. In {seconds} s erneut versuchen.", "The provider refused access for this key. Check the key's project, region or permissions.": "Der Anbieter hat den Zugriff für diesen Schlüssel verweigert. Projekt, Region oder Berechtigungen des Schlüssels prüfen.", - "The provider account is out of credit. Check its billing, or choose another AI Provider in Settings.": "Das Anbieterkonto hat kein Guthaben mehr. Die Abrechnung prüfen oder in den Einstellungen einen anderen KI-Anbieter wählen." + "The provider account is out of credit. Check its billing, or choose another AI Provider in Settings.": "Das Anbieterkonto hat kein Guthaben mehr. Die Abrechnung prüfen oder in den Einstellungen einen anderen KI-Anbieter wählen.", + "Shipwrecks": "Schiffswracks", + "Before 1900": "Vor 1900", + "After 1945": "Nach 1945", + "Date unknown": "Datum unbekannt", + "Position: centre of the protected area": "Position: Mitte des Schutzgebiets", + "Position approximate (within about {km} km)": "Position ungefähr (auf etwa {km} km genau)", + "Position surveyed (within about {m} m)": "Position vermessen (auf etwa {m} m genau)", + "Vessel: {value}": "Schiff: {value}", + "What happened: {value}": "Was geschah: {value}", + "Depth: {m} m ({quality})": "Tiefe: {m} m ({quality})", + "Depth: {m} m": "Tiefe: {m} m", + "Notes: {value}": "Hinweise: {value}", + "Cargo or finds: {value}": "Ladung oder Funde: {value}", + "Protected wreck": "Geschütztes Wrack", + "Source: {value}": "Quelle: {value}", + "Click the card to open EMODnet ↗": "Karte anklicken, um EMODnet zu öffnen ↗", + "Click the card to open the source ↗": "Karte anklicken, um die Quelle zu öffnen ↗", + "Wikidata unavailable; showing EMODnet only": "Wikidata nicht verfügbar; nur EMODnet wird angezeigt", + "EMODnet unavailable; showing Wikidata only": "EMODnet nicht verfügbar; nur Wikidata wird angezeigt", + "Shipwrecks unavailable": "Schiffswracks nicht verfügbar", + "EMODnet (European waters) · Wikidata (worldwide)": "EMODnet (europäische Gewässer) · Wikidata (weltweit)", + "{count} wrecks": { + "one": "{count} Wrack", + "other": "{count} Wracks" + }, + "1900–1945": "1900–1945", + "Shipwreck": "Schiffbruch", + "Fatalities: {count}": "Todesopfer: {count}", + "Survivors: {count}": "Überlebende: {count}", + "Click the card to open the article ↗": "Karte anklicken, um den Artikel zu öffnen ↗", + "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "Europäische Kulturerbe-Wracks stammen von EMODnet Human Activities, bekannte Wracks weltweit von Wikidata. Die Farbe zeigt, wann das Schiff sank; die Markierung wächst mit der Zahl der Todesopfer. Klicke auf eine Markierung für ihre Karte." } diff --git a/src/i18n/locales/es.json b/src/i18n/locales/es.json index 10dcbef8f..6df928b0a 100644 --- a/src/i18n/locales/es.json +++ b/src/i18n/locales/es.json @@ -3179,5 +3179,37 @@ "The provider rejected the API key. Check it in Provider Settings.": "El proveedor rechazó la clave de API. Revísala en Ajustes de proveedores.", "Too many chat requests. Try again in {seconds} s.": "Demasiadas solicitudes de chat. Vuelve a intentarlo en {seconds} s.", "The provider refused access for this key. Check the key's project, region or permissions.": "El proveedor denegó el acceso a esta clave. Revisa el proyecto, la región o los permisos de la clave.", - "The provider account is out of credit. Check its billing, or choose another AI Provider in Settings.": "La cuenta del proveedor no tiene crédito. Revisa la facturación o elige otro proveedor de IA en Ajustes." + "The provider account is out of credit. Check its billing, or choose another AI Provider in Settings.": "La cuenta del proveedor no tiene crédito. Revisa la facturación o elige otro proveedor de IA en Ajustes.", + "Shipwrecks": "Naufragios", + "Before 1900": "Antes de 1900", + "After 1945": "Después de 1945", + "Date unknown": "Fecha desconocida", + "Position: centre of the protected area": "Posición: centro de la zona protegida", + "Position approximate (within about {km} km)": "Posición aproximada (margen de unos {km} km)", + "Position surveyed (within about {m} m)": "Posición levantada (margen de unos {m} m)", + "Vessel: {value}": "Embarcación: {value}", + "What happened: {value}": "Qué ocurrió: {value}", + "Depth: {m} m ({quality})": "Profundidad: {m} m ({quality})", + "Depth: {m} m": "Profundidad: {m} m", + "Notes: {value}": "Notas: {value}", + "Cargo or finds: {value}": "Carga o hallazgos: {value}", + "Protected wreck": "Pecio protegido", + "Source: {value}": "Fuente: {value}", + "Click the card to open EMODnet ↗": "Haz clic en la ficha para abrir EMODnet ↗", + "Click the card to open the source ↗": "Haz clic en la ficha para abrir la fuente ↗", + "Wikidata unavailable; showing EMODnet only": "Wikidata no disponible; solo se muestra EMODnet", + "EMODnet unavailable; showing Wikidata only": "EMODnet no disponible; solo se muestra Wikidata", + "Shipwrecks unavailable": "Naufragios no disponibles", + "EMODnet (European waters) · Wikidata (worldwide)": "EMODnet (aguas europeas) · Wikidata (todo el mundo)", + "{count} wrecks": { + "one": "{count} naufragio", + "many": "{count} de naufragios", + "other": "{count} naufragios" + }, + "1900–1945": "1900–1945", + "Shipwreck": "Naufragio", + "Fatalities: {count}": "Fallecidos: {count}", + "Survivors: {count}": "Supervivientes: {count}", + "Click the card to open the article ↗": "Haz clic en la ficha para abrir el artículo ↗", + "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "Los pecios históricos europeos proceden de EMODnet Human Activities; los naufragios notables de todo el mundo, de Wikidata. El color indica cuándo se hundió el barco; el marcador crece con el número de muertos. Haz clic en un marcador para ver su ficha." } diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json index 108e56f36..b9b53c48d 100644 --- a/src/i18n/locales/fr.json +++ b/src/i18n/locales/fr.json @@ -3179,5 +3179,37 @@ "The provider rejected the API key. Check it in Provider Settings.": "Le fournisseur a refusé la clé API. Vérifiez-la dans les paramètres des fournisseurs.", "Too many chat requests. Try again in {seconds} s.": "Trop de requêtes de discussion. Réessayez dans {seconds} s.", "The provider refused access for this key. Check the key's project, region or permissions.": "Le fournisseur a refusé l'accès pour cette clé. Vérifiez le projet, la région ou les autorisations de la clé.", - "The provider account is out of credit. Check its billing, or choose another AI Provider in Settings.": "Le compte du fournisseur n'a plus de crédit. Vérifiez la facturation ou choisissez un autre fournisseur d'IA dans les paramètres." + "The provider account is out of credit. Check its billing, or choose another AI Provider in Settings.": "Le compte du fournisseur n'a plus de crédit. Vérifiez la facturation ou choisissez un autre fournisseur d'IA dans les paramètres.", + "Shipwrecks": "Épaves", + "Before 1900": "Avant 1900", + "After 1945": "Après 1945", + "Date unknown": "Date inconnue", + "Position: centre of the protected area": "Position : centre de la zone protégée", + "Position approximate (within about {km} km)": "Position approximative (à environ {km} km près)", + "Position surveyed (within about {m} m)": "Position relevée (à environ {m} m près)", + "Vessel: {value}": "Navire : {value}", + "What happened: {value}": "Ce qui s'est passé : {value}", + "Depth: {m} m ({quality})": "Profondeur : {m} m ({quality})", + "Depth: {m} m": "Profondeur : {m} m", + "Notes: {value}": "Notes : {value}", + "Cargo or finds: {value}": "Cargaison ou découvertes : {value}", + "Protected wreck": "Épave protégée", + "Source: {value}": "Source : {value}", + "Click the card to open EMODnet ↗": "Cliquez sur la fiche pour ouvrir EMODnet ↗", + "Click the card to open the source ↗": "Cliquez sur la fiche pour ouvrir la source ↗", + "Wikidata unavailable; showing EMODnet only": "Wikidata indisponible ; seul EMODnet est affiché", + "EMODnet unavailable; showing Wikidata only": "EMODnet indisponible ; seul Wikidata est affiché", + "Shipwrecks unavailable": "Épaves indisponibles", + "EMODnet (European waters) · Wikidata (worldwide)": "EMODnet (eaux européennes) · Wikidata (monde)", + "{count} wrecks": { + "one": "{count} épave", + "many": "{count} d'épaves", + "other": "{count} épaves" + }, + "1900–1945": "1900–1945", + "Shipwreck": "Naufrage", + "Fatalities: {count}": "Morts : {count}", + "Survivors: {count}": "Survivants : {count}", + "Click the card to open the article ↗": "Cliquez sur la fiche pour ouvrir l'article ↗", + "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "Les épaves patrimoniales européennes viennent d'EMODnet Human Activities ; les épaves notables du monde entier viennent de Wikidata. La couleur indique quand le navire a coulé ; le repère grossit avec le nombre de morts. Cliquez sur un repère pour voir sa fiche." } diff --git a/src/i18n/locales/it.json b/src/i18n/locales/it.json index 6768f93c7..9310da82c 100644 --- a/src/i18n/locales/it.json +++ b/src/i18n/locales/it.json @@ -3179,5 +3179,37 @@ "The provider rejected the API key. Check it in Provider Settings.": "Il provider ha rifiutato la chiave API. Controllala in Impostazioni provider.", "Too many chat requests. Try again in {seconds} s.": "Troppe richieste di chat. Riprova tra {seconds} s.", "The provider refused access for this key. Check the key's project, region or permissions.": "Il provider ha negato l'accesso per questa chiave. Controlla progetto, regione o autorizzazioni della chiave.", - "The provider account is out of credit. Check its billing, or choose another AI Provider in Settings.": "L'account del provider ha esaurito il credito. Controlla la fatturazione o scegli un altro provider IA in Impostazioni." + "The provider account is out of credit. Check its billing, or choose another AI Provider in Settings.": "L'account del provider ha esaurito il credito. Controlla la fatturazione o scegli un altro provider IA in Impostazioni.", + "Shipwrecks": "Relitti", + "Before 1900": "Prima del 1900", + "After 1945": "Dopo il 1945", + "Date unknown": "Data sconosciuta", + "Position: centre of the protected area": "Posizione: centro dell'area protetta", + "Position approximate (within about {km} km)": "Posizione approssimativa (entro circa {km} km)", + "Position surveyed (within about {m} m)": "Posizione rilevata (entro circa {m} m)", + "Vessel: {value}": "Imbarcazione: {value}", + "What happened: {value}": "Cosa è successo: {value}", + "Depth: {m} m ({quality})": "Profondità: {m} m ({quality})", + "Depth: {m} m": "Profondità: {m} m", + "Notes: {value}": "Note: {value}", + "Cargo or finds: {value}": "Carico o reperti: {value}", + "Protected wreck": "Relitto protetto", + "Source: {value}": "Fonte: {value}", + "Click the card to open EMODnet ↗": "Fai clic sulla scheda per aprire EMODnet ↗", + "Click the card to open the source ↗": "Fai clic sulla scheda per aprire la fonte ↗", + "Wikidata unavailable; showing EMODnet only": "Wikidata non disponibile; solo EMODnet", + "EMODnet unavailable; showing Wikidata only": "EMODnet non disponibile; solo Wikidata", + "Shipwrecks unavailable": "Relitti non disponibili", + "EMODnet (European waters) · Wikidata (worldwide)": "EMODnet (acque europee) · Wikidata (mondo)", + "{count} wrecks": { + "one": "{count} relitto", + "many": "{count} di relitti", + "other": "{count} relitti" + }, + "1900–1945": "1900–1945", + "Shipwreck": "Naufragio", + "Fatalities: {count}": "Vittime: {count}", + "Survivors: {count}": "Sopravvissuti: {count}", + "Click the card to open the article ↗": "Fai clic sulla scheda per aprire l'articolo ↗", + "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "I relitti storici europei provengono da EMODnet Human Activities; i relitti noti di tutto il mondo da Wikidata. Il colore indica quando la nave è affondata; l'indicatore cresce con il numero di vittime. Fai clic su un indicatore per la sua scheda." } diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.json index b4566b4cb..4a1edfb44 100644 --- a/src/i18n/locales/ja.json +++ b/src/i18n/locales/ja.json @@ -3029,5 +3029,35 @@ "The provider rejected the API key. Check it in Provider Settings.": "プロバイダーがAPIキーを拒否しました。プロバイダー設定で確認してください。", "Too many chat requests. Try again in {seconds} s.": "チャットのリクエストが多すぎます。{seconds}秒後にもう一度お試しください。", "The provider refused access for this key. Check the key's project, region or permissions.": "プロバイダーがこのキーでのアクセスを拒否しました。キーのプロジェクト、リージョン、権限を確認してください。", - "The provider account is out of credit. Check its billing, or choose another AI Provider in Settings.": "プロバイダーアカウントのクレジットが不足しています。課金状況を確認するか、設定で別のAIプロバイダーを選んでください。" + "The provider account is out of credit. Check its billing, or choose another AI Provider in Settings.": "プロバイダーアカウントのクレジットが不足しています。課金状況を確認するか、設定で別のAIプロバイダーを選んでください。", + "Shipwrecks": "難破船", + "Before 1900": "1900年以前", + "After 1945": "1945年以降", + "Date unknown": "日付不明", + "Position: centre of the protected area": "位置: 保護区域の中心", + "Position approximate (within about {km} km)": "おおよその位置(誤差約{km} km)", + "Position surveyed (within about {m} m)": "測量された位置(誤差約{m} m)", + "Vessel: {value}": "船種: {value}", + "What happened: {value}": "経緯: {value}", + "Depth: {m} m ({quality})": "水深: {m} m({quality})", + "Depth: {m} m": "水深: {m} m", + "Notes: {value}": "備考: {value}", + "Cargo or finds: {value}": "積荷・遺物: {value}", + "Protected wreck": "保護対象の難破船", + "Source: {value}": "出典: {value}", + "Click the card to open EMODnet ↗": "カードをクリックしてEMODnetを開く ↗", + "Click the card to open the source ↗": "カードをクリックして出典を開く ↗", + "Wikidata unavailable; showing EMODnet only": "Wikidataを利用できません。EMODnetのみ表示しています", + "EMODnet unavailable; showing Wikidata only": "EMODnetを利用できません。Wikidataのみ表示しています", + "Shipwrecks unavailable": "難破船データを利用できません", + "EMODnet (European waters) · Wikidata (worldwide)": "EMODnet(欧州海域)· Wikidata(世界)", + "{count} wrecks": { + "other": "難破船 {count}件" + }, + "1900–1945": "1900–1945", + "Shipwreck": "難破", + "Fatalities: {count}": "死者: {count}", + "Survivors: {count}": "生存者: {count}", + "Click the card to open the article ↗": "カードをクリックして記事を開く ↗", + "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "欧州の歴史的な難破船はEMODnet Human Activities、世界の著名な難破船はWikidataによります。色は沈没した時期を示し、マーカーは死者数に応じて大きくなります。マーカーをクリックするとカードが開きます。" } diff --git a/src/i18n/locales/pt.json b/src/i18n/locales/pt.json index 3f37cde2e..1c9b46418 100644 --- a/src/i18n/locales/pt.json +++ b/src/i18n/locales/pt.json @@ -3179,5 +3179,37 @@ "The provider rejected the API key. Check it in Provider Settings.": "O provedor recusou a chave de API. Verifique-a em \"Configurações de provedores\".", "Too many chat requests. Try again in {seconds} s.": "Chat: limite de requisições atingido. Tente novamente em {seconds} s.", "The provider refused access for this key. Check the key's project, region or permissions.": "O provedor negou o acesso para esta chave. Verifique o projeto, a região ou as permissões da chave.", - "The provider account is out of credit. Check its billing, or choose another AI Provider in Settings.": "A conta do provedor está sem crédito. Verifique o faturamento ou escolha outro provedor de IA em \"Configurações\"." + "The provider account is out of credit. Check its billing, or choose another AI Provider in Settings.": "A conta do provedor está sem crédito. Verifique o faturamento ou escolha outro provedor de IA em \"Configurações\".", + "Shipwrecks": "Naufrágios", + "Before 1900": "Antes de 1900", + "After 1945": "Depois de 1945", + "Date unknown": "Data desconhecida", + "Position: centre of the protected area": "Posição: centro da área protegida", + "Position approximate (within about {km} km)": "Posição aproximada (margem de cerca de {km} km)", + "Position surveyed (within about {m} m)": "Posição levantada (margem de cerca de {m} m)", + "Vessel: {value}": "Embarcação: {value}", + "What happened: {value}": "O que aconteceu: {value}", + "Depth: {m} m ({quality})": "Profundidade: {m} m ({quality})", + "Depth: {m} m": "Profundidade: {m} m", + "Notes: {value}": "Notas: {value}", + "Cargo or finds: {value}": "Carga ou achados: {value}", + "Protected wreck": "Naufrágio protegido", + "Source: {value}": "Fonte: {value}", + "Click the card to open EMODnet ↗": "Clique na ficha para abrir o EMODnet ↗", + "Click the card to open the source ↗": "Clique na ficha para abrir a fonte ↗", + "Wikidata unavailable; showing EMODnet only": "Wikidata indisponível; mostrando só o EMODnet", + "EMODnet unavailable; showing Wikidata only": "EMODnet indisponível; mostrando só o Wikidata", + "Shipwrecks unavailable": "Naufrágios indisponíveis", + "EMODnet (European waters) · Wikidata (worldwide)": "EMODnet (águas europeias) · Wikidata (mundo)", + "{count} wrecks": { + "one": "{count} naufrágio", + "many": "{count} de naufrágios", + "other": "{count} naufrágios" + }, + "1900–1945": "1900–1945", + "Shipwreck": "Naufrágio", + "Fatalities: {count}": "Mortos: {count}", + "Survivors: {count}": "Sobreviventes: {count}", + "Click the card to open the article ↗": "Clique na ficha para abrir o artigo ↗", + "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "Os naufrágios históricos europeus vêm do EMODnet Human Activities; os naufrágios notáveis do mundo vêm do Wikidata. A cor mostra quando o navio afundou; o marcador cresce com o número de mortos. Clique num marcador para ver a ficha." } diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json index e279508ef..1d4dbce42 100644 --- a/src/i18n/locales/ru.json +++ b/src/i18n/locales/ru.json @@ -3254,5 +3254,38 @@ "The provider rejected the API key. Check it in Provider Settings.": "Провайдер отклонил ключ API. Проверьте его в «Настройках провайдеров».", "Too many chat requests. Try again in {seconds} s.": "Слишком много запросов в чате. Повторите попытку через {seconds} с.", "The provider refused access for this key. Check the key's project, region or permissions.": "Провайдер отказал этому ключу в доступе. Проверьте проект, регион или разрешения ключа.", - "The provider account is out of credit. Check its billing, or choose another AI Provider in Settings.": "На вашем счёте у провайдера закончились средства. Проверьте оплату или выберите другого провайдера ИИ в настройках." + "The provider account is out of credit. Check its billing, or choose another AI Provider in Settings.": "На вашем счёте у провайдера закончились средства. Проверьте оплату или выберите другого провайдера ИИ в настройках.", + "Shipwrecks": "Кораблекрушения", + "Before 1900": "До 1900", + "After 1945": "После 1945", + "Date unknown": "Дата неизвестна", + "Position: centre of the protected area": "Положение: центр охраняемой зоны", + "Position approximate (within about {km} km)": "Положение приблизительное (точность около {km} км)", + "Position surveyed (within about {m} m)": "Положение измерено (точность около {m} м)", + "Vessel: {value}": "Судно: {value}", + "What happened: {value}": "Что произошло: {value}", + "Depth: {m} m ({quality})": "Глубина: {m} м ({quality})", + "Depth: {m} m": "Глубина: {m} м", + "Notes: {value}": "Примечания: {value}", + "Cargo or finds: {value}": "Груз или находки: {value}", + "Protected wreck": "Охраняемый объект", + "Source: {value}": "Источник: {value}", + "Click the card to open EMODnet ↗": "Нажмите на карточку, чтобы открыть EMODnet ↗", + "Click the card to open the source ↗": "Нажмите на карточку, чтобы открыть источник ↗", + "Wikidata unavailable; showing EMODnet only": "Wikidata недоступна; показан только EMODnet", + "EMODnet unavailable; showing Wikidata only": "EMODnet недоступен; показана только Wikidata", + "Shipwrecks unavailable": "Данные о кораблекрушениях недоступны", + "EMODnet (European waters) · Wikidata (worldwide)": "EMODnet (воды Европы) · Wikidata (весь мир)", + "{count} wrecks": { + "one": "{count} затонувшее судно", + "few": "{count} затонувших судна", + "many": "{count} затонувших судов", + "other": "{count} затонувшего судна" + }, + "1900–1945": "1900–1945", + "Shipwreck": "Кораблекрушение", + "Fatalities: {count}": "Погибших: {count}", + "Survivors: {count}": "Выживших: {count}", + "Click the card to open the article ↗": "Нажмите на карточку, чтобы открыть статью ↗", + "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "Исторические затонувшие суда Европы — из EMODnet Human Activities, известные кораблекрушения по всему миру — из Wikidata. Цвет показывает, когда судно затонуло; маркер растёт с числом погибших. Нажмите на маркер, чтобы открыть карточку." } diff --git a/src/i18n/locales/uk.json b/src/i18n/locales/uk.json index 8c3b634b9..d8b9296f0 100644 --- a/src/i18n/locales/uk.json +++ b/src/i18n/locales/uk.json @@ -3254,5 +3254,38 @@ "The provider rejected the API key. Check it in Provider Settings.": "Постачальник відхилив ключ API. Перевірте його в «Налаштуваннях постачальників».", "Too many chat requests. Try again in {seconds} s.": "Забагато запитів до чату. Спробуйте ще раз через {seconds} с.", "The provider refused access for this key. Check the key's project, region or permissions.": "Постачальник відмовив цьому ключу в доступі. Перевірте проєкт, регіон або дозволи ключа.", - "The provider account is out of credit. Check its billing, or choose another AI Provider in Settings.": "На вашому рахунку в постачальника закінчилися кошти. Перевірте оплату або виберіть іншого постачальника ШІ в налаштуваннях." + "The provider account is out of credit. Check its billing, or choose another AI Provider in Settings.": "На вашому рахунку в постачальника закінчилися кошти. Перевірте оплату або виберіть іншого постачальника ШІ в налаштуваннях.", + "Shipwrecks": "Корабельні аварії", + "Before 1900": "До 1900", + "After 1945": "Після 1945", + "Date unknown": "Дата невідома", + "Position: centre of the protected area": "Положення: центр охоронної зони", + "Position approximate (within about {km} km)": "Положення приблизне (точність близько {km} км)", + "Position surveyed (within about {m} m)": "Положення виміряно (точність близько {m} м)", + "Vessel: {value}": "Судно: {value}", + "What happened: {value}": "Що сталося: {value}", + "Depth: {m} m ({quality})": "Глибина: {m} м ({quality})", + "Depth: {m} m": "Глибина: {m} м", + "Notes: {value}": "Примітки: {value}", + "Cargo or finds: {value}": "Вантаж або знахідки: {value}", + "Protected wreck": "Охоронюваний об'єкт", + "Source: {value}": "Джерело: {value}", + "Click the card to open EMODnet ↗": "Натисніть картку, щоб відкрити EMODnet ↗", + "Click the card to open the source ↗": "Натисніть картку, щоб відкрити джерело ↗", + "Wikidata unavailable; showing EMODnet only": "Wikidata недоступна; показано лише EMODnet", + "EMODnet unavailable; showing Wikidata only": "EMODnet недоступний; показано лише Wikidata", + "Shipwrecks unavailable": "Дані про корабельні аварії недоступні", + "EMODnet (European waters) · Wikidata (worldwide)": "EMODnet (води Європи) · Wikidata (увесь світ)", + "{count} wrecks": { + "one": "{count} затонуле судно", + "few": "{count} затонулі судна", + "many": "{count} затонулих суден", + "other": "{count} затонулого судна" + }, + "1900–1945": "1900–1945", + "Shipwreck": "Корабельна аварія", + "Fatalities: {count}": "Загиблих: {count}", + "Survivors: {count}": "Тих, хто вижив: {count}", + "Click the card to open the article ↗": "Натисніть картку, щоб відкрити статтю ↗", + "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "Історичні затонулі судна Європи — з EMODnet Human Activities, відомі корабельні аварії світу — з Wikidata. Колір показує, коли судно затонуло; маркер збільшується з кількістю загиблих. Натисніть маркер, щоб відкрити картку." } diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json index 6125315f2..90684d7d5 100644 --- a/src/i18n/locales/zh-CN.json +++ b/src/i18n/locales/zh-CN.json @@ -3029,5 +3029,35 @@ "The provider rejected the API key. Check it in Provider Settings.": "服务商拒绝了 API 密钥。请在服务商设置中检查。", "Too many chat requests. Try again in {seconds} s.": "聊天请求过多。请在 {seconds} 秒后重试。", "The provider refused access for this key. Check the key's project, region or permissions.": "服务商拒绝了此密钥的访问请求。请检查该密钥所属的项目、区域或权限。", - "The provider account is out of credit. Check its billing, or choose another AI Provider in Settings.": "服务商账户余额不足。请检查账户的计费信息,或在设置中选择其他 AI 服务商。" + "The provider account is out of credit. Check its billing, or choose another AI Provider in Settings.": "服务商账户余额不足。请检查账户的计费信息,或在设置中选择其他 AI 服务商。", + "Shipwrecks": "沉船", + "Before 1900": "1900年以前", + "After 1945": "1945年以后", + "Date unknown": "日期不详", + "Position: centre of the protected area": "位置:保护区中心", + "Position approximate (within about {km} km)": "大致位置(误差约 {km} 公里)", + "Position surveyed (within about {m} m)": "实测位置(误差约 {m} 米)", + "Vessel: {value}": "船只:{value}", + "What happened: {value}": "经过:{value}", + "Depth: {m} m ({quality})": "深度:{m} 米({quality})", + "Depth: {m} m": "深度:{m} 米", + "Notes: {value}": "备注:{value}", + "Cargo or finds: {value}": "货物或出水文物:{value}", + "Protected wreck": "受保护沉船", + "Source: {value}": "来源:{value}", + "Click the card to open EMODnet ↗": "点击卡片打开 EMODnet ↗", + "Click the card to open the source ↗": "点击卡片打开来源 ↗", + "Wikidata unavailable; showing EMODnet only": "Wikidata 不可用;仅显示 EMODnet", + "EMODnet unavailable; showing Wikidata only": "EMODnet 不可用;仅显示 Wikidata", + "Shipwrecks unavailable": "沉船数据不可用", + "EMODnet (European waters) · Wikidata (worldwide)": "EMODnet(欧洲海域)· Wikidata(全球)", + "{count} wrecks": { + "other": "{count} 艘沉船" + }, + "1900–1945": "1900–1945", + "Shipwreck": "沉船", + "Fatalities: {count}": "遇难:{count}", + "Survivors: {count}": "幸存者:{count}", + "Click the card to open the article ↗": "点击卡片打开文章 ↗", + "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "欧洲历史沉船来自 EMODnet Human Activities;全球知名沉船来自 Wikidata。颜色表示船只沉没的时期,标记大小随遇难人数增加。点击标记查看卡片。" } diff --git a/src/i18n/locales/zh-Hant.json b/src/i18n/locales/zh-Hant.json index 66eb37b96..b1cbd78b3 100644 --- a/src/i18n/locales/zh-Hant.json +++ b/src/i18n/locales/zh-Hant.json @@ -3029,5 +3029,35 @@ "The provider rejected the API key. Check it in Provider Settings.": "服務商拒絕了 API 密鑰。請在服務商設置中檢查。", "Too many chat requests. Try again in {seconds} s.": "聊天請求過多。請在 {seconds} 秒後重試。", "The provider refused access for this key. Check the key's project, region or permissions.": "服務商拒絕了此密鑰的訪問請求。請檢查該密鑰所屬的項目、區域或權限。", - "The provider account is out of credit. Check its billing, or choose another AI Provider in Settings.": "服務商賬戶餘額不足。請檢查賬戶的計費信息,或在設置中選擇其他 AI 服務商。" + "The provider account is out of credit. Check its billing, or choose another AI Provider in Settings.": "服務商賬戶餘額不足。請檢查賬戶的計費信息,或在設置中選擇其他 AI 服務商。", + "Shipwrecks": "沉船", + "Before 1900": "1900年以前", + "After 1945": "1945年以後", + "Date unknown": "日期不詳", + "Position: centre of the protected area": "位置:保護區中心", + "Position approximate (within about {km} km)": "大致位置(誤差約 {km} 公里)", + "Position surveyed (within about {m} m)": "實測位置(誤差約 {m} 公尺)", + "Vessel: {value}": "船隻:{value}", + "What happened: {value}": "經過:{value}", + "Depth: {m} m ({quality})": "深度:{m} 公尺({quality})", + "Depth: {m} m": "深度:{m} 公尺", + "Notes: {value}": "備註:{value}", + "Cargo or finds: {value}": "貨物或出水文物:{value}", + "Protected wreck": "受保護沉船", + "Source: {value}": "來源:{value}", + "Click the card to open EMODnet ↗": "點擊卡片開啟 EMODnet ↗", + "Click the card to open the source ↗": "點擊卡片開啟來源 ↗", + "Wikidata unavailable; showing EMODnet only": "Wikidata 無法使用;僅顯示 EMODnet", + "EMODnet unavailable; showing Wikidata only": "EMODnet 無法使用;僅顯示 Wikidata", + "Shipwrecks unavailable": "沉船資料無法使用", + "EMODnet (European waters) · Wikidata (worldwide)": "EMODnet(歐洲海域)· Wikidata(全球)", + "{count} wrecks": { + "other": "{count} 艘沉船" + }, + "1900–1945": "1900–1945", + "Shipwreck": "沉船", + "Fatalities: {count}": "罹難:{count}", + "Survivors: {count}": "倖存者:{count}", + "Click the card to open the article ↗": "點擊卡片開啟文章 ↗", + "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "歐洲歷史沉船來自 EMODnet Human Activities;全球知名沉船來自 Wikidata。顏色表示船隻沉沒的時期,標記大小隨罹難人數增加。點擊標記查看卡片。" } diff --git a/src/i18n/same-as-english.json b/src/i18n/same-as-english.json index 7edaad647..3fd8eea8f 100644 --- a/src/i18n/same-as-english.json +++ b/src/i18n/same-as-english.json @@ -1,6 +1,7 @@ { "ar": [ "1090 MHz", + "1900–1945", "978 MHz UAT", "AIS: --", "AIS: {name}", @@ -35,6 +36,7 @@ ], "de": [ "1090 MHz", + "1900–1945", "978 MHz UAT", "AIS: --", "AIS: {name}", @@ -206,6 +208,7 @@ ], "es": [ "1090 MHz", + "1900–1945", "978 MHz UAT", "AIS: --", "AIS: {name}", @@ -338,6 +341,7 @@ ], "fr": [ "1090 MHz", + "1900–1945", "978 MHz UAT", "ALTITUDE", "ALTITUDE · FT", @@ -523,6 +527,7 @@ ], "it": [ "1090 MHz", + "1900–1945", "978 MHz UAT", "AFRICA", "AIS: --", @@ -698,6 +703,7 @@ ], "ja": [ "1090 MHz", + "1900–1945", "978 MHz UAT", "AIS: --", "AIS: {name}", @@ -748,6 +754,7 @@ ], "pt": [ "1090 MHz", + "1900–1945", "978 MHz UAT", "AIS: --", "AIS: {name}", @@ -880,6 +887,7 @@ "≥ {value} MW" ], "ru": [ + "1900–1945", "AIS: --", "AIS: {name}", "CCTV", @@ -898,6 +906,7 @@ "WHOT/BHOT" ], "uk": [ + "1900–1945", "AIS: --", "AIS: {name}", "CCTV", @@ -912,6 +921,7 @@ ], "zh-CN": [ "1090 MHz", + "1900–1945", "978 MHz UAT", "AIS: --", "AIS: {name}", @@ -970,6 +980,7 @@ ], "zh-Hant": [ "1090 MHz", + "1900–1945", "978 MHz UAT", "AIS: --", "AIS: {name}", diff --git a/src/layers/shipwrecks/cards.js b/src/layers/shipwrecks/cards.js new file mode 100644 index 000000000..251530b96 --- /dev/null +++ b/src/layers/shipwrecks/cards.js @@ -0,0 +1,123 @@ +import { formatDate, formatNumber, msg, t } from '../../i18n/index.js'; +import { EMODNET_PAGE_URL } from './records.js'; + +export const ERA_LABELS = Object.freeze({ + 'before-1900': msg('Before 1900'), + '1900-1945': msg('1900–1945'), + 'after-1945': msg('After 1945'), + undated: msg('Date unknown'), +}); + +export const ERA_COLORS = Object.freeze({ + 'before-1900': '#c79a5b', + '1900-1945': '#ff6b5e', + 'after-1945': '#4fc3f7', + undated: '#9aa7b4', +}); + +function formatDay(date) { + const match = /^(-?\d{4})-(\d{2})-(\d{2})$/.exec(date || ''); + if (!match) return ''; + return formatDate( + Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3])), + { day: 'numeric', month: 'short', year: 'numeric', timeZone: 'UTC' }, + ); +} + +function meters(value) { + return formatNumber(value, { + maximumFractionDigits: value < 10 ? 1 : 0, + }); +} + +/** How well the position is known, as one card line (or null). */ +export function positionLine(record) { + if (record.positionNote) return t('Position: centre of the protected area'); + const accuracy = record.positionAccuracy; + if (!Number.isFinite(accuracy)) return null; + // 1852 m is EMODnet's "within a nautical mile" for old, reported positions. + if (accuracy >= 1000) + return t('Position approximate (within about {km} km)', { + km: formatNumber(accuracy / 1000, { maximumFractionDigits: 1 }), + }); + return t('Position surveyed (within about {m} m)', { m: meters(accuracy) }); +} + +/** + * The link a click on the card opens: the Wikipedia (or Wikidata) page, the + * wreck's own page when EMODnet lists one, else EMODnet's portal. + * @param {object} record + * @returns {string} + */ +export function cardLink(record) { + return record?.url || EMODNET_PAGE_URL; +} + +/** + * Title and detail lines for one wreck card, laid out like the air-accident + * card: deaths first, then when and where, then the ship facts. Only facts + * about the ship: the records carry no names of people, and victims appear as + * a count only. + * @param {object} record A normalized shipwreck record. + * @returns {{title: string, details: string[], link: string}} + */ +export function describeShipwreck(record) { + const titleParts = [t('Shipwreck')]; + if (record.name) titleParts.push(record.name); + const details = []; + // Deaths first, right under the title: the fact readers look for. + const toll = []; + if (Number.isFinite(record.casualties)) + toll.push( + t('Fatalities: {count}', { count: formatNumber(record.casualties) }), + ); + if (record.survivors) + toll.push( + t('Survivors: {count}', { count: formatNumber(record.survivors) }), + ); + if (toll.length) details.push(toll.join(' · ')); + const when = + formatDay(record.date) || + (Number.isInteger(record.year) ? String(record.year) : '') || + record.dating || + ''; + const where = [when, record.country].filter(Boolean); + if (where.length) details.push(where.join(' · ')); + if (record.vesselType) + details.push(t('Vessel: {value}', { value: record.vesselType })); + if (record.cause) + details.push(t('What happened: {value}', { value: record.cause })); + if (Number.isFinite(record.depth)) + details.push( + record.depthQuality + ? t('Depth: {m} m ({quality})', { + m: meters(record.depth), + quality: record.depthQuality, + }) + : t('Depth: {m} m', { m: meters(record.depth) }), + ); + const position = positionLine(record); + if (position) details.push(position); + if (record.notes) details.push(t('Notes: {value}', { value: record.notes })); + if (record.cargo) + details.push(t('Cargo or finds: {value}', { value: record.cargo })); + if (record.protected) details.push(t('Protected wreck')); + const sources = + record.source === 'wikidata' + ? record.alsoIn === 'emodnet' + ? 'Wikidata · EMODnet' + : 'Wikidata' + : record.originator + ? `EMODnet (${record.originator})` + : 'EMODnet'; + details.push(t('Source: {value}', { value: sources })); + const link = cardLink(record); + details.push( + link === EMODNET_PAGE_URL + ? t('Click the card to open EMODnet ↗') + : link.includes('.wikipedia.org/') + ? t('Click the card to open the article ↗') + : t('Click the card to open the source ↗'), + ); + return { title: titleParts.join(' · '), details, link }; +} diff --git a/src/layers/shipwrecks/cards.test.mjs b/src/layers/shipwrecks/cards.test.mjs new file mode 100644 index 000000000..6b7c84c62 --- /dev/null +++ b/src/layers/shipwrecks/cards.test.mjs @@ -0,0 +1,63 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { describeShipwreck, positionLine } from './cards.js'; +import { EMODNET_PAGE_URL } from './records.js'; + +test('a Wikidata card shows the ship facts and links its article', () => { + const card = describeShipwreck({ + source: 'wikidata', + alsoIn: 'emodnet', + name: 'HMS Havant', + vesselType: 'destroyer', + date: '1940-06-01', + year: 1940, + cause: 'Was sunk on 06/01/1940 by the German air force', + casualties: 8, + survivors: 120, + depth: 14.72, + depthQuality: 'Least depth known', + positionAccuracy: 3.1, + notes: '1939 G and H-class destroyer', + country: 'France', + url: 'https://en.wikipedia.org/wiki/HMS_Havant_(H32)', + }); + assert.equal(card.title, 'Shipwreck · HMS Havant'); + assert.equal(card.link, 'https://en.wikipedia.org/wiki/HMS_Havant_(H32)'); + const text = card.details.join('\n'); + assert.equal(card.details[0], 'Fatalities: 8 · Survivors: 120'); + assert.match(card.details[1], /1940 · France$/); + assert.match(text, /Vessel: destroyer/); + assert.match(text, /What happened: Was sunk/); + assert.match(text, /Depth: 15 m \(Least depth known\)/); + assert.match(text, /Position surveyed \(within about 3\.1 m\)/); + assert.match(text, /Source: Wikidata · EMODnet/); + assert.match(text, /open the article/); +}); + +test('an EMODnet card without a page links the portal', () => { + const card = describeShipwreck({ + source: 'emodnet', + name: null, + year: null, + dating: 'C1st AD', + originator: 'The Oxford Roman Economy Project', + protected: true, + url: null, + }); + assert.equal(card.title, 'Shipwreck'); + assert.equal(card.link, EMODNET_PAGE_URL); + const text = card.details.join('\n'); + assert.equal(card.details[0], 'C1st AD'); + assert.match(text, /Protected wreck/); + assert.match(text, /EMODnet \(The Oxford Roman Economy Project\)/); + assert.match(text, /open EMODnet/); +}); + +test('position lines read the accuracy', () => { + assert.equal(positionLine({}), null); + assert.match(positionLine({ positionAccuracy: 1852 }), /about 1\.9 km/); + assert.match( + positionLine({ positionNote: 'x' }), + /centre of the protected area/, + ); +}); diff --git a/src/layers/shipwrecks/eras.js b/src/layers/shipwrecks/eras.js new file mode 100644 index 000000000..4e9c2a1ff --- /dev/null +++ b/src/layers/shipwrecks/eras.js @@ -0,0 +1,33 @@ +/** Era chips, oldest first; a wreck with no known year sits in its own chip. */ +export const SHIPWRECK_ERAS = Object.freeze([ + 'before-1900', + '1900-1945', + 'after-1945', + 'undated', +]); + +/** + * The era a wreck belongs to. Ancient wrecks dated only by period + * ("Roman Imperial", "C1st AD") count as before 1900. + * @param {{year?: number|null, ancient?: boolean}} record + * @returns {string} + */ +export function eraOf(record) { + const year = Number.isInteger(record?.year) ? record.year : null; + if (year === null) return record?.ancient ? 'before-1900' : 'undated'; + if (year < 1900) return 'before-1900'; + if (year <= 1945) return '1900-1945'; + return 'after-1945'; +} + +/** + * Normalize a requested set of eras; unknown names are ignored and an empty + * or missing request keeps the current set. + * @param {unknown} value Array of era ids. + * @param {Set} current + * @returns {Set} + */ +export function normalizeEras(value, current) { + if (!Array.isArray(value)) return new Set(current); + return new Set(value.filter((era) => SHIPWRECK_ERAS.includes(era))); +} diff --git a/src/layers/shipwrecks/eras.test.mjs b/src/layers/shipwrecks/eras.test.mjs new file mode 100644 index 000000000..3891d60e7 --- /dev/null +++ b/src/layers/shipwrecks/eras.test.mjs @@ -0,0 +1,23 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { SHIPWRECK_ERAS, eraOf, normalizeEras } from './eras.js'; + +test('each wreck falls in one era', () => { + assert.equal(eraOf({ year: 1588 }), 'before-1900'); + assert.equal(eraOf({ year: null, ancient: true }), 'before-1900'); + assert.equal(eraOf({ year: 1900 }), '1900-1945'); + assert.equal(eraOf({ year: 1945 }), '1900-1945'); + assert.equal(eraOf({ year: 1946 }), 'after-1945'); + assert.equal(eraOf({ year: null }), 'undated'); + assert.equal(eraOf(null), 'undated'); +}); + +test('era requests keep known eras only', () => { + const all = new Set(SHIPWRECK_ERAS); + assert.deepEqual( + [...normalizeEras(['after-1945', 'bogus'], all)], + ['after-1945'], + ); + assert.deepEqual([...normalizeEras('after-1945', all)], SHIPWRECK_ERAS); + assert.deepEqual([...normalizeEras([], all)], []); +}); diff --git a/src/layers/shipwrecks/index.js b/src/layers/shipwrecks/index.js new file mode 100644 index 000000000..05c2c64a4 --- /dev/null +++ b/src/layers/shipwrecks/index.js @@ -0,0 +1,424 @@ +import * as Cesium from 'cesium'; +import { formatNumber, msg, t, tn } from '../../i18n/index.js'; +import { createHorizonCull } from '../streetLevel/view.js'; +import { ERA_COLORS, ERA_LABELS, describeShipwreck } from './cards.js'; +import { SHIPWRECK_ERAS, eraOf, normalizeEras } from './eras.js'; +export * from './records.js'; +export * from './cards.js'; +export * from './eras.js'; +export { createShipwrecksSource } from './source.js'; + +export const SHIPWRECKS_LAYER_ID = 'shipwrecks'; +export const SHIPWRECKS_OVERLAY_SOURCE_ID = 'shipwrecks'; +const PICK_PREFIX = 'shipwreck:'; +const CARD_HOST_OPTIONS = Object.freeze({ + cohortLimit: 1, + collisionCapacity: 1, + moving: false, +}); +const MAX_CARD_LINES = 14; +/** + * Marker size in pixels: grows with the death toll, as on the air-accidents + * layer, from 16 px (no deaths known) to 36 px (about a thousand or more). + */ +export function markerPixelSize(casualties) { + const n = Number.isFinite(casualties) && casualties > 0 ? casualties : 0; + return Math.round(16 + Math.min(20, Math.log2(1 + n) * 2)); +} + +/** + * A round marker in the era's colour with a sinking hull and mast in the + * middle, as an SVG data URL. + * @param {string} color CSS colour. + * @returns {string} + */ +export function wreckMarkerImage(color) { + const svg = + `` + + `` + + `` + + `` + + ``; + return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`; +} + +/** + * Shipwrecks: EMODnet's European heritage wrecks and Wikidata's notable + * wrecks worldwide, one marker each, with a card and era chips. + */ +export function createShipwrecksLayer({ + source, + overlayHost = null, + screenSpaceEventHandlerFactory = null, + picking = null, + pointer = null, + openExternal = null, +} = {}) { + if (typeof source?.getSnapshot !== 'function') + throw new TypeError('Shipwrecks require a snapshot source'); + let _viewer = null; + let _enabled = false; + let _dataSource = null; + let _request = null; + let _records = new Map(); + let _pins = []; + let _snapshot = null; + let _lastError = null; + let _clickHandler = null; + let _rowListener = null; + let _selectedId = null; + let _selectedCardId = null; + let _selectedLink = null; + let _eras = new Set(SHIPWRECK_ERAS); + const _images = Object.fromEntries( + SHIPWRECK_ERAS.map((era) => [era, wreckMarkerImage(ERA_COLORS[era])]), + ); + + const render = () => _viewer?.scene?.requestRender?.(); + const notifyRow = () => _rowListener?.(); + const canSelect = () => + overlayHost && screenSpaceEventHandlerFactory && picking; + // Markers skip the depth test so terrain does not swallow them; the + // horizon cull hides the far side of the planet instead. + const _horizon = createHorizonCull({ + getViewer: () => _viewer, + items: () => _pins, + onChange: render, + }); + + /** Shown: its era chip is on. */ + function visible(record) { + return Boolean(record) && _eras.has(eraOf(record)); + } + + function applyPin(pin) { + pin.entity.show = pin.inFront && visible(pin.record); + } + + /** Re-apply the era chips to every marker and the open card. */ + function applyFilter() { + for (const pin of _pins) applyPin(pin); + if (_selectedId && !visible(_records.get(_selectedId))) clearSelection(); + notifyRow(); + render(); + } + + function rebuild(records) { + _records = new Map(records.map((record) => [record.id, record])); + _pins = []; + if (!_dataSource) return; + _dataSource.entities.suspendEvents(); + _dataSource.entities.removeAll(); + for (const record of records) { + const position = Cesium.Cartesian3.fromDegrees(record.lon, record.lat); + const entity = _dataSource.entities.add({ + id: `${PICK_PREFIX}${record.id}`, + position, + billboard: { + image: _images[eraOf(record)], + width: markerPixelSize(record.casualties), + height: markerPixelSize(record.casualties), + heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, + disableDepthTestDistance: Number.POSITIVE_INFINITY, + // Bigger toll, drawn on top of smaller neighbours. + eyeOffset: new Cesium.Cartesian3( + 0, + 0, + -Math.min(record.casualties || 0, 5000), + ), + }, + }); + const pin = { + entity, + record, + position, + inFront: true, + get show() { + return this.inFront; + }, + set show(value) { + this.inFront = value; + applyPin(this); + }, + }; + applyPin(pin); + _pins.push(pin); + } + _dataSource.entities.resumeEvents(); + _horizon.update(); + if (_selectedId && !_records.has(_selectedId)) clearSelection(); + else if (_selectedId) publishCard(); + render(); + } + + // ---- selection card ---------------------------------------------------- + function publishCard() { + if (!canSelect()) return; + const record = _selectedId ? _records.get(_selectedId) : null; + if (!visible(record)) { + clearSelection(); + return; + } + const { title, details, link } = describeShipwreck(record); + _selectedLink = link && openExternal ? link : null; + const card = { + id: `shipwreck-card:${record.id}`, + selected: true, + interactive: Boolean(_selectedLink), + title, + details: details.slice(0, MAX_CARD_LINES), + accent: ERA_COLORS[eraOf(record)], + priority: Number.MAX_SAFE_INTEGER, + gapPx: 15, + verticalOnly: true, + placement: 'above', + stateless: true, + horizonCull: true, + position: Cesium.Cartesian3.fromDegrees(record.lon, record.lat), + }; + if (card.interactive) { + const target = _selectedLink; + card.accessibilityLabel = t('Open the source for {title}', { title }); + card.activate = () => { + openExternal(target); + return true; + }; + } + _selectedCardId = card.id; + overlayHost.setEntries( + SHIPWRECKS_OVERLAY_SOURCE_ID, + [card], + CARD_HOST_OPTIONS, + ); + overlayHost.setVisible?.(SHIPWRECKS_OVERLAY_SOURCE_ID, true); + } + + function clearSelection() { + _selectedId = null; + _selectedCardId = null; + _selectedLink = null; + overlayHost?.setEntries( + SHIPWRECKS_OVERLAY_SOURCE_ID, + [], + CARD_HOST_OPTIONS, + ); + } + + function pickedRecordId(picked) { + const pickId = picking.resolvePickId(picked); + if (typeof pickId !== 'string' || !pickId.startsWith(PICK_PREFIX)) + return null; + const id = pickId.slice(PICK_PREFIX.length); + return _records.has(id) ? id : null; + } + + function installClickHandler() { + if (!canSelect() || _clickHandler || !_viewer) return; + picking.registerPickOwner?.( + SHIPWRECKS_LAYER_ID, + (pickedId) => + typeof pickedId === 'string' && pickedId.startsWith(PICK_PREFIX), + ); + _clickHandler = screenSpaceEventHandlerFactory(_viewer); + _clickHandler.setInputAction((click) => { + if (pointer && !pointer.isPointerFree()) return; + const cardHit = overlayHost.hitTest?.( + click.position?.x, + click.position?.y, + { sourceId: SHIPWRECKS_OVERLAY_SOURCE_ID }, + ); + if (cardHit && cardHit.entryId === _selectedCardId) { + if (_selectedLink) openExternal(_selectedLink); + return; + } + const picked = _viewer.scene.pick(click.position); + const id = picked ? pickedRecordId(picked) : null; + if (id) { + _selectedId = id; + publishCard(); + render(); + return; + } + if (picked) { + const pickId = picking.resolvePickId(picked); + if (pickId && picking.isOwnedByOtherLayer(SHIPWRECKS_LAYER_ID, pickId)) + return; + } + if (_selectedId) { + clearSelection(); + render(); + } + }, Cesium.ScreenSpaceEventType.LEFT_CLICK); + } + + function removeClickHandler() { + _clickHandler?.destroy(); + _clickHandler = null; + picking?.unregisterPickOwner?.(SHIPWRECKS_LAYER_ID); + } + + function toggleEra(era) { + if (_eras.has(era)) _eras.delete(era); + else _eras.add(era); + applyFilter(); + } + + function countOf(era) { + let count = 0; + for (const record of _records.values()) if (eraOf(record) === era) count++; + return count; + } + + const layer = { + id: SHIPWRECKS_LAYER_ID, + name: 'Shipwrecks', + icon: '⚓', + source: 'EMODnet · Wikidata', + // The proxy refreshes once a day; this only notices a new snapshot. + updateInterval: 6 * 60 * 60 * 1000, + + init(viewer) { + if (_viewer) throw new Error('Shipwrecks layer is already initialized'); + _viewer = viewer; + _dataSource = new Cesium.CustomDataSource(SHIPWRECKS_LAYER_ID); + _dataSource.show = false; + viewer.dataSources.add(_dataSource); + }, + + enable() { + _enabled = true; + if (_dataSource) _dataSource.show = true; + installClickHandler(); + if (_pins.length) _horizon.update(); + }, + + disable() { + _enabled = false; + _request?.abort(); + _request = null; + if (_dataSource) _dataSource.show = false; + removeClickHandler(); + clearSelection(); + _horizon.stop(); + render(); + }, + + async update() { + if (!_enabled || !_dataSource) return false; + _request?.abort(); + const request = new AbortController(); + _request = request; + try { + const snapshot = await source.getSnapshot({ signal: request.signal }); + if (request.signal.aborted || _request !== request || !_enabled) + return false; + _snapshot = snapshot; + _lastError = + snapshot.sources.emodnet && snapshot.sources.wikidata + ? null + : snapshot.sources.emodnet + ? msg('Wikidata unavailable; showing EMODnet only') + : msg('EMODnet unavailable; showing Wikidata only'); + rebuild(snapshot.records); + notifyRow(); + return true; + } catch (error) { + if (request.signal.aborted || _request !== request || !_enabled) + return false; + console.warn('[Data:Shipwrecks] Fetch error:', error); + _lastError = error?.message || msg('Shipwrecks unavailable'); + notifyRow(); + return false; + } finally { + if (_request === request) _request = null; + } + }, + + destroy(viewer = _viewer) { + layer.disable(); + if (_dataSource) { + viewer?.dataSources?.remove(_dataSource, true); + _dataSource = null; + } + _records = new Map(); + _pins = []; + _snapshot = null; + _viewer = null; + _rowListener = null; + }, + + /** The era filter: `eras` lists the era chips that are on. */ + getParams() { + return { eras: SHIPWRECK_ERAS.filter((era) => _eras.has(era)) }; + }, + + setParams(params = {}) { + if (!('eras' in params)) return true; + const next = normalizeEras(params.eras, _eras); + if (next.size === _eras.size && [...next].every((era) => _eras.has(era))) + return true; + _eras = next; + applyFilter(); + return true; + }, + + setRowControlsListener(listener) { + _rowListener = listener; + }, + + getRowControls() { + return { + chips: SHIPWRECK_ERAS.map((era) => ({ + id: era, + label: t(ERA_LABELS[era]), + active: _eras.has(era), + color: ERA_COLORS[era], + title: tn(countOf(era), '{count} wreck', '{count} wrecks', { + count: formatNumber(countOf(era)), + }), + onClick: () => toggleEra(era), + })), + legend: [], + info: t('EMODnet (European waters) · Wikidata (worldwide)'), + infoTitle: t( + 'European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.', + ), + }; + }, + + getStats() { + let shown = 0; + for (const record of _records.values()) if (visible(record)) shown++; + return { + count: shown, + lastUpdate: _snapshot?.fetchedAt ?? null, + stale: _snapshot?.stale === true, + error: _lastError, + }; + }, + + /** Loaded records as plain JSON-safe objects, for tools and QA. */ + getAnalystRecords(maxCount = 2000) { + if (!_enabled) return []; + const out = []; + for (const record of _records.values()) { + if (out.length >= maxCount) break; + if (!visible(record)) continue; + out.push({ + id: record.id, + source: record.source, + name: record.name, + vesselType: record.vesselType, + year: record.year, + era: eraOf(record), + lat: record.lat, + lon: record.lon, + depth: record.depth, + casualties: record.casualties, + }); + } + return out; + }, + }; + return layer; +} diff --git a/src/layers/shipwrecks/records.js b/src/layers/shipwrecks/records.js new file mode 100644 index 000000000..7a7072205 --- /dev/null +++ b/src/layers/shipwrecks/records.js @@ -0,0 +1,428 @@ +// Shared by the server proxy (server/providers/shipwrecks.js) and the browser +// layer, so it must not load the i18n catalogs: values stay data. + +/** EMODnet Human Activities "Cultural Heritage – Ship wrecks" (CC BY 4.0). */ +export const EMODNET_WFS_URL = + 'https://ows.emodnet-humanactivities.eu/wfs?service=WFS&request=GetFeature' + + '&version=2.0.0&typeNames=emodnet:heritageshipwrecks' + + '&outputFormat=application/json&srsName=EPSG:4326'; +/** Landing page shown when an EMODnet wreck has no web page of its own. */ +export const EMODNET_PAGE_URL = + 'https://emodnet.ec.europa.eu/en/human-activities'; + +export const SHIPWRECK_SOURCES = Object.freeze(['emodnet', 'wikidata']); + +/** + * Wikidata (CC0): shipwreck items that have at least one Wikipedia article, + * so the worldwide set stays to notable wrecks and skips bulk register + * imports, plus sinking events ("sinking of the RMS Titanic"), which are where + * Wikidata keeps the death toll. Dates come with their precision so a + * month-precise date is not shown as the 1st. Only ship and event facts are + * read: no items about people. + */ +export const WIKIDATA_QUERY = `SELECT ?item ?itemLabel ?itemDescription ?coord ?sunk ?sunkPrecision ?end ?deaths ?survivors ?typeLabel ?enwiki ?ptwiki ?event WHERE { + { + ?item wdt:P31/wdt:P279* wd:Q852190 ; wdt:P625 ?coord ; wikibase:sitelinks ?links . + FILTER(?links > 0) + OPTIONAL { ?item p:P793 ?wreck . ?wreck ps:P793 wd:Q906512 ; pqv:P585 [ wikibase:timeValue ?sunk ; wikibase:timePrecision ?sunkPrecision ] } + OPTIONAL { ?item wdt:P576 ?end } + OPTIONAL { ?item wdt:P31 ?type . FILTER(?type != wd:Q852190) } + } UNION { + ?item wdt:P31/wdt:P279* wd:Q906512 ; wdt:P625 ?coord . + BIND("event" AS ?event) + OPTIONAL { ?item p:P585/psv:P585 [ wikibase:timeValue ?sunk ; wikibase:timePrecision ?sunkPrecision ] } + OPTIONAL { ?item wdt:P1561 ?survivors } + } + OPTIONAL { ?item wdt:P1120 ?deaths } + OPTIONAL { ?enwiki schema:about ?item ; schema:isPartOf } + OPTIONAL { ?ptwiki schema:about ?item ; schema:isPartOf } + SERVICE wikibase:label { bd:serviceParam wikibase:language "en,pt,mul". } +}`; + +const MAX_TEXT = 160; +const MAX_NOTE = 260; +/** Same name within this distance: one wreck seen by both sources. */ +const SAME_WRECK_KM = 3; + +// Free text sometimes names people (owners, masters, divers who reported a +// wreck). The layer shows ships, never people, so such text is dropped whole. +const PERSON_TEXT = + /\b(mr|mrs|ms|dr|capt|captain|master|skipper|owner|owned|crew|body|bodies|drowned|reported by|according to)\b/i; + +/** EMODnet writes "n/a" or nothing where a value is unknown. */ +function clean(value, max = MAX_TEXT) { + if (typeof value !== 'string') return null; + const text = value + .replace(/[\u0000-\u001f<>]/g, ' ') + .replace(/\s+/g, ' ') + .trim(); + if (!text || /^(n\/a|null|unknown|none|-)$/i.test(text)) return null; + return text.length > max ? `${text.slice(0, max - 1).trimEnd()}…` : text; +} + +/** Free text with no personal names in it, or null. */ +function impersonalText(value, max) { + const text = clean(value, max); + return text && !PERSON_TEXT.test(text) ? text : null; +} + +function positiveNumber(value, max) { + const n = typeof value === 'number' ? value : Number(value); + return Number.isFinite(n) && n > 0 && n <= max ? n : null; +} + +function count(value) { + const text = String(value ?? '').replace(/\.0+$/, ''); + if (!/^\d{1,6}$/.test(text)) return null; + return Number(text); +} + +/** A sinking year from "1917", "1917-1918" or "c. 1917"; null otherwise. */ +export function parseYear(value, maxYear = new Date().getUTCFullYear()) { + const match = /(?:^|\D)(\d{3,4})(?:\D|$)/.exec(String(value ?? '')); + if (!match) return null; + const year = Number(match[1]); + return year >= 100 && year <= maxYear ? year : null; +} + +function validPoint(lat, lon) { + return ( + Number.isFinite(lat) && + Number.isFinite(lon) && + Math.abs(lat) <= 90 && + Math.abs(lon) <= 180 && + !(lat === 0 && lon === 0) + ); +} + +function httpUrl(value) { + const text = clean(value, 400); + if (!text) return null; + try { + const url = new URL(text); + return url.protocol === 'https:' || url.protocol === 'http:' + ? url.href + : null; + } catch { + return null; + } +} + +/** + * Normalize EMODnet's shipwreck GeoJSON. Records the portal took from + * wrecksite.eu are skipped: that site's data is not openly licensed. + * @param {object} payload WFS GeoJSON FeatureCollection. + * @returns {object[]} Shipwreck records. + */ +export function normalizeEmodnetFeatures(payload) { + const features = payload?.features; + if (!Array.isArray(features)) return []; + const out = []; + const ids = new Set(); + for (const feature of features) { + const p = feature?.properties || {}; + const coords = feature?.geometry?.coordinates; + if (feature?.geometry?.type !== 'Point' || !Array.isArray(coords)) continue; + const lon = Number(coords[0]); + const lat = Number(coords[1]); + if (!validPoint(lat, lon)) continue; + const origin = clean(p.source_inf, 80); + if (origin && /wrecksite/i.test(origin)) continue; + const key = clean(String(feature.id ?? p.source_id ?? ''), 80); + if (!key) continue; + const id = `emodnet:${key}`; + if (ids.has(id)) continue; + ids.add(id); + const year = parseYear(p.sink_yr); + const dating = clean(p.dating, 60); + const period = clean(p.period, 60); + const vesselType = + clean(p.obj_type, 60) || + (() => { + // ship_char is sometimes a short type ("Trawler"), sometimes a long + // history that can name people; only the short form is a type. + const text = clean(p.ship_char, 40); + return text && !/\d/.test(text) && !PERSON_TEXT.test(text) + ? text + : null; + })(); + out.push({ + id, + source: 'emodnet', + lat, + lon, + name: clean(p.name, 100), + vesselType, + year, + date: null, + dating: year ? null : dating, + ancient: !year && Boolean(period || dating), + cause: impersonalText(p.sink_context, MAX_NOTE), + notes: period && dating ? `${period} (${dating})` : period, + cargo: impersonalText(p.artefacts, 120), + protected: /protected/i.test(p.statutory || ''), + depth: positiveNumber(p.least_depth, 11000), + depthQuality: clean(p.depth_prec, 80), + positionAccuracy: positiveNumber(p.loc_prec, 100000), + positionNote: /centroid/i.test(p.point_info || '') + ? 'Centre of the protected area' + : null, + casualties: null, + survivors: null, + country: clean(p.country, 60), + originator: origin, + url: httpUrl(p.website1), + }); + } + return out; +} + +function wikiUrl(value) { + const url = httpUrl(value); + return url && /^https:\/\/[a-z]{2,3}\.wikipedia\.org\/wiki\//.test(url) + ? url + : null; +} + +/** + * A Wikidata time as a day ("1912-04-15") when it is day-precise, else as a + * year only: a month- or year-precise value reads back as the 1st. + * @returns {{date: string|null, year: number|null}} + */ +function wikidataTime(value, precision) { + const match = /^(-?\d{4})-(\d{2})-(\d{2})T/.exec(value || ''); + if (!match) return { date: null, year: null }; + const year = parseYear(match[1]); + const p = Number(precision); + // 11 = day; 9 = year; 10 = month. A missing precision (P576) counts as a day. + if (!Number.isFinite(p) || p >= 11) + return { date: `${match[1]}-${match[2]}-${match[3]}`, year }; + return { date: null, year: p >= 9 ? year : null }; +} + +/** "sinking of the RMS Titanic" → "Sinking of the RMS Titanic". */ +function sentenceCase(text) { + return text ? text.charAt(0).toUpperCase() + text.slice(1) : text; +} + +/** + * Normalize Wikidata SPARQL results to shipwreck records (one per item). + * Sinking events are folded into the ship they sank when both are listed. + * @param {object} payload SPARQL JSON results. + * @returns {object[]} + */ +export function normalizeWikidataResults(payload) { + const bindings = payload?.results?.bindings; + if (!Array.isArray(bindings)) return []; + const byItem = new Map(); + for (const binding of bindings) { + const value = (key) => binding?.[key]?.value; + const qid = /\/entity\/(Q\d{1,12})$/.exec(value('item') || '')?.[1]; + if (!qid) continue; + const sunk = wikidataTime(value('sunk'), value('sunkPrecision')); + const ended = wikidataTime(value('end'), null); + const known = byItem.get(qid); + if (known) { + // Extra rows only add what the first one lacked. + known.vesselType ||= clean(value('typeLabel'), 60); + if (!known.date && !known.year) { + known.date = sunk.date || ended.date; + known.year = sunk.year ?? ended.year; + } + known.casualties ??= count(value('deaths')); + known.survivors ??= count(value('survivors')); + continue; + } + const point = /^Point\(([-\d.eE]+) ([-\d.eE]+)\)$/.exec( + value('coord') || '', + ); + const lon = point ? Number(point[1]) : NaN; + const lat = point ? Number(point[2]) : NaN; + if (!validPoint(lat, lon)) continue; + const name = clean(value('itemLabel'), 100); + const event = value('event') === 'event'; + const when = sunk.date || sunk.year ? sunk : ended; + byItem.set(qid, { + id: `wikidata:${qid}`, + source: 'wikidata', + event, + lat, + lon, + // An unlabelled item reads back as its own Q-id; that is no name. + name: name && name !== qid ? (event ? sentenceCase(name) : name) : null, + vesselType: event ? null : clean(value('typeLabel'), 60), + year: when.year, + date: when.date, + dating: null, + ancient: false, + cause: null, + notes: impersonalText(value('itemDescription'), MAX_TEXT), + cargo: null, + protected: false, + depth: null, + depthQuality: null, + positionAccuracy: null, + positionNote: null, + casualties: count(value('deaths')), + survivors: count(value('survivors')), + country: null, + originator: null, + url: + wikiUrl(value('enwiki')) || + wikiUrl(value('ptwiki')) || + `https://www.wikidata.org/wiki/${qid}`, + }); + } + return foldSinkingEvents([...byItem.values()]); +} + +/** An event this far from a listed ship whose name it contains is that ship's sinking. */ +const SAME_SINKING_KM = 50; + +/** + * "Sinking of the RMS Titanic" near the RMS Titanic wreck is one marker: the + * ship keeps its article and takes the event's date, deaths and survivors. + */ +function foldSinkingEvents(records) { + // Wikidata sometimes has both the ship and its wreck as items at one spot + // ("Titanic", "wreck of the RMS Titanic"): keep the ship, one marker. + const isWreckItem = (record) => (/^wreck\b/i.test(record.name || '') ? 1 : 0); + const ships = []; + const candidates = records + .filter((record) => !record.event) + .sort((a, b) => isWreckItem(a) - isWreckItem(b)); + for (const record of candidates) { + const key = nameKey(record.name); + const twin = + key && + ships.find( + (ship) => + nameKey(ship.name) === key && + distanceKm(ship, record) <= SAME_WRECK_KM, + ); + if (!twin) { + ships.push(record); + continue; + } + twin.vesselType ||= record.vesselType; + if (!twin.date && !twin.year) { + twin.date = record.date; + twin.year = record.year; + } + twin.casualties ??= record.casualties; + twin.survivors ??= record.survivors; + } + const out = [...ships]; + for (const event of records.filter((record) => record.event)) { + const eventKey = ` ${nameKey(event.name)} `; + const ship = ships.find((candidate) => { + const key = nameKey(candidate.name); + return ( + key.length >= 3 && + eventKey.includes(` ${key} `) && + distanceKm(candidate, event) <= SAME_SINKING_KM + ); + }); + if (!ship) { + out.push(event); + continue; + } + if (!ship.date && !ship.year) { + ship.date = event.date; + ship.year = event.year; + } else if (!ship.date && event.date && event.year === ship.year) { + ship.date = event.date; + } + ship.casualties ??= event.casualties; + ship.survivors ??= event.survivors; + } + for (const record of out) delete record.event; + return out; +} + +function nameKey(name) { + return String(name || '') + .normalize('NFD') + .replace(/[̀-ͯ]/g, '') + .toLowerCase() + .replace(/\([^)]*\)/g, ' ') + .replace(/\b(wreck|sinking|loss|disaster|of)\b/g, ' ') + .replace( + /\b(hms|hmt|hmhs|hmas|sms|ss|ms|mv|rms|uss|hm|s\/s|m\/v|the)\b/g, + ' ', + ) + .replace(/[^a-z0-9]+/g, ' ') + .trim(); +} + +function distanceKm(a, b) { + const rad = Math.PI / 180; + const dLat = (b.lat - a.lat) * rad; + const dLon = (b.lon - a.lon) * rad; + const h = + Math.sin(dLat / 2) ** 2 + + Math.cos(a.lat * rad) * Math.cos(b.lat * rad) * Math.sin(dLon / 2) ** 2; + return 12742 * Math.asin(Math.min(1, Math.sqrt(h))); +} + +/** + * One list from both sources. A wreck in both (same name, a few km apart) + * keeps the Wikidata record, which links an article, and takes EMODnet's + * survey facts (depth, sinking text, year) that Wikidata lacks. + */ +export function mergeShipwreckRecords(emodnet = [], wikidata = []) { + const byName = new Map(); + for (const record of wikidata) { + const key = nameKey(record.name); + if (!key) continue; + if (!byName.has(key)) byName.set(key, []); + byName.get(key).push(record); + } + const kept = []; + for (const record of emodnet) { + const twin = (byName.get(nameKey(record.name)) || []).find( + (candidate) => distanceKm(candidate, record) <= SAME_WRECK_KM, + ); + if (!twin) { + kept.push(record); + continue; + } + twin.year ??= record.year; + twin.vesselType ||= record.vesselType; + twin.cause ||= record.cause; + twin.depth ??= record.depth; + twin.depthQuality ||= record.depthQuality; + twin.positionAccuracy ??= record.positionAccuracy; + twin.country ||= record.country; + twin.protected ||= record.protected; + twin.alsoIn = 'emodnet'; + } + return [...wikidata, ...kept]; +} + +/** + * Validate the proxy's snapshot in the browser. + * @returns {object[]|null} Records, or null when the payload is malformed. + */ +export function normalizeShipwreckSnapshot(payload) { + if (!Array.isArray(payload?.records)) return null; + const rows = []; + const ids = new Set(); + for (const record of payload.records) { + if ( + !record || + typeof record.id !== 'string' || + ids.has(record.id) || + !SHIPWRECK_SOURCES.includes(record.source) || + !validPoint(record.lat, record.lon) + ) + continue; + ids.add(record.id); + rows.push({ + ...record, + year: Number.isInteger(record.year) ? record.year : null, + url: httpUrl(record.url), + }); + } + return rows; +} diff --git a/src/layers/shipwrecks/records.test.mjs b/src/layers/shipwrecks/records.test.mjs new file mode 100644 index 000000000..a61154a5a --- /dev/null +++ b/src/layers/shipwrecks/records.test.mjs @@ -0,0 +1,212 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { + mergeShipwreckRecords, + normalizeEmodnetFeatures, + normalizeShipwreckSnapshot, + normalizeWikidataResults, + parseYear, +} from './records.js'; + +function feature(id, properties, coordinates = [-4.35, 54.13]) { + return { + type: 'Feature', + id, + geometry: { type: 'Point', coordinates }, + properties, + }; +} + +test('EMODnet wrecks keep ship facts and drop text that names people', () => { + const [wreck, roman] = normalizeEmodnetFeatures({ + features: [ + feature('w.1', { + name: 'MAINA-NUI', + sink_yr: '1987', + sink_context: 'Sank on 07/02/1987', + obj_type: 'Pusher or tug', + least_depth: 12.5, + depth_prec: 'Least depth known', + loc_prec: 50, + country: 'France', + source_inf: 'SHOM', + statutory: 'n/a', + website1: 'n/a', + }), + feature('w.2', { + name: 'Lerici', + sink_yr: '', + dating: 'C1st-2nd AD', + period: 'Roman Imperial', + artefacts: 'Marble, Columns', + obj_type: 'n/a', + ship_char: 'Owned by J. Smith, master was A. Jones', + sink_context: 'Wrecked here, reported by Mr Smith', + }), + feature('w.3', { name: 'Copied', source_inf: 'www.wrecksite.eu' }), + feature('w.4', { name: 'Null island' }, [0, 0]), + ], + }); + assert.equal(wreck.id, 'emodnet:w.1'); + assert.equal(wreck.year, 1987); + assert.equal(wreck.vesselType, 'Pusher or tug'); + assert.equal(wreck.cause, 'Sank on 07/02/1987'); + assert.equal(wreck.depth, 12.5); + assert.equal(wreck.positionAccuracy, 50); + assert.equal(wreck.url, null); + assert.equal(roman.year, null); + assert.equal(roman.ancient, true); + assert.equal(roman.dating, 'C1st-2nd AD'); + assert.equal(roman.notes, 'Roman Imperial (C1st-2nd AD)'); + assert.equal(roman.cargo, 'Marble, Columns'); + assert.equal(roman.vesselType, null, 'a history naming people is no type'); + assert.equal(roman.cause, null, 'text naming a person is dropped'); +}); + +test('Wikidata rows fold into one record per item', () => { + const item = 'http://www.wikidata.org/entity/Q1471525'; + const records = normalizeWikidataResults({ + results: { + bindings: [ + { + item: { value: item }, + itemLabel: { value: 'HMS Havant' }, + itemDescription: { value: '1939 G and H-class destroyer' }, + coord: { value: 'Point(2.26 51.13)' }, + sunk: { value: '1940-06-01T00:00:00Z' }, + enwiki: { value: 'https://en.wikipedia.org/wiki/HMS_Havant_(H32)' }, + }, + { + item: { value: item }, + typeLabel: { value: 'destroyer' }, + deaths: { value: '8' }, + coord: { value: 'Point(2.26 51.13)' }, + }, + { + item: { value: 'http://www.wikidata.org/entity/Q9' }, + itemLabel: { value: 'Q9' }, + coord: { value: 'Point(10 10)' }, + }, + ], + }, + }); + assert.equal(records.length, 2); + const [havant, unnamed] = records; + assert.equal(havant.date, '1940-06-01'); + assert.equal(havant.year, 1940); + assert.equal(havant.vesselType, 'destroyer'); + assert.equal(havant.casualties, 8); + assert.equal(havant.url, 'https://en.wikipedia.org/wiki/HMS_Havant_(H32)'); + assert.equal(unnamed.name, null); + assert.equal(unnamed.url, 'https://www.wikidata.org/wiki/Q9'); +}); + +test('a wreck in both sources keeps Wikidata and takes EMODnet survey facts', () => { + const wikidata = [ + { + id: 'wikidata:Q1', + source: 'wikidata', + name: 'HMS Havant', + lat: 51.13, + lon: 2.26, + year: null, + depth: null, + }, + ]; + const emodnet = [ + { + id: 'emodnet:a', + source: 'emodnet', + name: 'Havant (HMS)', + lat: 51.131, + lon: 2.262, + year: 1940, + depth: 14.7, + }, + { + id: 'emodnet:b', + source: 'emodnet', + name: 'HMS Havant', + lat: 45, + lon: -10, + year: 1950, + }, + ]; + const merged = mergeShipwreckRecords(emodnet, wikidata); + assert.deepEqual( + merged.map((record) => record.id), + ['wikidata:Q1', 'emodnet:b'], + ); + assert.equal(merged[0].year, 1940); + assert.equal(merged[0].depth, 14.7); + assert.equal(merged[0].alsoIn, 'emodnet'); +}); + +test('years and snapshots are validated', () => { + assert.equal(parseYear('1917-1918'), 1917); + assert.equal(parseYear('c. 1588'), 1588); + assert.equal(parseYear(''), null); + assert.equal(parseYear('3000'), null); + assert.equal(normalizeShipwreckSnapshot({}), null); + const rows = normalizeShipwreckSnapshot({ + records: [ + { id: 'a', source: 'emodnet', lat: 1, lon: 2, url: 'javascript:x' }, + { id: 'a', source: 'emodnet', lat: 1, lon: 2 }, + { id: 'b', source: 'other', lat: 1, lon: 2 }, + { id: 'c', source: 'wikidata', lat: 91, lon: 2 }, + ], + }); + assert.equal(rows.length, 1); + assert.equal(rows[0].url, null); +}); + +test('a sinking event folds into its ship; month-precise dates keep the year only', () => { + const entity = (q) => ({ value: `http://www.wikidata.org/entity/${q}` }); + const records = normalizeWikidataResults({ + results: { + bindings: [ + { + item: entity('Q25173'), + itemLabel: { value: 'Titanic' }, + coord: { value: 'Point(-49.9469 41.7325)' }, + }, + { + item: entity('Q3018259'), + itemLabel: { value: 'wreck of the RMS Titanic' }, + coord: { value: 'Point(-49.9469 41.7325)' }, + }, + { + item: entity('Q2577588'), + itemLabel: { value: 'sinking of the RMS Titanic' }, + coord: { value: 'Point(-49.9458 41.7319)' }, + event: { value: 'event' }, + sunk: { value: '1912-04-01T00:00:00Z' }, + sunkPrecision: { value: '10' }, + deaths: { value: '1501' }, + survivors: { value: '712' }, + }, + { + item: entity('Q1245004'), + itemLabel: { value: 'Costa Concordia disaster' }, + coord: { value: 'Point(10.92 42.37)' }, + event: { value: 'event' }, + sunk: { value: '2012-01-13T00:00:00Z' }, + sunkPrecision: { value: '11' }, + deaths: { value: '32' }, + }, + ], + }, + }); + assert.deepEqual( + records.map((record) => record.id), + ['wikidata:Q25173', 'wikidata:Q1245004'], + ); + const [titanic, concordia] = records; + assert.equal(titanic.date, null); + assert.equal(titanic.year, 1912); + assert.equal(titanic.casualties, 1501); + assert.equal(titanic.survivors, 712); + assert.equal(concordia.name, 'Costa Concordia disaster'); + assert.equal(concordia.date, '2012-01-13'); + assert.equal('event' in concordia, false); +}); diff --git a/src/layers/shipwrecks/source.js b/src/layers/shipwrecks/source.js new file mode 100644 index 000000000..49f75b526 --- /dev/null +++ b/src/layers/shipwrecks/source.js @@ -0,0 +1,35 @@ +import { readResponseJsonCapped } from '../../sources/httpBody.js'; +import { normalizeShipwreckSnapshot } from './records.js'; + +/** Same-origin source for the proxy's EMODnet + Wikidata shipwreck snapshot. */ +export function createShipwrecksSource({ + fetchImpl = (...args) => globalThis.fetch(...args), +} = {}) { + return { + async getSnapshot({ signal } = {}) { + signal?.throwIfAborted(); + const response = await fetchImpl('/api/shipwrecks', { signal }); + if (!response.ok) + throw new Error(`Shipwrecks unavailable (HTTP ${response.status})`); + const payload = await readResponseJsonCapped( + response, + 16 * 1024 * 1024, + signal, + ); + signal?.throwIfAborted(); + const records = normalizeShipwreckSnapshot(payload); + if (!records) throw new Error('Malformed shipwrecks response'); + return { + records, + fetchedAt: Number.isFinite(payload.fetchedAt) + ? payload.fetchedAt + : null, + stale: payload.stale === true, + sources: { + emodnet: payload.sources?.emodnet !== false, + wikidata: payload.sources?.wikidata !== false, + }, + }; + }, + }; +} diff --git a/src/standalone/layerSources.js b/src/standalone/layerSources.js index 2e0534a3a..8f903510c 100644 --- a/src/standalone/layerSources.js +++ b/src/standalone/layerSources.js @@ -20,6 +20,7 @@ import { createCycloneSource } from '../layers/cyclones/source.js'; import { createWindSource } from '../layers/wind/source.js'; import { createFirmsSource } from '../layers/firms/source.js'; import { createGhostMapsSource } from '../layers/ghostMaps/source.js'; +import { createShipwrecksSource } from '../layers/shipwrecks/source.js'; import { createMapillarySource } from '../layers/streetLevel/providers/mapillary/source.js'; import { createReferenceSources } from '../sources/reference.js'; export { createReferenceSources as createStandaloneReferenceSources } from '../sources/reference.js'; @@ -60,6 +61,7 @@ export function createStandaloneLayerSources( alpr: createAlprTileSource(), firms: createFirmsSource(), 's2-ghostmaps': createGhostMapsSource(), + shipwrecks: createShipwrecksSource(), wind: createWindSource(), weather: createWeatherSource(), cyclones: createCycloneSource(), diff --git a/src/ui/layerNames.js b/src/ui/layerNames.js index 21f681b11..617605035 100644 --- a/src/ui/layerNames.js +++ b/src/ui/layerNames.js @@ -37,6 +37,7 @@ export const LAYER_NAME_KEYS = Object.freeze({ 'gnss-integrity': msg('GNSS Integrity'), 'drone-airspace': msg('Prohibited & Restricted Airspace'), 's2-ghostmaps': msg('S2 GhostMaps'), + shipwrecks: msg('Shipwrecks'), wind: msg('Wind'), 'weather-radar': msg('Rain radar'), 'weather-satellite': msg('Satellite clouds'), diff --git a/src/ui/layerPanel.js b/src/ui/layerPanel.js index b24e8be7b..4c16b047c 100644 --- a/src/ui/layerPanel.js +++ b/src/ui/layerPanel.js @@ -78,6 +78,7 @@ const PANEL_GROUPS = [ 'fire-perimeters', 'gnss-integrity', 's2-ghostmaps', + 'shipwrecks', ], }, { diff --git a/src/voice/layerManifest.js b/src/voice/layerManifest.js index 1234fb61e..b05aba33d 100644 --- a/src/voice/layerManifest.js +++ b/src/voice/layerManifest.js @@ -457,6 +457,8 @@ export const VOICE_OFF_LAYERS = Object.freeze({ // query for this layer wait until there is room. 'drone-airspace': 'informational airspace layer; no room in the prompt budget', + // Same budget: a historical wreck archive waits for room too. + shipwrecks: 'historical shipwreck archive; no room in the prompt budget', }); const TYPE_NAMES = Object.freeze({ From 112ffd4386c779e1286cb4144633a75a2fb9722d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Itallo=20Brand=C3=A3o?= <45429643+IMBrandao@users.noreply.github.com> Date: Thu, 5 Nov 2026 04:49:36 -0300 Subject: [PATCH 025/171] feat(shipwrecks): period picker like air accidents, sharper icons - Replace the four era chips with the start and end year pickers the air-accidents layer uses (the same RowRange control, ported as is); the era colours stay as a legend under the row. - Rasterize the boat marker at 144 px so large markers stay sharp. Co-Authored-By: Claude Opus 5.5 --- DATA_SOURCES.md | 2 +- docs/CURRENT-STATE.md | 16 +++-- scripts/format-scope.json | 2 + scripts/package-boundaries.json | 7 ++ src/i18n/locales/ar.json | 8 ++- src/i18n/locales/de.json | 8 ++- src/i18n/locales/es.json | 8 ++- src/i18n/locales/fr.json | 8 ++- src/i18n/locales/it.json | 8 ++- src/i18n/locales/ja.json | 8 ++- src/i18n/locales/pt.json | 8 ++- src/i18n/locales/ru.json | 8 ++- src/i18n/locales/uk.json | 8 ++- src/i18n/locales/zh-CN.json | 8 ++- src/i18n/locales/zh-Hant.json | 8 ++- src/layers/shipwrecks/eras.js | 12 ---- src/layers/shipwrecks/eras.test.mjs | 12 +--- src/layers/shipwrecks/index.js | 94 +++++++++++++++++++-------- src/layers/shipwrecks/period.js | 71 ++++++++++++++++++++ src/layers/shipwrecks/period.test.mjs | 38 +++++++++++ src/ui/layerPanel.js | 23 ++++++- src/ui/layerPanel/LayerRows.vue | 9 +++ src/ui/layerPanel/RowRange.vue | 40 ++++++++++++ src/ui/layerPanel/layerRows.test.mjs | 59 +++++++++++++++++ src/ui/styles/radio.css | 37 +++++++++++ 25 files changed, 439 insertions(+), 71 deletions(-) create mode 100644 src/layers/shipwrecks/period.js create mode 100644 src/layers/shipwrecks/period.test.mjs create mode 100644 src/ui/layerPanel/RowRange.vue diff --git a/DATA_SOURCES.md b/DATA_SOURCES.md index 805771b67..6bababb81 100644 --- a/DATA_SOURCES.md +++ b/DATA_SOURCES.md @@ -40,7 +40,7 @@ How to read this: | **NIFC WFIGS** (Wildland Fire Interagency Geospatial Services, ArcGIS feature service) | Fire Perimeters layer: current interagency wildfire incident perimeters, containment, and incident facts | U.S. public domain (interagency wildland-fire data published through the [NIFC Open Data portal](https://data-nifc.opendata.arcgis.com/)); fetched keyless through `/api/fire-perimeters` (5-minute server cache) with `exceededTransferLimit` paging | "Wildfire perimeters: National Interagency Fire Center (WFIGS)" | | **S2 Underground GhostMaps** (`github.com/s2underground/GhostMaps`) | S2 GhostMaps layer: the current edition of S2's KMZ intel products (Common Intelligence Picture, 30-day kinetic pull, Border Crisis Map, Iran and Yemen products, newest incident drop). Keyless. `/api/ghostmaps` reads the branch head from git's ref advertisement every 15 s (`GHOSTMAPS_POLL_SECONDS`, minimum 5 s), lists the tree through the GitHub REST API only when the head changes (optional `GITHUB_TOKEN`), downloads files by commit-pinned raw URLs into `.gev-cache/ghostmaps/` and pushes new catalogs to browsers over server-sent events | [CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/) (repository README: "S2 Underground © 2025 by S2A1"); non-commercial, attribution required; files are fetched at runtime, never stored in this repository | "S2 GhostMaps intel products: S2 Underground © by S2A1, CC BY-NC-SA 4.0" — shown in-app | | **EMODnet Human Activities — Ship wrecks** (`ows.emodnet-humanactivities.eu/wfs`, layer `emodnet:heritageshipwrecks`) | Shipwrecks layer: about 7,000 wrecks in European waters (name, sinking year and text, vessel type, least depth and its quality, position accuracy, period, cargo, protected status). Keyless WFS GeoJSON, fetched by `/api/shipwrecks` once a day; rows sourced from wrecksite.eu are skipped and text naming people is dropped | [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) (EMODnet catalogue record `e965088b-a265-4517-84df-c49b156af8a7`; data originator AND-International, compiled from SHOM, National Monuments Service, Historic England and the Oxford Roman Economy Project); fetched at runtime, not stored in this repository | "Shipwrecks (Europe): EMODnet Human Activities (data originator AND-International, …), CC BY 4.0" — shown in-app | -| **Wikidata — shipwrecks** (`query.wikidata.org/sparql`) | Shipwrecks layer: shipwreck items (Q852190) with a coordinate and at least one Wikipedia article: name, ship type, sinking date, death count, description and article link. Keyless, fetched by `/api/shipwrecks` once a day | [CC0](https://creativecommons.org/publicdomain/zero/1.0/); fetched at runtime | "Shipwrecks (worldwide): Wikidata (CC0)" — shown in-app | +| **Wikidata — shipwrecks** (`query.wikidata.org/sparql`) | Shipwrecks layer: shipwreck items (Q852190) with a coordinate and at least one Wikipedia article, plus sinking events (Q906512, where the death toll lives): name, ship type, sinking date with its precision, deaths and survivors (counts only), description and article link. Keyless, fetched by `/api/shipwrecks` once a day | [CC0](https://creativecommons.org/publicdomain/zero/1.0/); fetched at runtime | "Shipwrecks (worldwide): Wikidata (CC0)" — shown in-app | | **InciWeb** (inciweb.wildfire.gov) | Per-incident "InciWeb ↗" card links to official incident pages (narratives, evacuation/closure notices) | U.S. government public incident information. Links are matched best-effort by incident name and state, with incident page origin and update times checked on selection. Same-origin `/api/fire-perimeters/inciweb` routes cache the catalog for 1 hour and publication metadata for 30 minutes; linked pages remain InciWeb content | "Incident information: InciWeb (inciweb.wildfire.gov)" | | **FAA Special Use Airspace** (`services6.arcgis.com` FeatureServer `Special_Use_Airspace`) | Prohibited & Restricted Airspace layer: US prohibited (P) and restricted (R) special-use airspace polygons (not the UAS Facility Map or UAS flight restrictions), altitude limits from the `*_VAL`/`*_UOM`/`*_CODE` fields, times of use, and controlling agency | U.S. public domain (FAA aeronautical data published through the [FAA AIS Open Data portal](https://adds-faa.opendata.arcgis.com/)); fetched keyless through `/api/drone-airspace` (1-hour server cache). Informational only — not a substitute for official UAS flight-planning tools | "Prohibited & restricted airspace: FAA Special Use Airspace" | | **OpenFreeMap / OpenMapTiles** | Vector tiles | OpenStreetMap data under ODbL 1.0 | OpenFreeMap © OpenMapTiles | diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index e0df74333..dd7838b7c 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -116,14 +116,18 @@ read: EMODnet's long histories (`ship_char`, `obj_desc`) are not, and any sinking or cargo text that names a person (owner, master, a diver who reported it) is dropped whole; deaths appear only as a Wikidata count. -The globe draws a small hull marker per wreck, ground-clamped with the depth -test off and the horizon cull GhostMaps uses, coloured by era: before 1900 +The globe draws a round marker with a hull and mast per wreck, ground-clamped +with the depth test off and the horizon cull GhostMaps uses, sized by deaths as +on Air accidents and coloured by era (a legend under the row): before 1900 (ancient wrecks dated only by period count here), 1900–1945, after 1945, and -date unknown. Four row chips show or hide each era (session-only, not in the -share link). Clicking a marker opens a `stateless` card with the name, vessel -type, sinking date or year (or the archaeological dating), what happened, deaths, +date unknown. A period filter under the row picks a start year and an end year +side by side, the same control as Air accidents (two pickers over the years in +the data; a reversed pair is swapped); undated wrecks show only when every year +is selected. The filter is session-only (not in the share link). Clicking a marker opens a `stateless` card laid out like the air-accident card: deaths and +survivors first, then the sinking date or year (or the archaeological dating) and +waters, vessel type, what happened, least depth and its quality, how well the position is known, period notes or -the Wikidata description, cargo or finds, protected status, waters and source. +the Wikidata description, cargo or finds, protected status and source. Clicking the card opens the Wikipedia article (else the Wikidata item), the wreck's own web page when EMODnet lists one, else EMODnet's portal. Voice does not toggle this layer yet (prompt budget, as for the airspace layer). diff --git a/scripts/format-scope.json b/scripts/format-scope.json index d3eb3d95b..16b5e1ac5 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -1214,6 +1214,7 @@ "src/data/firmsIntensity.js", "src/data/firmsIntensity.test.mjs", "src/ui/layerPanel/RowSwitch.vue", + "src/ui/layerPanel/RowRange.vue", "src/ui/layerPanel/RowSlider.vue", "src/sources/phaseTiming.test.mjs", "scripts/build-census-places.mjs", @@ -1271,5 +1272,6 @@ "src/layers/shipwrecks/records.test.mjs", "src/layers/shipwrecks/cards.test.mjs", "src/layers/shipwrecks/eras.test.mjs", + "src/layers/shipwrecks/period.test.mjs", "src/data/shipwrecksProxy.test.mjs" ] diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 7460d06d2..024982e83 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -686,6 +686,7 @@ "src/ui/rail/focusSafeChildren.js", "src/ui/layerPanel/RowText.vue", "src/ui/layerPanel/RowSwitch.vue", + "src/ui/layerPanel/RowRange.vue", "src/ui/layerPanel/RowSlider.vue", "src/ui/railTimeline.js", "src/ui/clearLayersControl.js", @@ -1023,6 +1024,7 @@ "src/ui/rail/focusSafeChildren.js", "src/ui/layerPanel/RowText.vue", "src/ui/layerPanel/RowSwitch.vue", + "src/ui/layerPanel/RowRange.vue", "src/ui/layerPanel/RowSlider.vue", "src/ui/railTimeline.js", "src/ui/layers.js", @@ -2812,6 +2814,7 @@ "src/ui/rail/focusSafeChildren.js", "src/ui/layerPanel/RowText.vue", "src/ui/layerPanel/RowSwitch.vue", + "src/ui/layerPanel/RowRange.vue", "src/ui/layerPanel/RowSlider.vue", "src/ui/railTimeline.js", "src/ui/layers.js", @@ -2945,6 +2948,7 @@ "src/layers/shipwrecks/records.js", "src/layers/shipwrecks/cards.js", "src/layers/shipwrecks/eras.js", + "src/layers/shipwrecks/period.js", "src/app/layers/droneAirspace.js", "src/layers/droneAirspace/index.js", "src/layers/droneAirspace/source.js", @@ -3702,6 +3706,7 @@ "src/layers/shipwrecks/records.js", "src/layers/shipwrecks/cards.js", "src/layers/shipwrecks/eras.js", + "src/layers/shipwrecks/period.js", "src/app/layers/droneAirspace.js", "src/layers/droneAirspace/index.js", "src/layers/droneAirspace/source.js", @@ -4769,6 +4774,7 @@ "src/layers/shipwrecks/records.js", "src/layers/shipwrecks/cards.js", "src/layers/shipwrecks/eras.js", + "src/layers/shipwrecks/period.js", "src/sources/httpBody.js", "src/data/geoFileImport.js", "src/i18n/marker.js", @@ -4802,6 +4808,7 @@ "src/layers/shipwrecks/records.js", "src/layers/shipwrecks/cards.js", "src/layers/shipwrecks/eras.js", + "src/layers/shipwrecks/period.js", "src/layers/ghostMaps/catalog.js", "src/sources/httpBody.js", "src/i18n/marker.js" diff --git a/src/i18n/locales/ar.json b/src/i18n/locales/ar.json index 147d9e307..7268d22ae 100644 --- a/src/i18n/locales/ar.json +++ b/src/i18n/locales/ar.json @@ -3439,5 +3439,11 @@ "Fatalities: {count}": "الوفيات: {count}", "Survivors: {count}": "الناجون: {count}", "Click the card to open the article ↗": "انقر على البطاقة لفتح المقالة ↗", - "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "يأتي حطام السفن التراثي الأوروبي من EMODnet Human Activities، ويأتي الحطام البارز في العالم من ويكي بيانات. يبيّن اللون متى غرقت السفينة، ويكبر حجم العلامة مع عدد الوفيات. انقر على علامة لعرض بطاقتها." + "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "يأتي حطام السفن التراثي الأوروبي من EMODnet Human Activities، ويأتي الحطام البارز في العالم من ويكي بيانات. يبيّن اللون متى غرقت السفينة، ويكبر حجم العلامة مع عدد الوفيات. انقر على علامة لعرض بطاقتها.", + "All years": "كل السنوات", + "Period": "الفترة", + "From": "من", + "To": "إلى", + "First year of the shipwreck period": "السنة الأولى من فترة الغرق", + "Last year of the shipwreck period": "السنة الأخيرة من فترة الغرق" } diff --git a/src/i18n/locales/de.json b/src/i18n/locales/de.json index cbcf280e2..29dcf5454 100644 --- a/src/i18n/locales/de.json +++ b/src/i18n/locales/de.json @@ -3135,5 +3135,11 @@ "Fatalities: {count}": "Todesopfer: {count}", "Survivors: {count}": "Überlebende: {count}", "Click the card to open the article ↗": "Karte anklicken, um den Artikel zu öffnen ↗", - "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "Europäische Kulturerbe-Wracks stammen von EMODnet Human Activities, bekannte Wracks weltweit von Wikidata. Die Farbe zeigt, wann das Schiff sank; die Markierung wächst mit der Zahl der Todesopfer. Klicke auf eine Markierung für ihre Karte." + "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "Europäische Kulturerbe-Wracks stammen von EMODnet Human Activities, bekannte Wracks weltweit von Wikidata. Die Farbe zeigt, wann das Schiff sank; die Markierung wächst mit der Zahl der Todesopfer. Klicke auf eine Markierung für ihre Karte.", + "All years": "Alle Jahre", + "Period": "Zeitraum", + "From": "Von", + "To": "Bis", + "First year of the shipwreck period": "Erstes Jahr des Schiffbruch-Zeitraums", + "Last year of the shipwreck period": "Letztes Jahr des Schiffbruch-Zeitraums" } diff --git a/src/i18n/locales/es.json b/src/i18n/locales/es.json index 6df928b0a..b6e440344 100644 --- a/src/i18n/locales/es.json +++ b/src/i18n/locales/es.json @@ -3211,5 +3211,11 @@ "Fatalities: {count}": "Fallecidos: {count}", "Survivors: {count}": "Supervivientes: {count}", "Click the card to open the article ↗": "Haz clic en la ficha para abrir el artículo ↗", - "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "Los pecios históricos europeos proceden de EMODnet Human Activities; los naufragios notables de todo el mundo, de Wikidata. El color indica cuándo se hundió el barco; el marcador crece con el número de muertos. Haz clic en un marcador para ver su ficha." + "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "Los pecios históricos europeos proceden de EMODnet Human Activities; los naufragios notables de todo el mundo, de Wikidata. El color indica cuándo se hundió el barco; el marcador crece con el número de muertos. Haz clic en un marcador para ver su ficha.", + "All years": "Todos los años", + "Period": "Periodo", + "From": "Desde", + "To": "Hasta", + "First year of the shipwreck period": "Primer año del periodo de naufragios", + "Last year of the shipwreck period": "Último año del periodo de naufragios" } diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json index b9b53c48d..8aac9e0a0 100644 --- a/src/i18n/locales/fr.json +++ b/src/i18n/locales/fr.json @@ -3211,5 +3211,11 @@ "Fatalities: {count}": "Morts : {count}", "Survivors: {count}": "Survivants : {count}", "Click the card to open the article ↗": "Cliquez sur la fiche pour ouvrir l'article ↗", - "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "Les épaves patrimoniales européennes viennent d'EMODnet Human Activities ; les épaves notables du monde entier viennent de Wikidata. La couleur indique quand le navire a coulé ; le repère grossit avec le nombre de morts. Cliquez sur un repère pour voir sa fiche." + "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "Les épaves patrimoniales européennes viennent d'EMODnet Human Activities ; les épaves notables du monde entier viennent de Wikidata. La couleur indique quand le navire a coulé ; le repère grossit avec le nombre de morts. Cliquez sur un repère pour voir sa fiche.", + "All years": "Toutes les années", + "Period": "Période", + "From": "Du", + "To": "Au", + "First year of the shipwreck period": "Première année de la période des naufrages", + "Last year of the shipwreck period": "Dernière année de la période des naufrages" } diff --git a/src/i18n/locales/it.json b/src/i18n/locales/it.json index 9310da82c..6d8a79983 100644 --- a/src/i18n/locales/it.json +++ b/src/i18n/locales/it.json @@ -3211,5 +3211,11 @@ "Fatalities: {count}": "Vittime: {count}", "Survivors: {count}": "Sopravvissuti: {count}", "Click the card to open the article ↗": "Fai clic sulla scheda per aprire l'articolo ↗", - "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "I relitti storici europei provengono da EMODnet Human Activities; i relitti noti di tutto il mondo da Wikidata. Il colore indica quando la nave è affondata; l'indicatore cresce con il numero di vittime. Fai clic su un indicatore per la sua scheda." + "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "I relitti storici europei provengono da EMODnet Human Activities; i relitti noti di tutto il mondo da Wikidata. Il colore indica quando la nave è affondata; l'indicatore cresce con il numero di vittime. Fai clic su un indicatore per la sua scheda.", + "All years": "Tutti gli anni", + "Period": "Periodo", + "From": "Dal", + "To": "Al", + "First year of the shipwreck period": "Primo anno del periodo dei naufragi", + "Last year of the shipwreck period": "Ultimo anno del periodo dei naufragi" } diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.json index 4a1edfb44..f1a5b6b54 100644 --- a/src/i18n/locales/ja.json +++ b/src/i18n/locales/ja.json @@ -3059,5 +3059,11 @@ "Fatalities: {count}": "死者: {count}", "Survivors: {count}": "生存者: {count}", "Click the card to open the article ↗": "カードをクリックして記事を開く ↗", - "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "欧州の歴史的な難破船はEMODnet Human Activities、世界の著名な難破船はWikidataによります。色は沈没した時期を示し、マーカーは死者数に応じて大きくなります。マーカーをクリックするとカードが開きます。" + "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "欧州の歴史的な難破船はEMODnet Human Activities、世界の著名な難破船はWikidataによります。色は沈没した時期を示し、マーカーは死者数に応じて大きくなります。マーカーをクリックするとカードが開きます。", + "All years": "全期間", + "Period": "期間", + "From": "開始", + "To": "終了", + "First year of the shipwreck period": "難破の期間の開始年", + "Last year of the shipwreck period": "難破の期間の終了年" } diff --git a/src/i18n/locales/pt.json b/src/i18n/locales/pt.json index 1c9b46418..73daed8c6 100644 --- a/src/i18n/locales/pt.json +++ b/src/i18n/locales/pt.json @@ -3211,5 +3211,11 @@ "Fatalities: {count}": "Mortos: {count}", "Survivors: {count}": "Sobreviventes: {count}", "Click the card to open the article ↗": "Clique na ficha para abrir o artigo ↗", - "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "Os naufrágios históricos europeus vêm do EMODnet Human Activities; os naufrágios notáveis do mundo vêm do Wikidata. A cor mostra quando o navio afundou; o marcador cresce com o número de mortos. Clique num marcador para ver a ficha." + "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "Os naufrágios históricos europeus vêm do EMODnet Human Activities; os naufrágios notáveis do mundo vêm do Wikidata. A cor mostra quando o navio afundou; o marcador cresce com o número de mortos. Clique num marcador para ver a ficha.", + "All years": "Todos os anos", + "Period": "Período", + "From": "Início", + "To": "Fim", + "First year of the shipwreck period": "Primeiro ano do período dos naufrágios", + "Last year of the shipwreck period": "Último ano do período dos naufrágios" } diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json index 1d4dbce42..bea9bea8f 100644 --- a/src/i18n/locales/ru.json +++ b/src/i18n/locales/ru.json @@ -3287,5 +3287,11 @@ "Fatalities: {count}": "Погибших: {count}", "Survivors: {count}": "Выживших: {count}", "Click the card to open the article ↗": "Нажмите на карточку, чтобы открыть статью ↗", - "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "Исторические затонувшие суда Европы — из EMODnet Human Activities, известные кораблекрушения по всему миру — из Wikidata. Цвет показывает, когда судно затонуло; маркер растёт с числом погибших. Нажмите на маркер, чтобы открыть карточку." + "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "Исторические затонувшие суда Европы — из EMODnet Human Activities, известные кораблекрушения по всему миру — из Wikidata. Цвет показывает, когда судно затонуло; маркер растёт с числом погибших. Нажмите на маркер, чтобы открыть карточку.", + "All years": "Все годы", + "Period": "Период", + "From": "С", + "To": "По", + "First year of the shipwreck period": "Первый год периода кораблекрушений", + "Last year of the shipwreck period": "Последний год периода кораблекрушений" } diff --git a/src/i18n/locales/uk.json b/src/i18n/locales/uk.json index d8b9296f0..0ee107b67 100644 --- a/src/i18n/locales/uk.json +++ b/src/i18n/locales/uk.json @@ -3287,5 +3287,11 @@ "Fatalities: {count}": "Загиблих: {count}", "Survivors: {count}": "Тих, хто вижив: {count}", "Click the card to open the article ↗": "Натисніть картку, щоб відкрити статтю ↗", - "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "Історичні затонулі судна Європи — з EMODnet Human Activities, відомі корабельні аварії світу — з Wikidata. Колір показує, коли судно затонуло; маркер збільшується з кількістю загиблих. Натисніть маркер, щоб відкрити картку." + "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "Історичні затонулі судна Європи — з EMODnet Human Activities, відомі корабельні аварії світу — з Wikidata. Колір показує, коли судно затонуло; маркер збільшується з кількістю загиблих. Натисніть маркер, щоб відкрити картку.", + "All years": "Усі роки", + "Period": "Період", + "From": "З", + "To": "По", + "First year of the shipwreck period": "Перший рік періоду корабельних аварій", + "Last year of the shipwreck period": "Останній рік періоду корабельних аварій" } diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json index 90684d7d5..dbdcd7c50 100644 --- a/src/i18n/locales/zh-CN.json +++ b/src/i18n/locales/zh-CN.json @@ -3059,5 +3059,11 @@ "Fatalities: {count}": "遇难:{count}", "Survivors: {count}": "幸存者:{count}", "Click the card to open the article ↗": "点击卡片打开文章 ↗", - "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "欧洲历史沉船来自 EMODnet Human Activities;全球知名沉船来自 Wikidata。颜色表示船只沉没的时期,标记大小随遇难人数增加。点击标记查看卡片。" + "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "欧洲历史沉船来自 EMODnet Human Activities;全球知名沉船来自 Wikidata。颜色表示船只沉没的时期,标记大小随遇难人数增加。点击标记查看卡片。", + "All years": "所有年份", + "Period": "时段", + "From": "起", + "To": "止", + "First year of the shipwreck period": "沉船时段的起始年份", + "Last year of the shipwreck period": "沉船时段的结束年份" } diff --git a/src/i18n/locales/zh-Hant.json b/src/i18n/locales/zh-Hant.json index b1cbd78b3..4033310d7 100644 --- a/src/i18n/locales/zh-Hant.json +++ b/src/i18n/locales/zh-Hant.json @@ -3059,5 +3059,11 @@ "Fatalities: {count}": "罹難:{count}", "Survivors: {count}": "倖存者:{count}", "Click the card to open the article ↗": "點擊卡片開啟文章 ↗", - "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "歐洲歷史沉船來自 EMODnet Human Activities;全球知名沉船來自 Wikidata。顏色表示船隻沉沒的時期,標記大小隨罹難人數增加。點擊標記查看卡片。" + "European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "歐洲歷史沉船來自 EMODnet Human Activities;全球知名沉船來自 Wikidata。顏色表示船隻沉沒的時期,標記大小隨罹難人數增加。點擊標記查看卡片。", + "All years": "所有年份", + "Period": "時段", + "From": "起", + "To": "迄", + "First year of the shipwreck period": "沉船時段的起始年份", + "Last year of the shipwreck period": "沉船時段的結束年份" } diff --git a/src/layers/shipwrecks/eras.js b/src/layers/shipwrecks/eras.js index 4e9c2a1ff..ec7b54245 100644 --- a/src/layers/shipwrecks/eras.js +++ b/src/layers/shipwrecks/eras.js @@ -19,15 +19,3 @@ export function eraOf(record) { if (year <= 1945) return '1900-1945'; return 'after-1945'; } - -/** - * Normalize a requested set of eras; unknown names are ignored and an empty - * or missing request keeps the current set. - * @param {unknown} value Array of era ids. - * @param {Set} current - * @returns {Set} - */ -export function normalizeEras(value, current) { - if (!Array.isArray(value)) return new Set(current); - return new Set(value.filter((era) => SHIPWRECK_ERAS.includes(era))); -} diff --git a/src/layers/shipwrecks/eras.test.mjs b/src/layers/shipwrecks/eras.test.mjs index 3891d60e7..41de855e8 100644 --- a/src/layers/shipwrecks/eras.test.mjs +++ b/src/layers/shipwrecks/eras.test.mjs @@ -1,6 +1,6 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { SHIPWRECK_ERAS, eraOf, normalizeEras } from './eras.js'; +import { eraOf } from './eras.js'; test('each wreck falls in one era', () => { assert.equal(eraOf({ year: 1588 }), 'before-1900'); @@ -11,13 +11,3 @@ test('each wreck falls in one era', () => { assert.equal(eraOf({ year: null }), 'undated'); assert.equal(eraOf(null), 'undated'); }); - -test('era requests keep known eras only', () => { - const all = new Set(SHIPWRECK_ERAS); - assert.deepEqual( - [...normalizeEras(['after-1945', 'bogus'], all)], - ['after-1945'], - ); - assert.deepEqual([...normalizeEras('after-1945', all)], SHIPWRECK_ERAS); - assert.deepEqual([...normalizeEras([], all)], []); -}); diff --git a/src/layers/shipwrecks/index.js b/src/layers/shipwrecks/index.js index 05c2c64a4..ad8f53ae9 100644 --- a/src/layers/shipwrecks/index.js +++ b/src/layers/shipwrecks/index.js @@ -2,10 +2,17 @@ import * as Cesium from 'cesium'; import { formatNumber, msg, t, tn } from '../../i18n/index.js'; import { createHorizonCull } from '../streetLevel/view.js'; import { ERA_COLORS, ERA_LABELS, describeShipwreck } from './cards.js'; -import { SHIPWRECK_ERAS, eraOf, normalizeEras } from './eras.js'; +import { SHIPWRECK_ERAS, eraOf } from './eras.js'; +import { + inPeriod, + normalizePeriod, + periodRange, + yearExtent, +} from './period.js'; export * from './records.js'; export * from './cards.js'; export * from './eras.js'; +export * from './period.js'; export { createShipwrecksSource } from './source.js'; export const SHIPWRECKS_LAYER_ID = 'shipwrecks'; @@ -28,13 +35,14 @@ export function markerPixelSize(casualties) { /** * A round marker in the era's colour with a sinking hull and mast in the - * middle, as an SVG data URL. + * middle, as an SVG data URL. It is rasterized at 144 px, four times the + * largest marker, so big markers stay sharp on high-density screens. * @param {string} color CSS colour. * @returns {string} */ export function wreckMarkerImage(color) { const svg = - `` + + `` + `` + `` + `` + @@ -69,7 +77,9 @@ export function createShipwrecksLayer({ let _selectedId = null; let _selectedCardId = null; let _selectedLink = null; - let _eras = new Set(SHIPWRECK_ERAS); + let _period = { from: null, to: null }; + let _extent = null; + let _range = null; const _images = Object.fromEntries( SHIPWRECK_ERAS.map((era) => [era, wreckMarkerImage(ERA_COLORS[era])]), ); @@ -86,16 +96,16 @@ export function createShipwrecksLayer({ onChange: render, }); - /** Shown: its era chip is on. */ + /** Shown: its year is inside the period (undated ones only for all years). */ function visible(record) { - return Boolean(record) && _eras.has(eraOf(record)); + return Boolean(record) && inPeriod(record, _range); } function applyPin(pin) { pin.entity.show = pin.inFront && visible(pin.record); } - /** Re-apply the era chips to every marker and the open card. */ + /** Re-apply the period to every marker and the open card. */ function applyFilter() { for (const pin of _pins) applyPin(pin); if (_selectedId && !visible(_records.get(_selectedId))) clearSelection(); @@ -105,6 +115,8 @@ export function createShipwrecksLayer({ function rebuild(records) { _records = new Map(records.map((record) => [record.id, record])); + _extent = yearExtent(records); + _range = periodRange(_period, _extent); _pins = []; if (!_dataSource) return; _dataSource.entities.suspendEvents(); @@ -257,18 +269,46 @@ export function createShipwrecksLayer({ picking?.unregisterPickOwner?.(SHIPWRECKS_LAYER_ID); } - function toggleEra(era) { - if (_eras.has(era)) _eras.delete(era); - else _eras.add(era); - applyFilter(); - } - function countOf(era) { let count = 0; - for (const record of _records.values()) if (eraOf(record) === era) count++; + for (const record of _records.values()) + if (eraOf(record) === era && inPeriod(record, _range)) count++; return count; } + /** The start and end year pickers, side by side, as on Air accidents. */ + function periodControls() { + if (!_extent || _extent.min === _extent.max) return {}; + const range = periodRange(_period, _extent); + const valueText = range.all + ? t('All years') + : range.from === range.to + ? String(range.from) + : `${range.from}–${range.to}`; + const options = []; + for (let year = _extent.max; year >= _extent.min; year--) + options.push({ value: year, label: String(year) }); + return { + range: { + id: 'period', + label: t('Period'), + valueText, + from: { + label: t('From'), + ariaLabel: t('First year of the shipwreck period'), + value: range.from, + }, + to: { + label: t('To'), + ariaLabel: t('Last year of the shipwreck period'), + value: range.to, + }, + options, + params: (end, value) => ({ [end]: Number(value) }), + }, + }; + } + const layer = { id: SHIPWRECKS_LAYER_ID, name: 'Shipwrecks', @@ -347,17 +387,16 @@ export function createShipwrecksLayer({ _rowListener = null; }, - /** The era filter: `eras` lists the era chips that are on. */ + /** The period filter: `from` and `to` are years (null = oldest / latest in the data). */ getParams() { - return { eras: SHIPWRECK_ERAS.filter((era) => _eras.has(era)) }; + return { ..._period }; }, setParams(params = {}) { - if (!('eras' in params)) return true; - const next = normalizeEras(params.eras, _eras); - if (next.size === _eras.size && [...next].every((era) => _eras.has(era))) - return true; - _eras = next; + const next = normalizePeriod(params, _period); + if (next.from === _period.from && next.to === _period.to) return true; + _period = next; + _range = periodRange(_period, _extent); applyFilter(); return true; }, @@ -368,17 +407,16 @@ export function createShipwrecksLayer({ getRowControls() { return { - chips: SHIPWRECK_ERAS.map((era) => ({ - id: era, - label: t(ERA_LABELS[era]), - active: _eras.has(era), + chips: [], + ...periodControls(), + // The colours are a legend: when the ship sank. + legend: SHIPWRECK_ERAS.map((era) => ({ + text: t(ERA_LABELS[era]), color: ERA_COLORS[era], - title: tn(countOf(era), '{count} wreck', '{count} wrecks', { + blurb: tn(countOf(era), '{count} wreck', '{count} wrecks', { count: formatNumber(countOf(era)), }), - onClick: () => toggleEra(era), })), - legend: [], info: t('EMODnet (European waters) · Wikidata (worldwide)'), infoTitle: t( 'European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.', diff --git a/src/layers/shipwrecks/period.js b/src/layers/shipwrecks/period.js new file mode 100644 index 000000000..f0cfa26e2 --- /dev/null +++ b/src/layers/shipwrecks/period.js @@ -0,0 +1,71 @@ +/** + * The sinking year, or null when it is unknown (ancient wrecks dated only by + * period, "C1st AD", have none). + */ +export function recordYear(record) { + return Number.isInteger(record?.year) ? record.year : null; +} + +/** First and last year present in the records (null when none is dated). */ +export function yearExtent(records) { + let min = Infinity; + let max = -Infinity; + for (const record of records) { + const year = recordYear(record); + if (year === null) continue; + if (year < min) min = year; + if (year > max) max = year; + } + return Number.isFinite(min) ? { min, max } : null; +} + +function yearParam(value) { + if (value === null) return null; + const year = + typeof value === 'string' && /^-?\d+$/.test(value) ? Number(value) : value; + return Number.isInteger(year) && Math.abs(year) < 10000 ? year : undefined; +} + +/** + * Merge a (partial) period request into the current one. `from: null` means + * the first year in the data and `to: null` the latest; an invalid year keeps + * the current one. + * @param {{from?: number|string|null, to?: number|string|null}} params + * @param {{from: number|null, to: number|null}} current + * @returns {{from: number|null, to: number|null}} + */ +export function normalizePeriod( + params = {}, + current = { from: null, to: null }, +) { + const next = { ...current }; + for (const end of ['from', 'to']) { + if (!(end in params)) continue; + const year = yearParam(params[end]); + if (year !== undefined) next[end] = year; + } + return next; +} + +/** + * The inclusive year range a period covers over the data's extent. Years are + * clamped to the data, and a start after the end is read as the reverse. + * @returns {{from: number, to: number, all: boolean}|null} + */ +export function periodRange(period, extent) { + if (!extent) return null; + const clamp = (year, fallback) => + Math.min(extent.max, Math.max(extent.min, year ?? fallback)); + const start = clamp(period.from, extent.min); + const end = clamp(period.to, extent.max); + const from = Math.min(start, end); + const to = Math.max(start, end); + return { from, to, all: from === extent.min && to === extent.max }; +} + +/** Whether a record falls in the range; undated records only when all years show. */ +export function inPeriod(record, range) { + if (!range || range.all) return true; + const year = recordYear(record); + return year !== null && year >= range.from && year <= range.to; +} diff --git a/src/layers/shipwrecks/period.test.mjs b/src/layers/shipwrecks/period.test.mjs new file mode 100644 index 000000000..7839a2840 --- /dev/null +++ b/src/layers/shipwrecks/period.test.mjs @@ -0,0 +1,38 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { + inPeriod, + normalizePeriod, + periodRange, + recordYear, + yearExtent, +} from './period.js'; + +const RECORDS = [ + { year: 1588 }, + { year: 1912 }, + { year: 2012 }, + { year: null, ancient: true }, +]; + +test('years come from the record; the extent ignores undated wrecks', () => { + assert.equal(recordYear(RECORDS[1]), 1912); + assert.equal(recordYear(RECORDS[3]), null); + assert.deepEqual(yearExtent(RECORDS), { min: 1588, max: 2012 }); + assert.equal(yearExtent([{ year: null }]), null); +}); + +test('all years show every wreck; a narrower period hides undated ones', () => { + const extent = yearExtent(RECORDS); + const all = periodRange({ from: null, to: null }, extent); + assert.deepEqual(all, { from: 1588, to: 2012, all: true }); + assert.ok(RECORDS.every((record) => inPeriod(record, all))); + const wars = periodRange(normalizePeriod({ from: '1914', to: 1945 }), extent); + assert.deepEqual( + RECORDS.map((record) => inPeriod(record, wars)), + [false, false, false, false], + ); + const reversed = periodRange({ from: 1950, to: 1900 }, extent); + assert.deepEqual(reversed, { from: 1900, to: 1950, all: false }); + assert.equal(inPeriod(RECORDS[1], reversed), true); +}); diff --git a/src/ui/layerPanel.js b/src/ui/layerPanel.js index 4c16b047c..ea62ef39b 100644 --- a/src/ui/layerPanel.js +++ b/src/ui/layerPanel.js @@ -445,6 +445,8 @@ export class LayerPanel { this._selectListItem(layerId, itemId, generation), onSlider: (layerId, sliderId, value) => this._moveSlider(layerId, sliderId, value, generation), + onRange: (layerId, rangeId, end, value) => + this._pickRangeEnd(layerId, rangeId, end, value, generation), }), id === null ? this._toggleContainer : this._groupContainers.get(id), ); @@ -474,7 +476,7 @@ export class LayerPanel { } /** - * A layer's row chips, one-of-many switch, slider, color legend, info line + * A layer's row chips, one-of-many switch, slider, start/end pickers, color legend, info line * and ordered list. The block * is hidden while the layer is off (or while a dependency owner has * surrendered it), so a quiet row stays quiet. Chips and list items are @@ -501,6 +503,7 @@ export class LayerPanel { const infoText = controls?.info ? String(controls.info) : ''; const segmented = controls?.segmented || null; const slider = controls?.slider || null; + const range = controls?.range || null; // The info line, once shown, stays in place and hides when empty. if (infoText) row.info = true; return { @@ -509,10 +512,12 @@ export class LayerPanel { legend.length === 0 && !infoText && !segmented && - !slider, + !slider && + !range, chips, segmented, slider, + range, legend, info: row.info ? { text: infoText, title: controls?.infoTitle || '' } @@ -577,6 +582,20 @@ export class LayerPanel { this.setLayerParams(id, slider.params(value), { origin: 'user' }); } + _pickRangeEnd(id, rangeId, end, value, generation = this._generation) { + if (this._destroyed || this._generation !== generation) return; + const range = this._rowControlsFor(id)?.range; + if ( + !range || + range.id !== rangeId || + (end !== 'from' && end !== 'to') || + typeof range.params !== 'function' || + !this.isEnabled(id) + ) + return; + this.setLayerParams(id, range.params(end, value), { origin: 'user' }); + } + _selectListItem(id, itemId, generation = this._generation) { if (this._destroyed || this._generation !== generation) return; const item = this._rowControlsFor(id)?.list?.items?.find( diff --git a/src/ui/layerPanel/LayerRows.vue b/src/ui/layerPanel/LayerRows.vue index 5f5d7c97e..81e2f31ed 100644 --- a/src/ui/layerPanel/LayerRows.vue +++ b/src/ui/layerPanel/LayerRows.vue @@ -1,6 +1,7 @@ @@ -68,6 +70,13 @@ defineProps({ :on-input=" (value) => onSlider(item.id, item.controls.slider.id, value) " + /> +// A row's start and end pickers on one line (e.g. the Air Accidents period). +// Both ends share one option list; `onSelect` reports which end moved +// ('from' or 'to') and the chosen option value. +defineProps({ + range: { type: Object, required: true }, + onSelect: { type: Function, default: () => {} }, +}); + + + diff --git a/src/ui/layerPanel/layerRows.test.mjs b/src/ui/layerPanel/layerRows.test.mjs index 966c41cb6..b0ccb178e 100644 --- a/src/ui/layerPanel/layerRows.test.mjs +++ b/src/ui/layerPanel/layerRows.test.mjs @@ -159,3 +159,62 @@ test('a row switch and slider render their markup and report choices', () => { assert.equal(segments[1].classList.contains('active'), true); render(null, container); }); + +test('a row range renders start and end pickers and reports which end moved', () => { + document.body.replaceChildren(); + const container = document.body.appendChild(document.createElement('div')); + const picks = []; + const item = { + ...row(false), + key: 'air-accidents', + id: 'air-accidents', + controls: { + hidden: false, + chips: [], + segmented: null, + slider: null, + range: { + id: 'period', + label: 'Period', + valueText: '2010–2024', + from: { label: 'From', ariaLabel: 'First year', value: 2010 }, + to: { label: 'To', ariaLabel: 'Last year', value: 2024 }, + options: [2024, 2010, 2007].map((year) => ({ + value: year, + label: String(year), + })), + }, + legend: [], + info: null, + list: null, + }, + }; + render( + h(LayerRows, { + items: [item], + onRange: (id, rangeId, end, value) => + picks.push([id, rangeId, end, value]), + }), + container, + ); + const block = container.querySelector('.data-toggle-range'); + assert.equal(block.dataset.rangeId, 'period'); + assert.equal( + block.querySelector('.data-toggle-slider-value').textContent, + '2010–2024', + ); + const [from, to] = block.querySelectorAll('select.data-toggle-range-select'); + assert.equal(from.getAttribute('aria-label'), 'First year'); + assert.equal(from.value, '2010'); + assert.equal(to.value, '2024'); + assert.deepEqual( + [...block.querySelectorAll('.data-toggle-range-caption')].map( + (caption) => caption.textContent, + ), + ['From', 'To'], + ); + to.value = '2007'; + to.dispatchEvent(new Event('change', { bubbles: true })); + assert.deepEqual(picks, [['air-accidents', 'period', 'to', '2007']]); + render(null, container); +}); diff --git a/src/ui/styles/radio.css b/src/ui/styles/radio.css index 91611bf4a..b69c18024 100644 --- a/src/ui/styles/radio.css +++ b/src/ui/styles/radio.css @@ -1067,6 +1067,43 @@ html:not([lang='en']) .data-row-list-text { letter-spacing: 0.8px; } +/* Optional start and end pickers on one line (Air Accidents period). The + shared field style paints each select. */ +.data-toggle-range { + flex-basis: 100%; + display: grid; + gap: 4px; + padding-top: 2px; +} + +.data-toggle-range-ends { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 8px; +} + +.data-toggle-range-end { + display: flex; + align-items: center; + gap: 6px; + min-width: 0; +} + +.data-toggle-range-caption { + font-family: var(--font-mono); + font-size: 8px; + letter-spacing: 1.2px; + color: var(--text-dim); + text-transform: uppercase; +} + +.data-toggle-range-select { + flex: 1; + min-width: 0; + min-height: 24px; + font: 10px/1 var(--font-mono); +} + /* Optional per-layer quantitative slider (Active Fires minimum FRP). The track is painted by the layer (`--slider-track`, a stepped color ramp), so the slider doubles as the marker legend; ticks sit under their thresholds. */ From 1199fe05c7d5fda1f9ba06d8646408516674fe6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Itallo=20Brand=C3=A3o?= <45429643+IMBrandao@users.noreply.github.com> Date: Thu, 5 Nov 2026 04:55:16 -0300 Subject: [PATCH 026/171] fix(shipwrecks): give the era legend its labels and counts The panel reads legend entries as label and count; the layer sent text, so each entry showed 'undefined'. Co-Authored-By: Claude Opus 5.5 --- src/layers/shipwrecks/index.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/layers/shipwrecks/index.js b/src/layers/shipwrecks/index.js index ad8f53ae9..21fbb11ed 100644 --- a/src/layers/shipwrecks/index.js +++ b/src/layers/shipwrecks/index.js @@ -411,7 +411,8 @@ export function createShipwrecksLayer({ ...periodControls(), // The colours are a legend: when the ship sank. legend: SHIPWRECK_ERAS.map((era) => ({ - text: t(ERA_LABELS[era]), + label: t(ERA_LABELS[era]), + count: countOf(era), color: ERA_COLORS[era], blurb: tn(countOf(era), '{count} wreck', '{count} wrecks', { count: formatNumber(countOf(era)), From b6ad32009fec418d1a5bbff4aa18adb1fbf5cd4c Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Thu, 5 Nov 2026 12:52:28 +0400 Subject: [PATCH 027/171] Say why Transit and Bike Share rows are empty outside coverage MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Over a city with no feed or system (London, Tokyo) both rows read "ON · — · never", the same as a feed that never answered. Transit already computed a coverage note but put it only in `coverage`, which the row does not show; Bike Share reported nothing at all. Both layers now report a `zoom-in` guidance status with a `statusMessage`: "Fly below 3,000 km to a covered region" / "No feed here yet · N regions available" for Transit, and "Fly below 48 km to a covered city" / "No bike share here yet · N systems available" for Bike Share. A loading or failed Bike Share city keeps its own text. Leaving coverage clears the layer's last-update time, so the row no longer dates data it no longer draws. The coverage-note translations move from the voice card into `translateStatusMessage` (ui/statusText.js), which the Layers row and the voice card now share. --- docs/CURRENT-STATE.md | 13 ++ src/i18n/locales/ar.json | 9 ++ src/i18n/locales/de.json | 5 + src/i18n/locales/es.json | 6 + src/i18n/locales/fr.json | 6 + src/i18n/locales/it.json | 6 + src/i18n/locales/ja.json | 4 + src/i18n/locales/pt.json | 6 + src/i18n/locales/ru.json | 7 ++ src/i18n/locales/uk.json | 7 ++ src/i18n/locales/zh-CN.json | 4 + src/i18n/locales/zh-Hant.json | 4 + src/layers/bikeshare/controls.js | 22 +++- src/layers/bikeshare/coverageStatus.test.mjs | 124 +++++++++++++++++++ src/layers/bikeshare/viewport.js | 3 + src/layers/transit/lifecycle.test.mjs | 39 ++++++ src/layers/transit/queries.js | 13 +- src/layers/transit/viewport.js | 3 + src/ui/layerPanel.js | 9 +- src/ui/layerPanel.test.mjs | 54 ++++++++ src/ui/statusText.js | 63 ++++++++++ src/ui/statusText.test.mjs | 58 ++++++++- src/voice/resultDisplay.js | 31 +---- 23 files changed, 459 insertions(+), 37 deletions(-) create mode 100644 src/layers/bikeshare/coverageStatus.test.mjs diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index f1244947d..8368eeacf 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1817,6 +1817,19 @@ Mapped-installation zoom guidance appears in the layer row without counting as a global loading failure. Guidance statuses do not suppress independent refresh errors. +Transit and Bike Share report the same kind of guidance when no feed or system +covers the view, instead of an undated `never`. Above their altitude gates the +rows read `GTFS-RT · Fly below 3,000 km to a covered region` and +`GBFS · Fly below 48 km to a covered city`; lower down over a city neither +covers (London, Tokyo) they read `GTFS-RT · No feed here yet · N regions +available` and `GBFS · No bike share here yet · N systems available`, N being +the enabled feeds and the catalogued systems. The +chip stays ON. A Bike Share city that is loading or failed keeps its own +loading or error text. Leaving every covered feed or system clears the layer's +last-update time, so the row never dates data it no longer draws. The same +English notes are the voice analyst's empty-result notes; both surfaces show +them translated through `translateStatusMessage` (`src/ui/statusText.js`). + ## Places and CCTV request bounds With a Google key configured, nearby and text search reject missing, blank, diff --git a/src/i18n/locales/ar.json b/src/i18n/locales/ar.json index c9fca14ce..b7193b9e8 100644 --- a/src/i18n/locales/ar.json +++ b/src/i18n/locales/ar.json @@ -2912,6 +2912,15 @@ "many": "لا مصدر بيانات هنا بعد · {n} منطقة متاحة", "other": "لا مصدر بيانات هنا بعد · {n} منطقة متاحة" }, + "Fly below {km} km to a covered city": "انخفض إلى ما دون {km} كم فوق مدينة مغطاة", + "No bike share here yet · {n} systems available": { + "zero": "لا دراجات مشتركة هنا بعد · {n} نظام متاح", + "one": "لا دراجات مشتركة هنا بعد · نظام واحد متاح ({n})", + "two": "لا دراجات مشتركة هنا بعد · نظامان متاحان ({n})", + "few": "لا دراجات مشتركة هنا بعد · {n} أنظمة متاحة", + "many": "لا دراجات مشتركة هنا بعد · {n} نظامًا متاحًا", + "other": "لا دراجات مشتركة هنا بعد · {n} نظام متاح" + }, "degraded": "متدهور", "stale": "متقادم", "partial": "جزئي", diff --git a/src/i18n/locales/de.json b/src/i18n/locales/de.json index bb683ed9f..57be9f388 100644 --- a/src/i18n/locales/de.json +++ b/src/i18n/locales/de.json @@ -2662,6 +2662,11 @@ "one": "Hier noch kein Feed · {n} Region verfügbar", "other": "Hier noch kein Feed · {n} Regionen verfügbar" }, + "Fly below {km} km to a covered city": "Unter {km} km Höhe zu einer abgedeckten Stadt fliegen", + "No bike share here yet · {n} systems available": { + "one": "Hier noch kein Bikesharing · {n} System verfügbar", + "other": "Hier noch kein Bikesharing · {n} Systeme verfügbar" + }, "degraded": "eingeschränkt", "stale": "veraltet", "partial": "teilweise", diff --git a/src/i18n/locales/es.json b/src/i18n/locales/es.json index 10dcbef8f..2a3bb478d 100644 --- a/src/i18n/locales/es.json +++ b/src/i18n/locales/es.json @@ -2821,6 +2821,12 @@ "many": "Aún no hay fuente aquí · {n} de regiones disponibles", "other": "Aún no hay fuente aquí · {n} regiones disponibles" }, + "Fly below {km} km to a covered city": "Desciende por debajo de {km} km sobre una ciudad con cobertura", + "No bike share here yet · {n} systems available": { + "one": "Aún no hay bicis compartidas aquí · {n} sistema disponible", + "many": "Aún no hay bicis compartidas aquí · {n} de sistemas disponibles", + "other": "Aún no hay bicis compartidas aquí · {n} sistemas disponibles" + }, "Wind speed field unavailable": "Campo de velocidad del viento no disponible", "Decoder feeds": "Fuentes del decodificador", "WebUSB + decoder feeds": "WebUSB + fuentes del decodificador", diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json index 108e56f36..57186643b 100644 --- a/src/i18n/locales/fr.json +++ b/src/i18n/locales/fr.json @@ -2531,6 +2531,12 @@ "many": "Pas encore de flux ici · {n} de régions disponibles", "other": "Pas encore de flux ici · {n} régions disponibles" }, + "Fly below {km} km to a covered city": "Descendez sous {km} km au-dessus d'une ville couverte", + "No bike share here yet · {n} systems available": { + "one": "Pas encore de vélos partagés ici · {n} système disponible", + "many": "Pas encore de vélos partagés ici · {n} de systèmes disponibles", + "other": "Pas encore de vélos partagés ici · {n} systèmes disponibles" + }, "degraded": "dégradé", "stale": "obsolète", "partial": "partiel", diff --git a/src/i18n/locales/it.json b/src/i18n/locales/it.json index 6768f93c7..cecbc7a03 100644 --- a/src/i18n/locales/it.json +++ b/src/i18n/locales/it.json @@ -2531,6 +2531,12 @@ "many": "Ancora nessun feed qui · {n} di regioni disponibili", "other": "Ancora nessun feed qui · {n} regioni disponibili" }, + "Fly below {km} km to a covered city": "Scendi sotto {km} km su una città coperta", + "No bike share here yet · {n} systems available": { + "one": "Ancora nessun bike sharing qui · {n} sistema disponibile", + "many": "Ancora nessun bike sharing qui · {n} di sistemi disponibili", + "other": "Ancora nessun bike sharing qui · {n} sistemi disponibili" + }, "degraded": "degradato", "stale": "obsoleto", "partial": "parziale", diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.json index b4566b4cb..47a84c9d4 100644 --- a/src/i18n/locales/ja.json +++ b/src/i18n/locales/ja.json @@ -2401,6 +2401,10 @@ "No feed here yet · {n} regions available": { "other": "ここにはまだフィードがありません · 利用可能な地域 {n}か所" }, + "Fly below {km} km to a covered city": "{km} km未満まで高度を下げ、カバー範囲内の都市へ移動してください", + "No bike share here yet · {n} systems available": { + "other": "ここにはまだシェアサイクルがありません · 利用可能なシステム {n}件" + }, "degraded": "性能低下", "stale": "更新遅延", "partial": "部分的", diff --git a/src/i18n/locales/pt.json b/src/i18n/locales/pt.json index 3f37cde2e..2ac851bc0 100644 --- a/src/i18n/locales/pt.json +++ b/src/i18n/locales/pt.json @@ -2533,6 +2533,12 @@ "many": "Ainda não há feed aqui · {n} de regiões disponíveis", "other": "Ainda não há feed aqui · {n} regiões disponíveis" }, + "Fly below {km} km to a covered city": "Desça abaixo de {km} km sobre uma cidade com cobertura", + "No bike share here yet · {n} systems available": { + "one": "Ainda não há bicicletas compartilhadas aqui · {n} sistema disponível", + "many": "Ainda não há bicicletas compartilhadas aqui · {n} de sistemas disponíveis", + "other": "Ainda não há bicicletas compartilhadas aqui · {n} sistemas disponíveis" + }, "degraded": "degradado", "stale": "desatualizado", "partial": "parcial", diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json index e279508ef..cba8c8796 100644 --- a/src/i18n/locales/ru.json +++ b/src/i18n/locales/ru.json @@ -2884,6 +2884,13 @@ "many": "Здесь пока нет потока данных · доступно {n} регионов", "other": "Здесь пока нет потока данных · доступно {n} региона" }, + "Fly below {km} km to a covered city": "Опуститесь ниже {km} км над городом с покрытием", + "No bike share here yet · {n} systems available": { + "one": "Здесь пока нет проката велосипедов · доступна {n} система", + "few": "Здесь пока нет проката велосипедов · доступны {n} системы", + "many": "Здесь пока нет проката велосипедов · доступно {n} систем", + "other": "Здесь пока нет проката велосипедов · доступно {n} системы" + }, "Wind speed field unavailable": "Поле скорости ветра недоступно", "Decoder feeds": "Потоки декодера", "WebUSB + decoder feeds": "WebUSB + потоки декодера", diff --git a/src/i18n/locales/uk.json b/src/i18n/locales/uk.json index 8c3b634b9..71054ea18 100644 --- a/src/i18n/locales/uk.json +++ b/src/i18n/locales/uk.json @@ -2595,6 +2595,13 @@ "many": "Тут поки немає потоку даних · доступно {n} регіонів", "other": "Тут поки немає потоку даних · доступно {n} регіону" }, + "Fly below {km} km to a covered city": "Опустіться нижче {km} км над містом із покриттям", + "No bike share here yet · {n} systems available": { + "one": "Тут поки немає прокату велосипедів · доступна {n} система", + "few": "Тут поки немає прокату велосипедів · доступні {n} системи", + "many": "Тут поки немає прокату велосипедів · доступно {n} систем", + "other": "Тут поки немає прокату велосипедів · доступно {n} системи" + }, "degraded": "з перебоями", "stale": "застарів", "partial": "частково", diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json index 6125315f2..0d4033ced 100644 --- a/src/i18n/locales/zh-CN.json +++ b/src/i18n/locales/zh-CN.json @@ -2302,6 +2302,10 @@ "No feed here yet · {n} regions available": { "other": "此处暂无数据源 · 有 {n} 个覆盖区域" }, + "Fly below {km} km to a covered city": "请降至 {km} km 以下并飞往有覆盖的城市", + "No bike share here yet · {n} systems available": { + "other": "此处暂无共享单车 · 有 {n} 个可用系统" + }, "degraded": "降级", "stale": "过期", "partial": "部分可用", diff --git a/src/i18n/locales/zh-Hant.json b/src/i18n/locales/zh-Hant.json index 66eb37b96..457a32aeb 100644 --- a/src/i18n/locales/zh-Hant.json +++ b/src/i18n/locales/zh-Hant.json @@ -2290,6 +2290,10 @@ "No feed here yet · {n} regions available": { "other": "此處暫無數據源 · 有 {n} 個覆蓋區域" }, + "Fly below {km} km to a covered city": "請降至 {km} km 以下並飛往有覆蓋的城市", + "No bike share here yet · {n} systems available": { + "other": "此處暫無共享單車 · 有 {n} 個可用系統" + }, "degraded": "降級", "stale": "過期", "partial": "部分可用", diff --git a/src/layers/bikeshare/controls.js b/src/layers/bikeshare/controls.js index 5f73a2dc9..993022506 100644 --- a/src/layers/bikeshare/controls.js +++ b/src/layers/bikeshare/controls.js @@ -1,5 +1,6 @@ import { msg, t } from '../../i18n/index.js'; -import { STATUS_POLL_MS } from './policy.js'; +import { ACTIVATION_ENTER_ALTITUDE_M, STATUS_POLL_MS } from './policy.js'; +import { GBFS_CITY_REGISTRY } from './registry.js'; export function createControls({ state: layerState, services, parts, source }) { const methods = { @@ -57,7 +58,7 @@ export function createControls({ state: layerState, services, parts, source }) { /** * Return current layer statistics for the UI status display. - * @returns {{ count: number, lastUpdate: number|null, loading: boolean, loadingLabel?: string, error?: string, degraded?: boolean, stale?: boolean }} + * @returns {{ count: number, lastUpdate: number|null, loading: boolean, loadingLabel?: string, error?: string, degraded?: boolean, stale?: boolean, status?: string, statusMessage?: string }} */ getStats() { const stats = { @@ -65,6 +66,23 @@ export function createControls({ state: layerState, services, parts, source }) { lastUpdate: layerState._lastUpdate, loading: layerState._loading, }; + // No system in range is guidance, not an empty feed: the camera is too + // high, or no catalogued system is near the view. A city that failed + // leaves range empty too, and reports its failure below instead. + if ( + layerState._enabled && + !layerState._loading && + layerState._activeCityIds.size === 0 && + layerState._failedCityIds.size === 0 + ) { + // English data (the analyst's empty note to the model, and the Layers + // row's prompt); both show it through translateStatusMessage + // (ui/statusText.js). + const note = layerState._altitudeGateEnabled + ? `No bike share here yet · ${GBFS_CITY_REGISTRY.length} systems available` + : `Fly below ${Math.round(ACTIVATION_ENTER_ALTITUDE_M / 1000).toLocaleString('en-US')} km to a covered city`; + return { ...stats, status: 'zoom-in', statusMessage: note }; + } if (layerState._loading) { stats.loadingLabel = layerState._activeCityIds.size > 0 diff --git a/src/layers/bikeshare/coverageStatus.test.mjs b/src/layers/bikeshare/coverageStatus.test.mjs new file mode 100644 index 000000000..a9f17e73e --- /dev/null +++ b/src/layers/bikeshare/coverageStatus.test.mjs @@ -0,0 +1,124 @@ +// BIKESHARE COVERAGE STATUS — a view with no system says so. +// +// Over a city with no catalogued system (London, Tokyo) the layer drew nothing +// and reported nothing, so its row read "ON · — · GBFS · never": the same as a +// feed that had never answered. These cases pin the rule that replaced it: +// with no system in range the layer reports a guidance status that says why, +// and a view it left keeps no date for data it no longer draws. +// +// Run with: npm test +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createState } from './state.js'; +import { createControls } from './controls.js'; +import { createModel } from './model.js'; +import { createViewport } from './viewport.js'; +import { GBFS_CITY_REGISTRY } from './registry.js'; + +const LONDON = { lat: 51.5072, lon: -0.1276 }; + +function makeLayer() { + const services = { + overlays: { + setOverlayEntries() {}, + setOverlaySourceVisible() {}, + clearOverlaySource() {}, + }, + render: { governorRequestRender() {} }, + }; + const state = createState({ services }); + const parts = { + queries: { collectDetectableStations: () => [] }, + model: createModel({ state, services, parts: {}, source: null }), + ingestion: { abortInFlight() {} }, + rendering: { removeCityPoints() {} }, + }; + parts.viewport = createViewport({ state, services, parts, source: null }); + const { methods } = createControls({ state, services, parts, source: {} }); + state._enabled = true; + return { state, methods, viewport: parts.viewport }; +} + +/** A viewer looking straight down at `at` from `height` metres. */ +function viewerAt(at, height) { + const rad = Math.PI / 180; + return { + camera: { + positionCartographic: { + height, + latitude: at.lat * rad, + longitude: at.lon * rad, + }, + computeViewRectangle: () => undefined, + }, + scene: { globe: {} }, + }; +} + +test('above the altitude gate the row says how low to fly', async () => { + const { state, methods, viewport } = makeLayer(); + state._viewer = viewerAt(LONDON, 2_000_000); + await viewport.runProximityCheck(); + + const stats = methods.getStats(); + assert.equal(stats.status, 'zoom-in'); + assert.equal(stats.statusMessage, 'Fly below 48 km to a covered city'); + assert.equal(stats.error, undefined); +}); + +test('a city with no system says so and counts the ones there are', async () => { + const { state, methods, viewport } = makeLayer(); + state._viewer = viewerAt(LONDON, 8_000); + await viewport.runProximityCheck(); + + const stats = methods.getStats(); + assert.equal(stats.status, 'zoom-in'); + assert.equal( + stats.statusMessage, + `No bike share here yet · ${GBFS_CITY_REGISTRY.length} systems available`, + ); + assert.equal(stats.count, 0); +}); + +test('a city with a system in range is not given the prompt', () => { + const { state, methods } = makeLayer(); + state._altitudeGateEnabled = true; + state._activeCityIds.add('boston-bluebikes'); + + assert.equal(methods.getStats().status, undefined); +}); + +test('a loading or failed city reports itself, not the prompt', () => { + const { state, methods } = makeLayer(); + state._altitudeGateEnabled = true; + state._loading = true; + assert.equal(methods.getStats().status, undefined); + + // A city that failed is dropped from range, and still owns the row. + state._loading = false; + state._failedCityIds.add('boston-bluebikes'); + const stats = methods.getStats(); + assert.equal(stats.status, undefined); + assert.equal(stats.error, 'GBFS fetch error'); +}); + +test('a disabled layer reports no prompt', () => { + const { state, methods } = makeLayer(); + state._enabled = false; + assert.equal(methods.getStats().status, undefined); +}); + +test('leaving every system behind drops the date of the data it drew', async () => { + for (const height of [8_000, 2_000_000]) { + const { state, methods, viewport } = makeLayer(); + state._lastUpdate = Date.now(); + // Boston's stations were drawn and dated; the camera moves to London. + state._activeCityIds.add('boston-bluebikes'); + state._cityRuntime.set('boston-bluebikes', {}); + state._viewer = viewerAt(LONDON, height); + await viewport.runProximityCheck(); + + assert.equal(state._activeCityIds.size, 0); + assert.equal(methods.getStats().lastUpdate, null, `at ${height} m`); + } +}); diff --git a/src/layers/bikeshare/viewport.js b/src/layers/bikeshare/viewport.js index 25a4df7d0..0739d341c 100644 --- a/src/layers/bikeshare/viewport.js +++ b/src/layers/bikeshare/viewport.js @@ -125,6 +125,8 @@ export function createViewport({ state: layerState, services, parts, source }) { // A failure belongs to a city in range; none are once everything is off. layerState._failedCityIds.clear(); layerState._count = 0; + // Nothing is left on the map to date. + layerState._lastUpdate = null; } /** @@ -227,6 +229,7 @@ export function createViewport({ state: layerState, services, parts, source }) { layerState._activeCityIds = nextActive; if (layerState._activeCityIds.size === 0) { layerState._count = 0; + layerState._lastUpdate = null; return; } diff --git a/src/layers/transit/lifecycle.test.mjs b/src/layers/transit/lifecycle.test.mjs index ea547f85d..a269dc9e9 100644 --- a/src/layers/transit/lifecycle.test.mjs +++ b/src/layers/transit/lifecycle.test.mjs @@ -3982,3 +3982,42 @@ test('parked transit reprojects held and reported courses at the bounded camera 'selected unknown course also stays screen-up', ); }); + +test('a view with no feed reads its coverage prompt, not an undated feed', async (t) => { + const app = harness(t); + app.serve('mbta', () => ({ + status: 200, + body: snapshot( + 'mbta', + 'MBTA', + [vehicle('bus-1', 42.36, -71.06, Date.now() / 1000)], + { fetchedAt: Date.now() }, + ), + })); + app.layer.enable(app.viewer); + await app.layer.update(); + assert.ok(app.layer.getStats().lastUpdate, 'Boston has a dated snapshot'); + + // London has no registered feed: the row prompts instead of dating Boston's + // last snapshot over an empty map. + app.lookAt({ west: -0.2, south: 51.45, east: -0.05, north: 51.55 }); + app.advance(1_000); + const away = app.layer.getStats(); + assert.equal(away.status, 'zoom-in'); + assert.equal(away.count, 0); + assert.equal(away.lastUpdate, null); + assert.match( + away.statusMessage, + /^No feed here yet · \d+ regions available$/, + ); + assert.equal(away.coverage, away.statusMessage); + + // Above the altitude gate the prompt says how low to fly. + app.viewer.camera.positionCartographic.height = 10_000_000; + app.lookAt({ west: -0.2, south: 51.45, east: -0.05, north: 51.55 }); + app.advance(1_000); + assert.equal( + app.layer.getStats().statusMessage, + 'Fly below 3,000 km to a covered region', + ); +}); diff --git a/src/layers/transit/queries.js b/src/layers/transit/queries.js index b86613160..8023cdb39 100644 --- a/src/layers/transit/queries.js +++ b/src/layers/transit/queries.js @@ -240,17 +240,20 @@ export function createQueries({ state, parts }) { const health = aggregateTransitFeedHealth(statuses, now); const count = state._vehicles.size; if (state._enabled && active.length === 0) { + // English data (the analyst's empty note to the model, and the Layers + // row's prompt); both show it through translateStatusMessage + // (ui/statusText.js). + const note = state._altitudeGateOpen + ? `No feed here yet · ${TRANSIT_ENABLED_FEEDS.length} regions available` + : `Fly below ${Math.round(ACTIVATION_ALTITUDE_M / 1000).toLocaleString('en-US')} km to a covered region`; return { count: 0, lastUpdate: state._lastUpdate, error: null, source: 'GTFS-RT', status: 'zoom-in', - // English data (the analyst's empty note to the model); the voice - // card shows it through NOTE_PATTERNS (voice/resultDisplay.js). - coverage: state._altitudeGateOpen - ? `No feed here yet · ${TRANSIT_ENABLED_FEEDS.length} regions available` - : `Fly below ${Math.round(ACTIVATION_ALTITUDE_M / 1000).toLocaleString('en-US')} km to a covered region`, + statusMessage: note, + coverage: note, }; } // Age is shown by the same rule the row state uses, so the text and the diff --git a/src/layers/transit/viewport.js b/src/layers/transit/viewport.js index 730126f10..27cc0569c 100644 --- a/src/layers/transit/viewport.js +++ b/src/layers/transit/viewport.js @@ -108,6 +108,9 @@ export function createViewport({ state, services, parts }) { parts.ingestion.removeFeedVehicles(feedId); } } + // Leaving coverage leaves nothing on the map to date: a row that read + // "26s ago" over an empty view would claim a feed that is no longer here. + if (desired.size === 0) state._lastUpdate = null; for (const [feedId, feed] of desired) { if (!state._activeFeeds.has(feedId)) { state._activeFeeds.set(feedId, feed); diff --git a/src/ui/layerPanel.js b/src/ui/layerPanel.js index b24e8be7b..29a4bc3c0 100644 --- a/src/ui/layerPanel.js +++ b/src/ui/layerPanel.js @@ -11,14 +11,17 @@ import { } from './layerNames.js'; export { localizeLayerName } from './layerNames.js'; import { createWeatherPanel } from './weatherPanel.js'; -import { translateFeedError, translateStatusLine } from './statusText.js'; +import { + translateFeedError, + translateStatusLine, + translateStatusMessage, +} from './statusText.js'; import { formatNumber, getLocale, msg, onLocaleChange, t, - translateKnown, } from '../i18n/index.js'; // Feed-state values are machine ids (QA hooks, CSS feed-* classes); only the @@ -691,7 +694,7 @@ export class LayerPanel { typeof stats.statusMessage === 'string' && stats.statusMessage.trim() ) { - return `${source} · ${translateKnown(stats.statusMessage.trim())}`; + return `${source} · ${translateStatusMessage(stats.statusMessage.trim())}`; } const ago = stats.lastUpdate ? this._timeAgo(stats.lastUpdate) : t('never'); if (stats.loading) { diff --git a/src/ui/layerPanel.test.mjs b/src/ui/layerPanel.test.mjs index 73710e3fc..1be2df5d7 100644 --- a/src/ui/layerPanel.test.mjs +++ b/src/ui/layerPanel.test.mjs @@ -431,3 +431,57 @@ test('without the Utilities list, Directions stays in Data Layers under Utilitie restore(); } }); + +test('a layer with no feed in view says why instead of "never"', async () => { + const { LayerPanel, presentLayerCount, presentLayerToggle } = + await import('./layerPanel.js'); + const { setLocale } = await import('../i18n/index.js'); + const panel = LayerPanel.prototype; + const rows = [ + { + id: 'transit', + name: 'Transit', + source: 'GTFS-RT', + enabled: true, + stats: { + count: 0, + lastUpdate: null, + source: 'GTFS-RT', + status: 'zoom-in', + statusMessage: 'No feed here yet · 16 regions available', + }, + meta: 'GTFS-RT · No feed here yet · 16 regions available', + }, + { + id: 'bikeshare', + name: 'Bikeshare', + source: 'GBFS', + enabled: true, + stats: { + count: 0, + lastUpdate: null, + loading: false, + status: 'zoom-in', + statusMessage: 'Fly below 48 km to a covered city', + }, + meta: 'GBFS · Fly below 48 km to a covered city', + }, + ]; + for (const layer of rows) { + // Guidance is normal operation: the layer is on and nothing has failed. + assert.equal(presentLayerToggle(layer).text, 'ON'); + assert.equal(presentLayerCount(layer.stats).empty, true); + assert.equal(panel._buildMetaText(layer), layer.meta); + } + + setLocale('ru'); + try { + for (const layer of rows) { + const meta = panel._buildMetaText(layer); + assert.doesNotMatch(meta, /never|Fly below|No feed|covered/, meta); + assert.match(meta, /^(GTFS-RT|GBFS) · /, meta); + } + } finally { + setLocale('en'); + } +}); diff --git a/src/ui/statusText.js b/src/ui/statusText.js index 1af6b8b2a..f4cbb59a0 100644 --- a/src/ui/statusText.js +++ b/src/ui/statusText.js @@ -265,3 +265,66 @@ export function translateStatusLine(text) { .map(translateStatusPiece) .join(STATUS_SEPARATOR); } + +/** Thousands separators out of an English number ("3,000" → 3000). */ +const englishNumber = (text) => Number(text.replace(/,/g, '')); + +// Coverage notes of a layer whose view has no feed, whole lines with a number +// in them: transit (transit/queries.js) and bikeshare (bikeshare/controls.js). +// Their " · " is part of one sentence, so they are matched before the line is +// split into pieces. Keep these in step with the producers. +const COVERAGE_NOTE_PATTERNS = [ + [ + /^Fly below ([\d,]+) km to a covered region$/, + ([, km]) => + t('Fly below {km} km to a covered region', { + km: formatNumber(englishNumber(km)), + }), + ], + [ + /^No feed here yet · ([\d,]+) regions available$/, + ([, regions]) => { + const count = englishNumber(regions); + return tn( + count, + 'No feed here yet · {n} region available', + 'No feed here yet · {n} regions available', + { n: formatNumber(count) }, + ); + }, + ], + [ + /^Fly below ([\d,]+) km to a covered city$/, + ([, km]) => + t('Fly below {km} km to a covered city', { + km: formatNumber(englishNumber(km)), + }), + ], + [ + /^No bike share here yet · ([\d,]+) systems available$/, + ([, systems]) => { + const count = englishNumber(systems); + return tn( + count, + 'No bike share here yet · {n} system available', + 'No bike share here yet · {n} systems available', + { n: formatNumber(count) }, + ); + }, + ], +]; + +/** + * A layer's status message in the UI language: its catalog entry, a coverage + * note by its shape, or a status line translated piece by piece. + */ +export function translateStatusMessage(text) { + if (typeof text !== 'string') return text; + const known = translateKnown(text); + if (known !== text) return known; + for (const [pattern, format] of COVERAGE_NOTE_PATTERNS) { + const match = pattern.exec(text); + if (match) return format(match); + } + return translateStatusLine(text); +} diff --git a/src/ui/statusText.test.mjs b/src/ui/statusText.test.mjs index a64975c48..1b6479b45 100644 --- a/src/ui/statusText.test.mjs +++ b/src/ui/statusText.test.mjs @@ -3,7 +3,11 @@ import assert from 'node:assert/strict'; import test from 'node:test'; import { setLocale, t } from '../i18n/index.js'; -import { translateFeedError, translateStatusLine } from './statusText.js'; +import { + translateFeedError, + translateStatusLine, + translateStatusMessage, +} from './statusText.js'; function inLocale(locale, run) { setLocale(locale); @@ -75,3 +79,55 @@ for (const locale of ['es', 'ru']) { }); }); } + +// A layer's coverage note when no feed covers the view: one sentence with a +// " · " in it (transit/queries.js, bikeshare/controls.js). +const COVERAGE_NOTES = [ + 'Fly below 3,000 km to a covered region', + 'No feed here yet · 16 regions available', + 'Fly below 48 km to a covered city', + 'No bike share here yet · 61 systems available', +]; + +test('en: coverage notes show as they came', () => { + setLocale('en'); + for (const text of COVERAGE_NOTES) + assert.equal(translateStatusMessage(text), text); + assert.equal( + translateStatusMessage('No bike share here yet · 1 systems available'), + 'No bike share here yet · 1 system available', + ); +}); + +for (const locale of ['es', 'ru', 'ja']) { + test(`${locale}: a coverage note translates whole, numbers kept`, () => { + inLocale(locale, () => { + for (const text of COVERAGE_NOTES) { + const shown = translateStatusMessage(text); + assert.doesNotMatch( + shown, + /\b(Fly|below|covered|feed|bike share|available)\b/, + shown, + ); + const number = /[\d,]+(?= km| regions| systems)/.exec(text)[0]; + assert.ok( + shown.replace(/[^\d]/g, '').includes(number.replace(/,/g, '')), + shown, + ); + } + }); + }); + + test(`${locale}: a status message without a coverage note keeps its other forms`, () => { + inLocale(locale, () => { + assert.equal( + translateStatusMessage('Upstream response too large'), + t('Upstream response too large'), + ); + assert.equal( + translateStatusMessage('2 feeds live · 14 heard'), + translateStatusLine('2 feeds live · 14 heard'), + ); + }); + }); +} diff --git a/src/voice/resultDisplay.js b/src/voice/resultDisplay.js index 112200f7f..cd909d2f7 100644 --- a/src/voice/resultDisplay.js +++ b/src/voice/resultDisplay.js @@ -29,7 +29,7 @@ import { } from '../i18n/index.js'; import { layerNameForId, sourceLabel } from '../ui/layerNames.js'; import { localizePlaceName } from '../ui/placeNames.js'; -import { translateStatusLine } from '../ui/statusText.js'; +import { translateStatusMessage } from '../ui/statusText.js'; import { formatQuantity } from '../ui/unitLabels.js'; /** Split "a; b" caveat text into separate notes. */ @@ -397,27 +397,6 @@ const NOTE_PATTERNS = [ 'Contacts panel snapshot — the same retained cohort supplies the card, speech, and follow-up memory', )) + period, ], - // Transit's empty note when no feed covers the view (transit/queries.js); - // the model gets the English. - [ - /^Fly below ([\d,]+) km to a covered region$/, - ([, km]) => - t('Fly below {km} km to a covered region', { - km: formatNumber(Number(km.replace(/,/g, ''))), - }), - ], - [ - /^No feed here yet · ([\d,]+) regions available$/, - ([, regions]) => { - const count = Number(regions.replace(/,/g, '')); - return tn( - count, - 'No feed here yet · {n} region available', - 'No feed here yet · {n} regions available', - { n: formatNumber(count) }, - ); - }, - ], [ /^([a-z0-9-]+) (off|loading|error)$/, ([, key, status]) => @@ -444,10 +423,10 @@ function shownNote(text) { const shown = match ? show(match) : null; if (shown) return shown; } - // A layer's empty note can be its status line, English pieces joined by - // " · " ("feeds 1090, 978 stale · 0 heard", "TTC 0 (95s old)"). - const known = translateKnown(text); - return known !== text ? known : translateStatusLine(text); + // A layer's empty note can be its coverage note ("Fly below 3,000 km to a + // covered region") or its status line, English pieces joined by " · " + // ("feeds 1090, 978 stale · 0 heard", "TTC 0 (95s old)"). + return translateStatusMessage(text); } /** Feed states as the card's chips show them; the values stay English. */ From 25c33893f666bf77b8cb416151657ab84a4a1834 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Thu, 5 Nov 2026 12:53:09 +0400 Subject: [PATCH 028/171] Add the changelog entry for #1576 --- changelog.d/1576-transit-bikeshare-coverage-prompt.md | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 changelog.d/1576-transit-bikeshare-coverage-prompt.md diff --git a/changelog.d/1576-transit-bikeshare-coverage-prompt.md b/changelog.d/1576-transit-bikeshare-coverage-prompt.md new file mode 100644 index 000000000..c3dcbe82a --- /dev/null +++ b/changelog.d/1576-transit-bikeshare-coverage-prompt.md @@ -0,0 +1,6 @@ +- Say why Transit and Bike Share are empty outside coverage. Over a city with + no feed or system (London, Tokyo) their Layers rows read + `No feed here yet · 16 regions available` and + `No bike share here yet · 61 systems available`, or how low to fly, instead + of `never`; leaving coverage clears the last-update time (German, @gekh, + #1576). From 652f3c8ea110f3b583e9adfd542617b06808f39b Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Thu, 5 Nov 2026 12:53:17 +0400 Subject: [PATCH 029/171] Hide a vessel's detection callout while its own card paints With Vessels and Detection on, a vessel with an ambient card on the map also got its detection callout next to the bracket. The callout lane paints beneath the cards, so its text showed through the card's plate and covered the speed and course. The callout now gives way only to a card the shared overlay actually paints in the same frame. The overlay paints part of the published cards (shared budget, collisions, UI chrome), so a vessel whose card was dropped keeps its callout. The detection lane paints before the cards publish their paint rects, so getOverlayPaintRect has nothing for the current frame there. The new isOverlayEntryQueued answers from the paint queue that the overlay solves before painting. Vessel detection objects name their card in cardSourceId/cardEntryId. --- docs/CURRENT-STATE.md | 2 +- src/data/aisLiveVessels.test.mjs | 39 +++++++++++++++++++ src/data/detection.js | 24 +++++++++++- src/data/detectionHost.test.mjs | 62 ++++++++++++++++++++++++++++++ src/layers/vessels/queries.js | 7 +++- src/overlays/worldOverlay.js | 26 +++++++++++++ src/overlays/worldOverlay.test.mjs | 38 ++++++++++++++++++ 7 files changed, 194 insertions(+), 4 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index f1244947d..370edcd7b 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -5322,7 +5322,7 @@ silently demoting every later lookup for the session. Mission world text has no native `LabelGraphics`: overview launch markers publish at most 48 ambient candidates for a 24-winner budget, while selecting a mission clears that overview source and publishes its launch-site callout, stage re-entry annotations, live/estimated payload-position readout, and orbit annotation as protected selected-lane entries. The source retains the exact former strings and colors. Static anchors reuse the Cartesian values used to build their mission geometry; the moving payload entry reads the layer's per-frame live-position cache; catalog-backed orbit annotation positions are cached in the same one-second matrix update that realigns the orbit primitive. Keyhole edge fade, horizon culling, final collision placement, and UI exclusion are owned by the shared host. Deselect restores the bounded overview, and refresh, disable, and destroy replace or clear both mission sources. A selected mission renders its orbit as four repeating tactical sectors, each containing one prominent cyan dot followed by one hundred thin translucent dashes. The bright dots act as orbit anchors while the subdued dash field remains depth-tested against the globe and is shown only for the selected mission. Close selected-pad views add one static 500 m-radius cyan launch-zone ring with a low-opacity translucent fill over the sampled photoreal launch-site surface. The single scene primitive is created only for the visible selected site and is otherwise dormant. It appears during Focus, sufficiently close manual zoom, and the replay countdown, but is suppressed above 120 km camera altitude, beyond 180 km direct camera-to-pad range, for unselected missions, and whenever Space Missions is inactive. Focus establishes a launch-site-centered camera transform once; subsequent manual heading and pitch changes remain centered on that site without an automated per-frame correction. Surface mission markers and labels use an additional conservative globe-limb margin before the exact ellipsoid occluder boundary, preventing near-horizon visibility from alternating between frames. -- **AIS vessels**: chevron symbology (naval cyan base, type tints), world-space headings, MMSI-keyed reconciliation (selection survives refreshes; pinned 3 refreshes with STALE marker when absent), detection-overlay integration (`type: 'SEA'`), contextStore registration for voice Q&A. Empty-space clicks, id-less photorealistic-tile picks, and Escape dismiss the vessel card/HUD/context and clear its trail; picks owned by another layer (including `gev-trail:*`) and raw vessel-record picks without a live MMSI key are no-ops for vessel selection. Click and key handlers detach while the layer is disabled and reinstall on enable. Selecting another vessel replaces the selection and trail, and reconciliation clears a trail if its owning vessel is evicted. +- **AIS vessels**: chevron symbology (naval cyan base, type tints), world-space headings, MMSI-keyed reconciliation (selection survives refreshes; pinned 3 refreshes with STALE marker when absent), detection-overlay integration (`type: 'SEA'`; a vessel whose ambient card the shared host paints in the current frame draws no detection callout, because the callout would show through the card's plate, while a vessel whose card was published but not painted (shared budget, collisions, UI chrome) keeps its callout — its detectable object names the card in `cardSourceId`/`cardEntryId`, and the callout lane asks `isOverlayEntryQueued` in `src/overlays/worldOverlay.js`, which answers from the solved paint queue because the detection lane paints before the cards publish their paint rects), contextStore registration for voice Q&A. Empty-space clicks, id-less photorealistic-tile picks, and Escape dismiss the vessel card/HUD/context and clear its trail; picks owned by another layer (including `gev-trail:*`) and raw vessel-record picks without a live MMSI key are no-ops for vessel selection. Click and key handlers detach while the layer is disabled and reinstall on enable. Selecting another vessel replaces the selection and trail, and reconciliation clears a trail if its owning vessel is evicted. - **Track trails**: server accumulates per-MMSI ring buffers (`/api/vessels/track?mmsi=`, Float32+Uint32, 64 samples, 30s/25m thinning); aircraft backfill proxies `/api/flights/track` (OAuth, own credit bucket). Military aircraft keep only their locally accumulated trails: `/api/military/track` validates the hex, then answers `503 history_unavailable` without an upstream request. - Shared `src/data/pickRegistry.js` stops the two flight layers' click handlers from fighting over the camera. diff --git a/src/data/aisLiveVessels.test.mjs b/src/data/aisLiveVessels.test.mjs index 8e12bff94..edb3505f2 100644 --- a/src/data/aisLiveVessels.test.mjs +++ b/src/data/aisLiveVessels.test.mjs @@ -1786,3 +1786,42 @@ test('vessel focus wire skips hidden sprites at rest while a target is tracked', assert.equal(result.activeCount, 1); for (const billboard of hidden) assert.equal(billboard.color.alpha, 1); }); + +test('detection objects name the vessel card their callout gives way to', () => { + const vessel = (mmsi, name) => ({ + name, + mmsi, + type: 'Cargo', + destination: '', + speed: 9.5, + course: 80, + heading: 80, + lastPositionUtc: '', + missedRefreshes: 0, + position: POS, + billboard: null, + }); + const keyed = vessel('200', 'GOLDEN BEAR'); + const unkeyed = { ...vessel('', 'NO MMSI'), lat: 37.8, lon: -122.4 }; + _setVesselStateForTest({ + viewer: {}, + records: [keyed, unkeyed], + billboardCollection: { show: true, remove() {} }, + }); + try { + const objects = Object.fromEntries( + aisLiveVesselsLayer + .getDetectableObjects() + .map((object) => [object.id, object]), + ); + assert.equal(objects['GOLDEN BEAR'].cardSourceId, 'ais-live-vessels'); + assert.equal(objects['GOLDEN BEAR'].cardEntryId, 'vessel:200'); + assert.equal( + objects['NO MMSI'].cardEntryId, + 'vessel:unkeyed:NO MMSI:37.80000:-122.40000', + 'the same identity the vessel card is published under', + ); + } finally { + _setVesselStateForTest({ enabled: false }); + } +}); diff --git a/src/data/detection.js b/src/data/detection.js index 36ed6372e..8ea124649 100644 --- a/src/data/detection.js +++ b/src/data/detection.js @@ -21,7 +21,10 @@ import { getKeyholeFadeTuning, keyholeLabelAlphaFromGeometry, } from '../celestialRing.js'; -import { registerWorldOverlayPaintLane } from '../overlays/worldOverlay.js'; +import { + isOverlayEntryQueued, + registerWorldOverlayPaintLane, +} from '../overlays/worldOverlay.js'; import { DETECTION_STYLE, DETECTION_THEME_MAP, @@ -576,6 +579,7 @@ export function getDetectionDiagnostics() { // sprites/strokes. Nothing is copied on the production paint path. result.calloutRects = _calloutPool .slice(0, _calloutCount) + .filter((row) => !row.yielded) .map(({ x, y, w, h, alpha }) => ({ x, y, w, h, alpha })); return result; } @@ -1077,6 +1081,9 @@ function _stashCallout(entry, acquireFade, keyhole) { font: FONT, microFont: MICRO_FONT, alpha: 1, + cardSourceId: '', + cardEntryId: '', + yielded: false, }; _calloutPool[_calloutCount] = row; } @@ -1103,6 +1110,9 @@ function _stashCallout(entry, acquireFade, keyhole) { row.font = FONT; row.microFont = MICRO_FONT; row.alpha = alpha; + row.cardSourceId = candidate.cardSourceId; + row.cardEntryId = candidate.cardEntryId; + row.yielded = false; _calloutCount++; } @@ -1134,7 +1144,15 @@ function _paintCalloutLane(frame) { ctx.textBaseline = 'alphabetic'; for (let i = 0; i < _calloutCount; i++) { const row = _calloutPool[i]; - paintDetectionCallout(ctx, row, row.alpha); + // The contact's own card (an ambient vessel card) already names it, and + // this callout would show through the card's plate. Checked every frame + // against the cards queued for THIS frame: the host paints only part of + // the published cards, and a contact whose card did not paint keeps its + // callout. + row.yielded = + row.cardEntryId !== '' && + isOverlayEntryQueued(row.cardSourceId, row.cardEntryId); + if (!row.yielded) paintDetectionCallout(ctx, row, row.alpha); } ctx.globalAlpha = 1; } @@ -1211,6 +1229,8 @@ function _materializeCandidate( primary, micro, hasMicro: card.hasMicro, + cardSourceId: obj.cardSourceId ? String(obj.cardSourceId) : '', + cardEntryId: obj.cardEntryId ? String(obj.cardEntryId) : '', }; } diff --git a/src/data/detectionHost.test.mjs b/src/data/detectionHost.test.mjs index f8858d602..7bcb9300e 100644 --- a/src/data/detectionHost.test.mjs +++ b/src/data/detectionHost.test.mjs @@ -19,9 +19,11 @@ import { suspendDetection, } from './detection.js'; import { + clearOverlaySource, destroyWorldOverlay, initWorldOverlay, setOverlayEntries, + setOverlaySourceVisible, } from '../overlays/worldOverlay.js'; import { DETECTION_THEME_MAP } from '../overlays/worldOverlayTokens.js'; import { @@ -579,6 +581,66 @@ test('every style paints its OWN plate token through the production callout path } }); +test('a callout gives way to its contact\'s own card only while that card paints', () => { + // A vessel's ambient card already shows its name, speed and course, and the + // callout drawn beneath it shows through the card's plate. The host paints + // only part of the published cards (shared budget, collisions, UI chrome), + // so a contact whose card was published but not painted keeps its callout. + const env = installEnvironment({ width: 900, height: 600, dpr: 1 }); + try { + const ships = [ + { x: -0.3, sourceId: 'carded', id: 'SHIP-CARDED', card: 'vessel:carded' }, + { x: 0.3, sourceId: 'dropped', id: 'SHIP-DROPPED', card: 'vessel:dropped' }, + ].map(({ x, sourceId, id, card }) => ({ + position: new Cesium.Cartesian3(x, 0, 6_356_752), + sourceId, + id, + metric: '6 kn', + type: 'SEA', + cardSourceId: card === 'vessel:carded' ? 'vessel-cards' : 'dropped-cards', + cardEntryId: card, + })); + initWorldOverlay(env.viewer); + initDetection(env.viewer, [{ id: 'ais-live-vessels', getDetectableObjects: () => ships }], () => {}); + const card = (id, title, x) => ({ + id, + position: new Cesium.Cartesian3(x, 0, 6_356_752), + variant: 'label', + title, + selected: true, + protected: true, + horizonCull: false, + edgeFade: 'none', + }); + setOverlayEntries('vessel-cards', [card('vessel:carded', 'CARD-CARDED', -0.3)]); + // Published, but the host does not paint it this frame. + setOverlayEntries('dropped-cards', [card('vessel:dropped', 'CARD-DROPPED', 0.3)]); + setOverlaySourceVisible('dropped-cards', false); + setMode('DENSE'); + settleFrame(env); + env.ctx.calls.length = 0; + settleFrame(env); + + const painted = (text) => env.ctx.calls.some(([name, value]) => name === 'fillText' && value === text); + assert.ok(painted('CARD-CARDED'), 'the fixture card reached the frame'); + assert.ok(!painted('CARD-DROPPED'), 'the hidden source paints no card'); + assert.ok(!painted('SHIP-CARDED'), 'no callout under the painted card'); + assert.ok(painted('SHIP-DROPPED'), 'the contact whose card did not paint keeps its callout'); + assert.equal(getDetectionDiagnostics().calloutRects.length, 1, + 'only the callout that painted is reported'); + + // The card leaves the host: the callout comes back on the next frame. + clearOverlaySource('vessel-cards'); + env.ctx.calls.length = 0; + settleFrame(env); + assert.ok(painted('SHIP-CARDED'), 'the callout returns once its card stops painting'); + } finally { + destroyDetection(); + destroyWorldOverlay(); + env.cleanup(); + } +}); + test('space-tier callouts take the heavier plate while air contacts keep the light one', () => { // Satellites sit over the high-albedo lit Earth disc far more often than // aircraft do, so the space tier carries the heavier backing. Losing the diff --git a/src/layers/vessels/queries.js b/src/layers/vessels/queries.js index c848acc2d..7b2b66825 100644 --- a/src/layers/vessels/queries.js +++ b/src/layers/vessels/queries.js @@ -21,6 +21,7 @@ import { REFRESH_MS, FOCUS_EVIDENCE_DEV, } from './policy.js'; +import { VESSEL_OVERLAY_SOURCE_ID } from '../../data/vesselLabels.js'; export function createQueries({ vesselState, @@ -469,7 +470,7 @@ export function createQueries({ * @param {Object} [options={}] - Options from the detection system. * @param {number} [options.maxCount] - Maximum objects to return (defaults to all). * @param {number} [options.seed] - Seed offset for stride sampling. - * @returns {Array<{position: Cesium.Cartesian3, id: string, type: string, skipLabel: boolean}>} + * @returns {Array<{position: Cesium.Cartesian3, id: string, type: string, skipLabel: boolean, cardSourceId: string, cardEntryId: string}>} */ getDetectableObjects(options = {}) { if ( @@ -504,6 +505,10 @@ export function createQueries({ id: record.name || record.mmsi || 'VESSEL', type: 'SEA', skipLabel: record === selected, + // The vessel's ambient card: while the overlay paints it, detection + // draws no callout under it. + cardSourceId: VESSEL_OVERLAY_SOURCE_ID, + cardEntryId: components.cards.vesselOverlayEntryId(record), klass: record.type ? String(record.type).toUpperCase().slice(0, 14) : undefined, diff --git a/src/overlays/worldOverlay.js b/src/overlays/worldOverlay.js index 7b0b9d5fd..16699c548 100644 --- a/src/overlays/worldOverlay.js +++ b/src/overlays/worldOverlay.js @@ -1065,6 +1065,22 @@ export function getOverlayPaintRect(sourceId, entryId) { return rect && rect.key === key && rect.stamp === _frameStamp ? rect : null; } +/** + * Whether an entry is queued to paint in the frame being painted. Custom lanes + * run before the host's own entries, so `getOverlayPaintRect` has nothing for + * this frame yet while they paint; this answers from the solved paint queue. + * @param {string} sourceId + * @param {string} entryId + * @returns {boolean} + */ +export function isOverlayEntryQueued(sourceId, entryId) { + if (_destroyed) return false; + const record = _records.get(entryKey(String(sourceId), String(entryId))); + return ( + !!record && record.queuedStamp === _frameStamp && record.queuedAlpha > 0.001 + ); +} + /** * Resolve the topmost interactive world-overlay entry at CSS-pixel coords. * @param {number} x @@ -1737,6 +1753,8 @@ function getProjectionRecord(entry) { contentAlpha: 1, altitudeAlpha: 1, sourceAlpha: 1, + queuedStamp: 0, + queuedAlpha: 0, protectedPlacement: null, distanceOptions: {}, altitudeOptions: {}, @@ -2254,6 +2272,14 @@ function addPaintItem(record, placement, temporalAlpha, selected) { item.zIndex = record.entry.zIndex; item.key = record.key; _paintQueue[_paintCount++] = item; + // Read by `isOverlayEntryQueued` while the custom lanes paint, before this + // item publishes its paint rect. Keyhole and sonar fades are left out. + record.queuedStamp = _frameStamp; + record.queuedAlpha = + record.sourceAlpha * + temporalAlpha * + record.distanceAlpha * + record.altitudeAlpha; } function sourceCanPaint(sourceId) { diff --git a/src/overlays/worldOverlay.test.mjs b/src/overlays/worldOverlay.test.mjs index f2e608b78..a0b5160b6 100644 --- a/src/overlays/worldOverlay.test.mjs +++ b/src/overlays/worldOverlay.test.mjs @@ -24,6 +24,7 @@ import { activateWorldOverlayAction, initWorldOverlay, subscribeWorldOverlayActions, + isOverlayEntryQueued, isOverlayPointVisible, normalizeOverlayEntry, paintLaneForOverlayEntry, @@ -1213,6 +1214,43 @@ test('custom detection lane receives the shared host frame and paints below ordi env.cleanup(); }); +test('a detection lane sees which cards this frame will paint before they publish paint rects', () => { + // The detection lane paints first, so a card's paint rectangle for this + // frame does not exist yet when it runs. The queued check is what lets a + // contact's callout give way to that contact's own card in the same frame. + const env = installMockEnvironment({ width: 400, height: 300, dpr: 1 }); + initWorldOverlay(env.viewer); + const seen = []; + registerWorldOverlayPaintLane('detection', () => { + seen.push({ + shown: isOverlayEntryQueued('cards', 'SHOWN'), + hidden: isOverlayEntryQueued('hidden-cards', 'HIDDEN'), + unknown: isOverlayEntryQueued('cards', 'NOT-PUBLISHED'), + rect: getOverlayPaintRect('cards', 'SHOWN'), + }); + }, { id: 'detection', active: true, target: 'detection' }); + setOverlayEntries('cards', [selectedEntry('SHOWN', { + position: positionAtScreen(200, 150), + })]); + setOverlayEntries('hidden-cards', [selectedEntry('HIDDEN', { + position: positionAtScreen(100, 100), + })]); + setOverlaySourceVisible('hidden-cards', false); + + env.postRender.raise(); + assert.deepEqual(seen[0], { shown: true, hidden: false, unknown: false, rect: null }, + 'the card is queued while its paint rect is still unpublished'); + assert.ok(getOverlayPaintRect('cards', 'SHOWN'), 'the card did paint after the lane'); + assert.equal(getOverlayPaintRect('hidden-cards', 'HIDDEN'), null); + + clearOverlaySource('cards'); + env.postRender.raise(); + assert.equal(seen[1].shown, false, 'a card cleared since the last frame is no longer queued'); + destroyWorldOverlay(); + assert.equal(isOverlayEntryQueued('cards', 'SHOWN'), false); + env.cleanup(); +}); + test('custom-lane painter state is bracketed by host save/restore', () => { // A painter that leaks a clip or alpha must not corrupt later frames: the // host wraps every custom-lane painter in save/try/finally-restore. Pin the From 092e7e71a8cabcaa2ed1274f5f217a0e971e1bec Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Thu, 5 Nov 2026 12:54:11 +0400 Subject: [PATCH 030/171] Add the changelog entry for #1577 --- changelog.d/1577-vessel-callout-under-card.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 changelog.d/1577-vessel-callout-under-card.md diff --git a/changelog.d/1577-vessel-callout-under-card.md b/changelog.d/1577-vessel-callout-under-card.md new file mode 100644 index 000000000..579d805b9 --- /dev/null +++ b/changelog.d/1577-vessel-callout-under-card.md @@ -0,0 +1,3 @@ +- A vessel whose ambient card is on the map no longer gets a Detection callout + showing through the card and covering its speed and course. A vessel whose + card the overlay did not paint keeps its callout (German, @gekh, #1577). From ee3466dff93152204238bd7f83bd456d850bef00 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Thu, 5 Nov 2026 13:14:00 +0400 Subject: [PATCH 031/171] Keep the queued-card check off the per-frame allocation path Writing a fractional alpha onto the overlay record for every paint item boxed a heap number per item per frame. The allocation gate caught it: the generic 60-entry workload went from 2,838 to 12,614 B/frame. The record now keeps only the frame stamp and a pointer to its paint item, and isOverlayEntryQueued multiplies the alphas when it is asked. The gate is back to main's numbers on Node 24. --- src/overlays/worldOverlay.js | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/src/overlays/worldOverlay.js b/src/overlays/worldOverlay.js index 16699c548..726e766ee 100644 --- a/src/overlays/worldOverlay.js +++ b/src/overlays/worldOverlay.js @@ -1076,8 +1076,14 @@ export function getOverlayPaintRect(sourceId, entryId) { export function isOverlayEntryQueued(sourceId, entryId) { if (_destroyed) return false; const record = _records.get(entryKey(String(sourceId), String(entryId))); + if (!record || record.queuedStamp !== _frameStamp) return false; + // Same channels as the paint, minus the per-frame keyhole and sonar fades. return ( - !!record && record.queuedStamp === _frameStamp && record.queuedAlpha > 0.001 + record.sourceAlpha * + record.queuedItem.temporalAlpha * + record.distanceAlpha * + record.altitudeAlpha > + 0.001 ); } @@ -1754,7 +1760,7 @@ function getProjectionRecord(entry) { altitudeAlpha: 1, sourceAlpha: 1, queuedStamp: 0, - queuedAlpha: 0, + queuedItem: null, protectedPlacement: null, distanceOptions: {}, altitudeOptions: {}, @@ -2273,13 +2279,10 @@ function addPaintItem(record, placement, temporalAlpha, selected) { item.key = record.key; _paintQueue[_paintCount++] = item; // Read by `isOverlayEntryQueued` while the custom lanes paint, before this - // item publishes its paint rect. Keyhole and sonar fades are left out. + // item publishes its paint rect. Only a stamp and a pointer: storing the + // item's alpha here would box a double per paint item per frame. record.queuedStamp = _frameStamp; - record.queuedAlpha = - record.sourceAlpha * - temporalAlpha * - record.distanceAlpha * - record.altitudeAlpha; + record.queuedItem = item; } function sourceCanPaint(sourceId) { From c73e4edce7e3e9b2534245f81d955be08dfd5a81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Itallo=20Brand=C3=A3o?= <45429643+IMBrandao@users.noreply.github.com> Date: Thu, 5 Nov 2026 10:44:17 -0300 Subject: [PATCH 032/171] docs(changelog): add #1583 fragment Co-Authored-By: Claude Opus 5.5 --- changelog.d/1583-shipwrecks.md | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 changelog.d/1583-shipwrecks.md diff --git a/changelog.d/1583-shipwrecks.md b/changelog.d/1583-shipwrecks.md new file mode 100644 index 000000000..06a2775c1 --- /dev/null +++ b/changelog.d/1583-shipwrecks.md @@ -0,0 +1,4 @@ +- New Shipwrecks layer (Events): about 8,000 wrecks from EMODnet (CC BY 4.0) + and Wikidata (CC0). Each has a card with deaths, date, vessel, cause, depth, + position quality and a source link. Markers grow with the death toll, and + the same period picker as air accidents filters by year (IMBrandao, #1583). From da00b096d2bae42b28a5e34a6c7aed5543d0291b Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Thu, 5 Nov 2026 21:21:02 +0400 Subject: [PATCH 033/171] Fade a vessel's callout by its card's painted opacity The callout now asks for the opacity its own card paints with this frame, keyhole fade included, and fades out as the card fades in. A card faded out at the keyhole rim leaves the callout readable, and a card fading out after leaving its source still hides it. The vessel card id is cached on the record, and the allocation gate covers the lookup. --- docs/CURRENT-STATE.md | 2 +- src/data/aisLiveVessels.test.mjs | 1 + src/data/detection.js | 33 ++-- src/data/detectionHost.test.mjs | 174 ++++++++++++++++++ src/layers/vessels/cards.js | 8 + src/layers/vessels/records.js | 3 + src/overlays/worldOverlay.js | 91 +++++---- src/overlays/worldOverlay.test.mjs | 16 +- .../worldOverlayAllocation.worker.mjs | 3 + 9 files changed, 274 insertions(+), 57 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 370edcd7b..26cf5af18 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -5322,7 +5322,7 @@ silently demoting every later lookup for the session. Mission world text has no native `LabelGraphics`: overview launch markers publish at most 48 ambient candidates for a 24-winner budget, while selecting a mission clears that overview source and publishes its launch-site callout, stage re-entry annotations, live/estimated payload-position readout, and orbit annotation as protected selected-lane entries. The source retains the exact former strings and colors. Static anchors reuse the Cartesian values used to build their mission geometry; the moving payload entry reads the layer's per-frame live-position cache; catalog-backed orbit annotation positions are cached in the same one-second matrix update that realigns the orbit primitive. Keyhole edge fade, horizon culling, final collision placement, and UI exclusion are owned by the shared host. Deselect restores the bounded overview, and refresh, disable, and destroy replace or clear both mission sources. A selected mission renders its orbit as four repeating tactical sectors, each containing one prominent cyan dot followed by one hundred thin translucent dashes. The bright dots act as orbit anchors while the subdued dash field remains depth-tested against the globe and is shown only for the selected mission. Close selected-pad views add one static 500 m-radius cyan launch-zone ring with a low-opacity translucent fill over the sampled photoreal launch-site surface. The single scene primitive is created only for the visible selected site and is otherwise dormant. It appears during Focus, sufficiently close manual zoom, and the replay countdown, but is suppressed above 120 km camera altitude, beyond 180 km direct camera-to-pad range, for unselected missions, and whenever Space Missions is inactive. Focus establishes a launch-site-centered camera transform once; subsequent manual heading and pitch changes remain centered on that site without an automated per-frame correction. Surface mission markers and labels use an additional conservative globe-limb margin before the exact ellipsoid occluder boundary, preventing near-horizon visibility from alternating between frames. -- **AIS vessels**: chevron symbology (naval cyan base, type tints), world-space headings, MMSI-keyed reconciliation (selection survives refreshes; pinned 3 refreshes with STALE marker when absent), detection-overlay integration (`type: 'SEA'`; a vessel whose ambient card the shared host paints in the current frame draws no detection callout, because the callout would show through the card's plate, while a vessel whose card was published but not painted (shared budget, collisions, UI chrome) keeps its callout — its detectable object names the card in `cardSourceId`/`cardEntryId`, and the callout lane asks `isOverlayEntryQueued` in `src/overlays/worldOverlay.js`, which answers from the solved paint queue because the detection lane paints before the cards publish their paint rects), contextStore registration for voice Q&A. Empty-space clicks, id-less photorealistic-tile picks, and Escape dismiss the vessel card/HUD/context and clear its trail; picks owned by another layer (including `gev-trail:*`) and raw vessel-record picks without a live MMSI key are no-ops for vessel selection. Click and key handlers detach while the layer is disabled and reinstall on enable. Selecting another vessel replaces the selection and trail, and reconciliation clears a trail if its owning vessel is evicted. +- **AIS vessels**: chevron symbology (naval cyan base, type tints), world-space headings, MMSI-keyed reconciliation (selection survives refreshes; pinned 3 refreshes with STALE marker when absent), detection-overlay integration (`type: 'SEA'`; a vessel's detection callout fades out while its own ambient card paints in the same frame, judged by the card's painted opacity including the keyhole fade, so a card dropped by budget, collisions or UI chrome, or faded out at the keyhole rim, leaves the callout readable), contextStore registration for voice Q&A. Empty-space clicks, id-less photorealistic-tile picks, and Escape dismiss the vessel card/HUD/context and clear its trail; picks owned by another layer (including `gev-trail:*`) and raw vessel-record picks without a live MMSI key are no-ops for vessel selection. Click and key handlers detach while the layer is disabled and reinstall on enable. Selecting another vessel replaces the selection and trail, and reconciliation clears a trail if its owning vessel is evicted. - **Track trails**: server accumulates per-MMSI ring buffers (`/api/vessels/track?mmsi=`, Float32+Uint32, 64 samples, 30s/25m thinning); aircraft backfill proxies `/api/flights/track` (OAuth, own credit bucket). Military aircraft keep only their locally accumulated trails: `/api/military/track` validates the hex, then answers `503 history_unavailable` without an upstream request. - Shared `src/data/pickRegistry.js` stops the two flight layers' click handlers from fighting over the camera. diff --git a/src/data/aisLiveVessels.test.mjs b/src/data/aisLiveVessels.test.mjs index edb3505f2..e1c2fcc5a 100644 --- a/src/data/aisLiveVessels.test.mjs +++ b/src/data/aisLiveVessels.test.mjs @@ -1821,6 +1821,7 @@ test('detection objects name the vessel card their callout gives way to', () => 'vessel:unkeyed:NO MMSI:37.80000:-122.40000', 'the same identity the vessel card is published under', ); + assert.equal(keyed.overlayEntryId, 'vessel:200', 'cached on the record for later frames'); } finally { _setVesselStateForTest({ enabled: false }); } diff --git a/src/data/detection.js b/src/data/detection.js index 8ea124649..f4d1ddf3b 100644 --- a/src/data/detection.js +++ b/src/data/detection.js @@ -22,7 +22,7 @@ import { keyholeLabelAlphaFromGeometry, } from '../celestialRing.js'; import { - isOverlayEntryQueued, + getQueuedOverlayEntryAlpha, registerWorldOverlayPaintLane, } from '../overlays/worldOverlay.js'; import { @@ -110,6 +110,11 @@ const THEME_MAP = DETECTION_THEME_MAP; const SPARSE_ZONE_FRACTION = 0.5; /** Solve cadence for membership/collision; accepted identities still reproject every frame. */ const LABEL_SOLVE_INTERVAL_MS = 125; +/** + * A contact's own card at this opacity or more hides its callout; below it the + * callout fades in, so a card fading in or out never snaps the callout. + */ +const CARD_ALPHA_HIDING_CALLOUT = 0.5; /** Alpha bands retain bracket batching while approximating a continuous radial fade. */ const BRACKET_ALPHA_STEPS = 4; /** Finer bands for Global Context echo brackets, whose fade is animated. */ @@ -579,8 +584,8 @@ export function getDetectionDiagnostics() { // sprites/strokes. Nothing is copied on the production paint path. result.calloutRects = _calloutPool .slice(0, _calloutCount) - .filter((row) => !row.yielded) - .map(({ x, y, w, h, alpha }) => ({ x, y, w, h, alpha })); + .filter((row) => row.paintAlpha > 0.001) + .map(({ x, y, w, h, paintAlpha }) => ({ x, y, w, h, alpha: paintAlpha })); return result; } @@ -1083,7 +1088,7 @@ function _stashCallout(entry, acquireFade, keyhole) { alpha: 1, cardSourceId: '', cardEntryId: '', - yielded: false, + paintAlpha: 1, }; _calloutPool[_calloutCount] = row; } @@ -1112,7 +1117,7 @@ function _stashCallout(entry, acquireFade, keyhole) { row.alpha = alpha; row.cardSourceId = candidate.cardSourceId; row.cardEntryId = candidate.cardEntryId; - row.yielded = false; + row.paintAlpha = alpha; _calloutCount++; } @@ -1144,15 +1149,15 @@ function _paintCalloutLane(frame) { ctx.textBaseline = 'alphabetic'; for (let i = 0; i < _calloutCount; i++) { const row = _calloutPool[i]; - // The contact's own card (an ambient vessel card) already names it, and - // this callout would show through the card's plate. Checked every frame - // against the cards queued for THIS frame: the host paints only part of - // the published cards, and a contact whose card did not paint keeps its - // callout. - row.yielded = - row.cardEntryId !== '' && - isOverlayEntryQueued(row.cardSourceId, row.cardEntryId); - if (!row.yielded) paintDetectionCallout(ctx, row, row.alpha); + // Under the contact's own card (an ambient vessel card) the callout would + // show through the plate. Only a card painting this frame counts. + const cardAlpha = + row.cardEntryId === '' + ? 0 + : getQueuedOverlayEntryAlpha(row.cardSourceId, row.cardEntryId); + row.paintAlpha = + row.alpha * Math.max(0, 1 - cardAlpha / CARD_ALPHA_HIDING_CALLOUT); + if (row.paintAlpha > 0.001) paintDetectionCallout(ctx, row, row.paintAlpha); } ctx.globalAlpha = 1; } diff --git a/src/data/detectionHost.test.mjs b/src/data/detectionHost.test.mjs index 7bcb9300e..4c1c6dddc 100644 --- a/src/data/detectionHost.test.mjs +++ b/src/data/detectionHost.test.mjs @@ -21,10 +21,17 @@ import { import { clearOverlaySource, destroyWorldOverlay, + getOverlayPaintRect, initWorldOverlay, setOverlayEntries, setOverlaySourceVisible, } from '../overlays/worldOverlay.js'; +import { applyVesselOverlayPolicy } from './vesselLabels.js'; +import { + getKeyholeFadeTuning, + getKeyholeGeometry, + keyholeLabelAlphaFromGeometry, +} from '../celestialRing.js'; import { DETECTION_THEME_MAP } from '../overlays/worldOverlayTokens.js'; import { clearAwarenessEchoField, @@ -641,6 +648,173 @@ test('a callout gives way to its contact\'s own card only while that card paints } }); +/** A vessel detection contact that names its ambient card, like the AIS layer does. */ +function shipWithCard(mmsi, position) { + return { + position, + sourceId: mmsi, + id: `SHIP-${mmsi}`, + metric: '6 kn', + type: 'SEA', + cardSourceId: 'ais-live-vessels', + cardEntryId: `vessel:${mmsi}`, + }; +} + +/** The production ambient vessel card (not protected: it goes through the arbiter). */ +function ambientVesselCard(mmsi, position) { + return applyVesselOverlayPolicy({ + id: `vessel:${mmsi}`, + position, + title: `CARD-${mmsi}`, + details: ['CARGO · 6KT · 80°'], + gapPx: 10, + }); +} + +test('a callout stays readable when its own card is faded out at the keyhole rim', () => { + // Default keyhole tuning: 7% feather, 1% outside opacity. + assert.deepEqual(getKeyholeFadeTuning(), { fadeRatio: 0.07, outsideOpacity: 0.01 }); + const width = 1600; + const height = 900; + const keyhole = getKeyholeGeometry(width, height); + const env = installEnvironment({ width, height, dpr: 1 }); + // Just outside the keyhole's left rim: the card sits above or below the + // anchor (outside, 1% alpha), the callout to its right (inside the feather). + const position = new Cesium.Cartesian3(270 / (width / 2) - 1, 1 - 460 / (height / 2), 6_356_752); + const ship = shipWithCard('200', position); + try { + initWorldOverlay(env.viewer); + initDetection(env.viewer, [{ id: 'ais-live-vessels', getDetectableObjects: () => [ship] }], () => {}); + setMode('DENSE'); + for (let i = 0; i < 4; i++) settleFrame(env); + const [alone] = getDetectionDiagnostics().calloutRects; + assert.ok(alone && alone.alpha >= 0.5, 'without a card the callout is clearly visible'); + + setOverlayEntries('ais-live-vessels', [ambientVesselCard('200', position)]); + for (let i = 0; i < 4; i++) settleFrame(env); + const rect = getOverlayPaintRect('ais-live-vessels', 'vessel:200'); + assert.ok(rect, 'the host paints the card (at the outside opacity)'); + const cardAlpha = keyholeLabelAlphaFromGeometry(rect.x + rect.w / 2, rect.y + rect.h / 2, keyhole); + assert.ok(cardAlpha <= 0.05, `the card is invisible at the rim (keyhole alpha ${cardAlpha})`); + + const callouts = getDetectionDiagnostics().calloutRects; + assert.equal(callouts.length, 1, 'the callout keeps painting while its card is faded out'); + assert.ok(callouts[0].alpha >= 0.4, 'and stays readable'); + } finally { + destroyDetection(); + destroyWorldOverlay(); + env.cleanup(); + } +}); + +test('a callout stays hidden while its card fades out after leaving the published cohort', () => { + const env = installEnvironment({ width: 1600, height: 900, dpr: 1 }); + const at = (x, y) => new Cesium.Cartesian3(x, y, 6_356_752); + const ship = shipWithCard('200', at(0.1, 0.1)); + const painted = (text) => env.ctx.calls.some(([name, value]) => name === 'fillText' && value === text); + const frame = (ms) => { + env.ctx.calls.length = 0; + env.advance(ms); + env.postRender.raise(); + }; + try { + initWorldOverlay(env.viewer); + initDetection(env.viewer, [{ id: 'ais-live-vessels', getDetectableObjects: () => [ship] }], () => {}); + setMode('DENSE'); + setOverlayEntries('ais-live-vessels', [ambientVesselCard('200', ship.position)]); + for (let i = 0; i < 6; i++) frame(250); + frame(16); + assert.ok(painted('CARD-200') && !painted('SHIP-200'), 'steady state: card only'); + + // The vessel layer republishes its screen-grid cohort after a camera move: + // this vessel's card is replaced by another one, the vessel stays detectable. + setOverlayEntries('ais-live-vessels', [ambientVesselCard('300', at(-0.5, -0.4))]); + frame(16); + assert.ok(getOverlayPaintRect('ais-live-vessels', 'vessel:200'), 'the dropped card is still fading out'); + assert.ok(painted('CARD-200'), 'and its text still paints'); + assert.ok(!painted('SHIP-200'), 'no full callout under the fading card'); + + for (let i = 0; i < 4; i++) frame(250); + assert.ok(!painted('CARD-200'), 'the card has faded out'); + assert.ok(painted('SHIP-200'), 'and the callout is back'); + } finally { + destroyDetection(); + destroyWorldOverlay(); + env.cleanup(); + } +}); + +test('a vessel whose ambient card loses the collision keeps its callout', () => { + const env = installEnvironment({ width: 900, height: 600, dpr: 1 }); + // Four vessels a few pixels apart: their cards collide (a card goes only + // above or below its anchor), so the arbiter paints only some of them. + const ships = [0, 1, 2, 3].map((i) => + shipWithCard(String(100 + i), new Cesium.Cartesian3(-0.2 + i * 0.005, i * 0.005, 6_356_752)), + ); + const painted = (text) => env.ctx.calls.some(([name, value]) => name === 'fillText' && value === text); + try { + initWorldOverlay(env.viewer); + initDetection(env.viewer, [{ id: 'ais-live-vessels', getDetectableObjects: () => ships }], () => {}); + setOverlayEntries( + 'ais-live-vessels', + ships.map((ship) => ambientVesselCard(ship.sourceId, ship.position)), + ); + setMode('DENSE'); + for (let i = 0; i < 4; i++) settleFrame(env); + env.ctx.calls.length = 0; + settleFrame(env); + + const winners = ships.filter((ship) => getOverlayPaintRect('ais-live-vessels', ship.cardEntryId)); + assert.ok( + winners.length >= 1 && winners.length < ships.length, + `the colliding cards leave some unpainted (${winners.length} of ${ships.length} painted)`, + ); + for (const ship of ships) { + const carded = winners.includes(ship); + assert.equal( + painted(ship.id), + !carded, + carded ? `${ship.id} draws no callout under its card` : `${ship.id} keeps its callout`, + ); + } + } finally { + destroyDetection(); + destroyWorldOverlay(); + env.cleanup(); + } +}); + +test('a callout fades out while its card fades in instead of vanishing at once', () => { + const env = installEnvironment({ width: 1600, height: 900, dpr: 1 }); + const ship = shipWithCard('200', new Cesium.Cartesian3(0.1, 0.1, 6_356_752)); + try { + initWorldOverlay(env.viewer); + initDetection(env.viewer, [{ id: 'ais-live-vessels', getDetectableObjects: () => [ship] }], () => {}); + setMode('DENSE'); + for (let i = 0; i < 4; i++) settleFrame(env); + const [alone] = getDetectionDiagnostics().calloutRects; + assert.ok(alone.alpha >= 0.9, 'the callout starts fully visible'); + + setOverlayEntries('ais-live-vessels', [ambientVesselCard('200', ship.position)]); + const alphas = []; + for (let i = 0; i < 30; i++) { + env.advance(16); + env.postRender.raise(); + alphas.push(getDetectionDiagnostics().calloutRects[0]?.alpha ?? 0); + } + assert.ok( + alphas.some((alpha) => alpha > 0.1 && alpha < alone.alpha - 0.1), + `the callout passes through partial opacity: ${alphas.map((a) => a.toFixed(2)).join(' ')}`, + ); + assert.equal(alphas.at(-1), 0, 'and is gone once the card is fully in'); + } finally { + destroyDetection(); + destroyWorldOverlay(); + env.cleanup(); + } +}); + test('space-tier callouts take the heavier plate while air contacts keep the light one', () => { // Satellites sit over the high-albedo lit Earth disc far more often than // aircraft do, so the space tier carries the heavier backing. Losing the diff --git a/src/layers/vessels/cards.js b/src/layers/vessels/cards.js index bcf3459f1..2563bf420 100644 --- a/src/layers/vessels/cards.js +++ b/src/layers/vessels/cards.js @@ -117,6 +117,14 @@ export function createCards({ /** Stable overlay identity for MMSI-keyed and source-retained unkeyed rows. */ function vesselOverlayEntryId(record) { + // Cached on the record: detection asks for it every frame for every vessel. + if (record?.overlayEntryId) return record.overlayEntryId; + const id = composeVesselOverlayEntryId(record); + if (record) record.overlayEntryId = id; + return id; + } + + function composeVesselOverlayEntryId(record) { const mmsi = String(record?.mmsi || '').trim(); if (mmsi) return `vessel:${mmsi}`; const name = String(record?.name || 'VESSEL').trim() || 'VESSEL'; diff --git a/src/layers/vessels/records.js b/src/layers/vessels/records.js index ad6d85cbd..aeb2f39bf 100644 --- a/src/layers/vessels/records.js +++ b/src/layers/vessels/records.js @@ -23,6 +23,9 @@ export function normalizeVessel(row) { lastPositionUtc: String(row.last_position_UTC || ''), lastPositionEpoch: finiteNumber(row.last_position_epoch), missedRefreshes: 0, + // Filled on first use by the cards' `vesselOverlayEntryId`. The id reads + // only the MMSI, or for an unkeyed row fields it never updates. + overlayEntryId: null, }; } diff --git a/src/overlays/worldOverlay.js b/src/overlays/worldOverlay.js index 726e766ee..aabcc7be0 100644 --- a/src/overlays/worldOverlay.js +++ b/src/overlays/worldOverlay.js @@ -258,6 +258,10 @@ const _paintQueue = []; const _paintItemPool = []; const _paintRectPool = []; const _paintRectByKey = new Map(); +/** @type {Map>} This frame's paint items by source and entry id. */ +const _queuedItemBySource = new Map(); +/** Index rows that stop painting are dropped this many frames apart. */ +const QUEUED_ITEM_PRUNE_FRAMES = 600; const _hitRects = []; const _paintedBySource = Object.create(null); const _paintedSourceKeys = []; @@ -1066,24 +1070,26 @@ export function getOverlayPaintRect(sourceId, entryId) { } /** - * Whether an entry is queued to paint in the frame being painted. Custom lanes - * run before the host's own entries, so `getOverlayPaintRect` has nothing for - * this frame yet while they paint; this answers from the solved paint queue. + * Opacity an entry will paint with in the frame being painted, or 0 when it is + * not queued. Valid from the custom lanes, which paint before the entries in + * later lanes publish their paint rects. Leaves out only the Cyber sonar fade. * @param {string} sourceId * @param {string} entryId - * @returns {boolean} + * @returns {number} */ -export function isOverlayEntryQueued(sourceId, entryId) { - if (_destroyed) return false; - const record = _records.get(entryKey(String(sourceId), String(entryId))); - if (!record || record.queuedStamp !== _frameStamp) return false; - // Same channels as the paint, minus the per-frame keyhole and sonar fades. +export function getQueuedOverlayEntryAlpha(sourceId, entryId) { + if (_destroyed) return 0; + const item = _queuedItemBySource.get(sourceId)?.get(entryId); + // Pooled items are reassigned every frame: check the frame and the entry. + if (!item || item.stamp !== _frameStamp) return 0; + const record = item.record; + if (record.entry.id !== entryId || record.entry.source !== sourceId) return 0; return ( record.sourceAlpha * - record.queuedItem.temporalAlpha * - record.distanceAlpha * - record.altitudeAlpha > - 0.001 + item.temporalAlpha * + record.distanceAlpha * + record.altitudeAlpha * + (_keyhole ? entryKeyholeAlpha(record.entry, item.placement, _keyhole) : 1) ); } @@ -1759,8 +1765,6 @@ function getProjectionRecord(entry) { contentAlpha: 1, altitudeAlpha: 1, sourceAlpha: 1, - queuedStamp: 0, - queuedItem: null, protectedPlacement: null, distanceOptions: {}, altitudeOptions: {}, @@ -2277,12 +2281,27 @@ function addPaintItem(record, placement, temporalAlpha, selected) { item.lane = paintLaneForOverlayEntry(record.entry); item.zIndex = record.entry.zIndex; item.key = record.key; + item.stamp = _frameStamp; _paintQueue[_paintCount++] = item; - // Read by `isOverlayEntryQueued` while the custom lanes paint, before this - // item publishes its paint rect. Only a stamp and a pointer: storing the - // item's alpha here would box a double per paint item per frame. - record.queuedStamp = _frameStamp; - record.queuedItem = item; + // Indexed by source and id rather than by `record.key`, so a lookup builds + // no string. A card fading out after it left its source's entries is still + // queued here, though `_records` no longer has it. + let bySource = _queuedItemBySource.get(record.entry.source); + if (!bySource) { + bySource = new Map(); + _queuedItemBySource.set(record.entry.source, bySource); + } + bySource.set(record.entry.id, item); +} + +/** Drop index rows for entries that stopped painting (bounded, not per frame). */ +function pruneQueuedItemIndex() { + for (const [sourceId, bySource] of _queuedItemBySource) { + for (const [entryId, item] of bySource) { + if (item.stamp !== _frameStamp) bySource.delete(entryId); + } + if (bySource.size === 0) _queuedItemBySource.delete(sourceId); + } } function sourceCanPaint(sourceId) { @@ -2354,6 +2373,7 @@ function solveDomains(timestamp) { solveRevision += domain.arbiter.solveRevision; } _paintQueue.length = _paintCount; + if (_frameStamp % QUEUED_ITEM_PRUNE_FRAMES === 0) pruneQueuedItemIndex(); _solveDirty = false; _diagnostics.solveMs = solveMs; _diagnostics.selectedCount = selectedCount; @@ -2482,23 +2502,25 @@ function paintCustomLane(lane) { } } +/** Keyhole edge fade of one placed entry (1 for entries that do not fade). */ +function entryKeyholeAlpha(entry, placement, keyhole) { + if (entry.edgeFade !== 'keyhole') return 1; + const keyholeX = placement.centerX - keyhole.centerX; + const keyholeY = placement.centerY - keyhole.centerY; + return keyholeX * keyholeX + keyholeY * keyholeY <= + keyhole.radius * keyhole.radius + ? 1 + : keyholeLabelAlphaFromGeometry( + placement.centerX, + placement.centerY, + keyhole, + ); +} + function paintEntryItem(item, keyhole, sonar) { const { record, placement } = item; const entry = record.entry; - let keyholeAlpha = 1; - if (entry.edgeFade === 'keyhole') { - const keyholeX = placement.centerX - keyhole.centerX; - const keyholeY = placement.centerY - keyhole.centerY; - keyholeAlpha = - keyholeX * keyholeX + keyholeY * keyholeY <= - keyhole.radius * keyhole.radius - ? 1 - : keyholeLabelAlphaFromGeometry( - placement.centerX, - placement.centerY, - keyhole, - ); - } + const keyholeAlpha = entryKeyholeAlpha(entry, placement, keyhole); // All five channels are normalized at their source. Keep the multiply on // the hot paint path so its intermediate doubles remain unboxed; the pure // `combinedOverlayAlpha` export still specifies/tests the same binding. @@ -2799,6 +2821,7 @@ export function destroyWorldOverlay() { _accessibleActivatorByKey.clear(); _accessibilitySignature = ''; _paintRectByKey.clear(); + _queuedItemBySource.clear(); _paintCount = 0; _paintRectCount = 0; _hitRectCount = 0; diff --git a/src/overlays/worldOverlay.test.mjs b/src/overlays/worldOverlay.test.mjs index a0b5160b6..6e713a5da 100644 --- a/src/overlays/worldOverlay.test.mjs +++ b/src/overlays/worldOverlay.test.mjs @@ -24,7 +24,7 @@ import { activateWorldOverlayAction, initWorldOverlay, subscribeWorldOverlayActions, - isOverlayEntryQueued, + getQueuedOverlayEntryAlpha, isOverlayPointVisible, normalizeOverlayEntry, paintLaneForOverlayEntry, @@ -1216,16 +1216,16 @@ test('custom detection lane receives the shared host frame and paints below ordi test('a detection lane sees which cards this frame will paint before they publish paint rects', () => { // The detection lane paints first, so a card's paint rectangle for this - // frame does not exist yet when it runs. The queued check is what lets a + // frame does not exist yet when it runs. The queued alpha is what lets a // contact's callout give way to that contact's own card in the same frame. const env = installMockEnvironment({ width: 400, height: 300, dpr: 1 }); initWorldOverlay(env.viewer); const seen = []; registerWorldOverlayPaintLane('detection', () => { seen.push({ - shown: isOverlayEntryQueued('cards', 'SHOWN'), - hidden: isOverlayEntryQueued('hidden-cards', 'HIDDEN'), - unknown: isOverlayEntryQueued('cards', 'NOT-PUBLISHED'), + shown: getQueuedOverlayEntryAlpha('cards', 'SHOWN'), + hidden: getQueuedOverlayEntryAlpha('hidden-cards', 'HIDDEN'), + unknown: getQueuedOverlayEntryAlpha('cards', 'NOT-PUBLISHED'), rect: getOverlayPaintRect('cards', 'SHOWN'), }); }, { id: 'detection', active: true, target: 'detection' }); @@ -1238,16 +1238,16 @@ test('a detection lane sees which cards this frame will paint before they publis setOverlaySourceVisible('hidden-cards', false); env.postRender.raise(); - assert.deepEqual(seen[0], { shown: true, hidden: false, unknown: false, rect: null }, + assert.deepEqual(seen[0], { shown: 1, hidden: 0, unknown: 0, rect: null }, 'the card is queued while its paint rect is still unpublished'); assert.ok(getOverlayPaintRect('cards', 'SHOWN'), 'the card did paint after the lane'); assert.equal(getOverlayPaintRect('hidden-cards', 'HIDDEN'), null); clearOverlaySource('cards'); env.postRender.raise(); - assert.equal(seen[1].shown, false, 'a card cleared since the last frame is no longer queued'); + assert.equal(seen[1].shown, 0, 'a card cleared since the last frame is no longer queued'); destroyWorldOverlay(); - assert.equal(isOverlayEntryQueued('cards', 'SHOWN'), false); + assert.equal(getQueuedOverlayEntryAlpha('cards', 'SHOWN'), 0); env.cleanup(); }); diff --git a/src/overlays/worldOverlayAllocation.worker.mjs b/src/overlays/worldOverlayAllocation.worker.mjs index e2a4c6240..93b47e7f3 100644 --- a/src/overlays/worldOverlayAllocation.worker.mjs +++ b/src/overlays/worldOverlayAllocation.worker.mjs @@ -1217,6 +1217,9 @@ function buildPhase6DetectionWorkload(count) { : `FL${String(180 + (index % 220)).padStart(3, '0')}`, type: ['AIR', 'SAT', 'SEA', 'VEH'][index % 4], tier: index % 17 === 0 ? 'military' : undefined, + // Vessels name their ambient card, so each callout asks the host for it. + cardSourceId: index % 4 === 2 ? 'ais-live-vessels' : undefined, + cardEntryId: index % 4 === 2 ? `vessel:${index}` : undefined, }); } return { From 90db4eb2c9ed0c61adbfe6ffaf7a17b1ffe1d829 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Thu, 5 Nov 2026 21:21:03 +0400 Subject: [PATCH 034/171] Name the real gate altitude and repaint coverage rows at once The Transit prompt said "Fly below 3,000 km", but the closed gate opens at 2,850 km; it now names the enter threshold, as Bike Share does. When the camera changes coverage, Transit and Bike Share ask the Layers panel to repaint instead of leaving the old prompt up until the next 15 s / 60 s tick. --- docs/CURRENT-STATE.md | 2 +- src/layers/bikeshare/controls.js | 9 ++ src/layers/bikeshare/lifecycle.js | 1 + src/layers/bikeshare/state.js | 4 + src/layers/bikeshare/viewport.js | 17 ++++ src/layers/promptRepaint.test.mjs | 122 +++++++++++++++++++++++++ src/layers/transit/gatePrompt.test.mjs | 66 +++++++++++++ src/layers/transit/lifecycle.test.mjs | 2 +- src/layers/transit/queries.js | 4 +- src/layers/transit/viewport.js | 7 ++ src/ui/statusText.test.mjs | 2 +- src/voice/analystEmptyNotes.test.mjs | 2 +- src/voice/resultDisplay.js | 2 +- 13 files changed, 233 insertions(+), 7 deletions(-) create mode 100644 src/layers/promptRepaint.test.mjs create mode 100644 src/layers/transit/gatePrompt.test.mjs diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 8368eeacf..946254fbf 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1819,7 +1819,7 @@ errors. Transit and Bike Share report the same kind of guidance when no feed or system covers the view, instead of an undated `never`. Above their altitude gates the -rows read `GTFS-RT · Fly below 3,000 km to a covered region` and +rows read `GTFS-RT · Fly below 2,850 km to a covered region` and `GBFS · Fly below 48 km to a covered city`; lower down over a city neither covers (London, Tokyo) they read `GTFS-RT · No feed here yet · N regions available` and `GBFS · No bike share here yet · N systems available`, N being diff --git a/src/layers/bikeshare/controls.js b/src/layers/bikeshare/controls.js index 993022506..78edd907b 100644 --- a/src/layers/bikeshare/controls.js +++ b/src/layers/bikeshare/controls.js @@ -14,6 +14,15 @@ export function createControls({ state: layerState, services, parts, source }) { updateInterval: STATUS_POLL_MS, + /** + * Keep the manager so camera-driven coverage changes can repaint the row + * before the next status poll. + * @param {object} dataManager DataLayerManager instance. + */ + attachDataManager(dataManager) { + layerState._dataManager = dataManager; + }, + /** * Return a sampled array of detectable station objects for HUD overlay rendering. * @param {Object} [options] - Sampling options (maxCount, seed). diff --git a/src/layers/bikeshare/lifecycle.js b/src/layers/bikeshare/lifecycle.js index 3e46b5972..050269bfd 100644 --- a/src/layers/bikeshare/lifecycle.js +++ b/src/layers/bikeshare/lifecycle.js @@ -169,6 +169,7 @@ export function createLifecycle({ viewer.scene.primitives.remove(layerState._pointCollection); layerState._pointCollection = null; } + layerState._dataManager = null; layerState._viewer = null; }, }; diff --git a/src/layers/bikeshare/state.js b/src/layers/bikeshare/state.js index 3617914bf..518c2397a 100644 --- a/src/layers/bikeshare/state.js +++ b/src/layers/bikeshare/state.js @@ -19,6 +19,10 @@ export function createState({ services }) { layerState._viewer = null; + /** @type {{ refreshLayerStats?: () => void }|null} Manager that repaints the layer's row. */ + + layerState._dataManager = null; + /** @type {Cesium.PointPrimitiveCollection|null} Primitive collection for station dots. */ layerState._pointCollection = null; diff --git a/src/layers/bikeshare/viewport.js b/src/layers/bikeshare/viewport.js index 0739d341c..dbc328f61 100644 --- a/src/layers/bikeshare/viewport.js +++ b/src/layers/bikeshare/viewport.js @@ -116,6 +116,14 @@ export function createViewport({ state: layerState, services, parts, source }) { parts.rendering.removeCityPoints(cityId); } + /** + * Repaint the layer's row now. Its text follows the camera (coverage + * prompt, station count), and the manager tick is 60 s. + */ + function refreshRow() { + layerState._dataManager?.refreshLayerStats?.(); + } + /** Deactivate all currently active cities and clear the active set. */ function deactivateAllCities() { @@ -205,9 +213,11 @@ export function createViewport({ state: layerState, services, parts, source }) { const generation = ++layerState._proximityGeneration; const altitude = getCameraAltitude(layerState._viewer); + const wasGateEnabled = layerState._altitudeGateEnabled; // Altitude gate: disable all cities when camera is too high if (!shouldActivateAtAltitude(altitude)) { deactivateAllCities(); + if (wasGateEnabled) refreshRow(); return; } @@ -226,12 +236,18 @@ export function createViewport({ state: layerState, services, parts, source }) { if (!nextActive.has(cityId)) layerState._failedCityIds.delete(cityId); } + const changed = + !wasGateEnabled || + nextActive.size !== layerState._activeCityIds.size || + [...nextActive].some((cityId) => !layerState._activeCityIds.has(cityId)); layerState._activeCityIds = nextActive; if (layerState._activeCityIds.size === 0) { layerState._count = 0; layerState._lastUpdate = null; + if (changed) refreshRow(); return; } + if (changed) refreshRow(); // Only activate cities that don't already have rendered points const toActivate = []; @@ -243,6 +259,7 @@ export function createViewport({ state: layerState, services, parts, source }) { await Promise.all( toActivate.map((cityId) => activateCity(cityId, generation)), ); + if (generation === layerState._proximityGeneration) refreshRow(); } /** Schedule a debounced proximity check after camera movement. */ diff --git a/src/layers/promptRepaint.test.mjs b/src/layers/promptRepaint.test.mjs new file mode 100644 index 000000000..563aaeac7 --- /dev/null +++ b/src/layers/promptRepaint.test.mjs @@ -0,0 +1,122 @@ +// When the camera changes which coverage prompt a Transit or +// Bike Share row shows, the layer asks the panel to repaint at once, instead +// of leaving the old prompt up until the manager's next tick (Transit 15 s, +// Bike Share 60 s). +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createState as createBikeState } from './bikeshare/state.js'; +import { createControls as createBikeControls } from './bikeshare/controls.js'; +import { createModel as createBikeModel } from './bikeshare/model.js'; +import { createViewport as createBikeViewport } from './bikeshare/viewport.js'; +import { createState as createTransitState } from './transit/state.js'; +import { createViewport as createTransitViewport } from './transit/viewport.js'; +import { createQueries as createTransitQueries } from './transit/queries.js'; + +const rad = Math.PI / 180; +const LONDON = { lat: 51.5072, lon: -0.1276 }; +const BOSTON = { lat: 42.3601, lon: -71.0589 }; + +const services = () => ({ + overlays: { + setOverlayEntries() {}, + setOverlaySourceVisible() {}, + clearOverlaySource() {}, + }, + render: { governorRequestRender() {} }, +}); + +function viewer(at, height) { + return { + camera: { + positionCartographic: { + height, + latitude: at.lat * rad, + longitude: at.lon * rad, + }, + computeViewRectangle: () => undefined, + }, + scene: { globe: {} }, + }; +} + +function spyManager() { + const dm = { repaints: 0 }; + dm.refreshLayerStats = () => { + dm.repaints++; + }; + return dm; +} + +test('Bike Share: flying from London into Boston repaints the prompt row', async () => { + const svc = services(); + const state = createBikeState({ services: svc }); + const parts = { + queries: { collectDetectableStations: () => [] }, + model: createBikeModel({ state, services: svc, parts: {}, source: null }), + ingestion: { + abortInFlight() {}, + loadCityStationInfo: async () => new Map(), + loadCityStationStatus: async () => new Map(), + }, + rendering: { + removeCityPoints() {}, + ensureCityPoints() {}, + applyStatusToPoints() {}, + }, + }; + parts.viewport = createBikeViewport({ + state, + services: svc, + parts, + source: null, + }); + const { methods } = createBikeControls({ + state, + services: svc, + parts, + source: {}, + }); + state._enabled = true; + const dm = spyManager(); + methods.attachDataManager(dm); + + state._viewer = viewer(LONDON, 8_000); + await parts.viewport.runProximityCheck(); + assert.equal(methods.getStats().status, 'zoom-in'); + + const before = dm.repaints; + state._viewer = viewer(BOSTON, 3_000); + await parts.viewport.runProximityCheck(); + assert.equal(methods.getStats().status, undefined, 'Boston is covered'); + assert.ok(dm.repaints > before, 'the row was asked to repaint'); +}); + +test('Transit: leaving Boston for London repaints the row', () => { + const svc = services(); + const state = createTransitState({ services: svc }); + const parts = { + ingestion: { + feedStatus: () => ({ count: 0 }), + pollFeed() {}, + removeFeedVehicles() {}, + sweepAgedVehicles() {}, + }, + rendering: { requestVisibility() {}, syncRenderHold() {} }, + }; + parts.viewport = createTransitViewport({ state, services: svc, parts }); + const queries = createTransitQueries({ state, parts }).methods; + state._enabled = true; + const dm = spyManager(); + state._dataManager = dm; + + state._viewer = viewer(BOSTON, 4_000); + parts.viewport.runProximityCheck(); + assert.ok(state._activeFeeds.size > 0, 'Boston has a feed'); + state._lastUpdate = Date.now(); + + const before = dm.repaints; + state._viewer = viewer(LONDON, 4_000); + parts.viewport.runProximityCheck(); + assert.equal(queries.getStats().status, 'zoom-in'); + assert.ok(dm.repaints > before, 'the row was asked to repaint'); +}); diff --git a/src/layers/transit/gatePrompt.test.mjs b/src/layers/transit/gatePrompt.test.mjs new file mode 100644 index 000000000..7f439fcdc --- /dev/null +++ b/src/layers/transit/gatePrompt.test.mjs @@ -0,0 +1,66 @@ +// The Transit coverage prompt names the altitude the closed gate +// actually opens at. Descending over Boston to 2,900 km (below 3,000 km, above +// the 2,850 km enter threshold) loads nothing, so a prompt "Fly below 3,000 km" +// asks for something the camera has already done. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createState } from './state.js'; +import { createViewport } from './viewport.js'; +import { createQueries } from './queries.js'; +import { ACTIVATION_ENTER_ALTITUDE_M } from './policy.js'; + +const BOSTON = { lat: 42.3601, lon: -71.0589 }; + +function makeLayer() { + const services = { + overlays: { + setOverlayEntries() {}, + setOverlaySourceVisible() {}, + clearOverlaySource() {}, + }, + render: { governorRequestRender() {} }, + }; + const state = createState({ services }); + const polled = []; + const parts = { + ingestion: { + feedStatus: () => ({ count: 0 }), + pollFeed: (feed) => polled.push(feed.id), + removeFeedVehicles() {}, + sweepAgedVehicles() {}, + }, + rendering: { requestVisibility() {}, syncRenderHold() {} }, + }; + parts.viewport = createViewport({ state, services, parts }); + const queries = createQueries({ state, parts }).methods; + state._enabled = true; + const rad = Math.PI / 180; + state._viewer = { + camera: { + positionCartographic: { + height: 0, + latitude: BOSTON.lat * rad, + longitude: BOSTON.lon * rad, + }, + computeViewRectangle: () => undefined, + }, + scene: { globe: {} }, + }; + return { state, queries, viewport: parts.viewport, polled }; +} + +test('below the prompted altitude but above the gate, the prompt names the gate', () => { + const { state, queries, viewport, polled } = makeLayer(); + state._viewer.camera.positionCartographic.height = 2_900_000; + viewport.runProximityCheck(); + + // Nothing loads at 2,900 km: the gate opens at the enter threshold. + assert.equal(state._altitudeGateOpen, false); + assert.deepEqual(polled, []); + + const km = Math.round(ACTIVATION_ENTER_ALTITUDE_M / 1000).toLocaleString( + 'en-US', + ); + const { statusMessage } = queries.getStats(); + assert.equal(statusMessage, `Fly below ${km} km to a covered region`); +}); diff --git a/src/layers/transit/lifecycle.test.mjs b/src/layers/transit/lifecycle.test.mjs index a269dc9e9..dc18fd6f0 100644 --- a/src/layers/transit/lifecycle.test.mjs +++ b/src/layers/transit/lifecycle.test.mjs @@ -4018,6 +4018,6 @@ test('a view with no feed reads its coverage prompt, not an undated feed', async app.advance(1_000); assert.equal( app.layer.getStats().statusMessage, - 'Fly below 3,000 km to a covered region', + 'Fly below 2,850 km to a covered region', ); }); diff --git a/src/layers/transit/queries.js b/src/layers/transit/queries.js index 8023cdb39..748929213 100644 --- a/src/layers/transit/queries.js +++ b/src/layers/transit/queries.js @@ -1,5 +1,5 @@ import { - ACTIVATION_ALTITUDE_M, + ACTIVATION_ENTER_ALTITUDE_M, FEED_STALE_AFTER_MS, aggregateTransitFeedHealth, transitDetectionClass, @@ -245,7 +245,7 @@ export function createQueries({ state, parts }) { // (ui/statusText.js). const note = state._altitudeGateOpen ? `No feed here yet · ${TRANSIT_ENABLED_FEEDS.length} regions available` - : `Fly below ${Math.round(ACTIVATION_ALTITUDE_M / 1000).toLocaleString('en-US')} km to a covered region`; + : `Fly below ${Math.round(ACTIVATION_ENTER_ALTITUDE_M / 1000).toLocaleString('en-US')} km to a covered region`; return { count: 0, lastUpdate: state._lastUpdate, diff --git a/src/layers/transit/viewport.js b/src/layers/transit/viewport.js index 27cc0569c..0e3b317d4 100644 --- a/src/layers/transit/viewport.js +++ b/src/layers/transit/viewport.js @@ -83,7 +83,9 @@ export function createViewport({ state, services, parts }) { if (!state._enabled || !state._viewer) return; refreshViewBounds(); const altitude = getCameraAltitude(); + const wasGateOpen = state._altitudeGateOpen; state._altitudeGateOpen = altitudeGateOpen(altitude); + let changed = state._altitudeGateOpen !== wasGateOpen; const center = state._altitudeGateOpen ? getCameraCenterLatLon() : null; const desired = new Map(); if (center) { @@ -106,6 +108,7 @@ export function createViewport({ state, services, parts }) { state._activeFeeds.delete(feedId); state._feedStatus.delete(feedId); parts.ingestion.removeFeedVehicles(feedId); + changed = true; } } // Leaving coverage leaves nothing on the map to date: a row that read @@ -115,11 +118,15 @@ export function createViewport({ state, services, parts }) { if (!state._activeFeeds.has(feedId)) { state._activeFeeds.set(feedId, feed); void parts.ingestion.pollFeed(feed, state._generation); + changed = true; } } parts.ingestion.sweepAgedVehicles(Date.now()); parts.rendering.syncRenderHold(); governorRequestRender('transit-proximity'); + // The row's text follows the camera (coverage prompt, feed list), so it + // repaints now instead of at the next 15 s manager tick. + if (changed) state._dataManager?.refreshLayerStats?.(); } function onCameraChanged() { diff --git a/src/ui/statusText.test.mjs b/src/ui/statusText.test.mjs index 1b6479b45..6d1648b6d 100644 --- a/src/ui/statusText.test.mjs +++ b/src/ui/statusText.test.mjs @@ -83,7 +83,7 @@ for (const locale of ['es', 'ru']) { // A layer's coverage note when no feed covers the view: one sentence with a // " · " in it (transit/queries.js, bikeshare/controls.js). const COVERAGE_NOTES = [ - 'Fly below 3,000 km to a covered region', + 'Fly below 2,850 km to a covered region', 'No feed here yet · 16 regions available', 'Fly below 48 km to a covered city', 'No bike share here yet · 61 systems available', diff --git a/src/voice/analystEmptyNotes.test.mjs b/src/voice/analystEmptyNotes.test.mjs index b0de16ebd..cfacee4bf 100644 --- a/src/voice/analystEmptyNotes.test.mjs +++ b/src/voice/analystEmptyNotes.test.mjs @@ -70,7 +70,7 @@ const cases = [ // Transit's coverage text when nothing is in view (transit/queries.js). const transitCoverage = [ - 'transit: Fly below 3,000 km to a covered region', + 'transit: Fly below 2,850 km to a covered region', 'transit: No feed here yet · 12 regions available', ]; diff --git a/src/voice/resultDisplay.js b/src/voice/resultDisplay.js index cd909d2f7..72a929b94 100644 --- a/src/voice/resultDisplay.js +++ b/src/voice/resultDisplay.js @@ -423,7 +423,7 @@ function shownNote(text) { const shown = match ? show(match) : null; if (shown) return shown; } - // A layer's empty note can be its coverage note ("Fly below 3,000 km to a + // A layer's empty note can be its coverage note ("Fly below 2,850 km to a // covered region") or its status line, English pieces joined by " · " // ("feeds 1090, 978 stale · 0 heard", "TTC 0 (95s old)"). return translateStatusMessage(text); From dd83812a21daeb83b3bedbd48e99d81d53d68195 Mon Sep 17 00:00:00 2001 From: Denis Groshev Date: Wed, 4 Nov 2026 02:20:57 +0100 Subject: [PATCH 035/171] Hold Cockpit regional news to the last 24 hours, and tell its states apart MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Regional News showed "REGIONAL NEWS UNAVAILABLE" above populated rows and a static "RECENT" footer over months-old articles. The status banner kept `display: grid` when hidden, every non-empty answer carried the unavailable text, and nothing limited or sorted articles by age. - One window (regionalNewsWindow.js, 24 h): the local proxy asks Google News with `when:1d` and GDELT for 24 h, drops undated, older or future-dated articles, sorts newest first, and reports newsWindowHours/newsFetchedAt. - The Cockpit labels four states: fresh (banner hidden, "LAST 24 H"), kept after a failed refresh ("CACHED · REFRESH FAILED"), no news in the window, and unavailable. The footer lives in the news state, so it survives page and tab changes, and the client drops out-of-window rows. - `.cockpit-brief-status[hidden]` now hides the banner. --- changelog.d/0-regional-news-freshness.md | 7 + docs/CURRENT-STATE.md | 9 +- scripts/package-boundaries.json | 16 +- server/providers/regional/briefing.js | 7 +- server/providers/regional/news.js | 43 +++- src/data/regionalBrief.test.mjs | 38 ++++ src/data/regionalModel.js | 7 + src/data/regionalNewsWindow.js | 66 ++++++ src/data/regionalProxy.test.mjs | 48 +++++ src/i18n/locales/ar.json | 7 +- src/i18n/locales/de.json | 7 +- src/i18n/locales/es.json | 7 +- src/i18n/locales/fr.json | 7 +- src/i18n/locales/it.json | 7 +- src/i18n/locales/ja.json | 7 +- src/i18n/locales/pt.json | 7 +- src/i18n/locales/ru.json | 7 +- src/i18n/locales/uk.json | 7 +- src/i18n/locales/zh-CN.json | 7 +- src/i18n/locales/zh-Hant.json | 7 +- src/ui/cockpitBriefPages.js | 26 ++- src/ui/cockpitBriefing.js | 121 +++++++++-- src/ui/cockpitBriefing.test.mjs | 249 +++++++++++++++++++++-- src/ui/styles/cockpit.css | 8 +- 24 files changed, 637 insertions(+), 85 deletions(-) create mode 100644 changelog.d/0-regional-news-freshness.md create mode 100644 src/data/regionalNewsWindow.js diff --git a/changelog.d/0-regional-news-freshness.md b/changelog.d/0-regional-news-freshness.md new file mode 100644 index 000000000..b0d6d831f --- /dev/null +++ b/changelog.d/0-regional-news-freshness.md @@ -0,0 +1,7 @@ +- Cockpit Regional News holds its list to the last 24 hours, newest first, on + the server and in the client, and labels its four states apart: fresh + results with no banner and a `LAST 24 H` footer, earlier results kept after + a failed refresh as `CACHED · REFRESH FAILED`, `NO NEWS IN THE LAST 24 H`, + and `REGIONAL NEWS UNAVAILABLE`. The banner is now really hidden over a + populated list, and the footer no longer reverts to a static `RECENT` on a + page change. diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 3dd914597..084ad4f83 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1932,8 +1932,9 @@ Overpass query validation, geometry simplification, disk caching and upstream transport now have separate modules; military-installation search reuses that transport. Regional briefing combines separate place, news and weather sources, while weather effects uses only the weather source. -GDELT compact dates that do not name a real calendar instant keep the article -with an unknown publication time. Existing process-scoped +GDELT compact dates that do not name a real calendar instant normalize to an +unknown publication time, and the 24-hour regional-news window then drops the +article. Existing process-scoped caches, rate limits, stale fallbacks and route ordering are preserved. Local voice has separate HUD-summary, debug-log and Realtime-token handlers, @@ -6096,11 +6097,11 @@ apply to `public/` assets or built-preview serving. `CONTEXT STANDBY`. The visible Cockpit actions, the `C` shortcut and voice use the same gate; voice entry still opens Contacts first, as its layer-targeted entry navigates through Contacts. -- **Aircraft cockpit view:** selecting a commercial or military aircraft reveals a `COCKPIT` action (`C`) once that aircraft's own layer is on; Contacts is not required. The action shows in Contacts (`#cockpit-entry`) and under the Intel HUD's bottom-right readout (`#cockpit-entry-readout`, with the HUD on, in its Tactical and Cyber layouts), so entry needs no Contacts panel. Turning off the ridden aircraft's layer ends the view (the layer clears its tracking). When an air feed the surrounding picture uses is off, the Cockpit says so instead of blocking: Live Signals leads with `MILITARY FEED OFF · PARTIAL PICTURE` or `FLIGHTS FEED OFF · PARTIAL PICTURE`, and the Contact card shows that line in place of its inputs status, so a partial picture is never presented as complete. `control_cockpit` refuses entry with `entryBlockedReason` `contacts-starting` (a Context change in flight), `subject-layer-off` (the aircraft's layer, or with none tracked any aircraft layer, is off) or `no-tracked-aircraft`. Cockpit mode temporarily releases Cesium's orbit-follow transform and drives a first-person camera from the tracked aircraft's existing smoothed display position and course. Its concave helmet-visor HUD shows callsign, UTC time, coordinates, curved roll/pitch guides, and a seven-division heading tape. Ambient commercial and military AIR contacts use a Cockpit near/far band selected by the shared Display 3D mode: Proximity admits at 150 km and retains to 185 km; All admits at 400 km and retains to 450 km. The shared 3D toggle now applies in Cockpit: Off keeps in-range contacts as rotating 2D aircraft silhouettes, while On lets a ready admitted glTF take over without a drawing gap. The Cockpit model cap remains 60 and can only lower the map budget; in-range contacts that are capped or still loading remain 2D silhouettes instead of degrading to out-of-range dots. Contacts outside the selected band use small rotation-free cyan-white pips for civilian aircraft and amber pips for military. The pilot's own airframe is not drawn in first person, and exiting clears the Cockpit band and restores normal map silhouettes/models. The normal left accordion remains available for Layers and Authoring and keeps the same 26vh HUD-aligned anchor used in map mode, independent of whether the bottom-left Contact card is expanded or collapsed; the right-rail CCTV and Context chooser are hidden to avoid duplicating or overlapping the cockpit presentation. When the intelligence HUD is enabled, its classification, scene summary, collection/orbit metadata, coordinates, and imaging-status text remain visible as reduced peripheral cockpit telemetry; the optical center and flight instruments stay clear, and turning the HUD off still hides it. Ground speed, exact heading, and rendered altitude form one compact lower-center instrument cluster, keeping the horizon and peripheral view open. A second live altitude tape hugs the inside-right visor rim: its rail and nine moving ticks are derived from the same responsive keyhole radius, remain 20 px inside the circular edge even on wide displays, fade deeply at both vertical ends, and move continuously behind a fixed current-altitude pointer; its interval tightens automatically near the surface and it is suppressed on narrow screens. Cockpit mode also has a weather-backed transparent volumetric-cloud pass derived from the supplied FBM/domain-warped R&D shader. It renders at no more than 520×320, uses 24 ray steps/three FBM octaves at 12 FPS, is clipped to the visor, fails clear when Open-Meteo is unavailable, and stops its animation completely on cockpit exit. It does not restore the prior CPU weather canvases, precipitation, scene fog, or any map-mode effect. When Contacts is active for the tracked aircraft, the compact `CONTACT` rail adds the 250 km subject window, four cohort counts, nearest observed/mapped example with relative bearing and distance, freshness, explicit uncertainty, and Previous and Next controls plus its own collapse control. The mirrored right rail is a three-page **cockpit briefing carousel**: source-backed live signals, location-matched regional headlines, and physical-region/current-weather context from bundled Natural Earth polygons and Open-Meteo. It is manual-first: Previous, Next, and direct page controls are always available, and the visible `CYCLE OFF` / `CYCLE ON` control starts or stops the nine-second page cycle. The cycle pauses on hover or keyboard focus and stops while collapsed, hidden, or outside cockpit mode; live signal data continues refreshing either way. Empty news matches and unavailable news use compact text states rather than reserving an empty media frame; partial local data remains explicit. Article links open their original publisher, and no headline is treated as verified risk intelligence. On desktop both cockpit rails use the same width and share a bottom-aligned safe baseline in opposite corners above the peripheral MGRS/GSD/time telemetry, leaving both that text and the lower-center instrument cluster readable. They collapse independently to slim tabs without stopping live data updates. Narrow screens use separated top/bottom fallbacks. Empty-space globe clicks are inert while cockpit owns the camera; `C`, `Escape`, or `EXIT COCKPIT` explicitly exits and restores the same tracked entity and standard follow camera. Unknown feeds remain unknown, selection loss still exits safely without inventing a replacement track, and the cockpit never presents the summary as threat scoring or an all-clear. This is a desktop first-person presentation, not a WebXR session. +- **Aircraft cockpit view:** selecting a commercial or military aircraft reveals a `COCKPIT` action (`C`) once that aircraft's own layer is on; Contacts is not required. The action shows in Contacts (`#cockpit-entry`) and under the Intel HUD's bottom-right readout (`#cockpit-entry-readout`, with the HUD on, in its Tactical and Cyber layouts), so entry needs no Contacts panel. Turning off the ridden aircraft's layer ends the view (the layer clears its tracking). When an air feed the surrounding picture uses is off, the Cockpit says so instead of blocking: Live Signals leads with `MILITARY FEED OFF · PARTIAL PICTURE` or `FLIGHTS FEED OFF · PARTIAL PICTURE`, and the Contact card shows that line in place of its inputs status, so a partial picture is never presented as complete. `control_cockpit` refuses entry with `entryBlockedReason` `contacts-starting` (a Context change in flight), `subject-layer-off` (the aircraft's layer, or with none tracked any aircraft layer, is off) or `no-tracked-aircraft`. Cockpit mode temporarily releases Cesium's orbit-follow transform and drives a first-person camera from the tracked aircraft's existing smoothed display position and course. Its concave helmet-visor HUD shows callsign, UTC time, coordinates, curved roll/pitch guides, and a seven-division heading tape. Ambient commercial and military AIR contacts use a Cockpit near/far band selected by the shared Display 3D mode: Proximity admits at 150 km and retains to 185 km; All admits at 400 km and retains to 450 km. The shared 3D toggle now applies in Cockpit: Off keeps in-range contacts as rotating 2D aircraft silhouettes, while On lets a ready admitted glTF take over without a drawing gap. The Cockpit model cap remains 60 and can only lower the map budget; in-range contacts that are capped or still loading remain 2D silhouettes instead of degrading to out-of-range dots. Contacts outside the selected band use small rotation-free cyan-white pips for civilian aircraft and amber pips for military. The pilot's own airframe is not drawn in first person, and exiting clears the Cockpit band and restores normal map silhouettes/models. The normal left accordion remains available for Layers and Authoring and keeps the same 26vh HUD-aligned anchor used in map mode, independent of whether the bottom-left Contact card is expanded or collapsed; the right-rail CCTV and Context chooser are hidden to avoid duplicating or overlapping the cockpit presentation. When the intelligence HUD is enabled, its classification, scene summary, collection/orbit metadata, coordinates, and imaging-status text remain visible as reduced peripheral cockpit telemetry; the optical center and flight instruments stay clear, and turning the HUD off still hides it. Ground speed, exact heading, and rendered altitude form one compact lower-center instrument cluster, keeping the horizon and peripheral view open. A second live altitude tape hugs the inside-right visor rim: its rail and nine moving ticks are derived from the same responsive keyhole radius, remain 20 px inside the circular edge even on wide displays, fade deeply at both vertical ends, and move continuously behind a fixed current-altitude pointer; its interval tightens automatically near the surface and it is suppressed on narrow screens. Cockpit mode also has a weather-backed transparent volumetric-cloud pass derived from the supplied FBM/domain-warped R&D shader. It renders at no more than 520×320, uses 24 ray steps/three FBM octaves at 12 FPS, is clipped to the visor, fails clear when Open-Meteo is unavailable, and stops its animation completely on cockpit exit. It does not restore the prior CPU weather canvases, precipitation, scene fog, or any map-mode effect. When Contacts is active for the tracked aircraft, the compact `CONTACT` rail adds the 250 km subject window, four cohort counts, nearest observed/mapped example with relative bearing and distance, freshness, explicit uncertainty, and Previous and Next controls plus its own collapse control. The mirrored right rail is a three-page **cockpit briefing carousel**: source-backed live signals, location-matched regional headlines, and physical-region/current-weather context from bundled Natural Earth polygons and Open-Meteo. It is manual-first: Previous, Next, and direct page controls are always available, and the visible `CYCLE OFF` / `CYCLE ON` control starts or stops the nine-second page cycle. The cycle pauses on hover or keyboard focus and stops while collapsed, hidden, or outside cockpit mode; live signal data continues refreshing either way. Regional News holds its list to the last 24 hours (`newsWindowHours` in the brief; the client drops anything older or undated even if a server sends it) and shows four distinct states: fresh results with no banner and a `{SOURCE} · LAST 24 H` footer; earlier results kept after a failed refresh under `CACHED · REFRESH FAILED` with the cached age in the footer; `NO NEWS IN THE LAST 24 H` when a source answered with nothing recent; and `REGIONAL NEWS UNAVAILABLE` when there is no place or no source answered, which clears the list only when there was nothing to keep. The footer follows that state across page changes. These are compact text states rather than an empty media frame; partial local data remains explicit. Article links open their original publisher, and no headline is treated as verified risk intelligence. On desktop both cockpit rails use the same width and share a bottom-aligned safe baseline in opposite corners above the peripheral MGRS/GSD/time telemetry, leaving both that text and the lower-center instrument cluster readable. They collapse independently to slim tabs without stopping live data updates. Narrow screens use separated top/bottom fallbacks. Empty-space globe clicks are inert while cockpit owns the camera; `C`, `Escape`, or `EXIT COCKPIT` explicitly exits and restores the same tracked entity and standard follow camera. Unknown feeds remain unknown, selection loss still exits safely without inventing a replacement track, and the cockpit never presents the summary as threat scoring or an all-clear. This is a desktop first-person presentation, not a WebXR session. - **Cockpit left-panel clearance:** the Cockpit Contact card and peripheral HUD participate in the adaptive left accordion's live obstacle measurements, including live viewport-height changes. Expanding Layers or Authoring keeps the active panel in the available upper-left corridor with internal scrolling; it does not cover the Contact card, lower Cockpit controls, or Cesium credit line. Outside Cockpit the hidden card does not alter the normal corridor. - **Cockpit Context scope:** the 250 km radius applies to the air/sea proximity cohorts. Installation counts come only from the currently loaded viewport and are labeled `CURRENT VIEWPORT ONLY` in the cockpit as well as the normal Context panel; neither surface presents them as a complete 250 km installation survey. - **Cockpit camera anchor:** first-person mode does not write feed-boundary corrections directly into the camera. A cockpit-only inertial anchor advances from the selected aircraft's displayed course and speed, then converges toward the authoritative delayed track with correction capped below forward motion. The displayed kinematics are derived from the same consecutive fix segment as the rendered position, with raw feed speed/course used only as fallback; a transient zero/missing feed speed therefore cannot freeze a visibly moving aircraft after layer enable or a map/cockpit handoff. Rendered altitude continues to come from that interpolated track position. Late ADS-B fixes and short render stalls can remove drift without accelerating or reversing the view. Camera placement runs before scene update/culling at a bounded 20 Hz so a moving cockpit does not force Photoreal 3D Tiles to retraverse on every display frame; textual instruments update at 10 Hz and context/layout work at 4 Hz. Every far Cockpit contact pip shares one stable Cesium texture-atlas entry and skips unused screen-projected course calculations, while only in-range 2D aircraft silhouettes pay the screen-projected rotation cost; ambient glTF collections are hidden/retained rather than synchronously destroyed at cockpit entry, and context rails lay out only on explicit content/state changes and viewport resize. The deliberate 15/30-second layer interpolation delays and per-Cesium-frame position caches remain unchanged. -- **Cockpit route, vision, and view controls:** visible on-screen `COCKPIT`, `RESET`, and `EXIT COCKPIT` controls replace reliance on the `C` shortcut. RESET uses the same canonical globe route as the map and voice actions, exits Cockpit, and releases its camera ownership rather than exposing the hidden map-style top action. When the tracked commercial flight has a plausible ADSBDB route, the top of the right briefing rail shows a compact `FROM → TO` airport strip and the visor shows a centered estimated-destination chevron with its relative bearing; its destination label rounds to whole degrees in 000–359, wrapping rounded north to 000° while the chevron continues to use the relative bearing independently of label rounding; absent or implausible route data hides the strip and cue rather than guessing. The cockpit-local vision control is an interactive `PREV / CURRENT / NEXT` carousel over `NORMAL`, `CRT`, `NVG`, `FLIR`, `ANIME`, and `NOIR`; its previous/next actions wrap, and activating the current value advances to the next style. Cockpit enters on the active map preset, so a Cyber FLIR map opens Cockpit on FLIR while Normal remains a distinct option instead of producing a second FLIR entry. Cockpit choices temporarily activate the existing Cesium post-process stages, while exiting Cockpit through either EXIT or RESET restores the pre-entry map style. The regional-news page uses a free Google News RSS locality query first, with the existing GDELT query retained only as a fail-soft fallback; linked headlines remain reporting, not verified incidents or risk intelligence. +- **Cockpit route, vision, and view controls:** visible on-screen `COCKPIT`, `RESET`, and `EXIT COCKPIT` controls replace reliance on the `C` shortcut. RESET uses the same canonical globe route as the map and voice actions, exits Cockpit, and releases its camera ownership rather than exposing the hidden map-style top action. When the tracked commercial flight has a plausible ADSBDB route, the top of the right briefing rail shows a compact `FROM → TO` airport strip and the visor shows a centered estimated-destination chevron with its relative bearing; its destination label rounds to whole degrees in 000–359, wrapping rounded north to 000° while the chevron continues to use the relative bearing independently of label rounding; absent or implausible route data hides the strip and cue rather than guessing. The cockpit-local vision control is an interactive `PREV / CURRENT / NEXT` carousel over `NORMAL`, `CRT`, `NVG`, `FLIR`, `ANIME`, and `NOIR`; its previous/next actions wrap, and activating the current value advances to the next style. Cockpit enters on the active map preset, so a Cyber FLIR map opens Cockpit on FLIR while Normal remains a distinct option instead of producing a second FLIR entry. Cockpit choices temporarily activate the existing Cesium post-process stages, while exiting Cockpit through either EXIT or RESET restores the pre-entry map style. The regional-news page uses a free Google News RSS locality query for the last day (`when:1d`) first, with the existing GDELT query (24 h timespan) retained only as a fail-soft fallback; both keep only articles published in the last 24 hours, newest first; linked headlines remain reporting, not verified incidents or risk intelligence. - Cockpit wind-direction labels wrap after rounding to whole degrees, so a direction of 359.5° displays as `N · 0°` rather than `N · 360°`. - The transit, ALPR, vessel, CCTV, Local ADS-B, flight and military context, awareness, Cockpit and Street Level heading readouts round through `roundHeadingDegrees` in `src/data/headingDegrees.js` (whole degrees 0–359, `null` when not finite, so each caller keeps its own placeholder); `normalizeHeading` lives there too and `cockpitMath.js` re-exports it. The Cockpit's `TRACK ACQUIRED` signal uses `formatHeadingReadout`, so a 359.6° track reads `COURSE 000°`. - **Cockpit missing observations:** missing local weather observations remain unknown rather than being converted to zero or clear skies, in the briefing and in the cloud effects; a missing temperature drops the whole local weather record, including its wind and condition. diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 7a20f7775..6ba148306 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -46,6 +46,7 @@ "src/ui/views/panels/CockpitSignalList.vue", "src/ui/views/panels/CockpitUtilityControls.vue", "src/ui/cockpitBriefPages.js", + "src/data/regionalNewsWindow.js", "src/ui/cockpitContextState.js", "src/ui/cockpitInstrumentState.js", "src/ui/cockpitRollingValue.js", @@ -467,6 +468,7 @@ "server/providers/regional/weather-effects.js", "server/providers/regional/weather.js", "src/data/regionalModel.js", + "src/data/regionalNewsWindow.js", "src/geoDistance.js", "src/nominatimGeocode.js", "src/sources/httpBody.js", @@ -566,6 +568,7 @@ "src/search/nominatim.js", "src/nominatimGeocode.js", "src/data/regionalModel.js", + "src/data/regionalNewsWindow.js", "src/geoDistance.js", "src/data/naturalEarthRegions.js", "src/data/bundledJson.js", @@ -863,6 +866,7 @@ "src/ui/cockpit.js", "src/ui/cockpitBriefing.js", "src/ui/cockpitBriefPages.js", + "src/data/regionalNewsWindow.js", "src/ui/cockpitContextState.js", "src/ui/cockpitInstrumentState.js", "src/ui/cockpitRollingValue.js", @@ -992,6 +996,7 @@ "src/ui/cockpit.js", "src/ui/cockpitBriefing.js", "src/ui/cockpitBriefPages.js", + "src/data/regionalNewsWindow.js", "src/ui/cockpitContextState.js", "src/ui/cockpitInstrumentState.js", "src/ui/cockpitRollingValue.js", @@ -2785,6 +2790,7 @@ "src/ui/cockpit.js", "src/ui/cockpitBriefing.js", "src/ui/cockpitBriefPages.js", + "src/data/regionalNewsWindow.js", "src/ui/cockpitContextState.js", "src/ui/cockpitInstrumentState.js", "src/ui/cockpitRollingValue.js", @@ -3712,6 +3718,7 @@ "src/search/nominatim.js", "src/nominatimGeocode.js", "src/data/regionalModel.js", + "src/data/regionalNewsWindow.js", "src/sources/httpBody.js", "src/i18n/marker.js", "src/sources/nominatim.js", @@ -3955,6 +3962,7 @@ "src/search/nominatim.js", "src/nominatimGeocode.js", "src/data/regionalModel.js", + "src/data/regionalNewsWindow.js", "src/sources/httpBody.js", "src/i18n/marker.js", "src/sources/nominatim.js", @@ -4250,7 +4258,11 @@ }, "regional-source": { "exports": ["./sources/regional"], - "modules": ["src/data/regionalModel.js", "src/geoDistance.js"], + "modules": [ + "src/data/regionalModel.js", + "src/data/regionalNewsWindow.js", + "src/geoDistance.js" + ], "external": [] }, "voice-action-schemas": { @@ -4439,6 +4451,7 @@ "src/search/google.js", "src/search/geospatial.js", "src/data/regionalModel.js", + "src/data/regionalNewsWindow.js", "src/geoDistance.js", "src/sources/httpBody.js", "src/i18n/marker.js", @@ -4463,6 +4476,7 @@ "src/nominatimGeocode.js", "src/search/geospatial.js", "src/data/regionalModel.js", + "src/data/regionalNewsWindow.js", "src/geoDistance.js", "src/sources/httpBody.js", "src/i18n/marker.js" diff --git a/server/providers/regional/briefing.js b/server/providers/regional/briefing.js index c5b17a12b..f56c7013c 100644 --- a/server/providers/regional/briefing.js +++ b/server/providers/regional/briefing.js @@ -3,6 +3,7 @@ import { fetchRegionalPlace } from './place.js'; import { fetchRegionalWeather } from './weather.js'; import { fetchRegionalNews } from './news.js'; import { validRegionalPoint } from './query.js'; +import { REGIONAL_NEWS_WINDOW_HOURS } from '../../../src/data/regionalModel.js'; import { coalesceProxyRequest } from '../common/http.js'; // --------------------------------------------------------------------------- @@ -50,10 +51,11 @@ function regionalBriefProxy({ placeProvider = fetchRegionalPlace } = {}) { if (!regionalBriefHasAnySource({ place, weather, news })) { throw new Error('All regional briefing sources unavailable'); } + const retrievedAt = new Date().toISOString(); const payload = { status: place && weather && news.status !== 'unavailable' ? 'ready' : 'partial', - retrievedAt: new Date().toISOString(), + retrievedAt, coordinates: point, place, placeStatus: place ? 'ready' : 'unavailable', @@ -62,6 +64,9 @@ function regionalBriefProxy({ placeProvider = fetchRegionalPlace } = {}) { newsStatus: news.status, newsQuery: news.query, newsSource: news.source, + newsWindowHours: REGIONAL_NEWS_WINDOW_HOURS, + // A cached or stale answer keeps this, so the client can show its age. + newsFetchedAt: retrievedAt, articles: news.articles, }; _regionalBriefCache.set(key, { payload, cachedAt: Date.now() }); diff --git a/server/providers/regional/news.js b/server/providers/regional/news.js index 155dfa908..085a6ba72 100644 --- a/server/providers/regional/news.js +++ b/server/providers/regional/news.js @@ -1,5 +1,10 @@ import { fetchRegionalText, fetchRegionalJson } from './http.js'; -import { normalizeRegionalArticles } from '../../../src/data/regionalModel.js'; +import { + REGIONAL_NEWS_WINDOW_HOURS, + googleNewsWindowOperator, + normalizeRegionalArticles, + recentRegionalArticles, +} from '../../../src/data/regionalModel.js'; function decodeRssText(value) { return String(value || '') @@ -22,7 +27,10 @@ function rssTag(block, tag) { ); } -function normalizeRssArticles(xml, limit = 5) { +// Feed items read before the window filter; Google returns about 100. +const RSS_ITEM_CAP = 100; + +function normalizeRssArticles(xml, limit = RSS_ITEM_CAP) { const seen = new Set(); const articles = []; for (const match of String(xml || '').matchAll( @@ -57,12 +65,27 @@ function normalizeRssArticles(xml, limit = 5) { return articles; } -async function fetchRegionalNews(place) { +/** + * Headlines for a place from the last REGIONAL_NEWS_WINDOW_HOURS, newest + * first: Google News RSS, then GDELT when RSS fails or has nothing recent. + * `empty` means a source answered with nothing in the window; `unavailable` + * means there was no place or no source answered. + * @param {{locality?: string, region?: string, country?: string}|null} place + * @param {{now?: () => number}} [options] + */ +async function fetchRegionalNews(place, { now = Date.now } = {}) { const query = place?.locality || place?.region || place?.country; if (!query) return { status: 'unavailable', query: null, articles: [], source: null }; + const recent = (articles) => + recentRegionalArticles(articles, { + now: now(), + windowHours: REGIONAL_NEWS_WINDOW_HOURS, + limit: 5, + }); + let answered = false; const rssParams = new URLSearchParams({ - q: String(query).replace(/["\\]/g, ' ').trim(), + q: `${String(query).replace(/["\\]/g, ' ').trim()} ${googleNewsWindowOperator()}`, hl: 'en-US', gl: 'US', ceid: 'US:en', @@ -75,7 +98,8 @@ async function fetchRegionalNews(place) { timeoutMs: 12_000, }, ); - const articles = normalizeRssArticles(xml, 5); + answered = true; + const articles = recent(normalizeRssArticles(xml)); if (articles.length) return { status: 'ready', query, articles, source: 'Google News RSS' }; } catch { @@ -87,7 +111,7 @@ async function fetchRegionalNews(place) { format: 'json', maxrecords: '5', sort: 'datedesc', - timespan: '48h', + timespan: `${REGIONAL_NEWS_WINDOW_HOURS}h`, }); try { const payload = await fetchRegionalJson( @@ -97,7 +121,7 @@ async function fetchRegionalNews(place) { timeoutMs: 12_000, }, ); - const articles = normalizeRegionalArticles(payload, 5); + const articles = recent(normalizeRegionalArticles(payload, 5)); return { status: articles.length ? 'ready' : 'empty', query, @@ -105,7 +129,10 @@ async function fetchRegionalNews(place) { source: 'GDELT fallback', }; } catch { - return { status: 'unavailable', query, articles: [], source: null }; + // An RSS answer with nothing recent is still a true empty result. + return answered + ? { status: 'empty', query, articles: [], source: 'Google News RSS' } + : { status: 'unavailable', query, articles: [], source: null }; } } diff --git a/src/data/regionalBrief.test.mjs b/src/data/regionalBrief.test.mjs index 18094ec1c..4606b6ad1 100644 --- a/src/data/regionalBrief.test.mjs +++ b/src/data/regionalBrief.test.mjs @@ -1,7 +1,11 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { + REGIONAL_NEWS_WINDOW_HOURS, + googleNewsWindowOperator, normalizeRegionalArticles, + recentRegionalArticles, + regionalNewsWindowHours, normalizeRegionalPlace, normalizeRegionalWeather, regionalDistanceM, @@ -61,3 +65,37 @@ test('regional distance handles nearby movement and missing positions', () => { assert.ok(distance > 11000 && distance < 11200); assert.equal(regionalDistanceM(null, null), Infinity); }); + +test('regional news is held to one 24-hour window, newest first, undated dropped', () => { + assert.equal(REGIONAL_NEWS_WINDOW_HOURS, 24); + assert.equal(googleNewsWindowOperator(), 'when:1d'); + assert.equal(googleNewsWindowOperator(6), 'when:6h'); + assert.equal(regionalNewsWindowHours('12'), 12); + assert.equal(regionalNewsWindowHours(0), 24); + assert.equal(regionalNewsWindowHours(undefined), 24); + const now = Date.parse('2026-11-04T12:00:00Z'); + const at = (hours) => new Date(now - hours * 3_600_000).toISOString(); + const rows = [ + { title: 'a', publishedAt: at(23) }, + { title: 'stale', publishedAt: at(25) }, + { title: 'undated', publishedAt: null }, + { title: 'garbled', publishedAt: 'not a date' }, + { title: 'b', publishedAt: at(1) }, + { title: 'future', publishedAt: at(-2) }, + { title: 'c', publishedAt: at(5) }, + ]; + assert.deepEqual( + recentRegionalArticles(rows, { now }).map((row) => row.title), + ['b', 'c', 'a'], + ); + assert.deepEqual( + recentRegionalArticles(rows, { now, limit: 2 }).map((row) => row.title), + ['b', 'c'], + ); + assert.deepEqual( + recentRegionalArticles(rows, { now, windowHours: 4 }).map((row) => row.title), + ['b'], + ); + assert.deepEqual(recentRegionalArticles([], { now }), []); + assert.deepEqual(recentRegionalArticles(undefined, { now }), []); +}); diff --git a/src/data/regionalModel.js b/src/data/regionalModel.js index 46f162d6f..281fc873f 100644 --- a/src/data/regionalModel.js +++ b/src/data/regionalModel.js @@ -55,6 +55,13 @@ export function normalizeRegionalPlace(payload) { }; } +export { + REGIONAL_NEWS_WINDOW_HOURS, + googleNewsWindowOperator, + recentRegionalArticles, + regionalNewsWindowHours, +} from './regionalNewsWindow.js'; + /** Normalize and deduplicate GDELT ArticleList output without trusting article HTML. */ export function normalizeRegionalArticles(payload, limit = MAX_ARTICLES) { const rows = Array.isArray(payload?.articles) ? payload.articles : []; diff --git a/src/data/regionalNewsWindow.js b/src/data/regionalNewsWindow.js new file mode 100644 index 000000000..15180eee0 --- /dev/null +++ b/src/data/regionalNewsWindow.js @@ -0,0 +1,66 @@ +/** The regional-news freshness window, shared by the servers and the Cockpit. */ + +/** At most this many articles answer a regional brief. */ +export const REGIONAL_NEWS_ROWS = 5; + +/** + * The regional-news freshness window, in hours. The servers ask upstream for + * this window, drop anything older and report it as `newsWindowHours`; the + * Cockpit labels its list with it. + */ +export const REGIONAL_NEWS_WINDOW_HOURS = 24; + +// A publish time this far ahead of the clock is skew, not a future story. +const REGIONAL_NEWS_CLOCK_SKEW_MS = 15 * 60_000; + +/** + * A served window in hours, or the default when it is missing or out of range. + * @param {unknown} value + * @returns {number} + */ +export function regionalNewsWindowHours(value) { + const hours = Number(value); + return Number.isInteger(hours) && hours >= 1 && hours <= 168 + ? hours + : REGIONAL_NEWS_WINDOW_HOURS; +} + +/** + * The Google News search operator asking for the window: `when:1d` for 24 h. + * @param {number} [hours] + * @returns {string} + */ +export function googleNewsWindowOperator(hours = REGIONAL_NEWS_WINDOW_HOURS) { + const span = regionalNewsWindowHours(hours); + return span % 24 === 0 ? `when:${span / 24}d` : `when:${span}h`; +} + +/** + * The articles published inside the window, newest first, at most `limit`. + * An article without a parseable publish time is dropped: nothing shows it is + * recent. One dated more than 15 minutes ahead of `now` is dropped too. + * @param {Array<{publishedAt?: string|null}>} articles + * @param {{now?: number, windowHours?: number, limit?: number}} [options] + * @returns {Array} + */ +export function recentRegionalArticles( + articles, + { + now = Date.now(), + windowHours = REGIONAL_NEWS_WINDOW_HOURS, + limit = REGIONAL_NEWS_ROWS, + } = {}, +) { + const oldest = now - regionalNewsWindowHours(windowHours) * 3_600_000; + return (Array.isArray(articles) ? articles : []) + .map((article) => ({ article, at: Date.parse(article?.publishedAt) })) + .filter( + ({ at }) => + Number.isFinite(at) && + at >= oldest && + at <= now + REGIONAL_NEWS_CLOCK_SKEW_MS, + ) + .sort((a, b) => b.at - a.at) + .slice(0, Math.max(0, limit)) + .map(({ article }) => article); +} diff --git a/src/data/regionalProxy.test.mjs b/src/data/regionalProxy.test.mjs index 97891bef8..b1e56da36 100644 --- a/src/data/regionalProxy.test.mjs +++ b/src/data/regionalProxy.test.mjs @@ -11,6 +11,7 @@ import createViteConfig, { validMilitaryInstallationBox, validRegionalPoint, } from '../../vite.config.js'; +import { fetchRegionalNews } from '../../server/providers/regional/news.js'; test('missing Google place context is a quiet keyless capability, not a 503', () => { assert.deepEqual(keylessGooglePlacesResponse(undefined), { @@ -113,3 +114,50 @@ test('regional brief treats an all-source outage as total failure', () => { news: { status: 'unavailable' }, }), true); }); + +test('local regional news asks for the last day, drops old and undated items, newest first', async (t) => { + const realFetch = globalThis.fetch; + t.after(() => { globalThis.fetch = realFetch; }); + const urls = []; + let rss; + let gdelt; + globalThis.fetch = async (url) => { + urls.push(new URL(String(url))); + const answer = String(url).includes('news.google') ? rss : gdelt; + return typeof answer === 'function' ? answer() : answer.clone(); + }; + const at = (hours) => new Date(Date.now() - hours * 3_600_000).toUTCString(); + const item = (title, date) => + `${title}https://news.example/${title}${date ? `${date}` : ''}`; + rss = new Response(`${[ + item('old', at(4 * 24)), + item('undated', null), + item('day', at(20)), + item('hour', at(1)), + ].join('')}`); + const place = { locality: 'Austin' }; + const ready = await fetchRegionalNews(place); + assert.equal(urls[0].searchParams.get('q'), 'Austin when:1d'); + assert.equal(ready.status, 'ready'); + assert.deepEqual(ready.articles.map((row) => row.title), ['hour', 'day']); + + // Nothing recent in RSS: GDELT is asked for the same 24 h window. + rss = new Response(`${item('old', at(30))}`); + gdelt = Response.json({ articles: [] }); + urls.length = 0; + const empty = await fetchRegionalNews(place); + assert.equal(urls[1].searchParams.get('timespan'), '24h'); + assert.deepEqual(empty, { status: 'empty', query: 'Austin', articles: [], source: 'GDELT fallback' }); + + // RSS answered with nothing recent and GDELT failed: still a true empty. + rss = new Response(''); + gdelt = () => Promise.reject(new TypeError('network')); + assert.equal((await fetchRegionalNews(place)).status, 'empty'); + + // Neither source answered, or no place: unavailable. + rss = () => Promise.resolve(new Response('busy', { status: 503 })); + const failed = await fetchRegionalNews(place); + assert.equal(failed.status, 'unavailable'); + assert.deepEqual(failed.articles, []); + assert.equal((await fetchRegionalNews(null)).status, 'unavailable'); +}); diff --git a/src/i18n/locales/ar.json b/src/i18n/locales/ar.json index f32216a1e..186bd4e1e 100644 --- a/src/i18n/locales/ar.json +++ b/src/i18n/locales/ar.json @@ -388,11 +388,12 @@ "PLACE / CONDITIONS / POSITION": "المكان / الأحوال / الموضع", "POSITION UNAVAILABLE": "الموضع غير متاح", "REGIONAL NEWS UNAVAILABLE": "الأخبار الإقليمية غير متاحة", + "CACHED · REFRESH FAILED": "مخزنة · فشل التحديث", "REGION UNAVAILABLE": "المنطقة غير متاحة", - "NO RECENT LOCATION MATCHES": "لا توجد تقارير حديثة مطابقة للموقع", + "NO NEWS IN THE LAST {hours} H": "لا أخبار خلال آخر {hours} س", "SOURCE": "المصدر", "{domain} · {age}": "{domain} · {age}", - "{source} · LOCATION QUERY": "{source} · استعلام الموقع", + "{source} · CACHED {age}": "{source} · مخزنة {age}", "TIME UNKNOWN": "الوقت غير معروف", "{count}M AGO": "قبل {count} د", "{count}H AGO": "قبل {count} س", @@ -2194,7 +2195,7 @@ "ADS-B PRIORITY · {status}": "أولوية ADS-B · {status}", "ADS-B EMERGENCY · {status}": "طوارئ ADS-B · {status}", "{aircraftClass} · {emergency} · {feedState}": "{aircraftClass} · {emergency} · {feedState}", - "{source} · LOCATION QUERY · RECENT": "{source} · استعلام الموقع · حديث", + "{source} · LAST {hours} H": "{source} · آخر {hours} س", "Rendered globe frames per second · toggle with `": "إطارات الكرة الأرضية المعروضة في الثانية · بدّل بالمفتاح `", "Ground heights could not be refreshed. Try the file again when the map has loaded.": "تعذّر تحديث ارتفاعات الأرض. أعد استيراد الملف بعد تحميل الخريطة.", "{count} map objects": { diff --git a/src/i18n/locales/de.json b/src/i18n/locales/de.json index b9d89d2fb..0fa269e20 100644 --- a/src/i18n/locales/de.json +++ b/src/i18n/locales/de.json @@ -399,13 +399,14 @@ "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.": "Briefing-Seiten automatisch alle 9 Sekunden wechseln (Signale → News → Lokal). Pausiert, solange sich der Mauszeiger über dem Bereich befindet oder dieser den Fokus hat. Live-Signaldaten werden in beiden Fällen laufend aktualisiert.", "ACQUIRING REGIONAL NEWS": "REGIONALE NEWS WERDEN ERFASST", "REGIONAL NEWS UNAVAILABLE": "REGIONALE NEWS NICHT VERFÜGBAR", + "CACHED · REFRESH FAILED": "CACHE · AKTUALISIERUNG FEHLGESCHLAGEN", "RESOLVING REGION": "REGION WIRD ERMITTELT", "REGION UNAVAILABLE": "REGION NICHT VERFÜGBAR", - "NO RECENT LOCATION MATCHES": "KEINE AKTUELLEN ORTSTREFFER", + "NO NEWS IN THE LAST {hours} H": "KEINE NEWS IN DEN LETZTEN {hours} H", "{domain} · {age}": "{domain} · {age}", "CLOUD {pct}%": "WOLKEN {pct} %", "CLOUD UNKNOWN": "WOLKEN UNBEKANNT", - "{source} · LOCATION QUERY": "{source} · ORTSABFRAGE", + "{source} · CACHED {age}": "{source} · CACHE {age}", "REGIONAL NEWS": "REGIONALE NEWS", "CONTEXT STANDBY": "KONTEXT STANDBY", "ENABLE GLOBAL CONTEXT FOR PROXIMITY PINGS": "GLOBALEN KONTEXT FÜR NÄHE-PINGS AKTIVIEREN", @@ -2094,7 +2095,7 @@ "ADS-B PRIORITY · {status}": "ADS-B-PRIORITÄT · {status}", "ADS-B EMERGENCY · {status}": "ADS-B-NOTFALL · {status}", "{aircraftClass} · {emergency} · {feedState}": "{aircraftClass} · {emergency} · {feedState}", - "{source} · LOCATION QUERY · RECENT": "{source} · ORTSABFRAGE · AKTUELL", + "{source} · LAST {hours} H": "{source} · LETZTE {hours} H", "Rendered globe frames per second · toggle with `": "Gerenderte Globus-Frames pro Sekunde · umschalten mit `", "Ground heights could not be refreshed. Try the file again when the map has loaded.": "Geländehöhen konnten nicht aktualisiert werden. Die Datei erneut laden, wenn die Karte geladen ist.", "{count} map objects": { diff --git a/src/i18n/locales/es.json b/src/i18n/locales/es.json index 6fefd6d91..078096514 100644 --- a/src/i18n/locales/es.json +++ b/src/i18n/locales/es.json @@ -274,11 +274,12 @@ "PLACE / CONDITIONS / POSITION": "LUGAR / CLIMA / POSICIÓN", "POSITION UNAVAILABLE": "POSICIÓN NO DISPONIBLE", "REGIONAL NEWS UNAVAILABLE": "NOTICIAS DE ZONA NO DISPONIBLES", + "CACHED · REFRESH FAILED": "EN CACHÉ · ERROR AL ACTUALIZAR", "REGION UNAVAILABLE": "REGIÓN NO DISPONIBLE", - "NO RECENT LOCATION MATCHES": "SIN COINCIDENCIAS RECIENTES DE UBICACIÓN", + "NO NEWS IN THE LAST {hours} H": "SIN NOTICIAS EN LAS ÚLTIMAS {hours} H", "SOURCE": "FUENTE", "{domain} · {age}": "{domain} · {age}", - "{source} · LOCATION QUERY": "{source} · CONSULTA POR UBICACIÓN", + "{source} · CACHED {age}": "{source} · EN CACHÉ {age}", "TIME UNKNOWN": "HORA DESCONOCIDA", "{count}M AGO": "HACE {count} MIN", "{count}H AGO": "HACE {count} H", @@ -1923,7 +1924,7 @@ "MILITARY FEED OFF · PARTIAL PICTURE": "FUENTE MILITAR DESACTIVADA · PANORAMA PARCIAL", "FLIGHTS FEED OFF · PARTIAL PICTURE": "FUENTE DE VUELOS DESACTIVADA · PANORAMA PARCIAL", "NEARBY AIRCRAFT INCOMPLETE · NOT AN ALL-CLEAR": "AERONAVES CERCANAS INCOMPLETAS · NO IMPLICA TODO DESPEJADO", - "{source} · LOCATION QUERY · RECENT": "{source} · CONSULTA POR UBICACIÓN · RECIENTE", + "{source} · LAST {hours} H": "{source} · ÚLTIMAS {hours} H", "ft": "ft", "kts": "kn", "PAUSE": "PAUSA", diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json index 85957a6c8..3ce27c53c 100644 --- a/src/i18n/locales/fr.json +++ b/src/i18n/locales/fr.json @@ -1649,14 +1649,15 @@ "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.": "Faire défiler automatiquement les pages du briefing toutes les 9 secondes (Signaux → Actus → Local). Pause pendant le survol ou quand le panneau a le focus. Les signaux en direct s'actualisent en continu dans les deux cas.", "ACQUIRING REGIONAL NEWS": "ACQUISITION DES ACTUS RÉGIONALES", "REGIONAL NEWS UNAVAILABLE": "ACTUS RÉGIONALES INDISPONIBLES", + "CACHED · REFRESH FAILED": "EN CACHE · ÉCHEC DE L’ACTUALISATION", "RESOLVING REGION": "IDENTIFICATION DE LA RÉGION", "REGION UNAVAILABLE": "RÉGION INDISPONIBLE", - "NO RECENT LOCATION MATCHES": "AUCUNE ACTU RÉCENTE POUR CE LIEU", + "NO NEWS IN THE LAST {hours} H": "AUCUNE ACTU CES {hours} DERNIÈRES H", "{domain} · {age}": "{domain} · {age}", "{value} KM/H": "{value} KM/H", "CLOUD {pct}%": "NÉBULOSITÉ {pct} %", "CLOUD UNKNOWN": "NÉBULOSITÉ INCONNUE", - "{source} · LOCATION QUERY": "{source} · REQUÊTE DE LIEU", + "{source} · CACHED {age}": "{source} · EN CACHE {age}", "REGIONAL NEWS": "ACTUS RÉGIONALES", "{label} · {radius} AIR/SEA WINDOW": "{label} · AIR/MER {radius}", "{scope} · INSTALLATIONS {coverage}": "{scope} · INSTALLATIONS : {coverage}", @@ -1716,7 +1717,7 @@ "OBSERVED / MAPPED PINGS": "PINGS OBSERVÉS / CARTOGRAPHIÉS", "SOURCE-BACKED EVENTS · NO SYNTHETIC NEWS": "ÉVÉNEMENTS SOURCÉS · AUCUNE ACTU SYNTHÉTIQUE", "LATEST LOCATION-MATCHED REPORTING": "DERNIÈRES ACTUS LIÉES AU LIEU", - "{source} · LOCATION QUERY · RECENT": "{source} · REQUÊTE DE LIEU · RÉCENT", + "{source} · LAST {hours} H": "{source} · {hours} DERNIÈRES H", "LOCAL INFO": "INFOS LOCALES", "PLACE / CONDITIONS / POSITION": "LIEU / CONDITIONS / POSITION", "TIME UNKNOWN": "HEURE INCONNUE", diff --git a/src/i18n/locales/it.json b/src/i18n/locales/it.json index add839aac..36f25a0cf 100644 --- a/src/i18n/locales/it.json +++ b/src/i18n/locales/it.json @@ -1649,14 +1649,15 @@ "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.": "Scorri automaticamente le pagine del briefing ogni 9 secondi (Segnali → Notizie → Locale). Lo scorrimento si interrompe quando passi sul pannello o lo selezioni. I dati dei segnali live si aggiornano comunque di continuo.", "ACQUIRING REGIONAL NEWS": "ACQUISIZIONE NOTIZIE REGIONALI", "REGIONAL NEWS UNAVAILABLE": "NOTIZIE REGIONALI NON DISPONIBILI", + "CACHED · REFRESH FAILED": "IN CACHE · AGGIORNAMENTO NON RIUSCITO", "RESOLVING REGION": "IDENTIFICAZIONE REGIONE", "REGION UNAVAILABLE": "REGIONE NON DISPONIBILE", - "NO RECENT LOCATION MATCHES": "NESSUNA CORRISPONDENZA RECENTE PER POSIZIONE", + "NO NEWS IN THE LAST {hours} H": "NESSUNA NOTIZIA NELLE ULTIME {hours} H", "{domain} · {age}": "{domain} · {age}", "{value} KM/H": "{value} KM/H", "CLOUD {pct}%": "NUVOLE {pct}%", "CLOUD UNKNOWN": "NUVOLE N/D", - "{source} · LOCATION QUERY": "{source} · QUERY PER POSIZIONE", + "{source} · CACHED {age}": "{source} · IN CACHE {age}", "REGIONAL NEWS": "NOTIZIE REGIONALI", "{label} · {radius} AIR/SEA WINDOW": "{label} · ARIA/MARE {radius}", "{scope} · INSTALLATIONS {coverage}": "{scope} · SITI {coverage}", @@ -1716,7 +1717,7 @@ "OBSERVED / MAPPED PINGS": "PING OSSERVATI / MAPPATI", "SOURCE-BACKED EVENTS · NO SYNTHETIC NEWS": "EVENTI DA FONTI · NESSUNA NOTIZIA SINTETICA", "LATEST LOCATION-MATCHED REPORTING": "ULTIME NOTIZIE PER POSIZIONE", - "{source} · LOCATION QUERY · RECENT": "{source} · QUERY PER POSIZIONE · RECENTI", + "{source} · LAST {hours} H": "{source} · ULTIME {hours} H", "LOCAL INFO": "INFO LOCALI", "PLACE / CONDITIONS / POSITION": "LUOGO / CONDIZIONI / POSIZIONE", "TIME UNKNOWN": "ORA SCONOSCIUTA", diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.json index dde397f27..e586716f8 100644 --- a/src/i18n/locales/ja.json +++ b/src/i18n/locales/ja.json @@ -1601,14 +1601,15 @@ "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秒ごとにブリーフィングページを自動で切り替えます(シグナル → ニュース → ローカル)。パネルにカーソルを合わせるかフォーカスしている間は一時停止します。ライブシグナルのデータは、どちらの場合も継続的に更新されます。", "ACQUIRING REGIONAL NEWS": "地域ニュースを取得中", "REGIONAL NEWS UNAVAILABLE": "地域ニュースを取得できません", + "CACHED · REFRESH FAILED": "キャッシュ · 更新失敗", "RESOLVING REGION": "地域を特定中", "REGION UNAVAILABLE": "地域を取得できません", - "NO RECENT LOCATION MATCHES": "この地域の最近のニュースなし", + "NO NEWS IN THE LAST {hours} H": "過去{hours}時間のニュースなし", "{domain} · {age}": "{domain} · {age}", "{value} KM/H": "{value} km/h", "CLOUD {pct}%": "雲量 {pct}%", "CLOUD UNKNOWN": "雲量不明", - "{source} · LOCATION QUERY": "{source} · 位置クエリ", + "{source} · CACHED {age}": "{source} · キャッシュ {age}", "REGIONAL NEWS": "地域ニュース", "{label} · {radius} AIR/SEA WINDOW": "{label} · 航空機/船舶の範囲 {radius}", "{scope} · INSTALLATIONS {coverage}": "{scope} · 施設 {coverage}", @@ -1666,7 +1667,7 @@ "OBSERVED / MAPPED PINGS": "観測 / マップ済みピング", "SOURCE-BACKED EVENTS · NO SYNTHETIC NEWS": "出典付きイベントのみ · 合成ニュースなし", "LATEST LOCATION-MATCHED REPORTING": "位置に一致する最新の報道", - "{source} · LOCATION QUERY · RECENT": "{source} · 位置クエリ · 最近", + "{source} · LAST {hours} H": "{source} · 過去{hours}時間", "LOCAL INFO": "ローカル情報", "PLACE / CONDITIONS / POSITION": "場所 / 天候 / 位置", "TIME UNKNOWN": "時刻不明", diff --git a/src/i18n/locales/pt.json b/src/i18n/locales/pt.json index 5b4b793eb..13d3fbc85 100644 --- a/src/i18n/locales/pt.json +++ b/src/i18n/locales/pt.json @@ -1649,14 +1649,15 @@ "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.": "Alternar as páginas do briefing automaticamente a cada 9 segundos (Sinais → Notícias → Local). A alternância pausa enquanto você passa o mouse ou foca o painel. Os dados de sinais ao vivo continuam sendo atualizados de qualquer forma.", "ACQUIRING REGIONAL NEWS": "OBTENDO NOTÍCIAS DA ÁREA", "REGIONAL NEWS UNAVAILABLE": "NOTÍCIAS DA ÁREA INDISPONÍVEIS", + "CACHED · REFRESH FAILED": "EM CACHE · FALHA AO ATUALIZAR", "RESOLVING REGION": "IDENTIFICANDO REGIÃO", "REGION UNAVAILABLE": "REGIÃO INDISPONÍVEL", - "NO RECENT LOCATION MATCHES": "NENHUMA CORRESPONDÊNCIA RECENTE COM O LOCAL", + "NO NEWS IN THE LAST {hours} H": "SEM NOTÍCIAS NAS ÚLTIMAS {hours} H", "{domain} · {age}": "{domain} · {age}", "{value} KM/H": "{value} KM/H", "CLOUD {pct}%": "NUVENS {pct}%", "CLOUD UNKNOWN": "NEBULOSIDADE DESCONHECIDA", - "{source} · LOCATION QUERY": "{source} · CONSULTA POR LOCAL", + "{source} · CACHED {age}": "{source} · EM CACHE {age}", "REGIONAL NEWS": "NOTÍCIAS DA ÁREA", "{label} · {radius} AIR/SEA WINDOW": "{label} · AR/MAR {radius}", "{scope} · INSTALLATIONS {coverage}": "{scope} · INSTALAÇÕES: {coverage}", @@ -1716,7 +1717,7 @@ "OBSERVED / MAPPED PINGS": "PINGS OBSERVADOS / MAPEADOS", "SOURCE-BACKED EVENTS · NO SYNTHETIC NEWS": "EVENTOS COM FONTE · SEM NOTÍCIAS SINTÉTICAS", "LATEST LOCATION-MATCHED REPORTING": "ÚLTIMAS NOTÍCIAS DO LOCAL", - "{source} · LOCATION QUERY · RECENT": "{source} · CONSULTA POR LOCAL · RECENTE", + "{source} · LAST {hours} H": "{source} · ÚLTIMAS {hours} H", "LOCAL INFO": "INFO LOCAL", "PLACE / CONDITIONS / POSITION": "LUGAR / CONDIÇÕES / POSIÇÃO", "TIME UNKNOWN": "HORA DESCONHECIDA", diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json index 1ffa64ac1..766af1005 100644 --- a/src/i18n/locales/ru.json +++ b/src/i18n/locales/ru.json @@ -366,10 +366,11 @@ "OVERCAST": "ПАСМУРНО", "ACQUIRING REGIONAL NEWS": "ЗАГРУЗКА РЕГИОНАЛЬНЫХ НОВОСТЕЙ", "REGIONAL NEWS UNAVAILABLE": "РЕГИОНАЛЬНЫЕ НОВОСТИ НЕДОСТУПНЫ", + "CACHED · REFRESH FAILED": "КЭШ · ОБНОВЛЕНИЕ НЕ УДАЛОСЬ", "RESOLVING REGION": "ОПРЕДЕЛЕНИЕ РЕГИОНА", "REGION UNAVAILABLE": "РЕГИОН НЕДОСТУПЕН", "FOG": "ТУМАН", - "NO RECENT LOCATION MATCHES": "НЕТ СВЕЖИХ СОВПАДЕНИЙ ПО МЕСТУ", + "NO NEWS IN THE LAST {hours} H": "НЕТ НОВОСТЕЙ ЗА {hours} Ч", "DRIZZLE": "МОРОСЬ", "RAIN": "ДОЖДЬ", "{domain} · {age}": "{domain} · {age}", @@ -381,7 +382,7 @@ "CLOUD {pct}%": "ОБЛАЧНОСТЬ {pct}%", "CLOUD UNKNOWN": "ОБЛАЧНОСТЬ НЕИЗВЕСТНА", "MIXED CONDITIONS": "СМЕШАННЫЕ УСЛОВИЯ", - "{source} · LOCATION QUERY": "{source} · ЗАПРОС ПО МЕСТУ", + "{source} · CACHED {age}": "{source} · КЭШ {age}", "REGIONAL NEWS": "НОВОСТИ РЕГИОНА", "CYCLE ON": "АВТО: ВКЛ", "CYCLE OFF": "АВТО: ВЫКЛ", @@ -1956,7 +1957,7 @@ "MILITARY FEED OFF · PARTIAL PICTURE": "ВОЕННЫЙ ПОТОК ВЫКЛ · КАРТИНА НЕПОЛНАЯ", "FLIGHTS FEED OFF · PARTIAL PICTURE": "ПОТОК РЕЙСОВ ВЫКЛ · КАРТИНА НЕПОЛНАЯ", "NEARBY AIRCRAFT INCOMPLETE · NOT AN ALL-CLEAR": "БЛИЖНИЕ ВОЗДУШНЫЕ СУДА: ДАННЫЕ НЕПОЛНЫЕ · ОТСУТСТВИЕ УГРОЗ НЕ ПОДТВЕРЖДЕНО", - "{source} · LOCATION QUERY · RECENT": "{source} · ЗАПРОС ПО МЕСТУ · НЕДАВНИЕ", + "{source} · LAST {hours} H": "{source} · ЗА {hours} Ч", "ft": "фт", "kts": "уз", "PAUSE": "ПАУЗА", diff --git a/src/i18n/locales/uk.json b/src/i18n/locales/uk.json index 5c93f74b7..388ea566d 100644 --- a/src/i18n/locales/uk.json +++ b/src/i18n/locales/uk.json @@ -1672,14 +1672,15 @@ "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 секунд (Сигнали → Новини → Місцеві дані). Пауза, доки ви наводите вказівник на панель або вона у фокусі. Дані сигналів у реальному часі однаково оновлюються безперервно.", "ACQUIRING REGIONAL NEWS": "ОТРИМАННЯ РЕГІОНАЛЬНИХ НОВИН", "REGIONAL NEWS UNAVAILABLE": "РЕГІОНАЛЬНІ НОВИНИ НЕДОСТУПНІ", + "CACHED · REFRESH FAILED": "КЕШ · ОНОВЛЕННЯ НЕ ВДАЛОСЯ", "RESOLVING REGION": "ВИЗНАЧЕННЯ РЕГІОНУ", "REGION UNAVAILABLE": "РЕГІОН НЕДОСТУПНИЙ", - "NO RECENT LOCATION MATCHES": "НЕМАЄ СВІЖИХ ЗБІГІВ ЗА РОЗТАШУВАННЯМ", + "NO NEWS IN THE LAST {hours} H": "НЕМАЄ НОВИН ЗА {hours} ГОД", "{domain} · {age}": "{domain} · {age}", "{value} KM/H": "{value} КМ/ГОД", "CLOUD {pct}%": "ХМАРНІСТЬ {pct}%", "CLOUD UNKNOWN": "ХМАРНІСТЬ НЕВІДОМА", - "{source} · LOCATION QUERY": "{source} · ЗАПИТ ЗА РОЗТАШУВАННЯМ", + "{source} · CACHED {age}": "{source} · КЕШ {age}", "REGIONAL NEWS": "РЕГІОНАЛЬНІ НОВИНИ", "{label} · {radius} AIR/SEA WINDOW": "{label} · РЕЙСИ / СУДНА · РАДІУС {radius}", "{scope} · INSTALLATIONS {coverage}": "{scope} · ОБʼЄКТИ: {coverage}", @@ -1740,7 +1741,7 @@ "OBSERVED / MAPPED PINGS": "СПОСТЕРЕЖЕНІ / НАНЕСЕНІ КОНТАКТИ", "SOURCE-BACKED EVENTS · NO SYNTHETIC NEWS": "ПОДІЇ ПІДТВЕРДЖЕНІ ДЖЕРЕЛАМИ · БЕЗ ІМІТОВАНИХ НОВИН", "LATEST LOCATION-MATCHED REPORTING": "ОСТАННІ ПУБЛІКАЦІЇ ЗА РОЗТАШУВАННЯМ", - "{source} · LOCATION QUERY · RECENT": "{source} · ЗАПИТ ЗА РОЗТАШУВАННЯМ · НЕЩОДАВНІ", + "{source} · LAST {hours} H": "{source} · ЗА {hours} ГОД", "LOCAL INFO": "МІСЦЕВІ ДАНІ", "PLACE / CONDITIONS / POSITION": "МІСЦЕ / УМОВИ / ПОЗИЦІЯ", "TIME UNKNOWN": "ЧАС НЕВІДОМИЙ", diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json index 828baa256..912582289 100644 --- a/src/i18n/locales/zh-CN.json +++ b/src/i18n/locales/zh-CN.json @@ -1577,14 +1577,15 @@ "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 秒自动轮换简报页面(信号 → 新闻 → 本地)。悬停或聚焦面板时暂停。无论是否轮换,实时信号数据都会持续刷新。", "ACQUIRING REGIONAL NEWS": "正在获取地区新闻", "REGIONAL NEWS UNAVAILABLE": "地区新闻不可用", + "CACHED · REFRESH FAILED": "缓存 · 刷新失败", "RESOLVING REGION": "正在解析区域", "REGION UNAVAILABLE": "区域不可用", - "NO RECENT LOCATION MATCHES": "暂无近期位置匹配结果", + "NO NEWS IN THE LAST {hours} H": "过去 {hours} 小时无新闻", "{domain} · {age}": "{domain} · {age}", "{value} KM/H": "{value} km/h", "CLOUD {pct}%": "云量 {pct}%", "CLOUD UNKNOWN": "云量未知", - "{source} · LOCATION QUERY": "{source} · 位置查询", + "{source} · CACHED {age}": "{source} · 缓存 {age}", "REGIONAL NEWS": "地区新闻", "{label} · {radius} AIR/SEA WINDOW": "{label} · {radius} 空/海监视窗口", "{scope} · INSTALLATIONS {coverage}": "{scope} · 设施 {coverage}", @@ -1642,7 +1643,7 @@ "OBSERVED / MAPPED PINGS": "观测 / 地图标注目标", "SOURCE-BACKED EVENTS · NO SYNTHETIC NEWS": "来源可查的事件 · 无合成新闻", "LATEST LOCATION-MATCHED REPORTING": "当前地区最新报道", - "{source} · LOCATION QUERY · RECENT": "{source} · 位置查询 · 近期", + "{source} · LAST {hours} H": "{source} · 过去 {hours} 小时", "LOCAL INFO": "本地信息", "PLACE / CONDITIONS / POSITION": "地点 / 状况 / 位置", "TIME UNKNOWN": "时间未知", diff --git a/src/i18n/locales/zh-Hant.json b/src/i18n/locales/zh-Hant.json index e08b69304..628c71284 100644 --- a/src/i18n/locales/zh-Hant.json +++ b/src/i18n/locales/zh-Hant.json @@ -1567,14 +1567,15 @@ "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 秒自動輪換簡報頁面(信號 → 新聞 → 本地)。懸停或聚焦面板時暫停。無論是否輪換,實時信號數據都會持續刷新。", "ACQUIRING REGIONAL NEWS": "正在獲取地區新聞", "REGIONAL NEWS UNAVAILABLE": "地區新聞不可用", + "CACHED · REFRESH FAILED": "快取 · 重新整理失敗", "RESOLVING REGION": "正在解析區域", "REGION UNAVAILABLE": "區域不可用", - "NO RECENT LOCATION MATCHES": "暫無近期位置匹配結果", + "NO NEWS IN THE LAST {hours} H": "過去 {hours} 小時無新聞", "{domain} · {age}": "{domain} · {age}", "{value} KM/H": "{value} km/h", "CLOUD {pct}%": "雲量 {pct}%", "CLOUD UNKNOWN": "雲量未知", - "{source} · LOCATION QUERY": "{source} · 位置查詢", + "{source} · CACHED {age}": "{source} · 快取 {age}", "REGIONAL NEWS": "地區新聞", "{label} · {radius} AIR/SEA WINDOW": "{label} · {radius} 空/海監視窗口", "{scope} · INSTALLATIONS {coverage}": "{scope} · 設施 {coverage}", @@ -1632,7 +1633,7 @@ "OBSERVED / MAPPED PINGS": "觀測 / 地圖標註目標", "SOURCE-BACKED EVENTS · NO SYNTHETIC NEWS": "來源可查的事件 · 無合成新聞", "LATEST LOCATION-MATCHED REPORTING": "當前地區最新報道", - "{source} · LOCATION QUERY · RECENT": "{source} · 位置查詢 · 近期", + "{source} · LAST {hours} H": "{source} · 過去 {hours} 小時", "LOCAL INFO": "本地信息", "PLACE / CONDITIONS / POSITION": "地點 / 狀況 / 位置", "TIME UNKNOWN": "時間未知", diff --git a/src/ui/cockpitBriefPages.js b/src/ui/cockpitBriefPages.js index e92488831..9f75c83d8 100644 --- a/src/ui/cockpitBriefPages.js +++ b/src/ui/cockpitBriefPages.js @@ -1,9 +1,29 @@ /** * The Cockpit briefing's pages and the state it starts in. It needs only the - * i18n module, so the controller and the view can both read it. + * i18n module and the regional-news window, so the controller and the view + * can both read it. */ +import { REGIONAL_NEWS_WINDOW_HOURS } from '../data/regionalNewsWindow.js'; import { msg, t } from '../i18n/index.js'; +// i18n-ignore: provider name +/** The news feed named before any briefing has answered. */ +export const DEFAULT_NEWS_SOURCE = 'GOOGLE NEWS RSS'; + +/** + * The Regional News footer for a fresh, empty or unavailable list: the feed + * and the window its articles are held to. + * @param {string} [source] + * @param {number} [hours] + * @returns {string} + */ +export function newsWindowFooter( + source = DEFAULT_NEWS_SOURCE, + hours = REGIONAL_NEWS_WINDOW_HOURS, +) { + return t('{source} · LAST {hours} H', { source, hours }); +} + export const COCKPIT_BRIEF_PAGES = [ { id: 'signals', @@ -15,8 +35,7 @@ export const COCKPIT_BRIEF_PAGES = [ id: 'news', kickerKey: msg('REGIONAL NEWS'), subtitleKey: msg('LATEST LOCATION-MATCHED REPORTING'), - sourceKey: msg('{source} · LOCATION QUERY · RECENT'), - sourceName: 'GOOGLE NEWS RSS', // i18n-ignore: provider name + // The news footer comes from the news state (`news.footer`), not here. }, { id: 'local', @@ -60,6 +79,7 @@ export function createBriefState() { statusHidden: false, state: null, status: t('ACQUIRING REGIONAL NEWS'), + footer: newsWindowFooter(), articles: [], }, local: { diff --git a/src/ui/cockpitBriefing.js b/src/ui/cockpitBriefing.js index a5c6d8c5a..738c8af80 100644 --- a/src/ui/cockpitBriefing.js +++ b/src/ui/cockpitBriefing.js @@ -12,7 +12,14 @@ import { COCKPIT_BRIEF_PAGES, CYCLE_HELP_KEYS, createBriefState, + newsWindowFooter, } from './cockpitBriefPages.js'; +import { + recentRegionalArticles, + regionalNewsWindowHours, +} from '../data/regionalNewsWindow.js'; + +const NEWS_ROWS = 4; // regionalModel.weatherCodeLabel is shared with node code and returns // English; translate it here. @@ -52,9 +59,13 @@ export function showBriefPage(index, { manual = false } = {}) { kicker: t(page.kickerKey), subtitle: t(page.subtitleKey), position: `${this.briefPageIndex + 1} / ${count}`, - source: page.sourceKey - ? t(page.sourceKey, { source: page.sourceName }) - : page.source, + // The news footer follows the news state, so it survives page changes. + source: + page.id === 'news' + ? this.brief.news.footer + : page.sourceKey + ? t(page.sourceKey) + : page.source, }); this.publishBriefView(); if (manual && this.briefAutoRotateEnabled) @@ -196,8 +207,8 @@ export function maybeRefreshRegionalBrief(info) { subjectId !== this.regionalBriefSubjectId ) return; - this.regionalBrief = payload; - this.renderRegionalBrief(payload, info); + this.regionalBrief = withCachedNews(payload, this.regionalBrief); + this.renderRegionalBrief(this.regionalBrief, info); }) .catch((error) => { if ( @@ -206,7 +217,11 @@ export function maybeRefreshRegionalBrief(info) { requestToken === this.regionalBriefRequestToken && subjectId === this.regionalBriefSubjectId ) { - this.renderRegionalBriefStatus('unavailable', info); + if (this.regionalBrief) { + const previous = this.regionalBrief; + this.regionalBrief = cachedNews(previous, previous); + this.renderRegionalBrief(this.regionalBrief, info); + } else this.renderRegionalBriefStatus('unavailable', info); } }) .finally(() => { @@ -215,6 +230,75 @@ export function maybeRefreshRegionalBrief(info) { }); } +/** + * A brief whose news comes from `previous` after a refresh that brought none: + * the earlier articles stay, marked `cached` so they are labelled as such. + * @param {object} payload The brief to keep everything else from. + * @param {object} previous The last brief rendered for this subject. + */ +function cachedNews(payload, previous) { + return { + ...payload, + newsStatus: 'cached', + newsSource: previous.newsSource, + newsWindowHours: previous.newsWindowHours, + newsFetchedAt: previous.newsFetchedAt ?? previous.retrievedAt ?? null, + articles: previous.articles, + }; +} + +// A refresh whose news read failed keeps the articles from before it. +function withCachedNews(payload, previous) { + return previous && payload?.newsStatus === 'unavailable' + ? cachedNews(payload, previous) + : payload; +} + +/** + * The Regional News state a brief presents. `ready` and `cached` have rows + * inside the window; `cached` is a refresh that failed (a client-side failure, + * or the local proxy's `stale` answer). `empty` is a source that answered with + * nothing in the window; anything else is `unavailable`. + * @returns {{state: string, status: string, footer: string, articles: object[]}} + */ +function regionalNewsView(payload) { + const hours = regionalNewsWindowHours(payload?.newsWindowHours); + // Old caches and the local path are held to the window here too. + const articles = recentRegionalArticles(payload?.articles, { + windowHours: hours, + limit: NEWS_ROWS, + }); + const source = String( + payload?.newsSource || t('REGIONAL NEWS'), + ).toUpperCase(); + const refreshFailed = + payload?.newsStatus === 'cached' || payload?.status === 'stale'; + if (articles.length && refreshFailed) + return { + state: 'cached', + status: t('CACHED · REFRESH FAILED'), + footer: t('{source} · CACHED {age}', { + source, + age: formatCockpitBriefAge( + payload?.newsFetchedAt ?? payload?.retrievedAt, + ), + }), + articles, + }; + const answered = + !refreshFailed && ['ready', 'empty'].includes(payload?.newsStatus); + return { + state: articles.length ? 'ready' : answered ? 'empty' : 'unavailable', + status: articles.length + ? '' + : answered + ? t('NO NEWS IN THE LAST {hours} H', { hours }) + : t('REGIONAL NEWS UNAVAILABLE'), + footer: newsWindowFooter(source, hours), + articles, + }; +} + export function renderRegionalBriefStatus(status, info) { const { news, local } = this.brief; news.statusHidden = false; @@ -223,7 +307,10 @@ export function renderRegionalBriefStatus(status, info) { status === 'loading' ? t('ACQUIRING REGIONAL NEWS') : t('REGIONAL NEWS UNAVAILABLE'); - if (status === 'unavailable') news.articles = []; + news.footer = newsWindowFooter(); + // Only called with no brief for this subject: any rows are another's. + news.articles = []; + if (this.briefPageIndex === 1) this.brief.source = news.footer; if (status === 'loading') local.place = t('RESOLVING REGION'); if (status === 'unavailable') local.place = t('REGION UNAVAILABLE'); local.coordinates = localCoordinates(info); @@ -231,7 +318,7 @@ export function renderRegionalBriefStatus(status, info) { } export function renderRegionalBrief(payload, info) { - const articles = Array.isArray(payload?.articles) ? payload.articles : []; + const { state, status, footer, articles } = regionalNewsView(payload); const seen = new Map(); const storyKey = (url) => { const count = seen.get(url) ?? 0; @@ -244,13 +331,11 @@ export function renderRegionalBrief(payload, info) { const placeLabel = payload?.place?.label || payload?.place?.country || t('REGION UNAVAILABLE'); this.brief.news = { - statusHidden: articles.length > 0, - state: payload?.newsStatus || 'unavailable', - status: - payload?.newsStatus === 'empty' - ? t('NO RECENT LOCATION MATCHES') - : t('REGIONAL NEWS UNAVAILABLE'), - articles: articles.slice(0, 4).map((article) => ({ + statusHidden: state === 'ready', + state, + status, + footer, + articles: articles.map((article) => ({ // A row keeps its node, and so its focus, only for the same story. key: storyKey(article.url), url: article.url, @@ -284,11 +369,7 @@ export function renderRegionalBrief(payload, info) { : '—', }; this.brief.regionalStatus = payload?.status || 'partial'; - if (this.briefPageIndex === 1) { - this.brief.source = t('{source} · LOCATION QUERY', { - source: String(payload?.newsSource || t('REGIONAL NEWS')).toUpperCase(), - }); - } + if (this.briefPageIndex === 1) this.brief.source = footer; this.publishBriefView(); this.scheduleContextLayout(); } diff --git a/src/ui/cockpitBriefing.test.mjs b/src/ui/cockpitBriefing.test.mjs index 7018c8f79..1b3fbf0bf 100644 --- a/src/ui/cockpitBriefing.test.mjs +++ b/src/ui/cockpitBriefing.test.mjs @@ -3,11 +3,14 @@ import '../testSupport/registerDom.mjs'; import test from 'node:test'; import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; import { createPinia } from 'pinia'; import { createApp, nextTick } from 'vue'; import { setLocale } from '../i18n/index.js'; import { createBriefState } from './cockpitBriefPages.js'; import { + maybeRefreshRegionalBrief, publishBriefView, renderRegionalBrief, renderRegionalBriefStatus, @@ -88,10 +91,7 @@ test('pages, the cycle toggle and the source follow the controller', async (t) = await nextTick(); assert.equal(text('#cockpit-brief-kicker'), 'REGIONAL NEWS'); assert.equal(text('#cockpit-brief-position'), '2 / 3'); - assert.equal( - text('#cockpit-brief-source'), - 'GOOGLE NEWS RSS · LOCATION QUERY · RECENT', - ); + assert.equal(text('#cockpit-brief-source'), 'GOOGLE NEWS RSS · LAST 24 H'); assert.deepEqual(visiblePages(), ['news']); assert.deepEqual(current(), ['false', 'true', 'false']); assert.equal($('#cockpit-signal-stream').dataset.briefPage, 'news'); @@ -129,7 +129,8 @@ test('regional news and local conditions render what the region returned', async url: `https://example.com/${index}`, title: `Story ${index}`, domain: 'example.com', - publishedAt: new Date().toISOString(), + // Newest first is the shown order, so Story 0 is the newest. + publishedAt: new Date(Date.now() - index * 60_000).toISOString(), })), weather: { temperatureC: 21.6, @@ -159,7 +160,7 @@ test('regional news and local conditions render what the region returned', async assert.equal(text('#cockpit-local-condition'), 'RAIN'); assert.equal(text('#cockpit-local-cloud'), 'CLOUD 40%'); assert.equal(text('#cockpit-local-precipitation'), '1.3'); - assert.equal(text('#cockpit-brief-source'), 'WIRE · LOCATION QUERY'); + assert.equal(text('#cockpit-brief-source'), 'WIRE · LAST 24 H'); assert.equal($('#cockpit-signal-stream').dataset.regionalStatus, 'ok'); renderRegionalBriefStatus.call(owner, 'unavailable', {}); await nextTick(); @@ -210,26 +211,246 @@ test('a refreshed news list keeps a focused story on its own link', async (t) => assert.equal($('#cockpit-news-list').textContent.includes('Story y'), true); }); -test('the news source names the feed only while it is current on page 2', async (t) => { +// This contract changed on purpose: the footer used to fall back to a +// static "· RECENT" on every page change, which promised nothing. It now +// follows the news state and names the window it holds articles to. +test('the news footer follows the news state across page changes, not a static RECENT', async (t) => { const { text, owner } = fixture(t); showBriefPage.call(owner, 1); - renderRegionalBrief.call(owner, { newsSource: 'wire', articles: [] }, INFO); + renderRegionalBrief.call( + owner, + { newsStatus: 'ready', newsSource: 'wire', newsWindowHours: 24, articles: [story('a')] }, + INFO, + ); await nextTick(); - assert.equal(text('#cockpit-brief-source'), 'WIRE · LOCATION QUERY'); + assert.equal(text('#cockpit-brief-source'), 'WIRE · LAST 24 H'); showBriefPage.call(owner, 2); showBriefPage.call(owner, 1); await nextTick(); - assert.equal( - text('#cockpit-brief-source'), - 'GOOGLE NEWS RSS · LOCATION QUERY · RECENT', - ); + assert.equal(text('#cockpit-brief-source'), 'WIRE · LAST 24 H'); showBriefPage.call(owner, 0); - renderRegionalBrief.call(owner, { newsSource: 'wire', articles: [] }, INFO); + renderRegionalBrief.call( + owner, + { newsStatus: 'ready', newsSource: 'wire', newsWindowHours: 12, articles: [story('a')] }, + INFO, + ); await nextTick(); + // Off page 2 the footer is the current page's. assert.equal( text('#cockpit-brief-source'), 'SOURCE-BACKED EVENTS · NO SYNTHETIC NEWS', ); + showBriefPage.call(owner, 1); + await nextTick(); + assert.equal(text('#cockpit-brief-source'), 'WIRE · LAST 12 H'); +}); + +test('the news banner is hidden by the stylesheet, not only by the attribute', async (t) => { + // happy-dom applies no author CSS by itself, so `hidden` alone proves + // nothing: `.cockpit-brief-status { display: grid }` used to beat it. + const css = readFileSync( + fileURLToPath(new URL('./styles/cockpit.css', import.meta.url)), + 'utf8', + ); + assert.match(css, /\.cockpit-brief-status\[hidden\]\s*\{\s*display:\s*none;?\s*\}/); + const { $, owner } = fixture(t); + const style = document.head.appendChild(document.createElement('style')); + t.after(() => style.remove()); + style.textContent = css; + showBriefPage.call(owner, 1); + renderRegionalBrief.call(owner, { newsStatus: 'ready', articles: [story('a')] }, INFO); + await nextTick(); + const banner = $('#cockpit-news-status'); + assert.equal(banner.hidden, true); + assert.equal(getComputedStyle(banner).display, 'none'); + renderRegionalBrief.call(owner, { newsStatus: 'empty', articles: [] }, INFO); + await nextTick(); + assert.equal(getComputedStyle(banner).display, 'grid'); +}); + +const hoursAgo = (hours) => new Date(Date.now() - hours * 3_600_000).toISOString(); + +test('ready, cached, empty and unavailable each label the news differently', async (t) => { + const { $, text, owner } = fixture(t); + showBriefPage.call(owner, 1); + const rows = () => + [...document.querySelectorAll('#cockpit-news-list strong')].map((row) => row.textContent); + const banner = () => ({ + hidden: $('#cockpit-news-status').hidden, + state: $('#cockpit-news-status').dataset.state, + text: text('#cockpit-news-status'), + }); + const ready = { + status: 'ready', + newsStatus: 'ready', + newsSource: 'Google News RSS', + newsWindowHours: 24, + newsFetchedAt: hoursAgo(0.5), + articles: [story('a'), story('b')], + }; + renderRegionalBrief.call(owner, ready, INFO); + await nextTick(); + assert.equal(banner().hidden, true); + assert.equal(banner().state, 'ready'); + assert.deepEqual(rows(), ['Story a', 'Story b']); + assert.equal(text('#cockpit-brief-source'), 'GOOGLE NEWS RSS · LAST 24 H'); + + // The local proxy's stale answer is a refresh that failed. + renderRegionalBrief.call(owner, { ...ready, status: 'stale' }, INFO); + await nextTick(); + assert.deepEqual(banner(), { + hidden: false, + state: 'cached', + text: 'CACHED · REFRESH FAILED', + }); + assert.deepEqual(rows(), ['Story a', 'Story b']); + assert.equal(text('#cockpit-brief-source'), 'GOOGLE NEWS RSS · CACHED 30M AGO'); + + renderRegionalBrief.call( + owner, + { ...ready, newsStatus: 'empty', newsSource: 'Google News RSS', articles: [] }, + INFO, + ); + await nextTick(); + assert.deepEqual(banner(), { + hidden: false, + state: 'empty', + text: 'NO NEWS IN THE LAST 24 H', + }); + assert.deepEqual(rows(), []); + + renderRegionalBrief.call( + owner, + { ...ready, newsStatus: 'unavailable', newsSource: null, articles: [] }, + INFO, + ); + await nextTick(); + assert.deepEqual(banner(), { + hidden: false, + state: 'unavailable', + text: 'REGIONAL NEWS UNAVAILABLE', + }); + assert.deepEqual(rows(), []); +}); + +test('articles outside the window are dropped even when a server sends them', async (t) => { + const { $, text, owner } = fixture(t); + showBriefPage.call(owner, 1); + const dated = (id, publishedAt) => ({ ...story(id), publishedAt }); + // The reported case: 4, 104, 215 and 165 days old under "RECENT". + renderRegionalBrief.call( + owner, + { + newsStatus: 'ready', + articles: [ + dated('old', hoursAgo(4 * 24)), + dated('older', hoursAgo(104 * 24)), + dated('undated', null), + dated('one', hoursAgo(20)), + dated('two', hoursAgo(2)), + ], + }, + INFO, + ); + await nextTick(); + assert.deepEqual( + [...document.querySelectorAll('#cockpit-news-list strong')].map((row) => row.textContent), + ['Story two', 'Story one'], + ); + assert.equal($('#cockpit-news-status').hidden, true); + renderRegionalBrief.call( + owner, + { newsStatus: 'ready', articles: [dated('old', hoursAgo(25))] }, + INFO, + ); + await nextTick(); + assert.equal(document.querySelectorAll('#cockpit-news-list li').length, 0); + assert.equal(text('#cockpit-news-status'), 'NO NEWS IN THE LAST 24 H'); +}); + +test('a failed refresh keeps the earlier articles as cached, and clears only when there are none', async (t) => { + const { $, text, owner } = fixture(t); + const answers = []; + Object.assign(owner, { + active: true, + regionalBriefSubjectId: null, + regionalBriefAbort: null, + regionalBriefRequestToken: 0, + regionalBriefFetchedAt: 0, + regionalBrief: null, + renderRegionalBrief, + renderRegionalBriefStatus, + }); + owner.services = { + ...owner.services, + regionalDistanceM: () => 0, + fetchRegionalBrief: () => answers.shift()(), + }; + const refresh = async (answer, info = { ...INFO, icao24: 'abc123' }) => { + answers.push(answer); + owner.regionalBriefFetchedAt = 0; + maybeRefreshRegionalBrief.call(owner, info); + await new Promise((resolve) => setTimeout(resolve, 0)); + await nextTick(); + }; + const rows = () => document.querySelectorAll('#cockpit-news-list li').length; + showBriefPage.call(owner, 1); + + // No earlier brief: an error clears and says unavailable. + await refresh(() => Promise.reject(new Error('503'))); + assert.equal($('#cockpit-news-status').dataset.state, 'unavailable'); + assert.equal(text('#cockpit-news-status'), 'REGIONAL NEWS UNAVAILABLE'); + assert.equal(rows(), 0); + + const fetchedAt = hoursAgo(1); + await refresh(() => + Promise.resolve({ + status: 'ready', + newsStatus: 'ready', + newsSource: 'Google News RSS', + newsWindowHours: 24, + newsFetchedAt: fetchedAt, + articles: [story('a'), story('b')], + }), + ); + assert.equal($('#cockpit-news-status').hidden, true); + assert.equal(rows(), 2); + + // A network failure keeps the rows and says so, with their age. + await refresh(() => Promise.reject(new TypeError('Failed to fetch'))); + assert.equal($('#cockpit-news-status').hidden, false); + assert.equal(text('#cockpit-news-status'), 'CACHED · REFRESH FAILED'); + assert.equal(rows(), 2); + assert.equal(text('#cockpit-brief-source'), 'GOOGLE NEWS RSS · CACHED 1H AGO'); + showBriefPage.call(owner, 2); + showBriefPage.call(owner, 1); + await nextTick(); + assert.equal(text('#cockpit-brief-source'), 'GOOGLE NEWS RSS · CACHED 1H AGO'); + + // So does a brief whose news read failed while weather answered. + await refresh(() => + Promise.resolve({ status: 'partial', newsStatus: 'unavailable', articles: [] }), + ); + assert.equal(text('#cockpit-news-status'), 'CACHED · REFRESH FAILED'); + assert.equal(rows(), 2); + + // A successful refresh clears the cached label; a true empty clears rows. + await refresh(() => + Promise.resolve({ status: 'ready', newsStatus: 'empty', newsSource: 'Google News RSS', articles: [] }), + ); + assert.equal(text('#cockpit-news-status'), 'NO NEWS IN THE LAST 24 H'); + assert.equal(rows(), 0); + assert.equal(text('#cockpit-brief-source'), 'GOOGLE NEWS RSS · LAST 24 H'); + + // Another aircraft never inherits the last one's rows. + await refresh(() => Promise.resolve({ newsStatus: 'ready', articles: [story('c')] })); + assert.equal(rows(), 1); + await refresh( + () => Promise.reject(new Error('503')), + { ...INFO, icao24: 'def456' }, + ); + assert.equal(text('#cockpit-news-status'), 'REGIONAL NEWS UNAVAILABLE'); + assert.equal(rows(), 0); }); test('an unchanged position publishes nothing new', (t) => { diff --git a/src/ui/styles/cockpit.css b/src/ui/styles/cockpit.css index d7ad845b6..3a56e7963 100644 --- a/src/ui/styles/cockpit.css +++ b/src/ui/styles/cockpit.css @@ -1818,7 +1818,13 @@ html:not([lang='en']) #cockpit-brief-auto { letter-spacing: 0.13em; text-align: center; } -.cockpit-brief-status[data-state='unavailable'] { +/* `display: grid` above would otherwise beat the UA [hidden] rule and keep a + stale banner over a populated list. */ +.cockpit-brief-status[hidden] { + display: none; +} +.cockpit-brief-status[data-state='unavailable'], +.cockpit-brief-status[data-state='cached'] { color: #d5a863; } .cockpit-local-place { From 2d9d5189467e34fc0f28dd0b26876de2fc03ae65 Mon Sep 17 00:00:00 2001 From: Denis Groshev Date: Wed, 4 Nov 2026 02:26:46 +0100 Subject: [PATCH 036/171] Add the news report model, markers and source The pure half of a news layer: validated records for a news server's `/api/news/hotspots|feed|outline` contract, a presentation model and canvas markers and picture cards, and a fetch client. - Colour carries severity only (0 no physical event, 1 minor, 2 significant, 3 major), never a side; the category is the icon, the rim is attestation (confirmed, a claim, one side's own press), size grows with sources and markers fade with age. - Cards say "Reported by {side} sources" and mark official channels; a machine-read English headline is labelled as such. - `createNewsSource` reads same-origin routes with a 15 s timeout, a 4 MiB cap and record-by-record validation; `NEWS_API_PATHS` and `newsQueryAllowed` let a host proxy exactly what the client sends. A 503 marked unavailable means "not configured": no retries. - Exported as `./layers/news/source`, with its own package boundary. --- package.json | 1 + scripts/package-boundaries.json | 11 + src/i18n/locales/ar.json | 56 +++ src/i18n/locales/de.json | 52 +++ src/i18n/locales/es.json | 53 +++ src/i18n/locales/fr.json | 53 +++ src/i18n/locales/it.json | 53 +++ src/i18n/locales/ja.json | 51 +++ src/i18n/locales/pt.json | 53 +++ src/i18n/locales/ru.json | 54 +++ src/i18n/locales/uk.json | 54 +++ src/i18n/locales/zh-CN.json | 51 +++ src/i18n/locales/zh-Hant.json | 51 +++ src/i18n/same-as-english.json | 22 ++ src/layers/news/cards.js | 206 ++++++++++ src/layers/news/model.js | 643 ++++++++++++++++++++++++++++++++ src/layers/news/model.test.mjs | 444 ++++++++++++++++++++++ src/layers/news/records.js | 325 ++++++++++++++++ src/layers/news/source.js | 162 ++++++++ src/layers/news/source.test.mjs | 164 ++++++++ src/layers/news/sprites.js | 94 +++++ 21 files changed, 2653 insertions(+) create mode 100644 src/layers/news/cards.js create mode 100644 src/layers/news/model.js create mode 100644 src/layers/news/model.test.mjs create mode 100644 src/layers/news/records.js create mode 100644 src/layers/news/source.js create mode 100644 src/layers/news/source.test.mjs create mode 100644 src/layers/news/sprites.js diff --git a/package.json b/package.json index 42121974f..c267cef79 100644 --- a/package.json +++ b/package.json @@ -257,6 +257,7 @@ "./layers/gnss/source": "./src/layers/gnss/source.js", "./layers/ghostmaps/source": "./src/layers/ghostMaps/source.js", "./layers/drone-airspace/source": "./src/layers/droneAirspace/source.js", + "./layers/news/source": "./src/layers/news/source.js", "./layers/firms/source": "./src/layers/firms/source.js", "./layers/installations/source": "./src/layers/installations/source.js", "./layers/launches/source": "./src/layers/launches/source.js", diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 6ba148306..328112590 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -4817,6 +4817,17 @@ ], "external": [] }, + "news-source": { + "exports": ["./layers/news/source"], + "modules": [ + "src/layers/news/source.js", + "src/layers/news/records.js", + "src/sources/httpBody.js", + "src/sources/capability.js", + "src/i18n/marker.js" + ], + "external": [] + }, "perimeters-source": { "exports": ["./layers/perimeters/source"], "modules": [ diff --git a/src/i18n/locales/ar.json b/src/i18n/locales/ar.json index 186bd4e1e..59cd4caa6 100644 --- a/src/i18n/locales/ar.json +++ b/src/i18n/locales/ar.json @@ -1,4 +1,60 @@ { + "News feed unavailable": "موجز الأخبار غير متاح", + "Disputed: {name}": "منطقة متنازع عليها: {name}", + "Administered by {holder} · claimed by {claimant}": "تديرها {holder} · تطالب بها {claimant}", + "Self-administered · claimed by {claimant}": "تدير نفسها · تطالب بها {claimant}", + "UN-patrolled zone": "منطقة تسيّر فيها الأمم المتحدة دوريات", + "Claimed by neither neighbour": "لا يطالب بها أي من الجارين", + "Video": "فيديو", + "Photos": "صور", + "Claimed by {who}": "ادعاء: {who}", + "Claimed": "ادعاء", + "Not yet confirmed by others": "لم يؤكده آخرون بعد", + "Reported by {side} sources": "أوردته مصادر {side}", + "Reported by {sides}": "أوردته {sides}", + "{side} sources": "مصادر {side}", + "Official": "رسمي", + "Reported by both sides": "أورده الطرفان", + "Independently reported": "أُبلغ عنه بشكل مستقل", + "Single source": "مصدر واحد", + "International": "دولية", + "Independent": "مستقلة", + "Unattributed": "غير منسوب", + "Outside party": "طرف خارجي", + "Ukraine–Russia": "أوكرانيا–روسيا", + "Israel–Gaza–Lebanon": "إسرائيل–غزة–لبنان", + "Iran–Hormuz": "إيران–هرمز", + "Yemen–Red Sea": "اليمن–البحر الأحمر", + "Sudan": "السودان", + "Sahel": "الساحل", + "Elsewhere": "أماكن أخرى", + "Strike": "ضربة", + "Alert": "إنذار", + "Air defence": "دفاع جوي", + "Ground fighting": "قتال بري", + "Casualties": "إصابات", + "Humanitarian": "إنساني", + "Disaster": "كارثة", + "Protest": "احتجاج", + "Political": "سياسي", + "No physical event": "لا حدث ميداني", + "Minor incident": "حادث بسيط", + "Significant": "كبير", + "Major": "جسيم", + "age|now": "الآن", + "{minutes} min": "{minutes} د", + "{hours} h": "{hours} س", + "{count} sources": { + "zero": "{count} مصدر", + "one": "مصدر واحد ({count})", + "two": "مصدران ({count})", + "few": "{count} مصادر", + "many": "{count} مصدرًا", + "other": "{count} مصدر" + }, + "News feed not configured on this server": "موجز الأخبار غير مهيأ على هذا الخادم", + "Malformed news hotspots response": "استجابة بؤر الأخبار غير صالحة", + "Malformed news feed response": "استجابة موجز الأخبار غير صالحة", "NO PLACE LEFT BEHIND": "لا مكان يُترك خلفنا", "Initializing photorealistic world...": "جارٍ تهيئة العالم الواقعي…", "Configuring viewer...": "جارٍ إعداد العارض…", diff --git a/src/i18n/locales/de.json b/src/i18n/locales/de.json index 0fa269e20..9421361bc 100644 --- a/src/i18n/locales/de.json +++ b/src/i18n/locales/de.json @@ -1,4 +1,56 @@ { + "News feed unavailable": "Nachrichtenfeed nicht verfügbar", + "Disputed: {name}": "Umstritten: {name}", + "Administered by {holder} · claimed by {claimant}": "Verwaltet von {holder} · beansprucht von {claimant}", + "Self-administered · claimed by {claimant}": "Selbstverwaltet · beansprucht von {claimant}", + "UN-patrolled zone": "Von der UNO überwachte Zone", + "Claimed by neither neighbour": "Von keinem Nachbarn beansprucht", + "Video": "Video", + "Photos": "Fotos", + "Claimed by {who}": "Behauptet von {who}", + "Claimed": "Behauptung", + "Not yet confirmed by others": "Noch nicht von anderen bestätigt", + "Reported by {side} sources": "Gemeldet von Quellen aus {side}", + "Reported by {sides}": "Gemeldet von {sides}", + "{side} sources": "Quellen aus {side}", + "Official": "Offiziell", + "Reported by both sides": "Von beiden Seiten gemeldet", + "Independently reported": "Unabhängig gemeldet", + "Single source": "Einzelne Quelle", + "International": "International", + "Independent": "Unabhängig", + "Unattributed": "Ohne Zuordnung", + "Outside party": "Außenstehende Partei", + "Ukraine–Russia": "Ukraine–Russland", + "Israel–Gaza–Lebanon": "Israel–Gaza–Libanon", + "Iran–Hormuz": "Iran–Hormus", + "Yemen–Red Sea": "Jemen–Rotes Meer", + "Sudan": "Sudan", + "Sahel": "Sahel", + "Elsewhere": "Anderswo", + "Strike": "Angriff", + "Alert": "Warnung", + "Air defence": "Luftabwehr", + "Ground fighting": "Bodenkämpfe", + "Casualties": "Opfer", + "Humanitarian": "Humanitär", + "Disaster": "Katastrophe", + "Protest": "Protest", + "Political": "Politik", + "No physical event": "Kein physisches Ereignis", + "Minor incident": "Kleiner Vorfall", + "Significant": "Erheblich", + "Major": "Schwer", + "age|now": "jetzt", + "{minutes} min": "{minutes} Min.", + "{hours} h": "{hours} Std.", + "{count} sources": { + "one": "{count} Quelle", + "other": "{count} Quellen" + }, + "News feed not configured on this server": "Nachrichtenfeed auf diesem Server nicht eingerichtet", + "Malformed news hotspots response": "Fehlerhafte Antwort zu Nachrichten-Brennpunkten", + "Malformed news feed response": "Fehlerhafte Antwort des Nachrichtenfeeds", "Flying to Austin, TX...": "Flug nach Austin, TX...", "Restoring shared view...": "Geteilte Ansicht wird wiederhergestellt...", "Configuring viewer...": "Viewer wird konfiguriert...", diff --git a/src/i18n/locales/es.json b/src/i18n/locales/es.json index 078096514..914a85171 100644 --- a/src/i18n/locales/es.json +++ b/src/i18n/locales/es.json @@ -1,4 +1,57 @@ { + "News feed unavailable": "Noticias no disponibles", + "Disputed: {name}": "En disputa: {name}", + "Administered by {holder} · claimed by {claimant}": "Administrado por {holder} · reclamado por {claimant}", + "Self-administered · claimed by {claimant}": "Autogobernado · reclamado por {claimant}", + "UN-patrolled zone": "Zona patrullada por la ONU", + "Claimed by neither neighbour": "Ningún vecino lo reclama", + "Video": "Vídeo", + "Photos": "Fotos", + "Claimed by {who}": "Según {who}", + "Claimed": "Afirmación", + "Not yet confirmed by others": "Aún sin confirmar por otros", + "Reported by {side} sources": "Informado por fuentes de {side}", + "Reported by {sides}": "Informado por {sides}", + "{side} sources": "fuentes de {side}", + "Official": "Oficial", + "Reported by both sides": "Informado por ambos bandos", + "Independently reported": "Informado de forma independiente", + "Single source": "Fuente única", + "International": "Internacional", + "Independent": "Independiente", + "Unattributed": "Sin atribuir", + "Outside party": "Parte externa", + "Ukraine–Russia": "Ucrania–Rusia", + "Israel–Gaza–Lebanon": "Israel–Gaza–Líbano", + "Iran–Hormuz": "Irán–Ormuz", + "Yemen–Red Sea": "Yemen–Mar Rojo", + "Sudan": "Sudán", + "Sahel": "Sahel", + "Elsewhere": "En otros lugares", + "Strike": "Ataque", + "Alert": "Alerta", + "Air defence": "Defensa aérea", + "Ground fighting": "Combates terrestres", + "Casualties": "Víctimas", + "Humanitarian": "Humanitario", + "Disaster": "Catástrofe", + "Protest": "Protesta", + "Political": "Político", + "No physical event": "Sin hecho físico", + "Minor incident": "Incidente menor", + "Significant": "Significativo", + "Major": "Grave", + "age|now": "ahora", + "{minutes} min": "{minutes} min", + "{hours} h": "{hours} h", + "{count} sources": { + "one": "{count} fuente", + "many": "{count} fuentes", + "other": "{count} fuentes" + }, + "News feed not configured on this server": "Noticias no configuradas en este servidor", + "Malformed news hotspots response": "Respuesta de focos de noticias mal formada", + "Malformed news feed response": "Respuesta de noticias mal formada", "NO PLACE LEFT BEHIND": "NINGÚN RINCÓN SIN VIGILAR", "Initializing photorealistic world...": "Inicializando el mundo fotorrealista...", "Configuring viewer...": "Configurando el visor...", diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json index 3ce27c53c..f01ca2956 100644 --- a/src/i18n/locales/fr.json +++ b/src/i18n/locales/fr.json @@ -1,4 +1,57 @@ { + "News feed unavailable": "Fil d’actualités indisponible", + "Disputed: {name}": "Contesté : {name}", + "Administered by {holder} · claimed by {claimant}": "Administré par {holder} · revendiqué par {claimant}", + "Self-administered · claimed by {claimant}": "Autoadministré · revendiqué par {claimant}", + "UN-patrolled zone": "Zone patrouillée par l’ONU", + "Claimed by neither neighbour": "Revendiqué par aucun voisin", + "Video": "Vidéo", + "Photos": "Photos", + "Claimed by {who}": "Selon {who}", + "Claimed": "Affirmation", + "Not yet confirmed by others": "Pas encore confirmé par d’autres", + "Reported by {side} sources": "Rapporté par des sources {side}", + "Reported by {sides}": "Rapporté par {sides}", + "{side} sources": "sources {side}", + "Official": "Officiel", + "Reported by both sides": "Rapporté par les deux camps", + "Independently reported": "Rapporté de façon indépendante", + "Single source": "Source unique", + "International": "Internationale", + "Independent": "Indépendante", + "Unattributed": "Non attribué", + "Outside party": "Partie extérieure", + "Ukraine–Russia": "Ukraine–Russie", + "Israel–Gaza–Lebanon": "Israël–Gaza–Liban", + "Iran–Hormuz": "Iran–Ormuz", + "Yemen–Red Sea": "Yémen–mer Rouge", + "Sudan": "Soudan", + "Sahel": "Sahel", + "Elsewhere": "Ailleurs", + "Strike": "Frappe", + "Alert": "Alerte", + "Air defence": "Défense aérienne", + "Ground fighting": "Combats au sol", + "Casualties": "Victimes", + "Humanitarian": "Humanitaire", + "Disaster": "Catastrophe", + "Protest": "Manifestation", + "Political": "Politique", + "No physical event": "Aucun événement physique", + "Minor incident": "Incident mineur", + "Significant": "Important", + "Major": "Majeur", + "age|now": "maintenant", + "{minutes} min": "{minutes} min", + "{hours} h": "{hours} h", + "{count} sources": { + "one": "{count} source", + "many": "{count} sources", + "other": "{count} sources" + }, + "News feed not configured on this server": "Fil d’actualités non configuré sur ce serveur", + "Malformed news hotspots response": "Réponse des foyers d’actualité mal formée", + "Malformed news feed response": "Réponse du fil d’actualités mal formée", "Pick a shape, then click the map.": "Choisissez une forme, puis cliquez sur la carte.", "Enter to place the pin, Esc to cancel.": "Enter pour poser l'épingle, Esc pour annuler.", "Click where the pin goes.": "Cliquez à l'endroit où poser l'épingle.", diff --git a/src/i18n/locales/it.json b/src/i18n/locales/it.json index 36f25a0cf..dcaf4855c 100644 --- a/src/i18n/locales/it.json +++ b/src/i18n/locales/it.json @@ -1,4 +1,57 @@ { + "News feed unavailable": "Feed delle notizie non disponibile", + "Disputed: {name}": "Conteso: {name}", + "Administered by {holder} · claimed by {claimant}": "Amministrato da {holder} · rivendicato da {claimant}", + "Self-administered · claimed by {claimant}": "Autogovernato · rivendicato da {claimant}", + "UN-patrolled zone": "Zona pattugliata dall’ONU", + "Claimed by neither neighbour": "Non rivendicato da nessun vicino", + "Video": "Video", + "Photos": "Foto", + "Claimed by {who}": "Secondo {who}", + "Claimed": "Affermazione", + "Not yet confirmed by others": "Non ancora confermato da altri", + "Reported by {side} sources": "Riportato da fonti {side}", + "Reported by {sides}": "Riportato da {sides}", + "{side} sources": "fonti {side}", + "Official": "Ufficiale", + "Reported by both sides": "Riportato da entrambe le parti", + "Independently reported": "Riportato in modo indipendente", + "Single source": "Fonte unica", + "International": "Internazionale", + "Independent": "Indipendente", + "Unattributed": "Non attribuito", + "Outside party": "Parte esterna", + "Ukraine–Russia": "Ucraina–Russia", + "Israel–Gaza–Lebanon": "Israele–Gaza–Libano", + "Iran–Hormuz": "Iran–Hormuz", + "Yemen–Red Sea": "Yemen–Mar Rosso", + "Sudan": "Sudan", + "Sahel": "Sahel", + "Elsewhere": "Altrove", + "Strike": "Attacco", + "Alert": "Allerta", + "Air defence": "Difesa aerea", + "Ground fighting": "Combattimenti a terra", + "Casualties": "Vittime", + "Humanitarian": "Umanitario", + "Disaster": "Disastro", + "Protest": "Protesta", + "Political": "Politica", + "No physical event": "Nessun evento fisico", + "Minor incident": "Incidente minore", + "Significant": "Rilevante", + "Major": "Grave", + "age|now": "ora", + "{minutes} min": "{minutes} min", + "{hours} h": "{hours} h", + "{count} sources": { + "one": "{count} fonte", + "many": "{count} fonti", + "other": "{count} fonti" + }, + "News feed not configured on this server": "Feed delle notizie non configurato su questo server", + "Malformed news hotspots response": "Risposta dei focolai di notizie non valida", + "Malformed news feed response": "Risposta del feed delle notizie non valida", "Pick a shape, then click the map.": "Scegli una forma, poi fai clic sulla mappa.", "Enter to place the pin, Esc to cancel.": "Premi Enter per posizionare il segnaposto, Esc per annullare.", "Click where the pin goes.": "Fai clic dove va il segnaposto.", diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.json index e586716f8..743fcb71c 100644 --- a/src/i18n/locales/ja.json +++ b/src/i18n/locales/ja.json @@ -1,4 +1,55 @@ { + "News feed unavailable": "ニュースフィードを利用できません", + "Disputed: {name}": "係争地: {name}", + "Administered by {holder} · claimed by {claimant}": "{holder}が施政 · {claimant}が領有を主張", + "Self-administered · claimed by {claimant}": "自治 · {claimant}が領有を主張", + "UN-patrolled zone": "国連が巡回する地域", + "Claimed by neither neighbour": "どちらの隣国も領有を主張していない", + "Video": "動画", + "Photos": "写真", + "Claimed by {who}": "{who}の主張", + "Claimed": "主張", + "Not yet confirmed by others": "他からの確認はまだない", + "Reported by {side} sources": "{side}側の情報源が報道", + "Reported by {sides}": "報道: {sides}", + "{side} sources": "{side}側の情報源", + "Official": "公式", + "Reported by both sides": "双方が報道", + "Independently reported": "独立した報道あり", + "Single source": "単一の情報源", + "International": "国際", + "Independent": "独立系", + "Unattributed": "出所不明", + "Outside party": "第三者", + "Ukraine–Russia": "ウクライナ–ロシア", + "Israel–Gaza–Lebanon": "イスラエル–ガザ–レバノン", + "Iran–Hormuz": "イラン–ホルムズ", + "Yemen–Red Sea": "イエメン–紅海", + "Sudan": "スーダン", + "Sahel": "サヘル", + "Elsewhere": "その他の地域", + "Strike": "攻撃", + "Alert": "警報", + "Air defence": "防空", + "Ground fighting": "地上戦", + "Casualties": "死傷者", + "Humanitarian": "人道", + "Disaster": "災害", + "Protest": "抗議", + "Political": "政治", + "No physical event": "物理的な事象なし", + "Minor incident": "小規模な事案", + "Significant": "重大", + "Major": "深刻", + "age|now": "今", + "{minutes} min": "{minutes}分", + "{hours} h": "{hours}時間", + "{count} sources": { + "other": "情報源 {count}件" + }, + "News feed not configured on this server": "このサーバーではニュースフィードが設定されていません", + "Malformed news hotspots response": "ニュースのホットスポット応答の形式が不正です", + "Malformed news feed response": "ニュースフィードの応答の形式が不正です", "Pick a shape, then click the map.": "図形を選んでから、地図をクリックしてください。", "Enter to place the pin, Esc to cancel.": "Enterでピンを配置、Escでキャンセル。", "Click where the pin goes.": "ピンを置く場所をクリックしてください。", diff --git a/src/i18n/locales/pt.json b/src/i18n/locales/pt.json index 13d3fbc85..2068c08b6 100644 --- a/src/i18n/locales/pt.json +++ b/src/i18n/locales/pt.json @@ -1,4 +1,57 @@ { + "News feed unavailable": "Feed de notícias indisponível", + "Disputed: {name}": "Em disputa: {name}", + "Administered by {holder} · claimed by {claimant}": "Administrado por {holder} · reivindicado por {claimant}", + "Self-administered · claimed by {claimant}": "Autogovernado · reivindicado por {claimant}", + "UN-patrolled zone": "Zona patrulhada pela ONU", + "Claimed by neither neighbour": "Nenhum vizinho o reivindica", + "Video": "Vídeo", + "Photos": "Fotos", + "Claimed by {who}": "Segundo {who}", + "Claimed": "Alegação", + "Not yet confirmed by others": "Ainda não confirmado por outros", + "Reported by {side} sources": "Noticiado por fontes de {side}", + "Reported by {sides}": "Noticiado por {sides}", + "{side} sources": "fontes de {side}", + "Official": "Oficial", + "Reported by both sides": "Noticiado por ambos os lados", + "Independently reported": "Noticiado de forma independente", + "Single source": "Fonte única", + "International": "Internacional", + "Independent": "Independente", + "Unattributed": "Sem atribuição", + "Outside party": "Parte externa", + "Ukraine–Russia": "Ucrânia–Rússia", + "Israel–Gaza–Lebanon": "Israel–Gaza–Líbano", + "Iran–Hormuz": "Irã–Ormuz", + "Yemen–Red Sea": "Iêmen–Mar Vermelho", + "Sudan": "Sudão", + "Sahel": "Sahel", + "Elsewhere": "Outros lugares", + "Strike": "Ataque", + "Alert": "Alerta", + "Air defence": "Defesa aérea", + "Ground fighting": "Combates terrestres", + "Casualties": "Vítimas", + "Humanitarian": "Humanitário", + "Disaster": "Desastre", + "Protest": "Protesto", + "Political": "Político", + "No physical event": "Sem evento físico", + "Minor incident": "Incidente menor", + "Significant": "Significativo", + "Major": "Grave", + "age|now": "agora", + "{minutes} min": "{minutes} min", + "{hours} h": "{hours} h", + "{count} sources": { + "one": "{count} fonte", + "many": "{count} fontes", + "other": "{count} fontes" + }, + "News feed not configured on this server": "Feed de notícias não configurado neste servidor", + "Malformed news hotspots response": "Resposta de focos de notícias malformada", + "Malformed news feed response": "Resposta do feed de notícias malformada", "Pick a shape, then click the map.": "Escolha uma forma e clique no mapa.", "Enter to place the pin, Esc to cancel.": "Enter para colocar o marcador, Esc para cancelar.", "Click where the pin goes.": "Clique onde o marcador deve ficar.", diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json index 766af1005..e6df84b68 100644 --- a/src/i18n/locales/ru.json +++ b/src/i18n/locales/ru.json @@ -1,4 +1,58 @@ { + "News feed unavailable": "Лента новостей недоступна", + "Disputed: {name}": "Спорная территория: {name}", + "Administered by {holder} · claimed by {claimant}": "Под управлением: {holder} · претендует: {claimant}", + "Self-administered · claimed by {claimant}": "Самоуправляемая · претендует: {claimant}", + "UN-patrolled zone": "Зона патрулирования ООН", + "Claimed by neither neighbour": "Не претендует ни один сосед", + "Video": "Видео", + "Photos": "Фото", + "Claimed by {who}": "Заявление: {who}", + "Claimed": "Заявление", + "Not yet confirmed by others": "Пока не подтверждено другими", + "Reported by {side} sources": "Сообщают источники {side}", + "Reported by {sides}": "Сообщают: {sides}", + "{side} sources": "источники {side}", + "Official": "Официально", + "Reported by both sides": "Сообщают обе стороны", + "Independently reported": "Подтверждено независимыми источниками", + "Single source": "Один источник", + "International": "Международные", + "Independent": "Независимые", + "Unattributed": "Без атрибуции", + "Outside party": "Внешняя сторона", + "Ukraine–Russia": "Украина–Россия", + "Israel–Gaza–Lebanon": "Израиль–Газа–Ливан", + "Iran–Hormuz": "Иран–Ормуз", + "Yemen–Red Sea": "Йемен–Красное море", + "Sudan": "Судан", + "Sahel": "Сахель", + "Elsewhere": "Другие места", + "Strike": "Удар", + "Alert": "Тревога", + "Air defence": "ПВО", + "Ground fighting": "Наземные бои", + "Casualties": "Жертвы", + "Humanitarian": "Гуманитарное", + "Disaster": "Бедствие", + "Protest": "Протест", + "Political": "Политика", + "No physical event": "Без физического события", + "Minor incident": "Незначительный инцидент", + "Significant": "Значительный", + "Major": "Крупный", + "age|now": "сейчас", + "{minutes} min": "{minutes} мин", + "{hours} h": "{hours} ч", + "{count} sources": { + "one": "{count} источник", + "few": "{count} источника", + "many": "{count} источников", + "other": "{count} источника" + }, + "News feed not configured on this server": "Лента новостей не настроена на этом сервере", + "Malformed news hotspots response": "Некорректный ответ горячих точек новостей", + "Malformed news feed response": "Некорректный ответ ленты новостей", "Flying to Austin, TX...": "Перелёт в Остин, Техас...", "Restoring shared view...": "Восстановление общего вида...", "Initializing systems...": "Инициализация систем...", diff --git a/src/i18n/locales/uk.json b/src/i18n/locales/uk.json index 388ea566d..41f6f1207 100644 --- a/src/i18n/locales/uk.json +++ b/src/i18n/locales/uk.json @@ -1,4 +1,58 @@ { + "News feed unavailable": "Стрічка новин недоступна", + "Disputed: {name}": "Спірна територія: {name}", + "Administered by {holder} · claimed by {claimant}": "Під управлінням: {holder} · претендує: {claimant}", + "Self-administered · claimed by {claimant}": "Самоврядна · претендує: {claimant}", + "UN-patrolled zone": "Зона патрулювання ООН", + "Claimed by neither neighbour": "Не претендує жоден сусід", + "Video": "Відео", + "Photos": "Фото", + "Claimed by {who}": "Заява: {who}", + "Claimed": "Заява", + "Not yet confirmed by others": "Поки не підтверджено іншими", + "Reported by {side} sources": "Повідомляють джерела {side}", + "Reported by {sides}": "Повідомляють: {sides}", + "{side} sources": "джерела {side}", + "Official": "Офіційно", + "Reported by both sides": "Повідомляють обидві сторони", + "Independently reported": "Підтверджено незалежними джерелами", + "Single source": "Одне джерело", + "International": "Міжнародні", + "Independent": "Незалежні", + "Unattributed": "Без атрибуції", + "Outside party": "Зовнішня сторона", + "Ukraine–Russia": "Україна–Росія", + "Israel–Gaza–Lebanon": "Ізраїль–Газа–Ліван", + "Iran–Hormuz": "Іран–Ормуз", + "Yemen–Red Sea": "Ємен–Червоне море", + "Sudan": "Судан", + "Sahel": "Сахель", + "Elsewhere": "Інші місця", + "Strike": "Удар", + "Alert": "Тривога", + "Air defence": "ППО", + "Ground fighting": "Наземні бої", + "Casualties": "Жертви", + "Humanitarian": "Гуманітарне", + "Disaster": "Лихо", + "Protest": "Протест", + "Political": "Політика", + "No physical event": "Без фізичної події", + "Minor incident": "Незначний інцидент", + "Significant": "Значний", + "Major": "Великий", + "age|now": "зараз", + "{minutes} min": "{minutes} хв", + "{hours} h": "{hours} год", + "{count} sources": { + "one": "{count} джерело", + "few": "{count} джерела", + "many": "{count} джерел", + "other": "{count} джерела" + }, + "News feed not configured on this server": "Стрічку новин не налаштовано на цьому сервері", + "Malformed news hotspots response": "Некоректна відповідь гарячих точок новин", + "Malformed news feed response": "Некоректна відповідь стрічки новин", "Pick a shape, then click the map.": "Виберіть фігуру й клацніть на карті.", "Enter to place the pin, Esc to cancel.": "Enter — поставити мітку, Esc — скасувати.", "Click where the pin goes.": "Клацніть там, де має бути мітка.", diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json index 912582289..30a4d8807 100644 --- a/src/i18n/locales/zh-CN.json +++ b/src/i18n/locales/zh-CN.json @@ -1,4 +1,55 @@ { + "News feed unavailable": "新闻源不可用", + "Disputed: {name}": "争议地区:{name}", + "Administered by {holder} · claimed by {claimant}": "由{holder}管辖 · {claimant}主张主权", + "Self-administered · claimed by {claimant}": "自治 · {claimant}主张主权", + "UN-patrolled zone": "联合国巡逻区", + "Claimed by neither neighbour": "两个邻国均未主张", + "Video": "视频", + "Photos": "照片", + "Claimed by {who}": "{who}声称", + "Claimed": "声称", + "Not yet confirmed by others": "尚未获他方证实", + "Reported by {side} sources": "{side}方来源报道", + "Reported by {sides}": "报道来源:{sides}", + "{side} sources": "{side}方来源", + "Official": "官方", + "Reported by both sides": "双方均有报道", + "Independently reported": "有独立来源报道", + "Single source": "单一来源", + "International": "国际", + "Independent": "独立", + "Unattributed": "未注明来源", + "Outside party": "外部方", + "Ukraine–Russia": "乌克兰–俄罗斯", + "Israel–Gaza–Lebanon": "以色列–加沙–黎巴嫩", + "Iran–Hormuz": "伊朗–霍尔木兹", + "Yemen–Red Sea": "也门–红海", + "Sudan": "苏丹", + "Sahel": "萨赫勒", + "Elsewhere": "其他地区", + "Strike": "打击", + "Alert": "警报", + "Air defence": "防空", + "Ground fighting": "地面战斗", + "Casualties": "伤亡", + "Humanitarian": "人道", + "Disaster": "灾害", + "Protest": "抗议", + "Political": "政治", + "No physical event": "无实际事件", + "Minor incident": "轻微事件", + "Significant": "重大", + "Major": "严重", + "age|now": "刚刚", + "{minutes} min": "{minutes} 分钟", + "{hours} h": "{hours} 小时", + "{count} sources": { + "other": "{count} 个来源" + }, + "News feed not configured on this server": "此服务器未配置新闻源", + "Malformed news hotspots response": "新闻热点响应格式错误", + "Malformed news feed response": "新闻源响应格式错误", "Pick a shape, then click the map.": "先选择形状,再在地图上点击。", "Enter to place the pin, Esc to cancel.": "按 Enter 放置图钉,按 Esc 取消。", "Click where the pin goes.": "点击图钉的放置位置。", diff --git a/src/i18n/locales/zh-Hant.json b/src/i18n/locales/zh-Hant.json index 628c71284..e29d0fff2 100644 --- a/src/i18n/locales/zh-Hant.json +++ b/src/i18n/locales/zh-Hant.json @@ -1,4 +1,55 @@ { + "News feed unavailable": "新聞來源無法使用", + "Disputed: {name}": "爭議地區:{name}", + "Administered by {holder} · claimed by {claimant}": "由{holder}管轄 · {claimant}主張主權", + "Self-administered · claimed by {claimant}": "自治 · {claimant}主張主權", + "UN-patrolled zone": "聯合國巡邏區", + "Claimed by neither neighbour": "兩個鄰國均未主張", + "Video": "影片", + "Photos": "照片", + "Claimed by {who}": "{who}聲稱", + "Claimed": "聲稱", + "Not yet confirmed by others": "尚未獲他方證實", + "Reported by {side} sources": "{side}方來源報導", + "Reported by {sides}": "報導來源:{sides}", + "{side} sources": "{side}方來源", + "Official": "官方", + "Reported by both sides": "雙方均有報導", + "Independently reported": "有獨立來源報導", + "Single source": "單一來源", + "International": "國際", + "Independent": "獨立", + "Unattributed": "未註明來源", + "Outside party": "外部方", + "Ukraine–Russia": "烏克蘭–俄羅斯", + "Israel–Gaza–Lebanon": "以色列–加薩–黎巴嫩", + "Iran–Hormuz": "伊朗–荷莫茲", + "Yemen–Red Sea": "葉門–紅海", + "Sudan": "蘇丹", + "Sahel": "薩赫爾", + "Elsewhere": "其他地區", + "Strike": "打擊", + "Alert": "警報", + "Air defence": "防空", + "Ground fighting": "地面戰鬥", + "Casualties": "傷亡", + "Humanitarian": "人道", + "Disaster": "災害", + "Protest": "抗議", + "Political": "政治", + "No physical event": "無實際事件", + "Minor incident": "輕微事件", + "Significant": "重大", + "Major": "嚴重", + "age|now": "剛剛", + "{minutes} min": "{minutes} 分鐘", + "{hours} h": "{hours} 小時", + "{count} sources": { + "other": "{count} 個來源" + }, + "News feed not configured on this server": "此伺服器未設定新聞來源", + "Malformed news hotspots response": "新聞熱點回應格式錯誤", + "Malformed news feed response": "新聞來源回應格式錯誤", "Pick a shape, then click the map.": "先選擇形狀,再在地圖上點擊。", "Enter to place the pin, Esc to cancel.": "按 Enter 放置圖釘,按 Esc 取消。", "Click where the pin goes.": "點擊圖釘的放置位置。", diff --git a/src/i18n/same-as-english.json b/src/i18n/same-as-english.json index 7edaad647..9cc9a667d 100644 --- a/src/i18n/same-as-english.json +++ b/src/i18n/same-as-english.json @@ -85,6 +85,7 @@ "House", "Hybrid", "Indie", + "International", "Ironbow", "Jazz", "LIVE", @@ -129,6 +130,7 @@ "Pin", "Plan", "Pop", + "Protest", "Punk", "RADAR · {units}", "RADIO", @@ -152,6 +154,7 @@ "STD", "SW", "SYNC", + "Sahel", "San Francisco", "Scanlines", "Scope", @@ -160,6 +163,7 @@ "Soul", "Station", "Station {id}", + "Sudan", "T minus {seconds}", "TAGS · {tags}", "TANKER", @@ -171,6 +175,7 @@ "Turboprop", "UPSTREAM", "Upstream HTTP {status}", + "Video", "Vignette", "WHOT/BHOT", "WIND", @@ -295,6 +300,7 @@ "SRC {value}", "SSE", "STD", + "Sahel", "San Francisco", "Sector", "Sonar", @@ -325,6 +331,8 @@ "panel", "view band|GLOBAL", "voice|ERROR", + "{hours} h", + "{minutes} min", "{rate} msg/s", "{speed} kn", "{type} SPD: {speed} HDG: {heading}", @@ -446,6 +454,7 @@ "PROPAGATION", "Paris", "Pause", + "Photos", "Plan", "Pop", "Punk", @@ -466,6 +475,7 @@ "STANDARD", "STATION", "STD", + "Sahel", "San Francisco", "Satellites", "Saturation", @@ -509,6 +519,9 @@ "{count} MSGS", "{count} SOURCES", "{count} messages", + "{count} sources", + "{hours} h", + "{minutes} min", "{n} cyclones", "{n} satellites", "{rate} msg/s", @@ -582,6 +595,7 @@ "Hip-Hop", "House", "Indie", + "Iran–Hormuz", "Ironbow", "Jazz", "KTS", @@ -636,11 +650,13 @@ "STD", "STOP", "SYNC", + "Sahel", "San Francisco", "Scope", "Sentinel-2", "Sonar", "Soul", + "Sudan", "TEMP", "TIMEOUT", "Talk", @@ -657,6 +673,7 @@ "VIEWSHED ON", "VOLUME", "VS", + "Video", "WHOT/BHOT", "Washington DC", "World", @@ -681,6 +698,8 @@ "{count} MSGS", "{count} feeds live", "{count} scenes", + "{hours} h", + "{minutes} min", "{rate} msg/s", "{scene} / {pack}: {status}. File: {path}. {attribution} · {license}", "{source} HTTP {status}", @@ -840,6 +859,7 @@ "SSE", "STATUS", "STATUS · ", + "Sahel", "Sentinel-2", "Sentinel-2 via HLS", "Sonar", @@ -870,6 +890,8 @@ "mph", "nominal", "view band|GLOBAL", + "{hours} h", + "{minutes} min", "{rate} msg/s", "{type} SPD: {speed} HDG: {heading}", "{value} KM", diff --git a/src/layers/news/cards.js b/src/layers/news/cards.js new file mode 100644 index 000000000..75b9932eb --- /dev/null +++ b/src/layers/news/cards.js @@ -0,0 +1,206 @@ +// Event cards on the globe: a picture, the headline in two lines, and "age · +// sources · sides", with the severity colour down the left edge and the +// event's marker as a badge on the picture. Painted on a canvas and handed to +// the world overlay as a thumbnail entry, so the overlay places them, keeps +// them apart and draws their leader to the marker, as it does CCTV cards. +// +// The picture is the publisher's own (hotlinked, never copied, credited on +// the card); until it loads, or without one, the card shows a tile in the +// severity colour with the category icon. + +import { WORLD_OVERLAY_STYLE } from '../../overlays/worldOverlayTokens.js'; +import { NEWS_SEVERITY } from './model.js'; +import { paintMarker } from './sprites.js'; + +/** Card size in CSS pixels. */ +export const CARD_W = 168; +export const CARD_H = 136; +const PAD = 4; +const PIC_H = 84; +const EDGE = 3; +const SCALE = 2; // canvas pixels per CSS pixel +const TITLE_FONT = '600 11px Inter, "Noto Sans Arabic", system-ui, sans-serif'; +const META_FONT = '9px "JetBrains Mono", "Noto Sans Arabic", monospace'; +const CREDIT_FONT = '8px Inter, "Noto Sans Arabic", system-ui, sans-serif'; +const MAX_CARDS = 200; + +const pictures = new Map(); // url → {image, state: 'loading'|'ok'|'failed', waiters} +const cards = new Map(); // key → canvas + +function picture(url, onLoad) { + let entry = pictures.get(url); + if (!entry) { + const image = new Image(); + // No referrer: the publisher sees a plain image request, as from a link preview. + image.referrerPolicy = 'no-referrer'; + image.decoding = 'async'; + entry = { image, state: 'loading', waiters: new Set() }; + pictures.set(url, entry); + image.onload = () => { + entry.state = 'ok'; + for (const done of entry.waiters) done(); + entry.waiters.clear(); + }; + image.onerror = () => { + entry.state = 'failed'; + entry.waiters.clear(); + }; + image.src = url; + } + if (entry.state === 'loading' && onLoad) entry.waiters.add(onLoad); + return entry; +} + +function roundRect(ctx, x, y, w, h, r) { + ctx.beginPath(); + ctx.moveTo(x + r, y); + ctx.arcTo(x + w, y, x + w, y + h, r); + ctx.arcTo(x + w, y + h, x, y + h, r); + ctx.arcTo(x, y + h, x, y, r); + ctx.arcTo(x, y, x + w, y, r); + ctx.closePath(); +} + +/** `text` in at most `lines` lines of `width`, the last cut with an ellipsis. */ +export function wrapLines(ctx, text, width, lines) { + const words = String(text || '') + .split(/\s+/) + .filter(Boolean); + const out = []; + let line = ''; + for (let i = 0; i < words.length; i++) { + const next = line ? `${line} ${words[i]}` : words[i]; + if (ctx.measureText(next).width <= width || !line) { + line = next; + continue; + } + out.push(line); + line = words[i]; + if (out.length === lines - 1) { + line = words.slice(i).join(' '); + break; + } + } + if (line) out.push(line); + const last = out.length - 1; + if (last >= 0 && ctx.measureText(out[last]).width > width) { + let cut = out[last]; + while (cut && ctx.measureText(`${cut}…`).width > width) + cut = cut.slice(0, -1); + out[last] = `${cut.trimEnd()}…`; + } + return out.slice(0, lines); +} + +/** Cover-fit an image into a box. */ +function drawCover(ctx, image, x, y, w, h) { + const iw = image.naturalWidth || image.width; + const ih = image.naturalHeight || image.height; + if (!iw || !ih) return; + const s = Math.max(w / iw, h / ih); + const sw = w / s; + const sh = h / s; + ctx.drawImage(image, (iw - sw) / 2, (ih - sh) / 2, sw, sh, x, y, w, h); +} + +function paint(canvas, view, look, pic) { + const ctx = canvas.getContext('2d'); + ctx.setTransform(SCALE, 0, 0, SCALE, 0, 0); + ctx.clearRect(0, 0, CARD_W, CARD_H); + const color = (NEWS_SEVERITY[look.severity] || NEWS_SEVERITY[0]).color; + + roundRect(ctx, 0.5, 0.5, CARD_W - 1, CARD_H - 1, WORLD_OVERLAY_STYLE.radius); + ctx.fillStyle = WORLD_OVERLAY_STYLE.selectedBackground; + ctx.fill(); + ctx.strokeStyle = WORLD_OVERLAY_STYLE.border; + ctx.lineWidth = 1; + ctx.stroke(); + // Severity down the left edge, where Breaking marks a Live report. + ctx.save(); + roundRect(ctx, 0.5, 0.5, CARD_W - 1, CARD_H - 1, WORLD_OVERLAY_STYLE.radius); + ctx.clip(); + ctx.fillStyle = color; + ctx.fillRect(0, 0, EDGE, CARD_H); + ctx.restore(); + + const px = PAD + EDGE; + const pw = CARD_W - px - PAD; + ctx.save(); + roundRect(ctx, px, PAD, pw, PIC_H, 3); + ctx.clip(); + if (pic?.state === 'ok') { + try { + drawCover(ctx, pic.image, px, PAD, pw, PIC_H); + } catch { + pic.state = 'failed'; + } + } + if (pic?.state !== 'ok') { + // No picture: a tile in the severity colour with the category icon. + const g = ctx.createLinearGradient(px, PAD, px + pw, PAD + PIC_H); + g.addColorStop(0, WORLD_OVERLAY_STYLE.background); + g.addColorStop(1, color); + ctx.fillStyle = g; + ctx.globalAlpha = 0.55; + ctx.fillRect(px, PAD, pw, PIC_H); + ctx.globalAlpha = 1; + paintMarker(ctx, look, px + pw / 2, PAD + PIC_H / 2, 34); + } + ctx.restore(); + // The event's marker as a badge, so the card reads with the map. + if (pic?.state === 'ok') paintMarker(ctx, look, px + 13, PAD + 13, 18); + // The picture's publisher, always named on it. + if (pic?.state === 'ok' && view.credit) { + ctx.font = CREDIT_FONT; + const w = Math.min(pw - 30, ctx.measureText(view.credit).width + 8); + ctx.fillStyle = 'rgba(0, 0, 0, 0.6)'; + ctx.fillRect(px + pw - w, PAD + PIC_H - 12, w, 12); + ctx.fillStyle = WORLD_OVERLAY_STYLE.title; + ctx.textBaseline = 'middle'; + ctx.fillText( + wrapLines(ctx, view.credit, w - 8, 1)[0] || '', + px + pw - w + 4, + PAD + PIC_H - 6, + ); + } + + ctx.textBaseline = 'alphabetic'; + ctx.fillStyle = WORLD_OVERLAY_STYLE.title; + ctx.font = TITLE_FONT; + wrapLines(ctx, view.title, pw, 2).forEach((line, i) => + ctx.fillText(line, px, PAD + PIC_H + 14 + i * 13), + ); + ctx.fillStyle = WORLD_OVERLAY_STYLE.detail; + ctx.font = META_FONT; + ctx.fillText(wrapLines(ctx, view.meta, pw, 1)[0] || '', px, CARD_H - PAD - 2); +} + +/** + * The canvas of an event's card. `onChange` runs when its picture arrives and + * the canvas has been repainted (ask the scene for a frame). + * @returns {HTMLCanvasElement|null} null where there is no canvas + */ +export function eventCard(id, view, look, onChange) { + const key = `${id}|${look.severity}|${look.category}|${look.rim}|${view.image || ''}|${view.title}|${view.meta}`; + if (cards.has(key)) return cards.get(key); + const canvas = globalThis.document?.createElement?.('canvas'); + if ( + !canvas?.getContext?.('2d') || + typeof globalThis.Path2D !== 'function' || + typeof globalThis.Image !== 'function' + ) + return null; + canvas.width = CARD_W * SCALE; + canvas.height = CARD_H * SCALE; + const pic = view.image + ? picture(view.image, () => { + paint(canvas, view, look, pic); + onChange?.(); + }) + : null; + paint(canvas, view, look, pic); + // Old cards go once there are many; the newest keys win. + if (cards.size >= MAX_CARDS) cards.delete(cards.keys().next().value); + cards.set(key, canvas); + return canvas; +} diff --git a/src/layers/news/model.js b/src/layers/news/model.js new file mode 100644 index 000000000..41fce5ab4 --- /dev/null +++ b/src/layers/news/model.js @@ -0,0 +1,643 @@ +// Pure presentation model for the news layer: severity, category glyphs, +// attestation, marker looks and placement, the feed's filters and paging, and +// the event cards the News panel and the globe show. No Cesium, no DOM. + +import { getLocale, msg, t, tn } from '../../i18n/index.js'; + +export const NEWS_LAYER_ID = 'news'; +export const NEWS_OVERLAY_SOURCE_ID = 'news'; +export const NEWS_PICK_PREFIX = 'news:'; +export const NEWS_FEED_PAGE = 60; +export const NEWS_MAP_LIMIT = 500; +/** News is real time only: nothing older than a day is shown anywhere. */ +export const NEWS_WINDOW_MS = 24 * 3_600_000; +// Above this camera height the layer shows one beacon per hotspot; below it +// (or once a hotspot is chosen) the outlines and individual reports. +export const NEWS_DETAIL_MAX_HEIGHT_M = 2_500_000; +// "In view": reports near the view centre, only once the camera is low enough +// for "here" to mean a region, read again when it settles in a new cell. +export const NEWS_IN_VIEW_MAX_HEIGHT_M = 3_000_000; +export const NEWS_IN_VIEW_RADIUS_KM = 500; +export const NEWS_IN_VIEW_LIMIT = 12; +export const NEWS_SETTLE_MS = 800; +export const NEWS_CELL_DEG = 0.5; +/** A feed card's click flies the camera to this height over the event. */ +export const NEWS_FOCUS_HEIGHT_M = 150_000; +// Minor news (a broad outlet's prices, sport, health) is left out unless asked for. +export const NEWS_RELEVANT = 'core,related'; + +const SOURCE_LABEL = msg('Source'); +const DISPUTED = msg('Disputed: {name}'); +const DISPUTE_TEXT = { + held: msg('Administered by {holder} · claimed by {claimant}'), + self: msg('Self-administered · claimed by {claimant}'), + un: msg('UN-patrolled zone'), + unclaimed: msg('Claimed by neither neighbour'), +}; +const MEDIA_LABELS = { video: msg('Video'), photo: msg('Photos') }; +const CLAIMED_BY = msg('Claimed by {who}'); +const CLAIMED = msg('Claimed'); +const UNCONFIRMED = msg('Not yet confirmed by others'); +const REPORTED_BY_SIDE = msg('Reported by {side} sources'); +const REPORTED_BY_SIDES = msg('Reported by {sides}'); +const SIDE_SOURCES = msg('{side} sources'); +const OFFICIAL = msg('Official'); +const OFFICIAL_AFFILIATIONS = new Set(['military', 'state']); +const ATTESTATION = { + 'both-sides': msg('Reported by both sides'), + independent: msg('Independently reported'), + single: msg('Single source'), +}; +const NEUTRAL_SIDES = Object.freeze({ + intl: msg('International'), + independent: msg('Independent'), + unknown: msg('Unattributed'), + external: msg('Outside party'), +}); + +/** + * Short chip names for the curated hotspots; the API's own English name is + * the fallback for any other. + */ +export const NEWS_HOTSPOT_LABELS = Object.freeze({ + 'ua-ru-war': msg('Ukraine–Russia'), + 'israel-gaza-lebanon': msg('Israel–Gaza–Lebanon'), + 'iran-hormuz': msg('Iran–Hormuz'), + yemen: msg('Yemen–Red Sea'), + 'sudan-war': msg('Sudan'), + sahel: msg('Sahel'), + elsewhere: msg('Elsewhere'), +}); + +/** A hotspot's chip label in the interface language. */ +export function hotspotLabel(hotspot) { + const key = NEWS_HOTSPOT_LABELS[hotspot?.id]; + if (key) return t(key); + return hotspot?.catchAll ? t(NEWS_HOTSPOT_LABELS.elsewhere) : hotspot?.name; +} + +/** A country's name in the interface language, from its ISO code. */ +export function countryName(code) { + if (!code) return ''; + try { + return ( + new Intl.DisplayNames([getLocale(), 'en'], { type: 'region' }).of(code) || + code + ); + } catch { + return code; + } +} + +/** Label for a disputed area: its name, who administers it, who claims it. */ +export function disputedLabel(area) { + return { + title: t(DISPUTED, { name: area.name }), + detail: t(DISPUTE_TEXT[area.kind] || DISPUTE_TEXT.held, { + holder: countryName(area.heldBy), + claimant: countryName(area.claimedBy), + }), + }; +} + +// A category is told by its icon (a 16-unit SVG path, filled or stroked). On +// the map and in the feed colour is severity (NEWS_SEVERITY), never the type +// of event or a side. +export const NEWS_CATEGORIES = Object.freeze({ + strike: { + label: msg('Strike'), + icon: 'M8 0.8 L9.6 5.2 L14.2 3.6 L11.2 7.6 L15.2 10.6 L10.3 10.6 L8 15.2 L5.7 10.6 L0.8 10.6 L4.8 7.6 L1.8 3.6 L6.4 5.2 Z', + solid: true, + }, + // A threat on its way (a drone's course, an air-raid alert): nothing has + // hit yet. Not a physical event, so never a picture card. + alert: { + label: msg('Alert'), + icon: 'M1.5 8 H11.5 M8 4.5 L11.5 8 L8 11.5 M14.5 3.5 V12.5', + }, + 'air-defence': { + label: msg('Air defence'), + icon: 'M8 1.5 L13.5 3.5 V8 C13.5 11.3 10.8 13.4 8 14.6 C5.2 13.4 2.5 11.3 2.5 8 V3.5 Z M8 4.5 V11', + }, + ground: { + label: msg('Ground fighting'), + icon: 'M3 13 L12 4 M8.5 3.5 H12.5 V7.5 M13 13 L4 4 M3.5 7.5 V3.5 H7.5', + }, + casualties: { + label: msg('Casualties'), + icon: 'M6.2 2 H9.8 V6.2 H14 V9.8 H9.8 V14 H6.2 V9.8 H2 V6.2 H6.2 Z', + solid: true, + }, + humanitarian: { + label: msg('Humanitarian'), + icon: 'M8 2.5 L14.5 13.5 H1.5 Z M8 2.5 V13.5', + }, + infrastructure: { + label: msg('Infrastructure'), + icon: 'M9.2 1 L3.2 9 H7.6 L6.6 15 L12.8 6.8 H8.4 Z', + solid: true, + }, + disaster: { + label: msg('Disaster'), + icon: 'M1.5 6.5 C3.5 4.5 5.5 4.5 7.5 6.5 S11.5 8.5 14.5 6.5 M1.5 10.5 C3.5 8.5 5.5 8.5 7.5 10.5 S11.5 12.5 14.5 10.5', + }, + protest: { + label: msg('Protest'), + icon: 'M2.5 6.2 V9.8 H5 L12.5 13.2 V2.8 L5 6.2 Z', + }, + political: { + label: msg('Political'), + icon: 'M2 14 H14 M2.5 5.5 H13.5 M8 1.8 L14 4.8 H2 Z M4.2 6.5 V12 M8 6.5 V12 M11.8 6.5 V12', + }, + other: { + label: msg('Other'), + icon: 'M8 4.5 A3.5 3.5 0 1 0 8.01 4.5 Z', + solid: true, + }, +}); + +// Severity 0–3. Lightness falls as severity rises, so the ramp still reads +// under colour blindness and in greyscale. +export const NEWS_SEVERITY = Object.freeze([ + { label: msg('No physical event'), color: '#8a9aa8' }, + { label: msg('Minor incident'), color: '#f2d64b' }, + { label: msg('Significant'), color: '#f28c28' }, + { label: msg('Major'), color: '#d7301f' }, +]); +/** The feed's default floor: significant and major events. */ +export const NEWS_DEFAULT_MIN_SEVERITY = 2; +const PHYSICAL = new Set([ + 'strike', + 'air-defence', + 'ground', + 'casualties', + 'infrastructure', + 'disaster', +]); + +export const categoryStyle = (category) => + NEWS_CATEGORIES[category] || NEWS_CATEGORIES.other; +export const categoryLabel = (category) => t(categoryStyle(category).label); +/** Party codes (UA, RU, IL…) are shown as-is; neutral sides are translated. */ +export const sideLabel = (side) => + Object.hasOwn(NEUTRAL_SIDES, side) ? t(NEUTRAL_SIDES[side]) : side; + +/** + * A report's severity, 0–3: the server's (the local model's reading, else + * its rules, raised to its event's), or a fallback from the category. + */ +export function reportSeverity(report) { + const own = Number.isInteger(report?.severity) ? report.severity : null; + const event = Number.isInteger(report?.event?.severity) + ? report.event.severity + : null; + if (own === null && event === null) + return PHYSICAL.has(report?.category) ? 1 : 0; + return Math.max(own ?? 0, event ?? 0); +} +export const severityStyle = (report) => NEWS_SEVERITY[reportSeverity(report)]; +export const severityLabel = (report) => t(severityStyle(report).label); + +/** When a report (or its event) was last heard of, in ms; NaN when unknown. */ +const lastHeard = (report) => + Date.parse(report?.event?.lastAt || report?.publishedAt || ''); + +/** Whether a report is from the last 24 hours (the only news shown). */ +export function withinNewsWindow(report, now = Date.now()) { + const at = Date.parse(report?.publishedAt || ''); + return Number.isFinite(at) && now - at <= NEWS_WINDOW_MS; +} + +/** + * How a report or its event is attested, as a chip: `claimed` (someone's + * claim, named where known), `confirmed` (both sides, or an independent + * source), `side` (one party's own press), `single` (one report), or null. + */ +export function attestation(report) { + const event = report?.event; + const status = event?.status || (report?.claim ? 'claimed' : null); + if (status === 'claimed') { + const who = event?.claimedBy || report?.claim?.by; + return { + kind: 'claimed', + label: who ? t(CLAIMED_BY, { who }) : t(CLAIMED), + }; + } + if (status === 'both-sides' || status === 'independent') + return { kind: 'confirmed', label: t(ATTESTATION[status]) }; + if (status === 'side' && event.reportedSide) + return { + kind: 'side', + label: t(REPORTED_BY_SIDE, { side: sideLabel(event.reportedSide) }), + }; + if (status === 'single') + return { kind: 'single', label: t(ATTESTATION.single) }; + return null; +} + +/** + * The attestation chip under a report. An official channel's own post is + * already marked Official: "Claimed by" itself would read as doubt about an + * alert. It says only that nobody else has reported it yet, and nothing for + * an alert, which is the channel's own notice. + */ +function ownClaimChip(report) { + const chip = attestation(report); + if ( + chip?.kind !== 'claimed' || + !OFFICIAL_AFFILIATIONS.has(report.affiliation) + ) + return chip; + const who = report.event?.claimedBy || report.claim?.by; + if (who && who !== report.sourceName && who !== report.publisher) return chip; + return report.category === 'alert' + ? null + : { kind: 'claimed', label: t(UNCONFIRMED) }; +} + +// The map card is a label, not a reader: long headlines are cut. +export const NEWS_CARD_TITLE_MAX = 90; + +/** A headline cut at a word to fit `max` characters. */ +export function shortTitle(title, max = NEWS_CARD_TITLE_MAX) { + const text = String(title || ''); + if (text.length <= max) return text; + const cut = text.slice(0, max - 1); + const word = cut.lastIndexOf(' '); + return `${word > max * 0.6 ? cut.slice(0, word) : cut}…`; +} + +/** The media a post carries ("Video", "Photos"), translated. */ +export function mediaLabels(report) { + return (report?.media || []) + .map((m) => (MEDIA_LABELS[m] ? t(MEDIA_LABELS[m]) : '')) + .filter(Boolean); +} + +/** + * How long ago, in few words: "now" under a minute, "N min" under an hour, + * "N h" under a day. Older is never shown; it reads + * "24 h". + */ +export function ageWords(at, now = Date.now()) { + const minutes = Math.max(0, Math.floor((now - Date.parse(at)) / 60_000)); + if (!Number.isFinite(minutes)) return ''; + if (minutes < 1) return t('now', { context: 'age' }); + if (minutes < 60) return t('{minutes} min', { minutes }); + return t('{hours} h', { hours: Math.min(24, Math.floor(minutes / 60)) }); +} + +/** + * How a report's marker looks: fill = severity, icon = category, rim = + * attestation (`confirmed` solid, `claimed` dashed, else thin), size = + * sources, opacity = age (fading to 45 % over a day). + */ +export function markerStyle(report, now = Date.now()) { + const kind = attestation(report)?.kind; + const at = lastHeard(report); + const hours = Number.isFinite(at) ? Math.max(0, (now - at) / 3_600_000) : 0; + return { + category: Object.hasOwn(NEWS_CATEGORIES, report?.category) + ? report.category + : 'other', + severity: reportSeverity(report), + rim: kind === 'confirmed' || kind === 'claimed' ? kind : 'thin', + size: eventPixelSize(report?.event?.size), + alpha: Math.max(0.45, 1 - (0.55 * Math.min(hours, 24)) / 24), + }; +} + +function hash(text) { + let h = 2166136261; + for (let i = 0; i < text.length; i++) { + h ^= text.charCodeAt(i); + h = Math.imul(h, 16777619); + } + return h >>> 0; +} + +/** + * Trend glyph for a hotspot: ▲/▼ when the last 24 h differ from the 24 h + * before by more than a fifth, nothing when flat or without a prior day. + */ +export function hotspotTrend(last24h, prev24h) { + if (!(prev24h > 0)) return ''; + if (last24h > prev24h * 1.2) return '▲'; + if (last24h < prev24h * 0.8) return '▼'; + return ''; +} + +/** Beacon size in pixels: grows with the square root of daily activity. */ +export const beaconPixelSize = (last24h) => + Math.round(Math.min(26, 10 + Math.sqrt(Math.max(0, last24h)) * 1.4)); + +/** Marker size for an event: grows with the number of distinct sources. */ +export function eventPixelSize(sources = 1) { + return Math.round( + Math.min(30, 16 + 3.5 * Math.log2(Math.max(1, Number(sources) || 1))), + ); +} + +// An event several sources report within the last few hours gets a halo. +export const NEWS_PRESSING_SOURCES = 5; +const PRESSING_MS = 3 * 3_600_000; + +/** Whether an event is fresh and widely reported, or fresh and major. */ +export function isPressing(report, now = Date.now()) { + const event = report?.event; + const fresh = now - lastHeard(report) <= PRESSING_MS; + return Boolean( + fresh && + ((event && event.size >= NEWS_PRESSING_SOURCES) || + reportSeverity(report) === 3), + ); +} + +// The big events stand as picture cards over their marker: several +// sources, and major or pressing. +export const NEWS_CARD_LIMIT = 10; +export const NEWS_CARD_MIN_SOURCES = 2; + +/** Whether an event gets a card on the map: physical events only, not statements. */ +export function isCardEvent(report, now = Date.now()) { + return Boolean( + report?.event?.size >= NEWS_CARD_MIN_SOURCES && + PHYSICAL.has(report.category) && + (reportSeverity(report) === 3 || isPressing(report, now)), + ); +} + +/** The card events among `reports`, most severe, most reported and newest first. */ +export function cardEvents(reports, now = Date.now(), limit = NEWS_CARD_LIMIT) { + return reports + .filter((r) => r.pins?.length && isCardEvent(r, now)) + .sort( + (a, b) => + reportSeverity(b) - reportSeverity(a) || + b.event.size - a.event.size || + (b.event.lastAt || '').localeCompare(a.event.lastAt || ''), + ) + .slice(0, limit); +} + +/** The distinct sides an event was reported by, lead first, translated. */ +function eventSides(report) { + const sides = (report?.event?.sides || []).map((s) => s.side); + return [...new Set(sides.length ? sides : [report?.side].filter(Boolean))]; +} + +/** "Reported by UA sources · RU sources", or '' when no side is known. */ +export function sidesLine(report) { + const sides = eventSides(report).filter((side) => side !== 'unknown'); + if (!sides.length) return ''; + if (sides.length === 1) + return t(REPORTED_BY_SIDE, { side: sideLabel(sides[0]) }); + return t(REPORTED_BY_SIDES, { + sides: sides + .map((side) => t(SIDE_SOURCES, { side: sideLabel(side) })) + .join(' · '), + }); +} + +/** The event's picture for a card: two or more sources, and the publisher named. */ +export function eventPicture(report) { + const event = report?.event; + if (!event?.image || event.size < NEWS_CARD_MIN_SOURCES) return null; + return { url: event.image.url, credit: event.image.publisher || '' }; +} + +/** What an event's picture card on the globe shows. */ +export function cardView(report, now = Date.now()) { + const event = report.event; + const sides = eventSides(report).map(sideLabel); + const picture = eventPicture(report); + return { + title: report.titleEn || report.title, + meta: [ + ageWords(event?.lastAt || report.publishedAt, now), + tn(event?.size || 1, '{count} source', '{count} sources'), + sides.slice(0, 3).join(', ') + (sides.length > 3 ? '…' : ''), + ] + .filter(Boolean) + .join(' · '), + image: picture?.url || null, + credit: picture?.credit || '', + }; +} + +/** "Source: host ↗" line for a report's card; the card opens the article. */ +export function sourceLinkLabel(url) { + let host = ''; + try { + host = new URL(url).hostname.replace(/^www\./, ''); + } catch { + return ''; + } + return `${t(SOURCE_LABEL)}: ${host} ↗`; +} + +/** The places a report is pinned at, joined, or null. */ +function placeLine(report) { + return ( + (report.pins?.length ? report.pins : [report.geo]) + .map((p) => p?.place) + .filter(Boolean) + .join(' · ') || null + ); +} + +/** + * One event card in the News panel: picture, + * headline, a mono meta line (severity, category, place, sources, age), the + * sides line, then attestation and media chips. Labels and colours are + * resolved here so the panel imports no layer code. + */ +export function feedCardView(report, now = Date.now()) { + const severity = reportSeverity(report); + const style = categoryStyle(report.category); + const size = report.event?.size || 1; + const translated = Boolean(report.titleEn && report.titleEn !== report.title); + return { + id: report.id, + url: report.url, + title: translated ? report.titleEn : report.title, + // The local model's English headline over a post in another language: + // the original stays beside it. + original: translated ? report.title : null, + snippet: report.snippet, + severity, + severityLabel: t(NEWS_SEVERITY[severity].label), + color: NEWS_SEVERITY[severity].color, + icon: style.icon, + solid: Boolean(style.solid), + category: categoryLabel(report.category), + place: placeLine(report), + placedByModel: Boolean(report.geo?.byModel), + mappable: Boolean(report.pins?.length), + sources: tn(size, '{count} source', '{count} sources'), + age: ageWords(report.event?.lastAt || report.publishedAt, now), + publisher: report.publisher, + sides: sidesLine(report), + sourceLink: sourceLinkLabel(report.url), + picture: eventPicture(report), + chips: [ + // An official channel speaking for itself (a ministry, the armed + // forces, a press service), not an outlet that quotes one. + OFFICIAL_AFFILIATIONS.has(report.affiliation) + ? { kind: 'official', label: t(OFFICIAL) } + : null, + ownClaimChip(report), + ...mediaLabels(report).map((label) => ({ kind: 'media', label })), + ].filter(Boolean), + // The event's first report from each other side, under the lead. + others: (report.event?.sides || []).slice(1).map((s) => ({ + side: sideLabel(s.side), + publisher: s.publisher, + title: s.title, + url: s.url, + })), + }; +} + +/** + * Marker position for a report. Many reports name the same city and would + * stack on one centroid, so each is spread on a small deterministic ring + * (about 1.5 km for a place, 6 km for a region, 28 km for a country) to stay + * individually clickable. The spread is display-only; cards show the place. + */ +export function reportMarkerPosition(report, pin = 0) { + const { lat, lon, precision } = report.pins?.[pin] || report.geo; + const h = hash(pin ? `${report.id}~${pin}` : report.id); + const angle = ((h % 3600) / 3600) * 2 * Math.PI; + const radiusDeg = + (precision === 'country' ? 0.25 : precision === 'region' ? 0.055 : 0.014) * + (0.35 + ((h >>> 12) % 65) / 100); + return { + lat: lat + radiusDeg * Math.sin(angle), + lon: lon + (radiusDeg * Math.cos(angle)) / Math.cos((lat * Math.PI) / 180), + }; +} + +/** + * Merge a page into the feed, newest first, one row per report id. + * `mode` 'head' refreshes the top and keeps the older cursor; 'append' adds an + * older page and takes its cursor; 'replace' starts over. + */ +export function mergeFeedPage(feed, page, mode) { + const byId = new Map(); + const items = + mode === 'replace' + ? page.reports + : mode === 'append' + ? [...feed.items, ...page.reports] + : [...page.reports, ...feed.items]; + for (const item of items) if (!byId.has(item.id)) byId.set(item.id, item); + return { + items: [...byId.values()].sort((a, b) => + b.publishedAt.localeCompare(a.publishedAt), + ), + nextBefore: + mode === 'head' && feed.items.length ? feed.nextBefore : page.nextBefore, + }; +} + +/** Normalised filters; anything unknown falls back to its default. */ +export function normalizeFilters(next = {}, hotspots = [], previous = {}) { + const merged = { ...previous, ...next }; + const hotspot = hotspots.some((h) => h.id === merged.hotspot) + ? merged.hotspot + : 'all'; + const category = Object.hasOwn(NEWS_CATEGORIES, merged.category) + ? merged.category + : 'all'; + const minSeverity = + Number.isInteger(merged.minSeverity) && + merged.minSeverity >= 0 && + merged.minSeverity <= 3 + ? merged.minSeverity + : NEWS_DEFAULT_MIN_SEVERITY; + return { + hotspot, + category, + minSeverity, + includeMinor: merged.includeMinor === true, + // Event cards on the map; off leaves only the clicked event's card. + cards: merged.cards !== false, + }; +} + +/** Whether a report passes the filters the server does not apply. */ +export function passesFilters(report, filters, now = Date.now()) { + return ( + withinNewsWindow(report, now) && + reportSeverity(report) >= filters.minSeverity + ); +} + +/** Whether a report belongs on the map under the current filters. */ +export function visibleOnMap(report, filters, now = Date.now()) { + return ( + (filters.hotspot === 'all' || + (report.hotspotIds || [report.hotspotId]).includes(filters.hotspot)) && + (filters.category === 'all' || report.category === filters.category) && + passesFilters(report, filters, now) + ); +} + +/** API query for the feed under the current filters: always the last 24 h. */ +export function feedQueryFor(filters, extra = {}) { + return { + events: true, + today: true, + relevance: filters.includeMinor ? '' : NEWS_RELEVANT, + hotspot: filters.hotspot, + category: filters.category === 'all' ? '' : filters.category, + limit: NEWS_FEED_PAGE, + ...extra, + }; +} + +/** The half-degree cell a point lies in, as a key. */ +export function viewCell({ lat, lon }) { + return `${Math.floor(lat / NEWS_CELL_DEG)}:${Math.floor(lon / NEWS_CELL_DEG)}`; +} + +/** Great-circle distance in kilometres. */ +export function distanceKm(a, b) { + const rad = Math.PI / 180; + const dLat = (b.lat - a.lat) * rad; + const dLon = (b.lon - a.lon) * rad; + const s = + Math.sin(dLat / 2) ** 2 + + Math.cos(a.lat * rad) * Math.cos(b.lat * rad) * Math.sin(dLon / 2) ** 2; + return 2 * 6371 * Math.asin(Math.min(1, Math.sqrt(s))); +} + +/** + * The reports near `centre` (any pin within NEWS_IN_VIEW_RADIUS_KM) that pass + * the filters, most severe and newest first. + */ +export function reportsInView( + reports, + centre, + filters, + now = Date.now(), + limit = NEWS_IN_VIEW_LIMIT, +) { + if (!centre) return []; + return reports + .filter( + (r) => + passesFilters(r, filters, now) && + (filters.category === 'all' || r.category === filters.category) && + r.pins?.some( + (pin) => distanceKm(pin, centre) <= NEWS_IN_VIEW_RADIUS_KM, + ), + ) + .sort( + (a, b) => + reportSeverity(b) - reportSeverity(a) || + b.publishedAt.localeCompare(a.publishedAt), + ) + .slice(0, limit); +} diff --git a/src/layers/news/model.test.mjs b/src/layers/news/model.test.mjs new file mode 100644 index 000000000..39492cc41 --- /dev/null +++ b/src/layers/news/model.test.mjs @@ -0,0 +1,444 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { + normalizeFeedPayload, + normalizeHotspotsPayload, + normalizeOutlinePayload, +} from './records.js'; +import { + NEWS_IN_VIEW_RADIUS_KM, + ageWords, + beaconPixelSize, + cardEvents, + cardView, + distanceKm, + eventPixelSize, + feedCardView, + feedQueryFor, + hotspotLabel, + hotspotTrend, + isPressing, + markerStyle, + mergeFeedPage, + normalizeFilters, + passesFilters, + reportMarkerPosition, + reportSeverity, + reportsInView, + sidesLine, + sourceLinkLabel, + viewCell, + visibleOnMap, + withinNewsWindow, +} from './model.js'; +import { newsFeedQuery } from './source.js'; + +const NOW = Date.parse('2026-10-28T10:00:00Z'); +const report = (id, publishedAt, extra = {}) => ({ + id, + title: `Report ${id}`, + url: `https://example.com/${id}`, + publishedAt, + publisher: 'Example', + side: 'UA', + category: 'strike', + hotspotIds: ['ua'], + geo: { + lat: 50, + lon: 36, + place: 'Kharkiv', + precision: 'city', + mappable: true, + }, + pins: [ + { lat: 50, lon: 36, place: 'Kharkiv', precision: 'city', mappable: true }, + ], + ...extra, +}); +const event = (extra = {}) => ({ + status: 'both-sides', + size: 6, + severity: 3, + lastAt: '2026-10-28T09:30:00Z', + sides: [ + { side: 'UA', title: 'a', url: 'https://a.test/', publisher: 'A' }, + { side: 'RU', title: 'b', url: 'https://b.test/', publisher: 'B' }, + ], + image: { url: 'https://a.test/p.jpg', publisher: 'A' }, + ...extra, +}); + +test('payloads are validated record by record; empty and malformed payloads', () => { + const hotspots = normalizeHotspotsPayload({ + hotspots: [ + { + id: 'ua', + name: 'UA', + bbox: [22, 44, 42, 56], + parties: ['UA', 'RU', ''], + counts: { last24h: 3 }, + }, + { id: 'bad', name: 'Bad', bbox: [42, 44, 22, 56] }, + { id: '../x', name: 'Bad id', bbox: [22, 44, 42, 56] }, + ], + ingest: { lastRunAt: '2026-10-28T10:00:00Z' }, + }); + assert.deepEqual( + hotspots.hotspots.map((h) => [h.id, h.parties, h.last24h]), + [['ua', ['UA', 'RU'], 3]], + ); + assert.equal(hotspots.lastRunAt, '2026-10-28T10:00:00.000Z'); + assert.equal(normalizeHotspotsPayload({}), null); + assert.equal(normalizeHotspotsPayload(null), null); + assert.deepEqual(normalizeHotspotsPayload({ hotspots: [] }).hotspots, []); + + const feed = normalizeFeedPayload({ + reports: [ + { + id: 'r_1', + title: ' Strike on Kharkiv ', + url: 'https://x.test/a', + publishedAt: '2026-10-28T09:00:00Z', + geo: { lat: 50, lon: 36, mappable: true }, + media: ['video', 'video', 'audio'], + event: { size: 3, image: { url: 'http://x.test/p.jpg' } }, + }, + { + id: 'r_2', + title: 'Bad link', + url: 'javascript:alert(1)', + publishedAt: '2026-10-28T09:00:00Z', + }, + { + id: 'r_3', + title: 'Bad geo', + url: 'https://user:pw@x.test/c', + publishedAt: '2026-10-28T09:00:00Z', + }, + { + id: 'r_4', + title: 'Off the globe', + url: 'https://x.test/d', + publishedAt: '2026-10-28T09:00:00Z', + geo: { lat: 200, lon: 36 }, + }, + ], + nextBefore: '2026-10-28T08:00:00Z', + }); + assert.deepEqual( + feed.reports.map((r) => [r.id, r.title, Boolean(r.geo), r.pins.length]), + [ + ['r_1', 'Strike on Kharkiv', true, 1], + ['r_4', 'Off the globe', false, 0], + ], + ); + assert.deepEqual(feed.reports[0].media, ['video']); + // A picture must be HTTPS on the publisher's site. + assert.equal(feed.reports[0].event.image, null); + assert.equal(feed.nextBefore, '2026-10-28T08:00:00.000Z'); + assert.equal(normalizeFeedPayload({ reports: 'x' }), null); + assert.deepEqual(normalizeFeedPayload({ reports: [] }), { + reports: [], + nextBefore: null, + }); +}); + +test('outlines keep valid rings, borders and named disputed areas', () => { + const ring = [ + [30, 45], + [31, 45], + [31, 46], + ]; + const outline = normalizeOutlinePayload({ + polygons: [{ outer: ring, holes: [[[0, 0]]] }, { outer: [[1, 2]] }], + borders: [ring, 'x'], + disputed: [ + { + name: 'Crimea', + kind: 'held', + heldBy: 'RU', + claimedBy: 'UA', + rings: [ring], + }, + { name: 'No rings', rings: [] }, + { name: 'Odd kind', kind: 'zzz', heldBy: 'nope', rings: [ring] }, + ], + }); + assert.equal(outline.polygons.length, 1); + assert.deepEqual(outline.polygons[0].holes, []); + assert.equal(outline.borders.length, 1); + assert.deepEqual( + outline.disputed.map((d) => [d.name, d.kind, d.heldBy]), + [ + ['Crimea', 'held', 'RU'], + ['Odd kind', 'held', null], + ], + ); + assert.deepEqual(normalizeOutlinePayload(null), { + polygons: [], + borders: [], + disputed: [], + }); +}); + +test('feed pages merge newest first without duplicates', () => { + const a = report('a', '2026-10-28T10:00:00Z'); + const b = report('b', '2026-10-28T09:00:00Z'); + const c = report('c', '2026-10-28T08:00:00Z'); + let feed = mergeFeedPage( + { items: [] }, + { reports: [a, b], nextBefore: 'B' }, + 'replace', + ); + assert.deepEqual( + [feed.items.map((r) => r.id), feed.nextBefore], + [['a', 'b'], 'B'], + ); + feed = mergeFeedPage(feed, { reports: [b, c], nextBefore: null }, 'append'); + assert.deepEqual( + [feed.items.map((r) => r.id), feed.nextBefore], + [['a', 'b', 'c'], null], + ); + const newer = report('n', '2026-10-28T11:00:00Z'); + feed = mergeFeedPage( + { ...feed, nextBefore: 'C' }, + { reports: [newer, a], nextBefore: 'X' }, + 'head', + ); + assert.deepEqual( + [feed.items.map((r) => r.id), feed.nextBefore], + [['n', 'a', 'b', 'c'], 'C'], + ); + assert.deepEqual( + mergeFeedPage({ items: [] }, { reports: [], nextBefore: null }, 'replace'), + { items: [], nextBefore: null }, + ); +}); + +test('filters default to significant news and map to a last-24-hours query', () => { + const hotspots = [{ id: 'ua' }, { id: 'me' }]; + const filters = normalizeFilters( + { hotspot: 'ua', category: 'nope', minSeverity: 9 }, + hotspots, + ); + assert.deepEqual(filters, { + hotspot: 'ua', + category: 'all', + minSeverity: 2, + includeMinor: false, + cards: true, + }); + assert.equal(normalizeFilters({ cards: false }, hotspots).cards, false); + assert.equal(normalizeFilters({ minSeverity: 0 }, hotspots).minSeverity, 0); + assert.equal(normalizeFilters({ hotspot: 'gone' }, hotspots).hotspot, 'all'); + assert.equal( + newsFeedQuery( + feedQueryFor(filters, { before: '2026-10-28T08:00:00.000Z' }), + ), + 'hotspot=ua&before=2026-10-28T08%3A00%3A00.000Z&limit=60&relevance=core%2Crelated&today=1&events=1', + ); + // "Include minor news" drops the relevance filter. + assert.doesNotMatch( + newsFeedQuery(feedQueryFor({ ...filters, includeMinor: true })), + /relevance/, + ); +}); + +test('only the last 24 hours pass, and the severity floor applies', () => { + const filters = normalizeFilters(); + const fresh = report('f', '2026-10-28T09:00:00Z', { severity: 2 }); + const minor = report('m', '2026-10-28T09:00:00Z', { severity: 1 }); + const old = report('o', '2026-10-27T09:00:00Z', { severity: 3 }); + assert.equal(withinNewsWindow(fresh, NOW), true); + assert.equal(withinNewsWindow(old, NOW), false); + assert.equal(withinNewsWindow({ publishedAt: 'x' }, NOW), false); + assert.deepEqual( + [fresh, minor, old] + .filter((r) => passesFilters(r, filters, NOW)) + .map((r) => r.id), + ['f'], + ); + assert.equal(visibleOnMap(minor, { ...filters, minSeverity: 0 }, NOW), true); + assert.equal(visibleOnMap(fresh, { ...filters, hotspot: 'me' }, NOW), false); +}); + +test('ageWords says now, minutes or hours', () => { + assert.equal(ageWords('2026-10-28T09:59:30Z', NOW), 'now'); + assert.equal(ageWords('2026-10-28T09:55:00Z', NOW), '5 min'); + assert.equal(ageWords('2026-10-28T07:10:00Z', NOW), '2 h'); + assert.equal(ageWords('2026-10-26T07:10:00Z', NOW), '24 h'); + assert.equal(ageWords('not a date', NOW), ''); +}); + +test('markers spread deterministically near their place; source link line', () => { + const r = report('r_spread', '2026-10-28T10:00:00Z'); + const p1 = reportMarkerPosition(r); + assert.deepEqual(reportMarkerPosition(r), p1); + assert.ok(Math.abs(p1.lat - 50) < 0.02 && Math.abs(p1.lon - 36) < 0.04); + assert.notDeepEqual( + reportMarkerPosition(report('r_other', r.publishedAt)), + p1, + ); + assert.equal( + sourceLinkLabel('https://www.reliefweb.int/report/x'), + 'Source: reliefweb.int ↗', + ); + assert.equal(sourceLinkLabel('not a url'), ''); +}); + +test('beacons carry a focus, a size by activity and a trend only against a prior day', () => { + const { hotspots } = normalizeHotspotsPayload({ + hotspots: [ + { + id: 'a', + name: 'A', + bbox: [20, 40, 40, 50], + focus: { lat: 45, lon: 30 }, + counts: { last24h: 120, prev24h: 80 }, + }, + { + id: 'b', + name: 'B', + bbox: [20, 40, 40, 50], + focus: { lat: 80, lon: 30 }, + }, + ], + }); + assert.deepEqual( + hotspots.map((h) => h.focus), + [ + { lat: 45, lon: 30 }, + { lat: 45, lon: 30 }, + ], + ); + assert.equal(hotspotTrend(120, 80), '▲'); + assert.equal(hotspotTrend(50, 80), '▼'); + assert.equal(hotspotTrend(85, 80), ''); + assert.equal(hotspotTrend(40, 0), ''); + assert.equal(beaconPixelSize(0), 10); + assert.equal(beaconPixelSize(10_000), 26); + assert.equal( + hotspotLabel({ id: 'ua-ru-war', name: 'Russia–Ukraine war' }), + 'Ukraine–Russia', + ); + assert.equal(hotspotLabel({ id: 'new-one', name: 'New one' }), 'New one'); + assert.equal( + hotspotLabel({ id: 'x', name: 'X', catchAll: true }), + 'Elsewhere', + ); +}); + +test('marker style: severity fill, attestation rim, size by sources, fading with age', () => { + const r = report('r_style', '2026-10-28T10:00:00Z', { + severity: 2, + event: event({ + status: 'claimed', + size: 4, + lastAt: '2026-10-28T10:00:00Z', + }), + }); + const fresh = markerStyle(r, NOW); + assert.equal(fresh.severity, 3); // the event's, when higher than the report's + assert.equal(fresh.rim, 'claimed'); + assert.equal(fresh.size, eventPixelSize(4)); + assert.equal(fresh.alpha, 1); + assert.equal(markerStyle(r, NOW + 48 * 3_600_000).alpha, 0.45); + assert.equal(reportSeverity({ category: 'political' }), 0); + assert.equal(reportSeverity({ category: 'strike' }), 1); +}); + +test('picture cards: physical, two or more sources, major or pressing, at most ten', () => { + const big = report('big', '2026-10-28T09:30:00Z', { event: event() }); + const statement = report('st', '2026-10-28T09:30:00Z', { + category: 'political', + event: event(), + }); + const lone = report('lone', '2026-10-28T09:30:00Z', { + event: event({ size: 1 }), + }); + const stale = report('stale', '2026-10-28T01:00:00Z', { + event: event({ severity: 2, lastAt: '2026-10-28T01:00:00Z' }), + }); + assert.equal(isPressing(big, NOW), true); + assert.deepEqual( + cardEvents([statement, lone, stale, big], NOW).map((r) => r.id), + ['big'], + ); + const many = Array.from({ length: 14 }, (_, i) => + report(`m${i}`, '2026-10-28T09:30:00Z', { event: event() }), + ); + assert.equal(cardEvents(many, NOW).length, 10); + const view = cardView(big, NOW); + assert.equal(view.image, 'https://a.test/p.jpg'); + assert.equal(view.credit, 'A'); + assert.equal(view.meta, '30 min · 6 sources · UA, RU'); + assert.equal(cardView(lone, NOW).image, null); +}); + +test('feed cards read like Breaking: headline, meta parts, sides and chips', () => { + const r = report('fc', '2026-10-28T09:00:00Z', { + title: 'Удар по Харкову', + titleEn: 'Strike on Kharkiv', + affiliation: 'military', + media: ['video', 'photo'], + geo: { lat: 50, lon: 36, place: 'Kharkiv', mappable: true, byModel: true }, + event: event({ lastAt: '2026-10-28T09:50:00Z' }), + }); + const view = feedCardView(r, NOW); + assert.equal(view.title, 'Strike on Kharkiv'); + assert.equal(view.original, 'Удар по Харкову'); + assert.equal(view.placedByModel, true); + assert.equal(view.severityLabel, 'Major'); + assert.equal(view.color, '#d7301f'); + assert.equal(view.category, 'Strike'); + assert.equal(view.place, 'Kharkiv'); + assert.equal(view.sources, '6 sources'); + assert.equal(view.age, '10 min'); + assert.equal(view.sides, 'Reported by UA sources · RU sources'); + assert.deepEqual(view.picture, { url: 'https://a.test/p.jpg', credit: 'A' }); + assert.deepEqual( + view.chips.map((c) => [c.kind, c.label]), + [ + ['official', 'Official'], + ['confirmed', 'Reported by both sides'], + ['media', 'Video'], + ['media', 'Photos'], + ], + ); + assert.deepEqual( + view.others.map((o) => o.side), + ['RU'], + ); + // A lone report: its own side, no picture, one source. + const single = feedCardView(report('s', '2026-10-28T09:00:00Z'), NOW); + assert.equal(single.sides, 'Reported by UA sources'); + assert.equal(single.picture, null); + assert.equal(single.original, null); + assert.equal(sidesLine({ side: 'unknown' }), ''); +}); + +test('in view: half-degree cells and reports within 500 km of the centre', () => { + assert.equal(viewCell({ lat: 50.2, lon: 36.7 }), '100:73'); + assert.equal(viewCell({ lat: 50.4, lon: 36.9 }), '100:73'); + assert.notEqual(viewCell({ lat: 50.6, lon: 36.7 }), '100:73'); + assert.ok( + Math.abs(distanceKm({ lat: 0, lon: 0 }, { lat: 0, lon: 1 }) - 111.2) < 0.5, + ); + const filters = normalizeFilters({ minSeverity: 0 }); + const near = report('near', '2026-10-28T09:00:00Z', { severity: 1 }); + const major = report('major', '2026-10-28T08:00:00Z', { severity: 3 }); + const far = report('far', '2026-10-28T09:00:00Z', { + pins: [{ lat: 31.5, lon: 34.4, place: 'Gaza', mappable: true }], + }); + const old = report('old', '2026-10-27T08:00:00Z'); + const centre = { lat: 49, lon: 36 }; + assert.ok(distanceKm(centre, far.pins[0]) > NEWS_IN_VIEW_RADIUS_KM); + assert.deepEqual( + reportsInView([near, far, old, major], centre, filters, NOW).map( + (r) => r.id, + ), + ['major', 'near'], + ); + assert.deepEqual(reportsInView([near], null, filters, NOW), []); + assert.deepEqual(reportsInView([], centre, filters, NOW), []); +}); diff --git a/src/layers/news/records.js b/src/layers/news/records.js new file mode 100644 index 000000000..266d17f7c --- /dev/null +++ b/src/layers/news/records.js @@ -0,0 +1,325 @@ +// Validate /api/news payloads before they reach the scene or the DOM. Every +// string is bounded, every URL is http(s), every position is finite; a record +// that fails is dropped, a payload that fails is rejected whole. A portable +// export (layers/news/source): no i18n here. + +const CATEGORY = /^[a-z][a-z-]{1,31}$/; +const CODE = /^[A-Za-z][A-Za-z0-9-]{0,31}$/; +const ID = /^[a-z0-9][a-z0-9_-]{0,63}$/i; +const EVENT_STATUSES = Object.freeze([ + 'both-sides', + 'independent', + 'claimed', + 'reported', + 'side', + 'single', +]); + +const text = (value, max) => + typeof value === 'string' && value.trim() + ? value.replace(/\s+/g, ' ').trim().slice(0, max) + : null; +const finite = (value, min, max) => + Number.isFinite(value) && value >= min && value <= max ? value : null; +const iso = (value) => { + const ms = Date.parse(value); + return Number.isFinite(ms) ? new Date(ms).toISOString() : null; +}; +const code = (value) => + typeof value === 'string' && CODE.test(value) ? value : null; +const severity = (value) => + Number.isInteger(value) && value >= 0 && value <= 3 ? value : null; + +/** An http(s) URL without credentials, as its normalised href, or null. */ +export function httpUrl(value) { + try { + const url = new URL(value); + return ['http:', 'https:'].includes(url.protocol) && + !url.username && + !url.password + ? url.href + : null; + } catch { + return null; + } +} + +function normalizeBbox(bbox) { + if (!Array.isArray(bbox) || bbox.length !== 4) return null; + const [west, south, east, north] = bbox; + if ( + finite(west, -180, 180) === null || + finite(east, -180, 180) === null || + finite(south, -90, 90) === null || + finite(north, -90, 90) === null || + west >= east || + south >= north + ) + return null; + return [west, south, east, north]; +} + +/** Beacon position: the curated focus point, else the bbox centre. */ +function normalizeFocus(focus, [west, south, east, north]) { + const lat = finite(focus?.lat, south, north); + const lon = finite(focus?.lon, west, east); + return lat !== null && lon !== null + ? { lat, lon } + : { lat: (south + north) / 2, lon: (west + east) / 2 }; +} + +function normalizeDeveloping(items) { + const out = []; + for (const raw of Array.isArray(items) ? items.slice(0, 16) : []) { + const lat = finite(raw?.focus?.lat, -90, 90); + const lon = finite(raw?.focus?.lon, -180, 180); + const country = + typeof raw?.country === 'string' && /^[A-Z]{2}$/.test(raw.country) + ? raw.country + : null; + if (lat === null || lon === null || !country) continue; + // A state where the catch-all flags states ("US-FL"), else the country. + const area = + typeof raw.area === 'string' && /^[A-Z]{2}-[A-Z0-9]{1,3}$/.test(raw.area) + ? raw.area + : null; + out.push({ + country, + key: area || country, + name: text(raw.name, 80) || country, + events: Math.max(0, Math.floor(Number(raw.events) || 0)), + reports: Math.max(0, Math.floor(Number(raw.reports) || 0)), + focus: { lat, lon }, + }); + } + return out; +} + +/** + * `/api/news/hotspots` → `{hotspots, categories, lastRunAt}`, or null when the + * payload has no hotspot list. + */ +export function normalizeHotspotsPayload(payload) { + if (!Array.isArray(payload?.hotspots)) return null; + const hotspots = []; + for (const raw of payload.hotspots.slice(0, 64)) { + const id = typeof raw?.id === 'string' && ID.test(raw.id) ? raw.id : null; + const name = text(raw?.name, 80); + const bbox = normalizeBbox(raw?.bbox); + if (!id || !name || !bbox) continue; + const counts = raw.counts || {}; + hotspots.push({ + id, + name, + kind: text(raw.kind, 16) || 'conflict', + catchAll: raw.catchAll === true, + developing: normalizeDeveloping(raw.developing), + bbox, + parties: Array.isArray(raw.parties) + ? raw.parties.filter((p) => code(p)) + : [], + last24h: Math.max(0, Math.floor(Number(counts.last24h) || 0)), + mapped24h: Math.max(0, Math.floor(Number(counts.mapped24h) || 0)), + prev24h: Number.isFinite(counts.prev24h) + ? Math.max(0, Math.floor(counts.prev24h)) + : null, + focus: normalizeFocus(raw.focus, bbox), + latestAt: iso(raw.latestAt), + }); + } + return { + hotspots, + categories: Array.isArray(payload.categories) + ? payload.categories.filter( + (c) => typeof c === 'string' && CATEGORY.test(c), + ) + : [], + lastRunAt: iso(payload.ingest?.lastRunAt), + }; +} + +function normalizeGeo(geo) { + if (!geo || typeof geo !== 'object') return null; + const lat = finite(geo.lat, -90, 90); + const lon = finite(geo.lon, -180, 180); + if (lat === null || lon === null) return null; + return { + lat, + lon, + place: text(geo.place, 80), + precision: text(geo.precision, 16) || 'city', + confidence: finite(geo.confidence, 0, 1) ?? 0, + mappable: geo.mappable === true, + byModel: geo.method === 'llm', + }; +} + +/** The event's picture: an HTTPS URL on the publisher's site, and whose it is. */ +function eventImage(image) { + const url = httpUrl(image?.url); + if (!url?.startsWith('https://')) return null; + return { url, publisher: text(image.publisher, 80) || '' }; +} + +/** An event summary from `/feed?events=1`: size and one report per side. */ +function normalizeEvent(event) { + if (!event || typeof event !== 'object') return null; + const count = (value) => Math.max(1, Math.floor(Number(value) || 1)); + const sides = []; + for (const side of Array.isArray(event.sides) + ? event.sides.slice(0, 8) + : []) { + const url = httpUrl(side?.url); + const title = text(side?.title, 300); + if (!url || !title) continue; + sides.push({ + side: code(side.side) || 'unknown', + title, + url, + publisher: text(side.publisher, 80) || '', + publishedAt: iso(side.publishedAt), + }); + } + return { + id: typeof event.id === 'string' && ID.test(event.id) ? event.id : null, + status: EVENT_STATUSES.includes(event.status) ? event.status : null, + claimedBy: text(event.claimedBy, 80), + reportedSide: code(event.reportedSide), + size: count(event.size), + reports: count(event.reports), + severity: severity(event.severity), + firstAt: iso(event.firstAt), + lastAt: iso(event.lastAt), + sides, + image: eventImage(event.image), + }; +} + +function normalizeReport(raw) { + const id = typeof raw?.id === 'string' && ID.test(raw.id) ? raw.id : null; + const title = text(raw?.title, 300); + const url = httpUrl(raw?.url); + const publishedAt = iso(raw?.publishedAt); + if (!id || !title || !url || !publishedAt) return null; + const source = raw.source || {}; + const geo = normalizeGeo(raw.geo); + // Map positions: the report's own place plus any other hotspot its title + // names (a roundup is pinned in each). + const pins = []; + for (const place of [ + geo, + ...(Array.isArray(raw.locations) + ? raw.locations.slice(0, 8).map(normalizeGeo) + : []), + ]) + if ( + place?.mappable && + !pins.some((p) => p.lat === place.lat && p.lon === place.lon) + ) + pins.push(place); + const hotspotId = typeof raw.hotspotId === 'string' ? raw.hotspotId : null; + return { + id, + hotspotId, + hotspotIds: Array.isArray(raw.hotspotIds) + ? raw.hotspotIds.filter((h) => typeof h === 'string').slice(0, 8) + : [hotspotId].filter(Boolean), + title, + url, + snippet: text(raw.snippet, 400), + publisher: text(raw.publisher, 80) || text(source.name, 80) || '', + sourceName: text(source.name, 80) || text(raw.publisher, 80) || '', + kind: text(raw.kind, 16) || 'rss', + side: code(raw.side) || 'unknown', + affiliation: text(raw.affiliation, 32), + attribution: text(source.attribution, 120), + category: + typeof raw.category === 'string' && CATEGORY.test(raw.category) + ? raw.category + : 'other', + publishedAt, + geo, + pins, + event: normalizeEvent(raw.event), + titleEn: text(raw.titleEn, 200), + relevance: ['core', 'related', 'minor'].includes(raw.relevance) + ? raw.relevance + : 'related', + severity: severity(raw.severity), + severityBy: raw.severityBy === 'model' ? 'model' : 'rules', + claim: + raw.claim && typeof raw.claim === 'object' + ? { by: text(raw.claim.by, 80) } + : null, + media: Array.isArray(raw.media) + ? [...new Set(raw.media.filter((m) => m === 'video' || m === 'photo'))] + : [], + }; +} + +function normalizeRing(ring) { + if (!Array.isArray(ring) || ring.length < 3) return null; + const points = []; + for (const point of ring.slice(0, 20_000)) { + const lon = finite(point?.[0], -180, 180); + const lat = finite(point?.[1], -90, 90); + if (lon !== null && lat !== null) points.push([lon, lat]); + } + return points.length >= 3 ? points : null; +} + +/** + * `/api/news/outline` → `{polygons, borders, disputed}`: the dissolved extent + * (`{outer, holes}`), the national borders inside it (rings) and its disputed + * areas, invalid parts dropped. + */ +export function normalizeOutlinePayload(payload) { + const polygons = []; + for (const raw of Array.isArray(payload?.polygons) + ? payload.polygons.slice(0, 200) + : []) { + const outer = normalizeRing(raw?.outer); + if (!outer) continue; + const holes = (Array.isArray(raw.holes) ? raw.holes.slice(0, 200) : []) + .map(normalizeRing) + .filter(Boolean); + polygons.push({ outer, holes }); + } + const borders = ( + Array.isArray(payload?.borders) ? payload.borders.slice(0, 50) : [] + ) + .map(normalizeRing) + .filter(Boolean); + const KINDS = ['held', 'self', 'un', 'unclaimed']; + const country = (value) => + typeof value === 'string' && /^[A-Z]{2}$/.test(value) ? value : null; + const disputed = []; + for (const raw of Array.isArray(payload?.disputed) + ? payload.disputed.slice(0, 30) + : []) { + const rings = (Array.isArray(raw?.rings) ? raw.rings.slice(0, 20) : []) + .map(normalizeRing) + .filter(Boolean); + const name = text(raw?.name, 60); + if (!rings.length || !name) continue; + disputed.push({ + name, + kind: KINDS.includes(raw.kind) ? raw.kind : 'held', + heldBy: country(raw.heldBy), + claimedBy: country(raw.claimedBy), + rings, + }); + } + return { polygons, borders, disputed }; +} + +/** `/api/news/feed` → `{reports, nextBefore}`, or null without a report list. */ +export function normalizeFeedPayload(payload) { + if (!Array.isArray(payload?.reports)) return null; + const reports = []; + for (const raw of payload.reports.slice(0, 500)) { + const report = normalizeReport(raw); + if (report) reports.push(report); + } + return { reports, nextBefore: iso(payload.nextBefore) }; +} diff --git a/src/layers/news/source.js b/src/layers/news/source.js new file mode 100644 index 000000000..8c739584b --- /dev/null +++ b/src/layers/news/source.js @@ -0,0 +1,162 @@ +import { readResponseJsonCapped } from '../../sources/httpBody.js'; +import { isUnavailableCapability } from '../../sources/capability.js'; +import { + normalizeFeedPayload, + normalizeHotspotsPayload, + normalizeOutlinePayload, +} from './records.js'; + +// A portable export (package.json): no i18n here. Failures stay English data; +// the layer shows them translated. +const msg = (text) => text; + +const MAX_BYTES = 4 * 1024 * 1024; +const BASE_PATH = '/api/news'; +// The outline geometry version the client draws (disputed areas included). +const OUTLINE_VERSION = '3'; + +/** The three read routes the news layer calls, for a host's path allowlist. */ +export const NEWS_API_PATHS = Object.freeze([ + `${BASE_PATH}/hotspots`, + `${BASE_PATH}/feed`, + `${BASE_PATH}/outline`, +]); + +const FEED_KEYS = Object.freeze([ + 'hotspot', + 'before', + 'since', + 'limit', + 'category', + 'relevance', +]); +const FLAG_KEYS = Object.freeze(['geo', 'today', 'events']); +const ISO = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,3})?Z$/; +const LIST = /^[a-z][a-z,-]{0,127}$/; +const FEED_VALUE = { + hotspot: (v) => /^[a-z0-9][a-z0-9_-]{0,63}$/i.test(v), + before: (v) => ISO.test(v), + since: (v) => ISO.test(v), + limit: (v) => /^\d{1,3}$/.test(v) && Number(v) >= 1 && Number(v) <= 500, + category: (v) => LIST.test(v), + relevance: (v) => LIST.test(v), +}; + +/** Feed query string from a plain object; unknown keys and empty values are dropped. */ +export function newsFeedQuery(query = {}) { + const params = new URLSearchParams(); + for (const key of FEED_KEYS) { + const value = query[key]; + if (value !== undefined && value !== null && value !== '') + params.set(key, String(value)); + } + for (const key of FLAG_KEYS) if (query[key]) params.set(key, '1'); + return params.toString(); +} + +/** + * Whether a request URL is one this client sends: a known route, known keys + * only, each value in its form. A host proxying the routes can admit exactly + * these and refuse the rest. + * @param {URL} url + */ +export function newsQueryAllowed(url) { + const params = [...url.searchParams]; + if (new Set(params.map(([key]) => key)).size !== params.length) return false; + if (url.pathname === `${BASE_PATH}/hotspots`) return params.length === 0; + if (url.pathname === `${BASE_PATH}/outline`) { + const keys = params.map(([key]) => key).sort(); + const value = url.searchParams; + return ( + params.length === 2 && + keys[1] === 'v' && + value.get('v') === OUTLINE_VERSION && + ((keys[0] === 'hotspot' && FEED_VALUE.hotspot(value.get('hotspot'))) || + (keys[0] === 'country' && + /^[A-Z]{2}(?:-[A-Z0-9]{1,3})?$/.test(value.get('country')))) + ); + } + if (url.pathname !== `${BASE_PATH}/feed`) return false; + return params.every(([key, value]) => + FLAG_KEYS.includes(key) + ? value === '1' + : Object.hasOwn(FEED_VALUE, key) && FEED_VALUE[key](value), + ); +} + +/** A failed read: a server without the news routes is a permanent miss. */ +async function responseError(response) { + let body = null; + try { + body = await readResponseJsonCapped(response, 16 * 1024); + } catch { + await response.body?.cancel?.().catch?.(() => {}); + } + const unavailable = + response.status === 404 || + (response.status === 503 && isUnavailableCapability(body)); + return Object.assign( + new Error( + unavailable + ? msg('News feed not configured on this server') + : msg('News feed unavailable'), + ), + { + status: response.status, + code: unavailable ? 'unavailable' : 'http', + unavailable, + retryable: !unavailable, + }, + ); +} + +/** Read hotspots, reports and outlines from the server's /api/news routes. */ +export function createNewsSource({ + fetchImpl = (...args) => globalThis.fetch(...args), + timeoutMs = 15_000, +} = {}) { + async function get(path, { signal } = {}) { + signal?.throwIfAborted(); + const timeout = AbortSignal.timeout(timeoutMs); + const request = signal ? AbortSignal.any([signal, timeout]) : timeout; + const response = await fetchImpl(`${BASE_PATH}${path}`, { + signal: request, + cache: 'no-store', + redirect: 'error', + }); + if (!response.ok) throw await responseError(response); + return readResponseJsonCapped(response, MAX_BYTES, request); + } + return { + async getHotspots({ signal } = {}) { + const payload = normalizeHotspotsPayload( + await get('/hotspots', { signal }), + ); + if (!payload) throw new Error(msg('Malformed news hotspots response')); + return payload; + }, + async getOutline(hotspotId, { signal } = {}) { + return normalizeOutlinePayload( + await get( + `/outline?hotspot=${encodeURIComponent(hotspotId)}&v=${OUTLINE_VERSION}`, + { signal }, + ), + ); + }, + async getCountryOutline(country, { signal } = {}) { + return normalizeOutlinePayload( + await get( + `/outline?country=${encodeURIComponent(country)}&v=${OUTLINE_VERSION}`, + { signal }, + ), + ); + }, + async getFeed(query = {}, { signal } = {}) { + const payload = normalizeFeedPayload( + await get(`/feed?${newsFeedQuery(query)}`, { signal }), + ); + if (!payload) throw new Error(msg('Malformed news feed response')); + return payload; + }, + }; +} diff --git a/src/layers/news/source.test.mjs b/src/layers/news/source.test.mjs new file mode 100644 index 000000000..3f48093ea --- /dev/null +++ b/src/layers/news/source.test.mjs @@ -0,0 +1,164 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { + NEWS_API_PATHS, + createNewsSource, + newsFeedQuery, + newsQueryAllowed, +} from './source.js'; + +const json = (body, status = 200) => + new Response(JSON.stringify(body), { + status, + headers: { 'Content-Type': 'application/json' }, + }); + +function recorder(respond) { + const calls = []; + return { + calls, + fetchImpl: async (url, init) => { + calls.push({ url, init }); + return respond(url, init); + }, + }; +} + +test('reads validated hotspots, feed and outlines from the same-origin routes', async () => { + const { calls, fetchImpl } = recorder((url) => { + if (url.startsWith('/api/news/hotspots')) + return json({ + hotspots: [{ id: 'ua', name: 'UA', bbox: [22, 44, 42, 56] }], + }); + if (url.startsWith('/api/news/feed')) + return json({ + reports: [ + { + id: 'r1', + title: 'T', + url: 'https://x.test/', + publishedAt: '2026-10-28T09:00:00Z', + }, + ], + nextBefore: null, + }); + return json({ polygons: [], borders: [], disputed: [] }); + }); + const source = createNewsSource({ fetchImpl }); + assert.equal((await source.getHotspots()).hotspots[0].id, 'ua'); + assert.equal( + (await source.getFeed({ hotspot: 'all', today: true, limit: 60 })) + .reports[0].id, + 'r1', + ); + assert.deepEqual((await source.getOutline('ua')).polygons, []); + await source.getCountryOutline('SD'); + assert.deepEqual( + calls.map((c) => c.url), + [ + '/api/news/hotspots', + '/api/news/feed?hotspot=all&limit=60&today=1', + '/api/news/outline?hotspot=ua&v=3', + '/api/news/outline?country=SD&v=3', + ], + ); + for (const { url, init } of calls) { + assert.equal(init.redirect, 'error'); + assert.equal(init.cache, 'no-store'); + assert.ok(init.signal instanceof AbortSignal); + // Every URL the client sends is one a host's allowlist admits. + assert.equal(newsQueryAllowed(new URL(url, 'http://h')), true, url); + } +}); + +test('malformed, failed and unconfigured reads reject; a server without news is a permanent miss', async () => { + const malformed = createNewsSource({ fetchImpl: async () => json({}) }); + await assert.rejects(malformed.getHotspots(), /Malformed news hotspots/); + await assert.rejects(malformed.getFeed(), /Malformed news feed/); + + const down = createNewsSource({ + fetchImpl: async () => json({ error: 'upstream' }, 502), + }); + await assert.rejects(down.getHotspots(), (error) => { + assert.equal(error.message, 'News feed unavailable'); + assert.equal(error.retryable, true); + assert.equal(error.unavailable, false); + return true; + }); + + const unconfigured = createNewsSource({ + fetchImpl: async () => + json( + { error: 'news_not_configured', unavailable: true, retryable: false }, + 503, + ), + }); + await assert.rejects(unconfigured.getHotspots(), (error) => { + assert.equal(error.message, 'News feed not configured on this server'); + assert.equal(error.code, 'unavailable'); + assert.equal(error.unavailable, true); + assert.equal(error.retryable, false); + return true; + }); + const missing = createNewsSource({ + fetchImpl: async () => new Response('Not found', { status: 404 }), + }); + await assert.rejects(missing.getFeed(), { unavailable: true }); + const broken = createNewsSource({ + fetchImpl: async () => new Response('{', { status: 200 }), + }); + await assert.rejects(broken.getHotspots(), SyntaxError); +}); + +test('reads time out and follow the caller signal', async () => { + const hang = (_url, { signal }) => + new Promise((_, reject) => + signal.addEventListener('abort', () => reject(signal.reason), { + once: true, + }), + ); + const slow = createNewsSource({ fetchImpl: hang, timeoutMs: 20 }); + await assert.rejects(slow.getHotspots(), { name: 'TimeoutError' }); + const caller = new AbortController(); + const pending = createNewsSource({ fetchImpl: hang }).getFeed( + {}, + { signal: caller.signal }, + ); + caller.abort(new Error('gone')); + await assert.rejects(pending, /gone/); + await assert.rejects( + createNewsSource({ fetchImpl: hang }).getHotspots({ + signal: AbortSignal.abort(new Error('already')), + }), + /already/, + ); +}); + +test('the host allowlist admits the client routes and refuses anything else', () => { + const allowed = (path) => newsQueryAllowed(new URL(path, 'http://h')); + assert.deepEqual(NEWS_API_PATHS, [ + '/api/news/hotspots', + '/api/news/feed', + '/api/news/outline', + ]); + assert.equal( + allowed( + `/api/news/feed?${newsFeedQuery({ hotspot: 'ua-ru-war', before: '2026-10-28T08:00:00.000Z', limit: 500, category: 'strike', relevance: 'core,related', geo: true, today: true, events: true })}`, + ), + true, + ); + for (const path of [ + '/api/news/hotspots?x=1', + '/api/news/feed?limit=501', + '/api/news/feed?limit=0', + '/api/news/feed?hotspot=all&hotspot=ua', + '/api/news/feed?since=yesterday', + '/api/news/feed?geo=yes', + '/api/news/feed?side=UA', + '/api/news/air-alerts', + '/api/news/outline?hotspot=ua', + '/api/news/outline?hotspot=ua&v=2', + '/api/news/outline?country=ukraine&v=3', + ]) + assert.equal(allowed(path), false, path); +}); diff --git a/src/layers/news/sprites.js b/src/layers/news/sprites.js new file mode 100644 index 000000000..ac7c71ac5 --- /dev/null +++ b/src/layers/news/sprites.js @@ -0,0 +1,94 @@ +// Marker sprites for news reports: a disc filled with the severity colour, +// the category's icon in it, and a rim for attestation. Drawn once per look +// on a canvas and handed to Cesium as a data URL, so its texture atlas keeps +// one copy per look however often the layer re-renders. + +import { NEWS_CATEGORIES, NEWS_SEVERITY } from './model.js'; + +const CANVAS = 64; +const BODY = 52; // disc diameter inside the canvas; the rest is rim and ring +const INK = '#0a0a0f'; +const RIM = '#ffffff'; +const SELECTED = '#00d4ff'; + +/** Canvas pixels per marker pixel: the billboard is drawn at this ratio. */ +export const SPRITE_SCALE = CANVAS / BODY; + +const cache = new Map(); + +/** + * Paint one marker look centred at (cx, cy) with a disc of `body` pixels: the + * sprites and the event cards' badges draw the same thing. + */ +export function paintMarker(ctx, { category, severity, rim }, cx, cy, body) { + const k = body / BODY; // the strokes below are tuned for the 52 px body + const r = body / 2; + // A dark edge keeps the lightest fills apart from bright ground. + ctx.beginPath(); + ctx.arc(cx, cy, r + 1.5 * k, 0, 2 * Math.PI); + ctx.fillStyle = 'rgba(0, 0, 0, 0.85)'; + ctx.fill(); + ctx.beginPath(); + ctx.arc(cx, cy, r, 0, 2 * Math.PI); + ctx.fillStyle = (NEWS_SEVERITY[severity] || NEWS_SEVERITY[0]).color; + ctx.fill(); + + // Attestation is the rim's form, never its colour. + if (rim === 'confirmed' || rim === 'claimed') { + ctx.beginPath(); + ctx.arc(cx, cy, r - 3.5 * k, 0, 2 * Math.PI); + ctx.setLineDash(rim === 'claimed' ? [7 * k, 5 * k] : []); + ctx.lineWidth = 7 * k; + ctx.strokeStyle = RIM; + ctx.stroke(); + ctx.setLineDash([]); + } else { + ctx.beginPath(); + ctx.arc(cx, cy, r - 1 * k, 0, 2 * Math.PI); + ctx.lineWidth = 2 * k; + ctx.strokeStyle = 'rgba(0, 0, 0, 0.75)'; + ctx.stroke(); + } + + const style = NEWS_CATEGORIES[category] || NEWS_CATEGORIES.other; + const icon = body * 0.56; + ctx.save(); + ctx.translate(cx - icon / 2, cy - icon / 2); + ctx.scale(icon / 16, icon / 16); + const path = new Path2D(style.icon); + ctx.lineCap = 'round'; + ctx.lineJoin = 'round'; + ctx.lineWidth = 1.7; + ctx.strokeStyle = INK; + if (style.solid) { + ctx.fillStyle = INK; + ctx.fill(path); + } else ctx.stroke(path); + ctx.restore(); +} + +/** + * Data URL of the sprite for a look, or null where there is no canvas (the + * layer then falls back to a plain point). + * @param {{category: string, severity: number, rim: 'confirmed'|'claimed'|'thin', selected?: boolean}} look + */ +export function markerSprite({ category, severity, rim, selected = false }) { + const key = `${category}|${severity}|${rim}|${selected ? 1 : 0}`; + if (cache.has(key)) return cache.get(key); + const canvas = globalThis.document?.createElement?.('canvas'); + const ctx = canvas?.getContext?.('2d'); + if (!ctx || typeof globalThis.Path2D !== 'function') return null; + canvas.width = canvas.height = CANVAS; + const c = CANVAS / 2; + paintMarker(ctx, { category, severity, rim }, c, c, BODY); + if (selected) { + ctx.beginPath(); + ctx.arc(c, c, CANVAS / 2 - 2, 0, 2 * Math.PI); + ctx.lineWidth = 3.5; + ctx.strokeStyle = SELECTED; + ctx.stroke(); + } + const url = canvas.toDataURL('image/png'); + cache.set(key, url); + return url; +} From 5bb489d1fb2c2460a3567029393745056a3c324e Mon Sep 17 00:00:00 2001 From: Denis Groshev Date: Thu, 5 Nov 2026 20:03:44 +0100 Subject: [PATCH 037/171] Put news on the globe, with a feed panel in the right rail MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Events ▸ News draws the last 24 hours of reports from curated hotspots (Ukraine–Russia, Israel–Gaza–Lebanon, Iran–Hormuz, Yemen–Red Sea, Sudan, Sahel) and developing situations elsewhere, from any server that answers the `/api/news` read routes. - Globe: one marker per merged event, clamped to the ground and culled at the horizon; one beacon per hotspot when zoomed out and a pulsing beacon for a developing situation; hotspot outlines with disputed areas dotted and labelled by who administers and who claims them; picture cards for at most ten major or fast-growing events with two or more sources, never overlapping, switchable off. - Panel: hotspot chips, a severity filter (significant and above by default), categories, minor news off by default, and a scrolling list of event cards with picture, headline, place, sources, age and the sides that reported it. "In view" lists what is near the map below 3,000 km once the camera settles. A card flies the globe to its event and opens it with a link to the publisher. Reduced motion stops the pulse and the flights. - Core serves no news itself: the local server proxies GEV_NEWS_ORIGIN when it is set, and answers 503 unavailable otherwise, so the layer reads "not configured" once instead of retrying. - Share token 9 (enabled-only); voice stays off for this layer. --- .env.example | 5 + DATA_SOURCES.md | 1 + changelog.d/1-news-layer.md | 6 + docs/CURRENT-STATE.md | 8 + scripts/package-boundaries.json | 29 + server/providers/local.js | 2 + server/providers/news.js | 109 ++ server/providers/news.test.mjs | 135 +++ src/app/constructCatalog.js | 2 + src/app/constructCatalog.test.mjs | 5 +- src/app/layers/news.js | 6 + src/app/sourceComposition.js | 1 + src/app/sourceComposition.test.mjs | 31 +- src/data/dataCredits.js | 8 + src/data/layerState.js | 1 + src/data/layerState.test.mjs | 34 +- src/data/layerStateTokenLedger.test.mjs | 64 +- src/data/layerStateTokenReservations.json | 1 + src/i18n/locales/ar.json | 46 + src/i18n/locales/de.json | 38 + src/i18n/locales/es.json | 40 + src/i18n/locales/fr.json | 40 + src/i18n/locales/it.json | 40 + src/i18n/locales/ja.json | 36 + src/i18n/locales/pt.json | 40 + src/i18n/locales/ru.json | 42 + src/i18n/locales/uk.json | 42 + src/i18n/locales/zh-CN.json | 36 + src/i18n/locales/zh-Hant.json | 36 + src/layers/news/index.js | 1240 +++++++++++++++++++++ src/layers/news/layer.test.mjs | 255 +++++ src/navigationPolicy.js | 2 + src/navigationPolicy.test.mjs | 1 + src/standalone/layerSources.js | 5 + src/ui/layerBindings.js | 9 + src/ui/layerNames.js | 1 + src/ui/layerPanel.js | 20 + src/ui/news/NewsCard.vue | 127 +++ src/ui/news/NewsFeed.vue | 217 ++++ src/ui/newsPanel.js | 73 ++ src/ui/newsPanel.test.mjs | 223 ++++ src/ui/panelChrome.js | 2 + src/ui/panelLayoutController.js | 3 + src/ui/panelRailCatalog.js | 1 + src/ui/styles/news.css | 378 +++++++ src/ui/views/ContextView.vue | 4 + src/voice/layerManifest.js | 1 + style.css | 1 + 48 files changed, 3394 insertions(+), 53 deletions(-) create mode 100644 changelog.d/1-news-layer.md create mode 100644 server/providers/news.js create mode 100644 server/providers/news.test.mjs create mode 100644 src/app/layers/news.js create mode 100644 src/layers/news/index.js create mode 100644 src/layers/news/layer.test.mjs create mode 100644 src/ui/news/NewsCard.vue create mode 100644 src/ui/news/NewsFeed.vue create mode 100644 src/ui/newsPanel.js create mode 100644 src/ui/newsPanel.test.mjs create mode 100644 src/ui/styles/news.css diff --git a/.env.example b/.env.example index b3de4cefa..d026e35e2 100644 --- a/.env.example +++ b/.env.example @@ -317,3 +317,8 @@ GEMINI_CHAT_MODEL=gemini-3.5-flash-lite # Each reserves up to 40 stations within the existing 750-station directory. # Restart after changing. Leave blank for the existing global selection. # RADIO_PRIORITY_COUNTRIES=IN,PL +# Optional: a news server for the News layer (its /api/news/hotspots, /feed +# and /outline routes), such as https://news.example. The dev server forwards +# only the layer's own GET requests there, with a 15 s timeout. Unset, Core +# serves no news and the layer shows itself unavailable. SERVER-SIDE ONLY. +# GEV_NEWS_ORIGIN= diff --git a/DATA_SOURCES.md b/DATA_SOURCES.md index ed0895b0a..5bddb2349 100644 --- a/DATA_SOURCES.md +++ b/DATA_SOURCES.md @@ -39,6 +39,7 @@ How to read this: | **NASA GIBS** (WMTS tiles + Worldview Snapshots) and **NASA CMR** (granule catalog) | Recent Imagery layer: HLS S30/L30 (Sentinel-2, Landsat 8/9) and VIIRS true-colour tiles draped on the map, per-day thumbnails and PNG exports; the HLS granule catalog (dates, cloud, footprints) for a selected box | U.S. public domain (NASA data); keyless, browser-direct (CORS `*`); no bulk use — one 30-day catalog query per box, tiles bounded to the box, six tile requests in flight | "We acknowledge the use of imagery provided by services from NASA's Global Imagery Browse Services (GIBS), part of NASA's Earth Science Data and Information System (ESDIS)." — [gibs.earthdata.nasa.gov](https://gibs.earthdata.nasa.gov), [HLS](https://lpdaac.usgs.gov/products/hlss30v002/) | | **NIFC WFIGS** (Wildland Fire Interagency Geospatial Services, ArcGIS feature service) | Fire Perimeters layer: current interagency wildfire incident perimeters, containment, and incident facts | U.S. public domain (interagency wildland-fire data published through the [NIFC Open Data portal](https://data-nifc.opendata.arcgis.com/)); fetched keyless through `/api/fire-perimeters` (5-minute server cache) with `exceededTransferLimit` paging | "Wildfire perimeters: National Interagency Fire Center (WFIGS)" | | **S2 Underground GhostMaps** (`github.com/s2underground/GhostMaps`) | S2 GhostMaps layer: the current edition of S2's KMZ intel products (Common Intelligence Picture, 30-day kinetic pull, Border Crisis Map, Iran and Yemen products, newest incident drop). Keyless. `/api/ghostmaps` reads the branch head from git's ref advertisement every 15 s (`GHOSTMAPS_POLL_SECONDS`, minimum 5 s), lists the tree through the GitHub REST API only when the head changes (optional `GITHUB_TOKEN`), downloads files by commit-pinned raw URLs into `.gev-cache/ghostmaps/` and pushes new catalogs to browsers over server-sent events | [CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/) (repository README: "S2 Underground © 2025 by S2A1"); non-commercial, attribution required; files are fetched at runtime, never stored in this repository | "S2 GhostMaps intel products: S2 Underground © by S2A1, CC BY-NC-SA 4.0" — shown in-app | +| **News server** (`GEV_NEWS_ORIGIN`, optional; none by default) | News layer: curated hotspots and the last 24 h of reports from many publishers, merged into events. Core serves no news itself; the local server forwards the layer's `/api/news/hotspots`, `/feed` and `/outline` GET requests to the configured server | Each report stays its publisher's: headlines and summaries link to the original article, and pictures are hotlinked from the publisher's site (no referrer), never stored | Per report: publisher name and article link on every card; picture cards name the picture's publisher. No single provider is credited for the feed | | **InciWeb** (inciweb.wildfire.gov) | Per-incident "InciWeb ↗" card links to official incident pages (narratives, evacuation/closure notices) | U.S. government public incident information. Links are matched best-effort by incident name and state, with incident page origin and update times checked on selection. Same-origin `/api/fire-perimeters/inciweb` routes cache the catalog for 1 hour and publication metadata for 30 minutes; linked pages remain InciWeb content | "Incident information: InciWeb (inciweb.wildfire.gov)" | | **FAA Special Use Airspace** (`services6.arcgis.com` FeatureServer `Special_Use_Airspace`) | Prohibited & Restricted Airspace layer: US prohibited (P) and restricted (R) special-use airspace polygons (not the UAS Facility Map or UAS flight restrictions), altitude limits from the `*_VAL`/`*_UOM`/`*_CODE` fields, times of use, and controlling agency | U.S. public domain (FAA aeronautical data published through the [FAA AIS Open Data portal](https://adds-faa.opendata.arcgis.com/)); fetched keyless through `/api/drone-airspace` (1-hour server cache). Informational only — not a substitute for official UAS flight-planning tools | "Prohibited & restricted airspace: FAA Special Use Airspace" | | **OpenFreeMap / OpenMapTiles** | Vector tiles | OpenStreetMap data under ODbL 1.0 | OpenFreeMap © OpenMapTiles | diff --git a/changelog.d/1-news-layer.md b/changelog.d/1-news-layer.md new file mode 100644 index 000000000..081316b9d --- /dev/null +++ b/changelog.d/1-news-layer.md @@ -0,0 +1,6 @@ +- Add the News layer (Events ▸ News) and its right-rail NEWS panel: the last + 24 hours from curated hotspots, coloured by severity only, with hotspot + beacons, outlines with disputed areas, picture cards for major events, an + "In view" list below 3,000 km and a continuous feed whose cards fly the globe + to the event. Core serves no news itself: set `GEV_NEWS_ORIGIN` to a news + server and the local server forwards the layer's three read routes there. diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 084ad4f83..4a52c0d74 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -4216,6 +4216,7 @@ its criteria cannot be silently ignored. | Ski Pistes ⛷ (`ski-pistes`) | OpenSnowMap piste raster tiles (keyless; CC BY-SA tiles, OSM data ODbL; no bulk download) | `src/data/osmOverlays.js` | — (browser-direct tiles) | on view (Cesium tile requests; no polling) | | 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) | | Prohibited & Restricted Airspace 🚫 | FAA Special Use Airspace prohibited (P) and restricted (R) zones (keyless FeatureServer, simplified geometry) | `src/layers/droneAirspace/` via `src/app/layers/droneAirspace.js` | `/api/drone-airspace` | 1 h (server cache 1 h; stale-on-error) | +| News ◆ (`news`) | A news server's `/api/news` read routes (curated hotspots, last 24 h of reports merged into events, outlines); Core serves none itself | `src/layers/news/` via `src/app/layers/news.js`; panel `src/ui/newsPanel.js` | `/api/news/hotspots`, `/api/news/feed`, `/api/news/outline` (local dev proxies `GEV_NEWS_ORIGIN`; unset answers "not configured") | 2 min map refresh; In view re-read when the camera settles 0.8 s in a new half-degree cell below 3,000 km | 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; @@ -5846,6 +5847,13 @@ request viewbox and continues searching without that geographic preference. - Pure half: `src/annotations/drawMode.js` (session, minimum vertices, double-click de-dup at 0.5 m, vertex ceiling, degenerate-geometry refusal, ring closing, dateline-safe length/area/centroid, hint text). Regression surface: `src/annotations/drawMode.test.mjs` and `src/data/inputOwnership.test.mjs` (pure), `src/annotations/drawToolBehaviour.test.mjs` (the tool driven against DOM and viewer doubles — leases, borrowed input actions, teardown, the Enter key, preview heights), `src/annotations/drawTool.test.mjs` (structural: where files live, which ids the markup carries, what the docs may claim), and the rendered harness `scripts/qa-draw-tool.mjs`. - The annotation tree is a declared ownership group: `./annotations` → `src/annotations/index.js` in `package.json`, with its module graph listed in `scripts/package-boundaries.json`, so an annotation module reaching outside that graph is a gate failure rather than a surprise in a layer's bundle. `drawMode.js`, `drawTool.js` and their tests are in `scripts/format-scope.json`. +### News (November 2026) + +- **What it shows.** Events ▸ **News**: reports from curated hotspots (Ukraine–Russia, Israel–Gaza–Lebanon, Iran–Hormuz, Yemen–Red Sea, Sudan, Sahel, and developing situations elsewhere), the last 24 hours only. Zoomed out, one beacon per hotspot with its daily count and trend, and a breathing beacon per developing situation (still under reduced motion). Below 2,500 km (7,500 km with a hotspot chosen), the hotspot outlines with disputed areas dotted and named, and every geocoded report as a ground-clamped marker: fill is severity (0 grey no physical event, 1 yellow minor, 2 orange significant, 3 red major), the icon is the category, the rim is attestation (solid confirmed, dashed claim, thin single), size grows with sources and the marker fades over the day. Colour never marks a side. Up to ten picture cards (physical events with two or more sources, major or pressing) stand over their markers without overlapping; "Show event cards" off leaves only the selected one. A selected report's card reads "Source: host ↗" and opens the article. +- **Panel.** The right-rail NEWS panel (`src/ui/newsPanel.js`, `src/ui/news/`) shows "Last 24 h", hotspot chips, severity (significant and above by default), category, "Include minor news" (off) and "Show event cards" (on), "In view" (reports within 500 km of the view centre while the camera is below 3,000 km) and a continuous feed of event cards: the publisher's picture when the event has one (hotlinked, no referrer, publisher credited), the headline (the model's English headline marked as such), a mono meta line (severity marker, category, place, sources, age), "Reported by UA sources · RU sources", attestation and media chips. A click flies the camera straight down from 150 km and selects the report. +- **Source.** `sources.news` (`createNewsSource`, export `./layers/news/source`) reads same-origin `/api/news/*` with a 15 s timeout, a 4 MiB cap and record-by-record validation; `newsQueryAllowed` lets a host admit exactly the client's requests. Core's local server (`server/providers/news.js`) forwards only those GET requests to `GEV_NEWS_ORIGIN`; unset, every route answers 503 `news_not_configured` and the layer reads unavailable without retrying until it is turned off and on. The feed has no area query, so In view filters the day's geocoded reports by distance. +- **State.** Share/restore token `6`, enabled-only. Voice is off for this layer (`VOICE_OFF_LAYERS`). + ### S2 GhostMaps (October 2026) - **What it shows.** Events ▸ **S2 GhostMaps** draws the current edition of S2 Underground's KMZ intel products from `github.com/s2underground/GhostMaps`. The products are the Common Intelligence Picture and the 30-day kinetic pull (both on by default), the Border Crisis Map, the Iran Common Intelligence Picture, Iran Kinetic Events, Yemen FLOT, and **Latest Drop**: the newest dated incident file outside those series, `0_Archive`, `Basedata` and `Reference Material`. Each product has a chip in the row. The chip choice is kept in `localStorage` (`gev.ghostmaps.products`) and falls back to the defaults when storage is blocked. diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 328112590..8e3591938 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -727,6 +727,11 @@ "src/ui/rail/RailTimeline.vue", "src/ui/rail/rangeValue.js", "src/ui/weather/WeatherReadout.vue", + "src/ui/newsPanel.js", + "src/ui/news/NewsFeed.vue", + "src/ui/news/NewsCard.vue", + "src/ui/kit/UiEmpty.vue", + "src/ui/kit/UiSelect.js", "src/ui/kit/UiButton.vue", "src/ui/kit/UiBadge.vue", "src/ui/rail/fieldValue.js", @@ -1131,6 +1136,11 @@ "src/ui/rail/RailTimeline.vue", "src/ui/rail/rangeValue.js", "src/ui/weather/WeatherReadout.vue", + "src/ui/newsPanel.js", + "src/ui/news/NewsFeed.vue", + "src/ui/news/NewsCard.vue", + "src/ui/kit/UiEmpty.vue", + "src/ui/kit/UiSelect.js", "src/ui/stores/streetLevel.js", "src/ui/stores/cctv.js", "src/ui/stores/radio.js", @@ -1190,6 +1200,7 @@ "src/ui/styles/first-run.css", "src/ui/styles/provider-settings.css", "src/ui/styles/weather.css", + "src/ui/styles/news.css", "src/ui/styles/recent-imagery.css" ], "external": [] @@ -2960,6 +2971,13 @@ "src/layers/droneAirspace/source.js", "src/layers/droneAirspace/records.js", "src/layers/droneAirspace/cards.js", + "src/app/layers/news.js", + "src/layers/news/index.js", + "src/layers/news/model.js", + "src/layers/news/records.js", + "src/layers/news/source.js", + "src/layers/news/sprites.js", + "src/layers/news/cards.js", "src/layers/cctv/sourcePolicy.js", "src/sources/reference.js", "src/search/nominatim.js", @@ -3212,6 +3230,10 @@ "src/ui/rail/RailTimeline.vue", "src/ui/rail/rangeValue.js", "src/ui/weather/WeatherReadout.vue", + "src/ui/newsPanel.js", + "src/ui/news/NewsFeed.vue", + "src/ui/news/NewsCard.vue", + "src/ui/kit/UiSelect.js", "src/ui/recentImagery/RecentImageryCard.vue", "src/ui/recentImagery/RecentImageryReadout.vue", "src/ui/stores/streetLevel.js", @@ -3714,6 +3736,13 @@ "src/layers/droneAirspace/source.js", "src/layers/droneAirspace/records.js", "src/layers/droneAirspace/cards.js", + "src/app/layers/news.js", + "src/layers/news/index.js", + "src/layers/news/model.js", + "src/layers/news/records.js", + "src/layers/news/source.js", + "src/layers/news/sprites.js", + "src/layers/news/cards.js", "src/layers/cctv/sourcePolicy.js", "src/search/nominatim.js", "src/nominatimGeocode.js", diff --git a/server/providers/local.js b/server/providers/local.js index 7067f3ec5..a7005db23 100644 --- a/server/providers/local.js +++ b/server/providers/local.js @@ -29,6 +29,7 @@ import { firePerimetersProxy } from './firePerimeters.js'; import { gnssIntegrityProxy } from './gnssIntegrity.js'; import { ghostMapsProxy } from './ghostMaps.js'; import { droneAirspaceProxy } from './droneAirspace.js'; +import { newsProxy } from './news.js'; import { cycloneProxy } from './cyclones.js'; import { windProxy } from './wind.js'; @@ -81,6 +82,7 @@ function localProviderPlugins({ gnssIntegrityProxy(), ghostMapsProxy(), droneAirspaceProxy(), + newsProxy(), keySetupEndpoint(), ]; } diff --git a/server/providers/news.js b/server/providers/news.js new file mode 100644 index 000000000..5d10ab2b1 --- /dev/null +++ b/server/providers/news.js @@ -0,0 +1,109 @@ +import { newsQueryAllowed } from '../../src/layers/news/source.js'; +import { readResponseTextCapped } from './common/http.js'; + +// News (/api/news/*): Core serves no news of its own. With GEV_NEWS_ORIGIN +// set (a news server such as https://news.example), this forwards exactly +// the GET requests the news layer sends there and relays the JSON; without +// it, every route answers "not configured" and the layer shows itself +// unavailable without retrying. + +const TIMEOUT_MS = 15_000; +const MAX_BYTES = 4 * 1024 * 1024; + +/** + * The configured news server's origin, or null: http(s) only, no + * credentials, query or fragment; a path is ignored. + * @param {string|undefined} raw + */ +export function newsOrigin(raw = process.env.GEV_NEWS_ORIGIN) { + const text = String(raw ?? '').trim(); + if (!text) return null; + try { + const url = new URL(text); + if ( + !['http:', 'https:'].includes(url.protocol) || + url.username || + url.password || + url.search || + url.hash + ) + return null; + return url.origin; + } catch { + return null; + } +} + +/** + * A thin, validated GET proxy for the news layer's three read routes. + * @param {{origin?: () => string|null, fetchImpl?: typeof fetch, timeoutMs?: number}} [options] + */ +export function newsProxy({ + origin = () => newsOrigin(), + fetchImpl = (...args) => globalThis.fetch(...args), + timeoutMs = TIMEOUT_MS, +} = {}) { + const json = (res, status, value) => { + if (res.destroyed) return; + res.writeHead(status, { + 'Content-Type': 'application/json', + 'Cache-Control': 'no-store', + ...(status === 405 ? { Allow: 'GET' } : {}), + }); + res.end(typeof value === 'string' ? value : JSON.stringify(value)); + }; + + async function handler(req, res) { + if (req.method !== 'GET') + return json(res, 405, { error: 'method_not_allowed' }); + const local = new URL(req.url || '/', 'http://local'); + const target = new URL( + `/api/news${local.pathname}${local.search}`, + 'http://local', + ); + if (!newsQueryAllowed(target)) + return json(res, 400, { error: 'invalid_news_request' }); + const base = origin(); + if (!base) + return json(res, 503, { + error: 'news_not_configured', + unavailable: true, + retryable: false, + }); + try { + const upstream = await fetchImpl( + new URL(`${target.pathname}${target.search}`, base), + { + headers: { Accept: 'application/json' }, + redirect: 'error', + signal: AbortSignal.timeout(timeoutMs), + }, + ); + if (!upstream.ok) { + await upstream.body?.cancel().catch(() => {}); + return json(res, 502, { + error: 'news_upstream_error', + status: upstream.status, + }); + } + const text = await readResponseTextCapped(upstream, MAX_BYTES); + // Relayed only as JSON; the browser validates every record. + JSON.parse(text); + return json(res, 200, text); + } catch (error) { + return json(res, error?.name === 'TimeoutError' ? 504 : 502, { + error: 'news_unavailable', + }); + } + } + + return { + name: 'news', + configureServer({ middlewares }) { + middlewares.use('/api/news', handler); + }, + configurePreviewServer({ middlewares }) { + middlewares.use('/api/news', handler); + }, + }; +} diff --git a/server/providers/news.test.mjs b/server/providers/news.test.mjs new file mode 100644 index 000000000..31e3ad4bb --- /dev/null +++ b/server/providers/news.test.mjs @@ -0,0 +1,135 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { newsOrigin, newsProxy } from './news.js'; + +/** Mount the proxy on a fake middleware stack and call it like Connect does. */ +function mount(options) { + let handler = null; + newsProxy(options).configureServer({ + middlewares: { + use(prefix, fn) { + assert.equal(prefix, '/api/news'); + handler = fn; + }, + }, + }); + return async (url, method = 'GET') => { + const res = { + destroyed: false, + status: 0, + headers: {}, + body: '', + writeHead(status, headers) { + this.status = status; + this.headers = headers; + }, + end(body) { + this.body = body; + }, + }; + await handler({ url, method }, res); + return { ...res, json: res.body ? JSON.parse(res.body) : null }; + }; +} + +test('the origin must be a plain http(s) origin', () => { + assert.equal(newsOrigin('https://news.example'), 'https://news.example'); + assert.equal( + newsOrigin('https://news.example/base/'), + 'https://news.example', + ); + for (const bad of [ + undefined, + '', + ' ', + 'ftp://x', + 'http://u:p@x', + 'http://x/?a=1', + 'http://x/#f', + 'not a url', + ]) + assert.equal(newsOrigin(bad), null, String(bad)); +}); + +test('without GEV_NEWS_ORIGIN every route answers not configured and nothing is fetched', async () => { + let fetches = 0; + const call = mount({ + origin: () => null, + fetchImpl: async () => { + fetches++; + throw new Error('unexpected'); + }, + }); + const response = await call('/hotspots'); + assert.equal(response.status, 503); + assert.deepEqual(response.json, { + error: 'news_not_configured', + unavailable: true, + retryable: false, + }); + assert.equal(fetches, 0); +}); + +test('forwards only the client routes, by GET, and relays the JSON', async () => { + const calls = []; + const call = mount({ + origin: () => 'https://news.example', + fetchImpl: async (url, init) => { + calls.push({ url: String(url), init }); + return new Response('{"reports":[],"nextBefore":null}', { status: 200 }); + }, + }); + const ok = await call('/feed?hotspot=all&limit=60&today=1&events=1'); + assert.equal(ok.status, 200); + assert.deepEqual(ok.json, { reports: [], nextBefore: null }); + assert.equal(ok.headers['Cache-Control'], 'no-store'); + assert.equal( + calls[0].url, + 'https://news.example/api/news/feed?hotspot=all&limit=60&today=1&events=1', + ); + assert.equal(calls[0].init.redirect, 'error'); + assert.ok(calls[0].init.signal instanceof AbortSignal); + + for (const url of [ + '/air-alerts', + '/feed?side=UA', + '/feed?limit=9999', + '/../admin', + '/hotspots?x=1', + ]) { + const refused = await call(url); + assert.equal(refused.status, 400, url); + } + const post = await call('/hotspots', 'POST'); + assert.equal(post.status, 405); + assert.equal(post.headers.Allow, 'GET'); + assert.equal(calls.length, 1); +}); + +test('upstream failures, bad JSON and timeouts become bounded errors', async () => { + const failing = mount({ + origin: () => 'https://news.example', + fetchImpl: async () => new Response('down', { status: 500 }), + }); + const down = await failing('/hotspots'); + assert.equal(down.status, 502); + assert.deepEqual(down.json, { error: 'news_upstream_error', status: 500 }); + + const garbled = mount({ + origin: () => 'https://news.example', + fetchImpl: async () => new Response('', { status: 200 }), + }); + assert.equal((await garbled('/hotspots')).status, 502); + + const slow = mount({ + origin: () => 'https://news.example', + timeoutMs: 10, + fetchImpl: (_url, { signal }) => + new Promise((_, reject) => + signal.addEventListener('abort', () => reject(signal.reason)), + ), + }); + const timedOut = await slow('/hotspots'); + assert.equal(timedOut.status, 504); + assert.deepEqual(timedOut.json, { error: 'news_unavailable' }); +}); diff --git a/src/app/constructCatalog.js b/src/app/constructCatalog.js index 488a5e9ab..2b1313ba9 100644 --- a/src/app/constructCatalog.js +++ b/src/app/constructCatalog.js @@ -30,6 +30,7 @@ import { createApplicationFirePerimeters } from './layers/perimeters.js'; import { createApplicationGnssIntegrity } from './layers/gnss.js'; import { createApplicationGhostMaps } from './layers/ghostMaps.js'; import { createApplicationDroneAirspace } from './layers/droneAirspace.js'; +import { createApplicationNews } from './layers/news.js'; import { createApplicationCables } from './layers/submarineCables.js'; import { createOsmOverlayLayers } from '../data/osmOverlays.js'; import { createApplicationStreetLevel } from './layers/streetLevel.js'; @@ -137,6 +138,7 @@ export function createApplicationCatalog({ createApplicationDroneAirspace({ source: sources['drone-airspace'], }), + createApplicationNews({ source: sources.news }), createApplicationAlpr({ surface, source: sources.alpr }), createApplicationStreetLevel({ surface, diff --git a/src/app/constructCatalog.test.mjs b/src/app/constructCatalog.test.mjs index 82a1dbcf0..1600f5499 100644 --- a/src/app/constructCatalog.test.mjs +++ b/src/app/constructCatalog.test.mjs @@ -40,7 +40,7 @@ test('catalogs construct distinct layers and classification from their supplied signal: b.signal, surface: fixtureSurface(b.signal), }); - assert.equal(first.layers.length, 37); + assert.equal(first.layers.length, 38); assert.ok(first.get('local-adsb'), 'Local ADS-B is registered'); assert.deepEqual( first.metadata.find(({ id }) => id === 'osm-places'), @@ -68,6 +68,7 @@ test('catalogs construct distinct layers and classification from their supplied assert.ok(first.get('gnss-integrity')); assert.ok(first.get('s2-ghostmaps')); assert.ok(first.get('drone-airspace')); + assert.ok(first.get('news')); assert.ok(first.get('transit')); const order = first.layers.map(({ id }) => id); assert.deepEqual( @@ -161,7 +162,7 @@ test('Mapillary can be omitted or replaced without changing catalog membership', surface: fixtureSurface(lifetime.signal), }; const catalog = createApplicationCatalog(options); - assert.equal(catalog.layers.length, 37); + assert.equal(catalog.layers.length, 38); assert.deepEqual(catalog.get('street-level').providerIds, []); assert.equal( catalogControlServices(catalog).streetLevelLayer, diff --git a/src/app/layers/news.js b/src/app/layers/news.js new file mode 100644 index 000000000..552ad20db --- /dev/null +++ b/src/app/layers/news.js @@ -0,0 +1,6 @@ +import { createNewsLayer } from '../../layers/news/index.js'; +import { overlayHost } from './overlayHost.js'; +/** Wire the news layer to the application overlay host. */ +export function createApplicationNews(options) { + return createNewsLayer({ overlayHost, ...options }); +} diff --git a/src/app/sourceComposition.js b/src/app/sourceComposition.js index a12378260..9cf47b3a9 100644 --- a/src/app/sourceComposition.js +++ b/src/app/sourceComposition.js @@ -50,6 +50,7 @@ export const CATALOG_SOURCE_CONTRACTS = Object.freeze({ 'gnss-integrity': contract(['gnss-integrity'], ['getSnapshot']), 's2-ghostmaps': contract(['s2-ghostmaps'], ['getCatalog', 'getFile']), 'drone-airspace': contract(['drone-airspace'], ['getSnapshot']), + news: contract(['news'], ['getHotspots', 'getFeed', 'getOutline']), cables: contract(['telegeography-submarine-cables'], ['fetch']), transit: contract(['transit'], ['requestSnapshot', 'getHistory']), }); diff --git a/src/app/sourceComposition.test.mjs b/src/app/sourceComposition.test.mjs index cee9c1246..28f2d3984 100644 --- a/src/app/sourceComposition.test.mjs +++ b/src/app/sourceComposition.test.mjs @@ -37,7 +37,7 @@ test('every acquisition source can be omitted without losing catalog membership' test('all acquisition sources may be absent, and enable fails before initializing or fetching', async (t) => { const actual = catalog({}, t); - assert.equal(actual.layers.length, 37); + assert.equal(actual.layers.length, 38); const manager = new LayerLifecycle( {}, { getSourceAvailability: actual.getSourceAvailability }, @@ -150,6 +150,35 @@ test('GhostMaps obeys source omission, replacement and explicit removal', async assert.equal(fetches, 0); }); +test('News is unavailable without a source and the standalone default reads only same-origin /api/news', async (t) => { + const missing = catalog({}, t); + assert.equal(missing.getSourceAvailability('news')?.available, false); + const manager = new LayerLifecycle( + {}, + { getSourceAvailability: missing.getSourceAvailability }, + ); + manager.register(missing.get('news')); + assert.equal(await manager.setEnabled('news', true), false); + assert.equal(manager.layers.get('news').initialized, false); + assert.equal(createStandaloneLayerSources({ news: null }).news, null); + + const urls = []; + t.mock.method(globalThis, 'fetch', async (url) => { + urls.push(url); + return new Response( + JSON.stringify({ + error: 'news_not_configured', + unavailable: true, + retryable: false, + }), + { status: 503 }, + ); + }); + const standalone = createStandaloneLayerSources().news; + await assert.rejects(standalone.getHotspots(), { unavailable: true }); + assert.deepEqual(urls, ['/api/news/hotspots']); +}); + test('empty Street Level uses the shared unavailable lifecycle without initialization', async (t) => { const actual = catalog({}, t); const manager = new LayerLifecycle( diff --git a/src/data/dataCredits.js b/src/data/dataCredits.js index 29075550c..ede5dc669 100644 --- a/src/data/dataCredits.js +++ b/src/data/dataCredits.js @@ -492,6 +492,14 @@ export const DATA_CREDITS = [ 'licensed under CC BY-NC-SA 4.0. ' + 'Shown as published; reports are S2 assessments, not verified fact.', }, + { + key: 'news', + html: + 'News: every report is credited to its own publisher and links to the original article; ' + + 'pictures are the publishers’ own, shown from their sites with the publisher named. ' + + 'No single provider stands behind the feed. Places, categories, severity and English ' + + 'headlines are derived automatically by the news server and can be wrong.', + }, { key: 'drivebc-cctv', html: diff --git a/src/data/layerState.js b/src/data/layerState.js index 46dadf9a0..2c149a192 100644 --- a/src/data/layerState.js +++ b/src/data/layerState.js @@ -662,6 +662,7 @@ export const LAYER_STATE_REGISTRY = Object.freeze([ token: 'i', disposition: 'enabled-only', }), + Object.freeze({ id: 'news', token: '9', disposition: 'enabled-only' }), Object.freeze({ id: 'radio', token: 'r', diff --git a/src/data/layerState.test.mjs b/src/data/layerState.test.mjs index 9d30e8973..9a8f824d8 100644 --- a/src/data/layerState.test.mjs +++ b/src/data/layerState.test.mjs @@ -203,8 +203,8 @@ function encode(state) { test('production registry is exact, canonical, and rejects incomplete contracts', async () => { assert.equal(validateLayerStateRegistry(), true); - assert.equal(REGISTERED_LAYER_IDS.length, 35); - assert.equal(new Set(REGISTERED_LAYER_IDS).size, 35); + assert.equal(REGISTERED_LAYER_IDS.length, 36); + assert.equal(new Set(REGISTERED_LAYER_IDS).size, 36); assert.ok(REGISTERED_LAYER_IDS.includes('transit')); assert.deepEqual(REGISTERED_LAYER_IDS, [...REGISTERED_LAYER_IDS].sort()); assert.deepEqual(LEGACY_LAYER_STATE_TOKENS, { @@ -243,19 +243,17 @@ test('production registry is exact, canonical, and rejects incomplete contracts' for (const [id, token] of Object.entries(LEGACY_LAYER_STATE_TOKENS)) { assert.equal(LAYER_STATE_TOKEN_RESERVATIONS[id], token); } - assert.equal(nextLayerStateToken(), '9'); + // News took the last single digit: the next tokens are pairs. + assert.equal(nextLayerStateToken(), '00'); assert.equal( nextLayerStateToken({ ...LAYER_STATE_TOKEN_RESERVATIONS, - alpha: '9', - bravo: '00', + alpha: '00', + bravo: '01', }), - '01', + '02', ); - const digitsExhausted = { - ...LAYER_STATE_TOKEN_RESERVATIONS, - ...Object.fromEntries([...'9'].map((digit) => [`prior-${digit}`, digit])), - }; + const digitsExhausted = { ...LAYER_STATE_TOKEN_RESERVATIONS }; assert.equal(nextLayerStateToken(digitsExhausted), '00'); assert.equal( nextLayerStateToken({ ...digitsExhausted, retired: '00', used: '01' }), @@ -306,8 +304,8 @@ test('production registry is exact, canonical, and rejects incomplete contracts' assert.equal( validateLayerStateAllocations(LAYER_STATE_TOKEN_RESERVATIONS, { ...LAYER_STATE_TOKEN_RESERVATIONS, - future: '9', - next: '00', + future: '00', + next: '01', }), true, ); @@ -315,12 +313,12 @@ test('production registry is exact, canonical, and rejects incomplete contracts' () => validateLayerStateAllocations(LAYER_STATE_TOKEN_RESERVATIONS, { ...LAYER_STATE_TOKEN_RESERVATIONS, - future: '00', + future: '01', }), - /next free token 9/, + /next free token 00/, ); const beforeLastDigit = { ...digitsExhausted }; - delete beforeLastDigit['prior-9']; + delete beforeLastDigit.news; assert.equal( validateLayerStateAllocations(beforeLastDigit, { ...beforeLastDigit, @@ -340,10 +338,10 @@ test('production registry is exact, canonical, and rejects incomplete contracts' assert.throws( () => validateLayerStateAllocations( - { ...LAYER_STATE_TOKEN_RESERVATIONS, merged: '9' }, - { ...LAYER_STATE_TOKEN_RESERVATIONS, merged: '9', competing: '9' }, + { ...LAYER_STATE_TOKEN_RESERVATIONS, merged: '00' }, + { ...LAYER_STATE_TOKEN_RESERVATIONS, merged: '00', competing: '00' }, ), - /next free token 00/, + /next free token 01/, ); assert.throws( () => validateLayerStateAllocations({ future: '00' }, { future: '01' }), diff --git a/src/data/layerStateTokenLedger.test.mjs b/src/data/layerStateTokenLedger.test.mjs index d46782378..04d25dce6 100644 --- a/src/data/layerStateTokenLedger.test.mjs +++ b/src/data/layerStateTokenLedger.test.mjs @@ -128,7 +128,7 @@ test('reservation ledger is complete, pinned, and rejects duplicate or malformed { ...parseLayerStateTokenReservations(reservationRows) }, { ...LAYER_STATE_TOKEN_RESERVATIONS }, ); - assert.equal(Object.keys(LAYER_STATE_TOKEN_RESERVATIONS).length, 35); + assert.equal(Object.keys(LAYER_STATE_TOKEN_RESERVATIONS).length, 36); assert.deepEqual( { ...LAYER_STATE_TOKEN_RESERVATIONS }, { @@ -140,6 +140,7 @@ test('reservation ledger is complete, pinned, and rejects duplicate or malformed 'sea-marks': '6', 'ski-pistes': '7', 'drone-airspace': '8', + news: '9', }, ); assert.throws( @@ -165,9 +166,9 @@ test('reservation ledger is complete, pinned, and rejects duplicate or malformed /Duplicate layer-state token reservation/, ); assert.equal( - parseLayerStateTokenReservations([...reservationRows, ['future', '9']]) + parseLayerStateTokenReservations([...reservationRows, ['future', '00']]) .future, - '9', + '00', ); assert.throws( () => @@ -185,14 +186,14 @@ test('reservation ledger is complete, pinned, and rejects duplicate or malformed test('published retired digits and competing PRs advance the merge-time allocation', () => { withPublishedBase( - { rows: [...reservationRows, ['retired-layer', '9']] }, + { rows: [...reservationRows, ['retired-layer', '00']] }, (cwd) => { const published = readPublishedLayerStateReservations('HEAD', cwd); - assert.equal(nextLayerStateToken(published), '00'); + assert.equal(nextLayerStateToken(published), '01'); assert.equal( validateLayerStateAllocations(published, { ...published, - newcomer: '00', + newcomer: '01', }), true, ); @@ -200,15 +201,15 @@ test('published retired digits and competing PRs advance the merge-time allocati () => validateLayerStateAllocations(published, { ...published, - competing: '9', + competing: '00', }), - /next free token 00/, + /next free token 01/, ); assert.throws( () => validateLayerStateAllocations(published, { ...LAYER_STATE_TOKEN_RESERVATIONS, - newcomer: '9', + newcomer: '00', }), /changed or removed: retired-layer/, ); @@ -216,8 +217,8 @@ test('published retired digits and competing PRs advance the merge-time allocati ); }); -test('PR B manually replaces provisional 9 with 00 after PR A publishes 9', () => { - withPublishedBase({ rows: [...reservationRows, ['pr-a', '9']] }, (cwd) => { +test('PR B manually replaces provisional 00 with 01 after PR A publishes 00', () => { + withPublishedBase({ rows: [...reservationRows, ['pr-a', '00']] }, (cwd) => { mkdirSync(path.join(cwd, 'scripts')); const fixtureChecker = path.join( cwd, @@ -238,8 +239,8 @@ test('PR B manually replaces provisional 9 with 00 after PR A publishes 9', () = writeCodecFixture( cwd, - [...reservationRows, ['pr-b', '9']], - [{ id: 'pr-b', token: '9' }], + [...reservationRows, ['pr-b', '00']], + [{ id: 'pr-b', token: '00' }], ); const beforeRebase = runCheck(); assert.equal(beforeRebase.status, 1); @@ -247,10 +248,10 @@ test('PR B manually replaces provisional 9 with 00 after PR A publishes 9', () = writeCodecFixture( cwd, - [...reservationRows, ['pr-a', '9'], ['pr-b', '9']], + [...reservationRows, ['pr-a', '00'], ['pr-b', '00']], [ - { id: 'pr-a', token: '9' }, - { id: 'pr-b', token: '9' }, + { id: 'pr-a', token: '00' }, + { id: 'pr-b', token: '00' }, ], ); const staleRebase = runCheck(); @@ -258,16 +259,16 @@ test('PR B manually replaces provisional 9 with 00 after PR A publishes 9', () = assert.match(staleRebase.stderr, /Duplicate layer-state token reservation/); const published = readPublishedLayerStateReservations('HEAD', cwd); - assert.equal(nextLayerStateToken(published), '00'); - const validBaselineRows = [...reservationRows, ['pr-a', '9']]; - writeCodecFixture(cwd, validBaselineRows, [{ id: 'pr-a', token: '9' }]); + assert.equal(nextLayerStateToken(published), '01'); + const validBaselineRows = [...reservationRows, ['pr-a', '00']]; + writeCodecFixture(cwd, validBaselineRows, [{ id: 'pr-a', token: '00' }]); const helper = spawnSync( process.execPath, [realpathSync(fixtureNext), 'pr-b'], { cwd, encoding: 'utf8' }, ); assert.equal(helper.status, 0, helper.stderr); - assert.match(helper.stdout, /pr-b: 00/); + assert.match(helper.stdout, /pr-b: 01/); assert.deepEqual( JSON.parse(readFileSync(path.join(cwd, LEDGER_PATH), 'utf8')), validBaselineRows, @@ -275,26 +276,27 @@ test('PR B manually replaces provisional 9 with 00 after PR A publishes 9', () = ); writeCodecFixture( cwd, - [...reservationRows, ['pr-a', '9'], ['pr-b', '00']], + [...reservationRows, ['pr-a', '00'], ['pr-b', '01']], [ - { id: 'pr-a', token: '9' }, - { id: 'pr-b', token: '00' }, + { id: 'pr-a', token: '00' }, + { id: 'pr-b', token: '01' }, ], ); const corrected = runCheck(); assert.equal(corrected.status, 0, corrected.stderr); - assert.match(corrected.stdout, /36 published, 1 new/); + assert.match(corrected.stdout, /37 published, 1 new/); }); }); test('allocation batches cross the last digit and base-36 pair boundaries in order', () => { - const digitRows = [...'9'].map((digit) => [`retired-${digit}`, digit]); + // News holds the last digit, 9: the ledger has no free digit left. + const digitRows = []; const allDigits = parseLayerStateTokenReservations([ ...reservationRows, ...digitRows, ]); const beforeNine = { ...allDigits }; - delete beforeNine['retired-9']; + delete beforeNine.news; assert.equal( validateLayerStateAllocations(beforeNine, { ...beforeNine, @@ -340,10 +342,8 @@ test('allocation batches cross the last digit and base-36 pair boundaries in ord test('an isolated valid two-character fixture round-trips an l field beyond the old 64-character cap', async () => { const cwd = mkdtempSync(path.join(tmpdir(), 'gev-layer-token-width-')); try { - const priorDigits = [...'9'].map((digit) => [ - `qa-prior-digit-${digit}`, - digit, - ]); + // News holds the last digit: no prior digit to fill. + const priorDigits = []; const fixtureLayers = ['00', '01', '02', '03'].map((token) => ({ id: `qa-layer-${token}`, token, @@ -377,7 +377,7 @@ test('an isolated valid two-character fixture round-trips an l field beyond the const params = new URLSearchParams([['v', '2']]); codec.encodeLayerStateParams(params, state); assert.ok(params.get('l').length > 64, 'fixture must cross the old cap'); - assert.equal(params.get('l').length, 81); + assert.equal(params.get('l').length, 83); const restored = codec.decodeLayerStateParams(params); assert.deepEqual(restored?.enabledLayerIds, expectedLayerIds); assert.deepEqual(restored?.options, state.options); @@ -395,7 +395,7 @@ test('checker reads a complete future base ledger and rejects retired-token reus }, (cwd) => { const published = readPublishedLayerStateReservations('HEAD', cwd); - assert.equal(Object.keys(published).length, 36); + assert.equal(Object.keys(published).length, 37); assert.equal(published['retired-layer'], '00'); assert.throws( () => diff --git a/src/data/layerStateTokenReservations.json b/src/data/layerStateTokenReservations.json index 836112713..03c977426 100644 --- a/src/data/layerStateTokenReservations.json +++ b/src/data/layerStateTokenReservations.json @@ -18,6 +18,7 @@ ["military", "m"], ["military-awareness", "g"], ["military-installations", "i"], + ["news", "9"], ["radio", "r"], ["recent-imagery", "1"], ["rocket-launches", "x"], diff --git a/src/i18n/locales/ar.json b/src/i18n/locales/ar.json index 59cd4caa6..f779fc9e9 100644 --- a/src/i18n/locales/ar.json +++ b/src/i18n/locales/ar.json @@ -1,5 +1,23 @@ { "News feed unavailable": "موجز الأخبار غير متاح", + "Developing: {name}": "تطورات: {name}", + "{count} events today": { + "zero": "{count} حدث اليوم", + "one": "حدث واحد اليوم ({count})", + "two": "حدثان اليوم ({count})", + "few": "{count} أحداث اليوم", + "many": "{count} حدثًا اليوم", + "other": "{count} حدث اليوم" + }, + "{count} reports today": { + "zero": "{count} تقرير اليوم", + "one": "تقرير واحد اليوم ({count})", + "two": "تقريران اليوم ({count})", + "few": "{count} تقارير اليوم", + "many": "{count} تقريرًا اليوم", + "other": "{count} تقرير اليوم" + }, + "Last 24 h from curated hotspots. Each report links to its publisher; places and categories are read from the text automatically and can be wrong. Side labels describe the source, not whether a report is true.": "آخر 24 ساعة من بؤر مختارة. يرتبط كل تقرير بناشره؛ تُستخرج الأماكن والفئات من النص تلقائيًا وقد تكون خاطئة. تصف تسميات الأطراف المصدر، لا صحة التقرير.", "Disputed: {name}": "منطقة متنازع عليها: {name}", "Administered by {holder} · claimed by {claimant}": "تديرها {holder} · تطالب بها {claimant}", "Self-administered · claimed by {claimant}": "تدير نفسها · تطالب بها {claimant}", @@ -55,6 +73,34 @@ "News feed not configured on this server": "موجز الأخبار غير مهيأ على هذا الخادم", "Malformed news hotspots response": "استجابة بؤر الأخبار غير صالحة", "Malformed news feed response": "استجابة موجز الأخبار غير صالحة", + "{place} (placed by model)": "{place} (حدده النموذج)", + "English headline by the model": "عنوان إنجليزي من النموذج", + "Not placed on the map": "غير موضوع على الخريطة", + "Close": "إغلاق", + "Any severity": "أي درجة خطورة", + "{severity} and above": "{severity} فأعلى", + "{severity} only": "{severity} فقط", + "All categories": "كل الفئات", + "Reading the news…": "جارٍ قراءة الأخبار…", + "News, last 24 hours": "الأخبار، آخر 24 ساعة", + "Last 24 h": "آخر 24 ساعة", + "Hotspots": "بؤر ساخنة", + "Severity": "الخطورة", + "Category": "الفئة", + "Include minor news": "تضمين الأخبار الثانوية", + "Show event cards": "إظهار بطاقات الأحداث", + "In view": "في مجال الرؤية", + "Nothing reported near here in the last 24 h": "لم يُبلَّغ عن شيء قريب من هنا في آخر 24 ساعة", + "Latest news": "آخر الأخبار", + "No news matches these filters in the last 24 h": "لا أخبار تطابق هذه المرشحات في آخر 24 ساعة", + "Load older news": "تحميل أخبار أقدم", + "How to read the map": "كيف تقرأ الخريطة", + "Colour: severity · icon: type of event": "اللون: الخطورة · الرمز: نوع الحدث", + "Solid rim: reported by both sides or independently. Dashed rim: a claim. Thin rim: one source, or one side’s own press.": "إطار متصل: أورده الطرفان أو مصدر مستقل. إطار متقطع: ادعاء. إطار رفيع: مصدر واحد، أو إعلام أحد الطرفين.", + "Larger: more sources · fainter: older. Picture card: a major or fast-growing event with two or more sources.": "أكبر: مصادر أكثر · أبهت: أقدم. بطاقة بصورة: حدث جسيم أو متسارع من مصدرين أو أكثر.", + "Side labels describe the source, not whether a report is true.": "تصف تسميات الأطراف المصدر، لا صحة التقرير.", + "Exit cockpit to fly to a news report": "اخرج من القمرة للانتقال إلى خبر", + "News items in the feed": "عدد الأخبار في الموجز", "NO PLACE LEFT BEHIND": "لا مكان يُترك خلفنا", "Initializing photorealistic world...": "جارٍ تهيئة العالم الواقعي…", "Configuring viewer...": "جارٍ إعداد العارض…", diff --git a/src/i18n/locales/de.json b/src/i18n/locales/de.json index 9421361bc..43b913524 100644 --- a/src/i18n/locales/de.json +++ b/src/i18n/locales/de.json @@ -1,5 +1,15 @@ { "News feed unavailable": "Nachrichtenfeed nicht verfügbar", + "Developing: {name}": "In Entwicklung: {name}", + "{count} events today": { + "one": "{count} Ereignis heute", + "other": "{count} Ereignisse heute" + }, + "{count} reports today": { + "one": "{count} Meldung heute", + "other": "{count} Meldungen heute" + }, + "Last 24 h from curated hotspots. Each report links to its publisher; places and categories are read from the text automatically and can be wrong. Side labels describe the source, not whether a report is true.": "Letzte 24 h aus ausgewählten Brennpunkten. Jede Meldung verlinkt auf ihren Herausgeber; Orte und Kategorien werden automatisch aus dem Text gelesen und können falsch sein. Seitenangaben beschreiben die Quelle, nicht ob eine Meldung stimmt.", "Disputed: {name}": "Umstritten: {name}", "Administered by {holder} · claimed by {claimant}": "Verwaltet von {holder} · beansprucht von {claimant}", "Self-administered · claimed by {claimant}": "Selbstverwaltet · beansprucht von {claimant}", @@ -51,6 +61,34 @@ "News feed not configured on this server": "Nachrichtenfeed auf diesem Server nicht eingerichtet", "Malformed news hotspots response": "Fehlerhafte Antwort zu Nachrichten-Brennpunkten", "Malformed news feed response": "Fehlerhafte Antwort des Nachrichtenfeeds", + "{place} (placed by model)": "{place} (vom Modell verortet)", + "English headline by the model": "Englische Schlagzeile vom Modell", + "Not placed on the map": "Nicht auf der Karte verortet", + "Close": "Schließen", + "Any severity": "Jeder Schweregrad", + "{severity} and above": "{severity} und höher", + "{severity} only": "Nur {severity}", + "All categories": "Alle Kategorien", + "Reading the news…": "Nachrichten werden gelesen…", + "News, last 24 hours": "Nachrichten der letzten 24 Stunden", + "Last 24 h": "Letzte 24 Std.", + "Hotspots": "Brennpunkte", + "Severity": "Schweregrad", + "Category": "Kategorie", + "Include minor news": "Nebensächliche Meldungen einbeziehen", + "Show event cards": "Ereigniskarten zeigen", + "In view": "Im Blick", + "Nothing reported near here in the last 24 h": "In den letzten 24 h nichts in der Nähe gemeldet", + "Latest news": "Neueste Nachrichten", + "No news matches these filters in the last 24 h": "Keine Nachrichten der letzten 24 h passen zu diesen Filtern", + "Load older news": "Ältere Nachrichten laden", + "How to read the map": "So liest man die Karte", + "Colour: severity · icon: type of event": "Farbe: Schweregrad · Symbol: Art des Ereignisses", + "Solid rim: reported by both sides or independently. Dashed rim: a claim. Thin rim: one source, or one side’s own press.": "Durchgehender Rand: von beiden Seiten oder unabhängig gemeldet. Gestrichelter Rand: eine Behauptung. Dünner Rand: eine Quelle oder die eigene Presse einer Seite.", + "Larger: more sources · fainter: older. Picture card: a major or fast-growing event with two or more sources.": "Größer: mehr Quellen · blasser: älter. Bildkarte: ein schweres oder schnell wachsendes Ereignis mit zwei oder mehr Quellen.", + "Side labels describe the source, not whether a report is true.": "Seitenangaben beschreiben die Quelle, nicht ob eine Meldung stimmt.", + "Exit cockpit to fly to a news report": "Cockpit verlassen, um zu einer Meldung zu fliegen", + "News items in the feed": "Meldungen im Feed", "Flying to Austin, TX...": "Flug nach Austin, TX...", "Restoring shared view...": "Geteilte Ansicht wird wiederhergestellt...", "Configuring viewer...": "Viewer wird konfiguriert...", diff --git a/src/i18n/locales/es.json b/src/i18n/locales/es.json index 914a85171..ba4fa99a9 100644 --- a/src/i18n/locales/es.json +++ b/src/i18n/locales/es.json @@ -1,5 +1,17 @@ { "News feed unavailable": "Noticias no disponibles", + "Developing: {name}": "En desarrollo: {name}", + "{count} events today": { + "one": "{count} suceso hoy", + "many": "{count} sucesos hoy", + "other": "{count} sucesos hoy" + }, + "{count} reports today": { + "one": "{count} noticia hoy", + "many": "{count} noticias hoy", + "other": "{count} noticias hoy" + }, + "Last 24 h from curated hotspots. Each report links to its publisher; places and categories are read from the text automatically and can be wrong. Side labels describe the source, not whether a report is true.": "Últimas 24 h de focos seleccionados. Cada noticia enlaza a su medio; los lugares y categorías se leen del texto automáticamente y pueden ser erróneos. Las etiquetas de bando describen la fuente, no si la noticia es cierta.", "Disputed: {name}": "En disputa: {name}", "Administered by {holder} · claimed by {claimant}": "Administrado por {holder} · reclamado por {claimant}", "Self-administered · claimed by {claimant}": "Autogobernado · reclamado por {claimant}", @@ -52,6 +64,34 @@ "News feed not configured on this server": "Noticias no configuradas en este servidor", "Malformed news hotspots response": "Respuesta de focos de noticias mal formada", "Malformed news feed response": "Respuesta de noticias mal formada", + "{place} (placed by model)": "{place} (ubicado por el modelo)", + "English headline by the model": "Titular en inglés del modelo", + "Not placed on the map": "Sin ubicar en el mapa", + "Close": "Cerrar", + "Any severity": "Cualquier gravedad", + "{severity} and above": "{severity} o más", + "{severity} only": "Solo {severity}", + "All categories": "Todas las categorías", + "Reading the news…": "Leyendo las noticias…", + "News, last 24 hours": "Noticias de las últimas 24 horas", + "Last 24 h": "Últimas 24 h", + "Hotspots": "Focos", + "Severity": "Gravedad", + "Category": "Categoría", + "Include minor news": "Incluir noticias menores", + "Show event cards": "Mostrar tarjetas de sucesos", + "In view": "A la vista", + "Nothing reported near here in the last 24 h": "Nada informado cerca de aquí en las últimas 24 h", + "Latest news": "Últimas noticias", + "No news matches these filters in the last 24 h": "Ninguna noticia de las últimas 24 h coincide con estos filtros", + "Load older news": "Cargar noticias anteriores", + "How to read the map": "Cómo leer el mapa", + "Colour: severity · icon: type of event": "Color: gravedad · icono: tipo de suceso", + "Solid rim: reported by both sides or independently. Dashed rim: a claim. Thin rim: one source, or one side’s own press.": "Borde continuo: informado por ambos bandos o de forma independiente. Borde discontinuo: una afirmación. Borde fino: una fuente, o la prensa de un bando.", + "Larger: more sources · fainter: older. Picture card: a major or fast-growing event with two or more sources.": "Más grande: más fuentes · más tenue: más antiguo. Tarjeta con imagen: un suceso grave o en rápido crecimiento con dos o más fuentes.", + "Side labels describe the source, not whether a report is true.": "Las etiquetas de bando describen la fuente, no si la noticia es cierta.", + "Exit cockpit to fly to a news report": "Sal de la cabina para volar a una noticia", + "News items in the feed": "Noticias en la lista", "NO PLACE LEFT BEHIND": "NINGÚN RINCÓN SIN VIGILAR", "Initializing photorealistic world...": "Inicializando el mundo fotorrealista...", "Configuring viewer...": "Configurando el visor...", diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json index f01ca2956..aae0bbb7d 100644 --- a/src/i18n/locales/fr.json +++ b/src/i18n/locales/fr.json @@ -1,5 +1,17 @@ { "News feed unavailable": "Fil d’actualités indisponible", + "Developing: {name}": "En cours : {name}", + "{count} events today": { + "one": "{count} événement aujourd’hui", + "many": "{count} événements aujourd’hui", + "other": "{count} événements aujourd’hui" + }, + "{count} reports today": { + "one": "{count} article aujourd’hui", + "many": "{count} articles aujourd’hui", + "other": "{count} articles aujourd’hui" + }, + "Last 24 h from curated hotspots. Each report links to its publisher; places and categories are read from the text automatically and can be wrong. Side labels describe the source, not whether a report is true.": "Dernières 24 h des foyers retenus. Chaque article renvoie à son éditeur ; lieux et catégories sont lus automatiquement dans le texte et peuvent être faux. Les étiquettes de camp décrivent la source, pas la véracité de l’article.", "Disputed: {name}": "Contesté : {name}", "Administered by {holder} · claimed by {claimant}": "Administré par {holder} · revendiqué par {claimant}", "Self-administered · claimed by {claimant}": "Autoadministré · revendiqué par {claimant}", @@ -52,6 +64,34 @@ "News feed not configured on this server": "Fil d’actualités non configuré sur ce serveur", "Malformed news hotspots response": "Réponse des foyers d’actualité mal formée", "Malformed news feed response": "Réponse du fil d’actualités mal formée", + "{place} (placed by model)": "{place} (placé par le modèle)", + "English headline by the model": "Titre anglais du modèle", + "Not placed on the map": "Non placé sur la carte", + "Close": "Fermer", + "Any severity": "Toute gravité", + "{severity} and above": "{severity} et plus", + "{severity} only": "{severity} uniquement", + "All categories": "Toutes les catégories", + "Reading the news…": "Lecture des actualités…", + "News, last 24 hours": "Actualités des dernières 24 heures", + "Last 24 h": "Dernières 24 h", + "Hotspots": "Foyers", + "Severity": "Gravité", + "Category": "Catégorie", + "Include minor news": "Inclure les actualités secondaires", + "Show event cards": "Afficher les cartes d’événement", + "In view": "Dans la vue", + "Nothing reported near here in the last 24 h": "Rien de signalé près d’ici ces dernières 24 h", + "Latest news": "Dernières actualités", + "No news matches these filters in the last 24 h": "Aucune actualité des dernières 24 h ne correspond à ces filtres", + "Load older news": "Charger des actualités plus anciennes", + "How to read the map": "Comment lire la carte", + "Colour: severity · icon: type of event": "Couleur : gravité · icône : type d’événement", + "Solid rim: reported by both sides or independently. Dashed rim: a claim. Thin rim: one source, or one side’s own press.": "Bord plein : rapporté par les deux camps ou de façon indépendante. Bord en tirets : une affirmation. Bord fin : une source, ou la presse d’un camp.", + "Larger: more sources · fainter: older. Picture card: a major or fast-growing event with two or more sources.": "Plus grand : plus de sources · plus pâle : plus ancien. Carte illustrée : un événement majeur ou en forte croissance, avec au moins deux sources.", + "Side labels describe the source, not whether a report is true.": "Les étiquettes de camp décrivent la source, pas la véracité de l’article.", + "Exit cockpit to fly to a news report": "Quittez le cockpit pour aller à un article", + "News items in the feed": "Articles dans le fil", "Pick a shape, then click the map.": "Choisissez une forme, puis cliquez sur la carte.", "Enter to place the pin, Esc to cancel.": "Enter pour poser l'épingle, Esc pour annuler.", "Click where the pin goes.": "Cliquez à l'endroit où poser l'épingle.", diff --git a/src/i18n/locales/it.json b/src/i18n/locales/it.json index dcaf4855c..cb9c27098 100644 --- a/src/i18n/locales/it.json +++ b/src/i18n/locales/it.json @@ -1,5 +1,17 @@ { "News feed unavailable": "Feed delle notizie non disponibile", + "Developing: {name}": "In sviluppo: {name}", + "{count} events today": { + "one": "{count} evento oggi", + "many": "{count} eventi oggi", + "other": "{count} eventi oggi" + }, + "{count} reports today": { + "one": "{count} notizia oggi", + "many": "{count} notizie oggi", + "other": "{count} notizie oggi" + }, + "Last 24 h from curated hotspots. Each report links to its publisher; places and categories are read from the text automatically and can be wrong. Side labels describe the source, not whether a report is true.": "Ultime 24 h dai focolai selezionati. Ogni notizia rimanda al suo editore; luoghi e categorie sono letti automaticamente dal testo e possono essere errati. Le etichette di parte descrivono la fonte, non se la notizia è vera.", "Disputed: {name}": "Conteso: {name}", "Administered by {holder} · claimed by {claimant}": "Amministrato da {holder} · rivendicato da {claimant}", "Self-administered · claimed by {claimant}": "Autogovernato · rivendicato da {claimant}", @@ -52,6 +64,34 @@ "News feed not configured on this server": "Feed delle notizie non configurato su questo server", "Malformed news hotspots response": "Risposta dei focolai di notizie non valida", "Malformed news feed response": "Risposta del feed delle notizie non valida", + "{place} (placed by model)": "{place} (collocato dal modello)", + "English headline by the model": "Titolo inglese del modello", + "Not placed on the map": "Non collocato sulla mappa", + "Close": "Chiudi", + "Any severity": "Qualsiasi gravità", + "{severity} and above": "{severity} e oltre", + "{severity} only": "Solo {severity}", + "All categories": "Tutte le categorie", + "Reading the news…": "Lettura delle notizie…", + "News, last 24 hours": "Notizie delle ultime 24 ore", + "Last 24 h": "Ultime 24 h", + "Hotspots": "Focolai", + "Severity": "Gravità", + "Category": "Categoria", + "Include minor news": "Includi notizie minori", + "Show event cards": "Mostra le schede degli eventi", + "In view": "In vista", + "Nothing reported near here in the last 24 h": "Nulla segnalato qui vicino nelle ultime 24 h", + "Latest news": "Ultime notizie", + "No news matches these filters in the last 24 h": "Nessuna notizia delle ultime 24 h corrisponde a questi filtri", + "Load older news": "Carica notizie precedenti", + "How to read the map": "Come leggere la mappa", + "Colour: severity · icon: type of event": "Colore: gravità · icona: tipo di evento", + "Solid rim: reported by both sides or independently. Dashed rim: a claim. Thin rim: one source, or one side’s own press.": "Bordo pieno: riportato da entrambe le parti o in modo indipendente. Bordo tratteggiato: un’affermazione. Bordo sottile: una fonte, o la stampa di una parte.", + "Larger: more sources · fainter: older. Picture card: a major or fast-growing event with two or more sources.": "Più grande: più fonti · più tenue: più vecchio. Scheda con immagine: un evento grave o in rapida crescita con due o più fonti.", + "Side labels describe the source, not whether a report is true.": "Le etichette di parte descrivono la fonte, non se la notizia è vera.", + "Exit cockpit to fly to a news report": "Esci dalla cabina per volare a una notizia", + "News items in the feed": "Notizie nel feed", "Pick a shape, then click the map.": "Scegli una forma, poi fai clic sulla mappa.", "Enter to place the pin, Esc to cancel.": "Premi Enter per posizionare il segnaposto, Esc per annullare.", "Click where the pin goes.": "Fai clic dove va il segnaposto.", diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.json index 743fcb71c..fc62c1703 100644 --- a/src/i18n/locales/ja.json +++ b/src/i18n/locales/ja.json @@ -1,5 +1,13 @@ { "News feed unavailable": "ニュースフィードを利用できません", + "Developing: {name}": "進行中: {name}", + "{count} events today": { + "other": "本日の出来事 {count}件" + }, + "{count} reports today": { + "other": "本日の報道 {count}件" + }, + "Last 24 h from curated hotspots. Each report links to its publisher; places and categories are read from the text automatically and can be wrong. Side labels describe the source, not whether a report is true.": "厳選したホットスポットの直近24時間。各報道は発信元にリンクします。場所とカテゴリは本文から自動で読み取るため誤りがあり得ます。陣営ラベルは情報源を示すもので、報道の真偽ではありません。", "Disputed: {name}": "係争地: {name}", "Administered by {holder} · claimed by {claimant}": "{holder}が施政 · {claimant}が領有を主張", "Self-administered · claimed by {claimant}": "自治 · {claimant}が領有を主張", @@ -50,6 +58,34 @@ "News feed not configured on this server": "このサーバーではニュースフィードが設定されていません", "Malformed news hotspots response": "ニュースのホットスポット応答の形式が不正です", "Malformed news feed response": "ニュースフィードの応答の形式が不正です", + "{place} (placed by model)": "{place}(モデルが推定)", + "English headline by the model": "モデルによる英語の見出し", + "Not placed on the map": "地図上に配置されていません", + "Close": "閉じる", + "Any severity": "すべての深刻度", + "{severity} and above": "{severity}以上", + "{severity} only": "{severity}のみ", + "All categories": "すべてのカテゴリ", + "Reading the news…": "ニュースを読み込み中…", + "News, last 24 hours": "直近24時間のニュース", + "Last 24 h": "直近24時間", + "Hotspots": "ホットスポット", + "Severity": "深刻度", + "Category": "カテゴリ", + "Include minor news": "軽微なニュースも含める", + "Show event cards": "イベントカードを表示", + "In view": "表示範囲内", + "Nothing reported near here in the last 24 h": "直近24時間、この付近の報道はありません", + "Latest news": "最新ニュース", + "No news matches these filters in the last 24 h": "直近24時間で条件に合うニュースはありません", + "Load older news": "以前のニュースを読み込む", + "How to read the map": "地図の見方", + "Colour: severity · icon: type of event": "色: 深刻度 · アイコン: 出来事の種類", + "Solid rim: reported by both sides or independently. Dashed rim: a claim. Thin rim: one source, or one side’s own press.": "実線の縁: 双方または独立した情報源が報道。破線の縁: 主張。細い縁: 単一の情報源、または一方の陣営のメディア。", + "Larger: more sources · fainter: older. Picture card: a major or fast-growing event with two or more sources.": "大きい: 情報源が多い · 薄い: 古い。画像カード: 情報源が2件以上ある深刻な、または急拡大中の出来事。", + "Side labels describe the source, not whether a report is true.": "陣営ラベルは情報源を示すもので、報道の真偽ではありません。", + "Exit cockpit to fly to a news report": "ニュースへ移動するにはコックピットを終了してください", + "News items in the feed": "フィード内のニュース数", "Pick a shape, then click the map.": "図形を選んでから、地図をクリックしてください。", "Enter to place the pin, Esc to cancel.": "Enterでピンを配置、Escでキャンセル。", "Click where the pin goes.": "ピンを置く場所をクリックしてください。", diff --git a/src/i18n/locales/pt.json b/src/i18n/locales/pt.json index 2068c08b6..a5da05da8 100644 --- a/src/i18n/locales/pt.json +++ b/src/i18n/locales/pt.json @@ -1,5 +1,17 @@ { "News feed unavailable": "Feed de notícias indisponível", + "Developing: {name}": "Em desenvolvimento: {name}", + "{count} events today": { + "one": "{count} evento hoje", + "many": "{count} eventos hoje", + "other": "{count} eventos hoje" + }, + "{count} reports today": { + "one": "{count} notícia hoje", + "many": "{count} notícias hoje", + "other": "{count} notícias hoje" + }, + "Last 24 h from curated hotspots. Each report links to its publisher; places and categories are read from the text automatically and can be wrong. Side labels describe the source, not whether a report is true.": "Últimas 24 h dos focos selecionados. Cada notícia leva ao seu editor; locais e categorias são lidos do texto automaticamente e podem estar errados. Os rótulos de lado descrevem a fonte, não se a notícia é verdadeira.", "Disputed: {name}": "Em disputa: {name}", "Administered by {holder} · claimed by {claimant}": "Administrado por {holder} · reivindicado por {claimant}", "Self-administered · claimed by {claimant}": "Autogovernado · reivindicado por {claimant}", @@ -52,6 +64,34 @@ "News feed not configured on this server": "Feed de notícias não configurado neste servidor", "Malformed news hotspots response": "Resposta de focos de notícias malformada", "Malformed news feed response": "Resposta do feed de notícias malformada", + "{place} (placed by model)": "{place} (localizado pelo modelo)", + "English headline by the model": "Manchete em inglês do modelo", + "Not placed on the map": "Não localizado no mapa", + "Close": "Fechar", + "Any severity": "Qualquer gravidade", + "{severity} and above": "{severity} ou mais", + "{severity} only": "Apenas {severity}", + "All categories": "Todas as categorias", + "Reading the news…": "Lendo as notícias…", + "News, last 24 hours": "Notícias das últimas 24 horas", + "Last 24 h": "Últimas 24 h", + "Hotspots": "Focos", + "Severity": "Gravidade", + "Category": "Categoria", + "Include minor news": "Incluir notícias menores", + "Show event cards": "Mostrar cartões de eventos", + "In view": "Na vista", + "Nothing reported near here in the last 24 h": "Nada noticiado aqui perto nas últimas 24 h", + "Latest news": "Últimas notícias", + "No news matches these filters in the last 24 h": "Nenhuma notícia das últimas 24 h corresponde a estes filtros", + "Load older news": "Carregar notícias anteriores", + "How to read the map": "Como ler o mapa", + "Colour: severity · icon: type of event": "Cor: gravidade · ícone: tipo de evento", + "Solid rim: reported by both sides or independently. Dashed rim: a claim. Thin rim: one source, or one side’s own press.": "Borda contínua: noticiado por ambos os lados ou de forma independente. Borda tracejada: uma alegação. Borda fina: uma fonte, ou a imprensa de um lado.", + "Larger: more sources · fainter: older. Picture card: a major or fast-growing event with two or more sources.": "Maior: mais fontes · mais tênue: mais antigo. Cartão com imagem: um evento grave ou em rápido crescimento com duas ou mais fontes.", + "Side labels describe the source, not whether a report is true.": "Os rótulos de lado descrevem a fonte, não se a notícia é verdadeira.", + "Exit cockpit to fly to a news report": "Saia da cabine para voar até uma notícia", + "News items in the feed": "Notícias no feed", "Pick a shape, then click the map.": "Escolha uma forma e clique no mapa.", "Enter to place the pin, Esc to cancel.": "Enter para colocar o marcador, Esc para cancelar.", "Click where the pin goes.": "Clique onde o marcador deve ficar.", diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json index e6df84b68..2725ef272 100644 --- a/src/i18n/locales/ru.json +++ b/src/i18n/locales/ru.json @@ -1,5 +1,19 @@ { "News feed unavailable": "Лента новостей недоступна", + "Developing: {name}": "Развивается: {name}", + "{count} events today": { + "one": "{count} событие сегодня", + "few": "{count} события сегодня", + "many": "{count} событий сегодня", + "other": "{count} события сегодня" + }, + "{count} reports today": { + "one": "{count} сообщение сегодня", + "few": "{count} сообщения сегодня", + "many": "{count} сообщений сегодня", + "other": "{count} сообщения сегодня" + }, + "Last 24 h from curated hotspots. Each report links to its publisher; places and categories are read from the text automatically and can be wrong. Side labels describe the source, not whether a report is true.": "Последние 24 ч по выбранным горячим точкам. Каждое сообщение ведёт к своему изданию; места и категории определяются по тексту автоматически и могут быть ошибочны. Метки сторон описывают источник, а не достоверность сообщения.", "Disputed: {name}": "Спорная территория: {name}", "Administered by {holder} · claimed by {claimant}": "Под управлением: {holder} · претендует: {claimant}", "Self-administered · claimed by {claimant}": "Самоуправляемая · претендует: {claimant}", @@ -53,6 +67,34 @@ "News feed not configured on this server": "Лента новостей не настроена на этом сервере", "Malformed news hotspots response": "Некорректный ответ горячих точек новостей", "Malformed news feed response": "Некорректный ответ ленты новостей", + "{place} (placed by model)": "{place} (место определила модель)", + "English headline by the model": "Английский заголовок от модели", + "Not placed on the map": "Не отмечено на карте", + "Close": "Закрыть", + "Any severity": "Любая тяжесть", + "{severity} and above": "{severity} и выше", + "{severity} only": "Только {severity}", + "All categories": "Все категории", + "Reading the news…": "Читаем новости…", + "News, last 24 hours": "Новости за последние 24 часа", + "Last 24 h": "За 24 ч", + "Hotspots": "Горячие точки", + "Severity": "Тяжесть", + "Category": "Категория", + "Include minor news": "Показывать второстепенные новости", + "Show event cards": "Показывать карточки событий", + "In view": "В поле зрения", + "Nothing reported near here in the last 24 h": "За последние 24 ч поблизости ничего не сообщалось", + "Latest news": "Последние новости", + "No news matches these filters in the last 24 h": "За последние 24 ч нет новостей по этим фильтрам", + "Load older news": "Загрузить более ранние новости", + "How to read the map": "Как читать карту", + "Colour: severity · icon: type of event": "Цвет: тяжесть · значок: тип события", + "Solid rim: reported by both sides or independently. Dashed rim: a claim. Thin rim: one source, or one side’s own press.": "Сплошной обод: сообщают обе стороны или независимые источники. Пунктирный обод: заявление. Тонкий обод: один источник или пресса одной стороны.", + "Larger: more sources · fainter: older. Picture card: a major or fast-growing event with two or more sources.": "Крупнее: больше источников · бледнее: старше. Карточка с фото: крупное или быстро растущее событие от двух и более источников.", + "Side labels describe the source, not whether a report is true.": "Метки сторон описывают источник, а не достоверность сообщения.", + "Exit cockpit to fly to a news report": "Выйдите из кабины, чтобы перелететь к сообщению", + "News items in the feed": "Новостей в ленте", "Flying to Austin, TX...": "Перелёт в Остин, Техас...", "Restoring shared view...": "Восстановление общего вида...", "Initializing systems...": "Инициализация систем...", diff --git a/src/i18n/locales/uk.json b/src/i18n/locales/uk.json index 41f6f1207..77aa0f593 100644 --- a/src/i18n/locales/uk.json +++ b/src/i18n/locales/uk.json @@ -1,5 +1,19 @@ { "News feed unavailable": "Стрічка новин недоступна", + "Developing: {name}": "Розвивається: {name}", + "{count} events today": { + "one": "{count} подія сьогодні", + "few": "{count} події сьогодні", + "many": "{count} подій сьогодні", + "other": "{count} події сьогодні" + }, + "{count} reports today": { + "one": "{count} повідомлення сьогодні", + "few": "{count} повідомлення сьогодні", + "many": "{count} повідомлень сьогодні", + "other": "{count} повідомлення сьогодні" + }, + "Last 24 h from curated hotspots. Each report links to its publisher; places and categories are read from the text automatically and can be wrong. Side labels describe the source, not whether a report is true.": "Останні 24 год за вибраними гарячими точками. Кожне повідомлення веде до свого видання; місця й категорії визначаються з тексту автоматично і можуть бути хибними. Позначки сторін описують джерело, а не правдивість повідомлення.", "Disputed: {name}": "Спірна територія: {name}", "Administered by {holder} · claimed by {claimant}": "Під управлінням: {holder} · претендує: {claimant}", "Self-administered · claimed by {claimant}": "Самоврядна · претендує: {claimant}", @@ -53,6 +67,34 @@ "News feed not configured on this server": "Стрічку новин не налаштовано на цьому сервері", "Malformed news hotspots response": "Некоректна відповідь гарячих точок новин", "Malformed news feed response": "Некоректна відповідь стрічки новин", + "{place} (placed by model)": "{place} (місце визначила модель)", + "English headline by the model": "Англійський заголовок від моделі", + "Not placed on the map": "Не позначено на мапі", + "Close": "Закрити", + "Any severity": "Будь-яка тяжкість", + "{severity} and above": "{severity} і вище", + "{severity} only": "Лише {severity}", + "All categories": "Усі категорії", + "Reading the news…": "Читаємо новини…", + "News, last 24 hours": "Новини за останні 24 години", + "Last 24 h": "За 24 год", + "Hotspots": "Гарячі точки", + "Severity": "Тяжкість", + "Category": "Категорія", + "Include minor news": "Показувати другорядні новини", + "Show event cards": "Показувати картки подій", + "In view": "У полі зору", + "Nothing reported near here in the last 24 h": "За останні 24 год поблизу нічого не повідомлялося", + "Latest news": "Останні новини", + "No news matches these filters in the last 24 h": "За останні 24 год немає новин за цими фільтрами", + "Load older news": "Завантажити давніші новини", + "How to read the map": "Як читати мапу", + "Colour: severity · icon: type of event": "Колір: тяжкість · значок: тип події", + "Solid rim: reported by both sides or independently. Dashed rim: a claim. Thin rim: one source, or one side’s own press.": "Суцільний обідок: повідомляють обидві сторони або незалежні джерела. Пунктирний обідок: заява. Тонкий обідок: одне джерело або преса однієї сторони.", + "Larger: more sources · fainter: older. Picture card: a major or fast-growing event with two or more sources.": "Більше: більше джерел · блідіше: давніше. Картка з фото: велика або швидко зростаюча подія з двох і більше джерел.", + "Side labels describe the source, not whether a report is true.": "Позначки сторін описують джерело, а не правдивість повідомлення.", + "Exit cockpit to fly to a news report": "Вийдіть із кабіни, щоб перелетіти до повідомлення", + "News items in the feed": "Новин у стрічці", "Pick a shape, then click the map.": "Виберіть фігуру й клацніть на карті.", "Enter to place the pin, Esc to cancel.": "Enter — поставити мітку, Esc — скасувати.", "Click where the pin goes.": "Клацніть там, де має бути мітка.", diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json index 30a4d8807..0b398051d 100644 --- a/src/i18n/locales/zh-CN.json +++ b/src/i18n/locales/zh-CN.json @@ -1,5 +1,13 @@ { "News feed unavailable": "新闻源不可用", + "Developing: {name}": "事态发展:{name}", + "{count} events today": { + "other": "今日 {count} 起事件" + }, + "{count} reports today": { + "other": "今日 {count} 条报道" + }, + "Last 24 h from curated hotspots. Each report links to its publisher; places and categories are read from the text automatically and can be wrong. Side labels describe the source, not whether a report is true.": "精选热点的最近 24 小时。每条报道都链接到其发布者;地点和类别由文本自动读取,可能有误。阵营标签描述的是来源,而非报道是否属实。", "Disputed: {name}": "争议地区:{name}", "Administered by {holder} · claimed by {claimant}": "由{holder}管辖 · {claimant}主张主权", "Self-administered · claimed by {claimant}": "自治 · {claimant}主张主权", @@ -50,6 +58,34 @@ "News feed not configured on this server": "此服务器未配置新闻源", "Malformed news hotspots response": "新闻热点响应格式错误", "Malformed news feed response": "新闻源响应格式错误", + "{place} (placed by model)": "{place}(由模型定位)", + "English headline by the model": "模型生成的英文标题", + "Not placed on the map": "未在地图上标出", + "Close": "关闭", + "Any severity": "任意严重程度", + "{severity} and above": "{severity}及以上", + "{severity} only": "仅{severity}", + "All categories": "所有类别", + "Reading the news…": "正在读取新闻…", + "News, last 24 hours": "最近 24 小时的新闻", + "Last 24 h": "最近 24 小时", + "Hotspots": "热点", + "Severity": "严重程度", + "Category": "类别", + "Include minor news": "包括次要新闻", + "Show event cards": "显示事件卡片", + "In view": "视野内", + "Nothing reported near here in the last 24 h": "最近 24 小时附近无报道", + "Latest news": "最新新闻", + "No news matches these filters in the last 24 h": "最近 24 小时没有符合这些筛选条件的新闻", + "Load older news": "加载更早的新闻", + "How to read the map": "如何解读地图", + "Colour: severity · icon: type of event": "颜色:严重程度 · 图标:事件类型", + "Solid rim: reported by both sides or independently. Dashed rim: a claim. Thin rim: one source, or one side’s own press.": "实线边框:双方或独立来源均有报道。虚线边框:一方声称。细边框:单一来源,或一方自身的媒体。", + "Larger: more sources · fainter: older. Picture card: a major or fast-growing event with two or more sources.": "越大:来源越多 · 越淡:越早。图片卡片:有两个或以上来源的严重或快速发展的事件。", + "Side labels describe the source, not whether a report is true.": "阵营标签描述的是来源,而非报道是否属实。", + "Exit cockpit to fly to a news report": "退出驾驶舱以飞往新闻报道", + "News items in the feed": "列表中的新闻数", "Pick a shape, then click the map.": "先选择形状,再在地图上点击。", "Enter to place the pin, Esc to cancel.": "按 Enter 放置图钉,按 Esc 取消。", "Click where the pin goes.": "点击图钉的放置位置。", diff --git a/src/i18n/locales/zh-Hant.json b/src/i18n/locales/zh-Hant.json index e29d0fff2..a89b6ba22 100644 --- a/src/i18n/locales/zh-Hant.json +++ b/src/i18n/locales/zh-Hant.json @@ -1,5 +1,13 @@ { "News feed unavailable": "新聞來源無法使用", + "Developing: {name}": "事態發展:{name}", + "{count} events today": { + "other": "今日 {count} 起事件" + }, + "{count} reports today": { + "other": "今日 {count} 則報導" + }, + "Last 24 h from curated hotspots. Each report links to its publisher; places and categories are read from the text automatically and can be wrong. Side labels describe the source, not whether a report is true.": "精選熱點的最近 24 小時。每則報導都連結至其發布者;地點與類別由文字自動判讀,可能有誤。陣營標籤描述的是來源,而非報導是否屬實。", "Disputed: {name}": "爭議地區:{name}", "Administered by {holder} · claimed by {claimant}": "由{holder}管轄 · {claimant}主張主權", "Self-administered · claimed by {claimant}": "自治 · {claimant}主張主權", @@ -50,6 +58,34 @@ "News feed not configured on this server": "此伺服器未設定新聞來源", "Malformed news hotspots response": "新聞熱點回應格式錯誤", "Malformed news feed response": "新聞來源回應格式錯誤", + "{place} (placed by model)": "{place}(由模型定位)", + "English headline by the model": "模型產生的英文標題", + "Not placed on the map": "未在地圖上標出", + "Close": "關閉", + "Any severity": "任意嚴重程度", + "{severity} and above": "{severity}及以上", + "{severity} only": "僅{severity}", + "All categories": "所有類別", + "Reading the news…": "正在讀取新聞…", + "News, last 24 hours": "最近 24 小時的新聞", + "Last 24 h": "最近 24 小時", + "Hotspots": "熱點", + "Severity": "嚴重程度", + "Category": "類別", + "Include minor news": "包括次要新聞", + "Show event cards": "顯示事件卡片", + "In view": "視野內", + "Nothing reported near here in the last 24 h": "最近 24 小時附近無報導", + "Latest news": "最新新聞", + "No news matches these filters in the last 24 h": "最近 24 小時沒有符合這些篩選條件的新聞", + "Load older news": "載入更早的新聞", + "How to read the map": "如何解讀地圖", + "Colour: severity · icon: type of event": "顏色:嚴重程度 · 圖示:事件類型", + "Solid rim: reported by both sides or independently. Dashed rim: a claim. Thin rim: one source, or one side’s own press.": "實線邊框:雙方或獨立來源均有報導。虛線邊框:一方聲稱。細邊框:單一來源,或一方自身的媒體。", + "Larger: more sources · fainter: older. Picture card: a major or fast-growing event with two or more sources.": "越大:來源越多 · 越淡:越早。圖片卡片:有兩個或以上來源的嚴重或快速發展的事件。", + "Side labels describe the source, not whether a report is true.": "陣營標籤描述的是來源,而非報導是否屬實。", + "Exit cockpit to fly to a news report": "退出駕駛艙以飛往新聞報導", + "News items in the feed": "列表中的新聞數", "Pick a shape, then click the map.": "先選擇形狀,再在地圖上點擊。", "Enter to place the pin, Esc to cancel.": "按 Enter 放置圖釘,按 Esc 取消。", "Click where the pin goes.": "點擊圖釘的放置位置。", diff --git a/src/layers/news/index.js b/src/layers/news/index.js new file mode 100644 index 000000000..2f8c08f90 --- /dev/null +++ b/src/layers/news/index.js @@ -0,0 +1,1240 @@ +import * as Cesium from 'cesium'; +import { isPointerFree } from '../../data/inputOwnership.js'; +import { hitTestWorldOverlay } from '../../overlays/worldOverlay.js'; +import { + isOwnedByOtherLayer, + registerPickOwner, + resolvePickId, + unregisterPickOwner, +} from '../../data/pickRegistry.js'; +import { + clearSelectedEntityContextForLayer, + registerEntityContext, + removeEntityContextsForLayer, + selectEntityContext, +} from '../../data/contextStore.js'; +import { msg, t, tn } from '../../i18n/index.js'; +import { createHorizonCull, viewCentre } from '../streetLevel/view.js'; +import { + NEWS_CARD_MIN_SOURCES, + NEWS_CATEGORIES, + NEWS_DETAIL_MAX_HEIGHT_M, + NEWS_FEED_PAGE, + NEWS_FOCUS_HEIGHT_M, + NEWS_IN_VIEW_MAX_HEIGHT_M, + NEWS_LAYER_ID, + NEWS_MAP_LIMIT, + NEWS_OVERLAY_SOURCE_ID, + NEWS_PICK_PREFIX, + NEWS_RELEVANT, + NEWS_SETTLE_MS, + NEWS_SEVERITY, + ageWords, + attestation, + beaconPixelSize, + cardEvents, + cardView, + categoryLabel, + disputedLabel, + feedCardView, + feedQueryFor, + hotspotLabel, + hotspotTrend, + isPressing, + markerStyle, + mediaLabels, + mergeFeedPage, + normalizeFilters, + passesFilters, + reportMarkerPosition, + reportsInView, + severityStyle, + shortTitle, + sideLabel, + sidesLine, + sourceLinkLabel, + viewCell, + visibleOnMap, + withinNewsWindow, +} from './model.js'; +import { SPRITE_SCALE, markerSprite } from './sprites.js'; +import { CARD_H, CARD_W, eventCard } from './cards.js'; +export * from './model.js'; +export { createNewsSource } from './source.js'; + +const FEED_UNAVAILABLE = msg('News feed unavailable'); +const REPORT_PREFIX = `${NEWS_PICK_PREFIX}report:`; +const HOTSPOT_PREFIX = `${NEWS_PICK_PREFIX}hotspot:`; +const DEVELOPING_PREFIX = `${NEWS_PICK_PREFIX}developing:`; +const DEVELOPING_COLOR = '#ffb020'; +// Disputed areas: dotted, in their own colour, apart from ordinary borders. +const DISPUTED_COLOR = '#f472b6'; +const HOTSPOT_COLOR = '#00d4ff'; +// A filtered feed page that shows almost nothing reads the next page by +// itself, a few times, so a strict severity floor still fills the list. +const AUTO_PAGES = 3; +const PULSE_MS = 1_600; +const emptyFeed = () => ({ + items: [], + nextBefore: null, + loading: false, + error: null, +}); +const emptyInView = () => ({ + active: false, + cell: null, + centre: null, + reports: [], + loading: false, + error: null, +}); + +/** + * News from curated hotspots, real time only (the last 24 hours). Zoomed out: + * one beacon per hotspot with its daily count and trend, and a breathing + * beacon per developing situation. Close up or with a hotspot chosen: + * outlines (disputed areas dotted) and the geocoded reports as markers, the + * big events as picture cards. The News panel renders the feed this layer + * publishes through getRowControls().feed. + */ +export function createNewsLayer({ + source, + overlayHost, + cesium = Cesium, + matchMedia = globalThis.matchMedia?.bind(globalThis), + now = () => Date.now(), + hitTestOverlay = hitTestWorldOverlay, + openUrl = (url) => globalThis.open?.(url, '_blank', 'noopener,noreferrer'), + getViewCentre = viewCentre, +} = {}) { + if ( + typeof source?.getHotspots !== 'function' || + typeof source?.getFeed !== 'function' + ) + throw new TypeError('News requires a news source'); + if (!overlayHost) throw new TypeError('News requires an overlay host'); + + let viewer = null, + dataSource = null, + outlineSource = null, + clickHandler = null, + listener = null, + runNavigation = null, + request = null, + feedRequest = null, + inViewRequest = null, + settleTimer = null, + pulseTimer = null, + removeCameraListener = null; + let enabled = false, + destroyed = false, + loading = false, + unavailable = false, + error = null, + lastUpdate = null, + lastRunAt = null, + autoPages = 0; + let hotspots = []; + let mapReports = []; + let feed = emptyFeed(); + let inView = emptyInView(); + let filters = normalizeFilters(); + let selectedId = null, + selectedPin = 0; + let shownDetail = null; + let cullTargets = []; + const contextEntities = new Map(); + const notify = () => listener?.(); + const requestRender = () => viewer?.scene?.requestRender?.(); + const reducedMotion = () => + Boolean(matchMedia?.('(prefers-reduced-motion: reduce)')?.matches); + + const findReport = (id) => + mapReports.find((r) => r.id === id) || + feed.items.find((r) => r.id === id) || + inView.reports.find((r) => r.id === id) || + null; + const selected = () => (selectedId ? findReport(selectedId) : null); + const onMap = (report) => visibleOnMap(report, filters, now()); + + function markerCartesian(report, pin = 0) { + const { lat, lon } = reportMarkerPosition(report, pin); + return cesium.Cartesian3.fromDegrees(lon, lat); + } + + const cameraHeight = () => viewer?.camera?.positionCartographic?.height; + + // Global view: one beacon per hotspot. Close up: outlines and individual + // reports. A chosen hotspot keeps the detail out to three times the height + // (its whole area fits on screen). + function detailMode() { + const height = cameraHeight(); + if (!Number.isFinite(height)) return filters.hotspot !== 'all'; + const limit = + filters.hotspot === 'all' + ? NEWS_DETAIL_MAX_HEIGHT_M + : NEWS_DETAIL_MAX_HEIGHT_M * 3; + return height < limit; + } + + // The catch-all ("Elsewhere") has no area to stand for: its reports are + // drawn as markers at every zoom instead of a beacon or an outline. + const catchAllIds = () => + new Set(hotspots.filter((h) => h.catchAll).map((h) => h.id)); + + // Markers draw over terrain (depth test off) so a pin is never swallowed by + // the ground it sits on; the shared horizon cull hides the far side. + const horizon = createHorizonCull({ + getViewer: () => viewer, + items: () => cullTargets, + onChange: () => { + requestRender(); + updatePulse(); + }, + }); + + // A developing situation's beacon breathes, unless motion is reduced. The + // scene renders on demand, so a slow timer asks for frames only while such + // a beacon is in view. + const pulseSize = (size) => + size * + (1 + 0.35 * (0.5 + 0.5 * Math.sin((Date.now() / PULSE_MS) * 2 * Math.PI))); + function updatePulse() { + const pulsing = + enabled && + !reducedMotion() && + cullTargets.some((target) => target.developing && target.show); + if (pulsing && !pulseTimer) pulseTimer = setInterval(requestRender, 250); + else if (!pulsing && pulseTimer) { + clearInterval(pulseTimer); + pulseTimer = null; + } + } + + const ambientLabel = (extra) => ({ + variant: 'label', + collisionGroup: 'ambient-label', + paintLane: 'ambient-label', + interactive: false, + horizonCull: true, + terrainOcclusion: false, + placement: 'above', + ...extra, + }); + + // Several separate events in one country outside every hotspot. + function renderDeveloping(hotspot, entities, labels) { + const still = reducedMotion(); + for (const item of hotspot.developing || []) { + const position = cesium.Cartesian3.fromDegrees( + item.focus.lon, + item.focus.lat, + ); + const size = beaconPixelSize(item.reports); + entities.add({ + id: `${DEVELOPING_PREFIX}${hotspot.id}:${item.key}`, + position, + point: { + pixelSize: still + ? size + : new cesium.CallbackProperty(() => pulseSize(size), false), + color: + cesium.Color.fromCssColorString(DEVELOPING_COLOR).withAlpha(0.35), + outlineColor: cesium.Color.fromCssColorString(DEVELOPING_COLOR), + outlineWidth: 2, + disableDepthTestDistance: Number.POSITIVE_INFINITY, + }, + }); + labels.push( + ambientLabel({ + id: `developing:${item.key}`, + position, + title: t('Developing: {name}', { name: item.name }), + details: [ + tn(item.events, '{count} event today', '{count} events today'), + ], + accent: DEVELOPING_COLOR, + priority: 9_000 + item.reports, + gapPx: size / 2 + 4, + }), + ); + } + } + + function renderBeacons(entities, labels) { + for (const hotspot of hotspots) { + if (hotspot.catchAll) { + renderDeveloping(hotspot, entities, labels); + continue; + } + const { lat, lon } = hotspot.focus; + const position = cesium.Cartesian3.fromDegrees(lon, lat); + entities.add({ + id: `${HOTSPOT_PREFIX}${hotspot.id}`, + position, + point: { + pixelSize: beaconPixelSize(hotspot.last24h), + color: cesium.Color.fromCssColorString(HOTSPOT_COLOR).withAlpha(0.35), + outlineColor: cesium.Color.fromCssColorString(HOTSPOT_COLOR), + outlineWidth: 2, + disableDepthTestDistance: Number.POSITIVE_INFINITY, + }, + }); + const trend = hotspotTrend(hotspot.last24h, hotspot.prev24h); + labels.push( + ambientLabel({ + id: `hotspot:${hotspot.id}`, + position, + title: hotspotLabel(hotspot), + details: [ + `${tn(hotspot.last24h, '{count} report today', '{count} reports today')}${trend ? ` ${trend}` : ''}`, + ], + accent: HOTSPOT_COLOR, + priority: 10_000 + hotspot.last24h, + gapPx: beaconPixelSize(hotspot.last24h) / 2 + 4, + }), + ); + } + } + + function renderHotspotOutlines(entities, labels) { + for (const hotspot of hotspots) { + if (hotspot.catchAll) continue; + const [w, s, e, n] = hotspot.bbox; + const active = filters.hotspot === hotspot.id; + // The bounding box only until the real outline has loaded. + if (!outlineParts.has(hotspot.id)) + entities.add({ + id: `${HOTSPOT_PREFIX}${hotspot.id}`, + polyline: { + positions: cesium.Cartesian3.fromDegreesArray([ + w, + s, + e, + s, + e, + n, + w, + n, + w, + s, + ]), + width: active ? 3 : 2, + clampToGround: true, + material: new cesium.PolylineDashMaterialProperty({ + color: cesium.Color.fromCssColorString(HOTSPOT_COLOR).withAlpha( + active ? 0.95 : 0.55, + ), + dashLength: 18, + }), + }, + }); + labels.push( + ambientLabel({ + id: `hotspot:${hotspot.id}`, + position: outlineParts.has(hotspot.id) + ? cesium.Cartesian3.fromDegrees( + hotspot.focus.lon, + hotspot.focus.lat, + ) + : cesium.Cartesian3.fromDegrees(w, n), + title: hotspotLabel(hotspot), + details: [ + tn( + hotspot.last24h, + '{count} report today', + '{count} reports today', + ), + ], + accent: HOTSPOT_COLOR, + priority: 10_000 + hotspot.last24h, + }), + ); + // Each disputed area is named, with who holds it and who claims it. + for (const area of outlineDisputed.get(hotspot.id) || []) { + const ring = area.rings[0]; + const lon = ring.reduce((sum, p) => sum + p[0], 0) / ring.length; + const lat = ring.reduce((sum, p) => sum + p[1], 0) / ring.length; + const label = disputedLabel(area); + labels.push( + ambientLabel({ + id: `disputed:${hotspot.id}:${area.name}`, + position: cesium.Cartesian3.fromDegrees(lon, lat), + title: label.title, + details: [label.detail], + accent: DISPUTED_COLOR, + priority: 8_000, + }), + ); + } + } + } + + function renderMarkers(entities, drawn) { + for (const report of drawn) { + const isSelected = report.id === selectedId; + if (!report.pins.length || (!isSelected && !onMap(report))) continue; + // One marker per pin; the pin index rides on the pick id. Fill is + // severity, the icon the category, the rim attestation; a marker grows + // with the sources reporting its event and fades with age. A fresh, + // widely reported or major event also gets a static halo. + const look = markerStyle(report, now()); + const color = cesium.Color.fromCssColorString( + severityStyle(report).color, + ); + const size = isSelected ? look.size + 4 : look.size; + const sprite = markerSprite({ ...look, selected: isSelected }); + const pressing = isPressing(report, now()); + for (const [pin] of report.pins.entries()) { + const position = markerCartesian(report, pin); + if (pressing) + entities.add({ + id: `${REPORT_PREFIX}${report.id}~${pin}~halo`, + position, + point: { + pixelSize: look.size * 2.4, + color: color.withAlpha(0.22), + outlineColor: color.withAlpha(0.6), + outlineWidth: 1, + heightReference: cesium.HeightReference.CLAMP_TO_GROUND, + disableDepthTestDistance: Number.POSITIVE_INFINITY, + }, + }); + entities.add({ + id: `${REPORT_PREFIX}${report.id}~${pin}`, + position, + ...(sprite + ? { + billboard: { + image: sprite, + width: Math.round(size * SPRITE_SCALE), + height: Math.round(size * SPRITE_SCALE), + color: cesium.Color.WHITE.withAlpha( + isSelected ? 1 : look.alpha, + ), + heightReference: cesium.HeightReference.CLAMP_TO_GROUND, + disableDepthTestDistance: Number.POSITIVE_INFINITY, + }, + } + : { + point: { + pixelSize: size, + color, + outlineColor: isSelected + ? cesium.Color.WHITE + : cesium.Color.BLACK.withAlpha(0.7), + outlineWidth: isSelected ? 3 : 1.5, + heightReference: cesium.HeightReference.CLAMP_TO_GROUND, + disableDepthTestDistance: Number.POSITIVE_INFINITY, + }, + }), + }); + } + } + } + + // The big events stand as picture cards over their marker, unless the + // reader has turned them off; never two on top of each other. The clicked + // event shows its picture card either way, under its marker, with its text + // card above. + function pictureCards(drawn, current, labels) { + const cardable = filters.cards + ? cardEvents( + drawn.filter((r) => r.id !== selectedId && onMap(r)), + now(), + ) + : []; + const pictured = + current?.pins.length && + current.event?.size >= NEWS_CARD_MIN_SOURCES && + current.pins[selectedPin] + ? [current] + : []; + for (const [rank, report] of [...pictured, ...cardable].entries()) { + const isSelected = report.id === selectedId; + const look = markerStyle(report, now()); + const view = cardView(report, now()); + const image = eventCard( + report.event?.id || report.id, + view, + look, + requestRender, + ); + if (!image) continue; + const color = severityStyle(report).color; + labels.push({ + id: `event-card:${report.id}`, + position: markerCartesian(report, isSelected ? selectedPin : 0), + variant: 'thumbnail', + paintLane: 'thumbnail', + title: '', + details: [], + image, + accent: color, + priority: isSelected ? Number.MAX_SAFE_INTEGER - 1 : 500_000 - rank, + collisionGroup: isSelected ? 'news-selected-picture' : 'ambient-card', + interactive: true, + accessibilityLabel: `${view.title}. ${view.meta}`, + activate: () => layer.setParams({ reportId: report.id, pin: 0 }), + horizonCull: true, + terrainOcclusion: false, + placement: isSelected ? 'below' : 'above', + verticalOnly: true, + gapPx: look.size / 2 + 12, + leaderOffsetPx: look.size / 2 + 2, + viewportPadding: 24, + // The collision box: rectangle overlap alone lets the cards of nearby + // anchors stack. + minAnchorSeparationPx: isSelected ? 0 : CARD_W * 0.85, + thumbnailWidth: CARD_W, + thumbnailHeight: CARD_H, + thumbnailPadX: 0, + thumbnailPadTop: 0, + thumbnailPadBottom: 0, + thumbnailTitleGap: 0, + thumbnailTitleHeight: 0, + thumbnailTitleChars: 0, + thumbnailBackground: 'rgba(0, 0, 0, 0)', + thumbnailLeaderColor: color, + thumbnailRuleHeight: 0, + thumbnailRadius: 4, + }); + } + } + + // The selected report's card: what, where, how attested, and the link to + // the original article ("Source: host ↗"), which a click on it opens. + function selectedCard(report, labels) { + if (!report?.pins.length) return; + const pin = report.pins[selectedPin] ? selectedPin : 0; + labels.push({ + id: `selected-report:${report.id}`, + position: markerCartesian(report, pin), + variant: 'card', + title: shortTitle(report.titleEn || report.title), + details: [ + [ + report.publisher, + sideLabel(report.side), + ageWords(report.publishedAt, now()), + ] + .filter(Boolean) + .join(' · '), + [ + categoryLabel(report.category), + t(severityStyle(report).label), + report.pins[pin].place, + ] + .filter(Boolean) + .join(' · '), + sidesLine(report), + attestation(report)?.label || '', + mediaLabels(report).join(' · '), + sourceLinkLabel(report.url), + ].filter(Boolean), + accent: severityStyle(report).color, + selected: true, + stateless: true, + priority: Number.MAX_SAFE_INTEGER, + interactive: true, + accessibilityLabel: sourceLinkLabel(report.url), + activate: () => { + openUrl(report.url); + return true; + }, + horizonCull: true, + terrainOcclusion: false, + placement: 'above', + gapPx: 12, + }); + } + + function render() { + if (!dataSource) return; + const entities = dataSource.entities; + // Removed before events are suspended: a marker removed and re-added + // under the same id in one suspended batch reaches Cesium's visualizers + // as "changed", and they keep drawing the removed entity (i.e. nothing). + entities.removeAll(); + entities.suspendEvents(); + const labels = []; + const detail = detailMode(); + shownDetail = detail; + if (detail) renderHotspotOutlines(entities, labels); + else renderBeacons(entities, labels); + // A report picked in the feed or In view still gets its marker. + const current = selected(); + const elsewhere = catchAllIds(); + const shown = detail + ? mapReports + : mapReports.filter((r) => elsewhere.has(r.hotspotId)); + const drawn = + current && !shown.some((r) => r.id === current.id) + ? [...shown, current] + : shown; + renderMarkers(entities, drawn); + entities.resumeEvents(); + showOutlines(detail); + const at = cesium.JulianDate.now(); + cullTargets = entities.values + .filter((entity) => (entity.point || entity.billboard) && entity.position) + .map((entity) => ({ + position: entity.position.getValue(at), + developing: String(entity.id).startsWith(DEVELOPING_PREFIX), + get show() { + return entity.show; + }, + set show(value) { + entity.show = value; + }, + })) + .filter((target) => target.position); + horizon.update(); + updatePulse(); + pictureCards(drawn, current, labels); + selectedCard(current, labels); + if (enabled) + overlayHost.setEntries(NEWS_OVERLAY_SOURCE_ID, labels, { moving: false }); + requestRender(); + } + + function registerContext(report) { + const place = report?.pins[selectedPin] || report?.geo; + if (!place) return null; + let entity = contextEntities.get(report.id); + if (!entity) { + entity = { show: true }; + contextEntities.set(report.id, entity); + } + const { lat, lon } = reportMarkerPosition( + report, + report.pins[selectedPin] ? selectedPin : 0, + ); + entity.__localBaseCartesian = cesium.Cartesian3.fromDegrees(lon, lat); + registerEntityContext(entity, { + id: `news-report:${report.id}`, + layerId: NEWS_LAYER_ID, + layerName: 'News', + source: report.publisher, + dataSource, + label: report.title, // i18n-ignore: publisher headline (data) + latitude: place.lat, + longitude: place.lon, + properties: { + publisher: report.publisher, + side: report.side, + category: report.category, + place: place.place, + publishedAt: report.publishedAt, + url: report.url, + }, + }); + return entity; + } + + function select(id, pin = 0) { + selectedId = id; + selectedPin = pin; + const report = selected(); + if (report) { + const entity = registerContext(report); + if (entity) selectEntityContext(entity); + } else clearSelectedEntityContextForLayer(NEWS_LAYER_ID); + render(); + notify(); + } + + function flyTo(navigate) { + if (!runNavigation || !viewer) return; + runNavigation(() => (enabled && !destroyed ? navigate() : undefined)); + } + + // A card's click: straight down over the event from 150 km. + function focusReport(report) { + if (!report?.pins.length) return; + const { lat, lon } = report.pins[selectedPin] || report.pins[0]; + flyTo(() => + viewer.camera.flyTo({ + destination: cesium.Cartesian3.fromDegrees( + lon, + lat, + NEWS_FOCUS_HEIGHT_M, + ), + duration: reducedMotion() ? 0 : 1.4, + }), + ); + } + + function focusRectangle([w, s, e, n]) { + flyTo(() => + viewer.camera.flyTo({ + destination: cesium.Rectangle.fromDegrees(w, s, e, n), + duration: reducedMotion() ? 0 : 1.6, + }), + ); + } + + // Hotspot extents (and developing countries) are drawn in their own data + // source, built once per outline and only shown or hidden afterwards: + // ground polygons over 3D tiles are slow to build, so they are never + // rebuilt on a re-render. A hotspot's fill clears when it is the chosen + // one so its border stays readable over the reports inside. + const outlineParts = new Map(); + const outlineRequests = new Set(); + const outlineDisputed = new Map(); + function addOutline( + key, + { polygons, borders, disputed = [] }, + { color, fillAlpha, pickId }, + ) { + if (!outlineSource || outlineParts.has(key)) return; + const css = cesium.Color.fromCssColorString(color); + const parts = { fills: [], borders: [] }; + const ring = (points) => cesium.Cartesian3.fromDegreesArray(points.flat()); + const closed = (points) => ring([...points, points[0]]); + const line = (id, positions, width, material) => + parts.borders.push( + outlineSource.entities.add({ + id, + show: false, + polyline: { positions, width, clampToGround: true, material }, + }), + ); + for (const [index, polygon] of polygons.entries()) { + if (fillAlpha > 0) + parts.fills.push( + outlineSource.entities.add({ + id: `${pickId}~fill${index}`, + show: false, + polygon: { + hierarchy: new cesium.PolygonHierarchy( + ring(polygon.outer), + polygon.holes.map( + (hole) => new cesium.PolygonHierarchy(ring(hole)), + ), + ), + material: css.withAlpha(fillAlpha), + classificationType: cesium.ClassificationType.BOTH, + }, + }), + ); + for (const [k, points] of [polygon.outer, ...polygon.holes].entries()) + line( + `${pickId}~line${index}.${k}`, + closed(points), + 2, + css.withAlpha(0.85), + ); + } + // National borders inside a multi-country hotspot: thin and dashed. + for (const [index, points] of borders.entries()) + line( + `${pickId}~border${index}`, + closed(points), + 1.5, + new cesium.PolylineDashMaterialProperty({ + color: css.withAlpha(0.6), + dashLength: 12, + }), + ); + const dotted = new cesium.PolylineDashMaterialProperty({ + color: cesium.Color.fromCssColorString(DISPUTED_COLOR).withAlpha(0.9), + dashLength: 6, + }); + for (const [index, area] of disputed.entries()) + for (const [k, points] of area.rings.entries()) + line(`${pickId}~disputed${index}.${k}`, closed(points), 2, dotted); + outlineDisputed.set(key, disputed); + outlineParts.set(key, parts); + } + function loadOutline(key, fetchOutline, style) { + if (outlineParts.has(key) || outlineRequests.has(key) || !fetchOutline) + return; + outlineRequests.add(key); + fetchOutline() + .then((outline) => { + if (destroyed) return; + addOutline(key, outline, style); + if (enabled) render(); + }) + // An outline is an extra: the bounding box stands in for it. + .catch(() => {}) + .finally(() => outlineRequests.delete(key)); + } + function loadOutlines() { + for (const hotspot of hotspots) { + if (!hotspot.catchAll) + loadOutline( + hotspot.id, + source.getOutline && (() => source.getOutline(hotspot.id)), + { + color: HOTSPOT_COLOR, + fillAlpha: 0.08, + pickId: `${HOTSPOT_PREFIX}${hotspot.id}`, + }, + ); + for (const item of hotspot.developing || []) + loadOutline( + `developing:${item.key}`, + source.getCountryOutline && + (() => source.getCountryOutline(item.key)), + { + color: DEVELOPING_COLOR, + fillAlpha: 0, + pickId: `${DEVELOPING_PREFIX}${hotspot.id}:${item.key}`, + }, + ); + } + } + function showOutlines(detail) { + const developing = new Set( + hotspots.flatMap((h) => (h.developing || []).map((d) => d.key)), + ); + for (const [key, parts] of outlineParts) { + const country = key.startsWith('developing:') ? key.slice(11) : null; + const visible = enabled && (country ? developing.has(country) : detail); + const fill = visible && !country && filters.hotspot !== key; + for (const entity of parts.fills) + if (entity.show !== fill) entity.show = fill; + for (const entity of parts.borders) + if (entity.show !== visible) entity.show = visible; + } + } + + const shownCount = () => + feed.items.filter((r) => passesFilters(r, filters, now())).length; + + async function loadFeed(mode) { + if (!enabled || unavailable) return; + if (mode === 'append' && (!feed.nextBefore || feed.loading)) return; + if (mode === 'replace') autoPages = 0; + feedRequest?.abort(); + const controller = new AbortController(); + feedRequest = controller; + feed = { ...feed, loading: true, error: null }; + notify(); + try { + const page = await source.getFeed( + feedQueryFor( + filters, + mode === 'append' ? { before: feed.nextBefore } : {}, + ), + { signal: controller.signal }, + ); + if (controller.signal.aborted || feedRequest !== controller || !enabled) + return; + feed = { + ...mergeFeedPage(feed, page, mode), + loading: false, + error: null, + }; + } catch (cause) { + if (controller.signal.aborted || feedRequest !== controller) return; + feed = { + ...feed, + loading: false, + error: cause?.message || FEED_UNAVAILABLE, + }; + } finally { + if (feedRequest === controller) feedRequest = null; + notify(); + } + if ( + enabled && + !feed.error && + feed.nextBefore && + shownCount() < NEWS_FEED_PAGE / 3 && + autoPages < AUTO_PAGES + ) { + autoPages++; + void loadFeed('append'); + } + } + + // "In view": below 3,000 km, the reports within 500 km of the view centre, + // read again once the camera has settled for 0.8 s in another half-degree + // cell. The feed has no area query, so the last day's geocoded reports are + // read and kept by distance here. + function scheduleInView() { + clearTimeout(settleTimer); + settleTimer = setTimeout(() => { + settleTimer = null; + void refreshInView(); + }, NEWS_SETTLE_MS); + } + async function refreshInView({ force = false } = {}) { + if (!enabled || unavailable) return; + const height = cameraHeight(); + if (!(height < NEWS_IN_VIEW_MAX_HEIGHT_M)) { + if (inView.active) { + inViewRequest?.abort(); + inViewRequest = null; + inView = emptyInView(); + notify(); + } + return; + } + const centre = getViewCentre(viewer); + if (!centre) return; + const cell = viewCell(centre); + if (!force && inView.active && cell === inView.cell) return; + inViewRequest?.abort(); + const controller = new AbortController(); + inViewRequest = controller; + inView = { ...inView, active: true, cell, centre, loading: true }; + notify(); + try { + const page = await source.getFeed( + { + hotspot: 'all', + geo: true, + today: true, + events: true, + relevance: filters.includeMinor ? '' : NEWS_RELEVANT, + limit: NEWS_MAP_LIMIT, + }, + { signal: controller.signal }, + ); + if (controller.signal.aborted || inViewRequest !== controller) return; + inView = { + ...inView, + reports: page.reports, + loading: false, + error: null, + }; + } catch (cause) { + if (controller.signal.aborted || inViewRequest !== controller) return; + inView = { + ...inView, + loading: false, + error: cause?.message || FEED_UNAVAILABLE, + }; + } finally { + if (inViewRequest === controller) inViewRequest = null; + notify(); + } + } + + function installSelection() { + if (clickHandler || !viewer?.scene?.canvas) return; + clickHandler = new cesium.ScreenSpaceEventHandler(viewer.scene.canvas); + clickHandler.setInputAction((click) => { + if (!enabled || destroyed || !isPointerFree() || !click?.position) return; + const card = hitTestOverlay(click.position.x, click.position.y, { + sourceId: NEWS_OVERLAY_SOURCE_ID, + }); + if (card?.entry?.activate) { + card.entry.activate(); + return; + } + const picked = viewer.scene.pick(click.position); + const id = picked ? resolvePickId(picked) : null; + if (typeof id === 'string' && id.startsWith(REPORT_PREFIX)) { + const [reportId, pin] = id.slice(REPORT_PREFIX.length).split('~'); + layer.setParams({ reportId, pin: Number(pin) || 0 }); + return; + } + if (typeof id === 'string' && id.startsWith(DEVELOPING_PREFIX)) { + const [hotspotId, key] = id + .slice(DEVELOPING_PREFIX.length) + .split('~')[0] + .split(':'); + const item = hotspots + .find((h) => h.id === hotspotId) + ?.developing?.find((d) => d.key === key); + layer.setParams({ filters: { hotspot: hotspotId } }); + if (item) { + const { lat, lon } = item.focus; + focusRectangle([ + lon - 5, + Math.max(-85, lat - 3.5), + lon + 5, + Math.min(85, lat + 3.5), + ]); + } + return; + } + if (typeof id === 'string' && id.startsWith(HOTSPOT_PREFIX)) { + const hotspotId = id.slice(HOTSPOT_PREFIX.length).split('~')[0]; + // Clicking the hotspot already in focus steps out of a report. + if (filters.hotspot === hotspotId) { + if (selectedId) layer.setParams({ clear: true }); + return; + } + layer.setParams({ filters: { hotspot: hotspotId } }); + return; + } + if (id && isOwnedByOtherLayer(NEWS_LAYER_ID, id)) return; + if (selectedId && !picked?.id) layer.setParams({ clear: true }); + }, cesium.ScreenSpaceEventType.LEFT_CLICK); + } + + function removeSelection() { + if (clickHandler && !clickHandler.isDestroyed?.()) clickHandler.destroy(); + clickHandler = null; + } + + function feedView() { + const at = now(); + const report = selected(); + const total = hotspots.reduce((sum, h) => sum + h.last24h, 0); + return { + filters, + hotspots: [ + { id: 'all', label: t('All'), count: total }, + ...hotspots.map((hotspot) => ({ + id: hotspot.id, + label: hotspotLabel(hotspot), + count: hotspot.last24h, + })), + ].map((chip) => ({ ...chip, active: filters.hotspot === chip.id })), + categories: Object.keys(NEWS_CATEGORIES).map((id) => ({ + value: id, + label: categoryLabel(id), + })), + severities: NEWS_SEVERITY.map((level, index) => ({ + value: index, + label: t(level.label), + color: level.color, + })), + items: feed.items + .filter((r) => passesFilters(r, filters, at)) + .map((r) => feedCardView(r, at)), + inView: { + active: inView.active, + loading: inView.loading, + error: inView.error ? t(FEED_UNAVAILABLE) : null, + items: reportsInView(inView.reports, inView.centre, filters, at).map( + (r) => feedCardView(r, at), + ), + }, + selected: + report && withinNewsWindow(report, at) + ? feedCardView(report, at) + : null, + hasMore: Boolean(feed.nextBefore), + loading: feed.loading || loading, + // Read failures are English data; the panel shows them translated. + error: error || feed.error ? t(error || feed.error) : null, + lastRunAt, + }; + } + + const layer = { + id: NEWS_LAYER_ID, + name: 'News', + icon: '◆', + source: 'GEV news', + updateInterval: 120_000, + + init(nextViewer) { + viewer = nextViewer; + dataSource = new cesium.CustomDataSource(NEWS_LAYER_ID); + outlineSource = new cesium.CustomDataSource(`${NEWS_LAYER_ID}-outlines`); + dataSource.show = false; + outlineSource.show = false; + viewer.dataSources?.add(outlineSource); + viewer.dataSources?.add(dataSource); + overlayHost.setVisible(NEWS_OVERLAY_SOURCE_ID, false); + }, + attachShellServices(services) { + runNavigation = + typeof services?.runNavigation === 'function' + ? services.runNavigation + : null; + }, + enable() { + if (destroyed || enabled) return; + enabled = true; + if (dataSource) dataSource.show = true; + if (outlineSource) outlineSource.show = true; + overlayHost.setVisible(NEWS_OVERLAY_SOURCE_ID, true); + registerPickOwner( + NEWS_LAYER_ID, + (id) => enabled && String(id).startsWith(NEWS_PICK_PREFIX), + ); + installSelection(); + // Re-render only when a camera move crosses the detail threshold. + removeCameraListener = + viewer?.camera?.moveEnd?.addEventListener?.(() => { + if (!enabled) return; + if (detailMode() !== shownDetail) render(); + scheduleInView(); + }) || null; + }, + disable() { + enabled = false; + unavailable = false; + error = null; + request?.abort(); + feedRequest?.abort(); + inViewRequest?.abort(); + request = feedRequest = inViewRequest = null; + clearTimeout(settleTimer); + settleTimer = null; + loading = false; + unregisterPickOwner(NEWS_LAYER_ID); + removeSelection(); + removeCameraListener?.(); + removeCameraListener = null; + horizon.stop(); + cullTargets = []; + clearInterval(pulseTimer); + pulseTimer = null; + if (outlineSource) outlineSource.show = false; + selectedId = null; + clearSelectedEntityContextForLayer(NEWS_LAYER_ID); + removeEntityContextsForLayer(NEWS_LAYER_ID); + contextEntities.clear(); + feed = emptyFeed(); + inView = emptyInView(); + mapReports = []; + if (dataSource) { + dataSource.entities.removeAll(); + dataSource.show = false; + } + overlayHost.clearSource(NEWS_OVERLAY_SOURCE_ID); + overlayHost.setVisible(NEWS_OVERLAY_SOURCE_ID, false); + requestRender(); + notify(); + }, + async update(_viewer, { signal } = {}) { + if (!enabled || destroyed) return false; + // A server without the news routes says so once; no background retries. + if (unavailable) return true; + request?.abort(); + const controller = new AbortController(); + const abort = () => controller.abort(signal.reason); + signal?.addEventListener('abort', abort, { once: true }); + request = controller; + loading = true; + notify(); + try { + const [index, todays] = await Promise.all([ + source.getHotspots({ signal: controller.signal }), + source.getFeed( + { + hotspot: 'all', + geo: true, + today: true, + events: true, + relevance: NEWS_RELEVANT, + limit: NEWS_MAP_LIMIT, + }, + { signal: controller.signal }, + ), + ]); + if (!enabled || controller.signal.aborted || request !== controller) + return false; + hotspots = index.hotspots; + loadOutlines(); + lastRunAt = index.lastRunAt; + mapReports = todays.reports.filter((r) => withinNewsWindow(r, now())); + filters = normalizeFilters({}, hotspots, filters); + error = null; + lastUpdate = now(); + render(); + void loadFeed(feed.items.length ? 'head' : 'replace'); + void refreshInView({ force: inView.active }); + return true; + } catch (cause) { + if (controller.signal.aborted || request !== controller) return false; + unavailable = cause?.unavailable === true; + error = cause?.message || FEED_UNAVAILABLE; + return true; + } finally { + signal?.removeEventListener('abort', abort); + if (request === controller) { + request = null; + loading = false; + notify(); + } + } + }, + setParams(params = {}) { + if (!enabled || destroyed) return; + if (params.clear === true) { + select(null); + return; + } + if (params.filters && typeof params.filters === 'object') { + const next = normalizeFilters(params.filters, hotspots, filters); + // The severity floor and the cards change what is shown, not what is read. + const readKey = ({ hotspot, category, includeMinor }) => + `${hotspot}|${category}|${includeMinor}`; + const reread = readKey(next) !== readKey(filters); + const minorChanged = next.includeMinor !== filters.includeMinor; + filters = next; + if ( + Object.hasOwn(params.filters, 'hotspot') && + next.hotspot !== 'all' + ) { + const hotspot = hotspots.find((h) => h.id === next.hotspot); + // The catch-all spans the world: choosing it filters, it does not fly. + if (hotspot && !hotspot.catchAll) focusRectangle(hotspot.bbox); + } + if (reread) feed = emptyFeed(); + render(); + if (reread) void loadFeed('replace'); + if (minorChanged) void refreshInView({ force: true }); + notify(); + } + if (params.loadMore === true) void loadFeed('append'); + if (typeof params.hotspotId === 'string') + layer.setParams({ filters: { hotspot: params.hotspotId } }); + if (typeof params.reportId === 'string' && findReport(params.reportId)) { + select( + params.reportId, + Number.isInteger(params.pin) && params.pin > 0 ? params.pin : 0, + ); + if (params.focus === true) focusReport(selected()); + } + }, + getRowControls() { + return { + chips: [], + legend: [], + info: t( + 'Last 24 h from curated hotspots. Each report links to its publisher; places and categories are read from the text automatically and can be wrong. Side labels describe the source, not whether a report is true.', + ), + // A ready-to-render view for the News panel (src/ui/newsPanel.js), + // which takes no layer imports: labels and colours are resolved here. + feed: feedView(), + }; + }, + setRowControlsListener(value) { + listener = typeof value === 'function' ? value : null; + }, + getAnalystRecords() { + return []; + }, + getStats() { + return { + count: mapReports.filter((r) => r.pins.length && onMap(r)).length, + lastUpdate, + loading, + error, + ...(unavailable + ? { status: 'unavailable', sourceUnavailable: true } + : {}), + source: 'GEV news', + }; + }, + destroy() { + if (destroyed) return; + layer.disable(); + destroyed = true; + if (viewer && dataSource) viewer.dataSources?.remove(dataSource, true); + if (viewer && outlineSource) + viewer.dataSources?.remove(outlineSource, true); + dataSource = null; + outlineSource = null; + outlineParts.clear(); + outlineDisputed.clear(); + viewer = null; + listener = null; + runNavigation = null; + }, + }; + return layer; +} diff --git a/src/layers/news/layer.test.mjs b/src/layers/news/layer.test.mjs new file mode 100644 index 000000000..5cc49938c --- /dev/null +++ b/src/layers/news/layer.test.mjs @@ -0,0 +1,255 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import * as Cesium from 'cesium'; +import { createNewsLayer } from './index.js'; + +const NOW = Date.parse('2026-10-28T10:00:00Z'); +const hotspotsPayload = { + hotspots: [ + { + id: 'ua-ru-war', + name: 'Russia–Ukraine war', + bbox: [22, 44, 42, 56], + focus: { lat: 48.6, lon: 35.5 }, + last24h: 3, + parties: ['UA', 'RU'], + }, + ], + categories: [], + lastRunAt: null, +}; +const report = (id, extra = {}) => ({ + id, + title: `Report ${id}`, + url: `https://example.com/${id}`, + publishedAt: '2026-10-28T09:00:00.000Z', + publisher: 'Example', + side: 'UA', + category: 'strike', + hotspotId: 'ua-ru-war', + hotspotIds: ['ua-ru-war'], + severity: 2, + geo: { lat: 50, lon: 36, place: 'Kharkiv', mappable: true }, + pins: [{ lat: 50, lon: 36, place: 'Kharkiv', mappable: true }], + event: null, + media: [], + ...extra, +}); + +function fixture( + t, + { source: overrides = {}, height = 20_000_000, reduced = false } = {}, +) { + const calls = { feed: [], hotspots: 0, outline: 0 }; + const reports = [ + report('major', { + severity: 3, + event: { + size: 3, + severity: 3, + status: 'both-sides', + lastAt: '2026-10-28T09:30:00.000Z', + sides: [], + image: null, + }, + }), + report('minor', { severity: 1 }), + report('old', { publishedAt: '2026-10-26T09:00:00.000Z', severity: 3 }), + report('far', { + severity: 2, + pins: [{ lat: 31.5, lon: 34.4, place: 'Gaza', mappable: true }], + }), + ]; + const source = { + getHotspots: async () => { + calls.hotspots++; + return hotspotsPayload; + }, + getFeed: async (query) => { + calls.feed.push(query); + return { reports, nextBefore: null }; + }, + getOutline: async () => { + calls.outline++; + return { polygons: [], borders: [], disputed: [] }; + }, + ...overrides, + }; + const entries = []; + const overlayHost = { + setEntries: (_id, list) => entries.push(list), + setVisible() {}, + clearSource: () => entries.push([]), + }; + const flights = []; + const camera = { + positionCartographic: { height }, + positionWC: Cesium.Cartesian3.fromDegrees(36, 49, height), + moveEnd: new Cesium.Event(), + flyTo: (options) => flights.push(options), + }; + const viewer = { + camera, + scene: { requestRender() {}, preRender: new Cesium.Event() }, + dataSources: { add() {}, remove() {} }, + }; + const layer = createNewsLayer({ + source, + overlayHost, + now: () => NOW, + matchMedia: () => ({ matches: reduced }), + getViewCentre: () => ({ lat: 49, lon: 36 }), + }); + // The context store announces selections on `window`, which Node lacks. + const originalWindow = globalThis.window; + globalThis.window = new EventTarget(); + layer.init(viewer); + layer.attachShellServices({ runNavigation: (navigate) => navigate() }); + t.after(() => { + layer.destroy(); + if (originalWindow === undefined) delete globalThis.window; + else globalThis.window = originalWindow; + }); + return { layer, viewer, camera, calls, entries, flights }; +} + +const settle = () => new Promise((resolve) => setTimeout(resolve, 0)); + +test('the feed shows the last 24 h at significant and above, beacons when zoomed out', async (t) => { + const { layer, calls, entries } = fixture(t); + layer.enable(); + assert.equal(await layer.update(), true); + await settle(); + assert.equal(calls.hotspots, 1); + // The map read and the panel's feed read both ask for the last day only. + assert.ok(calls.feed.every((query) => query.today === true)); + const view = layer.getRowControls().feed; + assert.deepEqual( + view.items.map((item) => item.id), + ['major', 'far'], + ); + assert.deepEqual( + view.hotspots.map((chip) => [chip.id, chip.label, chip.active]), + [ + ['all', 'All', true], + ['ua-ru-war', 'Ukraine–Russia', false], + ], + ); + const labels = entries.at(-1); + assert.ok(labels.some((entry) => entry.id === 'hotspot:ua-ru-war')); + assert.equal(layer.getStats().error, null); + // Zoomed out, the camera is too high for "In view". + assert.equal(view.inView.active, false); +}); + +test('choosing a card selects it and flies straight down from 150 km; reduced motion jumps', async (t) => { + const { layer, flights, entries } = fixture(t, { reduced: true }); + layer.enable(); + await layer.update(); + layer.setParams({ reportId: 'major', focus: true }); + assert.equal(flights.length, 1); + assert.equal(flights[0].duration, 0); + const at = Cesium.Cartographic.fromCartesian(flights[0].destination); + assert.ok(Math.abs(at.height - 150_000) < 1); + assert.ok(Math.abs(Cesium.Math.toDegrees(at.latitude) - 50) < 1e-6); + const card = entries.at(-1).find((e) => e.id === 'selected-report:major'); + assert.ok(card.details.includes('Source: example.com ↗')); + assert.equal(layer.getRowControls().feed.selected.id, 'major'); + layer.setParams({ clear: true }); + assert.equal(layer.getRowControls().feed.selected, null); +}); + +test('the card toggle and the severity floor change what is shown, not what is read', async (t) => { + const { layer, entries, calls } = fixture(t, { height: 500_000 }); + layer.enable(); + await layer.update(); + const cards = () => + entries.at(-1).filter((entry) => entry.id.startsWith('event-card:')); + // No canvas in Node: cards need one, so none are painted, and nothing throws. + assert.deepEqual(cards(), []); + await settle(); + const reads = calls.feed.length; + layer.setParams({ filters: { cards: false, minSeverity: 0 } }); + assert.equal(calls.feed.length, reads); + assert.equal(layer.getRowControls().feed.filters.cards, false); + assert.deepEqual( + layer.getRowControls().feed.items.map((item) => item.id), + ['major', 'minor', 'far'], + ); +}); + +test('In view reads again only when the camera settles low in a new cell', async (t) => { + t.mock.timers.enable({ apis: ['setTimeout'] }); + const { layer, camera, calls } = fixture(t, { height: 1_000_000 }); + layer.enable(); + await layer.update(); + const reads = () => calls.feed.filter((q) => q.limit === 500).length; + const before = reads(); + camera.moveEnd.raiseEvent(); + t.mock.timers.tick(799); + assert.equal(reads(), before); + t.mock.timers.tick(1); + await Promise.resolve(); + await Promise.resolve(); + const view = layer.getRowControls().feed.inView; + assert.equal(view.active, true); + // Gaza is beyond 500 km of the view centre; the old report is past 24 h. + assert.deepEqual( + view.items.map((item) => item.id), + ['major'], + ); + // Same cell: no new read. + const settled = reads(); + camera.moveEnd.raiseEvent(); + t.mock.timers.tick(800); + assert.equal(reads(), settled); + // Up above 3,000 km, In view goes away. + camera.positionCartographic.height = 5_000_000; + camera.moveEnd.raiseEvent(); + t.mock.timers.tick(800); + assert.equal(layer.getRowControls().feed.inView.active, false); +}); + +test('a server without news is unavailable once and is not asked again', async (t) => { + const failure = Object.assign( + new Error('News feed not configured on this server'), + { + unavailable: true, + }, + ); + let reads = 0; + const { layer } = fixture(t, { + source: { + getHotspots: async () => { + reads++; + throw failure; + }, + }, + }); + layer.enable(); + assert.equal(await layer.update(), true); + assert.equal(await layer.update(), true); + assert.equal(reads, 1); + const stats = layer.getStats(); + assert.equal(stats.sourceUnavailable, true); + assert.equal(stats.status, 'unavailable'); + assert.equal(layer.getRowControls().feed.error, failure.message); + // Turning the layer off and on asks again. + layer.disable(); + layer.enable(); + await layer.update(); + assert.equal(reads, 2); +}); + +test('a failed read keeps the layer on with an error; disable clears the overlay', async (t) => { + const { layer, entries } = fixture(t, { + source: { getFeed: async () => Promise.reject(new Error('boom')) }, + }); + layer.enable(); + assert.equal(await layer.update(), true); + assert.equal(layer.getStats().error, 'boom'); + assert.equal(layer.getStats().sourceUnavailable, undefined); + layer.disable(); + assert.deepEqual(entries.at(-1), []); + assert.deepEqual(layer.getRowControls().feed.items, []); +}); diff --git a/src/navigationPolicy.js b/src/navigationPolicy.js index f69cb54c0..d22d3e50b 100644 --- a/src/navigationPolicy.js +++ b/src/navigationPolicy.js @@ -31,6 +31,8 @@ const COCKPIT_REFUSALS = Object.freeze({ // «View coverage» button); the cyclone layer flies to the selected storm. weather: msg('Exit cockpit to view weather coverage'), cyclone: msg('Exit cockpit to fly to a cyclone'), + // The News panel's cards and the news layer's hotspots fly to the event. + news: msg('Exit cockpit to fly to a news report'), // Voice track_entity (TRACKABLE_FAMILIES kinds in gevActions.js) and // frame_overhead, which frames the contacts around the current view. aircraft: msg('Exit cockpit to fly to an aircraft'), diff --git a/src/navigationPolicy.test.mjs b/src/navigationPolicy.test.mjs index 9826846ca..661ea7918 100644 --- a/src/navigationPolicy.test.mjs +++ b/src/navigationPolicy.test.mjs @@ -136,6 +136,7 @@ test('weather layers name their destination in the Cockpit refusal', () => { const expected = { weather: 'Exit cockpit to view weather coverage', cyclone: 'Exit cockpit to fly to a cyclone', + news: 'Exit cockpit to fly to a news report', }; for (const [noun, text] of Object.entries(expected)) { const s = spy(); diff --git a/src/standalone/layerSources.js b/src/standalone/layerSources.js index 2e0534a3a..d1a273455 100644 --- a/src/standalone/layerSources.js +++ b/src/standalone/layerSources.js @@ -20,6 +20,7 @@ import { createCycloneSource } from '../layers/cyclones/source.js'; import { createWindSource } from '../layers/wind/source.js'; import { createFirmsSource } from '../layers/firms/source.js'; import { createGhostMapsSource } from '../layers/ghostMaps/source.js'; +import { createNewsSource } from '../layers/news/source.js'; import { createMapillarySource } from '../layers/streetLevel/providers/mapillary/source.js'; import { createReferenceSources } from '../sources/reference.js'; export { createReferenceSources as createStandaloneReferenceSources } from '../sources/reference.js'; @@ -60,6 +61,10 @@ export function createStandaloneLayerSources( alpr: createAlprTileSource(), firms: createFirmsSource(), 's2-ghostmaps': createGhostMapsSource(), + // Same-origin /api/news: the local server proxies GEV_NEWS_ORIGIN and, + // without it, answers "not configured", which the layer shows as + // unavailable without retrying. + news: createNewsSource(), wind: createWindSource(), weather: createWeatherSource(), cyclones: createCycloneSource(), diff --git a/src/ui/layerBindings.js b/src/ui/layerBindings.js index 60128f8e0..1ac398c38 100644 --- a/src/ui/layerBindings.js +++ b/src/ui/layerBindings.js @@ -147,6 +147,15 @@ export class LayerBindings { fires.attachShellServices({ imageryHost: this.services.imageryHost }); this._weatherShellModules.push(fires); } + // News flies to a chosen report or hotspot through the same release. + const news = this._dataManager?.layers?.get('news')?.module; + if (typeof news?.attachShellServices === 'function') { + news.attachShellServices({ + runNavigation: (navigate) => + this.runImmediateNavigation('news', navigate), + }); + this._weatherShellModules.push(news); + } } _persistAwarenessSelection(event, cleared = false) { diff --git a/src/ui/layerNames.js b/src/ui/layerNames.js index 694d57066..83f4e7833 100644 --- a/src/ui/layerNames.js +++ b/src/ui/layerNames.js @@ -37,6 +37,7 @@ export const LAYER_NAME_KEYS = Object.freeze({ 'gnss-integrity': msg('GNSS Integrity'), 'drone-airspace': msg('Prohibited & Restricted Airspace'), 's2-ghostmaps': msg('S2 GhostMaps'), + news: msg('News'), wind: msg('Wind'), 'weather-radar': msg('Rain radar'), 'weather-satellite': msg('Satellite clouds'), diff --git a/src/ui/layerPanel.js b/src/ui/layerPanel.js index b24e8be7b..39a840ab2 100644 --- a/src/ui/layerPanel.js +++ b/src/ui/layerPanel.js @@ -11,6 +11,7 @@ import { } from './layerNames.js'; export { localizeLayerName } from './layerNames.js'; import { createWeatherPanel } from './weatherPanel.js'; +import { createNewsPanel } from './newsPanel.js'; import { translateFeedError, translateStatusLine } from './statusText.js'; import { formatNumber, @@ -78,6 +79,7 @@ const PANEL_GROUPS = [ 'fire-perimeters', 'gnss-integrity', 's2-ghostmaps', + 'news', ], }, { @@ -310,6 +312,11 @@ export class LayerPanel { container?.ownerDocument?.getElementById?.('weather-panel-body'), setLayerParams: this.setLayerParams, }); + this._newsPanel?.destroy(); + this._newsPanel = createNewsPanel({ + container: container?.ownerDocument?.getElementById?.('news-panel-body'), + setLayerParams: this.setLayerParams, + }); this._mountRecentImagery(); this._renderToggles(); } @@ -345,6 +352,8 @@ export class LayerPanel { this._releaseBindings(); this._weatherPanel?.destroy(); this._weatherPanel = null; + this._newsPanel?.destroy(); + this._newsPanel = null; this._recentImageryPanel?.destroy(); this._recentImageryPanel = null; this._recentImageryFactory = null; @@ -409,10 +418,12 @@ export class LayerPanel { onLocaleChange(() => { this._paint(); this._refreshWeatherPanel(); + this._refreshNewsPanel(); }), ); this._paint(); this._refreshWeatherPanel(); + this._refreshNewsPanel(); } /** Present every row from the layers' current state and render them. */ @@ -641,6 +652,15 @@ export class LayerPanel { } this._paint(); this._refreshWeatherPanel(); + this._refreshNewsPanel(); + } + + /** Feed the News rail panel the view the news layer publishes while on. */ + _refreshNewsPanel() { + const layer = this.getAll().find(({ id }) => id === 'news'); + this._newsPanel?.update( + layer?.enabled ? this._rowControlsFor(layer.id)?.feed || null : null, + ); } _buildMetaText(layer) { diff --git a/src/ui/news/NewsCard.vue b/src/ui/news/NewsCard.vue new file mode 100644 index 000000000..46dbe5fb7 --- /dev/null +++ b/src/ui/news/NewsCard.vue @@ -0,0 +1,127 @@ + + + diff --git a/src/ui/news/NewsFeed.vue b/src/ui/news/NewsFeed.vue new file mode 100644 index 000000000..5d6fc8bce --- /dev/null +++ b/src/ui/news/NewsFeed.vue @@ -0,0 +1,217 @@ + + + diff --git a/src/ui/newsPanel.js b/src/ui/newsPanel.js new file mode 100644 index 000000000..78fd6ea24 --- /dev/null +++ b/src/ui/newsPanel.js @@ -0,0 +1,73 @@ +import { h, render as renderVue } from 'vue'; +import NewsFeed from './news/NewsFeed.vue'; + +const LAYER_ID = 'news'; +const LOAD_MORE_MARGIN_PX = 160; +// Remounting must not reopen a panel the reader already collapsed. +const appearedPanels = new WeakSet(); +const set = (node, key, value) => { + if (node[key] !== value) node[key] = value; +}; + +/** + * The News rail panel (`#news-panel`): it renders the `feed` view the news + * layer publishes through its row controls, shows itself only while the + * layer is on, and acts only through setLayerParams. Near the bottom of its + * scroller it asks for the next older page, once per page. + */ +export function createNewsPanel({ container, setLayerParams = () => {} } = {}) { + const document = container?.ownerDocument; + if (!document?.createElement) return null; + const panel = container.closest?.('#news-panel'); + const count = panel?.querySelector('#news-panel-count'); + const onParams = (params) => + setLayerParams(LAYER_ID, params, { origin: 'user' }); + let view = null; + let destroyed = false; + let requestedAt = -1; + + function render() { + if (destroyed) return; + renderVue(h(NewsFeed, { view, onParams }), container); + const hidden = !view; + if (panel) set(panel, 'hidden', hidden); + if (count) set(count, 'textContent', String(view?.items.length ?? 0)); + if (!hidden && panel && !appearedPanels.has(panel)) { + appearedPanels.add(panel); + // First appearance opens the panel unless a stored or shared collapse + // choice exists (marked by the panel chrome when it restored the state). + const preference = panel.dataset?.collapsedPreference; + if ( + panel.classList?.contains('collapsed') && + (preference === undefined || preference === 'default') + ) + panel.querySelector('[data-collapse-target="news-panel"]')?.click(); + } + } + + const onScroll = () => { + if (!view?.hasMore || view.loading) return; + const remaining = + container.scrollHeight - container.scrollTop - container.clientHeight; + if (remaining > LOAD_MORE_MARGIN_PX) return; + if (requestedAt === view.items.length) return; + requestedAt = view.items.length; + onParams({ loadMore: true }); + }; + container.addEventListener?.('scroll', onScroll, { passive: true }); + + return { + /** Show the layer's feed view, or hide the panel with null. */ + update(next) { + view = next || null; + render(); + }, + destroy() { + destroyed = true; + container.removeEventListener?.('scroll', onScroll); + renderVue(null, container); + if (panel) set(panel, 'hidden', true); + if (count) set(count, 'textContent', '0'); + }, + }; +} diff --git a/src/ui/newsPanel.test.mjs b/src/ui/newsPanel.test.mjs new file mode 100644 index 000000000..71346fdc3 --- /dev/null +++ b/src/ui/newsPanel.test.mjs @@ -0,0 +1,223 @@ +import '../testSupport/registerDom.mjs'; +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createNewsPanel } from './newsPanel.js'; +import { + NEWS_CATEGORIES, + NEWS_SEVERITY, + categoryLabel, + feedCardView, + normalizeFilters, +} from '../layers/news/model.js'; + +const NOW = Date.parse('2026-10-28T10:00:00Z'); +const report = (id, extra = {}) => ({ + id, + title: `Report ${id}`, + url: `https://www.example.com/${id}`, + publishedAt: '2026-10-28T09:00:00.000Z', + publisher: 'Example', + side: 'UA', + category: 'strike', + severity: 2, + geo: { lat: 50, lon: 36, place: 'Kharkiv', mappable: true }, + pins: [{ lat: 50, lon: 36, place: 'Kharkiv', mappable: true }], + event: null, + media: [], + ...extra, +}); +const big = report('big', { + severity: 3, + titleEn: 'Strike on Kharkiv', + title: 'Удар по Харкову', + media: ['video'], + event: { + size: 4, + severity: 3, + status: 'both-sides', + lastAt: '2026-10-28T09:50:00.000Z', + sides: [ + { side: 'UA', title: 'a', url: 'https://a.test/', publisher: 'A' }, + { side: 'RU', title: 'b', url: 'https://b.test/', publisher: 'B' }, + ], + image: { url: 'https://a.test/p.jpg', publisher: 'A' }, + }, +}); + +function view(extra = {}) { + return { + filters: normalizeFilters(), + hotspots: [ + { id: 'all', label: 'All', count: 7, active: true }, + { id: 'ua-ru-war', label: 'Ukraine–Russia', count: 7, active: false }, + ], + categories: Object.keys(NEWS_CATEGORIES).map((id) => ({ + value: id, + label: categoryLabel(id), + })), + severities: NEWS_SEVERITY.map((level, index) => ({ + value: index, + label: level.label, + color: level.color, + })), + items: [feedCardView(big, NOW), feedCardView(report('lone'), NOW)], + inView: { active: false, loading: false, error: null, items: [] }, + selected: null, + hasMore: true, + loading: false, + error: null, + ...extra, + }; +} + +function fixture() { + document.body.innerHTML = ` + `; + const panel = document.getElementById('news-panel'); + let opened = 0; + panel + .querySelector('[data-collapse-target]') + .addEventListener('click', () => { + opened++; + panel.classList.remove('collapsed'); + }); + const calls = []; + const news = createNewsPanel({ + container: document.getElementById('news-panel-body'), + setLayerParams: (id, params, options) => calls.push([id, params, options]), + }); + return { news, panel, calls, opened: () => opened }; +} + +test('the panel shows the last 24 h as event cards and opens once', () => { + const { news, panel, opened } = fixture(); + news.update(null); + assert.equal(panel.hidden, true); + news.update(view()); + assert.equal(panel.hidden, false); + assert.equal(opened(), 1); + assert.equal(document.getElementById('news-panel-count').textContent, '2'); + assert.equal( + panel.querySelector('.news-readout__window').textContent, + 'Last 24 h', + ); + assert.deepEqual( + [...panel.querySelectorAll('.data-toggle-chip[data-chip-id]')].map( + (chip) => chip.textContent, + ), + ['All 7', 'Ukraine–Russia 7'], + ); + const [first, second] = panel.querySelectorAll( + '.news-readout__feed .news-card', + ); + assert.equal( + first.querySelector('.news-card__title').textContent, + 'Strike on Kharkiv', + ); + assert.equal( + first.querySelector('.news-card__note').textContent, + 'English headline by the model', + ); + assert.equal( + first.querySelector('.news-card__meta').textContent, + 'Strike · Kharkiv · 4 sources · 10 min', + ); + assert.equal( + first.querySelector('.news-card__marker').getAttribute('aria-label'), + 'Major', + ); + assert.equal( + first.querySelector('.news-card__sides').textContent, + 'Reported by UA sources · RU sources', + ); + assert.deepEqual( + [...first.querySelectorAll('.news-chip')].map((c) => c.textContent), + ['Reported by both sides', 'Video'], + ); + const img = first.querySelector('.news-card__thumb img'); + assert.equal(img.getAttribute('src'), 'https://a.test/p.jpg'); + assert.equal(img.getAttribute('referrerpolicy'), 'no-referrer'); + assert.equal(first.querySelector('.news-card__credit').textContent, 'A'); + // A lone report has no picture. + assert.equal(second.querySelector('.news-card__thumb'), null); + // A later update does not reopen a panel the reader collapsed. + panel.classList.add('collapsed'); + news.update(view()); + assert.equal(opened(), 1); + news.destroy(); + assert.equal(panel.hidden, true); +}); + +test('a card click flies there; open, it links the source and closes', () => { + const { news, panel, calls } = fixture(); + news.update(view()); + panel.querySelector('.news-card__main').click(); + assert.deepEqual(calls.at(-1), [ + 'news', + { reportId: 'big', focus: true }, + { origin: 'user' }, + ]); + news.update(view({ selected: feedCardView(big, NOW) })); + const open = panel.querySelector('.news-card.is-open'); + const link = open.querySelector('.news-card__link'); + assert.equal(link.textContent, 'Source: example.com ↗'); + assert.equal(link.getAttribute('href'), 'https://www.example.com/big'); + assert.equal(link.getAttribute('rel'), 'noopener noreferrer'); + assert.equal( + open.querySelector('.news-card__original').textContent, + 'Удар по Харкову', + ); + open.querySelector('.news-card__main').click(); + assert.deepEqual(calls.at(-1)[1], { clear: true }); + news.destroy(); +}); + +test('filters, In view and empty or failed reads', () => { + const { news, panel, calls } = fixture(); + news.update(view()); + assert.equal(panel.querySelector('[aria-label="In view"]'), null); + const severity = panel.querySelector('select[aria-label="Severity"]'); + assert.equal(severity.value, '2'); + severity.value = '3'; + severity.dispatchEvent(new Event('change')); + assert.deepEqual(calls.at(-1)[1], { filters: { minSeverity: 3 } }); + const [minor, cards] = panel.querySelectorAll('.news-toggle input'); + assert.equal(minor.checked, false); + assert.equal(cards.checked, true); + cards.checked = false; + cards.dispatchEvent(new Event('change')); + assert.deepEqual(calls.at(-1)[1], { filters: { cards: false } }); + panel.querySelector('[data-chip-id="ua-ru-war"]').click(); + assert.deepEqual(calls.at(-1)[1], { filters: { hotspot: 'ua-ru-war' } }); + + news.update( + view({ + inView: { active: true, loading: false, error: null, items: [] }, + items: [], + hasMore: false, + }), + ); + const section = panel.querySelector('[aria-label="In view"]'); + assert.match( + section.textContent, + /Nothing reported near here in the last 24 h/, + ); + assert.match( + panel.textContent, + /No news matches these filters in the last 24 h/, + ); + assert.equal(panel.querySelector('.news-readout__footer button'), null); + + news.update( + view({ items: [], error: 'News feed unavailable', hasMore: false }), + ); + assert.equal( + panel.querySelector('.news-readout__status').textContent, + 'News feed unavailable', + ); + news.destroy(); +}); diff --git a/src/ui/panelChrome.js b/src/ui/panelChrome.js index 439c1d77c..c5da55c43 100644 --- a/src/ui/panelChrome.js +++ b/src/ui/panelChrome.js @@ -17,6 +17,7 @@ const SHARE_PANEL_STATE_SPECS = Object.freeze([ { id: 'data-panel' }, { id: 'cctv-panel' }, { id: 'weather-panel' }, + { id: 'news-panel' }, { id: 'recent-imagery-panel' }, { id: 'street-level-panel' }, { id: 'radio-panel' }, @@ -41,6 +42,7 @@ const COCKPIT_ENTRY_COLLAPSE_PANEL_IDS = Object.freeze([ 'data-panel', 'cctv-panel', 'weather-panel', + 'news-panel', 'recent-imagery-panel', 'street-level-panel', 'scene-panel', diff --git a/src/ui/panelLayoutController.js b/src/ui/panelLayoutController.js index dddedf575..0c525a758 100644 --- a/src/ui/panelLayoutController.js +++ b/src/ui/panelLayoutController.js @@ -95,6 +95,7 @@ export class PanelLayoutController { this._ppToggles = document.getElementById('pp-toggles'); this._cctvPanel = document.getElementById('cctv-panel'); this._weatherPanel = document.getElementById('weather-panel'); + this._newsPanel = document.getElementById('news-panel'); this._recentImageryPanel = document.getElementById('recent-imagery-panel'); this._streetLevelPanel = document.getElementById('street-level-panel'); } @@ -191,6 +192,7 @@ export class PanelLayoutController { for (const panel of [ this._cctvPanel, this._weatherPanel, + this._newsPanel, this._recentImageryPanel, this._streetLevelPanel, ]) { @@ -206,6 +208,7 @@ export class PanelLayoutController { this._ppToggles, this._cctvPanel, this._weatherPanel, + this._newsPanel, this._recentImageryPanel, this._streetLevelPanel, globalContextPanel, diff --git a/src/ui/panelRailCatalog.js b/src/ui/panelRailCatalog.js index 7309c7f21..dbda77dcd 100644 --- a/src/ui/panelRailCatalog.js +++ b/src/ui/panelRailCatalog.js @@ -22,6 +22,7 @@ export const PANEL_RAIL_ITEMS = Object.freeze({ 'pp-toggles': { icon: 'tune', label: msg('DISPLAY') }, 'cctv-panel': { icon: 'videocam', label: msg('CCTV') }, 'weather-panel': { icon: 'partly_cloudy_day', label: msg('WEATHER') }, + 'news-panel': { icon: 'public', label: msg('NEWS') }, 'recent-imagery-panel': { icon: 'satellite_alt', label: msg('RECENT IMAGERY'), diff --git a/src/ui/styles/news.css b/src/ui/styles/news.css new file mode 100644 index 000000000..9b70f2004 --- /dev/null +++ b/src/ui/styles/news.css @@ -0,0 +1,378 @@ +/* News rail panel (#news-panel): the last 24 hours as a doom-scroll of event + cards drawn with GEV's own tokens. Colour is + severity only (the layer sets --news-color per card); never a side. The + rail owns placement and height; only the body scrolls. */ +.news-panel-inner { + position: relative; + display: flex; + flex-direction: column; + gap: 8px; + min-height: 0; + max-height: 100%; + box-sizing: border-box; + padding: 14px; + border: 1px solid var(--glass-border); + border-radius: var(--panel-radius); + background: var(--glass-bg); + backdrop-filter: blur(24px) saturate(1.4); + -webkit-backdrop-filter: blur(24px) saturate(1.4); + box-shadow: + 0 8px 32px rgba(0, 0, 0, 0.5), + 0 0 0 1px rgba(255, 255, 255, 0.03) inset, + 0 1px 0 rgba(255, 255, 255, 0.06) inset; +} +#news-panel .panel-glow { + position: absolute; + inset: -18px; + background: radial-gradient( + ellipse at center, + rgba(0, 212, 255, 0.16) 0%, + transparent 65% + ); + filter: blur(16px); + opacity: 0.25; + pointer-events: none; +} +#news-panel .panel-header { + flex: 0 0 auto; +} +#news-panel-count { + color: var(--text-secondary); + font: 9px var(--font-mono); +} +#news-panel-body { + min-height: 0; + max-height: calc(var(--right-stack-max-height, 50svh) - 64px); + overflow-y: auto; + overscroll-behavior: contain; +} +#news-panel.collapsed #news-panel-body, +#news-panel[hidden] { + display: none !important; +} +#right-context-rail > #news-panel { + position: relative; + inset: auto; + flex: 0 0 auto; + width: 100%; + max-height: 100%; + pointer-events: auto; +} +#right-context-rail > #news-panel:not(.collapsed) { + display: flex; + flex-direction: column; + flex-shrink: 1; + min-height: 0; +} +#right-context-rail.layout-focus > #news-panel:not(.collapsed) { + flex: 0 1 var(--right-panel-allocated-height); + height: var(--right-panel-allocated-height); + min-height: 0; + max-height: var(--right-panel-allocated-height); +} +#right-context-rail.layout-focus + > #news-panel:not(.collapsed) + .news-panel-inner { + height: 100%; +} +#right-context-rail[data-rail-measuring] + > #news-panel:not(.collapsed) + > .news-panel-inner { + height: auto !important; +} +#right-context-rail #news-panel.collapsed { + width: var(--right-display-collapsed-width); + margin-inline-start: auto; +} +#right-context-rail #news-panel.collapsed .news-panel-inner { + height: 50px; + min-height: 50px; + padding-bottom: 10px; +} +@media (max-width: 720px) { + #right-context-rail #news-panel.collapsed { + width: 100%; + } +} +:root[data-ui-theme='cyber'] .news-panel-inner { + border-radius: 0; + clip-path: var(--cyber-panel-frame); + box-shadow: var(--cyber-panel-shadow); +} + +.news-readout { + display: flex; + flex-direction: column; + gap: 10px; + min-width: 0; + color: var(--text-primary); + font: 11px/1.4 var(--font-sans); +} +.news-readout__window, +.news-readout__head { + margin: 0; + color: var(--text-secondary); + font: 600 9px var(--font-mono); + letter-spacing: 0.12em; + text-transform: uppercase; +} +.news-readout__chips { + display: flex; + flex-wrap: wrap; + gap: 4px; +} +.news-readout__filters { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 6px; +} +.news-filter { + min-width: 0; +} +.news-toggle { + display: flex; + align-items: center; + gap: 6px; + color: var(--text-secondary); + font-size: 10px; + cursor: pointer; +} +.news-toggle input { + accent-color: var(--accent); +} +.news-readout__section { + display: flex; + flex-direction: column; + gap: 6px; +} +.news-readout__list { + display: flex; + flex-direction: column; + gap: 6px; + margin: 0; + padding: 0; + list-style: none; +} +.news-readout__list.is-stale { + opacity: 0.5; +} +.news-readout__status, +.news-readout__empty { + color: var(--text-dim); + font: 10px var(--font-mono); +} +.news-readout__footer { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; +} + +.news-card { + border: 1px solid var(--glass-border); + border-inline-start: 3px solid var(--news-color, var(--glass-border)); + border-radius: 6px; + background: rgba(255, 255, 255, 0.02); +} +.news-card:hover, +.news-card.is-open { + border-color: var(--glass-border-hover); + border-inline-start-color: var(--news-color); + background: rgba(0, 212, 255, 0.06); +} +.news-card.is-unmapped .news-card__title { + color: var(--text-secondary); +} +.news-card__main { + display: grid; + grid-template-columns: 96px 1fr; + column-gap: 8px; + row-gap: 3px; + width: 100%; + padding: 6px; + border: 0; + background: transparent; + color: inherit; + font: inherit; + text-align: start; + cursor: pointer; +} +.news-card__main > :not(.news-card__thumb) { + grid-column: 1 / -1; +} +.news-card__thumb ~ * { + grid-column: 2 !important; +} +.news-card__thumb { + position: relative; + grid-row: 1 / span 5; + width: 96px; + height: 64px; + overflow: hidden; + border-radius: 4px; + background: var(--bg-dark); +} +.news-card__thumb img { + width: 100%; + height: 100%; + object-fit: cover; +} +.news-card__credit { + position: absolute; + inset-inline-end: 0; + bottom: 0; + max-width: 100%; + overflow: hidden; + padding: 0 4px; + background: rgba(0, 0, 0, 0.6); + color: var(--text-primary); + font-size: 8px; + text-overflow: ellipsis; + white-space: nowrap; +} +.news-card__title { + display: -webkit-box; + overflow: hidden; + -webkit-box-orient: vertical; + -webkit-line-clamp: 3; + font-size: 12px; + font-weight: 600; + line-height: 1.3; +} +.news-card__note, +.news-card__sides { + color: var(--text-secondary); + font-size: 10px; +} +.news-card__meta { + display: flex; + align-items: center; + gap: 5px; + min-width: 0; + color: var(--text-secondary); + font: 10px var(--font-mono); +} +.news-card__marker { + flex: none; + display: inline-grid; + place-items: center; + width: 14px; + height: 14px; + border: 1px solid rgba(0, 0, 0, 0.8); + border-radius: 50%; + background: var(--news-color); +} +.news-card__marker svg { + width: 9px; + height: 9px; + fill: none; + stroke: var(--bg-dark); + stroke-width: 1.8; + stroke-linecap: round; + stroke-linejoin: round; +} +.news-card__marker.solid svg { + fill: var(--bg-dark); + stroke: none; +} +.news-card__chips { + display: flex; + flex-wrap: wrap; + gap: 4px; +} +.news-chip { + padding: 1px 6px; + border: 1px solid var(--glass-border-hover); + border-radius: 999px; + color: var(--text-secondary); + font: 9px var(--font-mono); +} +.news-chip--official, +.news-chip--confirmed { + border-color: rgba(0, 212, 255, 0.45); + color: var(--text-primary); +} +.news-chip--claimed { + border-style: dashed; +} +.news-card__open { + display: flex; + flex-direction: column; + gap: 6px; + padding: 0 8px 8px; +} +.news-card__original, +.news-card__snippet { + margin: 0; + color: var(--text-primary); + font-size: 11px; +} +.news-card__original { + color: var(--text-secondary); +} +.news-card__others { + display: flex; + flex-direction: column; + gap: 3px; + margin: 0; + padding: 0; + list-style: none; + font-size: 10px; +} +.news-card__others a, +.news-card__link { + color: var(--accent); + text-decoration: none; + overflow-wrap: anywhere; +} +.news-card__others a:hover, +.news-card__link:hover { + text-decoration: underline; +} +.news-card__side { + margin-inline-end: 6px; + color: var(--text-secondary); +} +.news-card__actions { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + font: 10px var(--font-mono); +} +.news-legend { + color: var(--text-secondary); + font-size: 10px; +} +.news-legend summary { + cursor: pointer; +} +.news-legend p { + margin: 4px 0; +} +.news-legend__severity { + display: flex; + flex-wrap: wrap; + gap: 4px 10px; + margin: 4px 0; + padding: 0; + list-style: none; +} +.news-legend__severity li::before { + content: ''; + display: inline-block; + width: 8px; + height: 8px; + margin-inline-end: 4px; + border-radius: 50%; + background: var(--news-color); +} +@media (prefers-reduced-motion: no-preference) { + .news-card, + .news-readout__list { + transition: + background var(--transition-fast), + border-color var(--transition-fast), + opacity var(--transition-fast); + } +} diff --git a/src/ui/views/ContextView.vue b/src/ui/views/ContextView.vue index c40665fe4..a0236afb2 100644 --- a/src/ui/views/ContextView.vue +++ b/src/ui/views/ContextView.vue @@ -36,6 +36,10 @@ const sceneRuntime = computed(() => scenePanel.value?.runtime ?? '');
+