mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-12 14:22:21 +00:00
Merge remote-tracking branch 'origin/main' into feat/cctv-model-specs-refresh
# Conflicts: # docs/CURRENT-STATE.md
This commit is contained in:
commit
911ce59e53
401 files changed
+26614
-1711
No files matched your search
@@ -208,9 +208,10 @@ export function formatMeasure(session) {
|
||||
if (!session) return '';
|
||||
if (session.shape === 'line') {
|
||||
const m = pathLengthM(session.vertices);
|
||||
return m >= 1000
|
||||
? `${(m / 1000).toFixed(m >= 10000 ? 0 : 1)} km`
|
||||
: `${Math.round(m)} m`;
|
||||
// Round before the kilometre cut. 999.6 m was printed as "1000 m".
|
||||
const whole = Math.round(m);
|
||||
if (whole < 1000) return `${whole} m`;
|
||||
return `${(m / 1000).toFixed(m >= 10000 ? 0 : 1)} km`;
|
||||
}
|
||||
if (session.shape === 'area') {
|
||||
const m2 = ringAreaM2(session.vertices);
|
||||
|
||||
@@ -330,3 +330,18 @@ test('longitude unwrapping is continuous and re-wraps to one canonical range', (
|
||||
assert.equal(wrapLongitude(180), -180);
|
||||
assert.equal(unwrapLongitudes([]).length, 0);
|
||||
});
|
||||
|
||||
test('a line that rounds up to a kilometre reads 1.0 km, not 1000 m', () => {
|
||||
const metresPerDegree = (6371.0088 * 1000 * Math.PI) / 180;
|
||||
const lat = 999.6 / metresPerDegree;
|
||||
const line = createDrawSession('line');
|
||||
addVertex(line, { lon: 0, lat: 0 });
|
||||
addVertex(line, { lon: 0, lat });
|
||||
const metres = pathLengthM(line.vertices);
|
||||
assert.ok(
|
||||
metres >= 999.5 && metres < 1000,
|
||||
`length should round to 1000 m, got ${metres}`,
|
||||
);
|
||||
assert.equal(formatMeasure(line), '1.0 km');
|
||||
assert.match(drawHint(line), /^1\.0 km · /);
|
||||
});
|
||||
@@ -27,6 +27,7 @@ import { createApplicationEarthquakes } from './layers/earthquakes.js';
|
||||
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 { createApplicationCables } from './layers/submarineCables.js';
|
||||
import { createApplicationStreetLevel } from './layers/streetLevel.js';
|
||||
import { createInfrastructureLayers } from '../data/infrastructure.js';
|
||||
@@ -126,6 +127,7 @@ export function createApplicationCatalog({
|
||||
createApplicationGnssIntegrity({
|
||||
source: sources['gnss-integrity'],
|
||||
}),
|
||||
createApplicationGhostMaps({ source: sources['s2-ghostmaps'] }),
|
||||
createApplicationAlpr({ surface, source: sources.alpr }),
|
||||
createApplicationStreetLevel({
|
||||
surface,
|
||||
|
||||
@@ -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, 32);
|
||||
assert.equal(first.layers.length, 33);
|
||||
assert.ok(first.get('local-adsb'), 'Local ADS-B is registered');
|
||||
assert.deepEqual(
|
||||
first.metadata.find(({ id }) => id === 'local-adsb'),
|
||||
@@ -61,6 +61,7 @@ test('catalogs construct distinct layers and classification from their supplied
|
||||
);
|
||||
assert.ok(first.get('fire-perimeters'));
|
||||
assert.ok(first.get('gnss-integrity'));
|
||||
assert.ok(first.get('s2-ghostmaps'));
|
||||
assert.ok(first.get('transit'));
|
||||
const order = first.layers.map(({ id }) => id);
|
||||
assert.deepEqual(
|
||||
@@ -154,7 +155,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, 32);
|
||||
assert.equal(catalog.layers.length, 33);
|
||||
assert.deepEqual(catalog.get('street-level').providerIds, []);
|
||||
assert.equal(
|
||||
catalogControlServices(catalog).streetLevelLayer,
|
||||
|
||||
Vendored
+8
-1
@@ -4,7 +4,11 @@ import { flyToAustin } from '../camera.js';
|
||||
import { initCockpitCloudEffects } from '../cockpitCloudEffects.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
|
||||
/** Construct the existing controls and camera presentation. */
|
||||
/**
|
||||
* Construct the existing controls and camera presentation. `initialShareCode`
|
||||
* opens a share code (the `<code>` of `/share/<code>`) at start-up, for a host
|
||||
* whose address does not carry one.
|
||||
*/
|
||||
export function createApplicationControls({
|
||||
scene: { viewer, mapStackController, operations },
|
||||
loaderStatus,
|
||||
@@ -13,6 +17,7 @@ export function createApplicationControls({
|
||||
catalog,
|
||||
placeSearch,
|
||||
defer,
|
||||
initialShareCode = null,
|
||||
}) {
|
||||
// Initialize the style manager (post-processing, HUD, locations, share links)
|
||||
const styleManager = new Controls(viewer, {
|
||||
@@ -27,6 +32,8 @@ export function createApplicationControls({
|
||||
requestServices: operations.requests,
|
||||
mapStackController,
|
||||
placeSearch,
|
||||
// A share code to open at start-up instead of the page's address.
|
||||
initialShareCode,
|
||||
});
|
||||
defer(() => styleManager.orbitController.stop());
|
||||
defer(() => styleManager.hud.destroy());
|
||||
|
||||
@@ -13,6 +13,7 @@ export function createApplicationData({
|
||||
// Initialize data layer manager
|
||||
const dataManager = new LayerLifecycle(viewer, {
|
||||
allowQaRegistration,
|
||||
visibilityTarget: document,
|
||||
getSourceAvailability: catalog?.getSourceAvailability,
|
||||
});
|
||||
defer(async () => {
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { createGhostMapsLayer } from '../../layers/ghostMaps/index.js';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
import * as overlays from '../../overlays/worldOverlay.js';
|
||||
import { isPointerFree } from '../../data/inputOwnership.js';
|
||||
|
||||
/** Wire the S2 Underground GhostMaps layer into the application catalog. */
|
||||
export function createApplicationGhostMaps(options) {
|
||||
return createGhostMapsLayer({
|
||||
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,
|
||||
});
|
||||
}
|
||||
@@ -48,6 +48,7 @@ export const CATALOG_SOURCE_CONTRACTS = Object.freeze({
|
||||
'fire-perimeters': contract(['fire-perimeters'], ['getSnapshot']),
|
||||
'air-quality': contract(['air-quality'], ['getSnapshot']),
|
||||
'gnss-integrity': contract(['gnss-integrity'], ['getSnapshot']),
|
||||
's2-ghostmaps': contract(['s2-ghostmaps'], ['getCatalog', 'getFile']),
|
||||
cables: contract(['telegeography-submarine-cables'], ['fetch']),
|
||||
transit: contract(['transit'], ['requestSnapshot', 'getHistory']),
|
||||
});
|
||||
|
||||
@@ -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, 32);
|
||||
assert.equal(actual.layers.length, 33);
|
||||
const manager = new LayerLifecycle(
|
||||
{},
|
||||
{ getSourceAvailability: actual.getSourceAvailability },
|
||||
@@ -86,6 +86,70 @@ test('standalone defaults allow exact replacements and explicit removal, and rej
|
||||
);
|
||||
});
|
||||
|
||||
test('GhostMaps obeys source omission, replacement and explicit removal', async (t) => {
|
||||
let fetches = 0;
|
||||
t.mock.method(globalThis, 'fetch', async () => {
|
||||
fetches++;
|
||||
throw new Error('Unexpected standalone acquisition');
|
||||
});
|
||||
const missing = catalog({}, t);
|
||||
assert.equal(missing.getSourceAvailability('s2-ghostmaps')?.available, false);
|
||||
const manager = new LayerLifecycle(
|
||||
{},
|
||||
{ getSourceAvailability: missing.getSourceAvailability },
|
||||
);
|
||||
manager.register(missing.get('s2-ghostmaps'));
|
||||
assert.equal(await manager.setEnabled('s2-ghostmaps', true), false);
|
||||
assert.equal(manager.layers.get('s2-ghostmaps').initialized, false);
|
||||
assert.equal(
|
||||
createStandaloneLayerSources({ 's2-ghostmaps': null })['s2-ghostmaps'],
|
||||
null,
|
||||
);
|
||||
|
||||
let reads = 0;
|
||||
let subscriptions = 0;
|
||||
let unsubscribed = 0;
|
||||
const source = {
|
||||
getCatalog: async () => {
|
||||
reads++;
|
||||
return { commit: 'a'.repeat(40), products: [] };
|
||||
},
|
||||
getFile: async () => {
|
||||
throw new Error('Empty catalog must not read files');
|
||||
},
|
||||
subscribe: () => {
|
||||
subscriptions++;
|
||||
return () => {
|
||||
unsubscribed++;
|
||||
};
|
||||
},
|
||||
};
|
||||
const supplied = createStandaloneLayerSources({ 's2-ghostmaps': source });
|
||||
assert.equal(supplied['s2-ghostmaps'], source);
|
||||
const configured = catalog(supplied, t);
|
||||
assert.equal(
|
||||
configured.getSourceAvailability('s2-ghostmaps').available,
|
||||
true,
|
||||
);
|
||||
const previous = Object.getOwnPropertyDescriptor(globalThis, 'document');
|
||||
globalThis.document = { addEventListener() {}, removeEventListener() {} };
|
||||
t.after(() => {
|
||||
if (previous) Object.defineProperty(globalThis, 'document', previous);
|
||||
else delete globalThis.document;
|
||||
});
|
||||
const layer = configured.get('s2-ghostmaps');
|
||||
t.after(() => layer.destroy());
|
||||
layer.init({ scene: { requestRender() {} } });
|
||||
layer.enable();
|
||||
await layer.update();
|
||||
layer.disable();
|
||||
assert.equal(reads, 1);
|
||||
assert.equal(subscriptions, 1);
|
||||
assert.equal(unsubscribed, 1);
|
||||
assert.equal(layer.getStats().commit, 'a'.repeat(40));
|
||||
assert.equal(fetches, 0);
|
||||
});
|
||||
|
||||
test('empty Street Level uses the shared unavailable lifecycle without initialization', async (t) => {
|
||||
const actual = catalog({}, t);
|
||||
const manager = new LayerLifecycle(
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
// Compatibility entry; source contracts are owned by sources/.
|
||||
export { createSourceSlot } from '../sources/sourceSlot.js';
|
||||
@@ -1,24 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createSourceSlot } from './sourceSlot.js';
|
||||
|
||||
test('replacing a source rejects its late result and old cleanup cannot clear the new source', async () => {
|
||||
let finish;
|
||||
const slot = createSourceSlot({ read: async () => 'default' }, ['read']);
|
||||
const old = slot.configure({ read: () => new Promise(resolve => { finish = resolve; }) });
|
||||
const pending = slot.source.read();
|
||||
const stop = slot.configure({ read: async () => 'replacement', attribution: { name: 'Replacement' } });
|
||||
old();
|
||||
finish('stale');
|
||||
await assert.rejects(pending, { name: 'AbortError' });
|
||||
assert.equal(await slot.source.read(), 'replacement');
|
||||
assert.equal(slot.source.attribution.name, 'Replacement');
|
||||
stop();
|
||||
assert.throws(() => slot.source.read(), /not configured/);
|
||||
});
|
||||
|
||||
test('an invalid replacement leaves the working source intact', async () => {
|
||||
const slot = createSourceSlot({ read: async () => 42 }, ['read']);
|
||||
assert.throws(() => slot.configure({}), TypeError);
|
||||
assert.equal(await slot.source.read(), 42);
|
||||
});
|
||||
@@ -7,6 +7,7 @@ import { createRecentImageryPanel } from '../ui/recentImagery.js';
|
||||
import { initGevVoiceCommands } from '../voice/gevRealtime.js';
|
||||
import { installViews, isEmbeddedInline } from './embed.js';
|
||||
import { installScopeMask, destroyScopeMask } from '../scopeMask.js';
|
||||
import { installLayerReleaseTrim } from '../sceneCommandRelease.js';
|
||||
import {
|
||||
installRenderGovernor,
|
||||
getRenderGovernorDiagnostics,
|
||||
@@ -110,6 +111,15 @@ export function createApplicationTools({
|
||||
// nothing animates per frame. Installed AFTER every module above has had
|
||||
// its chance to register pre-install holds. (perf wave 2)
|
||||
installRenderGovernor(viewer);
|
||||
// Cesium keeps a turned-off layer's draw commands (and so all its entities)
|
||||
// alive in reused per-pass arrays; trim them after each disable.
|
||||
defer(
|
||||
installLayerReleaseTrim({
|
||||
scene: viewer.scene,
|
||||
dataManager,
|
||||
requestRender: governorRequestRender,
|
||||
}),
|
||||
);
|
||||
|
||||
// Install the explicit scope mask used by the DISPLAY controls.
|
||||
installScopeMask(viewer);
|
||||
|
||||
@@ -137,6 +137,11 @@ export function createApplicationViewer({ container, creditContainer }) {
|
||||
);
|
||||
try {
|
||||
viewer.targetFrameRate = 60;
|
||||
// A phone pinch spans fewer screen pixels than desktop zoom gestures.
|
||||
// Keep Cesium's distance-aware zoom and collision limits, with less travel
|
||||
// required on touch-first screens. Mouse/trackpad sensitivity stays native.
|
||||
if (globalThis.matchMedia?.('(pointer: coarse)').matches)
|
||||
viewer.scene.screenSpaceCameraController.zoomFactor *= 3;
|
||||
// Before any tile builds a draw command: Cesium's per-vertex model
|
||||
// atmosphere fails to LINK on Apple's Metal backend and kills the
|
||||
// render loop. See app/atmosphereCompat.js.
|
||||
|
||||
@@ -261,7 +261,7 @@ test('deferred search releases only after its final authority check', () => {
|
||||
assert.match(ui, /begin: \(\) => this\._beginDeferredNavigation\('location'\)/);
|
||||
assert.match(ui, /beforeFly: \(generation\) => this\._reassertNavigationHandoff\(generation\)/);
|
||||
assert.match(ui, /isCurrent: \(generation\) =>\s*!this\._disposed && generation === this\._navigationGeneration/);
|
||||
assert.match(ui, /change\.type === 'settled'\)\s*this\._settleLocationSearchUi\(change\.generation\)/);
|
||||
assert.match(ui, /change\.type === 'settled'\)\s*this\._settleLocationSearchUi\(change\.generation, \{\s*keepQuery: state\.status === 'missing' \|\| state\.status === 'failed',?\s*\}\)/);
|
||||
assert.doesNotMatch(search.slice(0, search.indexOf('await this.search')), /_releaseFollowCamera/);
|
||||
});
|
||||
|
||||
|
||||
@@ -6,6 +6,15 @@ export function normalizeHeading(value) {
|
||||
return ((value % 360) + 360) % 360;
|
||||
}
|
||||
|
||||
/**
|
||||
* Three-digit heading readout, 000–359.
|
||||
* Rounding 359.5° and above lands on north (000), not 360.
|
||||
*/
|
||||
export function formatHeadingReadout(degrees) {
|
||||
if (!Number.isFinite(degrees)) return '---';
|
||||
return String(Math.round(normalizeHeading(degrees)) % 360).padStart(3, '0');
|
||||
}
|
||||
|
||||
/** Advance a displayed heading along the shortest arc without exceeding a slew rate. */
|
||||
export function slewHeading(current, target, maxStepDeg) {
|
||||
const from = normalizeHeading(current);
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
formatCockpitContextScope,
|
||||
formatCockpitEmergency,
|
||||
formatCompassDivision,
|
||||
formatHeadingReadout,
|
||||
formatSpeedRulerTick,
|
||||
normalizeHeading,
|
||||
relativeBearing,
|
||||
@@ -155,6 +156,14 @@ test('compass labels use cardinals where exact and degrees elsewhere', () => {
|
||||
assert.equal(formatCompassDivision(30), '030');
|
||||
});
|
||||
|
||||
test('a heading that rounds to north reads 000, not 360', () => {
|
||||
assert.equal(formatHeadingReadout(359.6), '000');
|
||||
assert.equal(formatHeadingReadout(359.4), '359');
|
||||
assert.equal(formatHeadingReadout(0), '000');
|
||||
assert.equal(formatHeadingReadout(10.2), '010');
|
||||
assert.equal(formatHeadingReadout(Number.NaN), '---');
|
||||
});
|
||||
|
||||
test('great-circle bearing resolves cardinal directions', () => {
|
||||
assert.ok(Math.abs(bearingBetweenCoordinates(0, 0, 1, 0) - 0) < 0.001);
|
||||
assert.ok(Math.abs(bearingBetweenCoordinates(0, 0, 0, 1) - 90) < 0.001);
|
||||
|
||||
@@ -94,6 +94,15 @@ test('context restore settles the Contacts coordinator before dependency fanout'
|
||||
assert.match(restore, /excludeLayerIds: settleContactsCoordinator[\s\S]*?contactsCoordinatorId/);
|
||||
});
|
||||
|
||||
test('Clear All during the Contacts settle stops the snapshot coming back', () => {
|
||||
const restore = _restoreContextSession.toString();
|
||||
const coordinatorOff = restore.indexOf('const coordinatorSettled = await this._dataManager.setEnabled(');
|
||||
const cancelled = restore.indexOf('if (restoreState.cancelled) return;', coordinatorOff);
|
||||
const fanout = restore.indexOf('await this._dataManager.restoreEnabledLayerIds(', coordinatorOff);
|
||||
assert.ok(cancelled > coordinatorOff, 'the cancellation is checked after Contacts settles');
|
||||
assert.ok(fanout > cancelled, 'and before the snapshot fans out');
|
||||
});
|
||||
|
||||
test('context restore preserves its exact pending target after a failed transition', () => {
|
||||
const restore = _restoreContextSession.toString();
|
||||
assert.match(restore, /const replayError = await settleContextIntentReplay\(\{/);
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Lighting options shared by every aircraft 3D model (Flights, Military
|
||||
* Flights, Local ADS-B).
|
||||
*
|
||||
* Cesium gives each Model a dynamic environment map: it renders the sky around
|
||||
* the model and reads the result back from the GPU (`readPixels`) to light it,
|
||||
* when the model is first placed and again when it moves more than 1 km, when
|
||||
* the scene's atmosphere settings change, or every scene hour under sunlight
|
||||
* lighting. Aircraft models take 94% of their surface from the class colour
|
||||
* (`colorBlendAmount`), so that lighting contributes little; without it they
|
||||
* are lit from Cesium's default spherical harmonics. Measured 2026-10-24
|
||||
* (Intel Arc, Google 3D, ~150 models in the scene): GPU per frame at rest
|
||||
* 14.3-14.8 -> 12.1-12.5 ms.
|
||||
*/
|
||||
export const AIRCRAFT_ENVIRONMENT_MAP_OPTIONS = Object.freeze({
|
||||
enabled: false,
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { readLayerSource } from '../testSupport/readLayerSource.mjs';
|
||||
import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from './aircraftModelLighting.js';
|
||||
|
||||
/**
|
||||
* Every aircraft model drawn in the scene skips Cesium's dynamic environment
|
||||
* map (a sky render and GPU readback per model). The preload calls only warm
|
||||
* the glTF cache and are never added to the scene, so they are left out:
|
||||
* drawn models are the calls that set a minimum pixel size.
|
||||
*/
|
||||
const SOURCES = [
|
||||
{
|
||||
name: 'flights',
|
||||
source: readLayerSource(new URL('./flights.js', import.meta.url)),
|
||||
},
|
||||
{
|
||||
name: 'militaryFlights',
|
||||
source: readLayerSource(new URL('./militaryFlights.js', import.meta.url)),
|
||||
},
|
||||
{
|
||||
name: 'localAdsb',
|
||||
source: readFileSync(
|
||||
new URL('../layers/localAdsb/models.js', import.meta.url),
|
||||
'utf8',
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
test('the shared option turns the dynamic environment map off', () => {
|
||||
assert.deepEqual({ ...AIRCRAFT_ENVIRONMENT_MAP_OPTIONS }, { enabled: false });
|
||||
assert.ok(Object.isFrozen(AIRCRAFT_ENVIRONMENT_MAP_OPTIONS));
|
||||
});
|
||||
|
||||
for (const { name, source } of SOURCES) {
|
||||
test(`${name}: every drawn aircraft model skips the dynamic environment map`, () => {
|
||||
const calls = [
|
||||
...source.matchAll(/(?:fromGltfAsync|loadModel)\(\{([\s\S]*?)\}\)/g),
|
||||
]
|
||||
.map((match) => match[1])
|
||||
.filter((options) => /\bminimumPixelSize:/.test(options));
|
||||
assert.ok(calls.length >= 1, `expected drawn model calls in ${name}`);
|
||||
for (const [index, options] of calls.entries())
|
||||
assert.match(
|
||||
options,
|
||||
/\benvironmentMapOptions:\s*AIRCRAFT_ENVIRONMENT_MAP_OPTIONS\b/,
|
||||
`${name} model call ${index + 1} must pass AIRCRAFT_ENVIRONMENT_MAP_OPTIONS`,
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
AISSTREAM_STALE_MS,
|
||||
aisStreamRows,
|
||||
ingestAisStreamEnvelope,
|
||||
readAisTrack,
|
||||
} from '../../server/providers/vessels/ais-store.js';
|
||||
|
||||
// ITU-R M.1371 encodes speed over ground in 0.1-knot units and course over
|
||||
@@ -63,3 +65,196 @@ test('the fastest encodable reading below the unavailable code is kept', () => {
|
||||
assert.equal(row.speed, 102.2);
|
||||
assert.equal(row.course, 359.9);
|
||||
});
|
||||
|
||||
test('a static data report keeps the motion and fix time of a tracked vessel', () => {
|
||||
ingestAisStreamEnvelope(
|
||||
positionReport('244690000', { Sog: 12.4, Cog: 86.7, TrueHeading: 87 }),
|
||||
);
|
||||
// AISStream's MetaData carries the last known position on every message,
|
||||
// static data included.
|
||||
assert.equal(
|
||||
ingestAisStreamEnvelope({
|
||||
MessageType: 'ShipStaticData',
|
||||
Message: {
|
||||
ShipStaticData: {
|
||||
UserID: 244690000,
|
||||
Name: 'EXAMPLE VESSEL',
|
||||
Type: 70,
|
||||
Destination: 'ROTTERDAM',
|
||||
ImoNumber: 9876543,
|
||||
},
|
||||
},
|
||||
MetaData: {
|
||||
MMSI: '244690000',
|
||||
latitude: 53.40879,
|
||||
longitude: 6.19741,
|
||||
time_utc: '2026-09-17 20:05:00.000000000 +0000 UTC',
|
||||
},
|
||||
}),
|
||||
true,
|
||||
);
|
||||
const row = rowFor('244690000');
|
||||
assert.equal(row.speed, 12.4);
|
||||
assert.equal(row.course, 86.7);
|
||||
assert.equal(row.heading, 87);
|
||||
assert.equal(row.last_position_UTC, '2026-09-17T20:00:00.000Z');
|
||||
assert.equal(row.destination, 'ROTTERDAM');
|
||||
assert.equal(row.imo, '9876543');
|
||||
});
|
||||
|
||||
// AISStream carries both Class B parts; the unused part has Valid: false.
|
||||
const classBStatic = (part, value) => ({
|
||||
MessageID: 24,
|
||||
RepeatIndicator: 0,
|
||||
Valid: true,
|
||||
Reserved: 0,
|
||||
PartNumber: part === 'B',
|
||||
ReportA: { Valid: part === 'A', Name: part === 'A' ? value : '' },
|
||||
ReportB: {
|
||||
Valid: part === 'B',
|
||||
ShipType: part === 'B' ? value : 0,
|
||||
VendorIDName: '',
|
||||
VenderIDModel: 0,
|
||||
VenderIDSerial: 0,
|
||||
CallSign: '',
|
||||
Dimension: { A: 0, B: 0, C: 0, D: 0 },
|
||||
FixType: 0,
|
||||
Spare: 0,
|
||||
},
|
||||
});
|
||||
|
||||
for (const [index, scenario] of [
|
||||
{
|
||||
type: 'ShipStaticData',
|
||||
initial: [
|
||||
{
|
||||
Name: 'OLD VESSEL',
|
||||
Type: 70,
|
||||
Destination: 'ROTTERDAM',
|
||||
ImoNumber: 9876543,
|
||||
},
|
||||
],
|
||||
updates: [
|
||||
{
|
||||
Name: 'NEW VESSEL',
|
||||
Type: 80,
|
||||
Destination: 'HAMBURG',
|
||||
ImoNumber: 9876544,
|
||||
},
|
||||
],
|
||||
empty: { Name: ' ', Type: 0, Destination: '', ImoNumber: 0 },
|
||||
expected: {
|
||||
name: 'NEW VESSEL',
|
||||
type: '80',
|
||||
destination: 'HAMBURG',
|
||||
imo: '9876544',
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'StaticDataReport',
|
||||
initial: [classBStatic('A', 'OLD VESSEL'), classBStatic('B', 36)],
|
||||
updates: [classBStatic('A', 'NEW VESSEL'), classBStatic('B', 37)],
|
||||
empty: classBStatic('A', ''),
|
||||
expected: { name: 'NEW VESSEL', type: '37', destination: '', imo: '' },
|
||||
},
|
||||
].entries()) {
|
||||
test(`${scenario.type} replaces static fields without inventing a position fix`, (t) => {
|
||||
const mmsi = String(244690100 + index);
|
||||
const start = Date.parse('2026-09-17T20:00:00Z');
|
||||
let now = start;
|
||||
t.mock.method(Date, 'now', () => now);
|
||||
const position = (
|
||||
lat,
|
||||
body = { Sog: 12.4, Cog: 86.7, TrueHeading: 87 },
|
||||
) => {
|
||||
const envelope = positionReport(mmsi, body);
|
||||
Object.assign(envelope.MetaData, {
|
||||
latitude: lat,
|
||||
time_utc: new Date(now).toISOString(),
|
||||
});
|
||||
return ingestAisStreamEnvelope(envelope);
|
||||
};
|
||||
const sendStatic = (body) =>
|
||||
ingestAisStreamEnvelope({
|
||||
MessageType: scenario.type,
|
||||
Message: { [scenario.type]: { UserID: Number(mmsi), ...body } },
|
||||
MetaData: {
|
||||
MMSI: mmsi,
|
||||
ShipName: 'STALE HEADER',
|
||||
latitude: 54,
|
||||
longitude: 7,
|
||||
time_utc: new Date(now).toISOString(),
|
||||
},
|
||||
});
|
||||
position(53.40879);
|
||||
for (const body of scenario.initial) assert.equal(sendStatic(body), true);
|
||||
now += 60_000;
|
||||
position(53.41879);
|
||||
const before = rowFor(mmsi);
|
||||
const track = readAisTrack(mmsi);
|
||||
assert.equal(track.length, 2);
|
||||
|
||||
now += 5 * 60_000;
|
||||
for (const body of scenario.updates) assert.equal(sendStatic(body), true);
|
||||
assert.deepEqual(rowFor(mmsi), { ...before, ...scenario.expected });
|
||||
assert.deepEqual(readAisTrack(mmsi), track);
|
||||
|
||||
// Empty or omitted static fields must not erase known metadata, including
|
||||
// the cached values used when the next actual position arrives.
|
||||
assert.equal(sendStatic(scenario.empty), true);
|
||||
assert.deepEqual(rowFor(mmsi), { ...before, ...scenario.expected });
|
||||
assert.deepEqual(readAisTrack(mmsi), track);
|
||||
if (scenario.type === 'StaticDataReport') {
|
||||
sendStatic({
|
||||
...classBStatic('A', ''),
|
||||
ReportA: { Valid: false, Name: 'INVALID NAME' },
|
||||
ReportB: { ...classBStatic('B', 99).ReportB, Valid: false },
|
||||
});
|
||||
assert.deepEqual(rowFor(mmsi), { ...before, ...scenario.expected });
|
||||
}
|
||||
now = start + 60_000 + AISSTREAM_STALE_MS + 1;
|
||||
assert.equal(
|
||||
rowFor(mmsi),
|
||||
undefined,
|
||||
'static traffic must not renew position freshness',
|
||||
);
|
||||
position(53.42879, { Sog: 0, Cog: 0, TrueHeading: 0 });
|
||||
const next = rowFor(mmsi);
|
||||
for (const [key, value] of Object.entries(scenario.expected))
|
||||
assert.equal(next[key], value, key);
|
||||
assert.equal(next.speed, 0);
|
||||
assert.equal(next.course, 0);
|
||||
assert.equal(next.heading, 0);
|
||||
assert.equal(next.last_position_epoch, Math.floor(now / 1000));
|
||||
assert.equal(readAisTrack(mmsi).length, 3);
|
||||
});
|
||||
}
|
||||
|
||||
test('partial static data keeps newer live metadata ahead of the old static cache', () => {
|
||||
const mmsi = '244690200';
|
||||
const staticReport = (body) => ({
|
||||
MessageType: 'ShipStaticData',
|
||||
Message: { ShipStaticData: { UserID: Number(mmsi), ...body } },
|
||||
MetaData: { MMSI: mmsi },
|
||||
});
|
||||
ingestAisStreamEnvelope(staticReport({ Name: 'OLD VESSEL', Type: 70 }));
|
||||
const extended = positionReport(mmsi, {});
|
||||
extended.MessageType = 'ExtendedClassBPositionReport';
|
||||
extended.Message = {
|
||||
ExtendedClassBPositionReport: {
|
||||
UserID: Number(mmsi),
|
||||
Type: 80,
|
||||
Sog: 12,
|
||||
Cog: 86,
|
||||
},
|
||||
};
|
||||
extended.MetaData.ShipName = 'NEW VESSEL';
|
||||
ingestAisStreamEnvelope(extended);
|
||||
const before = rowFor(mmsi);
|
||||
ingestAisStreamEnvelope(staticReport({ Destination: 'HAMBURG' }));
|
||||
assert.deepEqual(rowFor(mmsi), { ...before, destination: 'HAMBURG' });
|
||||
ingestAisStreamEnvelope(positionReport(mmsi, { Sog: 12, Cog: 86 }));
|
||||
assert.equal(rowFor(mmsi).name, 'NEW VESSEL');
|
||||
assert.equal(rowFor(mmsi).type, '80');
|
||||
assert.equal(rowFor(mmsi).destination, 'HAMBURG');
|
||||
});
|
||||
@@ -9,6 +9,8 @@ import alprCamerasLayer, {
|
||||
} from './alprCameras.js';
|
||||
import { createAlprTileSource } from '../layers/alpr/source.js';
|
||||
import { DATA_CREDITS } from './dataCredits.js';
|
||||
import { setLocale } from '../i18n/index.js';
|
||||
import { shownEntityLabel } from '../voice/speech.js';
|
||||
import {
|
||||
clearSelectedEntityContextForLayer,
|
||||
getContextStore,
|
||||
@@ -473,6 +475,29 @@ test('all manufacturers share one ALPR title and color; only supplied metadata a
|
||||
}
|
||||
});
|
||||
|
||||
// The voice model reads the label as data; the voice card translates it.
|
||||
test('the camera label stays English data in a translated interface', async () => {
|
||||
const h = cameraHarness();
|
||||
try {
|
||||
setLocale('ru');
|
||||
h.setFetch(async () =>
|
||||
cameraResponse([
|
||||
cameraNode(42, { tags: { 'surveillance:type': 'ALPR' } }),
|
||||
]),
|
||||
);
|
||||
await alprCamerasLayer.update();
|
||||
h.click(h.source.entities.values[0].id);
|
||||
assert.equal(getSelectedEntityContext().label, 'ALPR camera');
|
||||
assert.equal(
|
||||
shownEntityLabel(getSelectedEntityContext().label),
|
||||
'Камера ALPR',
|
||||
);
|
||||
} finally {
|
||||
setLocale('en');
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('invalid OSM ids and out-of-range coordinates never become camera entities', () => {
|
||||
for (const id of [undefined, null, 0, -1, 1.5, '42', NaN])
|
||||
assert.equal(normalizeAlprNode(cameraNode(id, { id })), null);
|
||||
|
||||
@@ -728,6 +728,8 @@ for (const phase of ['timer', 'move-end', 'approach', 'orbit']) {
|
||||
viewer,
|
||||
_sceneSeekGeneration: 0,
|
||||
_loadGeneration: 0,
|
||||
_bumpSceneSeekGeneration:
|
||||
SceneDirector.prototype._bumpSceneSeekGeneration,
|
||||
_cancelActiveSceneTravel:
|
||||
SceneDirector.prototype._cancelActiveSceneTravel,
|
||||
_setSceneMediaPlayback: SceneDirector.prototype._setSceneMediaPlayback,
|
||||
|
||||
@@ -115,7 +115,8 @@ test('status retains official clocks, knots, source links and finite current pos
|
||||
assert.equal(storm.issuedAt, TIME);
|
||||
assert.equal(storm.positionAt, TIME);
|
||||
assert.deepEqual(storm.position, { longitude: -125.8, latitude: 15.5 });
|
||||
assert.deepEqual(storm.movement, { directionDegrees: 255, speedKt: 12 });
|
||||
// NHC publishes movementSpeed in mph: 12 mph is 10 kt.
|
||||
assert.deepEqual(storm.movement, { directionDegrees: 255, speedKt: 10 });
|
||||
assert.equal(storm.windKt, 25);
|
||||
assert.equal(storm.pressureHpa, 1006);
|
||||
assert.match(storm.advisoryUrl, /^https:\/\/www\.nhc\.noaa\.gov\/text\//);
|
||||
|
||||
@@ -448,6 +448,14 @@ export const DATA_CREDITS = [
|
||||
'(<a href="https://earthdata.nasa.gov/firms" target="_blank" rel="noopener">earthdata.nasa.gov/firms</a>), ' +
|
||||
'part of NASA’s Earth Observing System Data and Information System (EOSDIS)',
|
||||
},
|
||||
{
|
||||
key: 's2-ghostmaps',
|
||||
html:
|
||||
'S2 GhostMaps intel products: S2 Underground © by S2A1, ' +
|
||||
'<a href="https://github.com/s2underground/GhostMaps" target="_blank" rel="noopener">github.com/s2underground/GhostMaps</a>, ' +
|
||||
'licensed under <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank" rel="noopener">CC BY-NC-SA 4.0</a>. ' +
|
||||
'Shown as published; reports are S2 assessments, not verified fact.',
|
||||
},
|
||||
{
|
||||
key: 'drivebc-cctv',
|
||||
html:
|
||||
|
||||
@@ -846,9 +846,13 @@ test('route numbers follow the page language and never break from their unit', (
|
||||
t.after(() => setLocale('en'));
|
||||
assert.equal(routeDistanceText(8.4), '8\u00a0m');
|
||||
assert.equal(routeDistanceText(236), '240\u00a0m');
|
||||
assert.equal(routeDistanceText(994), '990\u00a0m');
|
||||
assert.equal(routeDistanceText(996), '1.0\u00a0km');
|
||||
assert.equal(routeDistanceText(1500), '1.5\u00a0km');
|
||||
assert.equal(routeDistanceText(2_345_000), '2345\u00a0km');
|
||||
assert.equal(routeDurationText(39), '39\u00a0s');
|
||||
assert.equal(routeDurationText(59.4), '59\u00a0s');
|
||||
assert.equal(routeDurationText(59.6), '1\u00a0min');
|
||||
assert.equal(routeDurationText(3900), '1\u00a0h\u00a05\u00a0min');
|
||||
assert.equal(routeDurationText(7200), '2\u00a0h');
|
||||
assert.equal(routeDistanceText(-1), '');
|
||||
@@ -872,3 +876,46 @@ test('route numbers follow the page language and never break from their unit', (
|
||||
const list = directionsStepList({ route });
|
||||
assert.equal(list.items[1].lead, '240\u00a0м');
|
||||
});
|
||||
|
||||
test('ramp and lane wording stays localized after choosing the maneuver form', (t) => {
|
||||
t.after(() => setLocale('en'));
|
||||
const cases = [
|
||||
[
|
||||
'ru',
|
||||
'Въезжайте по съезду плавно налево на I-95',
|
||||
'Сверните на съезд резко направо',
|
||||
'Займите левую полосу',
|
||||
],
|
||||
[
|
||||
'es',
|
||||
'Toma la rampa ligeramente a la izquierda hacia I-95',
|
||||
'Toma la salida bruscamente a la derecha',
|
||||
'Toma el carril izquierdo',
|
||||
],
|
||||
[
|
||||
'zh-CN',
|
||||
'向左前方驶入匝道,进入 I-95',
|
||||
'从出口向右后方驶出',
|
||||
'使用左转车道',
|
||||
],
|
||||
];
|
||||
for (const [locale, ramp, exit, lane] of cases) {
|
||||
setLocale(locale);
|
||||
assert.equal(
|
||||
directionsInstruction({
|
||||
type: 'on ramp',
|
||||
modifier: 'slight left',
|
||||
name: 'I-95',
|
||||
}),
|
||||
ramp,
|
||||
);
|
||||
assert.equal(
|
||||
directionsInstruction({ type: 'off ramp', modifier: 'sharp right' }),
|
||||
exit,
|
||||
);
|
||||
assert.equal(
|
||||
directionsInstruction({ type: 'use lane', modifier: 'sharp left' }),
|
||||
lane,
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -53,6 +53,21 @@ test('buildFireCard: missing acquisition time omits the age segment', () => {
|
||||
assert.equal(card.details[0], 'high · N20');
|
||||
});
|
||||
|
||||
test('buildFireCard: power that rounds to 10 MW drops the decimal', () => {
|
||||
const crossed = buildFireCard(
|
||||
{ fire: fire({ frp: 9.96 }), position: {} },
|
||||
NOW,
|
||||
);
|
||||
assert.equal(crossed.title, '▲ 10 MW');
|
||||
const below = buildFireCard(
|
||||
{ fire: fire({ frp: 9.94 }), position: {} },
|
||||
NOW,
|
||||
);
|
||||
assert.equal(below.title, '▲ 9.9 MW');
|
||||
const selected = buildSelectedFireCard(fire({ frp: 9.96 }), NOW);
|
||||
assert.equal(selected.title, 'FIRE · 10 MW');
|
||||
});
|
||||
|
||||
test('buildFireCard: SNPP satellite code renders as SNPP, weak fire is not red', () => {
|
||||
const card = buildFireCard({ fire: fire({ satellite: 'N', frp: 0.8, confidence: 0.3 }), position: {} }, NOW);
|
||||
assert.match(card.details[0], /SNPP$/);
|
||||
|
||||
@@ -8,6 +8,9 @@ import * as Cesium from 'cesium';
|
||||
import { createFirmsHeatmapLayer, applyFirmsOverlayPolicy, buildCellCard } from './firmsHeatmap.js';
|
||||
import { fireDetectionKey } from './firmsLabels.js';
|
||||
import { registerPickOwner, unregisterPickOwner } from './pickRegistry.js';
|
||||
import { getSelectedEntityContext } from './contextStore.js';
|
||||
import { setLocale } from '../i18n/index.js';
|
||||
import { shownEntityLabel } from '../voice/speech.js';
|
||||
import { WORLD_FOCUS_REQUEST_EVENT } from '../worldFocus.js';
|
||||
import { readLayerSource } from '../testSupport/readLayerSource.mjs';
|
||||
import path from 'node:path';
|
||||
@@ -234,6 +237,27 @@ test('clicking a fire CARD behaves exactly like clicking its sprite', () => {
|
||||
}
|
||||
});
|
||||
|
||||
// The voice model reads these labels as data (track_entity, get_entity_context,
|
||||
// pointer_context); the voice card translates them where it shows them.
|
||||
test('fire labels stay English data in a translated interface', () => {
|
||||
const h = harness({ fires: [makeFire()], picked: { id: 'firms-7' } });
|
||||
try {
|
||||
setLocale('ru');
|
||||
h.click();
|
||||
assert.equal(getSelectedEntityContext().label, 'Fire · FRP 1520 MW');
|
||||
// The card's pattern must match what the producer actually writes.
|
||||
assert.equal(
|
||||
shownEntityLabel(getSelectedEntityContext().label),
|
||||
'Пожар · FRP 1520 МВт',
|
||||
);
|
||||
assert.equal(h.layer.getSelectedInfo().label, 'Fire · FRP 1520 MW');
|
||||
assert.equal(h.layer.getStrongestFire().label, 'Fire · FRP 1520 MW');
|
||||
} finally {
|
||||
h.cleanup();
|
||||
setLocale('en');
|
||||
}
|
||||
});
|
||||
|
||||
test('a click on neither sprite nor card clears without moving the camera', () => {
|
||||
const h = harness({ picked: { primitive: {}, content: {}, featureId: 0 } });
|
||||
try {
|
||||
|
||||
@@ -39,6 +39,17 @@ export function accentForSeverity(stopName) {
|
||||
return ACCENT_RGB[stopName] || ACCENT_RGB.yellow;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fire radiative power as shown on a card: "9.9" below 10 MW, "10" once
|
||||
* one-decimal rounding reaches 10. "10.0" would sit beside a whole "10".
|
||||
* @param {number} frp Megawatts.
|
||||
* @returns {string}
|
||||
*/
|
||||
export function formatFrpMw(frp) {
|
||||
const digits = Number(Number(frp).toFixed(1)) >= 10 ? 0 : 1;
|
||||
return Number(frp).toFixed(digits);
|
||||
}
|
||||
|
||||
/** Raw FIRMS satellite code → short display name (N = Suomi NPP). */
|
||||
export function satelliteShortName(satellite) {
|
||||
const s = String(satellite || '')
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
FIRMS_AMBIENT_COHORT_LIMIT,
|
||||
FIRMS_OVERLAY_SOURCE_ID,
|
||||
satelliteShortName,
|
||||
formatFrpMw,
|
||||
} from './firmsLabels.js';
|
||||
|
||||
test('FIRMS formatting helpers retain the shipped severity palette', () => {
|
||||
@@ -15,6 +16,14 @@ test('FIRMS formatting helpers retain the shipped severity palette', () => {
|
||||
assert.equal(accentForSeverity('chartreuse'), accentForSeverity('yellow'));
|
||||
});
|
||||
|
||||
test('FIRMS power that rounds to 10 MW drops the decimal', () => {
|
||||
assert.equal(formatFrpMw(9.96), '10');
|
||||
assert.equal(formatFrpMw(9.94), '9.9');
|
||||
assert.equal(formatFrpMw(0.8), '0.8');
|
||||
assert.equal(formatFrpMw(1520.27), '1520');
|
||||
assert.equal(formatFrpMw(210.4), '210');
|
||||
});
|
||||
|
||||
test('FIRMS satellite names retain the three VIIRS abbreviations', () => {
|
||||
assert.equal(satelliteShortName('N20'), 'N20');
|
||||
assert.equal(satelliteShortName('N21'), 'N21');
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
import { createFlowTileSource } from '../layers/traffic/flowSource.js';
|
||||
export { tilesForBounds } from './tomtomTiles.js';
|
||||
export { decodeFlowTile } from '../layers/traffic/flowDecode.js';
|
||||
const source = createFlowTileSource();
|
||||
export const { fetchFlowForBounds, getFlowSessionStats, resetFlowTileCache } =
|
||||
source;
|
||||
@@ -1,162 +0,0 @@
|
||||
// src/data/flowTiles.test.mjs
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import {
|
||||
decodeFlowTile,
|
||||
fetchFlowForBounds,
|
||||
tilesForBounds,
|
||||
getFlowSessionStats,
|
||||
resetFlowTileCache,
|
||||
} from './flowTiles.js';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
// Real TomTom flow tile, downtown Austin z12 x935 y1686 (probed live 2026-07-16).
|
||||
const FIXTURE = path.join(__dirname, 'fixtures', 'tomtom-flow-austin-12-935-1686.pbf');
|
||||
const FIXTURE_TILE = { z: 12, x: 935, y: 1686 };
|
||||
|
||||
function loadFixture() {
|
||||
return fs.readFileSync(FIXTURE);
|
||||
}
|
||||
|
||||
// ── decodeFlowTile against the real fixture ─────────────────
|
||||
|
||||
test('fixture decode: more than 50 flow segments', () => {
|
||||
const segments = decodeFlowTile(loadFixture(), FIXTURE_TILE.z, FIXTURE_TILE.x, FIXTURE_TILE.y);
|
||||
assert.ok(segments.length > 50, `got ${segments.length}`);
|
||||
});
|
||||
|
||||
test('fixture decode: every trafficLevel is within [0, 1]', () => {
|
||||
const segments = decodeFlowTile(loadFixture(), FIXTURE_TILE.z, FIXTURE_TILE.x, FIXTURE_TILE.y);
|
||||
for (const s of segments) {
|
||||
assert.ok(Number.isFinite(s.trafficLevel), `non-finite level: ${s.trafficLevel}`);
|
||||
assert.ok(s.trafficLevel >= 0 && s.trafficLevel <= 1, `level out of range: ${s.trafficLevel}`);
|
||||
}
|
||||
});
|
||||
|
||||
test('fixture decode: all coordinates land in downtown Austin', () => {
|
||||
const segments = decodeFlowTile(loadFixture(), FIXTURE_TILE.z, FIXTURE_TILE.x, FIXTURE_TILE.y);
|
||||
for (const s of segments) {
|
||||
assert.ok(Array.isArray(s.coords) && s.coords.length >= 2, 'polyline too short');
|
||||
for (const [lon, lat] of s.coords) {
|
||||
assert.ok(lon >= -98.0 && lon <= -97.5, `lon out of Austin range: ${lon}`);
|
||||
assert.ok(lat >= 30.0 && lat <= 30.5, `lat out of Austin range: ${lat}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('fixture decode: congestion exists (at least one trafficLevel < 1)', () => {
|
||||
const segments = decodeFlowTile(loadFixture(), FIXTURE_TILE.z, FIXTURE_TILE.x, FIXTURE_TILE.y);
|
||||
assert.ok(segments.some((s) => s.trafficLevel < 1), 'no congested segment found');
|
||||
});
|
||||
|
||||
test('fixture decode: segment shape is {coords, trafficLevel, roadType, closure}', () => {
|
||||
const segments = decodeFlowTile(loadFixture(), FIXTURE_TILE.z, FIXTURE_TILE.x, FIXTURE_TILE.y);
|
||||
for (const s of segments) {
|
||||
assert.equal(typeof s.roadType, 'string');
|
||||
assert.equal(typeof s.closure, 'boolean');
|
||||
}
|
||||
// The fixture carries real closures — closure decoding is exercised, not vacuous.
|
||||
assert.ok(segments.some((s) => s.closure === true), 'expected at least one closure in fixture');
|
||||
});
|
||||
|
||||
test('decode of a non-MVT buffer returns [] (defensive)', () => {
|
||||
assert.deepEqual(decodeFlowTile(Buffer.from('not a protobuf tile'), 12, 935, 1686), []);
|
||||
});
|
||||
|
||||
// ── tilesForBounds (re-exported slippy math) ────────────────
|
||||
|
||||
test('tilesForBounds: 30.2672,-97.7431 @ z12 -> covers x935 y1686', () => {
|
||||
const tiles = tilesForBounds({
|
||||
south: 30.2672 - 0.001, north: 30.2672 + 0.001,
|
||||
west: -97.7431 - 0.001, east: -97.7431 + 0.001,
|
||||
}, 12);
|
||||
assert.ok(
|
||||
tiles.some((t) => t.z === 12 && t.x === 935 && t.y === 1686),
|
||||
`fixture tile missing: ${JSON.stringify(tiles)}`
|
||||
);
|
||||
});
|
||||
|
||||
// ── fetchFlowForBounds (stubbed fetch: cache + abort) ───────
|
||||
|
||||
/** Bounds fully inside the fixture tile. */
|
||||
const FIXTURE_BOUNDS = { south: 30.24, north: 30.26, west: -97.76, east: -97.74 };
|
||||
|
||||
function stubFetch(impl) {
|
||||
const original = globalThis.fetch;
|
||||
globalThis.fetch = impl;
|
||||
return () => { globalThis.fetch = original; };
|
||||
}
|
||||
|
||||
test('fetchFlowForBounds: fetches covering tiles via /api/tomtom and decodes', async () => {
|
||||
resetFlowTileCache();
|
||||
const calls = [];
|
||||
const restore = stubFetch(async (url) => {
|
||||
calls.push(String(url));
|
||||
return new Response(loadFixture(), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/x-protobuf' },
|
||||
});
|
||||
});
|
||||
try {
|
||||
const segments = await fetchFlowForBounds(FIXTURE_BOUNDS);
|
||||
assert.equal(calls.length, 1);
|
||||
assert.match(calls[0], /^\/api\/tomtom\/flow\/12\/935\/1686\.pbf$/);
|
||||
assert.ok(segments.length > 50);
|
||||
assert.ok(getFlowSessionStats().tilesFetched >= 1);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('fetchFlowForBounds: decode cache serves repeat calls within TTL (no refetch)', async () => {
|
||||
resetFlowTileCache();
|
||||
let calls = 0;
|
||||
const restore = stubFetch(async () => {
|
||||
calls += 1;
|
||||
return new Response(loadFixture(), { status: 200 });
|
||||
});
|
||||
try {
|
||||
const first = await fetchFlowForBounds(FIXTURE_BOUNDS);
|
||||
const second = await fetchFlowForBounds(FIXTURE_BOUNDS);
|
||||
assert.equal(calls, 1, 'second call must be served from the decode cache');
|
||||
assert.equal(second.length, first.length);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('fetchFlowForBounds: aborted signal rejects (AbortSignal-aware)', async () => {
|
||||
resetFlowTileCache();
|
||||
const restore = stubFetch(async (url, opts) => {
|
||||
// Mimic real fetch abort semantics.
|
||||
if (opts?.signal?.aborted) {
|
||||
const err = new Error('aborted');
|
||||
err.name = 'AbortError';
|
||||
throw err;
|
||||
}
|
||||
return new Response(loadFixture(), { status: 200 });
|
||||
});
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
await assert.rejects(
|
||||
fetchFlowForBounds(FIXTURE_BOUNDS, { signal: controller.signal }),
|
||||
(err) => err.name === 'AbortError'
|
||||
);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('fetchFlowForBounds: non-OK tile responses reject when nothing succeeds', async () => {
|
||||
resetFlowTileCache();
|
||||
const restore = stubFetch(async () => new Response(JSON.stringify({ error: 'no_key' }), { status: 503 }));
|
||||
try {
|
||||
await assert.rejects(fetchFlowForBounds(FIXTURE_BOUNDS));
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
@@ -1134,7 +1134,8 @@ export function repairKmlRootNamespaces(value, what = 'KML') {
|
||||
return text.slice(0, start) + root + text.slice(end);
|
||||
}
|
||||
|
||||
function parseXml(text, what) {
|
||||
/** Parse KML or GPX with the shared namespace repairs and XML validation. */
|
||||
export function parseXml(text, what) {
|
||||
// Match the namespace repairs Cesium applies to ordinary exported KML.
|
||||
if (what !== 'GPX') text = repairKmlRootNamespaces(text, what);
|
||||
const doc = new DOMParser().parseFromString(
|
||||
@@ -1150,7 +1151,8 @@ function parseXml(text, what) {
|
||||
return doc;
|
||||
}
|
||||
|
||||
function decodeXml(bytes) {
|
||||
/** Decode XML bytes, honouring a UTF-16 byte-order mark. */
|
||||
export function decodeXml(bytes) {
|
||||
const encoding =
|
||||
bytes[0] === 0xff && bytes[1] === 0xfe
|
||||
? 'utf-16le'
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
// src/data/issPass.js
|
||||
/**
|
||||
* Next-ISS-pass prediction. Kept as a thin wrapper over satellitePass.js so the
|
||||
* original findNextIssPass signature and defaults still work.
|
||||
*/
|
||||
import { findNextSatellitePass, lookAnglesAt } from './satellitePass.js';
|
||||
|
||||
export { lookAnglesAt };
|
||||
|
||||
/**
|
||||
* Predict the next ISS pass over an observer location.
|
||||
* @param {Object} options
|
||||
* @param {Object} options.satrec SGP4 satellite record
|
||||
* @param {number} options.latDeg Observer latitude in degrees [-90, 90]
|
||||
* @param {number} options.lonDeg Observer longitude in degrees [-180, 180]
|
||||
* @param {number} options.fromMs UTC start time in milliseconds
|
||||
* @param {number} [options.minElevDeg=10] Elevation that defines rise and set, in degrees
|
||||
* @param {number} [options.horizonHours=24] Maximum search window in hours
|
||||
* @param {number} [options.coarseStepSec=30] Coarse search step in seconds
|
||||
* @param {number} [options.fineStepSec=5] Fine transit step in seconds for peak tracking and visibility
|
||||
* @param {boolean} [options.requireVisible=false] Require a naked-eye-visible pass
|
||||
* @returns {{ riseMs: number, setMs: number, maxElevDeg: number, maxElevMs: number, riseAzDeg: number, visible: boolean, sunlit: boolean, observerDark: boolean } | null}
|
||||
*/
|
||||
export function findNextIssPass({
|
||||
satrec,
|
||||
latDeg,
|
||||
lonDeg,
|
||||
fromMs,
|
||||
minElevDeg = 10,
|
||||
horizonHours = 24,
|
||||
coarseStepSec = 30,
|
||||
fineStepSec = 5,
|
||||
requireVisible = false,
|
||||
}) {
|
||||
return findNextSatellitePass({
|
||||
satrec,
|
||||
latDeg,
|
||||
lonDeg,
|
||||
fromMs,
|
||||
minElevDeg,
|
||||
horizonHours,
|
||||
coarseStepSec,
|
||||
fineStepSec,
|
||||
requireVisible,
|
||||
});
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
// src/data/issPass.test.mjs
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { twoline2satrec } from 'satellite.js';
|
||||
import { findNextIssPass, lookAnglesAt } from './issPass.js';
|
||||
import { findNextSatellitePass } from './satellitePass.js';
|
||||
|
||||
// Canonical archived ISS TLE (valid checksums; epoch 2008-09-20 ~12:25 UTC).
|
||||
const L1 = '1 25544U 98067A 08264.51782528 -.00002182 00000-0 -11606-4 0 2927';
|
||||
const L2 = '2 25544 51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537';
|
||||
const AUSTIN = { latDeg: 30.2672, lonDeg: -97.7431 };
|
||||
const FROM_MS = Date.UTC(2008, 8, 20, 12, 30, 0); // just after the TLE epoch
|
||||
|
||||
test('finds a structurally-consistent ISS pass within 24h of the TLE epoch', () => {
|
||||
const satrec = twoline2satrec(L1, L2);
|
||||
const pass = findNextIssPass({ satrec, ...AUSTIN, fromMs: FROM_MS, minElevDeg: 10 });
|
||||
assert.ok(pass, 'expected a pass within 24h at 30°N for a 51.6° inclination orbit');
|
||||
assert.ok(pass.riseMs > FROM_MS);
|
||||
assert.ok(pass.riseMs < pass.maxElevMs && pass.maxElevMs < pass.setMs);
|
||||
assert.ok(pass.maxElevDeg >= 10);
|
||||
assert.ok(pass.riseAzDeg >= 0 && pass.riseAzDeg < 360);
|
||||
|
||||
// Independent re-check: elevation at the reported peak really is the max-ish
|
||||
// and ≥ threshold; one minute before rise it is below threshold.
|
||||
const peak = lookAnglesAt(satrec, pass.maxElevMs, AUSTIN.latDeg, AUSTIN.lonDeg);
|
||||
assert.ok(peak && Math.abs(peak.elevDeg - pass.maxElevDeg) < 1.5);
|
||||
const before = lookAnglesAt(satrec, pass.riseMs - 60_000, AUSTIN.latDeg, AUSTIN.lonDeg);
|
||||
assert.ok(before && before.elevDeg < 10);
|
||||
});
|
||||
|
||||
test('forwards its original 30 s coarse step and fineStepSec to the pass engine', () => {
|
||||
const satrec = twoline2satrec(L1, L2);
|
||||
const opts = { satrec, ...AUSTIN, fromMs: FROM_MS, minElevDeg: 10, fineStepSec: 30 };
|
||||
assert.deepEqual(findNextIssPass(opts), findNextSatellitePass({ ...opts, coarseStepSec: 30 }));
|
||||
assert.notDeepEqual(findNextIssPass(opts), findNextIssPass({ ...opts, fineStepSec: 5 }));
|
||||
});
|
||||
|
||||
test('returns null when no pass clears an absurd threshold', () => {
|
||||
const satrec = twoline2satrec(L1, L2);
|
||||
const pass = findNextIssPass({ satrec, ...AUSTIN, fromMs: FROM_MS, minElevDeg: 89.9, horizonHours: 2 });
|
||||
assert.equal(pass, null);
|
||||
});
|
||||
@@ -23,7 +23,7 @@ const NEW_SINGLE_CHARACTER_TOKEN_PATTERN = /^[0-9]$/;
|
||||
* out-of-grammar ID is rejected outright, because half an address is a
|
||||
* DIFFERENT aircraft, not a shorter name for the same one.
|
||||
*/
|
||||
const TRACKING_ID_GRAMMAR = /^[0-9a-z~_-]{1,16}$/;
|
||||
export const TRACKING_ID_GRAMMAR = /^[0-9a-z~_-]{1,16}$/;
|
||||
/**
|
||||
* Ceilings for the untrusted v2 layer fields. The layer ceiling covers the
|
||||
* complete reserved one-character space plus every two-character base-36
|
||||
@@ -655,6 +655,11 @@ export const LAYER_STATE_REGISTRY = Object.freeze([
|
||||
token: 'x',
|
||||
disposition: 'enabled-only',
|
||||
}),
|
||||
Object.freeze({
|
||||
id: 's2-ghostmaps',
|
||||
token: '5',
|
||||
disposition: 'enabled-only',
|
||||
}),
|
||||
Object.freeze({
|
||||
id: 'satellites',
|
||||
token: 's',
|
||||
|
||||
+145
-13
@@ -202,8 +202,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, 31);
|
||||
assert.equal(new Set(REGISTERED_LAYER_IDS).size, 31);
|
||||
assert.equal(REGISTERED_LAYER_IDS.length, 32);
|
||||
assert.equal(new Set(REGISTERED_LAYER_IDS).size, 32);
|
||||
assert.ok(REGISTERED_LAYER_IDS.includes('transit'));
|
||||
assert.deepEqual(REGISTERED_LAYER_IDS, [...REGISTERED_LAYER_IDS].sort());
|
||||
assert.deepEqual(LEGACY_LAYER_STATE_TOKENS, {
|
||||
@@ -242,19 +242,19 @@ 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(), '5');
|
||||
assert.equal(nextLayerStateToken(), '6');
|
||||
assert.equal(
|
||||
nextLayerStateToken({
|
||||
...LAYER_STATE_TOKEN_RESERVATIONS,
|
||||
alpha: '5',
|
||||
bravo: '6',
|
||||
alpha: '6',
|
||||
bravo: '7',
|
||||
}),
|
||||
'7',
|
||||
'8',
|
||||
);
|
||||
const digitsExhausted = {
|
||||
...LAYER_STATE_TOKEN_RESERVATIONS,
|
||||
...Object.fromEntries(
|
||||
[...'56789'].map((digit) => [`prior-${digit}`, digit]),
|
||||
[...'6789'].map((digit) => [`prior-${digit}`, digit]),
|
||||
),
|
||||
};
|
||||
assert.equal(nextLayerStateToken(digitsExhausted), '00');
|
||||
@@ -307,8 +307,8 @@ test('production registry is exact, canonical, and rejects incomplete contracts'
|
||||
assert.equal(
|
||||
validateLayerStateAllocations(LAYER_STATE_TOKEN_RESERVATIONS, {
|
||||
...LAYER_STATE_TOKEN_RESERVATIONS,
|
||||
future: '5',
|
||||
next: '6',
|
||||
future: '6',
|
||||
next: '7',
|
||||
}),
|
||||
true,
|
||||
);
|
||||
@@ -318,7 +318,7 @@ test('production registry is exact, canonical, and rejects incomplete contracts'
|
||||
...LAYER_STATE_TOKEN_RESERVATIONS,
|
||||
future: '00',
|
||||
}),
|
||||
/next free token 5/,
|
||||
/next free token 6/,
|
||||
);
|
||||
const beforeLastDigit = { ...digitsExhausted };
|
||||
delete beforeLastDigit['prior-9'];
|
||||
@@ -341,10 +341,10 @@ test('production registry is exact, canonical, and rejects incomplete contracts'
|
||||
assert.throws(
|
||||
() =>
|
||||
validateLayerStateAllocations(
|
||||
{ ...LAYER_STATE_TOKEN_RESERVATIONS, merged: '5' },
|
||||
{ ...LAYER_STATE_TOKEN_RESERVATIONS, merged: '5', competing: '5' },
|
||||
{ ...LAYER_STATE_TOKEN_RESERVATIONS, merged: '6' },
|
||||
{ ...LAYER_STATE_TOKEN_RESERVATIONS, merged: '6', competing: '6' },
|
||||
),
|
||||
/next free token 6/,
|
||||
/next free token 7/,
|
||||
);
|
||||
assert.throws(
|
||||
() => validateLayerStateAllocations({ future: '00' }, { future: '01' }),
|
||||
@@ -2858,3 +2858,135 @@ test('explicit provider switches reach durable state without adopting unrelated
|
||||
coordinator.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
function enabledLayerParam(sink) {
|
||||
return new URLSearchParams(encode(sink.provider())).get('l');
|
||||
}
|
||||
|
||||
test('Clear All drops a saved layer a context mode had already switched off', async () => {
|
||||
const manager = productionManager();
|
||||
const storage = memoryStorage();
|
||||
const sink = shareSink();
|
||||
const coordinator = new LayerStateCoordinator(manager, sink, { storage });
|
||||
await coordinator.start();
|
||||
await manager.setEnabled('earthquakes', true, { origin: 'user' });
|
||||
await manager.setEnabled('flights', true, { origin: 'user' });
|
||||
assert.deepEqual(coordinator.getDurableState().enabledLayerIds, [
|
||||
'earthquakes',
|
||||
'flights',
|
||||
]);
|
||||
// Context isolation is a temporary, passive takeover: the saved choice stays.
|
||||
await manager.setEnabled('earthquakes', false, { origin: 'programmatic' });
|
||||
assert.deepEqual(coordinator.getDurableState().enabledLayerIds, [
|
||||
'earthquakes',
|
||||
'flights',
|
||||
]);
|
||||
|
||||
const updatesBefore = sink.updates;
|
||||
const result = await manager.clearSelectedLayers({ origin: 'user' });
|
||||
assert.deepEqual(result.targetIds, ['flights']);
|
||||
assert.ok(sink.updates > updatesBefore, 'the URL is told to refresh');
|
||||
assert.deepEqual([...manager.getEnabledLayerIds()], []);
|
||||
assert.deepEqual(coordinator.getDurableState().enabledLayerIds, []);
|
||||
assert.equal(enabledLayerParam(sink), '', 'the URL carries no layers');
|
||||
assert.deepEqual(
|
||||
parseStoredLayerState(storage.getItem(LAYER_STATE_STORAGE_KEY))
|
||||
.enabledLayerIds,
|
||||
[],
|
||||
'a reload restores nothing',
|
||||
);
|
||||
coordinator.destroy();
|
||||
});
|
||||
|
||||
test('Clear All drops a saved layer a dependency release superseded mid-batch', async () => {
|
||||
let manager;
|
||||
manager = productionManager({
|
||||
// Contacts-style owner: its own teardown releases a borrowed dependency
|
||||
// without awaiting it, which supersedes Clear All's turn for that layer.
|
||||
'military-awareness': {
|
||||
disable() {
|
||||
void manager.setEnabled('flights', false, { origin: 'programmatic' });
|
||||
return true;
|
||||
},
|
||||
},
|
||||
});
|
||||
const storage = memoryStorage();
|
||||
const sink = shareSink();
|
||||
const coordinator = new LayerStateCoordinator(manager, sink, { storage });
|
||||
await coordinator.start();
|
||||
await manager.setEnabled('earthquakes', true, { origin: 'user' });
|
||||
await manager.setEnabled('flights', true, { origin: 'user' });
|
||||
await manager.setEnabled('military-awareness', true, { origin: 'user' });
|
||||
|
||||
const result = await manager.clearSelectedLayers({ origin: 'user' });
|
||||
assert.equal(
|
||||
result.items.find((item) => item.id === 'flights')?.superseded,
|
||||
true,
|
||||
'the fixture reproduces the superseded flights turn',
|
||||
);
|
||||
assert.deepEqual([...manager.getEnabledLayerIds()], []);
|
||||
assert.deepEqual(coordinator.getDurableState().enabledLayerIds, []);
|
||||
assert.equal(enabledLayerParam(sink), '');
|
||||
coordinator.destroy();
|
||||
});
|
||||
|
||||
test('Clear All keeps a layer a newer explicit request turned back on', async () => {
|
||||
const manager = productionManager();
|
||||
const sink = shareSink();
|
||||
const coordinator = new LayerStateCoordinator(manager, sink, {
|
||||
storage: memoryStorage(),
|
||||
});
|
||||
await coordinator.start();
|
||||
await manager.setEnabled('earthquakes', true, { origin: 'user' });
|
||||
await manager.setEnabled('flights', true, { origin: 'user' });
|
||||
const clearing = manager.clearSelectedLayers({ origin: 'user' });
|
||||
// A direct request issued during the batch owns its layer.
|
||||
const reenable = manager.setEnabled('earthquakes', true, { origin: 'user' });
|
||||
await Promise.all([clearing, reenable]);
|
||||
assert.deepEqual([...manager.getEnabledLayerIds()], ['earthquakes']);
|
||||
assert.deepEqual(coordinator.getDurableState().enabledLayerIds, [
|
||||
'earthquakes',
|
||||
]);
|
||||
assert.equal(enabledLayerParam(sink), 'e');
|
||||
coordinator.destroy();
|
||||
});
|
||||
|
||||
test('a passive clear never rewrites saved layers', async () => {
|
||||
const manager = productionManager();
|
||||
const storage = memoryStorage();
|
||||
const coordinator = new LayerStateCoordinator(manager, shareSink(), {
|
||||
storage,
|
||||
});
|
||||
await coordinator.start();
|
||||
await manager.setEnabled('flights', true, { origin: 'user' });
|
||||
await manager.setEnabled('flights', false, { origin: 'programmatic' });
|
||||
const writes = storage.writes.length;
|
||||
await manager.clearSelectedLayers({ origin: 'programmatic' });
|
||||
assert.deepEqual(coordinator.getDurableState().enabledLayerIds, ['flights']);
|
||||
assert.equal(storage.writes.length, writes);
|
||||
coordinator.destroy();
|
||||
});
|
||||
|
||||
test('Clear All cancels a saved restore still waiting to start', async () => {
|
||||
const gate = deferred();
|
||||
const manager = productionManager();
|
||||
const sink = shareSink();
|
||||
const coordinator = new LayerStateCoordinator(manager, sink, {
|
||||
storage: memoryStorage(),
|
||||
restoreGate: gate.promise,
|
||||
});
|
||||
const params = new URLSearchParams('v=2&l=e.f');
|
||||
const restore = coordinator.start({
|
||||
shareLayerState: decodeLayerStateParams(params),
|
||||
});
|
||||
await manager.clearSelectedLayers({ origin: 'user' });
|
||||
assert.deepEqual(coordinator.getDurableState().enabledLayerIds, []);
|
||||
gate.resolve();
|
||||
const results = await restore;
|
||||
for (const id of ['earthquakes', 'flights']) {
|
||||
assert.equal(results.find((result) => result.layerId === id).succeeded, false);
|
||||
}
|
||||
assert.deepEqual([...manager.getEnabledLayerIds()], []);
|
||||
assert.equal(enabledLayerParam(sink), '');
|
||||
coordinator.destroy();
|
||||
});
|
||||
@@ -148,6 +148,36 @@ export class LayerStateCoordinator {
|
||||
return this.restorePromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace the running layer state with a share opened later in this tab
|
||||
* (hash navigation). Every in-flight restore and pending shared Follow is
|
||||
* superseded; the new state restores through the same passive share origin
|
||||
* as start-up, so recipient-local preferences are never written. A share
|
||||
* without a layer payload restores the defaults, as a reload of it would.
|
||||
*/
|
||||
applyShareLayerState({
|
||||
shareLayerState = null,
|
||||
shareCreatedAtMs = null,
|
||||
} = {}) {
|
||||
if (this._destroyed) return Promise.resolve([]);
|
||||
for (const controller of this._restoreControllers.values())
|
||||
controller.abort('superseded-by-share-navigation');
|
||||
this._revokePendingTrackingWatch('superseded-by-share-navigation');
|
||||
const selected = shareLayerState
|
||||
? normalizeLayerState(shareLayerState)
|
||||
: null;
|
||||
this._source = selected ? 'share' : 'legacy-share';
|
||||
this._shareCreatedAtMs =
|
||||
selected && Number.isFinite(shareCreatedAtMs) ? shareCreatedAtMs : null;
|
||||
this._durableState = selected || createDefaultLayerState();
|
||||
this.shareLinkManager?.onLayerStateChange?.();
|
||||
this._notifyDurableState();
|
||||
this.restorePromise = this._restoreSelectedState(
|
||||
LAYER_RESTORE_ORIGINS.share,
|
||||
);
|
||||
return this.restorePromise;
|
||||
}
|
||||
|
||||
get source() {
|
||||
return this._source;
|
||||
}
|
||||
@@ -220,6 +250,30 @@ export class LayerStateCoordinator {
|
||||
this._revokePendingTrackingWatch('owner-layer-disabled');
|
||||
}
|
||||
if (!isExplicitLayerStateOrigin(change.origin)) return;
|
||||
if (change.type === 'selection-cleared') {
|
||||
// Only layers a newer request turned back on survive Clear All. Any
|
||||
// other saved layer would reappear from the share link or a reload.
|
||||
const stillEnabled = new Set(change.enabledLayerIds || []);
|
||||
const dropped = this._durableState.enabledLayerIds.filter(
|
||||
(id) => !stillEnabled.has(id),
|
||||
);
|
||||
if (dropped.length === 0) return;
|
||||
for (const layerId of dropped) {
|
||||
this._restoreControllers
|
||||
.get(layerId)
|
||||
?.abort('superseded-by-explicit-visibility');
|
||||
}
|
||||
if (dropped.some((id) => SHARE_TRACKING_RESTORE_POLICIES[id])) {
|
||||
this._revokePendingTrackingWatch('superseded-by-explicit-visibility');
|
||||
}
|
||||
this._commitExplicit({
|
||||
...this._durableState,
|
||||
enabledLayerIds: this._durableState.enabledLayerIds.filter((id) =>
|
||||
stillEnabled.has(id),
|
||||
),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (change.type === 'visibility') {
|
||||
this._restoreControllers
|
||||
.get(change.layerId)
|
||||
@@ -312,15 +366,19 @@ export class LayerStateCoordinator {
|
||||
}
|
||||
|
||||
async _restoreSelectedState(origin) {
|
||||
// One controller set per run: a superseded run must not clear the newer
|
||||
// run's controllers when it settles.
|
||||
const controllers = new Map();
|
||||
for (const entry of LAYER_STATE_REGISTRY) {
|
||||
this._restoreControllers.set(entry.id, new AbortController());
|
||||
controllers.set(entry.id, new AbortController());
|
||||
}
|
||||
this._restoreControllers = controllers;
|
||||
try {
|
||||
await this._waitForRestoreGate();
|
||||
const enabled = new Set(this._durableState.enabledLayerIds);
|
||||
const settled = await Promise.allSettled(
|
||||
LAYER_STATE_REGISTRY.map(async (entry) => {
|
||||
const controller = this._restoreControllers.get(entry.id);
|
||||
const controller = controllers.get(entry.id);
|
||||
const targetEnabled = enabled.has(entry.id);
|
||||
const options = layerOptionsForRestore(this._durableState, entry.id);
|
||||
if (origin === LAYER_RESTORE_ORIGINS.share && options) {
|
||||
@@ -370,7 +428,7 @@ export class LayerStateCoordinator {
|
||||
}));
|
||||
}),
|
||||
);
|
||||
this.lastRestoreResults = settled.map((result, index) => {
|
||||
const results = settled.map((result, index) => {
|
||||
if (result.status === 'fulfilled') return result.value;
|
||||
const entry = LAYER_STATE_REGISTRY[index];
|
||||
return {
|
||||
@@ -387,9 +445,13 @@ export class LayerStateCoordinator {
|
||||
succeeded: false,
|
||||
};
|
||||
});
|
||||
return this.lastRestoreResults.map((result) => ({ ...result }));
|
||||
// A run superseded by a newer share keeps the newer run's results.
|
||||
if (this._restoreControllers === controllers)
|
||||
this.lastRestoreResults = results;
|
||||
return results.map((result) => ({ ...result }));
|
||||
} finally {
|
||||
this._restoreControllers.clear();
|
||||
if (this._restoreControllers === controllers)
|
||||
this._restoreControllers.clear();
|
||||
this._notifyDurableState();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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, 31);
|
||||
assert.equal(Object.keys(LAYER_STATE_TOKEN_RESERVATIONS).length, 32);
|
||||
assert.deepEqual(
|
||||
{ ...LAYER_STATE_TOKEN_RESERVATIONS },
|
||||
{
|
||||
@@ -136,6 +136,7 @@ test('reservation ledger is complete, pinned, and rejects duplicate or malformed
|
||||
'street-level': '0',
|
||||
'gnss-integrity': '3',
|
||||
'air-quality': '4',
|
||||
's2-ghostmaps': '5',
|
||||
},
|
||||
);
|
||||
assert.throws(
|
||||
@@ -161,9 +162,9 @@ test('reservation ledger is complete, pinned, and rejects duplicate or malformed
|
||||
/Duplicate layer-state token reservation/,
|
||||
);
|
||||
assert.equal(
|
||||
parseLayerStateTokenReservations([...reservationRows, ['future', '5']])
|
||||
parseLayerStateTokenReservations([...reservationRows, ['future', '6']])
|
||||
.future,
|
||||
'5',
|
||||
'6',
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
@@ -181,14 +182,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', '5']] },
|
||||
{ rows: [...reservationRows, ['retired-layer', '6']] },
|
||||
(cwd) => {
|
||||
const published = readPublishedLayerStateReservations('HEAD', cwd);
|
||||
assert.equal(nextLayerStateToken(published), '6');
|
||||
assert.equal(nextLayerStateToken(published), '7');
|
||||
assert.equal(
|
||||
validateLayerStateAllocations(published, {
|
||||
...published,
|
||||
newcomer: '6',
|
||||
newcomer: '7',
|
||||
}),
|
||||
true,
|
||||
);
|
||||
@@ -196,15 +197,15 @@ test('published retired digits and competing PRs advance the merge-time allocati
|
||||
() =>
|
||||
validateLayerStateAllocations(published, {
|
||||
...published,
|
||||
competing: '5',
|
||||
competing: '6',
|
||||
}),
|
||||
/next free token 6/,
|
||||
/next free token 7/,
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
validateLayerStateAllocations(published, {
|
||||
...LAYER_STATE_TOKEN_RESERVATIONS,
|
||||
newcomer: '5',
|
||||
newcomer: '6',
|
||||
}),
|
||||
/changed or removed: retired-layer/,
|
||||
);
|
||||
@@ -212,8 +213,8 @@ test('published retired digits and competing PRs advance the merge-time allocati
|
||||
);
|
||||
});
|
||||
|
||||
test('PR B manually replaces provisional 5 with 6 after PR A publishes 5', () => {
|
||||
withPublishedBase({ rows: [...reservationRows, ['pr-a', '5']] }, (cwd) => {
|
||||
test('PR B manually replaces provisional 6 with 7 after PR A publishes 6', () => {
|
||||
withPublishedBase({ rows: [...reservationRows, ['pr-a', '6']] }, (cwd) => {
|
||||
mkdirSync(path.join(cwd, 'scripts'));
|
||||
const fixtureChecker = path.join(
|
||||
cwd,
|
||||
@@ -234,8 +235,8 @@ test('PR B manually replaces provisional 5 with 6 after PR A publishes 5', () =>
|
||||
|
||||
writeCodecFixture(
|
||||
cwd,
|
||||
[...reservationRows, ['pr-b', '5']],
|
||||
[{ id: 'pr-b', token: '5' }],
|
||||
[...reservationRows, ['pr-b', '6']],
|
||||
[{ id: 'pr-b', token: '6' }],
|
||||
);
|
||||
const beforeRebase = runCheck();
|
||||
assert.equal(beforeRebase.status, 1);
|
||||
@@ -243,10 +244,10 @@ test('PR B manually replaces provisional 5 with 6 after PR A publishes 5', () =>
|
||||
|
||||
writeCodecFixture(
|
||||
cwd,
|
||||
[...reservationRows, ['pr-a', '5'], ['pr-b', '5']],
|
||||
[...reservationRows, ['pr-a', '6'], ['pr-b', '6']],
|
||||
[
|
||||
{ id: 'pr-a', token: '5' },
|
||||
{ id: 'pr-b', token: '5' },
|
||||
{ id: 'pr-a', token: '6' },
|
||||
{ id: 'pr-b', token: '6' },
|
||||
],
|
||||
);
|
||||
const staleRebase = runCheck();
|
||||
@@ -254,16 +255,16 @@ test('PR B manually replaces provisional 5 with 6 after PR A publishes 5', () =>
|
||||
assert.match(staleRebase.stderr, /Duplicate layer-state token reservation/);
|
||||
|
||||
const published = readPublishedLayerStateReservations('HEAD', cwd);
|
||||
assert.equal(nextLayerStateToken(published), '6');
|
||||
const validBaselineRows = [...reservationRows, ['pr-a', '5']];
|
||||
writeCodecFixture(cwd, validBaselineRows, [{ id: 'pr-a', token: '5' }]);
|
||||
assert.equal(nextLayerStateToken(published), '7');
|
||||
const validBaselineRows = [...reservationRows, ['pr-a', '6']];
|
||||
writeCodecFixture(cwd, validBaselineRows, [{ id: 'pr-a', token: '6' }]);
|
||||
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: 6/);
|
||||
assert.match(helper.stdout, /pr-b: 7/);
|
||||
assert.deepEqual(
|
||||
JSON.parse(readFileSync(path.join(cwd, LEDGER_PATH), 'utf8')),
|
||||
validBaselineRows,
|
||||
@@ -271,20 +272,20 @@ test('PR B manually replaces provisional 5 with 6 after PR A publishes 5', () =>
|
||||
);
|
||||
writeCodecFixture(
|
||||
cwd,
|
||||
[...reservationRows, ['pr-a', '5'], ['pr-b', '6']],
|
||||
[...reservationRows, ['pr-a', '6'], ['pr-b', '7']],
|
||||
[
|
||||
{ id: 'pr-a', token: '5' },
|
||||
{ id: 'pr-b', token: '6' },
|
||||
{ id: 'pr-a', token: '6' },
|
||||
{ id: 'pr-b', token: '7' },
|
||||
],
|
||||
);
|
||||
const corrected = runCheck();
|
||||
assert.equal(corrected.status, 0, corrected.stderr);
|
||||
assert.match(corrected.stdout, /32 published, 1 new/);
|
||||
assert.match(corrected.stdout, /33 published, 1 new/);
|
||||
});
|
||||
});
|
||||
|
||||
test('allocation batches cross the last digit and base-36 pair boundaries in order', () => {
|
||||
const digitRows = [...'56789'].map((digit) => [`retired-${digit}`, digit]);
|
||||
const digitRows = [...'6789'].map((digit) => [`retired-${digit}`, digit]);
|
||||
const allDigits = parseLayerStateTokenReservations([
|
||||
...reservationRows,
|
||||
...digitRows,
|
||||
@@ -336,7 +337,7 @@ 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 = [...'56789'].map((digit) => [
|
||||
const priorDigits = [...'6789'].map((digit) => [
|
||||
`qa-prior-digit-${digit}`,
|
||||
digit,
|
||||
]);
|
||||
@@ -373,7 +374,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, 73);
|
||||
assert.equal(params.get('l').length, 75);
|
||||
const restored = codec.decodeLayerStateParams(params);
|
||||
assert.deepEqual(restored?.enabledLayerIds, expectedLayerIds);
|
||||
assert.deepEqual(restored?.options, state.options);
|
||||
@@ -391,7 +392,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, 32);
|
||||
assert.equal(Object.keys(published).length, 33);
|
||||
assert.equal(published['retired-layer'], '00');
|
||||
assert.throws(
|
||||
() =>
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
["radio", "r"],
|
||||
["recent-imagery", "1"],
|
||||
["rocket-launches", "x"],
|
||||
["s2-ghostmaps", "5"],
|
||||
["satellites", "s"],
|
||||
["street-level", "0"],
|
||||
["telegeography-submarine-cables", "u"],
|
||||
|
||||
+69
-17
@@ -72,13 +72,20 @@ function refreshFailureFromStats(stats, label) {
|
||||
/**
|
||||
* LayerLifecycle — Manages registration, toggling, and update loops
|
||||
* for real-time data overlays on the CesiumJS globe.
|
||||
* Hosts may inject a visibilityTarget with hidden/visibilityState and event
|
||||
* listener methods. Without one, periodic work retains its headless behavior.
|
||||
*/
|
||||
export class LayerLifecycle {
|
||||
constructor(
|
||||
viewer,
|
||||
{ allowQaRegistration = false, getSourceAvailability } = {},
|
||||
{
|
||||
allowQaRegistration = false,
|
||||
getSourceAvailability,
|
||||
visibilityTarget = null,
|
||||
} = {},
|
||||
) {
|
||||
this._catalogSourceAvailability = getSourceAvailability;
|
||||
this._visibilityTarget = visibilityTarget;
|
||||
this.viewer = viewer;
|
||||
this._activityListeners = new Set();
|
||||
this.layers = new Map(); // id → { module, enabled, initialized, intervalId, lifecycleState, lifecycleUncertain }
|
||||
@@ -528,6 +535,13 @@ export class LayerLifecycle {
|
||||
}
|
||||
}
|
||||
|
||||
_stopUpdateLoop(entry) {
|
||||
clearInterval(entry.intervalId);
|
||||
entry.intervalId = null;
|
||||
entry.removeVisibilityListener?.();
|
||||
entry.removeVisibilityListener = null;
|
||||
}
|
||||
|
||||
_armUpdateLoop(layerId, entry) {
|
||||
const configuredRefreshInterval = Number(entry.module.refreshInterval);
|
||||
const updateInterval = Number(entry.module.updateInterval);
|
||||
@@ -538,9 +552,45 @@ export class LayerLifecycle {
|
||||
? updateInterval
|
||||
: 0;
|
||||
if (refreshInterval > 0) {
|
||||
entry.intervalId = setInterval(() => {
|
||||
const visibilityDocument = this._visibilityTarget;
|
||||
let intervalId = null;
|
||||
let dueAt = 0;
|
||||
const canPoll = () =>
|
||||
!visibilityDocument?.hidden &&
|
||||
visibilityDocument?.visibilityState !== 'hidden' &&
|
||||
entry.enabled &&
|
||||
!entry.destroying &&
|
||||
!entry.refreshing &&
|
||||
entry.intervalId === intervalId;
|
||||
// dueAt and the interval phase share one origin, so every interval tick
|
||||
// is a due poll. A visibility catch-up re-arms the interval at the new
|
||||
// deadline; otherwise the old phase would skip its next tick.
|
||||
const schedule = () => {
|
||||
clearInterval(intervalId);
|
||||
dueAt = Date.now() + refreshInterval;
|
||||
intervalId = setInterval(onInterval, refreshInterval);
|
||||
entry.intervalId = intervalId;
|
||||
};
|
||||
const onInterval = () => {
|
||||
if (!canPoll()) return;
|
||||
dueAt = Date.now() + refreshInterval;
|
||||
void this._runPeriodicUpdate(layerId, entry);
|
||||
}, refreshInterval);
|
||||
};
|
||||
const onVisibilityChange = () => {
|
||||
if (!canPoll() || Date.now() < dueAt) return;
|
||||
schedule();
|
||||
void this._runPeriodicUpdate(layerId, entry);
|
||||
};
|
||||
schedule();
|
||||
visibilityDocument?.addEventListener?.(
|
||||
'visibilitychange',
|
||||
onVisibilityChange,
|
||||
);
|
||||
entry.removeVisibilityListener = () =>
|
||||
visibilityDocument?.removeEventListener?.(
|
||||
'visibilitychange',
|
||||
onVisibilityChange,
|
||||
);
|
||||
} else if (updateInterval === 0) {
|
||||
entry.intervalId = setInterval(() => {
|
||||
if (!entry.enabled) return;
|
||||
@@ -772,8 +822,7 @@ export class LayerLifecycle {
|
||||
entry.lifecycleUncertain = !compensated && !cleanupConfirmed;
|
||||
settleLifecycle();
|
||||
if (!entry.enabled && entry.intervalId) {
|
||||
clearInterval(entry.intervalId);
|
||||
entry.intervalId = null;
|
||||
this._stopUpdateLoop(entry);
|
||||
}
|
||||
this._publishActivity({ type: 'status' });
|
||||
if (!compensated) {
|
||||
@@ -833,8 +882,7 @@ export class LayerLifecycle {
|
||||
}
|
||||
if (signal?.aborted) return finishCancelledDisable('disable');
|
||||
if (entry.intervalId) {
|
||||
clearInterval(entry.intervalId);
|
||||
entry.intervalId = null;
|
||||
this._stopUpdateLoop(entry);
|
||||
}
|
||||
entry.enabled = false;
|
||||
entry.lifecycleUncertain = false;
|
||||
@@ -845,8 +893,7 @@ export class LayerLifecycle {
|
||||
let abortCleanup = null;
|
||||
const cancelEnable = () => {
|
||||
if (entry.intervalId) {
|
||||
clearInterval(entry.intervalId);
|
||||
entry.intervalId = null;
|
||||
this._stopUpdateLoop(entry);
|
||||
}
|
||||
// Disable immediately so modules with their own AbortController (Radio)
|
||||
// cancel pending update work at the same turn boundary. A second
|
||||
@@ -876,8 +923,7 @@ export class LayerLifecycle {
|
||||
// a later abort cannot revoke a successful retry.
|
||||
signal?.removeEventListener('abort', cancelEnable);
|
||||
if (entry.intervalId) {
|
||||
clearInterval(entry.intervalId);
|
||||
entry.intervalId = null;
|
||||
this._stopUpdateLoop(entry);
|
||||
}
|
||||
await abortCleanup;
|
||||
let cleanupConfirmed = false;
|
||||
@@ -918,8 +964,7 @@ export class LayerLifecycle {
|
||||
};
|
||||
const finishFailedEnable = async (phase, error) => {
|
||||
if (entry.intervalId) {
|
||||
clearInterval(entry.intervalId);
|
||||
entry.intervalId = null;
|
||||
this._stopUpdateLoop(entry);
|
||||
}
|
||||
let cleanupConfirmed = false;
|
||||
try {
|
||||
@@ -1029,8 +1074,7 @@ export class LayerLifecycle {
|
||||
// Always clear any stale interval before assigning a new one, so we never
|
||||
// orphan a running timer and end up double-polling.
|
||||
if (entry.intervalId) {
|
||||
clearInterval(entry.intervalId);
|
||||
entry.intervalId = null;
|
||||
this._stopUpdateLoop(entry);
|
||||
}
|
||||
|
||||
// Manager-owned periodic refresh work has one normalized loading/error
|
||||
@@ -1606,6 +1650,15 @@ export class LayerLifecycle {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Clear All owns the whole selection, not only the layers it switched off
|
||||
// itself. A layer already off for a passive reason (isolated by a context
|
||||
// mode, released by a dependency owner, or superseded mid-batch) gets no
|
||||
// OFF of its own here, so publish the set that is still on afterwards.
|
||||
this._notifyListeners({
|
||||
type: 'selection-cleared',
|
||||
origin,
|
||||
enabledLayerIds: [...this.getEnabledLayerIds()],
|
||||
});
|
||||
const items = targetIds.map((id) => {
|
||||
const state = this.getLayerLifecycleState(id) || {
|
||||
enabled: false,
|
||||
@@ -2158,8 +2211,7 @@ export class LayerLifecycle {
|
||||
return false;
|
||||
}
|
||||
if (entry.intervalId) {
|
||||
clearInterval(entry.intervalId);
|
||||
entry.intervalId = null;
|
||||
this._stopUpdateLoop(entry);
|
||||
}
|
||||
entry.enabled = false;
|
||||
}
|
||||
|
||||
@@ -2,7 +2,18 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { createLocalGeoJsonLayer, mapAnalystRecord } from './localGeojson.js';
|
||||
import { localGeoJsonServices } from '../app/localGeojsonServices.js';
|
||||
import {
|
||||
createLocalGeoJsonLayer as createLayer,
|
||||
mapAnalystRecord,
|
||||
} from './localGeojsonCore.js';
|
||||
|
||||
/** The catalog's services, with the overlay host each test supplies. */
|
||||
const createLocalGeoJsonLayer = (options) =>
|
||||
createLayer(options, {
|
||||
...localGeoJsonServices,
|
||||
overlayHost: options.overlayHost,
|
||||
});
|
||||
|
||||
const DC_RAW = {
|
||||
id: '1176042553',
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
import { localGeoJsonServices } from '../app/localGeojsonServices.js';
|
||||
import {
|
||||
createLocalGeoJsonLayer as createLayer,
|
||||
createLocalInfrastructureOverlayPublisher as createPublisher,
|
||||
} from './localGeojsonCore.js';
|
||||
|
||||
export * from './localGeojsonCore.js';
|
||||
|
||||
/** Create a layer using the standalone app's operations; retain overlay overrides. */
|
||||
export function createLocalGeoJsonLayer(options) {
|
||||
return createLayer(options, {
|
||||
...localGeoJsonServices,
|
||||
overlayHost:
|
||||
options.overlayHost === undefined
|
||||
? localGeoJsonServices.overlayHost
|
||||
: options.overlayHost,
|
||||
});
|
||||
}
|
||||
|
||||
/** Create an overlay publisher using the standalone app's host by default. */
|
||||
export function createLocalInfrastructureOverlayPublisher(options) {
|
||||
return createPublisher({
|
||||
...options,
|
||||
host:
|
||||
options.host === undefined
|
||||
? localGeoJsonServices.overlayHost
|
||||
: options.host,
|
||||
});
|
||||
}
|
||||
@@ -6,13 +6,14 @@ import {
|
||||
GROUND_SAMPLE_MAX_ARMED_RETRIES,
|
||||
LOCAL_OVERLAY_COHORT_LIMIT,
|
||||
LOCAL_STEM_TIP_EPSILON_M,
|
||||
createLocalGeoJsonLayer,
|
||||
createLocalGeoJsonLayer as createLayer,
|
||||
createLocalInfrastructureOverlayEntry,
|
||||
createLocalInfrastructureOverlayPublisher,
|
||||
localDatasetError,
|
||||
localInfrastructureOverlayCopy,
|
||||
selectLocalInfrastructureOverlayCohort,
|
||||
} from './localGeojson.js';
|
||||
} from './localGeojsonCore.js';
|
||||
import { localGeoJsonServices } from '../app/localGeojsonServices.js';
|
||||
import { layerFeedState } from './manager.js';
|
||||
import { INFRA_LOD_ACTIVE_MIN, INFRA_LOD_ACTIVE_MAX } from './localGeojsonLod.js';
|
||||
import {
|
||||
@@ -21,6 +22,13 @@ import {
|
||||
_resetRenderGovernorForTest,
|
||||
} from '../renderGovernor.js';
|
||||
|
||||
/** The catalog's services, with the overlay host each test supplies. */
|
||||
const createLocalGeoJsonLayer = (options) =>
|
||||
createLayer(options, {
|
||||
...localGeoJsonServices,
|
||||
overlayHost: options.overlayHost ?? localGeoJsonServices.overlayHost,
|
||||
});
|
||||
|
||||
class MockLayerEvent {
|
||||
constructor() {
|
||||
this.listeners = new Set();
|
||||
@@ -1337,14 +1345,3 @@ test('globe-LOD re-selects during continuous motion, without ever seeing a moveE
|
||||
assert.deepEqual(env.layer.getLodDiagnostics(), parked, 'a parked camera never re-selects');
|
||||
});
|
||||
|
||||
|
||||
test('standalone publisher retains its default host for an undefined override', () => {
|
||||
const publisher = createLocalInfrastructureOverlayPublisher({
|
||||
sourceId: 'local-default-host-test', host: undefined,
|
||||
});
|
||||
assert.doesNotThrow(() => {
|
||||
publisher.show();
|
||||
publisher.hide();
|
||||
publisher.destroy();
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,17 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { createLocalGeoJsonLayer } from './localGeojson.js';
|
||||
import { localGeoJsonServices } from '../app/localGeojsonServices.js';
|
||||
import { createLocalGeoJsonLayer as createLayer } from './localGeojsonCore.js';
|
||||
import { getContextStore } from './contextStore.js';
|
||||
|
||||
/** The catalog's services, with the overlay host each test supplies. */
|
||||
const createLocalGeoJsonLayer = (options) =>
|
||||
createLayer(options, {
|
||||
...localGeoJsonServices,
|
||||
overlayHost: options.overlayHost,
|
||||
});
|
||||
|
||||
const dataset = JSON.stringify({
|
||||
type: 'Feature', id: 'dam', properties: { name: 'Test dam' },
|
||||
geometry: { type: 'Polygon', coordinates: [[[0, 0], [0.01, 0], [0, 0.01], [0, 0]]] },
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
* Pure selection policy for the bundled local-infrastructure layers
|
||||
* (`local-datacenters`, `local-dams`, and any future `createLocalGeoJsonLayer`
|
||||
* dataset). Cesium-specific projection, occlusion, and stem geometry stay in
|
||||
* `localGeojson.js`; this module turns the resulting in-view records into a
|
||||
* `localGeojsonCore.js`; this module turns the resulting in-view records into a
|
||||
* bounded "active" set — the only records that layer should spend per-frame
|
||||
* stem-geometry and ground-sample work on.
|
||||
*
|
||||
@@ -80,7 +80,7 @@ export const INFRA_LOD_INCUMBENT_BONUS = 250;
|
||||
|
||||
/**
|
||||
* Distance at or beyond which the proximity penalty is fully applied (m).
|
||||
* Matches LOCAL_OVERLAY_MAX_DISTANCE_M's order of magnitude in localGeojson.js.
|
||||
* Matches LOCAL_OVERLAY_MAX_DISTANCE_M's order of magnitude in infrastructureOverlayEntry.js.
|
||||
*/
|
||||
export const INFRA_LOD_FAR_M = 12_000_000;
|
||||
|
||||
@@ -97,7 +97,7 @@ export const INFRA_LOD_MAX_DISTANCE_PENALTY = 200;
|
||||
* (callers only compare it), but every input is normalized so the output is
|
||||
* always a finite number.
|
||||
*
|
||||
* @param {number} priority Existing label-priority score (localGeojson.js).
|
||||
* @param {number} priority Existing label-priority score (localGeojsonCore.js).
|
||||
* @param {number} distanceM Camera→feature distance in metres.
|
||||
* @param {boolean} isIncumbent Record currently holds an active stem.
|
||||
* @param {object} [options]
|
||||
@@ -297,7 +297,7 @@ export function applyInfraEvictionGrace({
|
||||
* ------------------------------------------------------------------ */
|
||||
|
||||
/**
|
||||
* Probe window for the motion fallback. `localGeojson.js` marks its selection
|
||||
* Probe window for the motion fallback. `localGeojsonCore.js` marks its selection
|
||||
* dirty on `moveEnd`, which covers drags, one-shot `setView`, and voice
|
||||
* `flyTo` — but a tracked-entity follow camera, a Cockpit view, a route
|
||||
* flight, or a continuous orbit never emits one. Without a fallback the
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ export { layerFeedState } from '../ui/layers.js';
|
||||
/** Compatibility facade for callers that construct a manager with its panel. */
|
||||
export class DataLayerManager extends LayerLifecycle {
|
||||
constructor(viewer, options) {
|
||||
super(viewer, options);
|
||||
super(viewer, { visibilityTarget: globalThis.document, ...options });
|
||||
this._presentation = new LayerPresentation(this);
|
||||
}
|
||||
buildTogglePanel(container) {
|
||||
|
||||
@@ -3492,3 +3492,92 @@ test('refreshLayerStats reaches presentation through the bare lifecycle', async
|
||||
lifecycle.refreshLayerStats();
|
||||
assert.deepEqual(changes, ['status']);
|
||||
});
|
||||
|
||||
test('periodic polls pause hidden, catch up once when due, and dispose visibility listeners', async (t) => {
|
||||
const listeners = new Set();
|
||||
const doc = {
|
||||
hidden: false,
|
||||
addEventListener: (_name, fn) => listeners.add(fn),
|
||||
removeEventListener: (_name, fn) => listeners.delete(fn),
|
||||
};
|
||||
t.mock.timers.enable({ apis: ['setInterval', 'Date'], now: 1000 });
|
||||
const { LayerLifecycle } = await import('./lifecycle.js');
|
||||
const manager = new LayerLifecycle({}, { visibilityTarget: doc });
|
||||
const { module, calls } = makeSlowLayer('hidden-poll');
|
||||
manager.register(module);
|
||||
await manager.setEnabled('hidden-poll', true);
|
||||
assert.equal(calls.update, 1);
|
||||
doc.hidden = true;
|
||||
t.mock.timers.tick(10000);
|
||||
assert.equal(calls.update, 1);
|
||||
assert.equal(await manager.refreshLayer('hidden-poll'), true);
|
||||
assert.equal(calls.update, 2, 'explicit refresh remains allowed');
|
||||
doc.hidden = false;
|
||||
for (const fn of listeners) fn();
|
||||
for (const fn of listeners) fn();
|
||||
assert.equal(calls.update, 3);
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
await manager.destroyAll();
|
||||
assert.equal(listeners.size, 0);
|
||||
t.mock.timers.tick(10000);
|
||||
assert.equal(calls.update, 3);
|
||||
});
|
||||
|
||||
async function resumeBetweenTicks(t, { failResume = false } = {}) {
|
||||
const listeners = new Set();
|
||||
const doc = {
|
||||
hidden: false,
|
||||
addEventListener: (_name, fn) => listeners.add(fn),
|
||||
removeEventListener: (_name, fn) => listeners.delete(fn),
|
||||
};
|
||||
t.mock.timers.enable({ apis: ['setInterval', 'Date'], now: 1000 });
|
||||
const { LayerLifecycle } = await import('./lifecycle.js');
|
||||
const manager = new LayerLifecycle({}, { visibilityTarget: doc });
|
||||
const { module, calls } = makeSlowLayer('resume-poll');
|
||||
const updates = [];
|
||||
module.update = async () => {
|
||||
calls.update++;
|
||||
updates.push(Date.now());
|
||||
await Promise.resolve();
|
||||
if (failResume && updates.length === 2) throw new Error('resume failed');
|
||||
};
|
||||
manager.register(module);
|
||||
await manager.setEnabled('resume-poll', true);
|
||||
assert.deepEqual(updates, [1000]);
|
||||
doc.hidden = true;
|
||||
t.mock.timers.tick(1000); // 2000: due tick skipped while hidden
|
||||
t.mock.timers.tick(500); // 2500: return between ticks
|
||||
doc.hidden = false;
|
||||
for (const fn of listeners) fn();
|
||||
assert.deepEqual(updates, [1000, 2500], 'overdue poll runs once on return');
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
const managerRefreshError = manager.layers.get('resume-poll').managerRefreshError;
|
||||
if (failResume) assert.equal(managerRefreshError, 'resume failed');
|
||||
else assert.equal(managerRefreshError, null);
|
||||
t.mock.timers.tick(999); // 3499: the old 3000 phase must not fire
|
||||
assert.deepEqual(updates, [1000, 2500]);
|
||||
t.mock.timers.tick(1); // 3500: one interval after the resume poll
|
||||
assert.deepEqual(updates, [1000, 2500, 3500]);
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
t.mock.timers.tick(1000);
|
||||
assert.deepEqual(updates, [1000, 2500, 3500, 4500], 'new phase keeps one interval');
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
await manager.destroyAll();
|
||||
assert.equal(listeners.size, 0);
|
||||
t.mock.timers.tick(5000);
|
||||
assert.equal(updates.length, 4);
|
||||
}
|
||||
|
||||
test('periodic polls realign to the deadline after a between-ticks resume', async (t) => {
|
||||
await resumeBetweenTicks(t);
|
||||
});
|
||||
|
||||
test('periodic polls realign to the deadline after a failed resume refresh', async (t) => {
|
||||
await resumeBetweenTicks(t, { failResume: true });
|
||||
});
|
||||
@@ -42,7 +42,10 @@ import {
|
||||
formatAwarenessLabel,
|
||||
getAwarenessNavigationTargets,
|
||||
} from './militaryAwarenessEngine.js';
|
||||
import { formatAwarenessCount } from '../layers/awareness/panel.js';
|
||||
import {
|
||||
formatAwarenessCount,
|
||||
presentAwarenessDistance,
|
||||
} from '../layers/awareness/panel.js';
|
||||
import { NAVIGATION_AUTHORITY_EVENT } from '../navigationPolicy.js';
|
||||
|
||||
const militaryAwarenessSource = readLayerSource(
|
||||
@@ -69,6 +72,12 @@ test('Contacts labels a capped cohort as a lower bound', () => {
|
||||
assert.equal(formatAwarenessCount({ count: null }), '?');
|
||||
});
|
||||
|
||||
test('Contacts moves a distance that rounds to 1,000 m into kilometres', () => {
|
||||
assert.equal(presentAwarenessDistance(999.4), '999\u00a0m');
|
||||
assert.equal(presentAwarenessDistance(999.6), '1.0\u00a0km');
|
||||
assert.equal(presentAwarenessDistance(4600), '4.6\u00a0km');
|
||||
});
|
||||
|
||||
function installAwarenessRuntime({
|
||||
isEnabled = () => true,
|
||||
isEffectivelyEnabled = isEnabled,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/** Pure proximity helpers for Global Context. No capability modeling. */
|
||||
|
||||
import { t } from '../i18n/index.js';
|
||||
import { msg, t } from '../i18n/index.js';
|
||||
import { UNNAMED_PLACE_NAMES } from './installationNames.js';
|
||||
|
||||
const UNNAMED_NAMES = new Set(UNNAMED_PLACE_NAMES);
|
||||
@@ -84,7 +84,8 @@ export function formatAwarenessLabel(value) {
|
||||
/**
|
||||
* Summarize sorted nearby results without promoting missing/stale feeds to a
|
||||
* negative finding. `UNKNOWN` is an input-data state, never an out-of-range
|
||||
* claim in this MVP.
|
||||
* claim in this MVP. `reason` is English data; the awareness panel shows it
|
||||
* in the UI language.
|
||||
*/
|
||||
export function summarizeAwarenessCohort(
|
||||
items,
|
||||
@@ -95,14 +96,14 @@ export function summarizeAwarenessCohort(
|
||||
relationship: AWARENESS_RELATIONSHIP.UNKNOWN,
|
||||
count: null,
|
||||
nearest: [],
|
||||
reason: t('feed unavailable'),
|
||||
reason: msg('feed unavailable'),
|
||||
};
|
||||
if (stale)
|
||||
return {
|
||||
relationship: AWARENESS_RELATIONSHIP.UNKNOWN,
|
||||
count: null,
|
||||
nearest: [],
|
||||
reason: t('feed stale'),
|
||||
reason: msg('feed stale'),
|
||||
};
|
||||
const normalized = (Array.isArray(items) ? items : [])
|
||||
.filter(
|
||||
@@ -119,8 +120,8 @@ export function summarizeAwarenessCohort(
|
||||
count: normalized.length,
|
||||
nearest: normalized.slice(0, limit),
|
||||
reason: normalized.length
|
||||
? t('observed or mapped nearby context')
|
||||
: t('no observed or mapped objects in current feeds'),
|
||||
? msg('observed or mapped nearby context')
|
||||
: msg('no observed or mapped objects in current feeds'),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { setLocale, translateKnown } from '../i18n/index.js';
|
||||
import {
|
||||
AWARENESS_RELATIONSHIP,
|
||||
findByDoublingRadius,
|
||||
@@ -47,6 +48,25 @@ test('unavailable and stale feeds remain unknown', () => {
|
||||
assert.equal(summarizeAwarenessCohort([], { stale: true }).reason, 'feed stale');
|
||||
});
|
||||
|
||||
test('cohort reasons stay English in data and translate where the panel shows them', (t) => {
|
||||
t.after(() => setLocale('en'));
|
||||
setLocale('ru');
|
||||
const reasons = [
|
||||
summarizeAwarenessCohort([], { available: false }).reason,
|
||||
summarizeAwarenessCohort([], { stale: true }).reason,
|
||||
summarizeAwarenessCohort([{ id: 'near', distanceM: 10 }]).reason,
|
||||
summarizeAwarenessCohort([]).reason,
|
||||
];
|
||||
assert.deepEqual(reasons, [
|
||||
'feed unavailable',
|
||||
'feed stale',
|
||||
'observed or mapped nearby context',
|
||||
'no observed or mapped objects in current feeds',
|
||||
]);
|
||||
// The awareness panel shows a reason through translateKnown().
|
||||
for (const reason of reasons) assert.notEqual(translateKnown(reason), reason);
|
||||
});
|
||||
|
||||
test('navigation prioritizes nearby targets from the selected cohort', () => {
|
||||
const cohorts = [
|
||||
{ id: 'flights', summary: { nearest: [{ icao24: 'a1', distanceM: 1000 }, { icao24: 'a2', distanceM: 2000 }] } },
|
||||
|
||||
@@ -13,8 +13,11 @@ function approximateDistanceM(latA, lonA, latB, lonB) {
|
||||
return Number.MAX_SAFE_INTEGER;
|
||||
const latitudeScale = 111320;
|
||||
const longitudeScale = latitudeScale * Math.cos((latA * Math.PI) / 180);
|
||||
// The short way round, so places either side of 180° stay close.
|
||||
let dLon = lonB - lonA;
|
||||
dLon -= 360 * Math.round(dLon / 360);
|
||||
return Math.round(
|
||||
Math.hypot((latB - latA) * latitudeScale, (lonB - lonA) * longitudeScale),
|
||||
Math.hypot((latB - latA) * latitudeScale, dLon * longitudeScale),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+25
-8
@@ -54,6 +54,21 @@ function direction(modifier) {
|
||||
return DIRECTION_WORDS[key] || key;
|
||||
}
|
||||
|
||||
/**
|
||||
* "on the left" only fits a bare side. "slight left" is the adverb
|
||||
* "slightly left", and "on the slightly left" is not an instruction.
|
||||
* @param {string} prefix "Take the ramp" or "Take the exit".
|
||||
* @param {string} modifier OSRM maneuver modifier.
|
||||
* @param {string} onto " onto …", or "".
|
||||
*/
|
||||
function directedWay(prefix, modifier, onto) {
|
||||
const dir = direction(modifier);
|
||||
if (dir === 'left' || dir === 'right')
|
||||
return `${prefix} on the ${dir}${onto}`;
|
||||
if (dir && dir !== 'straight') return `${prefix} ${dir}${onto}`;
|
||||
return `${prefix}${onto}`;
|
||||
}
|
||||
|
||||
function ordinal(n) {
|
||||
if (!Number.isInteger(n) || n < 1) return null;
|
||||
const suffix =
|
||||
@@ -103,13 +118,9 @@ export function instructionFor(step) {
|
||||
case 'merge':
|
||||
return dir ? `Merge ${dir}${onto}` : `Merge${onto}`;
|
||||
case 'on ramp':
|
||||
return dir
|
||||
? `Take the ramp on the ${dir}${onto}`
|
||||
: `Take the ramp${onto}`;
|
||||
return directedWay('Take the ramp', modifier, onto);
|
||||
case 'off ramp':
|
||||
return dir
|
||||
? `Take the exit on the ${dir}${onto}`
|
||||
: `Take the exit${onto}`;
|
||||
return directedWay('Take the exit', modifier, onto);
|
||||
case 'roundabout':
|
||||
case 'rotary': {
|
||||
const exit = ordinal(step?.exit);
|
||||
@@ -124,8 +135,14 @@ export function instructionFor(step) {
|
||||
case 'exit roundabout':
|
||||
case 'exit rotary':
|
||||
return `Exit the roundabout${onto}`;
|
||||
case 'use lane':
|
||||
return dir ? `Use the ${dir} lane${onto}` : `Continue${onto}`;
|
||||
case 'use lane': {
|
||||
const lane = modifier.includes('left')
|
||||
? 'left'
|
||||
: modifier.includes('right')
|
||||
? 'right'
|
||||
: '';
|
||||
return lane ? `Use the ${lane} lane${onto}` : `Continue${onto}`;
|
||||
}
|
||||
case 'notification':
|
||||
default:
|
||||
return `Continue${onto}`;
|
||||
|
||||
@@ -77,6 +77,26 @@ test('instructions read like a navigator, one sentence per OSRM maneuver', () =>
|
||||
instructionFor({ type: 'on ramp', modifier: 'left' }),
|
||||
'Take the ramp on the left',
|
||||
);
|
||||
assert.equal(
|
||||
instructionFor({ type: 'on ramp', modifier: 'slight left', name: 'I-95' }),
|
||||
'Take the ramp slightly left onto I-95',
|
||||
);
|
||||
assert.equal(
|
||||
instructionFor({ type: 'off ramp', modifier: 'sharp right', ref: 'I-280' }),
|
||||
'Take the exit sharply right onto I-280',
|
||||
);
|
||||
assert.equal(
|
||||
instructionFor({ type: 'on ramp', modifier: 'straight', name: 'US 101' }),
|
||||
'Take the ramp onto US 101',
|
||||
);
|
||||
assert.equal(
|
||||
instructionFor({ type: 'use lane', modifier: 'slight left' }),
|
||||
'Use the left lane',
|
||||
);
|
||||
assert.equal(
|
||||
instructionFor({ type: 'use lane', modifier: 'right', name: 'Main St' }),
|
||||
'Use the right lane onto Main St',
|
||||
);
|
||||
assert.equal(
|
||||
instructionFor({
|
||||
type: 'merge',
|
||||
|
||||
@@ -233,6 +233,9 @@ export async function resolveTerrainHeightRequest({
|
||||
for (let i = 0; i < missing.length; i += 1) {
|
||||
const result = fetched[i];
|
||||
if (validTerrainResult(result)) {
|
||||
// Re-insert rather than overwrite: a Map keeps an existing key in
|
||||
// its old position, and the proxy evicts from the front.
|
||||
cache.delete(missing[i].key);
|
||||
cache.set(missing[i].key, { at: fetchedAt, result });
|
||||
cacheChanged = true;
|
||||
} else if (absentTerrainDatum(result)) {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* @file Pure tile math + budget accounting for the TomTom traffic-flow proxy.
|
||||
*
|
||||
* Shared by the `/api/tomtom` vite plugin (server-side: coordinate validation,
|
||||
* daily budget governor) and `src/data/flowTiles.js` (client-side: which tiles
|
||||
* daily budget governor) and `src/layers/traffic/flowSource.js` (client-side: which tiles
|
||||
* cover the current traffic fetch bounds). Zero dependencies, Cesium-free, so
|
||||
* both sides can unit-test against it with node:test.
|
||||
*
|
||||
|
||||
@@ -124,7 +124,13 @@ class PlaybackClock {
|
||||
subscribe(listener) {
|
||||
if (this._destroyed || typeof listener !== 'function') return () => {};
|
||||
this._sceneClockListeners.add(listener);
|
||||
if (this._sceneClockSnapshot) listener({ ...this._sceneClockSnapshot });
|
||||
if (this._sceneClockSnapshot) {
|
||||
try {
|
||||
listener({ ...this._sceneClockSnapshot });
|
||||
} catch (error) {
|
||||
console.warn('[Scenes] Scene clock listener failed:', error);
|
||||
}
|
||||
}
|
||||
return () => this._sceneClockListeners.delete(listener);
|
||||
}
|
||||
|
||||
|
||||
@@ -171,3 +171,32 @@ test('a subscriber can Stop or replace the initial clock without the old start a
|
||||
});
|
||||
assert.equal(f.timers.size, 0);
|
||||
});
|
||||
|
||||
test('a subscriber throwing on immediate snapshot does not crash subscribe and receives unsubscribe handle', () => {
|
||||
const f = fixture();
|
||||
f.clock.publish(scene, shot, 1);
|
||||
let calls = 0;
|
||||
const warnings = [];
|
||||
const origWarn = console.warn;
|
||||
console.warn = (...args) => warnings.push(args);
|
||||
try {
|
||||
const unsubscribe = f.clock.subscribe(() => {
|
||||
calls++;
|
||||
throw new Error('listener failure');
|
||||
});
|
||||
assert.equal(typeof unsubscribe, 'function');
|
||||
assert.equal(calls, 1);
|
||||
assert.equal(warnings.length, 1);
|
||||
assert.equal(warnings[0][0], '[Scenes] Scene clock listener failed:');
|
||||
f.clock.publish(scene, shot, 2);
|
||||
assert.equal(calls, 2);
|
||||
assert.equal(warnings.length, 2);
|
||||
unsubscribe();
|
||||
f.clock.publish(scene, shot, 3);
|
||||
assert.equal(calls, 2);
|
||||
assert.equal(warnings.length, 2);
|
||||
f.clock.destroy();
|
||||
} finally {
|
||||
console.warn = origWarn;
|
||||
}
|
||||
});
|
||||
@@ -178,6 +178,92 @@ test('synchronous stop before execution prevents any side effect; rejection unlo
|
||||
assert.equal(calls, 2);
|
||||
});
|
||||
|
||||
test('a throwing changed observer does not break session dispatch, activation, or clearing', async () => {
|
||||
let executed = 0;
|
||||
let throwOnBusy = true;
|
||||
let throwOnEnd = true;
|
||||
const warnings = [];
|
||||
const origWarn = console.warn;
|
||||
console.warn = (...args) => warnings.push(args);
|
||||
try {
|
||||
const session = createInteractionSession({
|
||||
execute: () => {
|
||||
executed++;
|
||||
return true;
|
||||
},
|
||||
changed: (state) => {
|
||||
if (throwOnBusy && state.busy) throw new Error('start failed');
|
||||
if (throwOnEnd && !state.busy && state.selected === 'a') {
|
||||
throw new Error('end failed');
|
||||
}
|
||||
},
|
||||
});
|
||||
session.activate([{ id: 'a' }]);
|
||||
const result = await session.dispatch('a');
|
||||
assert.equal(result, true);
|
||||
assert.equal(executed, 1);
|
||||
assert.deepEqual(session.getState(), {
|
||||
active: true,
|
||||
busy: false,
|
||||
selected: 'a',
|
||||
count: 1,
|
||||
});
|
||||
assert.equal(warnings.length, 2);
|
||||
assert.equal(
|
||||
warnings[0][0],
|
||||
'[Scenes] Interaction session observer failed:',
|
||||
);
|
||||
assert.equal(
|
||||
warnings[1][0],
|
||||
'[Scenes] Interaction session observer failed:',
|
||||
);
|
||||
throwOnBusy = false;
|
||||
throwOnEnd = false;
|
||||
assert.equal(await session.dispatch('a'), true);
|
||||
assert.equal(executed, 2);
|
||||
session.clear();
|
||||
assert.deepEqual(session.getState(), {
|
||||
active: false,
|
||||
busy: false,
|
||||
selected: null,
|
||||
count: 0,
|
||||
});
|
||||
} finally {
|
||||
console.warn = origWarn;
|
||||
}
|
||||
});
|
||||
|
||||
test('an observer that always throws cannot stop activate or clear', () => {
|
||||
const warnings = [];
|
||||
const origWarn = console.warn;
|
||||
console.warn = (...args) => warnings.push(args);
|
||||
try {
|
||||
const session = createInteractionSession({
|
||||
execute: () => true,
|
||||
changed: () => {
|
||||
throw new Error('observer failed');
|
||||
},
|
||||
});
|
||||
session.activate([{ id: 'a' }, { id: 'b' }]);
|
||||
assert.deepEqual(session.getState(), {
|
||||
active: true,
|
||||
busy: false,
|
||||
selected: null,
|
||||
count: 2,
|
||||
});
|
||||
session.clear();
|
||||
assert.deepEqual(session.getState(), {
|
||||
active: false,
|
||||
busy: false,
|
||||
selected: null,
|
||||
count: 0,
|
||||
});
|
||||
assert.equal(warnings.length, 3);
|
||||
} finally {
|
||||
console.warn = origWarn;
|
||||
}
|
||||
});
|
||||
|
||||
test('settled pack shots cannot take the same-shot seek shortcut after Stop released geometry', async () => {
|
||||
const { SceneDirector } = await import('../../scenes/director.js');
|
||||
const shot = { id: 'shot', dataPackIds: ['pack'] };
|
||||
@@ -188,7 +274,7 @@ test('settled pack shots cannot take the same-shot seek shortcut after Stop rele
|
||||
_claimCameraOwnership: () =>
|
||||
assert.fail('Must reload the released pack before camera seek'),
|
||||
});
|
||||
assert.equal(director._seekLoadedShot({ id: 'scene' }, { shot }), false);
|
||||
assert.equal(await director._seekLoadedShot({ id: 'scene' }, { shot }), null);
|
||||
});
|
||||
|
||||
test('actions preserve camera refusal, layer admission signal and explicit transition cap', async () => {
|
||||
|
||||
@@ -6,6 +6,13 @@ export function createInteractionSession({ execute, changed = () => {} }) {
|
||||
selected = null;
|
||||
let actions = new Map();
|
||||
const state = () => ({ active, busy, selected, count: actions.size });
|
||||
function notify() {
|
||||
try {
|
||||
changed(state());
|
||||
} catch (error) {
|
||||
console.warn('[Scenes] Interaction session observer failed:', error);
|
||||
}
|
||||
}
|
||||
function clear() {
|
||||
active = false;
|
||||
busy = false;
|
||||
@@ -13,7 +20,7 @@ export function createInteractionSession({ execute, changed = () => {} }) {
|
||||
actions.clear();
|
||||
controller?.abort();
|
||||
controller = null;
|
||||
changed(state());
|
||||
notify();
|
||||
}
|
||||
return {
|
||||
clear,
|
||||
@@ -22,7 +29,7 @@ export function createInteractionSession({ execute, changed = () => {} }) {
|
||||
clear();
|
||||
actions = new Map(items.map((item) => [item.id, item]));
|
||||
active = !!actions.size;
|
||||
changed(state());
|
||||
notify();
|
||||
},
|
||||
async dispatch(id) {
|
||||
const item = actions.get(id);
|
||||
@@ -31,7 +38,7 @@ export function createInteractionSession({ execute, changed = () => {} }) {
|
||||
controller = current;
|
||||
busy = true;
|
||||
selected = id;
|
||||
changed(state());
|
||||
notify();
|
||||
let abort;
|
||||
try {
|
||||
const cancelled = new Promise((resolve) => {
|
||||
@@ -53,7 +60,7 @@ export function createInteractionSession({ execute, changed = () => {} }) {
|
||||
if (controller === current) {
|
||||
busy = false;
|
||||
controller = null;
|
||||
changed(state());
|
||||
notify();
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -35,6 +35,7 @@ export function buildPlaybackQueue(
|
||||
* releaseScene(scene, token?) leaves a previously loaded scene before playback
|
||||
* (false refuses that initial handoff). Between scenes and during final cleanup
|
||||
* it receives no cancelled token, so resource release can finish after Stop.
|
||||
* The first error wins when the final release also fails.
|
||||
* An empty/already-cancelled queue acquires and releases no resources.
|
||||
*
|
||||
* @param {Array<{scene:Object, shot:Object}>} queue Normalized, fixed shot queue.
|
||||
@@ -53,6 +54,7 @@ export async function playSceneQueue(
|
||||
const cancelled = () => Boolean(token.cancelled || token.signal?.aborted);
|
||||
let activeScene = null;
|
||||
let completedShots = 0;
|
||||
let runFailed = false;
|
||||
try {
|
||||
if (!queue.length || cancelled()) {
|
||||
return {
|
||||
@@ -68,8 +70,9 @@ export async function playSceneQueue(
|
||||
for (let index = 0; index < queue.length && !cancelled(); index++) {
|
||||
const { scene, shot } = queue[index];
|
||||
if (activeScene && activeScene.id !== scene.id) {
|
||||
await adapter.releaseScene(activeScene);
|
||||
const toRelease = activeScene;
|
||||
activeScene = null;
|
||||
await adapter.releaseScene(toRelease);
|
||||
if (cancelled()) break;
|
||||
}
|
||||
activeScene = scene;
|
||||
@@ -82,8 +85,23 @@ export async function playSceneQueue(
|
||||
}
|
||||
if (!cancelled()) await adapter.complete?.();
|
||||
return { status: cancelled() ? 'cancelled' : 'completed', completedShots };
|
||||
} catch (error) {
|
||||
runFailed = true;
|
||||
throw error;
|
||||
} finally {
|
||||
if (releaseOnFinish && activeScene) await adapter.releaseScene(activeScene);
|
||||
if (releaseOnFinish && activeScene) {
|
||||
const toRelease = activeScene;
|
||||
activeScene = null;
|
||||
try {
|
||||
await adapter.releaseScene(toRelease);
|
||||
} catch (error) {
|
||||
if (runFailed) {
|
||||
console.warn('[Scenes] Scene release failed:', error);
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -196,3 +196,68 @@ test('a cleanup failure rejects for the caller to restore its own controls', asy
|
||||
(error) => error === failure,
|
||||
);
|
||||
});
|
||||
|
||||
test('a phase failure is preserved when final scene release also throws', async () => {
|
||||
const phaseError = new Error('travel failed');
|
||||
const releaseError = new Error('release failed');
|
||||
const warnings = [];
|
||||
const origWarn = console.warn;
|
||||
console.warn = (...args) => warnings.push(args);
|
||||
try {
|
||||
const f = fixture({
|
||||
travel: async () => {
|
||||
throw phaseError;
|
||||
},
|
||||
releaseScene: async () => {
|
||||
throw releaseError;
|
||||
},
|
||||
});
|
||||
await assert.rejects(
|
||||
playSceneQueue(buildPlaybackQueue(scenes, 'a', { single: true }), f),
|
||||
(error) => error === phaseError,
|
||||
);
|
||||
assert.equal(warnings.length, 1);
|
||||
assert.equal(warnings[0][0], '[Scenes] Scene release failed:');
|
||||
assert.equal(warnings[0][1], releaseError);
|
||||
} finally {
|
||||
console.warn = origWarn;
|
||||
}
|
||||
});
|
||||
|
||||
test('a failing inter-scene release releases the active scene only once', async () => {
|
||||
const releaseError = new Error('release failed');
|
||||
const released = [];
|
||||
const f = fixture({
|
||||
releaseScene: async (scene) => {
|
||||
released.push(scene.id);
|
||||
throw releaseError;
|
||||
},
|
||||
});
|
||||
await assert.rejects(
|
||||
playSceneQueue(buildPlaybackQueue(scenes, 'a'), f),
|
||||
(error) => error === releaseError,
|
||||
);
|
||||
assert.deepEqual(released, ['a']);
|
||||
});
|
||||
|
||||
test('a falsy phase failure is still preserved over a release failure', async () => {
|
||||
const releaseError = new Error('release failed');
|
||||
const origWarn = console.warn;
|
||||
console.warn = () => {};
|
||||
try {
|
||||
const f = fixture({
|
||||
travel: async () => {
|
||||
throw undefined;
|
||||
},
|
||||
releaseScene: async () => {
|
||||
throw releaseError;
|
||||
},
|
||||
});
|
||||
await assert.rejects(
|
||||
playSceneQueue(buildPlaybackQueue(scenes, 'a', { single: true }), f),
|
||||
(error) => error === undefined,
|
||||
);
|
||||
} finally {
|
||||
console.warn = origWarn;
|
||||
}
|
||||
});
|
||||
@@ -75,4 +75,5 @@ test('the Docker install path keeps its loopback-only, launcher-owned contract',
|
||||
assert.match(compose, /^\s+- GEV_KEY_SETUP_TRUSTED_PEERS$/m, 'the operator policy reaches the launcher without a hard-coded address');
|
||||
assert.match(compose, /^\s+- GEV_ALLOWED_HOSTS$/m, 'the host allowlist reaches Vite');
|
||||
assert.doesNotMatch(compose, /network_mode/, 'the container keeps its own network namespace');
|
||||
assert.match(compose, /^\s+- \.:\/app:z$/m, 'SELinux hosts can read the bind-mounted checkout');
|
||||
});
|
||||
@@ -543,6 +543,10 @@ export function initFirstRunExperience({
|
||||
});
|
||||
|
||||
for (const button of buttons) button.addEventListener('click', onChoice);
|
||||
// The same dismissal as ESC, for screens without a keyboard.
|
||||
root
|
||||
.querySelector('[data-first-run-dismiss]')
|
||||
?.addEventListener('click', () => dismiss());
|
||||
suppressBox?.addEventListener('change', onSuppressChange);
|
||||
// Capture phase: the app binds its own global hotkeys (including bare letters
|
||||
// that cycle detection and styles), and the launcher owns the keyboard first.
|
||||
|
||||
@@ -913,6 +913,48 @@ test('markup, startup ordering and accessibility remain pinned', () => {
|
||||
assert.match(choicesBlock, /overflow-y: auto;/);
|
||||
});
|
||||
|
||||
test('the card closes without a keyboard: the ESC hint is a button, kept on phones', () => {
|
||||
const html = expandApplicationHtml(
|
||||
fs.readFileSync(new URL('../index.html', import.meta.url), 'utf8'),
|
||||
);
|
||||
const module = fs.readFileSync(
|
||||
new URL('./firstRunExperience.js', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
// The whole stylesheet, so a hide rule added in any other file is caught too.
|
||||
const css = readStylesheet(new URL('../style.css', import.meta.url));
|
||||
const footer = html.slice(
|
||||
html.indexOf('class="first-run-footer"'),
|
||||
html.indexOf('data-first-run-status'),
|
||||
);
|
||||
assert.match(
|
||||
footer,
|
||||
/<button type="button" class="first-run-dismiss" data-first-run-dismiss>/,
|
||||
);
|
||||
assert.match(footer, /data-i18n>ESC to dismiss</);
|
||||
assert.match(footer, /data-i18n>DISMISS</);
|
||||
// It closes the way ESC does, through the one dismiss path, so the session
|
||||
// flag and focus handling are the same.
|
||||
assert.match(
|
||||
module,
|
||||
/querySelector\('\[data-first-run-dismiss\]'\)\s*\?\.addEventListener\('click', \(\) => dismiss\(\)\)/,
|
||||
);
|
||||
// Phones used to hide the hint, leaving no way out but picking a mission.
|
||||
assert.doesNotMatch(css, /first-run-footer > span:last-child/);
|
||||
assert.doesNotMatch(css, /\.first-run-dismiss\s*\{[^}]*display:\s*none/);
|
||||
// A 44px touch target that does not add to the footer row's height.
|
||||
assert.match(
|
||||
css,
|
||||
/\.first-run-dismiss::before \{[^}]*position: absolute;[^}]*height: 44px;/,
|
||||
);
|
||||
assert.doesNotMatch(css, /\.first-run-dismiss \{[^}]*min-height/);
|
||||
// Touch screens read DISMISS rather than a key they do not have.
|
||||
assert.match(
|
||||
css,
|
||||
/@media \(hover: none\) and \(pointer: coarse\) \{\s*\.first-run-dismiss-key \{\s*display: none;/,
|
||||
);
|
||||
});
|
||||
|
||||
test('the launcher keeps focus, restores it, and never disables the focused button', () => {
|
||||
const module = fs.readFileSync(
|
||||
new URL('./firstRunExperience.js', import.meta.url),
|
||||
@@ -1010,11 +1052,13 @@ test('the voice TOOL SCHEMA matches the pinned contract — the mission mapping
|
||||
// Globe rotation adds one camera motion and its descriptions; Globe View
|
||||
// framing/default guidance updates only move_camera and mode descriptions.
|
||||
// Radio markup and the complete production-request comparison pin locality.
|
||||
// Restore the base camera/Globe View wording with the globe-rotation append.
|
||||
assert.equal(block.length, 30878, 'serialized tool schema length drifted');
|
||||
// Panel adds timeout and named voice/provider targets; consolidated guidance
|
||||
// preserves the mission mapping and globe-rotation arguments.
|
||||
// S2 GhostMaps extends the generated layer enums; both feature contracts remain.
|
||||
assert.equal(block.length, 31206, 'serialized tool schema length drifted');
|
||||
assert.equal(
|
||||
crypto.createHash('sha256').update(block).digest('hex'),
|
||||
'7b95f0f4258896fe5c3316265a19f3a6602809d4e7e681ee7ecd8f2df514ef1f',
|
||||
'f772df95404494bf492e02fde1beabffdfe61986940bffd0cf9ad5a38d768746',
|
||||
'the first-run missions must ride EXISTING tools: no schema edit, no cache bust',
|
||||
);
|
||||
const instructions = fs.readFileSync(
|
||||
|
||||
+69
-31
@@ -224,6 +224,20 @@ export class IntelHUD {
|
||||
// session, so this flips once — and both altitude readouts have to move
|
||||
// together when it does (see the repaint in _updateCameraData).
|
||||
this._geoidCorrectionApplied = false;
|
||||
// A summary built for one view must not land on the next: a request in
|
||||
// flight when the camera starts moving is aborted and nothing it ends
|
||||
// with paints (the revision moves), a reply still typing stops, and the
|
||||
// summary is marked dirty so the next periodic tick asks about the view
|
||||
// the camera has moved to.
|
||||
this._onCameraMoveStart = () => {
|
||||
this._markSummaryDirty();
|
||||
if (this._summaryRequest || this._summaryTypingInterval) {
|
||||
// Cancelled requests and partially typed replies are not reusable answers.
|
||||
this._lastSummarySignature = null;
|
||||
}
|
||||
this._summaryRequest?.abort();
|
||||
this._stopSummaryTyping();
|
||||
};
|
||||
this._onCameraMoveEnd = () => {
|
||||
this._markSummaryDirty();
|
||||
// The 250 ms telemetry timer and 15 s semantic-summary timer must not
|
||||
@@ -249,6 +263,7 @@ export class IntelHUD {
|
||||
this._passNum = 100 + Math.floor(Math.random() * 200);
|
||||
|
||||
this._buildDOM();
|
||||
this.viewer.camera.moveStart.addEventListener(this._onCameraMoveStart);
|
||||
this.viewer.camera.moveEnd.addEventListener(this._onCameraMoveEnd);
|
||||
this._startTimers();
|
||||
}
|
||||
@@ -267,28 +282,28 @@ export class IntelHUD {
|
||||
<div class="hud-sonar" aria-hidden="true"></div>
|
||||
|
||||
<div class="hud-top-bar">
|
||||
<span class="hud-top-bar-left">TOP SECRET // SI-TK // NOFORN</span>
|
||||
<span class="hud-top-bar-center">${this._missionId}</span>
|
||||
<span class="hud-top-bar-right">PAGE 1/1</span>
|
||||
<span class="hud-readout"><span class="hud-top-bar-left">TOP SECRET // SI-TK // NOFORN</span></span>
|
||||
<span class="hud-readout"><span class="hud-top-bar-center">${this._missionId}</span></span>
|
||||
<span class="hud-readout"><span class="hud-top-bar-right">PAGE 1/1</span></span>
|
||||
</div>
|
||||
|
||||
<div class="hud-corner hud-top-left">
|
||||
<div class="hud-bracket">┌</div>
|
||||
<div class="hud-content">
|
||||
<div class="hud-classification">TOP SECRET // SI-TK // NOFORN</div>
|
||||
<div class="hud-system">${this._missionId} ${this._sensorId}</div>
|
||||
<div class="hud-mode" id="hud-mode">${t(MODE_LABELS.normal)}</div>
|
||||
<div class="hud-readout"><div class="hud-classification">TOP SECRET // SI-TK // NOFORN</div></div>
|
||||
<div class="hud-readout"><div class="hud-system">${this._missionId} ${this._sensorId}</div></div>
|
||||
<div class="hud-readout"><div class="hud-mode" id="hud-mode">${t(MODE_LABELS.normal)}</div></div>
|
||||
<div class="hud-summary-wrap">
|
||||
<div class="hud-summary-label">${t('SUMMARY')}</div>
|
||||
<div class="hud-summary" id="hud-summary">${t('Awaiting telemetry...')}</div>
|
||||
<div class="hud-readout"><div class="hud-summary-label">${t('SUMMARY')}</div></div>
|
||||
<div class="hud-readout"><div class="hud-summary" id="hud-summary">${t('Awaiting telemetry...')}</div></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="hud-corner hud-top-right">
|
||||
<div class="hud-content" style="text-align:right">
|
||||
<div class="hud-rec"><span id="hud-rec-dot">●</span> ${t('REC')} <span id="hud-timestamp">2026-01-01 00:00:00Z</span></div>
|
||||
<div class="hud-orbital">ORB: ${this._orbitNum} PASS: DESC-${this._passNum}</div>
|
||||
<div class="hud-readout"><div class="hud-rec"><span id="hud-rec-dot">●</span> ${t('REC')} <span id="hud-timestamp">2026-01-01 00:00:00Z</span></div></div>
|
||||
<div class="hud-readout"><div class="hud-orbital">ORB: ${this._orbitNum} PASS: DESC-${this._passNum}</div></div>
|
||||
</div>
|
||||
<div class="hud-bracket">┐</div>
|
||||
</div>
|
||||
@@ -296,33 +311,33 @@ export class IntelHUD {
|
||||
<div class="hud-corner hud-bottom-left">
|
||||
<div class="hud-bracket">└</div>
|
||||
<div class="hud-content">
|
||||
<div id="hud-mgrs">MGRS: ---</div>
|
||||
<div id="hud-latlon">--°--'--"N ---°--'--"W</div>
|
||||
<div class="hud-readout"><div id="hud-mgrs">MGRS: ---</div></div>
|
||||
<div class="hud-readout"><div id="hud-latlon">--°--'--"N ---°--'--"W</div></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="hud-corner hud-bottom-right">
|
||||
<div class="hud-content" style="text-align:right">
|
||||
<div id="hud-gsd">GSD: --m NIIRS: --</div>
|
||||
<div id="hud-alt">ALT: --m SUN: --° EL</div>
|
||||
<div id="hud-ais-vessel" class="hud-ais-vessel">${t('AIS: --')}</div>
|
||||
<div class="hud-readout"><div id="hud-gsd">GSD: --m NIIRS: --</div></div>
|
||||
<div class="hud-readout"><div id="hud-alt">ALT: --m SUN: --° EL</div></div>
|
||||
<div class="hud-readout"><div id="hud-ais-vessel" class="hud-ais-vessel">${t('AIS: --')}</div></div>
|
||||
</div>
|
||||
<div class="hud-bracket">┘</div>
|
||||
</div>
|
||||
|
||||
<div class="hud-edge hud-left-edge">
|
||||
<div id="hud-coll">COLL: --:--:--Z</div>
|
||||
<div id="hud-ona">ONA: --°</div>
|
||||
<div class="hud-readout"><div id="hud-coll">COLL: --:--:--Z</div></div>
|
||||
<div class="hud-readout"><div id="hud-ona">ONA: --°</div></div>
|
||||
</div>
|
||||
|
||||
<div class="hud-edge hud-right-edge">
|
||||
<div>BAND: PAN</div>
|
||||
<div>BITS: 11</div>
|
||||
<div>LVL: 1A</div>
|
||||
<div class="hud-readout"><div>BAND: PAN</div></div>
|
||||
<div class="hud-readout"><div>BITS: 11</div></div>
|
||||
<div class="hud-readout"><div>LVL: 1A</div></div>
|
||||
</div>
|
||||
|
||||
<div class="hud-bottom-bar">
|
||||
<span id="hud-bottom-line">LAT: -- LON: -- MGRS: ---</span>
|
||||
<span class="hud-readout"><span id="hud-bottom-line">LAT: -- LON: -- MGRS: ---</span></span>
|
||||
</div>
|
||||
`;
|
||||
this._el.dataset.variant = this._variant;
|
||||
@@ -559,11 +574,12 @@ export class IntelHUD {
|
||||
* @returns {string} Formatted DMS string, e.g. `"38°53'23.10"N"`.
|
||||
*/
|
||||
_toDMS(decimal, type) {
|
||||
const abs = Math.abs(decimal);
|
||||
const deg = Math.floor(abs);
|
||||
const minFloat = (abs - deg) * 60;
|
||||
const min = Math.floor(minFloat);
|
||||
const sec = ((minFloat - min) * 60).toFixed(2);
|
||||
// Round once, in hundredths of a second, so a value that rounds up to
|
||||
// 60.00" carries into the minutes and degrees instead of printing 60.
|
||||
const hundredths = Math.round(Math.abs(decimal) * 360000);
|
||||
const deg = Math.floor(hundredths / 360000);
|
||||
const min = Math.floor(hundredths / 6000) % 60;
|
||||
const sec = ((hundredths % 6000) / 100).toFixed(2);
|
||||
|
||||
let dir;
|
||||
if (type === 'lat') dir = decimal >= 0 ? 'N' : 'S';
|
||||
@@ -766,6 +782,12 @@ export class IntelHUD {
|
||||
return provenance ? `${line} | ${provenance}` : line;
|
||||
}
|
||||
|
||||
/** Stop a summary still typing out, leaving what it has typed so far. */
|
||||
_stopSummaryTyping() {
|
||||
clearInterval(this._summaryTypingInterval);
|
||||
this._summaryTypingInterval = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Animate the summary text into the DOM using a typewriter effect
|
||||
* (2 characters every 24ms).
|
||||
@@ -816,8 +838,10 @@ export class IntelHUD {
|
||||
} catch (error) {
|
||||
console.warn('[HUD] summary context unavailable:', error);
|
||||
// Left dirty on purpose: the next periodic tick retries instead of
|
||||
// sticking on the fallback line for the rest of the session.
|
||||
this._setSummaryText(fallbackText, animate);
|
||||
// sticking on the fallback line for the rest of the session. The
|
||||
// fallback was composed for this view; a moved camera keeps its own.
|
||||
if (revision === this._summaryRevision)
|
||||
this._setSummaryText(fallbackText, animate);
|
||||
return;
|
||||
}
|
||||
if (revision !== this._summaryRevision) return;
|
||||
@@ -832,7 +856,11 @@ export class IntelHUD {
|
||||
this._summaryDirty = false;
|
||||
this._lastSummarySignature = signature;
|
||||
const controller = new AbortController();
|
||||
const timeout = window.setTimeout(() => controller.abort(), 5000);
|
||||
let timedOut = false;
|
||||
const timeout = window.setTimeout(() => {
|
||||
timedOut = true;
|
||||
controller.abort();
|
||||
}, 5000);
|
||||
this._summaryRequest = controller;
|
||||
try {
|
||||
this.summaryPolicy.onRequest?.();
|
||||
@@ -855,17 +883,24 @@ export class IntelHUD {
|
||||
animate,
|
||||
);
|
||||
} catch (error) {
|
||||
if (error?.name !== 'AbortError') {
|
||||
// The 5 s timeout is a failure like any other; a move's abort (or
|
||||
// destroy's) is not.
|
||||
const moved = revision !== this._summaryRevision;
|
||||
if (error?.name !== 'AbortError' || timedOut) {
|
||||
console.warn('[HUD] AI summary unavailable:', error);
|
||||
// Invalidate the committed signature so the next periodic tick
|
||||
// retries instead of sticking on the fallback line forever.
|
||||
this._lastSummarySignature = null;
|
||||
this._summaryDirty = true;
|
||||
}
|
||||
this._setSummaryText(fallbackText, animate);
|
||||
if (!moved) this._setSummaryText(fallbackText, animate);
|
||||
} finally {
|
||||
window.clearTimeout(timeout);
|
||||
if (this._summaryRequest === controller) this._summaryRequest = null;
|
||||
// A request whose answer was dropped (aborted by a move, or a reply
|
||||
// that came back after one) committed a signature it never painted;
|
||||
// forget it, or the next tick over the same place would skip asking.
|
||||
if (revision !== this._summaryRevision) this._lastSummarySignature = null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -874,6 +909,8 @@ export class IntelHUD {
|
||||
this._typeSummary(text);
|
||||
return;
|
||||
}
|
||||
// A plain paint replaces any reply still typing.
|
||||
this._stopSummaryTyping();
|
||||
const el = document.getElementById('hud-summary');
|
||||
if (el) el.textContent = text;
|
||||
}
|
||||
@@ -1044,6 +1081,7 @@ export class IntelHUD {
|
||||
clearInterval(this._timestampInterval);
|
||||
clearInterval(this._summaryInterval);
|
||||
clearInterval(this._summaryTypingInterval);
|
||||
this.viewer.camera.moveStart.removeEventListener(this._onCameraMoveStart);
|
||||
this.viewer.camera.moveEnd.removeEventListener(this._onCameraMoveEnd);
|
||||
this._dataManagerUnsubscribe?.();
|
||||
this._summaryRequest?.abort();
|
||||
|
||||
@@ -16,6 +16,9 @@
|
||||
// globals exist: Cesium's widget bundle probes for a real `document` at module
|
||||
// scope and a partial stub sends it down the browser path. Hence hook →
|
||||
// import → install DOM, in that order.
|
||||
//
|
||||
// The same hook is why the live AI-summary test lives here too: this is the
|
||||
// one file that can construct a real IntelHUD.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
@@ -33,7 +36,8 @@ registerHooks({
|
||||
return {
|
||||
format: 'module',
|
||||
shortCircuit: true,
|
||||
source: 'export function forward() { return "10SEG55776339"; }\nexport default { forward };\n',
|
||||
source:
|
||||
'export function forward() { return "10SEG55776339"; }\nexport default { forward };\n',
|
||||
};
|
||||
}
|
||||
return next(url, context);
|
||||
@@ -59,10 +63,20 @@ const SFO_ELLIPSOIDAL_M = -15;
|
||||
*/
|
||||
function installHudEnvironment() {
|
||||
const elements = new Map(
|
||||
['hud-alt', 'hud-summary', 'hud-mgrs', 'hud-latlon', 'hud-bottom-line', 'hud-gsd', 'hud-coll', 'hud-ona', 'hud-mode']
|
||||
.map((id) => [id, { textContent: '' }]),
|
||||
[
|
||||
'hud-alt',
|
||||
'hud-summary',
|
||||
'hud-mgrs',
|
||||
'hud-latlon',
|
||||
'hud-bottom-line',
|
||||
'hud-gsd',
|
||||
'hud-coll',
|
||||
'hud-ona',
|
||||
'hud-mode',
|
||||
].map((id) => [id, { textContent: '' }]),
|
||||
);
|
||||
const previousDocument = globalThis.document;
|
||||
const cameraListeners = {};
|
||||
globalThis.document = {
|
||||
getElementById: (id) => elements.get(id) ?? null,
|
||||
querySelectorAll: () => [],
|
||||
@@ -78,12 +92,24 @@ function installHudEnvironment() {
|
||||
height: SFO_ELLIPSOIDAL_M,
|
||||
},
|
||||
computeViewRectangle: () => undefined,
|
||||
moveEnd: { addEventListener() {}, removeEventListener() {} },
|
||||
moveStart: {
|
||||
addEventListener(listener) {
|
||||
cameraListeners.moveStart = listener;
|
||||
},
|
||||
removeEventListener() {},
|
||||
},
|
||||
moveEnd: {
|
||||
addEventListener(listener) {
|
||||
cameraListeners.moveEnd = listener;
|
||||
},
|
||||
removeEventListener() {},
|
||||
},
|
||||
},
|
||||
};
|
||||
return {
|
||||
elements,
|
||||
viewer,
|
||||
cameraListeners,
|
||||
restore() {
|
||||
if (previousDocument === undefined) delete globalThis.document;
|
||||
else globalThis.document = previousDocument;
|
||||
@@ -93,7 +119,9 @@ function installHudEnvironment() {
|
||||
|
||||
test('hud.js corrects the camera height to MSL through the geoid module', () => {
|
||||
assert.equal(
|
||||
has(/import \{[^}]*\bellipsoidalToMslDisplayM\b[^}]*\} from '\.\/data\/geoid\.js';/s),
|
||||
has(
|
||||
/import \{[^}]*\bellipsoidalToMslDisplayM\b[^}]*\} from '\.\/data\/geoid\.js';/s,
|
||||
),
|
||||
true,
|
||||
'hud.js must take the datum correction from ./data/geoid.js, not re-derive one',
|
||||
);
|
||||
@@ -108,7 +136,9 @@ test('hud.js corrects the camera height to MSL through the geoid module', () =>
|
||||
'the ~2.7 MB grid must be requested once, on demand — not at HUD construction',
|
||||
);
|
||||
assert.equal(
|
||||
has(/\.catch\(\(\) => \{\s*\/\* readout falls back to the uncorrected height \*\/\s*\}\)/),
|
||||
has(
|
||||
/\.catch\(\(\) => \{\s*\/\* readout falls back to the uncorrected height \*\/\s*\}\)/,
|
||||
),
|
||||
true,
|
||||
'a failed geoid load must leave the readout uncorrected, not unhandled',
|
||||
);
|
||||
@@ -141,7 +171,9 @@ test('the summary ALT tag agrees with the corner readout', () => {
|
||||
// Both are on screen together; a viewer reading "ALT -15M" in one corner and
|
||||
// "ALT: 17m" in the other has found a bug, not a distinction.
|
||||
assert.equal(
|
||||
has(/const altDisplayM = Number\.isFinite\(m\.altMslM\) \? m\.altMslM : m\.altM;/),
|
||||
has(
|
||||
/const altDisplayM = Number\.isFinite\(m\.altMslM\) \? m\.altMslM : m\.altM;/,
|
||||
),
|
||||
true,
|
||||
'the summary altitude tag must prefer the MSL datum and fall back to the raw height',
|
||||
);
|
||||
@@ -188,7 +220,11 @@ test('a cold tick paints both readouts uncorrected, and resolving flips both in
|
||||
// Tick 1 — cold. This is also the tick that requests the grid.
|
||||
hud._updateCameraData();
|
||||
assert.match(alt(), /^ALT: -15m/, `cold corner readout, got ${alt()}`);
|
||||
assert.match(summary(), /\| ALT -15M \|/, `cold summary tag, got ${summary()}`);
|
||||
assert.match(
|
||||
summary(),
|
||||
/\| ALT -15M \|/,
|
||||
`cold summary tag, got ${summary()}`,
|
||||
);
|
||||
|
||||
// The HUD registered its own continuation on this same shared promise
|
||||
// during tick 1, and it registered first, so awaiting here means its
|
||||
@@ -248,3 +284,294 @@ test('the corrected readouts are the MSL datum, not a coincidence of the SFO sig
|
||||
env.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('a summary asked for one view is dropped once the camera moves', async () => {
|
||||
const env = installHudEnvironment();
|
||||
const previousWindow = globalThis.window;
|
||||
globalThis.window = globalThis;
|
||||
const pending = [];
|
||||
const summaryService = {
|
||||
summarize: (context) =>
|
||||
new Promise((resolve) => {
|
||||
pending.push({
|
||||
context,
|
||||
reply: (summary) =>
|
||||
resolve({ ok: true, status: 200, data: { summary, error: null } }),
|
||||
});
|
||||
}),
|
||||
};
|
||||
let hud;
|
||||
try {
|
||||
hud = new IntelHUD(env.viewer, { summaryService });
|
||||
let place = 'Yellowstone';
|
||||
hud._summaryContext = async () => ({ place });
|
||||
const summary = () => env.elements.get('hud-summary').textContent;
|
||||
const settle = () => new Promise((resolve) => setImmediate(resolve));
|
||||
hud._updateCameraData();
|
||||
|
||||
// The periodic tick's call (force=false): it asks only for a dirty
|
||||
// summary. Asked over Yellowstone; the camera leaves before the reply
|
||||
// lands.
|
||||
const first = hud._updateSummary(false);
|
||||
await settle();
|
||||
assert.equal(pending.length, 1);
|
||||
env.cameraListeners.moveStart();
|
||||
pending[0].reply('Canyon Junction Wyoming');
|
||||
await first;
|
||||
assert.doesNotMatch(
|
||||
summary(),
|
||||
/Canyon Junction/,
|
||||
'a reply for the old view is dropped',
|
||||
);
|
||||
|
||||
// The next tick, with the camera still moving (a follow camera or an
|
||||
// orbit emits no moveEnd), asks about where it is now and paints it.
|
||||
place = 'Atlantic';
|
||||
const moving = hud._updateSummary(false);
|
||||
await settle();
|
||||
assert.equal(pending.length, 2, 'the move marked the summary dirty');
|
||||
assert.deepEqual(pending[1].context, { place: 'Atlantic' });
|
||||
pending[1].reply('North Atlantic Ocean');
|
||||
await moving;
|
||||
assert.equal(summary(), 'North Atlantic Ocean');
|
||||
} finally {
|
||||
for (const request of pending) request.reply('');
|
||||
hud?.destroy();
|
||||
if (previousWindow === undefined) delete globalThis.window;
|
||||
else globalThis.window = previousWindow;
|
||||
env.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('a request the camera leaves paints nothing: aborted, failed, or its context build throws', async () => {
|
||||
const env = installHudEnvironment();
|
||||
const previousWindow = globalThis.window;
|
||||
globalThis.window = globalThis;
|
||||
const pending = [];
|
||||
// Like fetch: an abort rejects with an AbortError, unless `ignoreAbort`.
|
||||
let ignoreAbort = false;
|
||||
const summaryService = {
|
||||
summarize: (context, { signal }) =>
|
||||
new Promise((resolve, reject) => {
|
||||
pending.push({ signal, reject });
|
||||
if (!ignoreAbort)
|
||||
signal.addEventListener('abort', () =>
|
||||
reject(Object.assign(new Error('aborted'), { name: 'AbortError' })),
|
||||
);
|
||||
}),
|
||||
};
|
||||
let hud;
|
||||
try {
|
||||
hud = new IntelHUD(env.viewer, { summaryService });
|
||||
hud._summaryContext = async () => ({ place: 'Yellowstone' });
|
||||
const element = env.elements.get('hud-summary');
|
||||
const settle = () => new Promise((resolve) => setImmediate(resolve));
|
||||
hud._updateCameraData();
|
||||
|
||||
// The move aborts the request in flight, and the abort paints nothing.
|
||||
let update = hud._updateSummary(false, true);
|
||||
await settle();
|
||||
element.textContent = 'shown before the move';
|
||||
env.cameraListeners.moveStart();
|
||||
assert.equal(pending[0].signal.aborted, true, 'the request is aborted');
|
||||
await update;
|
||||
assert.equal(element.textContent, 'shown before the move');
|
||||
|
||||
// A request that fails after the move (an error, the 5 s timeout) does
|
||||
// not paint the old view's fallback line either.
|
||||
ignoreAbort = true;
|
||||
update = hud._updateSummary(false, true);
|
||||
await settle();
|
||||
element.textContent = 'shown before the move';
|
||||
env.cameraListeners.moveStart();
|
||||
pending[1].reject(new Error('network'));
|
||||
await update;
|
||||
assert.equal(element.textContent, 'shown before the move');
|
||||
|
||||
// Nor does a context build that throws once the camera has moved.
|
||||
hud._summaryContext = async () => {
|
||||
env.cameraListeners.moveStart();
|
||||
throw new Error('view target unavailable');
|
||||
};
|
||||
element.textContent = 'shown before the move';
|
||||
await hud._updateSummary(false, true);
|
||||
assert.equal(element.textContent, 'shown before the move');
|
||||
} finally {
|
||||
hud?.destroy();
|
||||
if (previousWindow === undefined) delete globalThis.window;
|
||||
else globalThis.window = previousWindow;
|
||||
env.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('a cancelled summary retries the same context but completed answers stay reusable', async () => {
|
||||
const env = installHudEnvironment();
|
||||
const previousWindow = globalThis.window;
|
||||
globalThis.window = globalThis;
|
||||
const pending = [];
|
||||
const summaryService = {
|
||||
summarize: (context, { signal }) =>
|
||||
new Promise((resolve, reject) => {
|
||||
pending.push({
|
||||
context,
|
||||
reply: (summary) =>
|
||||
resolve({ ok: true, status: 200, data: { summary } }),
|
||||
});
|
||||
signal.addEventListener('abort', () =>
|
||||
reject(Object.assign(new Error('aborted'), { name: 'AbortError' })),
|
||||
);
|
||||
}),
|
||||
};
|
||||
let hud;
|
||||
try {
|
||||
hud = new IntelHUD(env.viewer, { summaryService });
|
||||
hud._summaryContext = async () => ({ place: 'San Francisco' });
|
||||
hud._updateCameraData();
|
||||
const settle = () => new Promise((resolve) => setImmediate(resolve));
|
||||
const first = hud._updateSummary(false);
|
||||
await settle();
|
||||
assert.equal(pending.length, 1);
|
||||
env.cameraListeners.moveStart();
|
||||
await first;
|
||||
|
||||
// An orbit can leave all semantic place/layer labels unchanged. The next
|
||||
// periodic tick must retry even though its context equals the aborted one.
|
||||
const retry = hud._updateSummary(false);
|
||||
await settle();
|
||||
assert.equal(
|
||||
pending.length,
|
||||
2,
|
||||
'the cancelled signature cannot suppress a retry',
|
||||
);
|
||||
assert.deepEqual(pending[1].context, pending[0].context);
|
||||
pending[1].reply('San Francisco Bay Urban Landscape');
|
||||
await retry;
|
||||
assert.equal(
|
||||
env.elements.get('hud-summary').textContent,
|
||||
'San Francisco Bay Urban Landscape',
|
||||
);
|
||||
|
||||
// Movement without an active request must not discard a completed answer.
|
||||
env.cameraListeners.moveStart();
|
||||
await hud._updateSummary(false);
|
||||
assert.equal(pending.length, 2, 'completed context still deduplicates');
|
||||
} finally {
|
||||
for (const request of pending) request.reply('');
|
||||
hud?.destroy();
|
||||
if (previousWindow === undefined) delete globalThis.window;
|
||||
else globalThis.window = previousWindow;
|
||||
env.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('after a dropped or timed-out request the next tick asks again, and a move stops typing', async (t) => {
|
||||
t.mock.timers.enable({ apis: ['setTimeout', 'setInterval'] });
|
||||
const env = installHudEnvironment();
|
||||
const previousWindow = globalThis.window;
|
||||
globalThis.window = globalThis;
|
||||
const pending = [];
|
||||
const summaryService = {
|
||||
summarize: (context, { signal }) =>
|
||||
new Promise((resolve, reject) => {
|
||||
pending.push({ resolve });
|
||||
signal.addEventListener('abort', () =>
|
||||
reject(Object.assign(new Error('aborted'), { name: 'AbortError' })),
|
||||
);
|
||||
}),
|
||||
};
|
||||
let hud;
|
||||
try {
|
||||
hud = new IntelHUD(env.viewer, { summaryService });
|
||||
// The same place before and after: a slow follow camera, a small pan.
|
||||
hud._summaryContext = async () => ({ place: 'Lisboa' });
|
||||
const element = env.elements.get('hud-summary');
|
||||
const settle = () => new Promise((resolve) => setImmediate(resolve));
|
||||
hud._updateCameraData();
|
||||
|
||||
// A move aborts the request; the next tick over the same place asks again.
|
||||
let update = hud._updateSummary(false);
|
||||
await settle();
|
||||
env.cameraListeners.moveStart();
|
||||
await update;
|
||||
update = hud._updateSummary(false);
|
||||
await settle();
|
||||
assert.equal(pending.length, 2, 'asked again after the abort');
|
||||
|
||||
// That one times out at 5 s: retried like any failure.
|
||||
t.mock.timers.tick(5_000);
|
||||
await update;
|
||||
update = hud._updateSummary(false);
|
||||
await settle();
|
||||
assert.equal(pending.length, 3, 'asked again after the timeout');
|
||||
pending[2].resolve({
|
||||
ok: true,
|
||||
status: 200,
|
||||
data: { summary: 'Lisboa Rua Augusta', error: null },
|
||||
});
|
||||
await update;
|
||||
|
||||
// A reply still typing stops when the camera starts moving.
|
||||
hud._typeSummary('Canyon Junction Wyoming Yellowstone National Park');
|
||||
t.mock.timers.tick(48);
|
||||
const typed = element.textContent;
|
||||
env.cameraListeners.moveStart();
|
||||
t.mock.timers.tick(2_000);
|
||||
assert.equal(
|
||||
element.textContent,
|
||||
typed,
|
||||
'no more characters after the move',
|
||||
);
|
||||
} finally {
|
||||
hud?.destroy();
|
||||
if (previousWindow === undefined) delete globalThis.window;
|
||||
else globalThis.window = previousWindow;
|
||||
env.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('a summary interrupted while typing can retry unchanged context', async (t) => {
|
||||
t.mock.timers.enable({ apis: ['setTimeout', 'setInterval'] });
|
||||
const env = installHudEnvironment();
|
||||
const previousWindow = globalThis.window;
|
||||
globalThis.window = globalThis;
|
||||
let calls = 0;
|
||||
const text = 'San Francisco Bay Urban Landscape';
|
||||
const summaryService = {
|
||||
summarize: async () => {
|
||||
calls++;
|
||||
return { ok: true, status: 200, data: { summary: text } };
|
||||
},
|
||||
};
|
||||
let hud;
|
||||
try {
|
||||
hud = new IntelHUD(env.viewer, { summaryService });
|
||||
hud._summaryContext = async () => ({ place: 'San Francisco' });
|
||||
hud._updateCameraData();
|
||||
await hud._updateSummary(true);
|
||||
t.mock.timers.tick(48);
|
||||
const element = env.elements.get('hud-summary');
|
||||
assert.notEqual(element.textContent, text, 'the answer is still typing');
|
||||
assert.equal(
|
||||
hud._summaryRequest,
|
||||
null,
|
||||
'the network request already finished',
|
||||
);
|
||||
env.cameraListeners.moveStart();
|
||||
assert.equal(hud._summaryTypingInterval, null);
|
||||
await hud._updateSummary(false);
|
||||
assert.equal(
|
||||
calls,
|
||||
2,
|
||||
'a partially displayed answer must not suppress retry',
|
||||
);
|
||||
assert.equal(element.textContent, text);
|
||||
env.cameraListeners.moveStart();
|
||||
await hud._updateSummary(false);
|
||||
assert.equal(calls, 2, 'the fully displayed answer remains reusable');
|
||||
} finally {
|
||||
hud?.destroy();
|
||||
if (previousWindow === undefined) delete globalThis.window;
|
||||
else globalThis.window = previousWindow;
|
||||
env.restore();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
// The HUD's LAT/LON readout in degrees-minutes-seconds. Seconds are printed to
|
||||
// two decimals, so a value within 0.005" of the next whole minute rounds up.
|
||||
// That carry must reach the minutes (and degrees): `122°20'60.00"W` is not a
|
||||
// coordinate. Ordinary decimal inputs land there through binary floating
|
||||
// point: 122.35 - 122 is 0.34999999999999432, so -122.35 read 20'60.00".
|
||||
//
|
||||
// hud.js imports `mgrs`, a CommonJS package whose named exports Node's ESM
|
||||
// loader cannot see, so this installs the same one-specifier stub as
|
||||
// hudAltitudeDatum.test.mjs before importing it.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { registerHooks } from 'node:module';
|
||||
|
||||
const MGRS_STUB_URL = 'gev-test-stub:mgrs';
|
||||
registerHooks({
|
||||
resolve(specifier, context, next) {
|
||||
if (specifier === 'mgrs') return { url: MGRS_STUB_URL, shortCircuit: true };
|
||||
return next(specifier, context);
|
||||
},
|
||||
load(url, context, next) {
|
||||
if (url === MGRS_STUB_URL) {
|
||||
return {
|
||||
format: 'module',
|
||||
shortCircuit: true,
|
||||
source:
|
||||
'export function forward() { return "10SEG55776339"; }\nexport default { forward };\n',
|
||||
};
|
||||
}
|
||||
return next(url, context);
|
||||
},
|
||||
});
|
||||
|
||||
const { IntelHUD } = await import('./hud.js');
|
||||
|
||||
const toDMS = (decimal, type) => IntelHUD.prototype._toDMS(decimal, type);
|
||||
|
||||
test('a rounded-up second carries into the minutes', () => {
|
||||
assert.equal(toDMS(-122.35, 'lon'), `122°21'00.00"W`);
|
||||
assert.equal(toDMS(139.7, 'lon'), `139°42'00.00"E`);
|
||||
assert.equal(toDMS(37.0166666, 'lat'), `37°01'00.00"N`);
|
||||
});
|
||||
|
||||
test('a carry through 59 minutes reaches the degrees', () => {
|
||||
assert.equal(toDMS(38.999999, 'lat'), `39°00'00.00"N`);
|
||||
assert.equal(toDMS(-0.999999, 'lat'), `01°00'00.00"S`);
|
||||
assert.equal(toDMS(179.999999, 'lon'), `180°00'00.00"E`);
|
||||
});
|
||||
|
||||
test('ordinary values keep their existing format', () => {
|
||||
assert.equal(toDMS(38.889722, 'lat'), `38°53'23.00"N`);
|
||||
assert.equal(toDMS(-77.035278, 'lon'), `077°02'07.00"W`);
|
||||
assert.equal(toDMS(51.5, 'lat'), `51°30'00.00"N`);
|
||||
assert.equal(toDMS(-33.8568, 'lat'), `33°51'24.48"S`);
|
||||
assert.equal(toDMS(0, 'lon'), `000°00'00.00"E`);
|
||||
assert.equal(toDMS(90, 'lat'), `90°00'00.00"N`);
|
||||
});
|
||||
|
||||
test('the telemetry tick paints the carried value into both readouts', () => {
|
||||
const elements = new Map(
|
||||
[
|
||||
'hud-alt',
|
||||
'hud-summary',
|
||||
'hud-mgrs',
|
||||
'hud-latlon',
|
||||
'hud-bottom-line',
|
||||
'hud-gsd',
|
||||
'hud-coll',
|
||||
'hud-ona',
|
||||
'hud-mode',
|
||||
].map((id) => [id, { textContent: '' }]),
|
||||
);
|
||||
const previousDocument = globalThis.document;
|
||||
globalThis.document = {
|
||||
getElementById: (id) => elements.get(id) ?? null,
|
||||
querySelectorAll: () => [],
|
||||
addEventListener() {},
|
||||
removeEventListener() {},
|
||||
};
|
||||
const viewer = {
|
||||
camera: {
|
||||
pitch: -Math.PI / 2,
|
||||
positionCartographic: {
|
||||
latitude: (37.75 * Math.PI) / 180,
|
||||
longitude: (-122.35 * Math.PI) / 180,
|
||||
height: 1500,
|
||||
},
|
||||
computeViewRectangle: () => undefined,
|
||||
moveStart: { addEventListener() {}, removeEventListener() {} },
|
||||
moveEnd: { addEventListener() {}, removeEventListener() {} },
|
||||
},
|
||||
};
|
||||
let hud;
|
||||
try {
|
||||
hud = new IntelHUD(viewer);
|
||||
hud._updateCameraData();
|
||||
const latlon = elements.get('hud-latlon').textContent;
|
||||
const bottom = elements.get('hud-bottom-line').textContent;
|
||||
assert.equal(latlon, `37°45'00.00"N 122°21'00.00"W`);
|
||||
assert.match(bottom, /LON: 122°21'00\.00"W/);
|
||||
assert.doesNotMatch(`${latlon} ${bottom}`, /60\.00"/);
|
||||
} finally {
|
||||
hud?.destroy();
|
||||
if (previousDocument === undefined) delete globalThis.document;
|
||||
else globalThis.document = previousDocument;
|
||||
}
|
||||
});
|
||||
@@ -16,7 +16,8 @@ export function hudQuantity(value, unit, digits = 0) {
|
||||
maximumFractionDigits: digits,
|
||||
});
|
||||
const label = unitLabel(unit);
|
||||
if (getLocale() === 'zh-CN') return label ? `${number} ${label}` : number;
|
||||
if (getLocale().startsWith('zh-'))
|
||||
return label ? `${number} ${label}` : number;
|
||||
return `${number}${label.toUpperCase()}`;
|
||||
}
|
||||
|
||||
|
||||
@@ -5,12 +5,12 @@ import { createModel } from '../layers/firms/model.js';
|
||||
import { createQueries } from '../layers/firms/queries.js';
|
||||
|
||||
const cases = [
|
||||
[0, '不到 1 分钟前', '<1m ago'],
|
||||
[120000, '2 分钟前', '2m ago'],
|
||||
[7200000, '2 小时前', '2h ago'],
|
||||
[0, '不到 1 分钟前', '<1m ago', '不到 1 分鐘前'],
|
||||
[120000, '2 分钟前', '2m ago', '2 分鐘前'],
|
||||
[7200000, '2 小时前', '2h ago', '2 小時前'],
|
||||
];
|
||||
|
||||
for (const [age, zh, en] of cases) {
|
||||
for (const [age, zh, en, hant] of cases) {
|
||||
test(`FIRMS live age ${age} ms has one relative-time suffix`, (context) => {
|
||||
const now = 1800000000000;
|
||||
context.mock.method(Date, 'now', () => now);
|
||||
@@ -36,6 +36,8 @@ for (const [age, zh, en] of cases) {
|
||||
assert.equal(methods.getStats().loadingLabel, `LIVE · updated ${en}`);
|
||||
setLocale('zh-CN');
|
||||
assert.equal(methods.getStats().loadingLabel, `实时 · 更新于 ${zh}`);
|
||||
setLocale('zh-Hant');
|
||||
assert.equal(methods.getStats().loadingLabel, `實時 · 更新於 ${hant}`);
|
||||
} finally {
|
||||
setLocale(previousLocale);
|
||||
}
|
||||
|
||||
@@ -35,12 +35,18 @@ test('normalizeLocale folds regional variants and rejects unshipped tags', () =>
|
||||
assert.equal(normalizeLocale(' RU '), 'ru');
|
||||
assert.equal(normalizeLocale('en_GB'), 'en');
|
||||
assert.equal(normalizeLocale('xx'), null);
|
||||
// Simplified Chinese by default; Traditional tags wait for zh-TW.
|
||||
// Explicit script tags take precedence over regional defaults.
|
||||
assert.equal(normalizeLocale('zh'), 'zh-CN');
|
||||
assert.equal(normalizeLocale('zh-CN'), 'zh-CN');
|
||||
assert.equal(normalizeLocale('zh-Hans-SG'), 'zh-CN');
|
||||
assert.equal(normalizeLocale('zh-TW'), null);
|
||||
assert.equal(normalizeLocale('zh-Hant-HK'), null);
|
||||
assert.equal(normalizeLocale('zh-Hant'), 'zh-Hant');
|
||||
assert.equal(normalizeLocale(' ZH_hant '), 'zh-Hant');
|
||||
assert.equal(normalizeLocale('zh-TW'), 'zh-Hant');
|
||||
assert.equal(normalizeLocale('zh-Hant-HK'), 'zh-Hant');
|
||||
assert.equal(normalizeLocale('zh-Hans-HK'), 'zh-CN');
|
||||
assert.equal(normalizeLocale('zh-Hant-CN'), 'zh-Hant');
|
||||
assert.equal(normalizeLocale('zh_HK'), 'zh-Hant');
|
||||
assert.equal(normalizeLocale('zh-MO'), 'zh-Hant');
|
||||
assert.equal(normalizeLocale(undefined), null);
|
||||
});
|
||||
|
||||
|
||||
+2
-1
@@ -19,8 +19,9 @@ import {
|
||||
import es from './locales/es.json' with { type: 'json' };
|
||||
import ru from './locales/ru.json' with { type: 'json' };
|
||||
import zhCN from './locales/zh-CN.json' with { type: 'json' };
|
||||
import zhHant from './locales/zh-Hant.json' with { type: 'json' };
|
||||
|
||||
const CATALOGS = Object.freeze({ es, ru, 'zh-CN': zhCN });
|
||||
const CATALOGS = Object.freeze({ es, ru, 'zh-CN': zhCN, 'zh-Hant': zhHant });
|
||||
|
||||
let currentLocale = DEFAULT_LOCALE;
|
||||
|
||||
|
||||
+9
-6
@@ -8,14 +8,15 @@ export const LOCALE_STORAGE_KEY = 'gev:locale:v1';
|
||||
export const DEFAULT_LOCALE = 'en';
|
||||
|
||||
/** Shipped locales; order does not matter. Adding one: docs/TRANSLATORS.md. */
|
||||
export const LOCALES = Object.freeze(['en', 'es', 'ru', 'zh-CN']);
|
||||
export const LOCALES = Object.freeze(['en', 'es', 'ru', 'zh-CN', 'zh-Hant']);
|
||||
|
||||
/** Each locale named in its own language, for the selector. */
|
||||
export const LOCALE_NAMES = Object.freeze({
|
||||
en: 'English',
|
||||
es: 'Español',
|
||||
ru: 'Русский',
|
||||
'zh-CN': '简体中文',
|
||||
'zh-CN': '中文(简体)',
|
||||
'zh-Hant': '中文(繁體)',
|
||||
});
|
||||
|
||||
/** Right-to-left locales. */
|
||||
@@ -23,17 +24,19 @@ const RTL_LOCALES = Object.freeze([]);
|
||||
|
||||
/**
|
||||
* Map any language tag to a shipped locale: 'ru-RU' and 'RU' → 'ru',
|
||||
* 'zh', 'zh-CN' and 'zh-Hans-SG' → 'zh-CN'.
|
||||
* 'zh', 'zh-CN' and 'zh-Hans-SG' → 'zh-CN';
|
||||
* 'zh-Hant', 'zh-TW', 'zh-HK' and 'zh-MO' → 'zh-Hant'.
|
||||
* @returns {string|null}
|
||||
*/
|
||||
export function normalizeLocale(candidate) {
|
||||
if (typeof candidate !== 'string') return null;
|
||||
const [primary, ...rest] = candidate.trim().toLowerCase().split(/[-_]/);
|
||||
// Traditional Chinese readers are not given Simplified: no zh-TW yet.
|
||||
if (primary === 'zh')
|
||||
if (primary === 'zh') {
|
||||
if (rest.includes('hans')) return 'zh-CN';
|
||||
return rest.some((part) => ['hant', 'tw', 'hk', 'mo'].includes(part))
|
||||
? null
|
||||
? 'zh-Hant'
|
||||
: 'zh-CN';
|
||||
}
|
||||
return LOCALES.includes(primary) ? primary : null;
|
||||
}
|
||||
|
||||
|
||||
@@ -302,9 +302,16 @@
|
||||
"CLOUD UNKNOWN": "NUBES DESCONOCIDAS",
|
||||
"Panel layout updated — positions reset to new defaults": "Disposición de paneles actualizada — posiciones restablecidas a los nuevos valores predeterminados",
|
||||
"Link copied!": "¡Enlace copiado!",
|
||||
"Link shared": "Enlace compartido",
|
||||
"This share link can't be opened": "Este enlace compartido no se puede abrir",
|
||||
"{id} isn't reporting now — showing where it was at {time}": "{id} no está transmitiendo ahora; se muestra dónde estaba a las {time}",
|
||||
"{id} isn't reporting now — showing where it was last seen": "{id} no está transmitiendo ahora; se muestra dónde se vio por última vez",
|
||||
"Shared vessel is unavailable": "El buque compartido no está disponible",
|
||||
"Copy failed": "No se pudo copiar",
|
||||
"Location not found": "Ubicación no encontrada",
|
||||
"Search failed": "No se pudo completar la búsqueda",
|
||||
"Check the spelling and press Enter to search again.": "Revisa la ortografía y pulsa Intro para buscar de nuevo.",
|
||||
"Press Enter to try again.": "Pulsa Intro para intentarlo de nuevo.",
|
||||
"Fly to a POI first": "Ve primero a un punto de interés",
|
||||
"Clearing selected data layers": "Limpiando las capas de datos seleccionadas",
|
||||
"Selected data layers could not be cleared": "No se pudieron limpiar las capas de datos seleccionadas",
|
||||
@@ -1153,6 +1160,7 @@
|
||||
"OpenStreetMap · community mapped": "OpenStreetMap · mapeado por la comunidad",
|
||||
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "Atlántico y Pacífico Norte oriental/central; no es una cobertura mundial de ciclones.",
|
||||
"Potential tropical cyclone": "Posible ciclón tropical",
|
||||
"Post-tropical cyclone": "Ciclón postropical",
|
||||
"Hurricane": "Huracán",
|
||||
"Tropical storm": "Tormenta tropical",
|
||||
"Tropical depression": "Depresión tropical",
|
||||
@@ -1866,11 +1874,15 @@
|
||||
"maneuver|Merge": "Incorpórate",
|
||||
"Merge onto {road}": "Incorpórate a {road}",
|
||||
"Take the ramp on the {direction}": "Toma la rampa {direction}",
|
||||
"Take the ramp {direction}": "Toma la rampa {direction}",
|
||||
"Take the ramp on the {direction} onto {road}": "Toma la rampa {direction} hacia {road}",
|
||||
"Take the ramp {direction} onto {road}": "Toma la rampa {direction} hacia {road}",
|
||||
"Take the ramp": "Toma la rampa",
|
||||
"Take the ramp onto {road}": "Toma la rampa hacia {road}",
|
||||
"Take the exit on the {direction}": "Toma la salida {direction}",
|
||||
"Take the exit {direction}": "Toma la salida {direction}",
|
||||
"Take the exit on the {direction} onto {road}": "Toma la salida {direction} hacia {road}",
|
||||
"Take the exit {direction} onto {road}": "Toma la salida {direction} hacia {road}",
|
||||
"Take the exit": "Toma la salida",
|
||||
"Take the exit onto {road}": "Toma la salida hacia {road}",
|
||||
"At the roundabout, take the {exit} exit": "En la rotonda, toma la {exit} salida",
|
||||
@@ -2937,6 +2949,34 @@
|
||||
"Gemini Live is unavailable for the configured model.": "Gemini Live no está disponible para el modelo configurado.",
|
||||
"Token request is too large": "La solicitud de credencial es demasiado grande",
|
||||
"Use an empty JSON token request": "Usa una solicitud de credencial con un objeto JSON vacío",
|
||||
"S2 GhostMaps": "S2 GhostMaps",
|
||||
"Intel Picture": "Panorama de inteligencia",
|
||||
"Kinetic 30d": "Cinético 30 d",
|
||||
"Border Crisis": "Crisis fronteriza",
|
||||
"Iran Picture": "Panorama de Irán",
|
||||
"Iran Kinetic": "Irán cinético",
|
||||
"Yemen FLOT": "FLOT de Yemen",
|
||||
"Latest Drop": "Última publicación",
|
||||
"GhostMaps file could not be read": "No se pudo leer el archivo de GhostMaps",
|
||||
"GhostMaps catalog unavailable": "Catálogo de GhostMaps no disponible",
|
||||
"Malformed GhostMaps catalog": "Catálogo de GhostMaps mal formado",
|
||||
"{count} source links ↗ · click card to open the first": {
|
||||
"one": "{count} enlace a la fuente ↗ · haz clic en la tarjeta para abrirlo",
|
||||
"many": "{count} de enlaces a fuentes ↗ · haz clic en la tarjeta para abrir el primero",
|
||||
"other": "{count} enlaces a fuentes ↗ · haz clic en la tarjeta para abrir el primero"
|
||||
},
|
||||
"S2 · {name}": "S2 · {name}",
|
||||
"Report": "Informe",
|
||||
"Open the source for {title}": "Abrir la fuente de {title}",
|
||||
"LIVE · GitHub {commit} · {message} · checked every {seconds}s": "EN VIVO · GitHub {commit} · {message} · comprobado cada {seconds} s",
|
||||
"GitHub {commit} · {message} · reconnecting for live updates": "GitHub {commit} · {message} · reconectando para recibir actualizaciones en vivo",
|
||||
"Connecting to the S2 GhostMaps repository…": "Conectando con el repositorio S2 GhostMaps…",
|
||||
"{count} placemarks": {
|
||||
"one": "{count} marcador",
|
||||
"many": "{count} de marcadores",
|
||||
"other": "{count} marcadores"
|
||||
},
|
||||
"S2 Underground publishes these KMZ products to GitHub. New uploads are detected within seconds and replace the previous edition automatically. Click a marker for its report.": "S2 Underground publica estos productos KMZ en GitHub. Las nuevas publicaciones se detectan en segundos y sustituyen automáticamente a la edición anterior. Haz clic en un marcador para ver su informe.",
|
||||
" Clouds are preserved from the source imagery.": " Las nubes provienen de las imágenes de origen.",
|
||||
"hemisphere|N": "N",
|
||||
"hemisphere|S": "S",
|
||||
@@ -2947,5 +2987,21 @@
|
||||
"Layers": "Capas",
|
||||
"Search": "Buscar",
|
||||
"More": "Más",
|
||||
"Panels": "Paneles"
|
||||
"Panels": "Paneles",
|
||||
"Recent speech": "Habla reciente",
|
||||
"Voice Settings": "Ajustes de voz",
|
||||
"Preview": "Vista previa",
|
||||
"Settings": "Ajustes",
|
||||
"Close voice panel": "Cerrar panel de voz",
|
||||
"Show Voice Preview": "Mostrar vista previa de voz",
|
||||
"Voice inactivity timeout": "Tiempo de inactividad de voz",
|
||||
"Custom": "Personalizado",
|
||||
"Minutes": "Minutos",
|
||||
"These preferences stay in this browser.": "Estas preferencias se guardan en este navegador.",
|
||||
"Your choice applies now, but could not be saved.": "Tu elección se aplica ahora, pero no se pudo guardar.",
|
||||
"Voice replies appear here.": "Las respuestas de voz aparecen aquí.",
|
||||
"Preview is off.": "La vista previa está desactivada.",
|
||||
"Automatic stop is unavailable for this voice connection.": "La parada automática no está disponible para esta conexión de voz.",
|
||||
"routing busy — too many routes at once": "servicio de rutas ocupado: demasiadas rutas a la vez",
|
||||
"route proxy error": "error del proxy de rutas"
|
||||
}
|
||||
@@ -294,6 +294,11 @@
|
||||
"Scene run complete": "Воспроизведение сцены завершено",
|
||||
"CCTV layer unavailable": "Слой CCTV недоступен",
|
||||
"Link copied!": "Ссылка скопирована!",
|
||||
"Link shared": "Ссылка отправлена",
|
||||
"This share link can't be opened": "Не удаётся открыть эту ссылку",
|
||||
"{id} isn't reporting now — showing where it was at {time}": "{id} сейчас не передаёт данные — показано последнее известное место ({time})",
|
||||
"{id} isn't reporting now — showing where it was last seen": "{id} сейчас не передаёт данные — показано последнее известное место",
|
||||
"Shared vessel is unavailable": "Судно по ссылке недоступно",
|
||||
"Copy failed": "Не удалось скопировать",
|
||||
"VISUAL PRESETS": "ПРЕСЕТЫ",
|
||||
"LOCATION": "МЕСТО",
|
||||
@@ -525,6 +530,8 @@
|
||||
"Resetting cockpit to full globe view": "Сброс кабины к виду всего глобуса",
|
||||
"Location not found": "Место не найдено",
|
||||
"Search failed": "Не удалось выполнить поиск",
|
||||
"Check the spelling and press Enter to search again.": "Проверьте написание и нажмите Enter, чтобы повторить поиск.",
|
||||
"Press Enter to try again.": "Нажмите Enter, чтобы попробовать снова.",
|
||||
"MAP": "КАРТА",
|
||||
"panel": "панель",
|
||||
"Expand {name}": "Развернуть {name}",
|
||||
@@ -1169,6 +1176,7 @@
|
||||
"OpenStreetMap · community mapped": "OpenStreetMap · данные сообщества",
|
||||
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "Атлантика и восточная/центральная часть северного Тихого океана; покрытие циклонов не глобальное.",
|
||||
"Potential tropical cyclone": "Потенциальный тропический циклон",
|
||||
"Post-tropical cyclone": "Посттропический циклон",
|
||||
"Hurricane": "Ураган",
|
||||
"Tropical storm": "Тропический шторм",
|
||||
"Tropical depression": "Тропическая депрессия",
|
||||
@@ -1898,11 +1906,15 @@
|
||||
"maneuver|Merge": "Перестройтесь",
|
||||
"Merge onto {road}": "Въезжайте на {road}",
|
||||
"Take the ramp on the {direction}": "Въезжайте на съезд {direction}",
|
||||
"Take the ramp {direction}": "Въезжайте на съезд {direction}",
|
||||
"Take the ramp on the {direction} onto {road}": "Въезжайте по съезду {direction} на {road}",
|
||||
"Take the ramp {direction} onto {road}": "Въезжайте по съезду {direction} на {road}",
|
||||
"Take the ramp": "Въезжайте на съезд",
|
||||
"Take the ramp onto {road}": "Въезжайте по съезду на {road}",
|
||||
"Take the exit on the {direction}": "Сверните на съезд {direction}",
|
||||
"Take the exit {direction}": "Сверните на съезд {direction}",
|
||||
"Take the exit on the {direction} onto {road}": "Сверните на съезд {direction} на {road}",
|
||||
"Take the exit {direction} onto {road}": "Сверните на съезд {direction} на {road}",
|
||||
"Take the exit": "Сверните на съезд",
|
||||
"Take the exit onto {road}": "Сверните на съезд на {road}",
|
||||
"At the roundabout, take the {exit} exit": "На кольце сверните на {exit} съезд",
|
||||
@@ -3004,6 +3016,36 @@
|
||||
"Gemini Live is unavailable for the configured model.": "Gemini Live недоступен для выбранной модели.",
|
||||
"Token request is too large": "Запрос токена слишком велик",
|
||||
"Use an empty JSON token request": "Используйте запрос токена с пустым объектом JSON",
|
||||
"S2 GhostMaps": "S2 GhostMaps",
|
||||
"Intel Picture": "Разведкартина",
|
||||
"Kinetic 30d": "Боевые 30 дн.",
|
||||
"Border Crisis": "Кризис на границе",
|
||||
"Iran Picture": "Иран: картина",
|
||||
"Iran Kinetic": "Иран: боевые",
|
||||
"Yemen FLOT": "Йемен: линия фронта",
|
||||
"Latest Drop": "Новый выпуск",
|
||||
"GhostMaps file could not be read": "Не удалось прочитать файл GhostMaps",
|
||||
"GhostMaps catalog unavailable": "Каталог GhostMaps недоступен",
|
||||
"Malformed GhostMaps catalog": "Повреждённый каталог GhostMaps",
|
||||
"{count} source links ↗ · click card to open the first": {
|
||||
"one": "{count} ссылка на источник ↗ · нажмите на карточку, чтобы открыть",
|
||||
"few": "{count} ссылки на источники ↗ · нажмите на карточку, чтобы открыть первую",
|
||||
"many": "{count} ссылок на источники ↗ · нажмите на карточку, чтобы открыть первую",
|
||||
"other": "{count} ссылки на источники ↗ · нажмите на карточку, чтобы открыть первую"
|
||||
},
|
||||
"S2 · {name}": "S2 · {name}",
|
||||
"Report": "Сводка",
|
||||
"Open the source for {title}": "Открыть источник: {title}",
|
||||
"LIVE · GitHub {commit} · {message} · checked every {seconds}s": "В ЭФИРЕ · GitHub {commit} · {message} · проверка каждые {seconds} с",
|
||||
"GitHub {commit} · {message} · reconnecting for live updates": "GitHub {commit} · {message} · переподключение для обновлений в реальном времени",
|
||||
"Connecting to the S2 GhostMaps repository…": "Подключение к репозиторию S2 GhostMaps…",
|
||||
"{count} placemarks": {
|
||||
"one": "{count} метка",
|
||||
"few": "{count} метки",
|
||||
"many": "{count} меток",
|
||||
"other": "{count} метки"
|
||||
},
|
||||
"S2 Underground publishes these KMZ products to GitHub. New uploads are detected within seconds and replace the previous edition automatically. Click a marker for its report.": "S2 Underground публикует эти продукты KMZ на GitHub. Новые файлы обнаруживаются за секунды и автоматически заменяют предыдущий выпуск. Нажмите на метку, чтобы открыть её сводку.",
|
||||
" Clouds are preserved from the source imagery.": " Облака оставлены такими, как на исходных снимках.",
|
||||
"hemisphere|N": "С",
|
||||
"hemisphere|S": "Ю",
|
||||
@@ -3014,5 +3056,21 @@
|
||||
"Layers": "Слои",
|
||||
"Search": "Поиск",
|
||||
"More": "Ещё",
|
||||
"Panels": "Панели"
|
||||
"Panels": "Панели",
|
||||
"Recent speech": "Недавняя речь",
|
||||
"Voice Settings": "Настройки голоса",
|
||||
"Preview": "Предпросмотр",
|
||||
"Settings": "Настройки",
|
||||
"Close voice panel": "Закрыть голосовую панель",
|
||||
"Show Voice Preview": "Показывать предпросмотр голоса",
|
||||
"Voice inactivity timeout": "Тайм-аут бездействия голоса",
|
||||
"Custom": "Другое",
|
||||
"Minutes": "Минуты",
|
||||
"These preferences stay in this browser.": "Эти настройки сохраняются в этом браузере.",
|
||||
"Your choice applies now, but could not be saved.": "Ваш выбор применён, но сохранить его не удалось.",
|
||||
"Voice replies appear here.": "Здесь появляются голосовые ответы.",
|
||||
"Preview is off.": "Предпросмотр отключён.",
|
||||
"Automatic stop is unavailable for this voice connection.": "Автоматическая остановка недоступна для этого голосового подключения.",
|
||||
"routing busy — too many routes at once": "сервис маршрутов занят: слишком много маршрутов одновременно",
|
||||
"route proxy error": "ошибка прокси маршрутов"
|
||||
}
|
||||
@@ -530,6 +530,7 @@
|
||||
"Cyclone advisories unavailable": "气旋公告不可用",
|
||||
"Cyclone data unavailable": "气旋数据不可用",
|
||||
"Potential tropical cyclone": "潜在热带气旋",
|
||||
"Post-tropical cyclone": "后热带气旋",
|
||||
"Hurricane": "飓风",
|
||||
"Tropical storm": "热带风暴",
|
||||
"Tropical depression": "热带低压",
|
||||
@@ -625,11 +626,15 @@
|
||||
"Merge onto {road}": "并入 {road}",
|
||||
"maneuver|Merge": "并道",
|
||||
"Take the ramp on the {direction} onto {road}": "{direction}驶入匝道,进入 {road}",
|
||||
"Take the ramp {direction} onto {road}": "{direction}驶入匝道,进入 {road}",
|
||||
"Take the ramp on the {direction}": "{direction}驶入匝道",
|
||||
"Take the ramp {direction}": "{direction}驶入匝道",
|
||||
"Take the ramp onto {road}": "驶入匝道,进入 {road}",
|
||||
"Take the ramp": "驶入匝道",
|
||||
"Take the exit on the {direction} onto {road}": "从出口{direction}驶出,进入 {road}",
|
||||
"Take the exit {direction} onto {road}": "从出口{direction}驶出,进入 {road}",
|
||||
"Take the exit on the {direction}": "从出口{direction}驶出",
|
||||
"Take the exit {direction}": "从出口{direction}驶出",
|
||||
"Take the exit onto {road}": "从出口驶出,进入 {road}",
|
||||
"Take the exit": "从出口驶出",
|
||||
"At the roundabout, take the {exit} exit onto {road}": "在环岛从{exit}出口驶出,进入 {road}",
|
||||
@@ -1472,6 +1477,11 @@
|
||||
"LIVE SIGNALS": "实时信号",
|
||||
"CCTV layer unavailable": "CCTV 图层不可用",
|
||||
"Link copied!": "链接已复制!",
|
||||
"Link shared": "链接已分享",
|
||||
"This share link can't be opened": "无法打开此分享链接",
|
||||
"{id} isn't reporting now — showing where it was at {time}": "{id} 目前没有发送信号——显示其在 {time} 的位置",
|
||||
"{id} isn't reporting now — showing where it was last seen": "{id} 目前没有发送信号——显示其最后出现的位置",
|
||||
"Shared vessel is unavailable": "分享的船只不可用",
|
||||
"Copy failed": "复制失败",
|
||||
"Return map to straight-down view": "将地图恢复为垂直俯视",
|
||||
"Tilt map to oblique view": "将地图倾斜至斜视角",
|
||||
@@ -1809,6 +1819,8 @@
|
||||
"ORBIT": "环绕",
|
||||
"Location not found": "未找到位置",
|
||||
"Search failed": "搜索失败",
|
||||
"Check the spelling and press Enter to search again.": "请检查拼写,然后按 Enter 重新搜索。",
|
||||
"Press Enter to try again.": "按 Enter 重试。",
|
||||
"Detailed outline unavailable": "无法获取详细轮廓",
|
||||
"Fly to a POI first": "请先飞往一个 POI",
|
||||
"Reset to full globe view": "重置为完整地球视图",
|
||||
@@ -2813,5 +2825,45 @@
|
||||
"Layers": "图层",
|
||||
"Search": "搜索",
|
||||
"More": "更多",
|
||||
"Panels": "面板"
|
||||
"Panels": "面板",
|
||||
"Recent speech": "最近语音",
|
||||
"Voice Settings": "语音设置",
|
||||
"Preview": "预览",
|
||||
"Settings": "设置",
|
||||
"Close voice panel": "关闭语音面板",
|
||||
"Show Voice Preview": "显示语音预览",
|
||||
"Voice inactivity timeout": "语音空闲超时",
|
||||
"Custom": "自定义",
|
||||
"Minutes": "分钟",
|
||||
"These preferences stay in this browser.": "这些偏好设置仅保存在此浏览器中。",
|
||||
"Your choice applies now, but could not be saved.": "选择已生效,但无法保存。",
|
||||
"Voice replies appear here.": "语音回复显示在此处。",
|
||||
"Preview is off.": "预览已关闭。",
|
||||
"Automatic stop is unavailable for this voice connection.": "此语音连接不支持自动停止。",
|
||||
"S2 GhostMaps": "S2 GhostMaps",
|
||||
"Intel Picture": "情报态势图",
|
||||
"Kinetic 30d": "近 30 天军事行动",
|
||||
"Border Crisis": "边境危机",
|
||||
"Iran Picture": "伊朗态势图",
|
||||
"Iran Kinetic": "伊朗军事行动",
|
||||
"Yemen FLOT": "也门前线",
|
||||
"Latest Drop": "最新发布",
|
||||
"GhostMaps file could not be read": "无法读取 GhostMaps 文件",
|
||||
"GhostMaps catalog unavailable": "GhostMaps 目录不可用",
|
||||
"Malformed GhostMaps catalog": "GhostMaps 目录格式无效",
|
||||
"{count} source links ↗ · click card to open the first": {
|
||||
"other": "{count} 个来源链接 ↗ · 点击卡片打开第一个"
|
||||
},
|
||||
"S2 · {name}": "S2 · {name}",
|
||||
"Report": "报告",
|
||||
"Open the source for {title}": "打开 {title} 的来源",
|
||||
"LIVE · GitHub {commit} · {message} · checked every {seconds}s": "实时 · GitHub {commit} · {message} · 每 {seconds} 秒检查一次",
|
||||
"GitHub {commit} · {message} · reconnecting for live updates": "GitHub {commit} · {message} · 正在重新连接以获取实时更新",
|
||||
"Connecting to the S2 GhostMaps repository…": "正在连接 S2 GhostMaps 仓库…",
|
||||
"{count} placemarks": {
|
||||
"other": "{count} 个地标"
|
||||
},
|
||||
"S2 Underground publishes these KMZ products to GitHub. New uploads are detected within seconds and replace the previous edition automatically. Click a marker for its report.": "S2 Underground 在 GitHub 发布这些 KMZ 产品。新上传的内容会在数秒内被检测到,并自动替换旧版本。点击标记查看报告。",
|
||||
"routing busy — too many routes at once": "路线服务繁忙:同时请求的路线过多",
|
||||
"route proxy error": "路线代理出错"
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -75,6 +75,8 @@
|
||||
"Radio",
|
||||
"Reggae",
|
||||
"Rock",
|
||||
"S2 GhostMaps",
|
||||
"S2 · {name}",
|
||||
"SAR",
|
||||
"SE",
|
||||
"SECTOR {lat} {lon}",
|
||||
@@ -135,6 +137,8 @@
|
||||
"NVG",
|
||||
"R&B",
|
||||
"REC",
|
||||
"S2 GhostMaps",
|
||||
"S2 · {name}",
|
||||
"VS",
|
||||
"WHOT/BHOT"
|
||||
],
|
||||
@@ -165,6 +169,65 @@
|
||||
"NVG",
|
||||
"REC",
|
||||
"SRC {value}",
|
||||
"S2 GhostMaps",
|
||||
"S2 · {name}",
|
||||
"Sentinel-2",
|
||||
"Techno",
|
||||
"Trance",
|
||||
"USB {rate} msg/s",
|
||||
"WHOT/BHOT",
|
||||
"dB",
|
||||
"ft",
|
||||
"hPa",
|
||||
"hemisphere|E",
|
||||
"hemisphere|N",
|
||||
"hemisphere|S",
|
||||
"hemisphere|W",
|
||||
"km",
|
||||
"km/h",
|
||||
"kt",
|
||||
"kts",
|
||||
"mph",
|
||||
"{city} CCTV",
|
||||
"{rate} msg/s",
|
||||
"{source} HTTP {status}",
|
||||
"{speed} kn",
|
||||
"{type} SPD: {speed} HDG: {heading}",
|
||||
"{value} KM",
|
||||
"{value} KM/S",
|
||||
"ΔE",
|
||||
"ΔN",
|
||||
"▲ {frp} MW"
|
||||
],
|
||||
"zh-Hant": [
|
||||
"1090 MHz",
|
||||
"978 MHz UAT",
|
||||
"AIS: --",
|
||||
"AIS: {name}",
|
||||
"BRG {value}°",
|
||||
"BRG —",
|
||||
"CAL {value}",
|
||||
"CAL · {badge}",
|
||||
"CCTV",
|
||||
"CRS {value}°",
|
||||
"CRT",
|
||||
"FLIR",
|
||||
"FOV",
|
||||
"FOV {value}°",
|
||||
"FT",
|
||||
"GEO",
|
||||
"HDG",
|
||||
"HDG {value}°",
|
||||
"House",
|
||||
"Ironbow",
|
||||
"KTS",
|
||||
"Landsat 8/9",
|
||||
"MM",
|
||||
"NVG",
|
||||
"REC",
|
||||
"SRC {value}",
|
||||
"S2 GhostMaps",
|
||||
"S2 · {name}",
|
||||
"Sentinel-2",
|
||||
"Techno",
|
||||
"Trance",
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { setLocale, t, tn, getLocale } from './index.js';
|
||||
import {
|
||||
resolveLocale,
|
||||
LOCALE_STORAGE_KEY,
|
||||
writeStoredLocale,
|
||||
applyDocumentLanguage,
|
||||
} from './locale.js';
|
||||
import { hudQuantity, LOCALIZED_LOCALITY } from '../hudLocalityFormat.js';
|
||||
import { formatCockpitDistance } from '../ui/cockpitPresentation.js';
|
||||
import { READOUT_WORDS } from '../layers/recentImagery/display.js';
|
||||
import { cctvSourceStatusLabel } from '../ui/cctvFrames.js';
|
||||
|
||||
test('Traditional Chinese resolves from URL, saved preference and browser language', () => {
|
||||
assert.equal(
|
||||
resolveLocale({
|
||||
location: { search: '?lang=zh-TW' },
|
||||
storage: { getItem: () => 'en' },
|
||||
languages: ['en'],
|
||||
}),
|
||||
'zh-Hant',
|
||||
);
|
||||
assert.equal(
|
||||
resolveLocale({
|
||||
location: { search: '' },
|
||||
storage: {
|
||||
getItem: (key) => (key === LOCALE_STORAGE_KEY ? 'zh-TW' : null),
|
||||
},
|
||||
languages: ['en'],
|
||||
}),
|
||||
'zh-Hant',
|
||||
);
|
||||
assert.equal(
|
||||
resolveLocale({
|
||||
location: { search: '' },
|
||||
storage: { getItem: () => null },
|
||||
languages: ['zh-Hant', 'en'],
|
||||
}),
|
||||
'zh-Hant',
|
||||
);
|
||||
});
|
||||
|
||||
test('Traditional Chinese persists and exposes the script locale for legacy choices', () => {
|
||||
const stored = new Map();
|
||||
assert.equal(
|
||||
writeStoredLocale('zh-TW', {
|
||||
setItem: (key, value) => stored.set(key, value),
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(stored.get(LOCALE_STORAGE_KEY), 'zh-Hant');
|
||||
const doc = { documentElement: {} };
|
||||
assert.equal(applyDocumentLanguage(doc, 'zh-TW'), true);
|
||||
assert.equal(doc.documentElement.lang, 'zh-Hant');
|
||||
assert.equal(doc.documentElement.dir, 'ltr');
|
||||
});
|
||||
|
||||
test('Traditional Chinese readouts preserve unit case, coordinates and natural relative dates', () => {
|
||||
const previous = getLocale();
|
||||
try {
|
||||
setLocale('zh-Hant');
|
||||
assert.equal(hudQuantity(2069, 'km', 1), '2069.0 km');
|
||||
assert.equal(formatCockpitDistance(14000), '14\u00a0km');
|
||||
assert.equal(
|
||||
LOCALIZED_LOCALITY.sector({ latDeg: 21.33, lonDeg: -77.5 }),
|
||||
'扇區 21.33N 77.50W',
|
||||
);
|
||||
assert.equal(READOUT_WORDS.daysAgo(9), '9 天前');
|
||||
assert.equal(READOUT_WORDS.daysAgo(0), '今天');
|
||||
assert.equal(cctvSourceStatusLabel('ok'), '正常');
|
||||
assert.equal(t('SAVE KEYS'), '保存密鑰');
|
||||
assert.equal(
|
||||
tn(2, 'Click {count} more point.', 'Click {count} more points.'),
|
||||
'再點擊 2 個點。',
|
||||
);
|
||||
} finally {
|
||||
setLocale(previous);
|
||||
}
|
||||
});
|
||||
@@ -395,6 +395,7 @@ export async function initKeySetup({
|
||||
const destroy = () => {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
delete root.dataset.ready;
|
||||
unregisterUnsavedWork();
|
||||
lifetime.abort();
|
||||
signal?.removeEventListener('abort', destroy);
|
||||
@@ -591,6 +592,7 @@ export async function initKeySetup({
|
||||
chip.addEventListener('click', openDialog);
|
||||
closeButton?.addEventListener('click', close);
|
||||
applyButton?.addEventListener('click', onApply);
|
||||
root.dataset.ready = 'true';
|
||||
// Remove buttons are rendered per row; delegate so re-renders stay wired.
|
||||
rowsHost?.addEventListener('click', (event) => {
|
||||
const authButton = event.target?.closest?.(
|
||||
|
||||
+20
-5
@@ -206,12 +206,27 @@ export function photonSearchUrl(
|
||||
url.searchParams.set('limit', String(limit));
|
||||
|
||||
const corners = String(bias ?? '').split('|');
|
||||
if (corners.length === 2) {
|
||||
const [swLat, swLng] = corners[0].split(',').map(Number);
|
||||
const [neLat, neLng] = corners[1].split(',').map(Number);
|
||||
if ([swLat, swLng, neLat, neLng].every(Number.isFinite)) {
|
||||
const tokens = corners.flatMap((corner) => corner.split(','));
|
||||
if (
|
||||
corners.length === 2 &&
|
||||
corners.every((corner) => corner.split(',').length === 2) &&
|
||||
tokens.every((token) => token.trim() !== '')
|
||||
) {
|
||||
const [swLat, swLng, neLat, neLng] = tokens.map(Number);
|
||||
if (
|
||||
[swLat, swLng, neLat, neLng].every(Number.isFinite) &&
|
||||
Math.abs(swLat) <= 90 &&
|
||||
Math.abs(neLat) <= 90 &&
|
||||
swLat <= neLat &&
|
||||
Math.abs(swLng) <= 180 &&
|
||||
Math.abs(neLng) <= 180
|
||||
) {
|
||||
const midpoint = (swLng + neLng + (swLng > neLng ? 360 : 0)) / 2;
|
||||
url.searchParams.set('lat', String((swLat + neLat) / 2));
|
||||
url.searchParams.set('lon', String((swLng + neLng) / 2));
|
||||
url.searchParams.set(
|
||||
'lon',
|
||||
String(midpoint > 180 ? midpoint - 360 : midpoint),
|
||||
);
|
||||
}
|
||||
}
|
||||
return url.toString();
|
||||
|
||||
@@ -452,3 +452,14 @@ function readGeocodingConsumer(file) {
|
||||
? [file, 'annotations/resolver.js'] : [file];
|
||||
return files.map((name) => fs.readFileSync(path.join(ROOT, 'src', name), 'utf8')).join('\n');
|
||||
}
|
||||
|
||||
|
||||
test('wrapped view bias stays near the antimeridian and malformed coordinates are omitted', () => {
|
||||
for (const [bias, expected] of [['-20,170|-10,-171', 179.5], ['50,175|60,-165', -175], ['0,180|10,-180', 180], ['0,-180|10,180', 0]]) {
|
||||
const params = new URL(photonSearchUrl('island', { bias })).searchParams;
|
||||
assert.equal(Number(params.get('lon')), expected);
|
||||
}
|
||||
for (const bias of ['-91,0|0,1', '0,181|1,0', '10,0|0,1', ',|,', '0,1,2|3,4', '0,1|Infinity,2']) {
|
||||
assert.equal(new URL(photonSearchUrl('island', { bias })).searchParams.has('lon'), false);
|
||||
}
|
||||
});
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
MARKER_SCALE_BY_DISTANCE,
|
||||
} from './policy.js';
|
||||
import { boxContains } from './model.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
import { msg } from '../../i18n/index.js';
|
||||
import { createAlprFloorResolver } from './floors.js';
|
||||
import { createAlprOverlay } from './overlay.js';
|
||||
import {
|
||||
@@ -452,7 +452,7 @@ export function createAlprPresentation({ state, services, source }) {
|
||||
layerName: 'ALPR Cameras',
|
||||
source:
|
||||
source.attribution?.description || source.label || 'Camera source',
|
||||
label: t('ALPR camera'),
|
||||
label: msg('ALPR camera'),
|
||||
latitude: record.latitude,
|
||||
longitude: record.longitude,
|
||||
properties: {
|
||||
|
||||
@@ -25,9 +25,10 @@ function presentAwarenessCount(summary = {}) {
|
||||
}
|
||||
|
||||
/** A distance as the panel shows it: 850 m, 4.6 km, 120 km, in the UI language. */
|
||||
function presentAwarenessDistance(meters) {
|
||||
export function presentAwarenessDistance(meters) {
|
||||
if (!Number.isFinite(meters) || meters < 0) return '—';
|
||||
if (meters < 1000) return formatQuantity(Math.round(meters), 'm');
|
||||
const wholeMeters = Math.round(meters);
|
||||
if (wholeMeters < 1000) return formatQuantity(wholeMeters, 'm');
|
||||
const digits = meters < 10000 ? 1 : 0;
|
||||
return formatQuantity(meters / 1000, 'km', {
|
||||
minimumFractionDigits: digits,
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* Format a compass direction for the awareness overlay.
|
||||
* @param {number} degrees
|
||||
* @returns {string}
|
||||
*/
|
||||
export function formatAwarenessDirection(degrees) {
|
||||
if (!Number.isFinite(degrees)) return '—';
|
||||
const normalized = ((degrees % 360) + 360) % 360;
|
||||
return String(Math.round(normalized) % 360).padStart(3, '0');
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { formatAwarenessDirection } from './presentation.js';
|
||||
|
||||
test('awareness bearings that round through north read 000, not 360', () => {
|
||||
assert.equal(formatAwarenessDirection(359.4), '359');
|
||||
assert.equal(formatAwarenessDirection(359.6), '000');
|
||||
assert.equal(formatAwarenessDirection(0), '000');
|
||||
assert.equal(formatAwarenessDirection(-0.4), '000');
|
||||
assert.equal(formatAwarenessDirection(Number.NaN), '—');
|
||||
});
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
} from '../../data/militaryAwarenessEngine.js';
|
||||
import { bearingBetweenCoordinates } from '../../cockpitMath.js';
|
||||
import { AWARENESS_PAGE_SIZE, CONTEXT_RIM_HEIGHT_M } from './policy.js';
|
||||
import { formatAwarenessDirection } from './presentation.js';
|
||||
|
||||
export function createRendering({
|
||||
state: layerState,
|
||||
@@ -225,12 +226,12 @@ export function createRendering({
|
||||
: null;
|
||||
const bearingText = Number.isFinite(bearing)
|
||||
? t('BRG {value}°', {
|
||||
value: String(Math.round(bearing)).padStart(3, '0'),
|
||||
value: formatAwarenessDirection(bearing),
|
||||
})
|
||||
: t('BRG —');
|
||||
const courseText = Number.isFinite(item.track)
|
||||
? ` · ${t('CRS {value}°', {
|
||||
value: String(Math.round(item.track)).padStart(3, '0'),
|
||||
value: formatAwarenessDirection(item.track),
|
||||
})}`
|
||||
: '';
|
||||
marker._label.textContent = `${label} · ${formatAwarenessDistance(item.distanceM)}\n${bearingText}${courseText}`;
|
||||
|
||||
@@ -41,13 +41,16 @@ const ADVISORIES_UNAVAILABLE = msg('Cyclone advisories unavailable');
|
||||
const SERVER_REASONS = new Set([msg('Cyclone data unavailable')]);
|
||||
const errorText = (error) =>
|
||||
error && (SERVER_REASONS.has(error) ? t(error) : translateKnown(error));
|
||||
// NHC's Tropical Cyclone Status JSON reference: PTC is post-tropical, PC is a
|
||||
// potential tropical cyclone, and subtropical systems are STS and STD.
|
||||
const CLASSIFICATION_NAMES = Object.freeze({
|
||||
PTC: msg('Potential tropical cyclone'),
|
||||
PC: msg('Potential tropical cyclone'),
|
||||
PTC: msg('Post-tropical cyclone'),
|
||||
HU: msg('Hurricane'),
|
||||
TS: msg('Tropical storm'),
|
||||
TD: msg('Tropical depression'),
|
||||
SS: msg('Subtropical storm'),
|
||||
SD: msg('Subtropical depression'),
|
||||
STS: msg('Subtropical storm'),
|
||||
STD: msg('Subtropical depression'),
|
||||
});
|
||||
const classificationName = (code) =>
|
||||
Object.hasOwn(CLASSIFICATION_NAMES, code)
|
||||
|
||||
@@ -513,12 +513,13 @@ test('only the latest queued focus runs and an unchanged selection survives refr
|
||||
});
|
||||
test('classification display expands known codes without altering the source or guessing unknown meanings', async () => {
|
||||
for (const [code, label] of [
|
||||
['PTC', 'Potential tropical cyclone'],
|
||||
['PC', 'Potential tropical cyclone'],
|
||||
['PTC', 'Post-tropical cyclone'],
|
||||
['HU', 'Hurricane'],
|
||||
['TS', 'Tropical storm'],
|
||||
['TD', 'Tropical depression'],
|
||||
['SS', 'Subtropical storm'],
|
||||
['SD', 'Subtropical depression'],
|
||||
['STS', 'Subtropical storm'],
|
||||
['STD', 'Subtropical depression'],
|
||||
['EX', 'EX'],
|
||||
['UNKNOWN', 'UNKNOWN'],
|
||||
]) {
|
||||
|
||||
@@ -38,33 +38,21 @@ export const DIRECTIONS_MODES = Object.freeze({
|
||||
export const DEFAULT_DIRECTIONS_MODE = 'car';
|
||||
|
||||
/**
|
||||
* The route proxy's refusal texts (server/providers/places/routes.js). They
|
||||
* stay English on the wire and in the AI tools; the row shows them translated.
|
||||
* The row error for a failed route request (createDirectionsSource errors),
|
||||
* as English data; the Layers panel shows it translated (ROUTING_ERROR_PATTERNS
|
||||
* in src/ui/statusText.js).
|
||||
*/
|
||||
const ROUTING_REFUSALS = new Set([
|
||||
msg('rate limited'),
|
||||
msg('routing service is rate limited'),
|
||||
msg('route leg too long'),
|
||||
msg('route too long'),
|
||||
]);
|
||||
|
||||
/** A refusal text from the route proxy in the language; unknown ones as given. */
|
||||
export function presentRoutingRefusal(text) {
|
||||
return ROUTING_REFUSALS.has(text) ? t(text) : text;
|
||||
}
|
||||
|
||||
/** The row text for a failed route request (createDirectionsSource errors). */
|
||||
export function presentRoutingFailure(error) {
|
||||
if (error?.status === 429) {
|
||||
return error.refusal
|
||||
? t('{error} — try again in a moment', {
|
||||
error: presentRoutingRefusal(error.refusal),
|
||||
})
|
||||
: t('Routing is rate limited — try again in a moment');
|
||||
? // i18n-ignore: English data, shown through ROUTING_ERROR_PATTERNS
|
||||
`${error.refusal} — try again in a moment`
|
||||
: msg('Routing is rate limited — try again in a moment');
|
||||
}
|
||||
if (Number.isFinite(error?.status) && error.status > 0)
|
||||
return t('Routing unavailable (HTTP {status})', { status: error.status });
|
||||
return error?.message || t('Routing unavailable');
|
||||
// i18n-ignore: English data, shown through ROUTING_ERROR_PATTERNS
|
||||
return `Routing unavailable (HTTP ${error.status})`;
|
||||
return error?.message || msg('Routing unavailable');
|
||||
}
|
||||
|
||||
/** Route colour — the annotation palette's cyan, so voice routes and Directions match. */
|
||||
@@ -112,7 +100,8 @@ export const FLIGHT_PROGRESS_MS = 250;
|
||||
export function routeDistanceText(meters) {
|
||||
if (!Number.isFinite(meters) || meters < 0) return '';
|
||||
if (meters < 100) return formatQuantity(Math.round(meters), 'm');
|
||||
if (meters < 1000) return formatQuantity(Math.round(meters / 10) * 10, 'm');
|
||||
const tens = Math.round(meters / 10) * 10;
|
||||
if (tens < 1000) return formatQuantity(tens, 'm');
|
||||
const km = meters / 1000;
|
||||
return km < 10
|
||||
? formatQuantity(km, 'km', {
|
||||
@@ -130,7 +119,8 @@ export function routeDistanceText(meters) {
|
||||
*/
|
||||
export function routeDurationText(seconds) {
|
||||
if (!Number.isFinite(seconds) || seconds < 0) return '';
|
||||
if (seconds < 60) return formatQuantity(Math.round(seconds), 's');
|
||||
const wholeSeconds = Math.round(seconds);
|
||||
if (wholeSeconds < 60) return formatQuantity(wholeSeconds, 's');
|
||||
const minutes = Math.round(seconds / 60);
|
||||
if (minutes < 60) return formatQuantity(minutes, 'min');
|
||||
const hours = formatQuantity(Math.floor(minutes / 60), 'h');
|
||||
@@ -306,16 +296,24 @@ export function directionsInstruction(step) {
|
||||
? t('Merge onto {road}', values)
|
||||
: t('Merge', { context: 'maneuver' });
|
||||
case 'on ramp':
|
||||
if (direction)
|
||||
if (modifier === 'left' || modifier === 'right')
|
||||
return road
|
||||
? t('Take the ramp on the {direction} onto {road}', values)
|
||||
: t('Take the ramp on the {direction}', values);
|
||||
if (direction && modifier !== 'straight')
|
||||
return road
|
||||
? t('Take the ramp {direction} onto {road}', values)
|
||||
: t('Take the ramp {direction}', values);
|
||||
return road ? t('Take the ramp onto {road}', values) : t('Take the ramp');
|
||||
case 'off ramp':
|
||||
if (direction)
|
||||
if (modifier === 'left' || modifier === 'right')
|
||||
return road
|
||||
? t('Take the exit on the {direction} onto {road}', values)
|
||||
: t('Take the exit on the {direction}', values);
|
||||
if (direction && modifier !== 'straight')
|
||||
return road
|
||||
? t('Take the exit {direction} onto {road}', values)
|
||||
: t('Take the exit {direction}', values);
|
||||
return road ? t('Take the exit onto {road}', values) : t('Take the exit');
|
||||
case 'roundabout':
|
||||
case 'rotary':
|
||||
@@ -344,9 +342,14 @@ export function directionsInstruction(step) {
|
||||
return road
|
||||
? t('Exit the roundabout onto {road}', values)
|
||||
: t('Exit the roundabout');
|
||||
case 'use lane':
|
||||
if (direction) {
|
||||
const lane = { road, direction: laneWord(modifier) };
|
||||
case 'use lane': {
|
||||
const side = modifier.includes('left')
|
||||
? 'left'
|
||||
: modifier.includes('right')
|
||||
? 'right'
|
||||
: '';
|
||||
if (side) {
|
||||
const lane = { road, direction: laneWord(side) };
|
||||
return road
|
||||
? t('Use the {direction} lane onto {road}', lane)
|
||||
: t('Use the {direction} lane', lane);
|
||||
@@ -354,6 +357,7 @@ export function directionsInstruction(step) {
|
||||
return road
|
||||
? t('Continue onto {road}', values)
|
||||
: t('Continue', { context: 'maneuver' });
|
||||
}
|
||||
default:
|
||||
return road
|
||||
? t('Continue onto {road}', values)
|
||||
@@ -643,7 +647,9 @@ export function directionsStats(state) {
|
||||
return {
|
||||
count: route?.steps.length || 0,
|
||||
lastUpdate,
|
||||
error: t('Another map tool is using clicks — close it, then SET A again'),
|
||||
error: msg(
|
||||
'Another map tool is using clicks — close it, then SET A again',
|
||||
),
|
||||
status: 'empty',
|
||||
source,
|
||||
};
|
||||
@@ -662,7 +668,7 @@ export function directionsStats(state) {
|
||||
return {
|
||||
count: 0,
|
||||
lastUpdate,
|
||||
error: error || t('No route found'),
|
||||
error: error || msg('No route found'),
|
||||
status: 'empty',
|
||||
source,
|
||||
};
|
||||
@@ -1144,13 +1150,10 @@ export function createDirectionsLayer({ services, source }) {
|
||||
clearRouteGraphics();
|
||||
_status = 'error';
|
||||
_error =
|
||||
payload?.error === 'no route found'
|
||||
? t('No route found between A and B')
|
||||
: payload?.error
|
||||
? t('Routing failed: {error}', {
|
||||
error: presentRoutingRefusal(payload.error),
|
||||
})
|
||||
: t('No route found between A and B');
|
||||
// i18n-ignore: English data, shown through ROUTING_ERROR_PATTERNS
|
||||
payload?.error && payload.error !== 'no route found'
|
||||
? `Routing failed: ${payload.error}`
|
||||
: msg('No route found between A and B');
|
||||
return;
|
||||
}
|
||||
_route = route;
|
||||
@@ -1167,9 +1170,9 @@ export function createDirectionsLayer({ services, source }) {
|
||||
// happened instead.
|
||||
_error =
|
||||
error?.name === 'AbortError'
|
||||
? t('Routing timed out')
|
||||
? msg('Routing timed out')
|
||||
: error?.name === 'TypeError'
|
||||
? t('Routing unavailable — no response from the routing service')
|
||||
? msg('Routing unavailable — no response from the routing service')
|
||||
: presentRoutingFailure(error);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
// Directions reports its fixed errors as English data (getStats(), and so the
|
||||
// layer snapshot the voice tools and the analyst read); the Layers panel row
|
||||
// shows them in the UI language.
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { setLocale, t as translate } from '../../i18n/index.js';
|
||||
import { LayerPanel } from '../../ui/layerPanel.js';
|
||||
import { directionsStats, presentRoutingFailure } from './index.js';
|
||||
|
||||
const idle = {
|
||||
enabled: true,
|
||||
mode: 'car',
|
||||
armed: null,
|
||||
a: null,
|
||||
b: null,
|
||||
status: 'idle',
|
||||
error: null,
|
||||
route: null,
|
||||
lastUpdate: null,
|
||||
};
|
||||
|
||||
const cases = [
|
||||
[
|
||||
{ ...idle, pointerBlocked: true },
|
||||
'Another map tool is using clicks — close it, then SET A again',
|
||||
],
|
||||
[{ ...idle, status: 'error' }, 'No route found'],
|
||||
[
|
||||
{ ...idle, status: 'error', error: 'Routing timed out' },
|
||||
'Routing timed out',
|
||||
],
|
||||
];
|
||||
|
||||
function rowFor(stats) {
|
||||
return LayerPanel.prototype._buildMetaText({
|
||||
id: 'directions',
|
||||
enabled: true,
|
||||
stats,
|
||||
});
|
||||
}
|
||||
|
||||
// Route request failures with the proxy's refusal or an HTTP status in them:
|
||||
// [the request error, its English row error, the row text in the language]
|
||||
const failures = () => [
|
||||
[
|
||||
{ status: 429, refusal: 'route leg too long' },
|
||||
'route leg too long — try again in a moment',
|
||||
translate('{error} — try again in a moment', {
|
||||
error: translate('route leg too long'),
|
||||
}),
|
||||
],
|
||||
[
|
||||
{ status: 429, refusal: null },
|
||||
'Routing is rate limited — try again in a moment',
|
||||
translate('Routing is rate limited — try again in a moment'),
|
||||
],
|
||||
[
|
||||
{ status: 503 },
|
||||
'Routing unavailable (HTTP 503)',
|
||||
translate('Routing unavailable (HTTP {status})', { status: 503 }),
|
||||
],
|
||||
[
|
||||
{ status: 0, message: '' },
|
||||
'Routing unavailable',
|
||||
translate('Routing unavailable'),
|
||||
],
|
||||
];
|
||||
|
||||
for (const locale of ['es', 'ru']) {
|
||||
test(`${locale}: Directions errors stay English in stats and read translated in the row`, (t) => {
|
||||
t.after(() => setLocale('en'));
|
||||
setLocale(locale);
|
||||
for (const [state, english] of cases) {
|
||||
const stats = directionsStats(state);
|
||||
assert.equal(stats.error, english);
|
||||
const row = rowFor(stats);
|
||||
assert.ok(row.includes(translate(english)), `${locale}: ${row}`);
|
||||
assert.ok(!row.includes(english), `${locale}: ${row}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
for (const locale of ['es', 'ru']) {
|
||||
test(`${locale}: route request failures stay English in stats and read translated in the row`, (t) => {
|
||||
t.after(() => setLocale('en'));
|
||||
setLocale(locale);
|
||||
for (const [failure, english, shown] of failures()) {
|
||||
const error = presentRoutingFailure(failure);
|
||||
assert.equal(error, english);
|
||||
const stats = directionsStats({ ...idle, status: 'error', error });
|
||||
assert.equal(stats.error, english);
|
||||
assert.ok(rowFor(stats).includes(shown), `${locale}: ${rowFor(stats)}`);
|
||||
assert.notEqual(shown, english);
|
||||
}
|
||||
// The proxy's refusal after "Routing failed:", and a text it never sends.
|
||||
for (const [refusal, shownRefusal] of [
|
||||
['route too long', translate('route too long')],
|
||||
['something else', 'something else'],
|
||||
]) {
|
||||
const row = rowFor(
|
||||
directionsStats({
|
||||
...idle,
|
||||
status: 'error',
|
||||
error: `Routing failed: ${refusal}`,
|
||||
}),
|
||||
);
|
||||
assert.ok(
|
||||
row.includes(
|
||||
translate('Routing failed: {error}', { error: shownRefusal }),
|
||||
),
|
||||
`${locale}: ${row}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test('en: the Directions row shows the English error', () => {
|
||||
setLocale('en');
|
||||
const row = rowFor(directionsStats({ ...idle, status: 'error' }));
|
||||
assert.match(row, /No route found/);
|
||||
});
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
satelliteShortName,
|
||||
fireDetectionKey,
|
||||
accentForSeverity,
|
||||
formatFrpMw,
|
||||
} from '../../data/firmsLabels.js';
|
||||
import {
|
||||
VIEW_PADDING,
|
||||
@@ -480,14 +481,15 @@ export function createModel({
|
||||
}
|
||||
|
||||
function formatFrp(frp) {
|
||||
return frp >= 10 ? frp.toFixed(0) : frp.toFixed(1);
|
||||
return formatFrpMw(frp);
|
||||
}
|
||||
|
||||
/** formatFrp for a card, with the locale's decimal separator ("4,9"). */
|
||||
|
||||
function formatFrpLabel(frp) {
|
||||
const digits = frp >= 10 ? 0 : 1;
|
||||
return formatNumber(frp, {
|
||||
const text = formatFrpMw(frp);
|
||||
const digits = text.includes('.') ? 1 : 0;
|
||||
return formatNumber(Number(text), {
|
||||
minimumFractionDigits: digits,
|
||||
maximumFractionDigits: digits,
|
||||
useGrouping: false,
|
||||
|
||||
@@ -18,9 +18,8 @@ export function createQueries({
|
||||
if (!fire) return null;
|
||||
return {
|
||||
id: fireDetectionKey(fire),
|
||||
label: t('Fire · FRP {frp} MW', {
|
||||
frp: components.model.formatFrp(fire.frp),
|
||||
}),
|
||||
// i18n-ignore: English entity label; the voice card translates it (shownEntityLabel)
|
||||
label: `Fire · FRP ${components.model.formatFrp(fire.frp)} MW`,
|
||||
latitude: fire.lat,
|
||||
longitude: fire.lon,
|
||||
frp: fire.frp,
|
||||
@@ -118,9 +117,8 @@ export function createQueries({
|
||||
latitude: strongest.lat,
|
||||
longitude: strongest.lon,
|
||||
frp: strongest.frp,
|
||||
label: t('Fire · FRP {frp} MW', {
|
||||
frp: components.model.formatFrp(strongest.frp),
|
||||
}),
|
||||
// i18n-ignore: English entity label; the voice card translates it (shownEntityLabel)
|
||||
label: `Fire · FRP ${components.model.formatFrp(strongest.frp)} MW`,
|
||||
};
|
||||
},
|
||||
|
||||
|
||||
@@ -193,9 +193,8 @@ export function createSelection({
|
||||
layerName: name,
|
||||
source: 'NASA FIRMS',
|
||||
dataSource: layerState._dataSource,
|
||||
label: t('Fire · FRP {frp} MW', {
|
||||
frp: components.model.formatFrp(fire.frp),
|
||||
}),
|
||||
// i18n-ignore: English entity label; the voice card translates it (shownEntityLabel)
|
||||
label: `Fire · FRP ${components.model.formatFrp(fire.frp)} MW`,
|
||||
latitude: fire.lat,
|
||||
longitude: fire.lon,
|
||||
properties: {
|
||||
|
||||
@@ -60,6 +60,10 @@ export function createMotion({
|
||||
publishFocusTargetFromCachedPosition,
|
||||
} = services.focus;
|
||||
|
||||
// Fixes leave the cache with their history; corrected positions invalidate
|
||||
// the local frame even when the existing Cartesian is mutated in place.
|
||||
const fixFrames = new WeakMap();
|
||||
|
||||
// Round 5: the old `_warmGroundedAircraftSurfaceCache` (global exact-5-decimal
|
||||
// warm for every grounded contact on Earth) is GONE. Parked-aircraft GPS
|
||||
// jitter minted fresh keys every poll → thousands of upstream points per
|
||||
@@ -124,7 +128,7 @@ export function createMotion({
|
||||
* @returns {Cesium.Cartesian3|null} Estimated ECEF position, or null if no history exists.
|
||||
*/
|
||||
|
||||
function _deadReckon(icao24, result) {
|
||||
function _deadReckon(icao24, result, sampledRenderTime) {
|
||||
const info = flightState.records.data.get(icao24);
|
||||
if (FOCUS_EVIDENCE_DEV && flightState._focusEvidenceIds.has(icao24)) {
|
||||
const position = flightState._billboards.get(icao24)?.position;
|
||||
@@ -149,11 +153,13 @@ export function createMotion({
|
||||
const out = result || new Cesium.Cartesian3();
|
||||
// Render one poll interval behind real time so we interpolate between
|
||||
// two KNOWN fixes whenever possible (see RENDER_DELAY_SEC rationale).
|
||||
const renderTime = Cesium.JulianDate.addSeconds(
|
||||
Cesium.JulianDate.now(),
|
||||
-RENDER_DELAY_SEC,
|
||||
flightState._scratchRenderTime,
|
||||
);
|
||||
const renderTime =
|
||||
sampledRenderTime ??
|
||||
Cesium.JulianDate.addSeconds(
|
||||
Cesium.JulianDate.now(flightState._scratchRenderTime),
|
||||
-RENDER_DELAY_SEC,
|
||||
flightState._scratchRenderTime,
|
||||
);
|
||||
|
||||
// Bracketing pair: interpolate — no extrapolation error, no snap-back.
|
||||
for (let i = history.length - 1; i >= 1; i--) {
|
||||
@@ -286,12 +292,31 @@ export function createMotion({
|
||||
0,
|
||||
flightState._scratchOffset,
|
||||
);
|
||||
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(
|
||||
fix.position,
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
flightState._scratchEnu,
|
||||
let frame = fixFrames.get(fix);
|
||||
if (!frame) {
|
||||
frame = {
|
||||
position: new Cesium.Cartesian3(),
|
||||
matrix: new Cesium.Matrix4(),
|
||||
};
|
||||
fixFrames.set(fix, frame);
|
||||
}
|
||||
if (
|
||||
!frame.valid ||
|
||||
!Cesium.Cartesian3.equals(frame.position, fix.position)
|
||||
) {
|
||||
Cesium.Transforms.eastNorthUpToFixedFrame(
|
||||
fix.position,
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
frame.matrix,
|
||||
);
|
||||
Cesium.Cartesian3.clone(fix.position, frame.position);
|
||||
frame.valid = true;
|
||||
}
|
||||
return Cesium.Matrix4.multiplyByPoint(
|
||||
frame.matrix,
|
||||
flightState._scratchOffset,
|
||||
out,
|
||||
);
|
||||
return Cesium.Matrix4.multiplyByPoint(enu, flightState._scratchOffset, out);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { createMotion } from './motion.js';
|
||||
import { arcOffsetEnu } from '../../data/motionModel.js';
|
||||
|
||||
function fixture() {
|
||||
const flightState = {
|
||||
records: { data: new Map() },
|
||||
_positionHistory: new Map(),
|
||||
_focusEvidenceIds: new Set(),
|
||||
_scratchArc: {},
|
||||
_scratchOffset: new Cesium.Cartesian3(),
|
||||
_scratchRenderTime: new Cesium.JulianDate(),
|
||||
};
|
||||
const motion = createMotion({
|
||||
flightState,
|
||||
services: { groundFloor: {}, camera: {}, focus: {} },
|
||||
parts: {},
|
||||
});
|
||||
return { flightState, motion };
|
||||
}
|
||||
|
||||
function expectedPosition(fix, dt, turnRate, transform) {
|
||||
const arc = {};
|
||||
arcOffsetEnu(fix.velocity, fix.track, turnRate, dt, arc);
|
||||
return Cesium.Matrix4.multiplyByPoint(
|
||||
transform(fix.position, Cesium.Ellipsoid.WGS84, new Cesium.Matrix4()),
|
||||
new Cesium.Cartesian3(arc.east, arc.north, 0),
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
}
|
||||
|
||||
function close(actual, expected) {
|
||||
assert.ok(Cesium.Cartesian3.distance(actual, expected) < 1e-8);
|
||||
}
|
||||
|
||||
test('extrapolation reuses fixed frames and invalidates corrected coordinates', (t) => {
|
||||
const { motion } = fixture();
|
||||
const transform = Cesium.Transforms.eastNorthUpToFixedFrame;
|
||||
const spy = t.mock.method(
|
||||
Cesium.Transforms,
|
||||
'eastNorthUpToFixedFrame',
|
||||
transform,
|
||||
);
|
||||
const fix = {
|
||||
position: Cesium.Cartesian3.fromDegrees(-97, 30, 200),
|
||||
velocity: 90,
|
||||
track: 70,
|
||||
};
|
||||
const out = new Cesium.Cartesian3();
|
||||
for (const dt of [-30, 5, 30, 60]) {
|
||||
motion._extrapolateFix(fix, {}, dt, out, 1.5);
|
||||
close(out, expectedPosition(fix, dt, 1.5, transform));
|
||||
}
|
||||
assert.equal(spy.mock.callCount(), 1);
|
||||
|
||||
// Ground reflooring mutates an existing fix's Cartesian in place.
|
||||
Cesium.Cartesian3.fromDegrees(-97, 30, 350, undefined, fix.position);
|
||||
motion._extrapolateFix(fix, {}, 30, out, 1.5);
|
||||
close(out, expectedPosition(fix, 30, 1.5, transform));
|
||||
assert.equal(spy.mock.callCount(), 2);
|
||||
|
||||
fix.position = Cesium.Cartesian3.fromDegrees(140, 80, 1000);
|
||||
motion._extrapolateFix(fix, {}, 30, out, -2);
|
||||
close(out, expectedPosition(fix, 30, -2, transform));
|
||||
assert.equal(spy.mock.callCount(), 3);
|
||||
|
||||
fix.velocity = 210;
|
||||
fix.track = 359;
|
||||
motion._extrapolateFix(fix, {}, 15, out, -1);
|
||||
close(out, expectedPosition(fix, 15, -1, transform));
|
||||
assert.equal(spy.mock.callCount(), 3);
|
||||
|
||||
const replacement = { ...fix };
|
||||
motion._extrapolateFix(replacement, {}, 15, out, -1);
|
||||
close(out, expectedPosition(replacement, 15, -1, transform));
|
||||
assert.equal(spy.mock.callCount(), 4);
|
||||
});
|
||||
|
||||
test('stationary fixes do not build a frame until motion needs it', (t) => {
|
||||
const { motion } = fixture();
|
||||
const spy = t.mock.method(Cesium.Transforms, 'eastNorthUpToFixedFrame');
|
||||
const fix = {
|
||||
position: Cesium.Cartesian3.fromDegrees(0, 0, 0),
|
||||
velocity: 0,
|
||||
track: 90,
|
||||
};
|
||||
const out = new Cesium.Cartesian3();
|
||||
close(motion._extrapolateFix(fix, {}, 30, out), fix.position);
|
||||
fix.velocity = 10;
|
||||
close(motion._extrapolateFix(fix, {}, 0, out), fix.position);
|
||||
assert.equal(spy.mock.callCount(), 0);
|
||||
motion._extrapolateFix(fix, {}, 30, out);
|
||||
assert.equal(spy.mock.callCount(), 1);
|
||||
});
|
||||
|
||||
test('fleet render time is shared without resampling or mutating the supplied instant', (t) => {
|
||||
const { flightState, motion } = fixture();
|
||||
const start = Cesium.JulianDate.fromIso8601('2026-10-24T12:00:00Z');
|
||||
const end = Cesium.JulianDate.addSeconds(start, 60, new Cesium.JulianDate());
|
||||
const renderTime = Cesium.JulianDate.addSeconds(
|
||||
start,
|
||||
30,
|
||||
new Cesium.JulianDate(),
|
||||
);
|
||||
const savedTime = Cesium.JulianDate.clone(renderTime);
|
||||
const history = [
|
||||
{
|
||||
time: start,
|
||||
position: Cesium.Cartesian3.fromDegrees(-97, 30, 1000),
|
||||
track: 90,
|
||||
},
|
||||
{
|
||||
time: end,
|
||||
position: Cesium.Cartesian3.fromDegrees(-96.99, 30, 1000),
|
||||
track: 90,
|
||||
},
|
||||
];
|
||||
for (const id of ['one', 'two']) {
|
||||
flightState.records.data.set(id, { velocity: 100, true_track: 90 });
|
||||
flightState._positionHistory.set(id, history);
|
||||
}
|
||||
t.mock.method(Cesium.JulianDate, 'now', () => {
|
||||
throw new Error('unexpected per-contact clock read');
|
||||
});
|
||||
const expected = Cesium.Cartesian3.lerp(
|
||||
history[0].position,
|
||||
history[1].position,
|
||||
0.5,
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
for (const id of ['one', 'two'])
|
||||
close(
|
||||
motion._deadReckon(id, new Cesium.Cartesian3(), renderTime),
|
||||
expected,
|
||||
);
|
||||
assert.ok(Cesium.JulianDate.equals(renderTime, savedTime));
|
||||
});
|
||||
|
||||
test('tracked callers still sample a fresh delayed time without a fleet epoch', (t) => {
|
||||
const { flightState, motion } = fixture();
|
||||
const start = Cesium.JulianDate.fromIso8601('2026-10-24T12:00:00Z');
|
||||
const history = [
|
||||
{
|
||||
time: start,
|
||||
position: Cesium.Cartesian3.fromDegrees(-97, 30, 1000),
|
||||
track: 90,
|
||||
},
|
||||
{
|
||||
time: Cesium.JulianDate.addSeconds(start, 60, new Cesium.JulianDate()),
|
||||
position: Cesium.Cartesian3.fromDegrees(-96.99, 30, 1000),
|
||||
track: 90,
|
||||
},
|
||||
];
|
||||
flightState.records.data.set('tracked', { velocity: 100, true_track: 90 });
|
||||
flightState._positionHistory.set('tracked', history);
|
||||
let elapsed = 60;
|
||||
const spy = t.mock.method(Cesium.JulianDate, 'now', (result) => {
|
||||
assert.equal(result, flightState._scratchRenderTime);
|
||||
return Cesium.JulianDate.addSeconds(start, elapsed, result);
|
||||
});
|
||||
const out = new Cesium.Cartesian3();
|
||||
close(
|
||||
motion._deadReckon('tracked', out),
|
||||
Cesium.Cartesian3.lerp(
|
||||
history[0].position,
|
||||
history[1].position,
|
||||
0.5,
|
||||
new Cesium.Cartesian3(),
|
||||
),
|
||||
);
|
||||
elapsed = 75;
|
||||
close(
|
||||
motion._deadReckon('tracked', out),
|
||||
Cesium.Cartesian3.lerp(
|
||||
history[0].position,
|
||||
history[1].position,
|
||||
0.75,
|
||||
new Cesium.Cartesian3(),
|
||||
),
|
||||
);
|
||||
assert.equal(spy.mock.callCount(), 2);
|
||||
});
|
||||
@@ -452,8 +452,8 @@ export function createQueries({
|
||||
const isTracked = icao24 === flightState._trackedIcao;
|
||||
// Keep planes rendered as a 3D model (billboard hidden) so the detection box
|
||||
// doesn't vanish on the 2D→3D handoff; bb.position stays current while hidden.
|
||||
const model = flightState._models.get(icao24);
|
||||
const modelOwnsVisual = parts.rendering._modelOwnsVisual(icao24);
|
||||
const model = flightState._models.get(icao24) ?? null;
|
||||
const modelOwnsVisual = parts.rendering._modelOwnsVisual(icao24, model);
|
||||
if (!isTracked && !bb.show && !modelOwnsVisual) continue;
|
||||
const info = flightState.records.data.get(icao24);
|
||||
let object = flightState._detectionObjects.get(icao24);
|
||||
@@ -491,8 +491,19 @@ export function createQueries({
|
||||
object.position = pos;
|
||||
object.skipLabel = isTracked;
|
||||
// Card text only — declutter/cohort identity is `object.sourceId` (icao24).
|
||||
const id = _contactLabel(icao24, info);
|
||||
if (object.id !== id) object.id = id;
|
||||
const callsign = info?.callsign;
|
||||
const registration = info?.registration;
|
||||
// Records and enrichment may change in place. Cache by field values,
|
||||
// while keeping the live visual anchor above independent of text.
|
||||
if (
|
||||
object.id === undefined ||
|
||||
object._labelCallsign !== callsign ||
|
||||
object._labelRegistration !== registration
|
||||
) {
|
||||
object.id = _contactLabel(icao24, info);
|
||||
object._labelCallsign = callsign;
|
||||
object._labelRegistration = registration;
|
||||
}
|
||||
const altitude = info?.altitude;
|
||||
if (object._altitude !== altitude) {
|
||||
object._altitude = altitude;
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { createQueries } from './queries.js';
|
||||
import { createRendering } from './rendering.js';
|
||||
|
||||
function fixture() {
|
||||
const info = {
|
||||
callsign: ' TEST123 ',
|
||||
registration: ' N123 ',
|
||||
altitude: 1000,
|
||||
};
|
||||
const bb = { show: true, position: new Cesium.Cartesian3(1, 2, 3) };
|
||||
const flightState = {
|
||||
feed: {},
|
||||
_billboardCollection: { show: true },
|
||||
_billboards: new Map([['abc123', bb]]),
|
||||
_models: new Map(),
|
||||
_detectionObjects: new Map(),
|
||||
records: { data: new Map([['abc123', info]]) },
|
||||
};
|
||||
let formats = 0;
|
||||
const services = {
|
||||
aircraftPresentation: {},
|
||||
militaryRegistry: {},
|
||||
camera: {},
|
||||
focus: {},
|
||||
recession: {},
|
||||
labels: {
|
||||
formatFlightLevel: (altitude) => {
|
||||
formats++;
|
||||
return String(altitude);
|
||||
},
|
||||
},
|
||||
};
|
||||
const parts = {
|
||||
testing: {},
|
||||
tracking: { _trackedModelRegimeActive: () => true },
|
||||
motion: { _trackedVisualCached: () => null },
|
||||
};
|
||||
parts.rendering = createRendering({ flightState, services, parts });
|
||||
const queries = createQueries({ flightState, services, parts }).methods;
|
||||
return { flightState, info, bb, parts, queries, formats: () => formats };
|
||||
}
|
||||
|
||||
test('candidate text follows in-place enrichment without freezing identity or positions', () => {
|
||||
const f = fixture();
|
||||
const [first] = f.queries.getDetectableObjects();
|
||||
assert.equal(first.id, 'TEST123');
|
||||
assert.equal(first.sourceId, 'abc123');
|
||||
f.bb.position = new Cesium.Cartesian3(4, 5, 6);
|
||||
assert.equal(f.queries.getDetectableObjects()[0], first);
|
||||
assert.equal(first.position, f.bb.position);
|
||||
assert.equal(f.formats(), 1);
|
||||
f.info.callsign = ' NEW456 ';
|
||||
assert.equal(f.queries.getDetectableObjects()[0].id, 'NEW456');
|
||||
f.info.callsign = ' ';
|
||||
assert.equal(f.queries.getDetectableObjects()[0].id, 'N123');
|
||||
f.info.registration = ' N456 ';
|
||||
f.info.altitude = 2000;
|
||||
assert.equal(f.queries.getDetectableObjects()[0].id, 'N456');
|
||||
assert.equal(first.metric, '2000');
|
||||
assert.equal(f.formats(), 2);
|
||||
f.flightState.records.data.set('abc123', { ...f.info });
|
||||
assert.equal(f.queries.getDetectableObjects()[0], first);
|
||||
f.flightState.records.data.delete('abc123');
|
||||
assert.equal(f.queries.getDetectableObjects()[0].id, 'abc123');
|
||||
assert.equal(first.sourceId, 'abc123');
|
||||
});
|
||||
|
||||
test('unchanged candidate text is normalized once across paints', (t) => {
|
||||
const f = fixture();
|
||||
const trim = String.prototype.trim;
|
||||
let calls = 0;
|
||||
t.mock.method(String.prototype, 'trim', function () {
|
||||
if (String(this) === ' TEST123 ') calls++;
|
||||
return trim.call(this);
|
||||
});
|
||||
for (let i = 0; i < 20; i++) f.queries.getDetectableObjects();
|
||||
assert.equal(calls, 1);
|
||||
});
|
||||
|
||||
test('candidate collection resolves models once and keeps handoffs live', (t) => {
|
||||
const f = fixture();
|
||||
const get = t.mock.method(f.flightState._models, 'get');
|
||||
const [candidate] = f.queries.getDetectableObjects();
|
||||
assert.equal(get.mock.callCount(), 1);
|
||||
const model = {
|
||||
ready: false,
|
||||
show: true,
|
||||
modelMatrix: Cesium.Matrix4.fromTranslation(
|
||||
new Cesium.Cartesian3(10, 20, 30),
|
||||
),
|
||||
};
|
||||
f.parts.rendering._modelSpec = () => ({
|
||||
visualCenterNative: Cesium.Cartesian3.ZERO,
|
||||
scale: 1,
|
||||
});
|
||||
f.flightState._models.set('abc123', model);
|
||||
f.bb.show = false;
|
||||
assert.deepEqual(f.queries.getDetectableObjects(), []);
|
||||
model.ready = true;
|
||||
assert.equal(f.queries.getDetectableObjects()[0], candidate);
|
||||
assert.deepEqual(candidate.position, new Cesium.Cartesian3(10, 20, 30));
|
||||
Cesium.Matrix4.setTranslation(
|
||||
model.modelMatrix,
|
||||
new Cesium.Cartesian3(40, 50, 60),
|
||||
model.modelMatrix,
|
||||
);
|
||||
f.queries.getDetectableObjects();
|
||||
assert.deepEqual(candidate.position, new Cesium.Cartesian3(40, 50, 60));
|
||||
model.show = false;
|
||||
assert.deepEqual(f.queries.getDetectableObjects(), []);
|
||||
f.bb.show = true;
|
||||
assert.equal(f.queries.getDetectableObjects()[0].position, f.bb.position);
|
||||
assert.equal(get.mock.callCount(), 6);
|
||||
model.show = true;
|
||||
assert.equal(f.parts.rendering._modelOwnsVisual('abc123'), true);
|
||||
assert.equal(get.mock.callCount(), 7);
|
||||
});
|
||||
|
||||
test('tracked ownership and live anchors remain independent of fleet models', () => {
|
||||
const f = fixture();
|
||||
f.flightState._trackedIcao = 'abc123';
|
||||
f.flightState._trackedModel = { ready: true, show: true };
|
||||
f.parts.rendering._modelSpec = () => ({});
|
||||
let anchor = new Cesium.Cartesian3(10, 20, 30);
|
||||
f.parts.motion._trackedVisualCached = () => anchor;
|
||||
const [candidate] = f.queries.getDetectableObjects();
|
||||
assert.equal(candidate.position, anchor);
|
||||
assert.equal(candidate.skipLabel, true);
|
||||
assert.equal(f.parts.rendering._modelOwnsVisual('abc123', null), true);
|
||||
anchor = new Cesium.Cartesian3(40, 50, 60);
|
||||
assert.equal(f.queries.getDetectableObjects()[0].position, anchor);
|
||||
for (const tracked of [
|
||||
null,
|
||||
{ ready: false, show: true },
|
||||
{ ready: true, show: false },
|
||||
]) {
|
||||
f.flightState._trackedModel = tracked;
|
||||
assert.equal(
|
||||
f.parts.rendering._modelOwnsVisual('abc123', { ready: true, show: true }),
|
||||
false,
|
||||
);
|
||||
}
|
||||
f.flightState._trackedModel = { ready: true, show: true };
|
||||
f.parts.tracking._trackedModelRegimeActive = () => false;
|
||||
assert.equal(f.parts.rendering._modelOwnsVisual('abc123', null), false);
|
||||
});
|
||||
@@ -32,10 +32,12 @@ import {
|
||||
TRACKED_MODEL_MIN_PX,
|
||||
TRACKED_MODEL_MAX_PX,
|
||||
FLEET_DR_INTERVAL_MS,
|
||||
RENDER_DELAY_SEC,
|
||||
COURSE_SLEW_DT_MAX_SEC,
|
||||
ROTATION_REFRESH_MS,
|
||||
COURSE_MAX_DPS,
|
||||
} from './policy.js';
|
||||
import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from '../../data/aircraftModelLighting.js';
|
||||
|
||||
export function createRendering({
|
||||
flightState,
|
||||
@@ -382,17 +384,20 @@ export function createRendering({
|
||||
* null or still-loading tracked model from claiming a visual it is not
|
||||
* drawing yet.
|
||||
* @param {string} icao24
|
||||
* @param {Cesium.Model|null} [model] Resolved fleet model; null means absent.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
|
||||
function _modelOwnsVisual(icao24) {
|
||||
function _modelOwnsVisual(icao24, model) {
|
||||
if (icao24 === flightState._trackedIcao) {
|
||||
return (
|
||||
parts.tracking._trackedModelRegimeActive() &&
|
||||
_modelIsRendering(flightState._trackedModel)
|
||||
);
|
||||
}
|
||||
return _modelIsRendering(flightState._models.get(icao24));
|
||||
return _modelIsRendering(
|
||||
model === undefined ? flightState._models.get(icao24) : model,
|
||||
);
|
||||
}
|
||||
|
||||
/** A model is the visual only once it actually draws — loaded AND shown.
|
||||
@@ -503,6 +508,7 @@ export function createRendering({
|
||||
model = await Cesium.Model.fromGltfAsync({
|
||||
url: resolveAsset(spec.url),
|
||||
asynchronous: false,
|
||||
environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS,
|
||||
minimumPixelSize: MODEL_MIN_PX,
|
||||
scale: spec.scale,
|
||||
color: flightState._irBoost ? Cesium.Color.WHITE : _modelColor(icao24),
|
||||
@@ -709,6 +715,7 @@ export function createRendering({
|
||||
Cesium.Model.fromGltfAsync({
|
||||
url: resolveAsset(trackedSpec.url),
|
||||
asynchronous: false,
|
||||
environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS,
|
||||
minimumPixelSize: TRACKED_MODEL_MIN_PX,
|
||||
scale: trackedSpec.scale,
|
||||
color: flightState._irBoost ? Cesium.Color.WHITE : Cesium.Color.CYAN,
|
||||
@@ -854,6 +861,12 @@ export function createRendering({
|
||||
)
|
||||
: 0.08;
|
||||
flightState._lastFleetTickMs = nowMs;
|
||||
// Every contact in this pass shares the same delayed display instant.
|
||||
const renderTime = Cesium.JulianDate.addSeconds(
|
||||
Cesium.JulianDate.now(flightState._scratchFleetRenderTime),
|
||||
-RENDER_DELAY_SEC,
|
||||
flightState._scratchFleetRenderTime,
|
||||
);
|
||||
|
||||
_drainIrReloadQueue(); // bounded per-tick slice of any pending boost-flip reload
|
||||
if (flightState._cockpitContactMode)
|
||||
@@ -957,7 +970,11 @@ export function createRendering({
|
||||
|
||||
const info = flightState.records.data.get(icao24);
|
||||
|
||||
const dr = parts.motion._deadReckon(icao24, flightState._scratchFleetPos);
|
||||
const dr = parts.motion._deadReckon(
|
||||
icao24,
|
||||
flightState._scratchFleetPos,
|
||||
renderTime,
|
||||
);
|
||||
// The dead-reckoned point drifts away from the fix whose cell supplied the
|
||||
// height, so a grounded contact's sprite ends up under the mesh it taxied
|
||||
// (or coasted) over. Re-floor at the DISPLAYED coordinate — read-only, and
|
||||
|
||||
@@ -242,12 +242,12 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._scratchCarto = new Cesium.Cartographic();
|
||||
|
||||
flightState._scratchEnu = new Cesium.Matrix4();
|
||||
|
||||
flightState._scratchArc = { east: 0, north: 0, endCourseDeg: 0 };
|
||||
|
||||
flightState._scratchRenderTime = new Cesium.JulianDate();
|
||||
|
||||
flightState._scratchFleetRenderTime = new Cesium.JulianDate();
|
||||
|
||||
flightState._scratchFleetPos = new Cesium.Cartesian3();
|
||||
|
||||
flightState._scratchSonarScreen = new Cesium.Cartesian2();
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
// S2 Underground GhostMaps catalog: which KMZ in the public repository is the
|
||||
// current edition of each product. Pure and portable (the server builds the
|
||||
// catalog, tests pin the rules); no i18n, no DOM, no Cesium.
|
||||
|
||||
export const GHOSTMAPS_REPO = Object.freeze({
|
||||
owner: 's2underground',
|
||||
name: 'GhostMaps',
|
||||
branch: 'main',
|
||||
url: 'https://github.com/s2underground/GhostMaps',
|
||||
});
|
||||
|
||||
/** Largest KMZ the proxy downloads; matches the browser's import ceiling. */
|
||||
export const GHOSTMAPS_MAX_FILE_BYTES = 50 * 1024 * 1024;
|
||||
|
||||
const ARCGIS = 'ArcGIS Data for ATAK (KMZs)/';
|
||||
const INCIDENTS = 'Incident Response Products for ATAK (KMZs and Documents)/';
|
||||
|
||||
/**
|
||||
* Curated products, in panel order. Each names a series of dated uploads; the
|
||||
* newest edition wins. Patterns match whole repository paths, so a renamed
|
||||
* folder fails closed (the product drops out) instead of matching elsewhere.
|
||||
*/
|
||||
export const GHOSTMAPS_PRODUCTS = Object.freeze([
|
||||
Object.freeze({
|
||||
id: 'cip',
|
||||
// i18n-ignore: catalog data; the panel shows its own translated label
|
||||
title: 'Common Intelligence Picture',
|
||||
defaultOn: true,
|
||||
pattern: new RegExp(
|
||||
`^${escape(ARCGIS)}Common Intelligence Picture/Master Database/[^/]+\\.kmz$`,
|
||||
'i',
|
||||
),
|
||||
}),
|
||||
Object.freeze({
|
||||
id: 'kinetic-30d',
|
||||
// i18n-ignore: catalog data; the panel shows its own translated label
|
||||
title: 'Kinetic Activity (30 days)',
|
||||
defaultOn: true,
|
||||
pattern: new RegExp(
|
||||
`^${escape(ARCGIS)}Common Intelligence Picture/30-Day Pulls/Kinetic[^/]*\\.kmz$`,
|
||||
'i',
|
||||
),
|
||||
}),
|
||||
Object.freeze({
|
||||
id: 'border-crisis',
|
||||
// i18n-ignore: catalog data; the panel shows its own translated label
|
||||
title: 'Border Crisis Map',
|
||||
defaultOn: false,
|
||||
pattern: new RegExp(
|
||||
`^${escape(ARCGIS)}Border Crisis Map/S2Underground_Border_Crisis_Map[^/]*\\.kmz$`,
|
||||
'i',
|
||||
),
|
||||
}),
|
||||
Object.freeze({
|
||||
id: 'iran-cip',
|
||||
// i18n-ignore: catalog data; the panel shows its own translated label
|
||||
title: 'Iran Common Intelligence Picture',
|
||||
defaultOn: false,
|
||||
pattern: new RegExp(
|
||||
`^${escape(INCIDENTS)}Iran[^/]*/Iran Common Intelligence Picture/[^/]+\\.kmz$`,
|
||||
'i',
|
||||
),
|
||||
}),
|
||||
Object.freeze({
|
||||
id: 'iran-kinetic',
|
||||
// i18n-ignore: catalog data; the panel shows its own translated label
|
||||
title: 'Iran Kinetic Events',
|
||||
defaultOn: false,
|
||||
pattern: new RegExp(
|
||||
`^${escape(INCIDENTS)}Iran[^/]*/Iran Kinetic Events/[^/]+\\.kmz$`,
|
||||
'i',
|
||||
),
|
||||
}),
|
||||
Object.freeze({
|
||||
id: 'yemen-flot',
|
||||
// i18n-ignore: catalog data; the panel shows its own translated label
|
||||
title: 'Yemen FLOT',
|
||||
defaultOn: false,
|
||||
pattern: new RegExp(
|
||||
`^${escape(INCIDENTS)}Yemen[^/]*/Yemen FLOT[^/]*\\.kmz$`,
|
||||
'i',
|
||||
),
|
||||
}),
|
||||
]);
|
||||
|
||||
/** The newest incident product outside the curated series and the archive. */
|
||||
export const GHOSTMAPS_LATEST_DROP = Object.freeze({
|
||||
id: 'latest-drop',
|
||||
// i18n-ignore: catalog data; the panel shows its own translated label
|
||||
title: 'Latest incident drop',
|
||||
defaultOn: false,
|
||||
});
|
||||
|
||||
const LATEST_DROP_EXCLUDED =
|
||||
/\/(?:0_Archive|Basedata|Reference Material)(?:\/|$)/i;
|
||||
|
||||
function escape(text) {
|
||||
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
}
|
||||
|
||||
const MONTHS = [
|
||||
'jan',
|
||||
'feb',
|
||||
'mar',
|
||||
'apr',
|
||||
'may',
|
||||
'jun',
|
||||
'jul',
|
||||
'aug',
|
||||
'sep',
|
||||
'oct',
|
||||
'nov',
|
||||
'dec',
|
||||
];
|
||||
const DATE_IN_NAME =
|
||||
/(january|february|march|april|may|june|july|august|september|sept|october|november|december|jan|feb|mar|apr|jun|jul|aug|sep|oct|nov|dec)[ _-]?(\d{1,2})(?:st|nd|rd|th)?[ ,_-]+(20\d\d)/i;
|
||||
const EDITION_IN_NAME = /(?:[ _-]export)?[ _-]v?(\d{1,3})$/i;
|
||||
|
||||
/**
|
||||
* The date and edition written into an S2 file name, e.g.
|
||||
* `..._October_16_2026_Export_1.kmz` → 2026-10-16, edition 1. Undated names
|
||||
* report `dateMs: null` and sort below every dated edition.
|
||||
* @param {string} fileName
|
||||
* @returns {{dateMs: ?number, edition: number}}
|
||||
*/
|
||||
export function parseGhostMapsEdition(fileName) {
|
||||
const stem = String(fileName || '').replace(/\.km[lz]$/i, '');
|
||||
const match = DATE_IN_NAME.exec(stem);
|
||||
let dateMs = null;
|
||||
if (match) {
|
||||
const month = MONTHS.indexOf(match[1].slice(0, 3).toLowerCase());
|
||||
const day = Number(match[2]);
|
||||
const year = Number(match[3]);
|
||||
const at = Date.UTC(year, month, day);
|
||||
// Date.UTC rolls 31 Sep into 1 Oct; only an exact calendar date counts.
|
||||
if (month >= 0 && new Date(at).getUTCDate() === day) dateMs = at;
|
||||
}
|
||||
const tail = match ? stem.slice(match.index + match[0].length) : stem;
|
||||
const edition = Number(EDITION_IN_NAME.exec(tail)?.[1] ?? 0);
|
||||
return { dateMs, edition };
|
||||
}
|
||||
|
||||
function newer(a, b) {
|
||||
if (!b) return true;
|
||||
const ad = a.dateMs ?? -Infinity;
|
||||
const bd = b.dateMs ?? -Infinity;
|
||||
if (ad !== bd) return ad > bd;
|
||||
if (a.edition !== b.edition) return a.edition > b.edition;
|
||||
return a.path > b.path;
|
||||
}
|
||||
|
||||
/** `S2Underground_Border_Crisis_Map_June_02_2026_v1.kmz` → readable words. */
|
||||
export function ghostMapsFileTitle(fileName) {
|
||||
return String(fileName || '')
|
||||
.replace(/\.km[lz]$/i, '')
|
||||
.replace(/^S2Underground_/i, '')
|
||||
.replace(/_/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the product catalog from a recursive git tree listing.
|
||||
* @param {Array<{path: string, type: string, sha: string, size?: number}>} tree
|
||||
* @returns {Array<{id: string, title: string, defaultOn: boolean,
|
||||
* path: string, fileName: string, fileTitle: string, version: string,
|
||||
* size: number, dateMs: ?number, edition: number}>}
|
||||
*/
|
||||
export function buildGhostMapsCatalog(tree) {
|
||||
const best = new Map();
|
||||
let drop = null;
|
||||
for (const entry of Array.isArray(tree) ? tree : []) {
|
||||
if (entry?.type !== 'blob' || typeof entry.path !== 'string') continue;
|
||||
if (!/\.kmz$/i.test(entry.path)) continue;
|
||||
if (!/^[0-9a-f]{40}$/.test(entry.sha || '')) continue;
|
||||
const size = Number(entry.size);
|
||||
if (!Number.isFinite(size) || size <= 0 || size > GHOSTMAPS_MAX_FILE_BYTES)
|
||||
continue;
|
||||
const fileName = entry.path.slice(entry.path.lastIndexOf('/') + 1);
|
||||
const candidate = {
|
||||
path: entry.path,
|
||||
fileName,
|
||||
version: entry.sha,
|
||||
size,
|
||||
...parseGhostMapsEdition(fileName),
|
||||
};
|
||||
const product = GHOSTMAPS_PRODUCTS.find(({ pattern }) =>
|
||||
pattern.test(entry.path),
|
||||
);
|
||||
if (product) {
|
||||
if (newer(candidate, best.get(product.id)))
|
||||
best.set(product.id, candidate);
|
||||
} else if (
|
||||
entry.path.startsWith(INCIDENTS) &&
|
||||
!LATEST_DROP_EXCLUDED.test(`/${entry.path}`) &&
|
||||
candidate.dateMs != null &&
|
||||
newer(candidate, drop)
|
||||
) {
|
||||
drop = candidate;
|
||||
}
|
||||
}
|
||||
const rows = [];
|
||||
for (const product of [...GHOSTMAPS_PRODUCTS, GHOSTMAPS_LATEST_DROP]) {
|
||||
const file =
|
||||
product === GHOSTMAPS_LATEST_DROP ? drop : best.get(product.id);
|
||||
if (!file) continue;
|
||||
rows.push({
|
||||
id: product.id,
|
||||
title: product.title,
|
||||
defaultOn: product.defaultOn,
|
||||
...file,
|
||||
fileTitle: ghostMapsFileTitle(file.fileName),
|
||||
});
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* Raw download URL pinned to a commit, so a CDN can never hand back an older
|
||||
* edition for a newer catalog.
|
||||
* @param {string} commit 40-hex commit sha.
|
||||
* @param {string} path Repository path.
|
||||
*/
|
||||
export function ghostMapsRawUrl(commit, path) {
|
||||
const encoded = path.split('/').map(encodeURIComponent).join('/');
|
||||
return `https://raw.githubusercontent.com/${GHOSTMAPS_REPO.owner}/${GHOSTMAPS_REPO.name}/${commit}/${encoded}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The branch head from a git smart-HTTP ref advertisement
|
||||
* (`/info/refs?service=git-upload-pack`), or null.
|
||||
* @param {string} text
|
||||
* @param {string} [branch]
|
||||
* @returns {?string}
|
||||
*/
|
||||
export function parseGitRefAdvertisement(text, branch = GHOSTMAPS_REPO.branch) {
|
||||
const ref = `refs/heads/${branch}`;
|
||||
for (const line of String(text || '').split('\n')) {
|
||||
// pkt-line: 4 hex length digits, then "<sha> <ref>" (the first ref line
|
||||
// also carries a NUL and the capability list).
|
||||
const match = /^[0-9a-f]{4}([0-9a-f]{40}) ([^\0\s]+)/.exec(line);
|
||||
if (match && match[2] === ref) return match[1];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
Loaded 100 of 401 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user