mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-17 16:52:20 +00:00
Merge origin/main: shipwrecks, news, transit fronts, signal-lost trails and uncredited photos on the renderer's ports
Upstream's layers and changes are carried onto the ports, with no Cesium outside src/render and no reach into the viewer: - Shipwrecks draw as one icon set, clicked through the input dispatcher. - News draws through draw sets, the camera port and the input dispatcher; its beacons pulse each frame through the frame port. - The scene occlusion probe moves into src/render/cesium and reaches detection through a new application hook, createOcclusionProbe; its private Cesium reads go through internals.js. - Flight and military trails, the stale and SIGNAL LOST cue, coasting and following the world clock run on the draw and frame ports. GPU icons follow the scene clock while the world clock is followed, and fade when stale. A report that holds is not planned again every tick. - Vessels are keyed by their record id. The stub boot now enables military, shipwrecks and news as well.
This commit is contained in:
commit
a755f63638
331 files changed
+40654
-1666
No files matched your search
@@ -1,7 +1,8 @@
|
||||
import { normalizeDisplayText } from '../../data/displayText.js';
|
||||
import { QUERY_LIMIT, QUERY_SNAP_DEGREES } from './policy.js';
|
||||
|
||||
function textTag(value) {
|
||||
const t = String(value ?? '').trim();
|
||||
const t = normalizeDisplayText(value);
|
||||
return t || null;
|
||||
}
|
||||
|
||||
|
||||
@@ -150,7 +150,7 @@ export function createHistory({ state: layerState, services, parts, source }) {
|
||||
return (
|
||||
items.find(
|
||||
(item) =>
|
||||
String(item?.icao24 || item?.mmsi || item?.id) === String(subject.id),
|
||||
String(item?.icao24 || item?.id || item?.mmsi) === String(subject.id),
|
||||
) || subject
|
||||
);
|
||||
}
|
||||
|
||||
@@ -117,7 +117,7 @@ export function createPanel({ state: layerState, parts }) {
|
||||
.slice(page, page + AWARENESS_PAGE_SIZE)
|
||||
.map((item, index) => {
|
||||
const label = formatAwarenessLabel(item);
|
||||
const targetId = item.icao24 || item.mmsi || item.id;
|
||||
const targetId = item.icao24 || item.id || item.mmsi;
|
||||
const distance = presentAwarenessDistance(item.distanceM);
|
||||
if (!targetId)
|
||||
return {
|
||||
@@ -182,6 +182,29 @@ export function createPanel({ state: layerState, parts }) {
|
||||
: null;
|
||||
}
|
||||
|
||||
/** The tracked airliner's photo with its credit, or null. The subject
|
||||
* refresh resolves it; only the subject it was resolved for shows it. */
|
||||
function presentPhoto(subject) {
|
||||
const held = layerState.subjectPhoto;
|
||||
if (
|
||||
!held ||
|
||||
held.layerId !== subject.layerId ||
|
||||
String(held.id) !== String(subject.id)
|
||||
)
|
||||
return null;
|
||||
const { photo } = held;
|
||||
return {
|
||||
src: photo.src,
|
||||
width: photo.width ?? null,
|
||||
height: photo.height ?? null,
|
||||
link: photo.link,
|
||||
// A photo whose answer names no photographer shows no credit line.
|
||||
credit: photo.photographer
|
||||
? t('Photo © {photographer}', { photographer: photo.photographer })
|
||||
: '',
|
||||
};
|
||||
}
|
||||
|
||||
function renderResults() {
|
||||
if (!layerState.enabled || !layerState.results) return hidePanel();
|
||||
ensurePanel();
|
||||
@@ -191,6 +214,7 @@ export function createPanel({ state: layerState, parts }) {
|
||||
kind: 'results',
|
||||
subject: `${subject.label} · ${t('{distance} FLIGHT / VESSEL WINDOW', { distance: presentAwarenessDistance(AWARENESS_RADIUS_M) })}`,
|
||||
subjectNames: presentNames(subject.memberNames),
|
||||
photo: presentPhoto(subject),
|
||||
navigation: presentNavigation(),
|
||||
rows: cohorts.map(presentRow),
|
||||
note: t(
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createPanel } from './panel.js';
|
||||
import { createSubject } from './subject.js';
|
||||
|
||||
test('a Contacts row names its provider as the Layers panel does, with its feed state', () => {
|
||||
const cohort = (id, source, sourceStatus) => ({
|
||||
@@ -36,3 +37,130 @@ test('a Contacts row names its provider as the Layers panel does, with its feed
|
||||
);
|
||||
state.offPanelLocale?.();
|
||||
});
|
||||
|
||||
const PHOTO = Object.freeze({
|
||||
src: 'https://t.plnspttrs.net/1/abc123_280.jpg',
|
||||
width: 280,
|
||||
height: 186,
|
||||
photographer: 'Jane Doe',
|
||||
link: 'https://www.planespotters.net/photo/1/n123ab',
|
||||
});
|
||||
|
||||
/** The published Contacts view for one subject and the refresh's photo. */
|
||||
function photoView(subject, subjectPhoto) {
|
||||
const state = {
|
||||
enabled: true,
|
||||
results: { subject, cohorts: [] },
|
||||
subjectPhoto,
|
||||
cohortPages: new Map(),
|
||||
panelListeners: new Set(),
|
||||
panelSignature: '',
|
||||
navigationIndex: 0,
|
||||
};
|
||||
const parts = {
|
||||
navigation: { canNavigateNext: () => false },
|
||||
rendering: { hideDirectionOverlay() {} },
|
||||
};
|
||||
createPanel({ state, parts }).renderResults();
|
||||
state.offPanelLocale?.();
|
||||
return state.panelView;
|
||||
}
|
||||
|
||||
const FLIGHT = Object.freeze({
|
||||
layerId: 'flights',
|
||||
id: 'abc123',
|
||||
label: 'N123AB',
|
||||
});
|
||||
|
||||
test('the Contacts view carries the tracked flight’s photo with its credit', () => {
|
||||
const view = photoView(FLIGHT, {
|
||||
layerId: 'flights',
|
||||
id: 'abc123',
|
||||
photo: PHOTO,
|
||||
});
|
||||
assert.deepEqual(view.photo, {
|
||||
src: PHOTO.src,
|
||||
width: 280,
|
||||
height: 186,
|
||||
link: PHOTO.link,
|
||||
credit: 'Photo © Jane Doe',
|
||||
});
|
||||
});
|
||||
|
||||
test('the Contacts view shows an uncredited photo with no credit line', () => {
|
||||
const view = photoView(FLIGHT, {
|
||||
layerId: 'flights',
|
||||
id: 'abc123',
|
||||
photo: { ...PHOTO, photographer: '' },
|
||||
});
|
||||
assert.equal(view.photo.src, PHOTO.src);
|
||||
assert.equal(view.photo.link, PHOTO.link);
|
||||
assert.equal(view.photo.credit, '');
|
||||
});
|
||||
|
||||
test('the Contacts view has no photo without one, or with another subject’s', () => {
|
||||
assert.equal(photoView(FLIGHT, null).photo, null);
|
||||
assert.equal(
|
||||
photoView(FLIGHT, { layerId: 'flights', id: 'def456', photo: PHOTO }).photo,
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
photoView(
|
||||
{ layerId: 'ais-live-vessels', id: 'abc123', label: 'VESSEL' },
|
||||
{ layerId: 'flights', id: 'abc123', photo: PHOTO },
|
||||
).photo,
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('only the tracked flight has a photo: not a vessel, an installation, a military aircraft or another flight', () => {
|
||||
const tracked = {
|
||||
layerId: 'flights',
|
||||
id: 'abc123',
|
||||
label: 'N123AB',
|
||||
photo: PHOTO,
|
||||
};
|
||||
let current = tracked;
|
||||
let lookups = 0;
|
||||
const flights = {
|
||||
getTrackedSubject: () => {
|
||||
lookups += 1;
|
||||
return current;
|
||||
},
|
||||
};
|
||||
const military = {
|
||||
getTrackedSubject: () => ({ ...tracked, layerId: 'military' }),
|
||||
};
|
||||
const { resolveSubjectPhoto } = createSubject({
|
||||
state: {},
|
||||
services: { flights, military, vessels: {}, installations: {} },
|
||||
parts: {
|
||||
navigation: {
|
||||
isFlightLayer: (id) => id === 'flights' || id === 'military',
|
||||
},
|
||||
},
|
||||
});
|
||||
assert.deepEqual(
|
||||
resolveSubjectPhoto({ layerId: 'flights', id: 'abc123' }),
|
||||
PHOTO,
|
||||
);
|
||||
assert.equal(lookups, 1);
|
||||
assert.equal(resolveSubjectPhoto({ layerId: 'flights', id: 'def456' }), null);
|
||||
assert.equal(
|
||||
resolveSubjectPhoto({ layerId: 'ais-live-vessels', id: 'abc123' }),
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
resolveSubjectPhoto({ layerId: 'military-installations', id: 'abc123' }),
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
resolveSubjectPhoto({ layerId: 'military', id: 'abc123' }),
|
||||
null,
|
||||
);
|
||||
assert.equal(resolveSubjectPhoto(null), null);
|
||||
current = null;
|
||||
assert.equal(resolveSubjectPhoto({ layerId: 'flights', id: 'abc123' }), null);
|
||||
current = { ...tracked, photo: null };
|
||||
assert.equal(resolveSubjectPhoto({ layerId: 'flights', id: 'abc123' }), null);
|
||||
});
|
||||
@@ -15,6 +15,8 @@ export function createState({ services }) {
|
||||
/** Stops following the manager's adoptions (see watchAdoptions). */
|
||||
unwatchAdoptions: null,
|
||||
subject: null,
|
||||
/** The tracked flight's photo with the subject it belongs to, or null. */
|
||||
subjectPhoto: null,
|
||||
results: null,
|
||||
visual: null,
|
||||
/** Whether layer views replace the panel's initial markup yet. */
|
||||
|
||||
@@ -88,7 +88,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
|
||||
.getNearby(position, AWARENESS_RADIUS_M, AWARENESS_QUERY_LIMIT)
|
||||
.filter(
|
||||
(item) =>
|
||||
!parts.queries.isSame(subject, item, 'ais-live-vessels', 'mmsi'),
|
||||
!parts.queries.isSame(subject, item, 'ais-live-vessels', 'id'),
|
||||
);
|
||||
const coverage = installationsState.stats?.coverage;
|
||||
const installationRadius =
|
||||
@@ -378,19 +378,48 @@ export function createSubject({ state: layerState, services, parts, source }) {
|
||||
*
|
||||
* Identity (`subject.id`) is NEVER re-derived — only the rendered string.
|
||||
* @param {{layerId: string, id: string, label: string}} subject Current subject.
|
||||
* @param {?object} [tracked] The subject's tracked descriptor, when the
|
||||
* caller already has it (see trackedSubjectOf).
|
||||
* @returns {string} The current label, or the cached one when the owning layer
|
||||
* has no tracked subject (e.g. a cross-layer handoff is in flight).
|
||||
*/
|
||||
|
||||
function resolveSubjectLabel(subject) {
|
||||
if (!parts.navigation.isFlightLayer(subject?.layerId))
|
||||
return subject?.label;
|
||||
function resolveSubjectLabel(subject, tracked = trackedSubjectOf(subject)) {
|
||||
return tracked?.label || subject?.label;
|
||||
}
|
||||
|
||||
/**
|
||||
* The owning flight layer's tracked-subject descriptor when it describes
|
||||
* this subject, else null. Built once per refresh and shared by the label
|
||||
* and the photo.
|
||||
* @param {{layerId: string, id: string}|null} subject Current subject.
|
||||
* @returns {?{id: string, label: string, photo?: ?object}}
|
||||
*/
|
||||
function trackedSubjectOf(subject) {
|
||||
if (!parts.navigation.isFlightLayer(subject?.layerId)) return null;
|
||||
const layer =
|
||||
subject.layerId === 'flights' ? flightsLayer : militaryFlightsLayer;
|
||||
const tracked = layer.getTrackedSubject?.();
|
||||
if (tracked?.label && String(tracked.id) === String(subject.id))
|
||||
return tracked.label;
|
||||
return subject.label;
|
||||
return tracked && String(tracked.id) === String(subject.id)
|
||||
? tracked
|
||||
: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The tracked airliner's Planespotters photo, for the Contacts panel.
|
||||
*
|
||||
* Only the flights layer looks photos up, and only for the plane it tracks;
|
||||
* a vessel, an installation, a military aircraft or an untracked flight has
|
||||
* none.
|
||||
* @param {{layerId: string, id: string}|null} subject Current subject.
|
||||
* @param {?object} [tracked] The subject's tracked descriptor, when the
|
||||
* caller already has it.
|
||||
* @returns {?{src: string, width: ?number, height: ?number, photographer: string, link: string}}
|
||||
*/
|
||||
function resolveSubjectPhoto(subject, tracked = trackedSubjectOf(subject)) {
|
||||
return subject?.layerId === 'flights' && tracked?.photo
|
||||
? tracked.photo
|
||||
: null;
|
||||
}
|
||||
|
||||
/** Refresh proximity counts/distances against the subject's current live position. */
|
||||
@@ -417,8 +446,21 @@ export function createSubject({ state: layerState, services, parts, source }) {
|
||||
if (presence === SUBJECT_PRESENCE.LIVE) layerState.subjectMissing = false;
|
||||
else if (presence === SUBJECT_PRESENCE.MISSING)
|
||||
layerState.subjectMissing = true;
|
||||
const nextLabel = resolveSubjectLabel(layerState.subject);
|
||||
const tracked = trackedSubjectOf(layerState.subject);
|
||||
const nextLabel = resolveSubjectLabel(layerState.subject, tracked);
|
||||
const labelChanged = nextLabel !== layerState.subject.label;
|
||||
// The panel reads the photo from here, with the subject it belongs to.
|
||||
const photo = resolveSubjectPhoto(layerState.subject, tracked);
|
||||
layerState.subjectPhoto = photo
|
||||
? {
|
||||
layerId: layerState.subject.layerId,
|
||||
id: layerState.subject.id,
|
||||
photo,
|
||||
}
|
||||
: null;
|
||||
// A photo arriving after selection is render-worthy on its own, as a label.
|
||||
const photoChanged =
|
||||
(photo?.src ?? null) !== (layerState.panelView?.photo?.src ?? null);
|
||||
layerState.subject = { ...layerState.subject, position, label: nextLabel };
|
||||
const movementM = layerState.lastEvaluatedPosition
|
||||
? distance(layerState.lastEvaluatedPosition, position)
|
||||
@@ -439,7 +481,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
|
||||
// kept the ICAO hex until unrelated movement, a source-revision bump, or
|
||||
// page rotation happened to repaint it. Gated on an ACTUAL change so the
|
||||
// common no-op refresh (every 750 ms) still costs no repaint.
|
||||
if (labelChanged) parts.panel.renderResults();
|
||||
if (labelChanged || photoChanged) parts.panel.renderResults();
|
||||
parts.rendering.scheduleDirectionOverlayUpdate(force);
|
||||
return;
|
||||
}
|
||||
@@ -474,7 +516,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
|
||||
if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return null;
|
||||
return {
|
||||
layerId: record.layerId,
|
||||
id: record.properties?.mmsi || record.id,
|
||||
id: record.properties?.vesselId || record.id,
|
||||
label: record.label || record.id,
|
||||
memberNames: record.properties?.memberNames || [],
|
||||
position: fromDegrees(longitude, latitude, 0),
|
||||
@@ -499,6 +541,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
|
||||
militaryInstallationsLayer.setContextAnchor?.(null);
|
||||
layerState.autoFocusRetryPending = false;
|
||||
layerState.subject = null;
|
||||
layerState.subjectPhoto = null;
|
||||
layerState.subjectMissing = false;
|
||||
layerState.results = null;
|
||||
layerState.navigationHistory = [];
|
||||
@@ -525,6 +568,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
|
||||
resolveSubjectPosition,
|
||||
collectionSubjectPosition,
|
||||
resolveSubjectLabel,
|
||||
resolveSubjectPhoto,
|
||||
refreshSelectedSubject,
|
||||
subjectFromContext,
|
||||
markSubjectEvicted,
|
||||
|
||||
@@ -3,6 +3,10 @@ import { fireDetectionKey } from '../../data/firmsLabels.js';
|
||||
import { filterFires } from '../../data/firmsIntensity.js';
|
||||
import { msg } from '../../i18n/index.js';
|
||||
|
||||
/** A time a Date can print: epoch ms within JavaScript's date range. */
|
||||
const isSnapshotEnd = (value) =>
|
||||
Number.isFinite(value) && Math.abs(value) <= 8_640_000_000_000_000;
|
||||
|
||||
export function createIngestion({
|
||||
layerState,
|
||||
services,
|
||||
@@ -32,6 +36,7 @@ export function createIngestion({
|
||||
return;
|
||||
if (payload.keyRequired) {
|
||||
layerState._keyRequired = true;
|
||||
layerState._at = null;
|
||||
layerState._error = null;
|
||||
layerState._stale = false;
|
||||
return;
|
||||
@@ -39,6 +44,9 @@ export function createIngestion({
|
||||
layerState._keyRequired = false;
|
||||
layerState._error = null;
|
||||
layerState._stale = Boolean(payload?.stale);
|
||||
// A snapshot of the 24 hours to a set time names it; one of the
|
||||
// trailing 24 hours to now does not.
|
||||
layerState._at = isSnapshotEnd(payload?.at) ? payload.at : null;
|
||||
const previousSelection = layerState._selectedFire;
|
||||
layerState._selectedFire = null;
|
||||
layerState._allFires = adaptFirmsRecords(payload?.fires);
|
||||
|
||||
@@ -119,6 +119,7 @@ export function createLifecycle({
|
||||
layerState._rowControlsListener = null;
|
||||
layerState._cellCount = 0;
|
||||
layerState._lastUpdate = null;
|
||||
layerState._at = null;
|
||||
layerState._keyRequired = false;
|
||||
layerState._stale = false;
|
||||
layerState._error = null;
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
rampTrackGradient,
|
||||
sliderPositionForFrp,
|
||||
} from '../../data/firmsIntensity.js';
|
||||
import { formatNumber, t } from '../../i18n/index.js';
|
||||
import { formatNumber, formatUtcDayMonth, t } from '../../i18n/index.js';
|
||||
import { LOD_LEVELS, REFRESH_INTERVAL_MS } from './policy.js';
|
||||
|
||||
/** Slider resolution: whole-percent positions along the log axis. */
|
||||
@@ -190,8 +190,9 @@ export function createQueries({
|
||||
* Layer stats for the data panel. Degraded feed states surface through
|
||||
* `error` (established qa-failstate pattern: a dead feed must never look
|
||||
* like a healthy empty layer) with a matching human `loadingLabel`:
|
||||
* 'LIVE · updated Xm ago' fresh, 'STALE · cached Xh' when the proxy
|
||||
* served past-TTL cache, 'KEY REQUIRED' keyless.
|
||||
* 'LIVE · updated Xm ago' fresh, '24 h to MM-DD HH:MM UTC' for a
|
||||
* snapshot that ends at a set time (`at`), 'STALE · cached Xh' when the
|
||||
* proxy served past-TTL cache, 'KEY REQUIRED' keyless.
|
||||
*/
|
||||
getStats() {
|
||||
const now = Date.now();
|
||||
@@ -213,6 +214,11 @@ export function createQueries({
|
||||
loadingLabel = staleText;
|
||||
} else if (layerState._error) {
|
||||
loadingLabel = layerState._error;
|
||||
} else if (Number.isFinite(layerState._at)) {
|
||||
loadingLabel = t('24 h to {day} {time} UTC', {
|
||||
day: formatUtcDayMonth(layerState._at),
|
||||
time: new Date(layerState._at).toISOString().slice(11, 16),
|
||||
});
|
||||
} else if (layerState._lastUpdate) {
|
||||
loadingLabel = t('LIVE · updated {age}', {
|
||||
age: components.model.formatAgoMinutes(now - layerState._lastUpdate),
|
||||
@@ -226,6 +232,11 @@ export function createQueries({
|
||||
lastUpdate: layerState._lastUpdate,
|
||||
loading: layerState._loading,
|
||||
stale: layerState._stale,
|
||||
// The end of the 24 hours shown when the snapshot ends at a set time;
|
||||
// null for the trailing 24 hours to now. Such a snapshot is not live,
|
||||
// so the row names the provider without the catalog's "LIVE".
|
||||
at: Number.isFinite(layerState._at) ? layerState._at : null,
|
||||
...(Number.isFinite(layerState._at) ? { source: 'NASA FIRMS' } : {}),
|
||||
// The machine-readable half of the keyless state, ahead of the human
|
||||
// strings below: without it "no key configured" is indistinguishable
|
||||
// from a broken feed, and the row reads as a fault instead of a step
|
||||
|
||||
@@ -76,6 +76,8 @@ export function createFirmsState({ services, config }) {
|
||||
|
||||
layerState._lastUpdate = null;
|
||||
|
||||
layerState._at = null;
|
||||
|
||||
layerState._currentLodId = null;
|
||||
|
||||
layerState._currentLodIndex = -1;
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { getLocale, setLocale } from '../../i18n/index.js';
|
||||
import { createModel } from './model.js';
|
||||
import { createQueries } from './queries.js';
|
||||
|
||||
test('a FIRMS snapshot that ends at a set time names it instead of LIVE', (context) => {
|
||||
const now = 1800000000000;
|
||||
context.mock.method(Date, 'now', () => now);
|
||||
const previousLocale = getLocale();
|
||||
const at = Date.UTC(2026, 9, 21, 15);
|
||||
const layerState = {
|
||||
_loading: false,
|
||||
_stale: false,
|
||||
_keyRequired: false,
|
||||
_error: null,
|
||||
_lastUpdate: now - 120000,
|
||||
_at: at,
|
||||
_count: 1,
|
||||
_cellCount: 0,
|
||||
_fires: [],
|
||||
};
|
||||
const model = createModel({ services: { anchors: {} } });
|
||||
const { methods } = createQueries({
|
||||
layerState,
|
||||
components: { model },
|
||||
config: {},
|
||||
});
|
||||
try {
|
||||
setLocale('en');
|
||||
assert.equal(methods.getStats().loadingLabel, '24 h to 10-21 15:00 UTC');
|
||||
assert.equal(methods.getStats().at, at);
|
||||
assert.equal(methods.getStats().source, 'NASA FIRMS', 'the row drops LIVE');
|
||||
setLocale('de');
|
||||
assert.equal(
|
||||
methods.getStats().loadingLabel,
|
||||
'24 Std. bis 21.10. 15:00 UTC',
|
||||
);
|
||||
layerState._at = null;
|
||||
setLocale('en');
|
||||
assert.equal(methods.getStats().loadingLabel, 'LIVE · updated 2m ago');
|
||||
assert.equal(methods.getStats().at, null);
|
||||
assert.equal(methods.getStats().source, undefined);
|
||||
} finally {
|
||||
setLocale(previousLocale);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* What the layer drops when the world clock moves it to another time (its
|
||||
* source declares a timeline; see src/time/snapshotTimeline.js).
|
||||
*/
|
||||
export function createClockFollow({ flightState, parts }) {
|
||||
/**
|
||||
* Forget how every contact moved, before the snapshot at another time takes
|
||||
* the place of every contact: their fixes, courses, floors and the tracked
|
||||
* trail belong to the time the clock left.
|
||||
*/
|
||||
function resetMotion() {
|
||||
flightState.records.reset();
|
||||
flightState._positionHistory.clear();
|
||||
flightState._displayCourse.clear();
|
||||
flightState._groundSnap.clear();
|
||||
flightState._displayFloorState.clear();
|
||||
flightState._drReconcileValid = false;
|
||||
flightState._cachedDRFrame = -1;
|
||||
flightState._cachedDRPosition = null;
|
||||
parts.tracking._clearTrail();
|
||||
flightState._lastCamPoseSig = '';
|
||||
}
|
||||
|
||||
/** Drop every contact: the time has none to show, or the clock went live. */
|
||||
function clear() {
|
||||
if (flightState._trackedIcao)
|
||||
parts.tracking._clearTracking(false, { evicted: true });
|
||||
resetMotion();
|
||||
// Each contact's icon row and 3D model go with it.
|
||||
for (const icao24 of [...(flightState._icons?.ids() ?? [])])
|
||||
parts.icons._forgetContact(icao24);
|
||||
flightState._detectionObjects.clear();
|
||||
flightState.feed._count = 0;
|
||||
flightState.feed._lastUpdate = null;
|
||||
}
|
||||
|
||||
return { resetMotion, clear };
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { FlightRecords } from './records.js';
|
||||
import { createIngestion } from './ingestion.js';
|
||||
import { createClockFollow } from './clockFollow.js';
|
||||
import { displayDelayMs, followsClock, RENDER_DELAY_SEC } from './policy.js';
|
||||
|
||||
// Flights follow the world clock only while their source declares a timeline
|
||||
// (src/time/snapshotTimeline.js); these cover the layer's side of it.
|
||||
|
||||
const T = 1_800_000_000_000;
|
||||
const following = { timeline: { active: () => true } };
|
||||
const live = { timeline: { active: () => false } };
|
||||
|
||||
function records(now = () => T) {
|
||||
return new FlightRecords({
|
||||
geoidHeight: () => 0,
|
||||
cachedGroundFloor: () => null,
|
||||
floorAltitudeM: (altitude) => altitude,
|
||||
now,
|
||||
});
|
||||
}
|
||||
const view = () => ({
|
||||
viewerLatDeg: null,
|
||||
viewerLonDeg: null,
|
||||
trackedId: null,
|
||||
floorWarmPoints: [],
|
||||
});
|
||||
const observation = (fields = {}) => ({
|
||||
id: 'abc123',
|
||||
reference: 'abc123',
|
||||
longitude: -77,
|
||||
latitude: 39,
|
||||
callsign: 'TEST1',
|
||||
baroAltitudeM: 1000,
|
||||
onGround: false,
|
||||
speedMps: 120,
|
||||
courseDeg: 90,
|
||||
positionTimeMs: T - 5_000,
|
||||
...fields,
|
||||
});
|
||||
|
||||
test('contacts are drawn behind the live edge, and at the time following the clock', () => {
|
||||
assert.equal(displayDelayMs({ timeline: null }), RENDER_DELAY_SEC * 1000);
|
||||
assert.equal(displayDelayMs({}), RENDER_DELAY_SEC * 1000);
|
||||
assert.equal(displayDelayMs(live), RENDER_DELAY_SEC * 1000);
|
||||
assert.equal(displayDelayMs(following), 0);
|
||||
assert.equal(followsClock({}), false);
|
||||
assert.equal(followsClock(following), true);
|
||||
});
|
||||
|
||||
test('civil records judge absence and receipt at the layer clock', () => {
|
||||
let now = T;
|
||||
const store = records(() => now);
|
||||
const { meta } = store.receive(observation({ positionTimeMs: null }), view());
|
||||
assert.equal(meta.observedReceiptMs, T);
|
||||
assert.equal(meta.newestFixMs, T, 'an undated fix is the clock time');
|
||||
assert.equal(
|
||||
store.absence('abc123', { complete: true, tracked: true }),
|
||||
'stale',
|
||||
);
|
||||
assert.equal(
|
||||
store.absence('abc123', {
|
||||
complete: true,
|
||||
tracked: true,
|
||||
nowMs: T + 11 * 60_000,
|
||||
}),
|
||||
'remove',
|
||||
'a given time judges retention',
|
||||
);
|
||||
store.receive(observation(), view());
|
||||
now = T + 11 * 60_000;
|
||||
assert.equal(
|
||||
store.absence('abc123', { complete: true, tracked: true }),
|
||||
'remove',
|
||||
'the clock judges retention when no time is given',
|
||||
);
|
||||
});
|
||||
|
||||
test('a records reset forgets where airframes were and keeps what they are', () => {
|
||||
const store = records();
|
||||
const first = store.receive(observation(), view());
|
||||
first.meta.typeCode = 'B738';
|
||||
first.meta.registration = 'N123';
|
||||
first.meta.photo = { src: 'photo.jpg' };
|
||||
store.absence('abc123', { complete: true });
|
||||
store.beginSnapshot(T);
|
||||
store.reset();
|
||||
assert.equal(store.data.size, 0);
|
||||
assert.equal(store.missingPolls.size, 0);
|
||||
assert.equal(store.lastSnapshotMs, null);
|
||||
const again = store.receive(
|
||||
observation({ positionTimeMs: T - 600_000, callsign: 'OTHER' }),
|
||||
view(),
|
||||
);
|
||||
assert.equal(again.prevMeta, undefined, 'no motion carries across');
|
||||
assert.equal(again.groundFlipped, false);
|
||||
assert.equal(again.meta.typeCode, 'B738');
|
||||
assert.equal(again.meta.registration, 'N123');
|
||||
assert.equal(again.meta.photo.src, 'photo.jpg');
|
||||
assert.equal(again.meta.newestFixMs, T - 600_000, 'an earlier fix applies');
|
||||
store.forget('abc123');
|
||||
assert.equal(store.airframes.size, 0);
|
||||
});
|
||||
|
||||
function ingestion(source, { follows = false } = {}) {
|
||||
const feed = {
|
||||
_source: source,
|
||||
_activeUpdateControllers: new Set(),
|
||||
_trackingRefreshEpoch: 0,
|
||||
_lastSource: 'Fixture',
|
||||
_retryAt: 0,
|
||||
};
|
||||
const applied = [];
|
||||
const state = { follows };
|
||||
const { methods } = createIngestion({
|
||||
feed,
|
||||
getQuery: () => ({ latitude: 39 }),
|
||||
applySnapshot: (snapshot, _viewer, options) => {
|
||||
applied.push({ snapshot, options });
|
||||
return { count: 1, ids: new Set() };
|
||||
},
|
||||
setSourceLabel: () => {},
|
||||
applyPendingTrackingRestore: () => {},
|
||||
followsClock: () => state.follows,
|
||||
});
|
||||
return { feed, applied, state, methods };
|
||||
}
|
||||
|
||||
test('civil polls carry no time; a snapshot at a time carries it and replaces', async () => {
|
||||
const queries = [];
|
||||
const probe = ingestion({
|
||||
async getSnapshot(query) {
|
||||
queries.push(query);
|
||||
return { records: [], observedAtMs: T - 60_000, freshness: 'current' };
|
||||
},
|
||||
});
|
||||
await probe.methods.update(null);
|
||||
assert.deepEqual(queries[0], { latitude: 39 });
|
||||
assert.equal(probe.applied[0].options, undefined);
|
||||
assert.equal(await probe.methods.loadAt(T - 60_000, { replace: true }), true);
|
||||
assert.deepEqual(queries[1], { latitude: 39, atMs: T - 60_000 });
|
||||
assert.deepEqual(probe.applied[1].options, { replace: true });
|
||||
assert.equal(probe.feed._lastUpdate, T - 60_000);
|
||||
});
|
||||
|
||||
test('following the clock, civil polls stop and a poll already out is dropped', async () => {
|
||||
let release;
|
||||
const probe = ingestion({
|
||||
getSnapshot: () =>
|
||||
new Promise((resolve) => {
|
||||
release = resolve;
|
||||
}),
|
||||
});
|
||||
const out = probe.methods.update(null);
|
||||
probe.state.follows = true;
|
||||
release({ records: [], observedAtMs: T, freshness: 'current' });
|
||||
await out;
|
||||
assert.equal(probe.applied.length, 0);
|
||||
await probe.methods.update(null);
|
||||
assert.equal(probe.applied.length, 0, 'no poll while following');
|
||||
});
|
||||
|
||||
test('a failed snapshot at a time reports it without holding the live backoff', async () => {
|
||||
const probe = ingestion({
|
||||
async getSnapshot() {
|
||||
throw Object.assign(new Error('nope'), { retryAfterMs: 60_000 });
|
||||
},
|
||||
});
|
||||
assert.equal(await probe.methods.loadAt(T), false);
|
||||
assert.equal(probe.feed._retryAt, 0);
|
||||
assert.equal(probe.feed._lastError, 'Live data unavailable');
|
||||
});
|
||||
|
||||
test('a jump forgets how contacts moved; clearing drops every contact', () => {
|
||||
const calls = [];
|
||||
// The contacts' icon rows.
|
||||
const icons = new Set(['abc123']);
|
||||
const flightState = {
|
||||
records: records(),
|
||||
_positionHistory: new Map([['abc123', []]]),
|
||||
_displayCourse: new Map([['abc123', 90]]),
|
||||
_groundSnap: { clear: () => calls.push('ground') },
|
||||
_displayFloorState: new Map([['abc123', {}]]),
|
||||
_drReconcileValid: true,
|
||||
_cachedDRFrame: 7,
|
||||
_icons: { ids: () => [...icons] },
|
||||
_detectionObjects: new Map([['abc123', {}]]),
|
||||
_trackedIcao: 'abc123',
|
||||
feed: { _count: 1, _lastUpdate: T },
|
||||
};
|
||||
const parts = {
|
||||
tracking: {
|
||||
_clearTrail: () => calls.push('trail'),
|
||||
_clearTracking: (_skip, { evicted }) => {
|
||||
calls.push(`untrack:${evicted}`);
|
||||
flightState._trackedIcao = null;
|
||||
},
|
||||
},
|
||||
icons: {
|
||||
// A contact's row goes, and its 3D model with it.
|
||||
_forgetContact: (id) => {
|
||||
icons.delete(id);
|
||||
calls.push(`model:${id}`);
|
||||
},
|
||||
},
|
||||
};
|
||||
const follow = createClockFollow({ flightState, parts });
|
||||
flightState.records.receive(observation(), view());
|
||||
follow.resetMotion();
|
||||
assert.equal(flightState.records.data.size, 0);
|
||||
assert.equal(flightState._positionHistory.size, 0);
|
||||
assert.equal(flightState._displayCourse.size, 0);
|
||||
assert.equal(flightState._displayFloorState.size, 0);
|
||||
assert.equal(flightState._drReconcileValid, false);
|
||||
assert.equal(icons.size, 1, 'contacts stay until replaced');
|
||||
follow.clear();
|
||||
assert.equal(icons.size, 0);
|
||||
assert.equal(flightState._detectionObjects.size, 0);
|
||||
assert.equal(flightState.feed._count, 0);
|
||||
assert.equal(flightState.feed._lastUpdate, null);
|
||||
assert.ok(calls.includes('untrack:true'));
|
||||
assert.ok(calls.includes('model:abc123'));
|
||||
});
|
||||
|
||||
test('a snapshot at a time the source drops for a newer one sets no error', async () => {
|
||||
const probe = ingestion({
|
||||
async getSnapshot() {
|
||||
throw new DOMException('Superseded', 'AbortError');
|
||||
},
|
||||
});
|
||||
await assert.rejects(probe.methods.loadAt(T), { name: 'AbortError' });
|
||||
assert.equal(probe.feed._lastError, undefined);
|
||||
assert.equal(probe.feed._backoff, undefined);
|
||||
assert.equal(probe.feed._retryAt, 0);
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import { findCamera } from '../../render/rendererOf.js';
|
||||
import { frustumPlanes, sphereOutside } from '../../geo/frustum.js';
|
||||
import { horizonFrom } from '../../geo/horizon.js';
|
||||
import { distanceSquared, vec } from '../../geo/vector.js';
|
||||
import { parsePlanespottersPhoto } from '../../data/planespottersPhoto.js';
|
||||
import {
|
||||
ENRICH_MAX_INFLIGHT,
|
||||
ENRICH_DISPATCH_GAP_MS,
|
||||
@@ -10,6 +11,7 @@ import {
|
||||
ENRICH_AMBIENT_REFILL_TOKENS,
|
||||
ENRICH_AMBIENT_REFILL_WINDOW_MS,
|
||||
ENRICH_AMBIENT_PER_SWEEP,
|
||||
ENRICH_RETRY_COOLDOWN_MS,
|
||||
} from './policy.js';
|
||||
|
||||
/** A contact counts as on screen while a sphere this big around it is (m). */
|
||||
@@ -22,11 +24,62 @@ export function createEnrichment({
|
||||
layer,
|
||||
resolveAsset,
|
||||
}) {
|
||||
function _enqueueEnrich(key, query, onData, priority = false) {
|
||||
const { isMilitaryIcao } = services.militaryRegistry;
|
||||
const { isTr3b } = services.aircraftPresentation;
|
||||
/**
|
||||
* Whether `key` is answered, queued, or cooling down after a failure. A
|
||||
* key past its cool-down is released here so it can be asked again.
|
||||
* @param {string} key Lookup key.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function _enrichHeld(key) {
|
||||
if (flightState._enrichSeen.has(key)) return true;
|
||||
const retryAfter = flightState._enrichRetryAfter.get(key);
|
||||
if (retryAfter === undefined) return false;
|
||||
if (Date.now() < retryAfter) return true;
|
||||
flightState._enrichRetryAfter.delete(key);
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a source failure is permanent: an unsupported lookup, or an HTTP
|
||||
* 4xx other than 401/403 (an authorization refusal that may clear), 408
|
||||
* (timeout) and 429 (rate limited). Anything else, including an error without a
|
||||
* status, is temporary.
|
||||
* @param {*} error The rejection, as `LiveSourceError` / `httpError` carry it.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function _enrichFailureIsFinal(error) {
|
||||
if (error?.code === 'unsupported') return true;
|
||||
const status = Number(error?.status);
|
||||
return (
|
||||
Number.isInteger(status) &&
|
||||
status >= 400 &&
|
||||
status < 500 &&
|
||||
status !== 401 &&
|
||||
status !== 403 &&
|
||||
status !== 408 &&
|
||||
status !== 429
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ask each key at most once per session, except that a lookup whose source
|
||||
* failed temporarily (rejected or threw) may be asked again after
|
||||
* ENRICH_RETRY_COOLDOWN_MS; an answer, found or not, and a permanent
|
||||
* refusal (see _enrichFailureIsFinal) are final.
|
||||
* @param {string} key Session-unique lookup key.
|
||||
* @param {object} query The source's enrichment query.
|
||||
* @param {function(object):void} onData Receives a `found` answer.
|
||||
* @param {boolean} [priority] Front of the queue.
|
||||
* @param {function(*):?object} [read] Reads the source's answer first, for
|
||||
* a lookup whose answer may arrive in more than one shape.
|
||||
*/
|
||||
function _enqueueEnrich(key, query, onData, priority = false, read = null) {
|
||||
if (flightState.lifetime.signal.aborted) return;
|
||||
if (flightState._enrichSeen.has(key)) return;
|
||||
if (_enrichHeld(key)) return;
|
||||
flightState._enrichSeen.add(key);
|
||||
const job = { query, onData };
|
||||
const job = { key, query, onData, read };
|
||||
// Priority (tracked / model-eligible) goes to the FRONT so a deep ambient
|
||||
// backlog can never delay the plane the user just clicked or zoomed into.
|
||||
if (priority) flightState._enrichQueue.unshift(job);
|
||||
@@ -66,9 +119,24 @@ export function createEnrichment({
|
||||
signal: lifetime.signal,
|
||||
});
|
||||
})
|
||||
.then((data) => {
|
||||
if (!lifetime.signal.aborted && data && data.found) job.onData(data);
|
||||
})
|
||||
.then(
|
||||
(answer) => {
|
||||
const data = job.read ? job.read(answer) : answer;
|
||||
if (!lifetime.signal.aborted && data && data.found)
|
||||
job.onData(data);
|
||||
},
|
||||
(error) => {
|
||||
// The source failed: release the key after a cool-down. A layer
|
||||
// teardown is not a failure and schedules nothing, and a
|
||||
// permanent refusal is as final as an answer.
|
||||
if (lifetime.signal.aborted || _enrichFailureIsFinal(error)) return;
|
||||
flightState._enrichSeen.delete(job.key);
|
||||
flightState._enrichRetryAfter.set(
|
||||
job.key,
|
||||
Date.now() + ENRICH_RETRY_COOLDOWN_MS,
|
||||
);
|
||||
},
|
||||
)
|
||||
.catch(() => {
|
||||
/* enrichment never surfaces errors */
|
||||
})
|
||||
@@ -122,6 +190,14 @@ export function createEnrichment({
|
||||
(data) => {
|
||||
const meta = flightState.records.data.get(icao24);
|
||||
if (!meta) return;
|
||||
// A late answer for a callsign the plane no longer flies is dropped.
|
||||
if (
|
||||
String(meta.callsign || '')
|
||||
.trim()
|
||||
.toUpperCase() !== cs
|
||||
)
|
||||
return;
|
||||
meta.routeCallsign = cs;
|
||||
meta.airline = data.airline || meta.airline;
|
||||
if (data.origin && data.destination)
|
||||
meta.route = { origin: data.origin, destination: data.destination };
|
||||
@@ -132,6 +208,31 @@ export function createEnrichment({
|
||||
); // route lookups only fire for the TRACKED plane — front of the queue
|
||||
}
|
||||
|
||||
/** The tracked plane's photo from Planespotters, asked once per hex at the
|
||||
* front of the queue like its route. A miss is final; a temporary failure
|
||||
* is asked again after the cool-down. A military aircraft or a converted
|
||||
* TR-3B is never looked up. The answer is read with
|
||||
* `parsePlanespottersPhoto` whatever shape the source returns (the upstream
|
||||
* answer, a server's cached shape, or an already-read photo), so only a
|
||||
* checked photo is ever stored. */
|
||||
function _requestPhotoEnrichment(icao24) {
|
||||
if (!/^[0-9a-f]{6}$/i.test(icao24)) return;
|
||||
const id = icao24.toLowerCase();
|
||||
if (isMilitaryIcao(id) || isTr3b(id)) return;
|
||||
_enqueueEnrich(
|
||||
`p:${id}`,
|
||||
{ kind: 'photo', id },
|
||||
(data) => {
|
||||
const meta = flightState.records.data.get(id);
|
||||
if (!meta) return; // evicted while the lookup was in flight
|
||||
const { src, width, height, photographer, link } = data;
|
||||
meta.photo = { src, width, height, photographer, link };
|
||||
},
|
||||
true,
|
||||
parsePlanespottersPhoto,
|
||||
);
|
||||
}
|
||||
|
||||
/** QA seam: headless harnesses (scripts/qa-enrich-ambient.mjs) shrink the
|
||||
* bucket knobs via window.__GEV_ENRICH_AMBIENT_QA = {ceil, refillTokens,
|
||||
* windowMs} — they cannot wait out a real 5-minute window. Read lazily each
|
||||
@@ -200,7 +301,9 @@ export function createEnrichment({
|
||||
const icons = flightState._icons;
|
||||
const t = parts.icons._displayMs();
|
||||
for (const icao24 of icons.ids()) {
|
||||
if (flightState._enrichSeen.has(`t:${icao24}`)) continue; // answered / queued / negative this session
|
||||
// Answered, queued, negative this session, or cooling down after a
|
||||
// failure: never spend a token on it.
|
||||
if (_enrichHeld(`t:${icao24}`)) continue;
|
||||
if (!/^[0-9a-f]{6}$/i.test(icao24)) continue; // adsbdb keys are 6-char hex only
|
||||
if (flightState.records.data.get(icao24)?.onGround) continue; // ground traffic never spends ambient budget (click-to-enrich still works)
|
||||
if (!icons.position(icao24, t, position)) continue;
|
||||
@@ -227,6 +330,7 @@ export function createEnrichment({
|
||||
_drainEnrich,
|
||||
_requestTypeEnrichment,
|
||||
_requestRouteEnrichment,
|
||||
_requestPhotoEnrichment,
|
||||
_ambientBudgetKnobs,
|
||||
_refillAmbientBudget,
|
||||
_sweepAmbientEnrichment,
|
||||
|
||||
@@ -8,6 +8,8 @@ import {
|
||||
FLOOR_FAR_EVERY_TICKS,
|
||||
FLOOR_NEAR_M,
|
||||
RENDER_DELAY_SEC,
|
||||
STALE_ALPHA,
|
||||
followsClock,
|
||||
} from './policy.js';
|
||||
|
||||
/** Pinned grounded rows rewrite only past this displayed move (m²) or turn (°). */
|
||||
@@ -26,6 +28,8 @@ export function createIcons({ flightState, services, parts }) {
|
||||
parts,
|
||||
layerId: 'flights',
|
||||
renderDelaySec: RENDER_DELAY_SEC,
|
||||
followsClock: () => followsClock(flightState),
|
||||
staleAlpha: STALE_ALPHA,
|
||||
courseMaxDps: COURSE_MAX_DPS,
|
||||
cockpitContactSizePx: COCKPIT_CONTACT_SIZE_PX,
|
||||
holdsPlan: (icao24) =>
|
||||
|
||||
@@ -11,6 +11,9 @@ import { createLifecycle } from './lifecycle.js';
|
||||
import { createEvidence } from './evidence.js';
|
||||
import { createTesting } from './testing.js';
|
||||
import { createQueries } from './queries.js';
|
||||
import { createClockFollow } from './clockFollow.js';
|
||||
import { createSnapshotTimeline } from '../../time/snapshotTimeline.js';
|
||||
import { worldClock } from '../../time/worldClock.js';
|
||||
/** Compose one civil-flight layer with application-owned scene services. */
|
||||
export function createCivilFlightLayer({
|
||||
source,
|
||||
@@ -31,6 +34,7 @@ export function createCivilFlightLayer({
|
||||
parts.evidence = createEvidence(context);
|
||||
parts.testing = createTesting(context);
|
||||
parts.queries = createQueries(context);
|
||||
parts.clockFollow = createClockFollow(context);
|
||||
const applySnapshot = createFlightSnapshotRenderer({
|
||||
flightState,
|
||||
records: flightState.records,
|
||||
@@ -47,7 +51,11 @@ export function createCivilFlightLayer({
|
||||
feed: flightState.feed,
|
||||
getQuery: (viewer) =>
|
||||
parts.controller._flightQuery(viewer || flightState._viewer),
|
||||
applySnapshot,
|
||||
applySnapshot: (snapshot, viewer, options) => {
|
||||
if (options?.replace) parts.clockFollow.resetMotion();
|
||||
return applySnapshot(snapshot, viewer, options);
|
||||
},
|
||||
followsClock: () => flightState.timeline.active(),
|
||||
setSourceLabel: (source) => {
|
||||
layer.source = source;
|
||||
},
|
||||
@@ -55,6 +63,19 @@ export function createCivilFlightLayer({
|
||||
parts.tracking._applyPendingTrackingRestore(),
|
||||
});
|
||||
|
||||
// Contacts follow the world clock while the source declares a timeline.
|
||||
flightState.timeline = createSnapshotTimeline({
|
||||
id: 'flights',
|
||||
clock: worldClock,
|
||||
source: () => flightState.feed._source,
|
||||
load: (atMs, { signal, replace }) =>
|
||||
parts.ingestion.methods.loadAt(atMs, { signal, replace }),
|
||||
clear: () => parts.clockFollow.clear(),
|
||||
resumeLive: () => {
|
||||
layer.update(flightState._viewer).catch(() => {});
|
||||
},
|
||||
});
|
||||
|
||||
Object.assign(
|
||||
layer,
|
||||
parts.queries.methods,
|
||||
|
||||
+101
-67
@@ -11,85 +11,119 @@ export function createIngestion({
|
||||
applySnapshot,
|
||||
setSourceLabel,
|
||||
applyPendingTrackingRestore,
|
||||
followsClock = () => false,
|
||||
}) {
|
||||
const methods = {
|
||||
async update(viewer, { signal = null } = {}) {
|
||||
const nowMs = Date.now();
|
||||
const trackingRefreshEpoch = ++feed._trackingRefreshEpoch;
|
||||
// Following the world clock, the layer shows the snapshots loadAt
|
||||
// applies; polling the live feed would put the live edge among them.
|
||||
if (followsClock()) return;
|
||||
await acquire(viewer, { signal });
|
||||
},
|
||||
|
||||
/**
|
||||
* Apply the source's snapshot at world time `atMs` (its timeline says it
|
||||
* can answer one), in place of every contact when `replace`. Resolves
|
||||
* whether it was applied.
|
||||
* @param {number} atMs
|
||||
* @param {{signal?: AbortSignal|null, replace?: boolean, viewer?: object}} [options]
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
async loadAt(atMs, { signal = null, replace = false, viewer = null } = {}) {
|
||||
// Whatever polls or loads for another time no longer applies.
|
||||
if (replace)
|
||||
for (const controller of feed._activeUpdateControllers)
|
||||
controller.abort();
|
||||
return acquire(viewer, { signal, atMs, replace });
|
||||
},
|
||||
};
|
||||
|
||||
async function acquire(viewer, { signal = null, atMs, replace = false }) {
|
||||
const nowMs = Date.now();
|
||||
const timed = atMs !== undefined;
|
||||
const trackingRefreshEpoch = ++feed._trackingRefreshEpoch;
|
||||
feed._lastTrackingRefreshOutcome = {
|
||||
epoch: trackingRefreshEpoch,
|
||||
status: 'source-unavailable',
|
||||
ids: new Set(),
|
||||
source: feed._lastSource,
|
||||
coverage: feed._lastCoverage,
|
||||
};
|
||||
if (!timed && feed._retryAt && nowMs < feed._retryAt) {
|
||||
feed._backoff = true;
|
||||
return;
|
||||
}
|
||||
|
||||
const resourceController = new AbortController();
|
||||
feed._activeUpdateControllers.add(resourceController);
|
||||
const updateSignal = signal
|
||||
? AbortSignal.any([signal, resourceController.signal])
|
||||
: resourceController.signal;
|
||||
try {
|
||||
updateSignal.throwIfAborted();
|
||||
const query = timed ? { ...getQuery(viewer), atMs } : getQuery(viewer);
|
||||
const snapshot = await feed._source.getSnapshot(query, {
|
||||
signal: updateSignal,
|
||||
});
|
||||
updateSignal.throwIfAborted();
|
||||
// The clock left the live edge while this poll was out.
|
||||
if (!timed && followsClock()) return;
|
||||
feed._lastStatus = snapshot.status ?? 200;
|
||||
const sourceEpochMs = snapshot.observedAtMs;
|
||||
const sourceAgeMs = snapshot.ageMs;
|
||||
const sourceStale = snapshot.stale || snapshot.freshness === 'unknown';
|
||||
feed._backoff = sourceStale;
|
||||
feed._retryAt = 0;
|
||||
// i18n-ignore: English data; the panel shows it through FEED_ERROR_PATTERNS (ui/statusText.js)
|
||||
feed._lastError = sourceStale
|
||||
? sourceAgeMs == null
|
||||
? msg('Source snapshot time unavailable')
|
||||
: `Source snapshot ${Math.max(2, Math.round(sourceAgeMs / 60_000))} min old`
|
||||
: null;
|
||||
feed._lastSource = snapshot.source;
|
||||
feed._lastCoverage = snapshot.coverage;
|
||||
setSourceLabel(feed._lastSource);
|
||||
const accepted = timed
|
||||
? applySnapshot(snapshot, viewer, { replace })
|
||||
: applySnapshot(snapshot, viewer);
|
||||
feed._count = accepted.count;
|
||||
// Freshness belongs to the source snapshot, not the moment this browser
|
||||
// received a cached 200 response.
|
||||
feed._lastUpdate = sourceEpochMs;
|
||||
feed._lastTrackingRefreshOutcome = {
|
||||
epoch: trackingRefreshEpoch,
|
||||
status: 'source-unavailable',
|
||||
ids: new Set(),
|
||||
status: 'accepted',
|
||||
ids: accepted.ids,
|
||||
source: feed._lastSource,
|
||||
coverage: feed._lastCoverage,
|
||||
};
|
||||
if (feed._retryAt && nowMs < feed._retryAt) {
|
||||
feed._backoff = true;
|
||||
return;
|
||||
console.log(`[Data:Flights] Updated: ${feed._count} aircraft`);
|
||||
applyPendingTrackingRestore();
|
||||
return true;
|
||||
} catch (e) {
|
||||
if (updateSignal.aborted || e?.name === 'AbortError') {
|
||||
throw new DOMException('Flights update aborted', 'AbortError');
|
||||
}
|
||||
|
||||
const resourceController = new AbortController();
|
||||
feed._activeUpdateControllers.add(resourceController);
|
||||
const updateSignal = signal
|
||||
? AbortSignal.any([signal, resourceController.signal])
|
||||
: resourceController.signal;
|
||||
try {
|
||||
updateSignal.throwIfAborted();
|
||||
const snapshot = await feed._source.getSnapshot(getQuery(viewer), {
|
||||
signal: updateSignal,
|
||||
});
|
||||
updateSignal.throwIfAborted();
|
||||
feed._lastStatus = snapshot.status ?? 200;
|
||||
const sourceEpochMs = snapshot.observedAtMs;
|
||||
const sourceAgeMs = snapshot.ageMs;
|
||||
const sourceStale = snapshot.stale || snapshot.freshness === 'unknown';
|
||||
feed._backoff = sourceStale;
|
||||
feed._retryAt = 0;
|
||||
// i18n-ignore: English data; the panel shows it through FEED_ERROR_PATTERNS (ui/statusText.js)
|
||||
feed._lastError = sourceStale
|
||||
? sourceAgeMs == null
|
||||
? msg('Source snapshot time unavailable')
|
||||
: `Source snapshot ${Math.max(2, Math.round(sourceAgeMs / 60_000))} min old`
|
||||
: null;
|
||||
feed._lastSource = snapshot.source;
|
||||
feed._lastCoverage = snapshot.coverage;
|
||||
setSourceLabel(feed._lastSource);
|
||||
const accepted = applySnapshot(snapshot, viewer);
|
||||
feed._count = accepted.count;
|
||||
// Freshness belongs to the source snapshot, not the moment this browser
|
||||
// received a cached 200 response.
|
||||
feed._lastUpdate = sourceEpochMs;
|
||||
feed._lastTrackingRefreshOutcome = {
|
||||
epoch: trackingRefreshEpoch,
|
||||
status: 'accepted',
|
||||
ids: accepted.ids,
|
||||
source: feed._lastSource,
|
||||
coverage: feed._lastCoverage,
|
||||
};
|
||||
console.log(`[Data:Flights] Updated: ${feed._count} aircraft`);
|
||||
applyPendingTrackingRestore();
|
||||
} catch (e) {
|
||||
if (updateSignal.aborted || e?.name === 'AbortError') {
|
||||
throw new DOMException('Flights update aborted', 'AbortError');
|
||||
}
|
||||
console.warn('[Data:Flights] Fetch error:', e);
|
||||
feed._backoff = true;
|
||||
console.warn('[Data:Flights] Fetch error:', e);
|
||||
feed._backoff = true;
|
||||
// A snapshot at a time is asked again by the clock's follower.
|
||||
if (!timed)
|
||||
feed._retryAt =
|
||||
Date.now() + (e?.retryAfterMs ?? ERROR_BACKOFF_INTERVAL);
|
||||
feed._lastStatus = e?.status ?? null;
|
||||
if (e?.source) {
|
||||
feed._lastSource = e.source;
|
||||
setSourceLabel(feed._lastSource);
|
||||
}
|
||||
feed._lastError =
|
||||
e?.name === 'LiveSourceError'
|
||||
? e.message
|
||||
: msg('Live data unavailable');
|
||||
} finally {
|
||||
feed._activeUpdateControllers.delete(resourceController);
|
||||
feed._lastStatus = e?.status ?? null;
|
||||
if (e?.source) {
|
||||
feed._lastSource = e.source;
|
||||
setSourceLabel(feed._lastSource);
|
||||
}
|
||||
},
|
||||
};
|
||||
feed._lastError =
|
||||
e?.name === 'LiveSourceError'
|
||||
? e.message
|
||||
: msg('Live data unavailable');
|
||||
return false;
|
||||
} finally {
|
||||
feed._activeUpdateControllers.delete(resourceController);
|
||||
}
|
||||
}
|
||||
|
||||
return { methods };
|
||||
}
|
||||
|
||||
@@ -148,6 +148,7 @@ export function createLifecycle({
|
||||
flightState._lastFleetTickMs = 0;
|
||||
});
|
||||
}
|
||||
flightState.timeline?.start();
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -156,6 +157,7 @@ export function createLifecycle({
|
||||
* @param {object} viewer
|
||||
*/
|
||||
disable(viewer) {
|
||||
flightState.timeline?.stop();
|
||||
parts.controller._abortActiveUpdates();
|
||||
parts.tracking._cancelPendingTrackingRestore();
|
||||
if (flightState._icons) flightState._icons.show = false;
|
||||
@@ -194,6 +196,7 @@ export function createLifecycle({
|
||||
* @param {object} viewer
|
||||
*/
|
||||
destroy(viewer) {
|
||||
flightState.timeline?.stop();
|
||||
flightState.lifetime.abort();
|
||||
flightState._enrichActive = 0;
|
||||
flightState._enrichLastDispatchMs = 0;
|
||||
@@ -248,6 +251,7 @@ export function createLifecycle({
|
||||
flightState._displayFloorState.clear();
|
||||
flightState._enrichQueue.length = 0;
|
||||
flightState._enrichSeen.clear();
|
||||
flightState._enrichRetryAfter.clear();
|
||||
if (flightState._enrichDripTimer) {
|
||||
clearTimeout(flightState._enrichDripTimer);
|
||||
flightState._enrichDripTimer = null;
|
||||
|
||||
@@ -27,6 +27,8 @@ import {
|
||||
import {
|
||||
COURSE_HOLD_SPEED_MPS,
|
||||
lerpAngleDeg,
|
||||
floorCoastedPosition,
|
||||
staleHoldsForFix,
|
||||
arcOffsetEnu,
|
||||
courseSlewCapDps,
|
||||
limitCourseStep,
|
||||
@@ -39,7 +41,6 @@ import {
|
||||
} from '../../data/modelVisualAnchor.js';
|
||||
import {
|
||||
FOCUS_EVIDENCE_DEV,
|
||||
RENDER_DELAY_SEC,
|
||||
TRACKED_MODEL_MAX_PX,
|
||||
TRACKED_MODEL_MIN_PX,
|
||||
TRACKED_BILLBOARD_SCALE_BY_DISTANCE,
|
||||
@@ -56,6 +57,8 @@ import {
|
||||
DISPLAY_CORRIDOR_LOOKAHEAD_SEC,
|
||||
DISPLAY_CORRIDOR_CELL_BUDGET,
|
||||
DISPLAY_CORRIDOR_FAIR_SHARE,
|
||||
displayDelayMs,
|
||||
followsClock,
|
||||
} from './policy.js';
|
||||
import { readEntityRecord } from '../../data/entityRecords.js';
|
||||
import {
|
||||
@@ -68,6 +71,7 @@ import {
|
||||
julianAt,
|
||||
fixSpeedMps,
|
||||
fixTrackDeg,
|
||||
staleCoastSeconds,
|
||||
} from '../../data/aircraftMotionRegime.js';
|
||||
|
||||
/** Whether two ECEF points are the same point, component for component. */
|
||||
@@ -226,7 +230,7 @@ export function createMotion({
|
||||
sampledRenderTime ??
|
||||
addSeconds(
|
||||
julianFromEpochMs(flightState.now(), flightState._scratchRenderTime),
|
||||
-RENDER_DELAY_SEC,
|
||||
-displayDelayMs(flightState) / 1000,
|
||||
flightState._scratchRenderTime,
|
||||
);
|
||||
|
||||
@@ -249,7 +253,9 @@ export function createMotion({
|
||||
regime.minDt,
|
||||
regime.maxDt,
|
||||
);
|
||||
return _extrapolateFix(regime.fix, info, dt, out, regime.turnRateDps);
|
||||
_extrapolateFix(regime.fix, info, dt, out, regime.turnRateDps);
|
||||
// A coast never goes below the ground.
|
||||
return dt > 0 ? floorCoastedPosition(out, cachedGroundFloor) : out;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -265,9 +271,38 @@ export function createMotion({
|
||||
renderTime,
|
||||
RECORD_FIELDS,
|
||||
regime,
|
||||
{ cachedGroundFloor },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a contact has stopped where its coast ended (or held at its last
|
||||
* report) with no newer report, and since when it has had none.
|
||||
* @param {string} icao24
|
||||
* @returns {{reportEpochMs: number, holds: boolean}|null} Null while a
|
||||
* report is ahead of the display time or the contact is still coasting.
|
||||
*/
|
||||
function _signalLost(icao24) {
|
||||
const newest = flightState._positionHistory.get(icao24)?.at(-1);
|
||||
if (!newest) return null;
|
||||
const newestMs = fixEpochMs(newest);
|
||||
const elapsedSec =
|
||||
(flightState.now() - displayDelayMs(flightState) - newestMs) / 1000;
|
||||
if (!(elapsedSec > 0)) return null;
|
||||
const info = flightState.records.data.get(icao24);
|
||||
const coastSec = staleCoastSeconds(newest, info, cachedGroundFloor);
|
||||
if (!(elapsedSec > coastSec)) return null;
|
||||
return {
|
||||
reportEpochMs: Number.isFinite(newest.reportEpochMs)
|
||||
? newest.reportEpochMs
|
||||
: newestMs,
|
||||
holds: staleHoldsForFix(newest, {
|
||||
onGround: info?.onGround,
|
||||
cachedGroundFloor,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Dead-reckon a fix along its own velocity/track by `dt` seconds, integrating a
|
||||
* constant-rate-turn arc when `turnRateDps` is significant (straight line
|
||||
@@ -323,7 +358,7 @@ export function createMotion({
|
||||
if (!history || history.length === 0) return true;
|
||||
const renderTime = addSeconds(
|
||||
julianFromEpochMs(flightState.now()),
|
||||
-RENDER_DELAY_SEC,
|
||||
-displayDelayMs(flightState) / 1000,
|
||||
flightState._scratchWarmupTime,
|
||||
);
|
||||
return julianLessThan(renderTime, history[0].time);
|
||||
@@ -404,9 +439,15 @@ export function createMotion({
|
||||
}
|
||||
|
||||
const nowMs = Date.now();
|
||||
// How far the contact may move between frames goes by the world's time,
|
||||
// which plays faster than the wall clock when following it at a rate.
|
||||
const worldMs = followsClock(flightState) ? flightState.now() : nowMs;
|
||||
const info = flightState.records.data.get(icao24);
|
||||
if (sameTrack) {
|
||||
const dtSec = Math.max(0.001, (nowMs - flightState._drPrevMs) / 1000);
|
||||
const dtSec = Math.max(
|
||||
0.001,
|
||||
(worldMs - flightState._drPrevWorldMs) / 1000,
|
||||
);
|
||||
const speed = (info && info.velocity) || 0;
|
||||
// Plausible single-frame motion (m): real velocity × frame Δt, ×4 slack + 25 m base.
|
||||
const plausible = speed * dtSec * 4 + 25;
|
||||
@@ -451,6 +492,7 @@ export function createMotion({
|
||||
copyInto(raw, flightState._drPrevRaw);
|
||||
copyInto(display, flightState._drPrevDisplay);
|
||||
flightState._drPrevMs = nowMs;
|
||||
flightState._drPrevWorldMs = worldMs;
|
||||
flightState._drReconcileValid = true;
|
||||
flightState._cachedDRPosition = display;
|
||||
const focusSizePx = _trackedFocusSizePx(
|
||||
@@ -1093,6 +1135,7 @@ export function createMotion({
|
||||
_copyPosition: copyPosition,
|
||||
_historyFix: historyFix,
|
||||
_motionRegime,
|
||||
_signalLost,
|
||||
_extrapolateFix,
|
||||
_isTrackWarmingUp,
|
||||
_trackedFocusSizePx,
|
||||
|
||||
@@ -4,6 +4,7 @@ import { createCivilFlightLayer } from './index.js';
|
||||
import { createFlightState } from './state.js';
|
||||
import { createEnrichment } from './enrichment.js';
|
||||
import { createTracking } from './tracking.js';
|
||||
import { LiveSourceError } from '../../sources/live/contract.js';
|
||||
|
||||
function services() {
|
||||
const names = [
|
||||
@@ -29,6 +30,14 @@ function services() {
|
||||
};
|
||||
}
|
||||
|
||||
/** The services enrichment reads: which hexes are military or a TR-3B. */
|
||||
function enrichServices({ military = [], tr3b = [] } = {}) {
|
||||
return {
|
||||
militaryRegistry: { isMilitaryIcao: (id) => military.includes(id) },
|
||||
aircraftPresentation: { isTr3b: (id) => tr3b.includes(id) },
|
||||
};
|
||||
}
|
||||
|
||||
test('constructing independent flight layers performs no source request and isolates selection', () => {
|
||||
let requests = 0;
|
||||
const source = {
|
||||
@@ -91,7 +100,11 @@ test('aborted enrichment cannot write into a later lifecycle or decrement its ac
|
||||
},
|
||||
};
|
||||
const flightState = createFlightState({ source, services: services() });
|
||||
const enrichment = createEnrichment({ flightState, services: {}, parts: {} });
|
||||
const enrichment = createEnrichment({
|
||||
flightState,
|
||||
services: enrichServices(),
|
||||
parts: {},
|
||||
});
|
||||
let writes = 0;
|
||||
enrichment._enqueueEnrich(
|
||||
'test',
|
||||
@@ -119,7 +132,11 @@ test('a synchronous enrichment failure stays bounded and releases its slot', asy
|
||||
},
|
||||
},
|
||||
});
|
||||
const enrichment = createEnrichment({ flightState, services: {}, parts: {} });
|
||||
const enrichment = createEnrichment({
|
||||
flightState,
|
||||
services: enrichServices(),
|
||||
parts: {},
|
||||
});
|
||||
assert.doesNotThrow(() =>
|
||||
enrichment._enqueueEnrich('test', {}, () => assert.fail()),
|
||||
);
|
||||
@@ -180,25 +197,28 @@ test('the tracked trail head is drawn each frame while tracked and stops with th
|
||||
const viewer = { isDestroyed: () => false };
|
||||
const { draw, unbind } = bindFakeDraw(viewer, { frame });
|
||||
const at = (lon) => Cesium.Cartesian3.fromDegrees(lon, 0, 1000);
|
||||
const old = Cesium.JulianDate.addSeconds(
|
||||
Cesium.JulianDate.now(),
|
||||
-600,
|
||||
new Cesium.JulianDate(),
|
||||
);
|
||||
// Three reports ten seconds apart, ten minutes ago.
|
||||
const reportAt = (i) => {
|
||||
const epochMs = Date.now() - 600_000 + i * 10_000;
|
||||
return { epochMs, time: Cesium.JulianDate.fromDate(new Date(epochMs)) };
|
||||
};
|
||||
let headLon = 0.03;
|
||||
const flightState = {
|
||||
now: Date.now,
|
||||
_viewer: viewer,
|
||||
_trackedIcao: 'abc123',
|
||||
_trail: null,
|
||||
_trailPositions: [],
|
||||
_trailFixes: [],
|
||||
_trailBackfillToken: 0,
|
||||
_trailHeadOff: null,
|
||||
_cockpitContactMode: false,
|
||||
_positionHistory: new Map([
|
||||
[
|
||||
'abc123',
|
||||
[0, 0.01, 0.02].map((lon) => ({ time: old, position: at(lon) })),
|
||||
[0, 0.01, 0.02].map((lon, i) => ({
|
||||
...reportAt(i),
|
||||
position: at(lon),
|
||||
})),
|
||||
],
|
||||
]),
|
||||
_scratchWarmupTime: new Cesium.JulianDate(),
|
||||
@@ -255,3 +275,336 @@ test('the tracked trail head is drawn each frame while tracked and stops with th
|
||||
unbind();
|
||||
}
|
||||
});
|
||||
|
||||
test('the tracked plane’s photo is asked once per hex and lands on its record', async () => {
|
||||
const queries = [];
|
||||
let answer = {
|
||||
found: true,
|
||||
src: 'https://t.plnspttrs.net/33043/1745410_822dfe330c_280.jpg',
|
||||
width: 420,
|
||||
height: 280,
|
||||
photographer: 'Jan Seler',
|
||||
link: 'https://www.planespotters.net/photo/1745410/x?utm_source=api',
|
||||
};
|
||||
const flightState = createFlightState({
|
||||
services: services(),
|
||||
source: {
|
||||
async getEnrichment(query) {
|
||||
queries.push(query);
|
||||
if (answer instanceof Error) throw answer;
|
||||
return answer;
|
||||
},
|
||||
},
|
||||
});
|
||||
const enrichment = createEnrichment({
|
||||
flightState,
|
||||
services: enrichServices(),
|
||||
parts: {},
|
||||
});
|
||||
flightState.records.data.set('a0f1bb', { callsign: 'AAL1' });
|
||||
flightState._trackedIcao = 'a0f1bb';
|
||||
flightState._trackedEntity = {};
|
||||
enrichment._requestPhotoEnrichment('A0F1BB');
|
||||
enrichment._requestPhotoEnrichment('a0f1bb');
|
||||
await new Promise((done) => setImmediate(done));
|
||||
assert.deepEqual(queries, [{ kind: 'photo', id: 'a0f1bb' }]);
|
||||
assert.deepEqual(flightState.records.data.get('a0f1bb').photo, {
|
||||
src: answer.src,
|
||||
width: 420,
|
||||
height: 280,
|
||||
photographer: 'Jan Seler',
|
||||
link: answer.link,
|
||||
});
|
||||
|
||||
// A failure is not asked again within its cool-down.
|
||||
answer = new Error('outage');
|
||||
flightState.records.data.set('abc123', {});
|
||||
enrichment._requestPhotoEnrichment('abc123');
|
||||
await new Promise((done) => setTimeout(done, 300));
|
||||
enrichment._requestPhotoEnrichment('abc123');
|
||||
await new Promise((done) => setImmediate(done));
|
||||
assert.equal(queries.length, 2);
|
||||
assert.equal(flightState.records.data.get('abc123').photo, undefined);
|
||||
enrichment._requestPhotoEnrichment('not-hex');
|
||||
assert.equal(queries.length, 2);
|
||||
flightState.lifetime.abort();
|
||||
});
|
||||
|
||||
test('a military aircraft or a converted TR-3B is never looked up for a photo', async () => {
|
||||
const queries = [];
|
||||
const flightState = createFlightState({
|
||||
services: services(),
|
||||
source: {
|
||||
async getEnrichment(query) {
|
||||
queries.push(query);
|
||||
return { found: false };
|
||||
},
|
||||
},
|
||||
});
|
||||
const enrichment = createEnrichment({
|
||||
flightState,
|
||||
services: enrichServices({ military: ['ae1234'], tr3b: ['a0f1bb'] }),
|
||||
parts: {},
|
||||
});
|
||||
for (const id of ['ae1234', 'a0f1bb']) {
|
||||
flightState.records.data.set(id, {});
|
||||
enrichment._requestPhotoEnrichment(id);
|
||||
}
|
||||
enrichment._requestPhotoEnrichment('AE1234');
|
||||
await new Promise((done) => setImmediate(done));
|
||||
assert.deepEqual(queries, []);
|
||||
assert.equal(flightState._enrichSeen.size, 0);
|
||||
flightState.lifetime.abort();
|
||||
});
|
||||
|
||||
test('a photo answer in the upstream shape or a server’s cached shape lands checked', async () => {
|
||||
const SRC = 'https://t.plnspttrs.net/33043/1745410_822dfe330c_280.jpg';
|
||||
const LINK = 'https://www.planespotters.net/photo/1745410/x?utm_source=api';
|
||||
const answers = {
|
||||
a0f1bb: {
|
||||
photos: [
|
||||
{
|
||||
thumbnail_large: { src: SRC, size: { width: 420, height: 280 } },
|
||||
link: LINK,
|
||||
photographer: 'Jan Seler',
|
||||
},
|
||||
],
|
||||
},
|
||||
abc123: {
|
||||
found: true,
|
||||
thumbnail: { src: SRC, width: 420, height: 280 },
|
||||
photographer: 'Jan Seler',
|
||||
link: LINK,
|
||||
},
|
||||
def456: {
|
||||
found: true,
|
||||
thumbnail: { src: 'https://evil.example/a.jpg', width: 1, height: 1 },
|
||||
photographer: 'Jan Seler',
|
||||
link: LINK,
|
||||
},
|
||||
fed789: { photos: [] },
|
||||
};
|
||||
const flightState = createFlightState({
|
||||
services: services(),
|
||||
source: { getEnrichment: async ({ id }) => answers[id] },
|
||||
});
|
||||
const enrichment = createEnrichment({
|
||||
flightState,
|
||||
services: enrichServices(),
|
||||
parts: {},
|
||||
});
|
||||
const ids = Object.keys(answers);
|
||||
for (const id of ids) flightState.records.data.set(id, {});
|
||||
for (const id of ids) {
|
||||
enrichment._requestPhotoEnrichment(id);
|
||||
// One dispatch per drip gap.
|
||||
await new Promise((done) => setTimeout(done, 250));
|
||||
}
|
||||
const photo = {
|
||||
src: SRC,
|
||||
width: 420,
|
||||
height: 280,
|
||||
photographer: 'Jan Seler',
|
||||
link: LINK,
|
||||
};
|
||||
assert.deepEqual(flightState.records.data.get('a0f1bb').photo, photo);
|
||||
assert.deepEqual(flightState.records.data.get('abc123').photo, photo);
|
||||
assert.equal(flightState.records.data.get('def456').photo, undefined);
|
||||
assert.equal(flightState.records.data.get('fed789').photo, undefined);
|
||||
flightState.lifetime.abort();
|
||||
});
|
||||
|
||||
/** An enrichment queue over `answer(query)` with a hand-driven clock. */
|
||||
function enrichmentClock(t, answer) {
|
||||
let now = 1_000_000;
|
||||
t.mock.method(Date, 'now', () => now);
|
||||
const queries = [];
|
||||
const flightState = createFlightState({
|
||||
services: services(),
|
||||
source: {
|
||||
getEnrichment(query) {
|
||||
queries.push(query.id);
|
||||
return answer(query);
|
||||
},
|
||||
},
|
||||
});
|
||||
const enrichment = createEnrichment({
|
||||
flightState,
|
||||
services: enrichServices(),
|
||||
parts: { tracking: { _updateTrackedLabelModel() {} } },
|
||||
});
|
||||
const settle = () => new Promise((done) => setImmediate(done));
|
||||
const advance = (ms) => {
|
||||
now += ms;
|
||||
};
|
||||
return { flightState, enrichment, queries, settle, advance };
|
||||
}
|
||||
|
||||
test('a failed lookup is asked again only after its cool-down', async (t) => {
|
||||
let fail = true;
|
||||
const { flightState, enrichment, queries, settle, advance } = enrichmentClock(
|
||||
t,
|
||||
async () => {
|
||||
if (fail) throw new Error('503');
|
||||
return { found: true, typeCode: 'A321' };
|
||||
},
|
||||
);
|
||||
flightState.records.data.set('a0f1bb', {});
|
||||
enrichment._requestTypeEnrichment('a0f1bb');
|
||||
await settle();
|
||||
assert.deepEqual(queries, ['a0f1bb']);
|
||||
advance(59_000);
|
||||
enrichment._requestTypeEnrichment('a0f1bb');
|
||||
await settle();
|
||||
assert.deepEqual(queries, ['a0f1bb'], 'not within the cool-down');
|
||||
fail = false;
|
||||
advance(1_000);
|
||||
enrichment._requestTypeEnrichment('a0f1bb');
|
||||
await settle();
|
||||
assert.deepEqual(queries, ['a0f1bb', 'a0f1bb'], 'asked again after it');
|
||||
assert.equal(flightState.records.data.get('a0f1bb').typeCode, 'A321');
|
||||
advance(120_000);
|
||||
enrichment._requestTypeEnrichment('a0f1bb');
|
||||
await settle();
|
||||
assert.equal(queries.length, 2, 'an answer is final');
|
||||
assert.equal(flightState._enrichActive, 0);
|
||||
flightState.lifetime.abort();
|
||||
});
|
||||
|
||||
test('a synchronous source failure cools down like a rejected one', async (t) => {
|
||||
const { flightState, enrichment, queries, settle, advance } = enrichmentClock(
|
||||
t,
|
||||
() => {
|
||||
throw new Error('boom');
|
||||
},
|
||||
);
|
||||
enrichment._requestPhotoEnrichment('a0f1bb');
|
||||
await settle();
|
||||
advance(60_000);
|
||||
enrichment._requestPhotoEnrichment('a0f1bb');
|
||||
await settle();
|
||||
assert.deepEqual(queries, ['a0f1bb', 'a0f1bb']);
|
||||
flightState.lifetime.abort();
|
||||
});
|
||||
|
||||
test('a "not found" answer is never asked again', async (t) => {
|
||||
const { flightState, enrichment, queries, settle, advance } = enrichmentClock(
|
||||
t,
|
||||
async ({ kind }) => (kind === 'photo' ? { photos: [] } : { found: false }),
|
||||
);
|
||||
enrichment._requestTypeEnrichment('a0f1bb');
|
||||
await settle();
|
||||
advance(1_000); // past the dispatch drip
|
||||
enrichment._requestPhotoEnrichment('a0f1bb');
|
||||
await settle();
|
||||
assert.equal(queries.length, 2);
|
||||
advance(3_600_000);
|
||||
enrichment._requestTypeEnrichment('a0f1bb');
|
||||
enrichment._requestPhotoEnrichment('a0f1bb');
|
||||
await settle();
|
||||
assert.equal(queries.length, 2);
|
||||
assert.equal(flightState._enrichRetryAfter.size, 0);
|
||||
flightState.lifetime.abort();
|
||||
});
|
||||
|
||||
test('a lookup cut off by the layer’s teardown schedules no retry', async (t) => {
|
||||
let release;
|
||||
const { flightState, enrichment, settle } = enrichmentClock(
|
||||
t,
|
||||
(query) =>
|
||||
new Promise((_resolve, reject) => {
|
||||
release = () => reject(new DOMException('aborted', 'AbortError'));
|
||||
}),
|
||||
);
|
||||
enrichment._requestTypeEnrichment('a0f1bb');
|
||||
await settle();
|
||||
flightState.lifetime.abort();
|
||||
release();
|
||||
await settle();
|
||||
assert.equal(flightState._enrichRetryAfter.size, 0);
|
||||
assert.equal(flightState._enrichSeen.has('t:a0f1bb'), true);
|
||||
});
|
||||
|
||||
test('a permanent refusal is final; a timeout, rate limit, outage or authorization refusal cools down', async (t) => {
|
||||
const errors = {
|
||||
aaaaa1: new LiveSourceError('denied', 'adsbdb HTTP 404', { status: 404 }),
|
||||
aaaaa2: new LiveSourceError('unsupported', 'Enrichment unavailable'),
|
||||
aaaaa3: new LiveSourceError('limited', 'adsbdb rate limited', {
|
||||
status: 429,
|
||||
}),
|
||||
aaaaa4: new LiveSourceError('unavailable', 'adsbdb HTTP 503', {
|
||||
status: 503,
|
||||
}),
|
||||
aaaaa5: new LiveSourceError('unavailable', 'adsbdb HTTP 408', {
|
||||
status: 408,
|
||||
}),
|
||||
aaaaa6: new Error('network'),
|
||||
aaaaa7: new LiveSourceError('denied', 'Unauthorized', { status: 401 }),
|
||||
aaaaa8: new LiveSourceError('denied', 'Forbidden', { status: 403 }),
|
||||
};
|
||||
const { flightState, enrichment, queries, settle, advance } = enrichmentClock(
|
||||
t,
|
||||
async ({ id }) => {
|
||||
throw errors[id];
|
||||
},
|
||||
);
|
||||
const ids = Object.keys(errors);
|
||||
for (const id of ids) {
|
||||
enrichment._requestTypeEnrichment(id);
|
||||
await settle();
|
||||
advance(1_000); // past the dispatch drip
|
||||
}
|
||||
assert.deepEqual(queries, ids);
|
||||
advance(60_000);
|
||||
for (const id of ids) {
|
||||
enrichment._requestTypeEnrichment(id);
|
||||
await settle();
|
||||
advance(1_000);
|
||||
}
|
||||
assert.deepEqual(
|
||||
queries.slice(ids.length),
|
||||
['aaaaa3', 'aaaaa4', 'aaaaa5', 'aaaaa6', 'aaaaa7', 'aaaaa8'],
|
||||
'a 404 and an unsupported lookup are never asked again',
|
||||
);
|
||||
assert.equal(flightState._enrichSeen.has('t:aaaaa1'), true);
|
||||
assert.equal(flightState._enrichRetryAfter.has('t:aaaaa1'), false);
|
||||
flightState.lifetime.abort();
|
||||
});
|
||||
|
||||
test('a route answer for a callsign the plane no longer flies is dropped', async (t) => {
|
||||
const pending = [];
|
||||
const { flightState, enrichment, settle, advance } = enrichmentClock(
|
||||
t,
|
||||
(query) => new Promise((resolve) => pending.push({ query, resolve })),
|
||||
);
|
||||
const meta = { callsign: 'UAL9' };
|
||||
flightState.records.data.set('a0f1bb', meta);
|
||||
enrichment._requestRouteEnrichment('a0f1bb');
|
||||
await settle();
|
||||
meta.callsign = 'UAL10'; // the next poll's callsign
|
||||
advance(1_000);
|
||||
enrichment._requestRouteEnrichment('a0f1bb');
|
||||
await settle();
|
||||
assert.deepEqual(
|
||||
pending.map(({ query }) => query.id),
|
||||
['UAL9', 'UAL10'],
|
||||
);
|
||||
const route = (code) => ({
|
||||
found: true,
|
||||
airline: `${code} Air`,
|
||||
origin: { code: `${code}O` },
|
||||
destination: { code: `${code}D` },
|
||||
});
|
||||
pending[0].resolve(route('OLD'));
|
||||
await settle();
|
||||
assert.equal(meta.route, undefined, 'the late UAL9 answer is ignored');
|
||||
assert.equal(meta.airline, undefined);
|
||||
pending[1].resolve(route('NEW'));
|
||||
await settle();
|
||||
assert.deepEqual(meta.route, {
|
||||
origin: { code: 'NEWO' },
|
||||
destination: { code: 'NEWD' },
|
||||
});
|
||||
assert.equal(meta.routeCallsign, 'UAL10');
|
||||
flightState.lifetime.abort();
|
||||
});
|
||||
@@ -141,7 +141,7 @@ export const TRAIL_COLOR = '#00d4ff';
|
||||
|
||||
/** @constant {number} Combined cap on trail vertices (backfill + live accumulation). */
|
||||
|
||||
export const TRAIL_MAX_POINTS = 400;
|
||||
export const TRAIL_MAX_POINTS = 2000;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Render-behind smoothing (PRD WS-C C2 — approved product decision):
|
||||
@@ -156,6 +156,15 @@ export const TRAIL_MAX_POINTS = 400;
|
||||
|
||||
export const RENDER_DELAY_SEC = 30;
|
||||
|
||||
/** Whether the layer shows the world clock's time instead of the live feed:
|
||||
* its source declares a timeline and the clock is away from live. */
|
||||
export const followsClock = (state) => state.timeline?.active() === true;
|
||||
|
||||
/** How far behind the time contacts are drawn: RENDER_DELAY_SEC live, none
|
||||
* following the clock, whose snapshots are loaded ahead of the time. */
|
||||
export const displayDelayMs = (state) =>
|
||||
followsClock(state) ? 0 : RENDER_DELAY_SEC * 1000;
|
||||
|
||||
/** @constant {number} Polls an aircraft may miss before removal (transient OpenSky dropouts). */
|
||||
|
||||
// --- Landed-plane fast cull (owner field report 2026-07-02: "phantom" planes
|
||||
@@ -234,6 +243,11 @@ export const ENRICH_MAX_INFLIGHT = 4;
|
||||
|
||||
export const ENRICH_DISPATCH_GAP_MS = 200;
|
||||
|
||||
/** A lookup whose source failed (an outage, a timeout, a restarting server) may
|
||||
* be asked again after this long; a real "not found" answer never is. */
|
||||
|
||||
export const ENRICH_RETRY_COOLDOWN_MS = 60_000;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Ambient fleet type enrichment (2026-07-02 field data: OpenSky's live
|
||||
// category field is 0/"no info" for ~94% of planes, so ambient classification
|
||||
@@ -431,3 +445,6 @@ export const FLOOR_EASE_EPSILON_M = 0.02;
|
||||
* airborne long enough to have gone anywhere. */
|
||||
|
||||
export const FLOOR_SEED_GRACE_MS = 90_000;
|
||||
|
||||
/** Alpha of a contact that has missed an update or lost its signal: the stale fade, for the fleet and the tracked aircraft alike. */
|
||||
export const STALE_ALPHA = 0.45;
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
LANDED_SPEED_MAX_MPS,
|
||||
FOCUS_EVIDENCE_DEV,
|
||||
FLEET_DR_INTERVAL_MS,
|
||||
followsClock,
|
||||
} from './policy.js';
|
||||
import { emergencyBroadcastPhrase } from '../../data/aircraftEmergency.js';
|
||||
|
||||
@@ -27,7 +28,8 @@ export function createQueries({
|
||||
layer,
|
||||
resolveAsset,
|
||||
}) {
|
||||
const { tr3bTypeLabel, tr3bAircraftClass } = services.aircraftPresentation;
|
||||
const { isTr3b, tr3bTypeLabel, tr3bAircraftClass } =
|
||||
services.aircraftPresentation;
|
||||
const { formatFlightLevel } = services.labels;
|
||||
const { isMilitaryIcao } = services.militaryRegistry;
|
||||
const {
|
||||
@@ -206,6 +208,12 @@ export function createQueries({
|
||||
destination: { ...info.route.destination },
|
||||
}
|
||||
: null,
|
||||
// The airframe's Planespotters photo for the Context panel; a military
|
||||
// aircraft or a converted TR-3B (it would name the real one) shows none.
|
||||
photo:
|
||||
info?.photo && !isTr3b(icao24) && !isMilitaryIcao(icao24)
|
||||
? { ...info.photo }
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -850,8 +858,9 @@ export function createQueries({
|
||||
|
||||
/**
|
||||
* Describe the currently tracked aircraft at its dead-reckoned position.
|
||||
* @returns {{icao24: string, callsign: string|null, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null, verticalRateMps: number|null}|null}
|
||||
* Tracked aircraft info, or null when nothing is tracked.
|
||||
* @returns {{icao24: string, callsign: string|null, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null, verticalRateMps: number|null, photo: {src: string, width: number|null, height: number|null, photographer: string, link: string}|null}|null}
|
||||
* Tracked aircraft info, or null when nothing is tracked. `photo` is the
|
||||
* airframe's credited Planespotters photo, or null.
|
||||
*/
|
||||
getTrackedInfo() {
|
||||
if (!flightState._trackedIcao) return null;
|
||||
@@ -881,6 +890,8 @@ export function createQueries({
|
||||
_toCleanText(described.registration) ||
|
||||
described.icao24,
|
||||
position: clone(described.position),
|
||||
// The airframe's photo for the Context panel, or null.
|
||||
photo: described.photo,
|
||||
};
|
||||
},
|
||||
|
||||
@@ -947,6 +958,8 @@ export function createQueries({
|
||||
retryInSec,
|
||||
source: flightState.feed._lastSource,
|
||||
coverage: flightState.feed._lastCoverage,
|
||||
// Following the world clock, the snapshot's age is told from its time.
|
||||
...(followsClock(flightState) && { atMs: flightState.now() }),
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
@@ -9,6 +9,10 @@ export const LANDED_MISSING_POLL_LIMIT = 1;
|
||||
|
||||
export const MISSING_POLL_LIMIT = 3;
|
||||
|
||||
/** The tracked contact is kept this long after its newest fix: five minutes
|
||||
* coasting, then five stopped as SIGNAL LOST. */
|
||||
export const TRACKED_RETENTION_MS = 10 * 60_000;
|
||||
|
||||
/** Cooldown in milliseconds after a transient source error. */
|
||||
export const ERROR_BACKOFF_INTERVAL = 20000;
|
||||
|
||||
|
||||
+125
-17
@@ -11,22 +11,67 @@ import {
|
||||
GROUND_FLOOR_WARM_MAX_ALT_M,
|
||||
LANDED_MISSING_POLL_LIMIT,
|
||||
MISSING_POLL_LIMIT,
|
||||
TRACKED_RETENTION_MS,
|
||||
} from './recordPolicy.js';
|
||||
|
||||
/** Source-independent aircraft metadata and bounded missing-poll retention. */
|
||||
export class FlightRecords {
|
||||
constructor({ geoidHeight, cachedGroundFloor, floorAltitudeM }) {
|
||||
constructor({
|
||||
geoidHeight,
|
||||
cachedGroundFloor,
|
||||
floorAltitudeM,
|
||||
now = () => Date.now(),
|
||||
}) {
|
||||
this.services = {
|
||||
geoidHeight,
|
||||
cachedGroundFloor,
|
||||
floorAltitudeM,
|
||||
};
|
||||
/** The time records are judged at: the layer's clock. */
|
||||
this.now = now;
|
||||
this.data = new Map();
|
||||
// Facts about an airframe, not a moment, kept across a reset.
|
||||
this.airframes = new Map();
|
||||
this.missingPolls = new Map();
|
||||
// Contacts whose last poll re-sent a fix no newer than the one before.
|
||||
this.fixRepeated = new Set();
|
||||
this.lastSnapshotMs = null;
|
||||
this.snapshotAdvanced = true;
|
||||
this.geoidNCache = new Map();
|
||||
this.geoidReady = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start reading a snapshot taken at `observedAtMs`. A fix re-sent in a
|
||||
* newer snapshot marks its contact as not updated; the same snapshot read
|
||||
* again does not.
|
||||
* @param {number} observedAtMs
|
||||
*/
|
||||
beginSnapshot(observedAtMs) {
|
||||
this.snapshotAdvanced =
|
||||
!Number.isFinite(observedAtMs) ||
|
||||
!Number.isFinite(this.lastSnapshotMs) ||
|
||||
observedAtMs > this.lastSnapshotMs;
|
||||
if (Number.isFinite(observedAtMs))
|
||||
this.lastSnapshotMs = Math.max(
|
||||
this.lastSnapshotMs ?? -Infinity,
|
||||
observedAtMs,
|
||||
);
|
||||
}
|
||||
|
||||
/** Note a received fix: the newest fix time, and whether it advanced. */
|
||||
_noteFix(id, prevMeta, fixEpochMs) {
|
||||
const prevFixMs = prevMeta?.newestFixMs;
|
||||
// A fix counts as new only when it moves on by a second: feeds that
|
||||
// derive fix time from receipt (readsb `now − seen_pos`, 0.1 s) jitter.
|
||||
if (!Number.isFinite(prevFixMs) || fixEpochMs >= prevFixMs + 1000) {
|
||||
this.fixRepeated.delete(id);
|
||||
return fixEpochMs;
|
||||
}
|
||||
if (this.snapshotAdvanced) this.fixRepeated.add(id);
|
||||
return prevFixMs;
|
||||
}
|
||||
|
||||
receive(
|
||||
observation,
|
||||
{ viewerLatDeg, viewerLonDeg, trackedId, floorWarmPoints },
|
||||
@@ -54,6 +99,9 @@ export class FlightRecords {
|
||||
// regressing to the ICAO hex / a 0° (north) heading. Bounded by the
|
||||
// MISSING_POLL_LIMIT eviction below, which deletes the whole entry.
|
||||
const prevMeta = this.data.get(icao24);
|
||||
// The airframe's facts: this record's, or those kept across a reset.
|
||||
const airframe = prevMeta ?? this.airframes.get(icao24);
|
||||
this.airframes.delete(icao24);
|
||||
// Grounded planes with no baro reading sit at 0 m, not the 10 km
|
||||
// airborne default (a parked plane must never float).
|
||||
// NOTE (height-datum fix): `alt` stays the AVIATION field — the sticky
|
||||
@@ -158,6 +206,12 @@ export class FlightRecords {
|
||||
// (2) otherwise the SAME default policy `alt` already uses, so the two
|
||||
// never disagree on the genuine "no data yet" case (a never-reported
|
||||
// aircraft has no prior render height, so it lands here unchanged).
|
||||
// Neither altitude this poll nor a held render height: the height below
|
||||
// is the airborne default, invented. The tracked trail keeps no point there.
|
||||
const renderAltitudeInvented =
|
||||
pickedAltM == null &&
|
||||
!onGround &&
|
||||
!Number.isFinite(prevMeta?.renderAltitudeM);
|
||||
let renderAltitudeM;
|
||||
if (pickedAltM != null) {
|
||||
renderAltitudeM = pickedAltM;
|
||||
@@ -198,10 +252,22 @@ export class FlightRecords {
|
||||
!!prevMeta && (prevMeta.onGround === true) !== onGround;
|
||||
// Store flight metadata for click-to-track labels
|
||||
const cat = stickyNumber(category, prevMeta?.category, null);
|
||||
const nextCallsign = stickyText(callsign, prevMeta?.callsign);
|
||||
// A route (and its airline) belongs to the callsign it was looked up for;
|
||||
// a new callsign drops it, so an old flight's route never shows under it.
|
||||
const routeHeld =
|
||||
Boolean(airframe?.routeCallsign) &&
|
||||
airframe.routeCallsign === nextCallsign.toUpperCase();
|
||||
const fixEpochMs =
|
||||
Number.isFinite(observation.positionTimeMs) &&
|
||||
observation.positionTimeMs > 0
|
||||
? observation.positionTimeMs
|
||||
: this.now();
|
||||
const meta = {
|
||||
sourceReference: observation.reference,
|
||||
observedReceiptMs: Date.now(),
|
||||
callsign: stickyText(callsign, prevMeta?.callsign),
|
||||
observedReceiptMs: this.now(),
|
||||
newestFixMs: this._noteFix(icao24, prevMeta, fixEpochMs),
|
||||
callsign: nextCallsign,
|
||||
altitude: alt,
|
||||
// geoAltitudeM/renderAltitudeM are ADDITIVE fields alongside the
|
||||
// untouched aviation `altitude` — never rename/replace it (labels,
|
||||
@@ -209,6 +275,7 @@ export class FlightRecords {
|
||||
// still read `altitude`/baro).
|
||||
geoAltitudeM,
|
||||
renderAltitudeM,
|
||||
renderAltitudeInvented,
|
||||
onGround,
|
||||
// Round 7: sticky airborne history — the landed fast-cull only
|
||||
// applies to contacts that actually flew this session.
|
||||
@@ -218,7 +285,7 @@ export class FlightRecords {
|
||||
category: cat,
|
||||
// An adsbdb-enriched type code outranks the coarse OpenSky category.
|
||||
klass: classifyAircraft({
|
||||
typeCode: prevMeta?.typeCode ?? null,
|
||||
typeCode: airframe?.typeCode ?? null,
|
||||
category: cat,
|
||||
}),
|
||||
turnRateDps: prevMeta?.turnRateDps || 0,
|
||||
@@ -253,11 +320,14 @@ export class FlightRecords {
|
||||
null,
|
||||
),
|
||||
// adsbdb enrichment — written by the enrichment callbacks, carried across polls:
|
||||
typeCode: prevMeta?.typeCode ?? null,
|
||||
typeName: prevMeta?.typeName ?? null,
|
||||
registration: prevMeta?.registration ?? null,
|
||||
airline: prevMeta?.airline ?? null,
|
||||
route: prevMeta?.route ?? null,
|
||||
typeCode: airframe?.typeCode ?? null,
|
||||
typeName: airframe?.typeName ?? null,
|
||||
registration: airframe?.registration ?? null,
|
||||
airline: routeHeld ? (airframe.airline ?? null) : null,
|
||||
route: routeHeld ? (airframe.route ?? null) : null,
|
||||
routeCallsign: routeHeld ? airframe.routeCallsign : null,
|
||||
// Planespotters photo of the tracked airframe (Core asks it directly).
|
||||
photo: airframe?.photo ?? null,
|
||||
// The RAW poll fix lat/lon (this tick's OpenSky state-vector
|
||||
// coords, pre-dead-reckon) — kept distinct from the continuously
|
||||
// dead-reckoned billboard position for any consumer that needs the
|
||||
@@ -267,24 +337,36 @@ export class FlightRecords {
|
||||
};
|
||||
this.data.set(icao24, meta);
|
||||
|
||||
const fixEpochMs =
|
||||
Number.isFinite(observation.positionTimeMs) &&
|
||||
observation.positionTimeMs > 0
|
||||
? observation.positionTimeMs
|
||||
: Date.now();
|
||||
return { icao24, prevMeta, meta, groundFlipped, fixEpochMs };
|
||||
}
|
||||
|
||||
absence(id, { complete, retainIds, likelyLanded }) {
|
||||
absence(
|
||||
id,
|
||||
{ complete, retainIds, likelyLanded, tracked = false, nowMs = this.now() },
|
||||
) {
|
||||
const misses = (this.missingPolls.get(id) || 0) + 1;
|
||||
// The tracked contact has missed an update: it is stale from the first
|
||||
// one, and kept (so the camera keeps its target) until ten minutes after
|
||||
// its newest fix, whatever the snapshot says. With no fix time known it
|
||||
// takes the ordinary limits below.
|
||||
const meta = this.data.get(id);
|
||||
const fixMs = meta?.newestFixMs ?? meta?.observedReceiptMs;
|
||||
if (tracked && Number.isFinite(fixMs)) {
|
||||
if (nowMs - fixMs < TRACKED_RETENTION_MS) {
|
||||
this.missingPolls.set(id, misses);
|
||||
return 'stale';
|
||||
}
|
||||
this.missingPolls.delete(id);
|
||||
return 'remove';
|
||||
}
|
||||
// Partial admissions and position-less rows do not prove absence, but
|
||||
// retention remains bounded; a likely-landed position-less contact
|
||||
// still takes the landed limit.
|
||||
if (
|
||||
(!complete || (retainIds?.has(id) && !likelyLanded)) &&
|
||||
Date.now() - (this.data.get(id)?.observedReceiptMs ?? 0) < 300000
|
||||
nowMs - (this.data.get(id)?.observedReceiptMs ?? 0) < 300000
|
||||
)
|
||||
return 'retain';
|
||||
const misses = (this.missingPolls.get(id) || 0) + 1;
|
||||
const limit = likelyLanded ? LANDED_MISSING_POLL_LIMIT : MISSING_POLL_LIMIT;
|
||||
if (misses < limit) {
|
||||
this.missingPolls.set(id, misses);
|
||||
@@ -294,9 +376,35 @@ export class FlightRecords {
|
||||
return 'remove';
|
||||
}
|
||||
|
||||
/**
|
||||
* Forget every observation, as when the world clock jumps to another time:
|
||||
* what an airframe is (its type, registration, route and photo) is kept for
|
||||
* when it is seen again; where it was and when is not.
|
||||
*/
|
||||
reset() {
|
||||
for (const [id, meta] of this.data) {
|
||||
this.airframes.set(id, {
|
||||
typeCode: meta.typeCode,
|
||||
typeName: meta.typeName,
|
||||
registration: meta.registration,
|
||||
airline: meta.airline,
|
||||
route: meta.route,
|
||||
routeCallsign: meta.routeCallsign,
|
||||
photo: meta.photo,
|
||||
});
|
||||
}
|
||||
this.data.clear();
|
||||
this.missingPolls.clear();
|
||||
this.fixRepeated.clear();
|
||||
this.lastSnapshotMs = null;
|
||||
this.snapshotAdvanced = true;
|
||||
}
|
||||
|
||||
forget(id) {
|
||||
this.data.delete(id);
|
||||
this.airframes.delete(id);
|
||||
this.missingPolls.delete(id);
|
||||
this.fixRepeated.delete(id);
|
||||
this.geoidNCache.delete(id);
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,7 @@ test('civil records keep aviation units separate from render height and survive
|
||||
assert.equal(first.meta.renderAltitudeM, 1040);
|
||||
assert.equal(first.fixEpochMs, 1700000000000);
|
||||
first.meta.typeCode = 'B738';
|
||||
first.meta.photo = { src: 'https://t.plnspttrs.net/1/2_280.jpg' };
|
||||
const second = store.receive(
|
||||
observation({
|
||||
callsign: '',
|
||||
@@ -55,6 +56,7 @@ test('civil records keep aviation units separate from render height and survive
|
||||
assert.equal(second.meta.velocity, 120);
|
||||
assert.equal(second.meta.true_track, 90);
|
||||
assert.equal(second.meta.typeCode, 'B738');
|
||||
assert.equal(second.meta.photo, first.meta.photo, 'the photo survives polls');
|
||||
assert.equal(Object.hasOwn(second.meta, 'cullPosition'), false);
|
||||
assert.deepEqual(JSON.parse(JSON.stringify(second.meta)), second.meta);
|
||||
});
|
||||
@@ -140,3 +142,121 @@ test('civil emergency status follows the latest poll instead of sticking', () =>
|
||||
assert.equal(next.meta.squawk, '2000');
|
||||
assert.equal(next.meta.emergency, null);
|
||||
});
|
||||
|
||||
test('a route belongs to its callsign: a new callsign drops it, a blank one keeps it', () => {
|
||||
const store = records();
|
||||
store.geoidReady = true;
|
||||
const first = store.receive(observation({ callsign: 'UAL9' }), view());
|
||||
first.meta.route = { origin: { code: 'AUS' }, destination: { code: 'DEN' } };
|
||||
first.meta.airline = 'United';
|
||||
first.meta.routeCallsign = 'UAL9';
|
||||
const same = store.receive(observation({ callsign: 'UAL9 ' }), view());
|
||||
assert.equal(same.meta.route, first.meta.route);
|
||||
const blank = store.receive(observation({ callsign: '' }), view());
|
||||
assert.equal(
|
||||
blank.meta.route,
|
||||
first.meta.route,
|
||||
'a dropped callsign is sticky',
|
||||
);
|
||||
assert.equal(blank.meta.airline, 'United');
|
||||
const next = store.receive(observation({ callsign: 'UAL10' }), view());
|
||||
assert.equal(next.meta.route, null, 'the old route never shows under UAL10');
|
||||
assert.equal(next.meta.airline, null);
|
||||
assert.equal(next.meta.routeCallsign, null);
|
||||
});
|
||||
|
||||
test('a contact with no altitude yet is marked as drawn at an invented height; a held one is not', () => {
|
||||
const store = records();
|
||||
const none = store.receive(
|
||||
observation({ baroAltitudeM: null, ellipsoidAltitudeM: null }),
|
||||
view(),
|
||||
);
|
||||
assert.equal(none.meta.renderAltitudeInvented, true);
|
||||
const known = store.receive(
|
||||
observation({ positionTimeMs: 1700000005000 }),
|
||||
view(),
|
||||
);
|
||||
assert.equal(known.meta.renderAltitudeInvented, false);
|
||||
const held = store.receive(
|
||||
observation({
|
||||
baroAltitudeM: null,
|
||||
ellipsoidAltitudeM: null,
|
||||
positionTimeMs: 1700000010000,
|
||||
}),
|
||||
view(),
|
||||
);
|
||||
assert.equal(held.meta.renderAltitudeInvented, false);
|
||||
const parked = records().receive(
|
||||
observation({ id: 'abc124', baroAltitudeM: null, onGround: true }),
|
||||
view(),
|
||||
);
|
||||
assert.equal(parked.meta.renderAltitudeInvented, false);
|
||||
});
|
||||
|
||||
test('the tracked contact is stale from its first missed update and kept until ten minutes after its newest fix', () => {
|
||||
const realNow = Date.now;
|
||||
const fixMs = Date.UTC(2026, 10, 9, 20, 0);
|
||||
let clock = fixMs + 5_000;
|
||||
Date.now = () => clock;
|
||||
try {
|
||||
for (const snapshot of [
|
||||
{ complete: true },
|
||||
{ complete: true, retainIds: new Set(['abc123']) },
|
||||
{ complete: false },
|
||||
]) {
|
||||
const store = records();
|
||||
store.receive(observation({ positionTimeMs: fixMs }), view());
|
||||
const absent = (tracked) =>
|
||||
store.absence('abc123', { ...snapshot, likelyLanded: false, tracked });
|
||||
clock = fixMs + 15_000;
|
||||
assert.equal(absent(true), 'stale');
|
||||
assert.equal(store.missingPolls.get('abc123'), 1);
|
||||
// Kept long after the untracked limits, measured from the fix time.
|
||||
clock = fixMs + 9 * 60_000;
|
||||
assert.equal(absent(true), 'stale');
|
||||
clock = fixMs + 10 * 60_000 - 1;
|
||||
assert.equal(absent(true), 'stale');
|
||||
clock = fixMs + 10 * 60_000;
|
||||
assert.equal(absent(true), 'remove');
|
||||
assert.equal(store.missingPolls.has('abc123'), false);
|
||||
}
|
||||
// Untracked contacts keep their own limits.
|
||||
const store = records();
|
||||
store.receive(observation({ positionTimeMs: fixMs }), view());
|
||||
clock = fixMs + 15_000;
|
||||
const untracked = (snapshot) =>
|
||||
store.absence('abc123', { ...snapshot, likelyLanded: false });
|
||||
assert.equal(untracked({ complete: false }), 'retain');
|
||||
assert.deepEqual(
|
||||
[1, 2, 3].map(() => untracked({ complete: true })),
|
||||
['stale', 'stale', 'remove'],
|
||||
);
|
||||
} finally {
|
||||
Date.now = realNow;
|
||||
}
|
||||
});
|
||||
|
||||
test('a repeated fix time marks the contact as not updated; removal is unchanged', () => {
|
||||
const store = records();
|
||||
const fixMs = Date.UTC(2026, 10, 9, 20, 0);
|
||||
store.beginSnapshot(fixMs + 2_000);
|
||||
store.receive(observation({ positionTimeMs: fixMs }), view());
|
||||
assert.equal(store.fixRepeated.has('abc123'), false);
|
||||
// The next poll re-sends the same position.
|
||||
store.beginSnapshot(fixMs + 12_000);
|
||||
store.receive(observation({ positionTimeMs: fixMs }), view());
|
||||
assert.equal(store.fixRepeated.has('abc123'), true);
|
||||
assert.equal(store.missingPolls.has('abc123'), false);
|
||||
// The same snapshot read again is not a missed update.
|
||||
store.beginSnapshot(fixMs + 12_000);
|
||||
store.receive(observation({ positionTimeMs: fixMs }), view());
|
||||
assert.equal(store.fixRepeated.has('abc123'), true);
|
||||
// A newer fix clears it.
|
||||
store.beginSnapshot(fixMs + 22_000);
|
||||
store.receive(observation({ positionTimeMs: fixMs + 10_000 }), view());
|
||||
assert.equal(store.fixRepeated.has('abc123'), false);
|
||||
store.beginSnapshot(fixMs + 32_000);
|
||||
store.receive(observation({ positionTimeMs: fixMs + 10_000 }), view());
|
||||
store.forget('abc123');
|
||||
assert.equal(store.fixRepeated.has('abc123'), false);
|
||||
});
|
||||
@@ -2,9 +2,11 @@ import { findCamera } from '../../render/rendererOf.js';
|
||||
import {
|
||||
turnRateFromFixHistory,
|
||||
liftRepeatedGroundFix,
|
||||
staleHoldsForFix,
|
||||
synthesizeForwardKinematicsFix,
|
||||
} from '../../data/motionModel.js';
|
||||
import { POSITION_HISTORY_LIMIT } from './recordPolicy.js';
|
||||
import { followsClock } from './policy.js';
|
||||
|
||||
/** Apply reconciled aircraft records to the layer's drawing and follow state. */
|
||||
export function createFlightSnapshotRenderer({
|
||||
@@ -20,8 +22,12 @@ export function createFlightSnapshotRenderer({
|
||||
queries,
|
||||
}) {
|
||||
const { refreshMilitaryRegistryIfStale, isMilitaryIcao } = militaryRegistry;
|
||||
const { warmGroundFloor } = groundFloor;
|
||||
return function applySnapshot(snapshot, viewer) {
|
||||
const { warmGroundFloor, cachedGroundFloor } = groundFloor;
|
||||
/**
|
||||
* `replace`: the snapshot is the world at another time (the world clock
|
||||
* jumped), so it stands in for every contact: one it lacks is gone at once.
|
||||
*/
|
||||
return function applySnapshot(snapshot, viewer, { replace = false } = {}) {
|
||||
// Before init (or after destroy) there is no icon set to draw into.
|
||||
if (!flightState._icons) return { count: 0, ids: new Set() };
|
||||
const currentIcaos = new Set();
|
||||
@@ -35,6 +41,7 @@ export function createFlightSnapshotRenderer({
|
||||
const viewerLatDeg = hasSubpoint ? pose.lat : null;
|
||||
const viewerLonDeg = hasSubpoint ? pose.lon : null;
|
||||
const floorWarmPoints = [];
|
||||
records.beginSnapshot(snapshot.observedAtMs);
|
||||
|
||||
// Classification and display policy consume source-independent observations.
|
||||
refreshMilitaryRegistryIfStale();
|
||||
@@ -96,14 +103,17 @@ export function createFlightSnapshotRenderer({
|
||||
// Per-fix kinematics: the fix's own velocity/track ride along so the
|
||||
// extrapolation paths use the values that BELONG to the fix they
|
||||
// extend, not whatever the latest poll reported.
|
||||
history.push(
|
||||
motion._historyFix(
|
||||
history.push({
|
||||
...motion._historyFix(
|
||||
fixEpochMs,
|
||||
position,
|
||||
meta.velocity,
|
||||
meta.true_track,
|
||||
),
|
||||
);
|
||||
// Drawn at an invented height: a trail seeded from history keeps no
|
||||
// position for it.
|
||||
inventedHeight: meta.renderAltitudeInvented === true,
|
||||
});
|
||||
if (history.length > POSITION_HISTORY_LIMIT) {
|
||||
history.shift();
|
||||
}
|
||||
@@ -116,7 +126,10 @@ export function createFlightSnapshotRenderer({
|
||||
// Round 2 (owner): ground traffic appends too — taxi history stays
|
||||
// live after touchdown (grounded flights positions are already
|
||||
// surface-clamped via the surfaceM chain, so the ground leg drapes).
|
||||
if (isTracked) tracking._appendTrailFix(motion._copyPosition(position));
|
||||
if (isTracked)
|
||||
tracking._appendTrailFix(motion._copyPosition(position), fixEpochMs, {
|
||||
nullAltitude: meta.renderAltitudeInvented === true,
|
||||
});
|
||||
} else {
|
||||
const modelOwnsGroundVisual = rendering._modelOwnsVisual(icao24);
|
||||
if (!modelOwnsGroundVisual) {
|
||||
@@ -124,24 +137,31 @@ export function createFlightSnapshotRenderer({
|
||||
}
|
||||
// Apply fresh kinematics only from a forward synthetic fix. Mutating
|
||||
// the historical fix reprojects the entire stale interval and snaps
|
||||
// the rendered aircraft when course or speed changes late.
|
||||
// the rendered aircraft when course or speed changes late. The stale
|
||||
// rules apply: none for a contact that holds at its report, a coast
|
||||
// capped from the real report, never below the ground. It is a motion
|
||||
// aid, not a report, so it never joins the trail.
|
||||
const kinematicsChanged =
|
||||
newest.velocity !== meta.velocity || newest.track !== meta.true_track;
|
||||
if (kinematicsChanged) {
|
||||
const holds = staleHoldsForFix(newest, {
|
||||
onGround: meta.onGround,
|
||||
cachedGroundFloor,
|
||||
});
|
||||
if (kinematicsChanged && !holds) {
|
||||
const synthetic = synthesizeForwardKinematicsFix(newest, {
|
||||
epochMs: Date.now(),
|
||||
// Following the clock, the snapshot's time is the moment it moves on from.
|
||||
epochMs: followsClock(flightState)
|
||||
? snapshot.observedAtMs
|
||||
: Date.now(),
|
||||
velocity: meta.velocity,
|
||||
track: meta.true_track,
|
||||
turnRateDps: meta.turnRateDps,
|
||||
cachedGroundFloor,
|
||||
});
|
||||
if (synthetic) {
|
||||
history.push(synthetic);
|
||||
if (history.length > POSITION_HISTORY_LIMIT) history.shift();
|
||||
meta.turnRateDps = turnRateFromFixHistory(history);
|
||||
if (isTracked)
|
||||
tracking._appendTrailFix(
|
||||
motion._copyPosition(synthetic.position),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -170,6 +190,13 @@ export function createFlightSnapshotRenderer({
|
||||
// (position updates automatically via dead-reckoning CallbackProperty)
|
||||
if (isTracked && flightState._trackedEntity) {
|
||||
tracking._updateTrackedLabelModel(icao24);
|
||||
// Re-ask the tracked plane's lookups each poll. Answered and queued
|
||||
// keys return at once; a lookup whose source failed runs again once
|
||||
// its cool-down has passed, and the route uses the callsign this
|
||||
// snapshot just recorded.
|
||||
enrichment._requestTypeEnrichment(icao24, true);
|
||||
enrichment._requestRouteEnrichment(icao24);
|
||||
enrichment._requestPhotoEnrichment(icao24);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,11 +211,15 @@ export function createFlightSnapshotRenderer({
|
||||
if (!currentIcaos.has(icao24)) absentIds.push(icao24);
|
||||
}
|
||||
for (const icao24 of absentIds) {
|
||||
const absence = records.absence(icao24, {
|
||||
complete: snapshot.complete,
|
||||
retainIds: snapshot.retainIds,
|
||||
likelyLanded: queries._likelyLanded(icao24),
|
||||
});
|
||||
const absence = replace
|
||||
? 'remove'
|
||||
: records.absence(icao24, {
|
||||
complete: snapshot.complete,
|
||||
retainIds: snapshot.retainIds,
|
||||
likelyLanded: queries._likelyLanded(icao24),
|
||||
tracked: icao24 === flightState._trackedIcao,
|
||||
nowMs: flightState.now?.(),
|
||||
});
|
||||
if (absence === 'retain') continue;
|
||||
if (absence === 'stale') {
|
||||
icons._applyIconPresentation(icao24); // the faded freshness alpha
|
||||
@@ -215,6 +246,14 @@ export function createFlightSnapshotRenderer({
|
||||
icons._forgetContact(icao24); // aged out: its 3D model goes too (no orphan / cap leak)
|
||||
}
|
||||
|
||||
// The tracked contact at the new time: its trail starts there.
|
||||
if (
|
||||
replace &&
|
||||
flightState._trackedIcao &&
|
||||
currentIcaos.has(flightState._trackedIcao)
|
||||
)
|
||||
tracking._startTrail(flightState._trackedIcao);
|
||||
|
||||
// Ambient type enrichment: give ON-SCREEN planes real types (bounded
|
||||
// sweep — see _sweepAmbientEnrichment; internally fail-silent).
|
||||
enrichment._sweepAmbientEnrichment();
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { createFlightSnapshotRenderer } from './snapshotRenderer.js';
|
||||
import { createMotion } from './motion.js';
|
||||
import { createFlightState } from './state.js';
|
||||
|
||||
// A poll that repeats a contact's last position with new speed or course
|
||||
// must not move it past where the stale rules allow, and never adds a
|
||||
// report to the tracked trail.
|
||||
|
||||
const ICAO = '00a002';
|
||||
const SEC = 1000;
|
||||
|
||||
/** Any property is a no-op function unless given. */
|
||||
function stub(overrides = {}) {
|
||||
return new Proxy(overrides, {
|
||||
get: (target, key) => (key in target ? target[key] : () => undefined),
|
||||
});
|
||||
}
|
||||
|
||||
function harness({ ground = () => null }) {
|
||||
const appended = [];
|
||||
const history = [];
|
||||
const iconIds = new Set();
|
||||
const groundFloor = stub({
|
||||
cachedGroundFloor: ground,
|
||||
GROUND_FLOOR_LIFT_M: 0.5,
|
||||
});
|
||||
const services = stub({
|
||||
camera: stub(),
|
||||
focus: stub(),
|
||||
groundFloor,
|
||||
meshFloor: stub(),
|
||||
groundSnap: stub({ createGroundSnap: () => stub() }),
|
||||
});
|
||||
const flightState = createFlightState({
|
||||
services,
|
||||
source: { label: 'Fixture aircraft' },
|
||||
});
|
||||
// The shared icon set the layer draws its contacts into.
|
||||
flightState._icons = {
|
||||
has: (id) => iconIds.has(id),
|
||||
ids: () => [...iconIds],
|
||||
get count() {
|
||||
return iconIds.size;
|
||||
},
|
||||
};
|
||||
flightState._trackedIcao = ICAO;
|
||||
flightState._positionHistory.set(ICAO, history);
|
||||
const parts = {
|
||||
rendering: stub({ _modelOwnsVisual: () => false }),
|
||||
icons: stub({
|
||||
_iconIds: () => [...iconIds],
|
||||
_addIcon: (id) => iconIds.add(id),
|
||||
_forgetContact: (id) => iconIds.delete(id),
|
||||
}),
|
||||
};
|
||||
parts.motion = createMotion({ flightState, services, parts, layer: {} });
|
||||
let meta = null;
|
||||
let fixEpochMs = 0;
|
||||
const records = stub({
|
||||
receive: () => {
|
||||
flightState.records.data.set(ICAO, meta);
|
||||
return { prevMeta: meta, meta, groundFlipped: false, fixEpochMs };
|
||||
},
|
||||
absence: () => 'retain',
|
||||
});
|
||||
const apply = createFlightSnapshotRenderer({
|
||||
flightState,
|
||||
records,
|
||||
militaryRegistry: stub({ isMilitaryIcao: () => false }),
|
||||
groundFloor,
|
||||
meshFloor: stub(),
|
||||
rendering: parts.rendering,
|
||||
tracking: stub({
|
||||
_militaryLayerSuppresses: () => false,
|
||||
_appendTrailFix: (position, epochMs) =>
|
||||
appended.push({ position, epochMs }),
|
||||
}),
|
||||
motion: parts.motion,
|
||||
icons: parts.icons,
|
||||
enrichment: stub(),
|
||||
queries: stub({ _likelyLanded: () => false }),
|
||||
});
|
||||
return {
|
||||
history,
|
||||
appended,
|
||||
poll(nextMeta, epochMs) {
|
||||
meta = nextMeta;
|
||||
fixEpochMs = epochMs;
|
||||
apply({ records: [{ id: ICAO }], complete: true }, null);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const lightAircraft = (velocity, track) => ({
|
||||
rawLat: 38.1436,
|
||||
rawLon: -122.5561,
|
||||
renderAltitudeM: 10,
|
||||
altitude: 40,
|
||||
velocity,
|
||||
true_track: track,
|
||||
onGround: false,
|
||||
wasAirborne: true,
|
||||
klass: 'light',
|
||||
});
|
||||
|
||||
test('a low contact whose position repeats while its speed changes is not moved and adds nothing to the trail', (t) => {
|
||||
const t0 = Date.UTC(2026, 10, 9, 20, 0);
|
||||
t.mock.timers.enable({ apis: ['Date'], now: t0 });
|
||||
const h = harness({ ground: () => -30 });
|
||||
h.poll(lightAircraft(36.4, 63), t0);
|
||||
const first = h.history[0].position;
|
||||
for (const [i, velocity] of [30, 22, 14, 9].entries()) {
|
||||
t.mock.timers.tick(10 * SEC);
|
||||
h.poll(lightAircraft(velocity, 63 + i * 20), t0);
|
||||
}
|
||||
assert.equal(h.history.length, 1, 'a synthetic fix moved a holding contact');
|
||||
assert.equal(h.history[0].position, first);
|
||||
assert.equal(h.appended.length, 1, 'only the real report joins the trail');
|
||||
});
|
||||
|
||||
test('a cruising contact whose position repeats coasts no further than the stale cap, and the synthetic fix is not a report', (t) => {
|
||||
const t0 = Date.UTC(2026, 10, 9, 20, 0);
|
||||
t.mock.timers.enable({ apis: ['Date'], now: t0 });
|
||||
const h = harness({});
|
||||
const cruise = (velocity, track) => ({
|
||||
rawLat: 36,
|
||||
rawLon: -115,
|
||||
renderAltitudeM: 9_000,
|
||||
altitude: 9_000,
|
||||
velocity,
|
||||
true_track: track,
|
||||
onGround: false,
|
||||
wasAirborne: true,
|
||||
klass: 'jet',
|
||||
});
|
||||
h.poll(cruise(220, 90), t0);
|
||||
const report = h.history[0].position;
|
||||
t.mock.timers.tick(300 * SEC);
|
||||
h.poll(cruise(200, 100), t0);
|
||||
assert.equal(h.history.length, 2);
|
||||
const moved = Cesium.Cartesian3.distance(report, h.history[1].position);
|
||||
assert.ok(
|
||||
moved <= 220 * 300 + 1,
|
||||
`the synthetic fix coasted ${moved.toFixed(0)} m`,
|
||||
);
|
||||
assert.equal(h.appended.length, 1, 'the synthetic fix joined the trail');
|
||||
});
|
||||
|
||||
test('a report drawn at an invented height says so on its history fix', (t) => {
|
||||
const t0 = Date.UTC(2026, 10, 9, 20, 0);
|
||||
t.mock.timers.enable({ apis: ['Date'], now: t0 });
|
||||
const h = harness({});
|
||||
h.poll({ ...lightAircraft(60, 90), renderAltitudeInvented: true }, t0);
|
||||
h.poll({ ...lightAircraft(60, 90), rawLon: -122.55 }, t0 + 10 * SEC);
|
||||
assert.equal(h.history[0].inventedHeight, true);
|
||||
assert.equal(h.history[1].inventedHeight, false);
|
||||
});
|
||||
|
||||
test('with the ground unknown, a low barometric altitude alone does not hold a contact', (t) => {
|
||||
const t0 = Date.UTC(2026, 10, 9, 20, 0);
|
||||
t.mock.timers.enable({ apis: ['Date'], now: t0 });
|
||||
const h = harness({});
|
||||
h.poll(lightAircraft(36.4, 63), t0);
|
||||
t.mock.timers.tick(10 * SEC);
|
||||
h.poll(lightAircraft(30, 80), t0);
|
||||
// It coasts under the stale cap instead.
|
||||
assert.equal(h.history.length, 2);
|
||||
assert.equal(h.history[0].staleHolds, false);
|
||||
assert.equal(h.appended.length, 1);
|
||||
});
|
||||
@@ -0,0 +1,418 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { createMotion } from './motion.js';
|
||||
import { createFlightState } from './state.js';
|
||||
import { createTracking } from './tracking.js';
|
||||
import {
|
||||
staleCoastSeconds,
|
||||
staleHoldsAtLastReport,
|
||||
} from '../../data/motionModel.js';
|
||||
import { TRAIL_CONTINUITY_MAX_SPEED_KT } from '../../data/trailContinuity.js';
|
||||
import { RENDER_DELAY_SEC } from './policy.js';
|
||||
|
||||
const SEC = 1000;
|
||||
// Ellipsoidal ground at a sea-level airfield (geoid about -32 m).
|
||||
const FIELD_GROUND_M = -30;
|
||||
|
||||
/** A motion module over one contact's history, with a fixed clock. */
|
||||
function motionFixture({ info, fixes, nowMs, ground = () => null }) {
|
||||
const flightState = {
|
||||
records: { data: new Map([['00a001', info]]) },
|
||||
_positionHistory: new Map([['00a001', fixes]]),
|
||||
_focusEvidenceIds: new Set(),
|
||||
_scratchArc: {},
|
||||
_scratchOffset: new Cesium.Cartesian3(),
|
||||
_scratchRenderTime: new Cesium.JulianDate(),
|
||||
_scratchCoastCarto: new Cesium.Cartographic(),
|
||||
now: () => nowMs,
|
||||
};
|
||||
const motion = createMotion({
|
||||
flightState,
|
||||
services: {
|
||||
groundFloor: {
|
||||
cachedGroundFloor: ground,
|
||||
floorAltitudeM: (alt, g) =>
|
||||
Number.isFinite(g) ? Math.max(alt, g + 1.5) : alt,
|
||||
},
|
||||
camera: {},
|
||||
focus: {},
|
||||
},
|
||||
parts: {},
|
||||
});
|
||||
return { flightState, motion };
|
||||
}
|
||||
|
||||
function fix(timeMs, lat, lon, heightM, velocity, track) {
|
||||
return {
|
||||
time: Cesium.JulianDate.fromDate(new Date(timeMs)),
|
||||
epochMs: timeMs,
|
||||
position: Cesium.Cartesian3.fromDegrees(lon, lat, heightM),
|
||||
velocity,
|
||||
track,
|
||||
};
|
||||
}
|
||||
|
||||
const height = (position) => Cesium.Cartographic.fromCartesian(position).height;
|
||||
|
||||
test('a stale contact holds at its last report when it reported on the ground or low', () => {
|
||||
assert.equal(staleHoldsAtLastReport({ onGround: true }), true);
|
||||
// A light aircraft on final: -30 m barometric, its render height 1.5 m above the known ground.
|
||||
assert.equal(
|
||||
staleHoldsAtLastReport({
|
||||
onGround: false,
|
||||
heightM: FIELD_GROUND_M + 1.5,
|
||||
groundM: FIELD_GROUND_M,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
// Ground unknown: a low barometric altitude alone does not hold it; it
|
||||
// coasts under the cap.
|
||||
assert.equal(
|
||||
staleHoldsAtLastReport({ onGround: false, heightM: 120 }),
|
||||
false,
|
||||
);
|
||||
// A high airfield: 1,600 m barometric but 60 m above its ground.
|
||||
assert.equal(
|
||||
staleHoldsAtLastReport({
|
||||
onGround: false,
|
||||
heightM: 1_660,
|
||||
groundM: 1_600,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
staleHoldsAtLastReport({
|
||||
onGround: false,
|
||||
heightM: 10_000,
|
||||
groundM: 20,
|
||||
}),
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test('a stale contact coasts up to its source limit at any speed, and a holding one not at all', () => {
|
||||
const coast = (over) =>
|
||||
staleCoastSeconds({
|
||||
elapsedSec: 400,
|
||||
coastLimitSec: 300,
|
||||
speedMps: 230,
|
||||
holds: false,
|
||||
...over,
|
||||
});
|
||||
assert.equal(coast(), 300);
|
||||
assert.equal(coast({ elapsedSec: 200 }), 200);
|
||||
assert.equal(coast({ coastLimitSec: 60 }), 60);
|
||||
assert.equal(coast({ speedMps: 1_000 }), 300);
|
||||
assert.equal(coast({ holds: true }), 0);
|
||||
assert.equal(coast({ elapsedSec: -5 }), 0);
|
||||
});
|
||||
|
||||
test('a light aircraft on short final goes stale after a low, slow, descending report, the icon holds at that report, not below the ground', () => {
|
||||
const t0 = Date.UTC(2026, 10, 9, 20, 0);
|
||||
const fixes = [
|
||||
fix(t0, 38.1279, -122.5425, 122, 40, 340),
|
||||
fix(t0 + 30 * SEC, 38.133, -122.5494, 38, 37, 10),
|
||||
fix(t0 + 60 * SEC, 38.1436, -122.5561, FIELD_GROUND_M + 1.5, 36.4, 63),
|
||||
];
|
||||
const info = {
|
||||
altitude: -30,
|
||||
renderAltitudeM: FIELD_GROUND_M + 1.5,
|
||||
rawLat: 38.1436,
|
||||
rawLon: -122.5561,
|
||||
velocity: 36.4,
|
||||
true_track: 63,
|
||||
onGround: false,
|
||||
wasAirborne: true,
|
||||
lastContactEpochMs: t0 + 60 * SEC,
|
||||
};
|
||||
for (const afterSec of [5, 45, 90, 240]) {
|
||||
const nowMs = t0 + 60 * SEC + RENDER_DELAY_SEC * SEC + afterSec * SEC;
|
||||
const { motion } = motionFixture({
|
||||
info,
|
||||
fixes,
|
||||
nowMs,
|
||||
ground: () => FIELD_GROUND_M,
|
||||
});
|
||||
const drawn = motion._deadReckon('00a001', new Cesium.Cartesian3());
|
||||
assert.ok(
|
||||
Cesium.Cartesian3.distance(drawn, fixes[2].position) < 0.01,
|
||||
`${afterSec} s after the report the icon is at the report`,
|
||||
);
|
||||
assert.ok(height(drawn) >= FIELD_GROUND_M);
|
||||
}
|
||||
});
|
||||
|
||||
function cruiser(lastContactAfterSec) {
|
||||
const t0 = Date.UTC(2026, 10, 9, 20, 0);
|
||||
const fixes = [
|
||||
fix(t0, 40, -100, 10_000, 230, 90),
|
||||
fix(t0 + 15 * SEC, 40, -99.96, 10_000, 230, 90),
|
||||
];
|
||||
const info = {
|
||||
altitude: 10_000,
|
||||
renderAltitudeM: 10_000,
|
||||
rawLat: 40,
|
||||
rawLon: -99.96,
|
||||
velocity: 230,
|
||||
true_track: 90,
|
||||
onGround: false,
|
||||
wasAirborne: true,
|
||||
lastContactEpochMs: t0 + 15 * SEC + lastContactAfterSec * SEC,
|
||||
};
|
||||
const at = (afterSec) => {
|
||||
const nowMs = t0 + 15 * SEC + RENDER_DELAY_SEC * SEC + afterSec * SEC;
|
||||
const { motion } = motionFixture({ info, fixes, nowMs });
|
||||
return motion._deadReckon('00a001', new Cesium.Cartesian3());
|
||||
};
|
||||
const d = (p) => Cesium.Cartesian3.distance(p, fixes[1].position);
|
||||
return { at, d };
|
||||
}
|
||||
|
||||
test('a cruising contact still heard after its last position coasts past 90 s, for up to 5 minutes, then stops', () => {
|
||||
// Contact kept arriving for four minutes after the last position.
|
||||
const { at, d } = cruiser(240);
|
||||
const near = (got, want) => Math.abs(got - want) < want * 0.005 + 50;
|
||||
assert.ok(near(d(at(90)), 230 * 90));
|
||||
assert.ok(near(d(at(200)), 230 * 200), 'still moving at 200 s');
|
||||
assert.ok(near(d(at(300)), 230 * 300));
|
||||
assert.ok(near(d(at(400)), 230 * 300), 'stopped at 300 s');
|
||||
assert.ok(Cesium.Cartesian3.distance(at(400), at(600)) < 0.01);
|
||||
});
|
||||
|
||||
test('a cruising contact that stops reporting coasts five minutes, then stops', () => {
|
||||
const { at, d } = cruiser(0);
|
||||
assert.ok(Math.abs(d(at(60)) - 230 * 60) < 120);
|
||||
assert.ok(Math.abs(d(at(300)) - 230 * 300) < 600);
|
||||
assert.ok(Cesium.Cartesian3.distance(at(301), at(420)) < 0.01);
|
||||
});
|
||||
|
||||
test('a bad reported speed coasts no faster than the 1,500 kt continuity limit', () => {
|
||||
const t0 = Date.UTC(2026, 10, 9, 20, 0);
|
||||
// 2,000 m/s (about 3,900 kt): a corrupt velocity, not a real aircraft.
|
||||
const fixes = [
|
||||
fix(t0, 40, -100, 10_000, 2_000, 90),
|
||||
fix(t0 + 15 * SEC, 40, -99.96, 10_000, 2_000, 90),
|
||||
];
|
||||
const info = {
|
||||
altitude: 10_000,
|
||||
renderAltitudeM: 10_000,
|
||||
rawLat: 40,
|
||||
rawLon: -99.96,
|
||||
velocity: 2_000,
|
||||
true_track: 90,
|
||||
onGround: false,
|
||||
wasAirborne: true,
|
||||
};
|
||||
const nowMs = t0 + 15 * SEC + RENDER_DELAY_SEC * SEC + 300 * SEC;
|
||||
const { motion } = motionFixture({ info, fixes, nowMs });
|
||||
const drawn = motion._deadReckon('00a001', new Cesium.Cartesian3());
|
||||
const limitMps = (TRAIL_CONTINUITY_MAX_SPEED_KT * 1852) / 3600;
|
||||
const d = Cesium.Cartesian3.distance(drawn, fixes[1].position);
|
||||
assert.ok(Math.abs(d - limitMps * 300) < 1_500, `${d.toFixed(0)} m`);
|
||||
});
|
||||
|
||||
test('coasting never takes a contact below the ground', () => {
|
||||
const t0 = Date.UTC(2026, 10, 9, 20, 0);
|
||||
const fixes = [
|
||||
fix(t0, 39.7, -105.5, 3_400, 80, 270),
|
||||
fix(t0 + 15 * SEC, 39.7, -105.514, 3_400, 80, 270),
|
||||
];
|
||||
const info = {
|
||||
altitude: 3_400,
|
||||
renderAltitudeM: 3_400,
|
||||
rawLat: 39.7,
|
||||
rawLon: -105.514,
|
||||
velocity: 80,
|
||||
true_track: 270,
|
||||
onGround: false,
|
||||
wasAirborne: true,
|
||||
};
|
||||
// 3,000 m under the report, rising to 3,600 m along the coast west.
|
||||
const nowMs = t0 + 15 * SEC + RENDER_DELAY_SEC * SEC + 60 * SEC;
|
||||
const { motion } = motionFixture({
|
||||
info,
|
||||
fixes,
|
||||
nowMs,
|
||||
ground: (lat, lon) => (lon < -105.52 ? 3_600 : 3_000),
|
||||
});
|
||||
const drawn = motion._deadReckon('00a001', new Cesium.Cartesian3());
|
||||
assert.ok(height(drawn) >= 3_600, `height ${height(drawn)}`);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// The trail and head across a stale gap.
|
||||
|
||||
function services(trail) {
|
||||
const names = [
|
||||
'picking',
|
||||
'sprites',
|
||||
'aircraftPresentation',
|
||||
'camera',
|
||||
'militaryRegistry',
|
||||
'labels',
|
||||
'meshFloor',
|
||||
'focus',
|
||||
'readout',
|
||||
'context',
|
||||
'render',
|
||||
'recession',
|
||||
];
|
||||
return {
|
||||
...Object.fromEntries(names.map((name) => [name, {}])),
|
||||
groundSnap: { createGroundSnap: () => ({ clear() {} }) },
|
||||
trails: trail,
|
||||
geoid: { ensureGeoidReady: async () => {}, geoidHeight: () => 0 },
|
||||
groundFloor: {
|
||||
resolveGroundFloorCellsBounded: async () => {},
|
||||
cachedGroundFloor: () => null,
|
||||
floorAltitudeM: (alt) => alt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function trailHarness({ fixes, nowMs, head }) {
|
||||
const calls = [];
|
||||
const trail = {
|
||||
createTrail: () => ({
|
||||
setSegments(segments) {
|
||||
calls.push(segments.map((segment) => segment.slice()));
|
||||
},
|
||||
setPositions(positions) {
|
||||
calls.push([positions.slice()]);
|
||||
},
|
||||
setVisible() {},
|
||||
clear() {},
|
||||
destroy() {},
|
||||
}),
|
||||
};
|
||||
const svc = services(trail);
|
||||
const flightState = createFlightState({
|
||||
services: svc,
|
||||
source: { label: 'Fixture aircraft' },
|
||||
});
|
||||
const added = [];
|
||||
flightState._viewer = {
|
||||
isDestroyed: () => false,
|
||||
entities: {
|
||||
add(definition) {
|
||||
added.push(definition);
|
||||
return definition;
|
||||
},
|
||||
remove() {},
|
||||
},
|
||||
};
|
||||
flightState._trackedIcao = '00a001';
|
||||
let clock = nowMs;
|
||||
flightState.now = () => clock;
|
||||
flightState._positionHistory.set('00a001', fixes);
|
||||
let headPosition = head;
|
||||
const tracking = createTracking({
|
||||
flightState,
|
||||
services: svc,
|
||||
parts: {
|
||||
motion: {
|
||||
_isTrackWarmingUp: () => false,
|
||||
_trackedTrailCached: () => headPosition,
|
||||
_trackedDisplayPosition: () => headPosition,
|
||||
_trackedModelCenterWorld: () => null,
|
||||
_trackedModelEnvelopeM: () => null,
|
||||
},
|
||||
},
|
||||
layer: {},
|
||||
});
|
||||
return {
|
||||
tracking,
|
||||
flightState,
|
||||
drawn: () => (calls.at(-1) ?? []).flat(),
|
||||
// The live head the trail would draw now.
|
||||
head: () => tracking._trailHeadPositions(),
|
||||
setClock: (ms) => {
|
||||
clock = ms;
|
||||
},
|
||||
setHead: (position) => {
|
||||
headPosition = position;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('a holding contact draws no head, and the trail ends at the last report, never past the icon', () => {
|
||||
const t0 = Date.UTC(2026, 10, 9, 20, 0);
|
||||
const fixes = [
|
||||
fix(t0, 38.1678, -122.527, 303, 45, 200),
|
||||
fix(t0 + 30 * SEC, 38.1279, -122.5425, 122, 40, 340),
|
||||
fix(t0 + 60 * SEC, 38.133, -122.5494, 38, 37, 10),
|
||||
fix(t0 + 90 * SEC, 38.1436, -122.5561, 0, 36.4, 63),
|
||||
];
|
||||
const last = fixes.at(-1).position;
|
||||
// The display time is long past the last report; the icon holds there.
|
||||
const h = trailHarness({
|
||||
fixes,
|
||||
nowMs: t0 + 90 * SEC + RENDER_DELAY_SEC * SEC + 120 * SEC,
|
||||
head: Cesium.Cartesian3.clone(last),
|
||||
});
|
||||
h.tracking._startTrail('00a001');
|
||||
// Every report, including the last, is in the trail: the head no longer
|
||||
// cuts from the one before it to the icon.
|
||||
assert.equal(h.drawn().length, 4);
|
||||
assert.equal(h.drawn().at(-1), h.flightState._trailFixes.at(-1).position);
|
||||
assert.deepEqual(h.head(), []);
|
||||
});
|
||||
|
||||
test('while the display is between reports, the trail stops at the report behind the icon', () => {
|
||||
const t0 = Date.UTC(2026, 10, 9, 20, 0);
|
||||
// Reports every 10 s; the icon is drawn 30 s behind, between the 2nd and 3rd.
|
||||
const fixes = [0, 1, 2, 3, 4, 5].map((i) =>
|
||||
fix(t0 + i * 10 * SEC, 40, -100 + i * 0.03, 10_000, 230, 90),
|
||||
);
|
||||
const nowMs = t0 + 25 * SEC + RENDER_DELAY_SEC * SEC;
|
||||
const icon = Cesium.Cartesian3.fromDegrees(-100 + 0.075, 40, 10_000);
|
||||
const h = trailHarness({ fixes, nowMs, head: icon });
|
||||
h.tracking._startTrail('00a001');
|
||||
// Reports at 0, 10 and 20 s are behind the icon (display time 25 s).
|
||||
assert.equal(h.drawn().length, 3);
|
||||
const head = h.head();
|
||||
assert.equal(head.length, 2);
|
||||
assert.ok(Cesium.Cartesian3.distance(head[0], fixes[2].position) < 0.01);
|
||||
});
|
||||
|
||||
test('the hold-or-coast decision is made once per report: a floor that resolves mid-coast does not snap the icon back', () => {
|
||||
const t0 = Date.UTC(2026, 10, 9, 20, 0);
|
||||
const fixes = [
|
||||
fix(t0, 39.7, -104.6, 1_900, 70, 270),
|
||||
fix(t0 + 15 * SEC, 39.7, -104.6123, 1_900, 70, 270),
|
||||
];
|
||||
const info = {
|
||||
altitude: 1_950,
|
||||
renderAltitudeM: 1_900,
|
||||
rawLat: 39.7,
|
||||
rawLon: -104.6123,
|
||||
velocity: 70,
|
||||
true_track: 270,
|
||||
onGround: false,
|
||||
wasAirborne: true,
|
||||
lastContactEpochMs: t0 + 15 * SEC + 120 * SEC,
|
||||
};
|
||||
// No floor known when the contact goes stale: baro says well clear of the
|
||||
// ground, so it coasts. Mid-coast the floor resolves 100 m under the report.
|
||||
let ground = () => null;
|
||||
const at = (afterSec) => {
|
||||
const nowMs = t0 + 15 * SEC + RENDER_DELAY_SEC * SEC + afterSec * SEC;
|
||||
const { motion } = motionFixture({
|
||||
info,
|
||||
fixes,
|
||||
nowMs,
|
||||
ground: (lat, lon) => ground(lat, lon),
|
||||
});
|
||||
return motion._deadReckon('00a001', new Cesium.Cartesian3());
|
||||
};
|
||||
const d = (p) => Cesium.Cartesian3.distance(p, fixes[1].position);
|
||||
const before = d(at(30));
|
||||
assert.ok(Math.abs(before - 70 * 30) < 50, `coasted ${before.toFixed(0)} m`);
|
||||
ground = () => 1_800;
|
||||
const after = d(at(31));
|
||||
assert.ok(
|
||||
after > before,
|
||||
`the icon went from ${before.toFixed(0)} m to ${after.toFixed(0)} m`,
|
||||
);
|
||||
});
|
||||
@@ -10,9 +10,13 @@ export function createFlightState({ source, services }) {
|
||||
flightState.records = new FlightRecords({
|
||||
...services.geoid,
|
||||
...services.groundFloor,
|
||||
now: () => flightState.now(),
|
||||
});
|
||||
/** The time contacts are drawn behind by the render delay, in epoch ms. */
|
||||
flightState.now = worldTimeFor('flights');
|
||||
/** Follows the world clock while the source declares a timeline (set by the
|
||||
* layer); see followsClock and displayDelayMs in policy.js. */
|
||||
flightState.timeline = null;
|
||||
|
||||
/** Per-class model spec. Hangar-fleet classes (CLASS_MODEL_REAL) ship GLBs
|
||||
* vertex-baked to real-world METERS in the airplane.glb axis convention, so
|
||||
@@ -154,9 +158,32 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._trailHeadOff = null;
|
||||
|
||||
/** @type {{x: number, y: number, z: number}[]} Chronological tracked-aircraft fixes (oldest first) */
|
||||
/** @type {{position: {x: number, y: number, z: number}|null, timeMs: number, nullAltitude: boolean, breakBefore: boolean, drawn?: boolean}[]}
|
||||
* Chronological tracked-aircraft trail (oldest first): reports, and
|
||||
* (`drawn`) where the icon was drawn between them; `breakBefore` starts a
|
||||
* new segment. */
|
||||
|
||||
flightState._trailPositions = [];
|
||||
flightState._trailFixes = [];
|
||||
|
||||
/** @type {number} Body fixes drawn: those at or before the display time. */
|
||||
|
||||
flightState._trailBodyCount = 0;
|
||||
|
||||
/** @type {{x: number, y: number, z: number}|null} Where the tracked icon was last recorded into the trail. */
|
||||
|
||||
flightState._trailRecordPosition = null;
|
||||
|
||||
/** @type {number} Display time (epoch ms) of that recording. */
|
||||
|
||||
flightState._trailRecordMs = -Infinity;
|
||||
|
||||
/** @type {string|undefined} The stale cue last written into the tracked label (see `_staleCueTick`). */
|
||||
|
||||
flightState._trackedStaleCueText = undefined;
|
||||
|
||||
/** @type {{key: string, cue: {text: string, dimmed: boolean}}|null} This frame's tracked stale cue (see `_trackedStaleCue`). */
|
||||
|
||||
flightState._trackedStaleCueCache = null;
|
||||
|
||||
/** @type {number} Monotonic token — invalidates in-flight backfill responses */
|
||||
|
||||
@@ -291,6 +318,10 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._enrichSeen = new Set();
|
||||
|
||||
/** Lookup key -> epoch ms before which a failed lookup is not asked again. */
|
||||
|
||||
flightState._enrichRetryAfter = new Map();
|
||||
|
||||
flightState._enrichAmbientBudget = ENRICH_AMBIENT_BUDGET_CEIL;
|
||||
|
||||
/** Epoch ms the bucket last accounted a refill window from (0 = unset). */
|
||||
@@ -307,6 +338,9 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._drPrevMs = 0;
|
||||
|
||||
/** World time of that frame: the wall clock live, the cursor following the clock. */
|
||||
flightState._drPrevWorldMs = 0;
|
||||
|
||||
flightState._drReconcileValid = false;
|
||||
|
||||
/** @type {string|null} icao the reconciliation state currently belongs to */
|
||||
|
||||
@@ -227,6 +227,19 @@ export function createTesting({
|
||||
);
|
||||
}
|
||||
|
||||
/** Forget every enrichment lookup and the dispatch clock, so a test that
|
||||
* moved `Date.now` leaves no future-dated drip or cool-down behind. */
|
||||
function _resetEnrichmentForTest() {
|
||||
flightState._enrichQueue.length = 0;
|
||||
flightState._enrichSeen.clear();
|
||||
flightState._enrichRetryAfter.clear();
|
||||
flightState._enrichLastDispatchMs = 0;
|
||||
if (flightState._enrichDripTimer) {
|
||||
clearTimeout(flightState._enrichDripTimer);
|
||||
flightState._enrichDripTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Exercise the exact fleet admission and return the admitted model's record. */
|
||||
|
||||
function _ensureFleetModelForTest(icao24) {
|
||||
@@ -277,5 +290,6 @@ export function createTesting({
|
||||
_ensureFleetModelForTest,
|
||||
_trackedModelForTest,
|
||||
_modelSetIdsForTest,
|
||||
_resetEnrichmentForTest,
|
||||
};
|
||||
}
|
||||
+285
-94
@@ -18,13 +18,9 @@ import {
|
||||
trackedContactHolder,
|
||||
} from '../../data/trackedAircraftIcon.js';
|
||||
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
|
||||
import {
|
||||
addSeconds,
|
||||
julianLessThanOrEquals,
|
||||
julianFromEpochMs,
|
||||
julianToEpochMs,
|
||||
} from '../../geo/julian.js';
|
||||
import { clone, distanceSquared, vec } from '../../geo/vector.js';
|
||||
import { julianToEpochMs } from '../../geo/julian.js';
|
||||
import { renderedFrames } from '../../data/renderedFrames.js';
|
||||
import { clone, distance, distanceSquared, vec } from '../../geo/vector.js';
|
||||
import { trailHeadStart } from '../../data/modelVisualAnchor.js';
|
||||
import { aircraftIcon, TRACKED_ICON_PX } from '../../data/aircraftIcons.js';
|
||||
import { routePlausible } from '../../data/routePlausible.js';
|
||||
@@ -36,12 +32,30 @@ import {
|
||||
import { inputFor } from '../../input/dispatcher.js';
|
||||
import {
|
||||
TRAIL_MAX_POINTS,
|
||||
RENDER_DELAY_SEC,
|
||||
DR_CORRECTION_MS,
|
||||
TRAIL_COLOR,
|
||||
CYAN_TRANSPARENT,
|
||||
TRACKED_CYAN,
|
||||
TRACKED_BILLBOARD_SCALE_BY_DISTANCE,
|
||||
STALE_ALPHA,
|
||||
displayDelayMs,
|
||||
followsClock,
|
||||
} from './policy.js';
|
||||
import {
|
||||
drawTrailSegments,
|
||||
historyFixEpochMs,
|
||||
insertTrailFix,
|
||||
joinTrailBackfill,
|
||||
recordTrailPoint,
|
||||
trailBackfillFixes,
|
||||
trailBodyCount,
|
||||
trailBodyCountOutsideModel,
|
||||
trailBodySegments,
|
||||
trailHeadStartFix,
|
||||
trailRecordingBlocked,
|
||||
TRAIL_RECORD_STEP_M,
|
||||
TRAIL_RECORD_STEP_MS,
|
||||
} from '../../data/trailContinuity.js';
|
||||
import { roundHeadingDegrees } from '../../data/headingDegrees.js';
|
||||
import { entityRecord } from '../../data/entityRecords.js';
|
||||
|
||||
@@ -56,6 +70,8 @@ function aircraftPickId(hit) {
|
||||
return isOtherTrackedIconSet(hit.set, 'flights') ? undefined : hit.id;
|
||||
}
|
||||
|
||||
const STALE_CYAN = Object.freeze([...TRACKED_CYAN.slice(0, 3), STALE_ALPHA]);
|
||||
|
||||
export function createTracking({
|
||||
flightState,
|
||||
services,
|
||||
@@ -342,18 +358,78 @@ export function createTracking({
|
||||
}
|
||||
|
||||
/**
|
||||
* Append one fix to the tracked aircraft's trail accumulation and refresh
|
||||
* the rendered trail. Caller passes an owned (cloned) Cartesian3.
|
||||
* @param {{x: number, y: number, z: number}} position - New ECEF fix, appended at the head.
|
||||
* Put one report into the tracked aircraft's trail, in time order, and
|
||||
* refresh the rendered trail. Caller passes an owned (cloned) position. A
|
||||
* report that breaks from its neighbour starts a new segment (see
|
||||
* trailContinuity).
|
||||
* @param {{x: number, y: number, z: number}} position - The report's ECEF position.
|
||||
* @param {number} [epochMs] - The report's time; defaults to the tracked
|
||||
* aircraft's newest position-history fix, which every caller has just pushed.
|
||||
* @param {{nullAltitude?: boolean}} [options] - `nullAltitude`: the report
|
||||
* had no altitude, so its position is not kept and the line breaks there.
|
||||
* A report for a time the display has already passed replaces what was
|
||||
* drawn after it (see `insertTrailFix`).
|
||||
*/
|
||||
|
||||
function _appendTrailFix(position) {
|
||||
flightState._trailPositions.push(position);
|
||||
if (flightState._trailPositions.length > TRAIL_MAX_POINTS)
|
||||
flightState._trailPositions.shift();
|
||||
function _appendTrailFix(position, epochMs, { nullAltitude = false } = {}) {
|
||||
const history = flightState._positionHistory.get(flightState._trackedIcao);
|
||||
const timeMs = Number.isFinite(epochMs)
|
||||
? epochMs
|
||||
: historyFixEpochMs(history?.[history.length - 1]);
|
||||
insertTrailFix(
|
||||
flightState._trailFixes,
|
||||
position,
|
||||
timeMs,
|
||||
TRAIL_MAX_POINTS,
|
||||
{
|
||||
nullAltitude,
|
||||
displayMs: flightState.now() - displayDelayMs(flightState),
|
||||
settleMs: DR_CORRECTION_MS,
|
||||
},
|
||||
);
|
||||
_refreshTrailDisplay();
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-frame trail work, run before each frame draws whether or not the
|
||||
* head is visible: record where the tracked icon is drawn (at most once a
|
||||
* second or every 150 m) and move the body on as the display time passes
|
||||
* reports. The head only reads the result.
|
||||
*/
|
||||
|
||||
function _trailTick() {
|
||||
if (!flightState._trackedIcao || !flightState._trail) return;
|
||||
const displayMs = flightState.now() - displayDelayMs(flightState);
|
||||
let changed = false;
|
||||
if (
|
||||
flightState._trailFixes.length &&
|
||||
!parts.motion._isTrackWarmingUp() &&
|
||||
!trailRecordingBlocked(flightState._trailFixes, displayMs)
|
||||
) {
|
||||
const drawn = parts.motion._trackedDisplayPosition(
|
||||
flightState._trackedIcao,
|
||||
);
|
||||
const last = flightState._trailRecordPosition;
|
||||
if (
|
||||
drawn &&
|
||||
(!last ||
|
||||
displayMs - flightState._trailRecordMs >= TRAIL_RECORD_STEP_MS ||
|
||||
distance(last, drawn) >= TRAIL_RECORD_STEP_M)
|
||||
) {
|
||||
flightState._trailRecordMs = displayMs;
|
||||
flightState._trailRecordPosition = clone(drawn);
|
||||
changed = recordTrailPoint(
|
||||
flightState._trailFixes,
|
||||
clone(drawn),
|
||||
displayMs,
|
||||
TRAIL_MAX_POINTS,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (changed || _trailBodyCountNow() !== flightState._trailBodyCount)
|
||||
_refreshTrailDisplay();
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the trail with its head clamped to the render-behind display
|
||||
* position. Raw newest fixes run up to RENDER_DELAY_SEC ahead of the
|
||||
@@ -363,17 +439,33 @@ export function createTracking({
|
||||
*/
|
||||
|
||||
function _refreshTrailDisplay() {
|
||||
// The trail BODY is the accumulated fixes EXCLUDING the newest raw one — that newest
|
||||
// fix is at ~now, ~one poll interval AHEAD of the delayed icon (rendered at
|
||||
// now − RENDER_DELAY_SEC), so drawing it would push the trail in front of the plane.
|
||||
// The cheap per-frame trail head segment bridges the last body point to the
|
||||
// delayed dead-reckoned head, so the body primitive only rebuilds on a real fix
|
||||
// (poll cadence), never at motion cadence.
|
||||
// The trail BODY is the accumulated fixes at or before the delayed display time
|
||||
// (now − RENDER_DELAY_SEC); newer fixes are AHEAD of the icon, so drawing them
|
||||
// would push the trail in front of the plane. The cheap per-frame trail head
|
||||
// line bridges the last body point to the delayed dead-reckoned head, so the
|
||||
// body rebuilds only on a real fix or when the display time passes one, never
|
||||
// at motion cadence.
|
||||
// A break lifts the pen: each segment is its own line, nothing between them.
|
||||
if (!flightState._trail) return;
|
||||
flightState._trail.setPositions(
|
||||
flightState._trailPositions.length > 1
|
||||
? flightState._trailPositions.slice(0, -1)
|
||||
: flightState._trailPositions,
|
||||
flightState._trailBodyCount = _trailBodyCountNow();
|
||||
drawTrailSegments(
|
||||
flightState._trail,
|
||||
trailBodySegments(flightState._trailFixes, flightState._trailBodyCount),
|
||||
);
|
||||
}
|
||||
|
||||
/** Fixes at or before the time the aircraft is drawn (now − RENDER_DELAY_SEC),
|
||||
* less the newest recorded points inside its 3D model. */
|
||||
|
||||
function _trailBodyCountNow() {
|
||||
return trailBodyCountOutsideModel(
|
||||
flightState._trailFixes,
|
||||
trailBodyCount(
|
||||
flightState._trailFixes,
|
||||
flightState.now() - displayDelayMs(flightState),
|
||||
),
|
||||
parts.motion._trackedModelCenterWorld(),
|
||||
parts.motion._trackedModelEnvelopeM(),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -383,14 +475,13 @@ export function createTracking({
|
||||
* @returns {Array<{x: number, y: number, z: number}>}
|
||||
*/
|
||||
function _trailHeadPositions() {
|
||||
// Need ≥2 accumulated points: the body draws all-but-newest, so the head must
|
||||
// start at the last DISPLAYED body point (index n−2). With a single fix that
|
||||
// point would be the sole raw fix — which is ~now, AHEAD of the delayed icon —
|
||||
// so the segment would draw IN FRONT of the plane. Likewise during warm-up the
|
||||
// icon predates all real history, so there is no valid body point behind it.
|
||||
// The head starts at the last DISPLAYED body point, the newest fix at or
|
||||
// before the delayed display time; a fix ahead of the icon would draw the
|
||||
// segment IN FRONT of the plane. During warm-up the icon predates all real
|
||||
// history, so there is no valid body point behind it.
|
||||
if (
|
||||
!flightState._trackedIcao ||
|
||||
flightState._trailPositions.length < 2 ||
|
||||
!flightState._trailFixes.length ||
|
||||
parts.motion._isTrackWarmingUp()
|
||||
)
|
||||
return [];
|
||||
@@ -398,10 +489,17 @@ export function createTracking({
|
||||
parts.motion._trackedTrailCached() ||
|
||||
parts.motion._trackedDisplayPosition(flightState._trackedIcao);
|
||||
if (!head) return [];
|
||||
// body[n−2] (last displayed body point) → delayed head: runs FORWARD, never a
|
||||
// backward/reversing segment.
|
||||
const start =
|
||||
flightState._trailPositions[flightState._trailPositions.length - 2];
|
||||
// The last body point (a report, or where the icon was drawn a moment
|
||||
// ago) → the icon. No head across a break: a body point more than 150 km
|
||||
// away, or too long ago or too far to be one path, stays detached; none
|
||||
// while the aircraft holds at its last point.
|
||||
const last = trailHeadStartFix(
|
||||
flightState._trailFixes,
|
||||
head,
|
||||
flightState.now(),
|
||||
flightState._trailBodyCount,
|
||||
);
|
||||
if (!last) return [];
|
||||
// On a contact that has not moved this segment runs from inside the
|
||||
// model out to its own anchor — a line through the fuselage. The END
|
||||
// never gives, so a moving trail still terminates on the tail; the
|
||||
@@ -410,7 +508,7 @@ export function createTracking({
|
||||
// See trailHeadStart. Read `head` in place and clone only on the draw
|
||||
// path — a suppressed parked contact runs this every frame.
|
||||
const from = trailHeadStart(
|
||||
start,
|
||||
last.position,
|
||||
head,
|
||||
parts.motion._trackedModelCenterWorld(),
|
||||
parts.motion._trackedModelEnvelopeM(),
|
||||
@@ -420,8 +518,10 @@ export function createTracking({
|
||||
return [from, clone(head)];
|
||||
}
|
||||
|
||||
/** Each drawn frame, before it draws: the live head where the aircraft is now. */
|
||||
/** Each drawn frame, before it draws: the trail moved on, then the live
|
||||
* head where the aircraft is now. */
|
||||
function _drawTrailHead() {
|
||||
_trailTick();
|
||||
flightState._trail?.setHead(_trailHeadPositions());
|
||||
}
|
||||
|
||||
@@ -434,21 +534,24 @@ export function createTracking({
|
||||
|
||||
function _startTrail(icao24) {
|
||||
flightState._trailBackfillToken += 1;
|
||||
flightState._trailPositions = [];
|
||||
flightState._trailFixes = [];
|
||||
flightState._trailRecordPosition = null;
|
||||
flightState._trailRecordMs = -Infinity;
|
||||
const history = flightState._positionHistory.get(icao24) || [];
|
||||
// Seed only fixes at/behind the DELAYED display time (now − RENDER_DELAY_SEC). The
|
||||
// newest ~RENDER_DELAY_SEC of fixes are AHEAD of the displayed icon; including them
|
||||
// would draw the trail in front of the plane. They join the trail via _appendTrailFix
|
||||
// as they age past the delay.
|
||||
const seedRenderTime = addSeconds(
|
||||
julianFromEpochMs(flightState.now()),
|
||||
-RENDER_DELAY_SEC,
|
||||
flightState._scratchWarmupTime,
|
||||
);
|
||||
// Seed every report. The body only draws those at or before the delayed
|
||||
// display time (now − RENDER_DELAY_SEC); newer ones join it as the display
|
||||
// passes them. A synthetic forward fix (it carries `reportEpochMs`) is a
|
||||
// motion aid, never a report. A report drawn at an invented height keeps
|
||||
// no position and breaks the line.
|
||||
for (const fix of history) {
|
||||
if (julianLessThanOrEquals(fix.time, seedRenderTime)) {
|
||||
flightState._trailPositions.push(clone(fix.position));
|
||||
}
|
||||
if (Number.isFinite(fix.reportEpochMs)) continue;
|
||||
insertTrailFix(
|
||||
flightState._trailFixes,
|
||||
clone(fix.position),
|
||||
historyFixEpochMs(fix),
|
||||
TRAIL_MAX_POINTS,
|
||||
{ nullAltitude: fix.inventedHeight === true },
|
||||
);
|
||||
}
|
||||
if (!flightState._trail && flightState._viewer) {
|
||||
flightState._trail = createTrail(flightState._viewer, {
|
||||
@@ -486,15 +589,16 @@ export function createTracking({
|
||||
|
||||
async function _backfillTrail(icao24, token, oldestFixEpochSec) {
|
||||
let path = null;
|
||||
// Following the world clock, the track ends at the world's time.
|
||||
const atMs = followsClock(flightState) ? flightState.now() : undefined;
|
||||
try {
|
||||
const signal = AbortSignal.any([
|
||||
flightState.lifetime.signal,
|
||||
AbortSignal.timeout(8000),
|
||||
]);
|
||||
const track = await flightState.feed._source.getTrack?.(
|
||||
flightState.records.data.get(icao24)?.sourceReference ?? icao24,
|
||||
{
|
||||
signal: AbortSignal.any([
|
||||
flightState.lifetime.signal,
|
||||
AbortSignal.timeout(8000),
|
||||
]),
|
||||
},
|
||||
atMs === undefined ? { signal } : { signal, atMs },
|
||||
);
|
||||
path = track?.records ?? null;
|
||||
} catch {
|
||||
@@ -524,8 +628,15 @@ export function createTracking({
|
||||
} = waypoint;
|
||||
const time = observedAtMs / 1000;
|
||||
if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue;
|
||||
if (atMs !== undefined && !(observedAtMs <= atMs)) continue;
|
||||
if (!Number.isFinite(time) || time >= oldestFixEpochSec) continue;
|
||||
parsed.push({ lat, lon, baroAlt });
|
||||
parsed.push({
|
||||
lat,
|
||||
lon,
|
||||
baroAlt,
|
||||
onGround: waypoint.onGround === true,
|
||||
timeMs: observedAtMs,
|
||||
});
|
||||
}
|
||||
if (!parsed.length) return;
|
||||
|
||||
@@ -548,27 +659,29 @@ export function createTracking({
|
||||
)
|
||||
return;
|
||||
|
||||
const older = [];
|
||||
let lastAltM = null; // carry-forward for no-baro points whose cell isn't warm yet
|
||||
for (const { lat, lon, baroAlt } of parsed) {
|
||||
const baroM = Number.isFinite(baroAlt)
|
||||
? baroAlt + geoidHeight(lat, lon)
|
||||
: null;
|
||||
let altM = floorAltitudeM(baroM, cachedGroundFloor(lat, lon));
|
||||
// No baro + unresolved floor: hold the previous waypoint's altitude
|
||||
// (continuity — never a dive/spike to a made-up height). Leading points
|
||||
// with nothing to carry keep the old 10 km airborne default.
|
||||
if (altM == null) altM = lastAltM != null ? lastAltM : 10000;
|
||||
lastAltM = altM;
|
||||
older.push(fromDegrees(lon, lat, altM));
|
||||
}
|
||||
|
||||
flightState._trailPositions = older.concat(flightState._trailPositions);
|
||||
if (flightState._trailPositions.length > TRAIL_MAX_POINTS) {
|
||||
flightState._trailPositions = flightState._trailPositions.slice(
|
||||
flightState._trailPositions.length - TRAIL_MAX_POINTS,
|
||||
);
|
||||
}
|
||||
// Every waypoint is kept, each leg its own segment. A ground waypoint is
|
||||
// at altitude 0, floored at the ground. A waypoint with no altitude is a
|
||||
// break on both sides: it sits on the ground where the floor is known and
|
||||
// is skipped otherwise; a skipped point still breaks the line.
|
||||
const backfill = trailBackfillFixes(
|
||||
parsed.map(({ lat, lon, baroAlt, onGround, timeMs }) => {
|
||||
const known = Number.isFinite(baroAlt) ? baroAlt : onGround ? 0 : null;
|
||||
const altM = floorAltitudeM(
|
||||
known == null ? null : known + geoidHeight(lat, lon),
|
||||
cachedGroundFloor(lat, lon),
|
||||
);
|
||||
return {
|
||||
position: altM == null ? null : fromDegrees(lon, lat, altM),
|
||||
timeMs,
|
||||
nullAltitude: known == null,
|
||||
};
|
||||
}),
|
||||
);
|
||||
flightState._trailFixes = joinTrailBackfill(
|
||||
backfill,
|
||||
flightState._trailFixes,
|
||||
TRAIL_MAX_POINTS,
|
||||
);
|
||||
_refreshTrailDisplay();
|
||||
}
|
||||
|
||||
@@ -578,7 +691,9 @@ export function createTracking({
|
||||
|
||||
function _clearTrail() {
|
||||
flightState._trailBackfillToken += 1;
|
||||
flightState._trailPositions = [];
|
||||
flightState._trailFixes = [];
|
||||
flightState._trailRecordPosition = null;
|
||||
flightState._trailRecordMs = -Infinity;
|
||||
if (flightState._trail) flightState._trail.clear();
|
||||
flightState._trailHeadOff?.();
|
||||
flightState._trailHeadOff = null;
|
||||
@@ -713,14 +828,89 @@ export function createTracking({
|
||||
flightState._pendingTrackingRestore = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The tracked plane's stale cue and whether it is drawn with the stale fade.
|
||||
* - SIGNAL LOST · <time since its last report>, dimmed: its coast has ended
|
||||
* (or it holds at its last report after a missed update) and no newer
|
||||
* report has come.
|
||||
* - STALE, dimmed: it has missed an update and still coasts, or the whole
|
||||
* feed is backing off.
|
||||
* @param {string} icao24
|
||||
* @returns {{text: string, dimmed: boolean}}
|
||||
*/
|
||||
|
||||
function _trackedStaleCue(icao24) {
|
||||
const records = flightState.records;
|
||||
const misses = records.missingPolls.get(icao24) || 0;
|
||||
const repeated = records.fixRepeated?.has(icao24) === true;
|
||||
const backoff = flightState.feed._backoff === true;
|
||||
// Computed once per frame for the label, the icon colour and the model
|
||||
// fade; a poll between frames changes the key.
|
||||
const frame = renderedFrames(flightState._viewer);
|
||||
const key =
|
||||
frame >= 0 ? `${frame}|${icao24}|${misses}|${repeated}|${backoff}` : null;
|
||||
const cached = flightState._trackedStaleCueCache;
|
||||
if (key !== null && cached?.key === key) return cached.cue;
|
||||
const cue = _computeTrackedStaleCue(
|
||||
icao24,
|
||||
misses > 0 || repeated,
|
||||
backoff,
|
||||
);
|
||||
flightState._trackedStaleCueCache = key === null ? null : { key, cue };
|
||||
return cue;
|
||||
}
|
||||
|
||||
/** `_trackedStaleCue` without the per-frame cache. A repeated fix counts as missed. */
|
||||
|
||||
function _computeTrackedStaleCue(icao24, missed, backoff) {
|
||||
const lost = parts.motion._signalLost(icao24);
|
||||
if (lost && (missed || !lost.holds)) {
|
||||
const sec = Math.max(
|
||||
0,
|
||||
Math.floor((flightState.now() - lost.reportEpochMs) / 1000),
|
||||
);
|
||||
const time =
|
||||
sec < 60
|
||||
? `${formatNumber(sec, { useGrouping: false })} ${unitLabel('s')}`
|
||||
: `${formatNumber(Math.floor(sec / 60), { useGrouping: false })} ${unitLabel('min')}`;
|
||||
return { text: t('SIGNAL LOST · {time}', { time }), dimmed: true };
|
||||
}
|
||||
// A missed update or a stalled feed: no newer position is coming in.
|
||||
if (missed || backoff) return { text: t('STALE'), dimmed: true };
|
||||
return { text: '', dimmed: false };
|
||||
}
|
||||
|
||||
/** The tracked billboard's colour: cyan, faded while stale, clear while the 3D model is the visual. */
|
||||
|
||||
function _trackedIconColor() {
|
||||
if (parts.rendering._modelOwnsVisual(flightState._trackedIcao))
|
||||
return CYAN_TRANSPARENT;
|
||||
return _trackedStaleCue(flightState._trackedIcao).dimmed
|
||||
? STALE_CYAN
|
||||
: TRACKED_CYAN;
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-word the tracked label when its stale cue changes (STALE, SIGNAL LOST,
|
||||
* each new second or minute of it). Run from the layer's per-frame pass.
|
||||
*/
|
||||
|
||||
function _staleCueTick() {
|
||||
const icao24 = flightState._trackedIcao;
|
||||
if (!icao24 || !flightState._trackedEntity) return;
|
||||
const text = _trackedStaleCue(icao24).text;
|
||||
if (text === flightState._trackedStaleCueText) return;
|
||||
flightState._trackedStaleCueText = text;
|
||||
_updateTrackedLabelModel(icao24);
|
||||
}
|
||||
|
||||
/** Multi-line tracked presentation text: "CS · FL · kts" + "Airline · Type" +
|
||||
* "ORIG → DEST". The route line is gated by
|
||||
* routePlausible so a wrong-leg adsbdb route is hidden, not displayed.
|
||||
* While the plane is in its missed-poll grace (coasting on dead reckoning
|
||||
* with sticky metadata), the first line carries a "· STALE" cue — the fleet's
|
||||
* 45%-alpha billboard fade doesn't apply to the tracked plane (its entity
|
||||
* owns the visual), so without this the readout would present last-known
|
||||
* velocity/altitude as live. */
|
||||
* The first line carries the stale cue (`_trackedStaleCue`): STALE while
|
||||
* the plane coasts on dead reckoning after a missed update, SIGNAL LOST
|
||||
* once the coast has ended, so last-known velocity/altitude are never
|
||||
* presented as live. */
|
||||
|
||||
function _trackedLabelText(icao24) {
|
||||
const info = flightState.records.data.get(icao24);
|
||||
@@ -741,10 +931,7 @@ export function createTracking({
|
||||
const spd = info.velocity
|
||||
? quantity(Math.round(info.velocity * 1.944), 'kts')
|
||||
: '';
|
||||
const stale =
|
||||
flightState.records.missingPolls.get(icao24) || flightState.feed._backoff
|
||||
? t('STALE')
|
||||
: '';
|
||||
const stale = _trackedStaleCue(icao24).text;
|
||||
const lines = [[cs, fl, spd, stale].filter(Boolean).join(' · ')];
|
||||
// Converted contacts report their class as TR-3B and nothing else — the
|
||||
// operator/type identity is exactly what the Easter egg is replacing.
|
||||
@@ -944,12 +1131,9 @@ export function createTracking({
|
||||
image: _trackedBillboardImage(),
|
||||
sprite,
|
||||
position: getTrackedPosition,
|
||||
// Solid cyan when the billboard is the visual (zoomed out, 3D off, or model still loading);
|
||||
// transparent once the tracked model is actually up (ready + shown).
|
||||
color: () =>
|
||||
parts.rendering._modelOwnsVisual(flightState._trackedIcao)
|
||||
? CYAN_TRANSPARENT
|
||||
: TRACKED_CYAN,
|
||||
// Solid cyan (faded while stale) when the billboard is the visual (zoomed out, 3D off,
|
||||
// or model still loading); transparent once the tracked model is actually up.
|
||||
color: _trackedIconColor,
|
||||
// Screen-projected rotation, evaluated per frame on the camera's own
|
||||
// axes, so it stays exact through a tracked orbit. The tracked target
|
||||
// must never vanish into tile geometry — tracking a taxiing plane at
|
||||
@@ -1025,6 +1209,7 @@ export function createTracking({
|
||||
// starts one.
|
||||
parts.enrichment._requestTypeEnrichment(icao24, true); // tracked plane — front of the enrichment queue
|
||||
parts.enrichment._requestRouteEnrichment(icao24);
|
||||
parts.enrichment._requestPhotoEnrichment(icao24);
|
||||
// Round 2 (owner): grounded contacts get trails too — a landed-but-taxiing
|
||||
// aircraft's history is retrievable on select. Grounded flights positions
|
||||
// are already surface-clamped (the surfaceM chain), so seeds/appends drape.
|
||||
@@ -1184,6 +1369,9 @@ export function createTracking({
|
||||
_trackedModelRegimeActive,
|
||||
_syncTracked2dRotation,
|
||||
_appendTrailFix,
|
||||
_trailTick,
|
||||
_drawTrailHead,
|
||||
_trailHeadPositions,
|
||||
_refreshTrailDisplay,
|
||||
_startTrail,
|
||||
_backfillTrail,
|
||||
@@ -1197,6 +1385,9 @@ export function createTracking({
|
||||
_applyPendingTrackingRestore,
|
||||
_cancelPendingTrackingRestore,
|
||||
_trackedLabelText,
|
||||
_trackedStaleCue,
|
||||
_trackedIconColor,
|
||||
_staleCueTick,
|
||||
_updateTrackedLabelModel,
|
||||
_syncTrackedBillboardImage,
|
||||
_refreshTr3bContact,
|
||||
|
||||
@@ -0,0 +1,412 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { createFlightState } from './state.js';
|
||||
import { createTracking } from './tracking.js';
|
||||
import { TRAIL_MAX_POINTS } from './policy.js';
|
||||
import { trailHeadJoins, trailPairBreaks } from '../../data/trailContinuity.js';
|
||||
|
||||
const MINUTE = 60_000;
|
||||
const HOUR = 60 * MINUTE;
|
||||
const NM = 1852;
|
||||
|
||||
function services({ trails, floor = () => null } = {}) {
|
||||
const names = [
|
||||
'picking',
|
||||
'sprites',
|
||||
'aircraftPresentation',
|
||||
'camera',
|
||||
'militaryRegistry',
|
||||
'labels',
|
||||
'meshFloor',
|
||||
'focus',
|
||||
'readout',
|
||||
'context',
|
||||
'render',
|
||||
'recession',
|
||||
];
|
||||
return {
|
||||
...Object.fromEntries(names.map((name) => [name, {}])),
|
||||
groundSnap: { createGroundSnap: () => ({ clear() {} }) },
|
||||
trails,
|
||||
geoid: { ensureGeoidReady: async () => {}, geoidHeight: () => 0 },
|
||||
groundFloor: {
|
||||
resolveGroundFloorCellsBounded: async () => {},
|
||||
cachedGroundFloor: floor,
|
||||
floorAltitudeM: (alt, ground) =>
|
||||
Number.isFinite(alt)
|
||||
? alt
|
||||
: Number.isFinite(ground)
|
||||
? ground + 1
|
||||
: null,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** A fake trail that records every segment list it is given. */
|
||||
function recordingTrail() {
|
||||
const calls = [];
|
||||
return {
|
||||
calls,
|
||||
// What draws: a lone point is a segment with no line.
|
||||
last: () =>
|
||||
(calls[calls.length - 1] ?? []).filter((segment) => segment.length >= 2),
|
||||
createTrail: () => ({
|
||||
setSegments(segments) {
|
||||
calls.push(segments.map((segment) => segment.slice()));
|
||||
},
|
||||
setPositions(positions) {
|
||||
calls.push([positions.slice()]);
|
||||
},
|
||||
setVisible() {},
|
||||
clear() {
|
||||
calls.push([]);
|
||||
},
|
||||
destroy() {},
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function viewer() {
|
||||
const added = [];
|
||||
return {
|
||||
added,
|
||||
isDestroyed: () => false,
|
||||
entities: {
|
||||
add(definition) {
|
||||
added.push(definition);
|
||||
return definition;
|
||||
},
|
||||
remove() {},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A tracked aircraft whose live history holds `liveFixes` ({timeMs, lat, lon}),
|
||||
* with a track endpoint answering `waypoints`.
|
||||
*/
|
||||
function trackedHarness({
|
||||
liveFixes = [],
|
||||
waypoints = null,
|
||||
nowMs,
|
||||
floor,
|
||||
head = null,
|
||||
} = {}) {
|
||||
const trail = recordingTrail();
|
||||
const svc = services({ trails: trail, floor });
|
||||
const flightState = createFlightState({
|
||||
services: svc,
|
||||
source: {
|
||||
label: 'Fixture aircraft',
|
||||
async getTrack() {
|
||||
if (!waypoints) throw new Error('404');
|
||||
return { records: waypoints };
|
||||
},
|
||||
},
|
||||
});
|
||||
const v = viewer();
|
||||
flightState._viewer = v;
|
||||
flightState._trackedIcao = 'abc123';
|
||||
flightState.now = () => nowMs;
|
||||
flightState._positionHistory.set(
|
||||
'abc123',
|
||||
liveFixes.map((fix) => ({
|
||||
time: Cesium.JulianDate.fromDate(new Date(fix.timeMs)),
|
||||
epochMs: fix.timeMs,
|
||||
position: Cesium.Cartesian3.fromDegrees(fix.lon, fix.lat, 10_000),
|
||||
})),
|
||||
);
|
||||
const tracking = createTracking({
|
||||
flightState,
|
||||
services: svc,
|
||||
parts: {
|
||||
motion: {
|
||||
_isTrackWarmingUp: () => false,
|
||||
_trackedTrailCached: () => head,
|
||||
_trackedDisplayPosition: () => head,
|
||||
_trackedModelCenterWorld: () => null,
|
||||
_trackedModelEnvelopeM: () => null,
|
||||
},
|
||||
},
|
||||
layer: {},
|
||||
});
|
||||
return { trail, tracking, flightState, viewer: v };
|
||||
}
|
||||
|
||||
const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
function waypoint(timeMs, lat, lon, baroAltitudeM = 10_000) {
|
||||
return { observedAtMs: timeMs, latitude: lat, longitude: lon, baroAltitudeM };
|
||||
}
|
||||
|
||||
/** `count` waypoints one minute apart flying east at ~420 kt from (lat, lon). */
|
||||
function leg(startMs, lat, lon, count) {
|
||||
return Array.from({ length: count }, (_, i) =>
|
||||
waypoint(startMs + i * MINUTE, lat, lon + i * 0.12),
|
||||
);
|
||||
}
|
||||
|
||||
/** The live head the trail would draw now. */
|
||||
function headPositions({ tracking }) {
|
||||
return tracking._trailHeadPositions();
|
||||
}
|
||||
|
||||
test('a pair 40 minutes and 300 km apart stays joined', () => {
|
||||
assert.equal(trailPairBreaks(40 * MINUTE, 300_000), false);
|
||||
});
|
||||
|
||||
test('a pair 1 minute and 200 km apart breaks: faster than 1,500 kt', () => {
|
||||
assert.equal(trailPairBreaks(MINUTE, 200_000), true);
|
||||
});
|
||||
|
||||
test('a gap longer than 48 minutes breaks, and time that does not advance breaks', () => {
|
||||
assert.equal(trailPairBreaks(49 * MINUTE, 10_000), true);
|
||||
assert.equal(trailPairBreaks(48 * MINUTE, 10_000), false);
|
||||
assert.equal(trailPairBreaks(0, 0), true);
|
||||
assert.equal(trailPairBreaks(-MINUTE, 100), true);
|
||||
});
|
||||
|
||||
test('a parked aircraft two hours apart within 0.1 nm stays joined', () => {
|
||||
assert.equal(trailPairBreaks(2 * HOUR, 0.09 * NM), false);
|
||||
assert.equal(trailPairBreaks(3 * HOUR + MINUTE, 0.09 * NM), true);
|
||||
assert.equal(trailPairBreaks(2 * HOUR, 0.2 * NM), true);
|
||||
});
|
||||
|
||||
test('the head joins within 150 km under the time and speed test', () => {
|
||||
assert.equal(trailHeadJoins(30_000, 5_000), true);
|
||||
assert.equal(trailHeadJoins(30 * MINUTE, 151_000), false);
|
||||
assert.equal(trailHeadJoins(HOUR, 5_000), false);
|
||||
});
|
||||
|
||||
test('a backfill with gaps of 10 h, 2 h, 1.2 h and 6.5 h draws five segments and no line across a gap', async () => {
|
||||
const t0 = Date.UTC(2026, 10, 8, 0, 0);
|
||||
const legs = [];
|
||||
let start = t0;
|
||||
const gaps = [10 * HOUR, 2 * HOUR, 1.2 * HOUR, 6.5 * HOUR];
|
||||
const anchors = [
|
||||
[30, 31],
|
||||
[12, 0],
|
||||
[14, -15],
|
||||
[20, -40],
|
||||
[35, -75],
|
||||
];
|
||||
for (let i = 0; i < anchors.length; i++) {
|
||||
const points = leg(start, anchors[i][0], anchors[i][1], 6);
|
||||
legs.push(points);
|
||||
start = points[points.length - 1].observedAtMs + (gaps[i] ?? 0);
|
||||
}
|
||||
const waypoints = legs.flat();
|
||||
const lastLeg = legs[legs.length - 1];
|
||||
const liveStart = lastLeg[lastLeg.length - 1].observedAtMs + MINUTE;
|
||||
const liveFixes = [0, 1, 2].map((i) => ({
|
||||
timeMs: liveStart + i * MINUTE,
|
||||
lat: 35,
|
||||
lon: -75 + 0.72 + i * 0.12,
|
||||
}));
|
||||
const nowMs = liveStart + 3 * MINUTE;
|
||||
const { trail, tracking, flightState } = trackedHarness({
|
||||
liveFixes,
|
||||
waypoints,
|
||||
nowMs,
|
||||
});
|
||||
tracking._startTrail('abc123');
|
||||
await settle();
|
||||
|
||||
assert.equal(flightState._trailFixes.length, waypoints.length + 3);
|
||||
const segments = trail.last();
|
||||
assert.equal(segments.length, 5);
|
||||
const bodyCount = segments.reduce((sum, segment) => sum + segment.length, 0);
|
||||
// The body draws every fix at or before the display time: all of them here.
|
||||
assert.equal(bodyCount, waypoints.length + 3);
|
||||
for (const [index, segment] of segments.entries()) {
|
||||
const expected = legs[index].map((point) =>
|
||||
Cesium.Cartesian3.fromDegrees(point.longitude, point.latitude, 10_000),
|
||||
);
|
||||
for (const position of segment.slice(0, expected.length)) {
|
||||
assert.ok(
|
||||
expected.some((e) => Cesium.Cartesian3.distance(e, position) < 1),
|
||||
`segment ${index} holds a point from another leg`,
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('a null-altitude waypoint breaks the line, and nothing is drawn at 10 km', async () => {
|
||||
const t0 = Date.UTC(2026, 10, 8, 0, 0);
|
||||
const waypoints = leg(t0, 40, 10, 6);
|
||||
waypoints[3] = waypoint(waypoints[3].observedAtMs, 40, 10.36, null);
|
||||
const nowMs = t0 + 8 * MINUTE;
|
||||
const liveFixes = [
|
||||
{ timeMs: t0 + 6 * MINUTE, lat: 40, lon: 10.72 },
|
||||
{ timeMs: t0 + 7 * MINUTE, lat: 40, lon: 10.84 },
|
||||
];
|
||||
|
||||
// Unknown floor: the null point is skipped, and the line still breaks there.
|
||||
const skipped = trackedHarness({ liveFixes, waypoints, nowMs });
|
||||
skipped.tracking._startTrail('abc123');
|
||||
await settle();
|
||||
assert.equal(
|
||||
skipped.flightState._trailFixes.length,
|
||||
waypoints.length - 1 + 2,
|
||||
);
|
||||
const segments = skipped.trail.last();
|
||||
assert.deepEqual(
|
||||
segments.map((segment) => segment.length),
|
||||
[3, 4],
|
||||
);
|
||||
for (const segment of segments) {
|
||||
for (const position of segment) {
|
||||
const height = Cesium.Cartographic.fromCartesian(position).height;
|
||||
assert.ok(Math.abs(height - 10_000) < 1, 'only real altitudes drawn');
|
||||
}
|
||||
}
|
||||
|
||||
// Known floor: the point is kept on the ground, alone, joined to nothing.
|
||||
const grounded = trackedHarness({
|
||||
liveFixes,
|
||||
waypoints,
|
||||
nowMs,
|
||||
floor: () => 120,
|
||||
});
|
||||
grounded.tracking._startTrail('abc123');
|
||||
await settle();
|
||||
assert.equal(grounded.flightState._trailFixes.length, waypoints.length + 2);
|
||||
assert.deepEqual(
|
||||
grounded.trail.last().map((segment) => segment.length),
|
||||
[3, 4],
|
||||
);
|
||||
const kept = grounded.flightState._trailFixes[3];
|
||||
assert.ok(
|
||||
Math.abs(Cesium.Cartographic.fromCartesian(kept.position).height - 121) < 1,
|
||||
);
|
||||
});
|
||||
|
||||
test('a history tail far from the first live fix does not connect to it', async () => {
|
||||
const t0 = Date.UTC(2026, 10, 8, 0, 0);
|
||||
// History ends 20 minutes before the first live fix, 1,400 km away.
|
||||
const waypoints = leg(t0, 50, 0, 5);
|
||||
const liveStart = t0 + 24 * MINUTE;
|
||||
const liveFixes = [0, 1, 2].map((i) => ({
|
||||
timeMs: liveStart + i * MINUTE,
|
||||
lat: 50,
|
||||
lon: 20 + i * 0.12,
|
||||
}));
|
||||
const { trail, tracking } = trackedHarness({
|
||||
liveFixes,
|
||||
waypoints,
|
||||
nowMs: liveStart + 3 * MINUTE,
|
||||
});
|
||||
tracking._startTrail('abc123');
|
||||
await settle();
|
||||
assert.deepEqual(
|
||||
trail.last().map((segment) => segment.length),
|
||||
[5, 3],
|
||||
);
|
||||
});
|
||||
|
||||
test('the head is drawn to a nearby aircraft and not to one more than 150 km away', () => {
|
||||
const t0 = Date.UTC(2026, 10, 8, 0, 0);
|
||||
const liveFixes = [0, 1, 2].map((i) => ({
|
||||
timeMs: t0 + i * MINUTE,
|
||||
lat: 50,
|
||||
lon: 1 + i * 0.12,
|
||||
}));
|
||||
const near = Cesium.Cartesian3.fromDegrees(1.3, 50, 10_000);
|
||||
const joined = trackedHarness({
|
||||
liveFixes,
|
||||
nowMs: t0 + 3 * MINUTE,
|
||||
head: near,
|
||||
});
|
||||
joined.tracking._startTrail('abc123');
|
||||
const drawn = headPositions(joined);
|
||||
assert.equal(drawn.length, 2);
|
||||
assert.ok(Cesium.Cartesian3.distance(drawn[1], near) < 1e-6);
|
||||
|
||||
const far = Cesium.Cartesian3.fromDegrees(4, 50, 10_000);
|
||||
const detached = trackedHarness({
|
||||
liveFixes,
|
||||
nowMs: t0 + 3 * MINUTE,
|
||||
head: far,
|
||||
});
|
||||
detached.tracking._startTrail('abc123');
|
||||
assert.deepEqual(headPositions(detached), []);
|
||||
|
||||
// An hour without a fix: the head no longer joins the last body point.
|
||||
const stale = trackedHarness({ liveFixes, nowMs: t0 + HOUR, head: near });
|
||||
stale.tracking._startTrail('abc123');
|
||||
assert.deepEqual(headPositions(stale), []);
|
||||
});
|
||||
|
||||
test('a live fix after a one-hour feed gap starts a new segment', () => {
|
||||
const t0 = Date.UTC(2026, 10, 8, 0, 0);
|
||||
const liveFixes = [0, 1, 2].map((i) => ({
|
||||
timeMs: t0 + i * MINUTE,
|
||||
lat: 50,
|
||||
lon: 1 + i * 0.12,
|
||||
}));
|
||||
const { trail, tracking, flightState } = trackedHarness({
|
||||
liveFixes,
|
||||
nowMs: t0 + 3 * MINUTE,
|
||||
});
|
||||
tracking._startTrail('abc123');
|
||||
assert.deepEqual(
|
||||
trail.last().map((segment) => segment.length),
|
||||
[3],
|
||||
);
|
||||
const later = t0 + 2 * MINUTE + HOUR;
|
||||
// The display time moves past the new fixes.
|
||||
flightState.now = () => later + 3 * MINUTE;
|
||||
for (const [i, lon] of [3, 3.12, 3.24].entries()) {
|
||||
tracking._appendTrailFix(
|
||||
Cesium.Cartesian3.fromDegrees(lon, 50, 10_000),
|
||||
later + i * MINUTE,
|
||||
);
|
||||
}
|
||||
assert.equal(flightState._trailFixes.length, 6);
|
||||
assert.deepEqual(
|
||||
trail.last().map((segment) => segment.length),
|
||||
[3, 3],
|
||||
);
|
||||
});
|
||||
|
||||
test('every waypoint of a 24 h history survives, and the trail stays within TRAIL_MAX_POINTS', async () => {
|
||||
// A full day at one fix per minute.
|
||||
const day = 24 * 60;
|
||||
const t0 = Date.UTC(2026, 10, 8, 0, 0);
|
||||
const full = leg(t0, 10, -100, day);
|
||||
const liveStart = t0 + day * MINUTE;
|
||||
const liveFixes = [{ timeMs: liveStart, lat: 10, lon: -100 + day * 0.12 }];
|
||||
const kept = trackedHarness({
|
||||
liveFixes,
|
||||
waypoints: full,
|
||||
nowMs: liveStart + MINUTE,
|
||||
});
|
||||
kept.tracking._startTrail('abc123');
|
||||
await settle();
|
||||
assert.ok(TRAIL_MAX_POINTS >= day + 500);
|
||||
assert.equal(kept.flightState._trailFixes.length, full.length + 1);
|
||||
assert.deepEqual(
|
||||
kept.trail.last().map((segment) => segment.length),
|
||||
[day + 1],
|
||||
);
|
||||
|
||||
const count = TRAIL_MAX_POINTS + 120;
|
||||
const large = leg(
|
||||
liveStart - count * MINUTE,
|
||||
10,
|
||||
-100 + (day - count) * 0.12,
|
||||
count,
|
||||
);
|
||||
const capped = trackedHarness({
|
||||
liveFixes,
|
||||
waypoints: large,
|
||||
nowMs: liveStart + MINUTE,
|
||||
});
|
||||
capped.tracking._startTrail('abc123');
|
||||
await settle();
|
||||
const fixes = capped.flightState._trailFixes;
|
||||
assert.equal(fixes.length, TRAIL_MAX_POINTS);
|
||||
// The oldest go first: the newest live fix is still the last point.
|
||||
assert.equal(fixes[fixes.length - 1].timeMs, liveStart);
|
||||
});
|
||||
@@ -0,0 +1,833 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { bindRenderer } from '../../render/rendererOf.js';
|
||||
import { createStubRenderer } from '../../render/stub/index.js';
|
||||
import { createMotion } from './motion.js';
|
||||
import { createFlightState } from './state.js';
|
||||
import { createTracking } from './tracking.js';
|
||||
import { RENDER_DELAY_SEC, STALE_ALPHA } from './policy.js';
|
||||
|
||||
// Between reports, a tracked trail is the path the icon was actually drawn
|
||||
// along: the real display position, recorded as the frames go by. These tests
|
||||
// drive the real motion and display path frame by frame.
|
||||
|
||||
const SEC = 1000;
|
||||
const ICAO = '00a001';
|
||||
const T0 = Date.UTC(2026, 10, 9, 21, 0);
|
||||
|
||||
function fix(timeMs, lat, lon, heightM, velocity, track) {
|
||||
return {
|
||||
time: Cesium.JulianDate.fromDate(new Date(timeMs)),
|
||||
epochMs: timeMs,
|
||||
position: Cesium.Cartesian3.fromDegrees(lon, lat, heightM),
|
||||
velocity,
|
||||
track,
|
||||
};
|
||||
}
|
||||
|
||||
function services(trail, ground) {
|
||||
const names = [
|
||||
'picking',
|
||||
'sprites',
|
||||
'aircraftPresentation',
|
||||
'camera',
|
||||
'militaryRegistry',
|
||||
'labels',
|
||||
'meshFloor',
|
||||
'focus',
|
||||
'readout',
|
||||
'context',
|
||||
'render',
|
||||
'recession',
|
||||
];
|
||||
return {
|
||||
...Object.fromEntries(names.map((name) => [name, {}])),
|
||||
aircraftPresentation: {
|
||||
isTr3b: () => false,
|
||||
tr3bTypeLabel: (id, label) => label,
|
||||
},
|
||||
focus: {
|
||||
nearFarScalarValueAtDistance: () => 1,
|
||||
clearFocusTarget() {},
|
||||
publishFocusTargetAt() {},
|
||||
publishFocusTargetFromCachedPosition() {},
|
||||
},
|
||||
groundSnap: { createGroundSnap: () => ({ clear() {} }) },
|
||||
trails: trail,
|
||||
geoid: { ensureGeoidReady: async () => {}, geoidHeight: () => 0 },
|
||||
groundFloor: {
|
||||
resolveGroundFloorCellsBounded: async () => {},
|
||||
cachedGroundFloor: ground,
|
||||
stickyFloorCell: (lat, lon) => ({ lat, lon }),
|
||||
neighborFloorM: () => null,
|
||||
floorAltitudeM: (alt, g) =>
|
||||
Number.isFinite(g) && Number.isFinite(alt)
|
||||
? Math.max(alt, g + 1.5)
|
||||
: alt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Real motion, real display position and real tracking over one contact.
|
||||
* `frame()` runs one rendered frame: a frame of the stub renderer, whose
|
||||
* preRender pass moves the trail on and then draws its head.
|
||||
*/
|
||||
function harness({
|
||||
fixes,
|
||||
info,
|
||||
nowMs,
|
||||
ground = () => null,
|
||||
envelopeM = null,
|
||||
}) {
|
||||
const segmentsCalls = [];
|
||||
let headPositions = [];
|
||||
const trail = {
|
||||
createTrail: () => ({
|
||||
setSegments(segments) {
|
||||
segmentsCalls.push(segments.map((segment) => segment.slice()));
|
||||
},
|
||||
setPositions(positions) {
|
||||
segmentsCalls.push([positions.slice()]);
|
||||
},
|
||||
setHead(positions) {
|
||||
headPositions = positions.slice();
|
||||
},
|
||||
setVisible() {},
|
||||
clear() {},
|
||||
destroy() {},
|
||||
}),
|
||||
};
|
||||
const svc = services(trail, ground);
|
||||
const flightState = createFlightState({
|
||||
services: svc,
|
||||
source: { label: 'Fixture aircraft' },
|
||||
});
|
||||
flightState.records.data.set(ICAO, info);
|
||||
// The scene, on the stub renderer: each frame runs its preRender pass
|
||||
// (the trail moves on, then its head is drawn) and counts as drawn.
|
||||
const renderer = createStubRenderer();
|
||||
flightState._viewer = {};
|
||||
bindRenderer(flightState._viewer, renderer);
|
||||
flightState._trackedIcao = ICAO;
|
||||
let clock = nowMs;
|
||||
flightState.now = () => clock;
|
||||
flightState._positionHistory.set(ICAO, fixes);
|
||||
const parts = {
|
||||
rendering: { _modelOwnsVisual: () => false, _modelSpec: () => ({}) },
|
||||
queries: { _contactLabel: (id, info) => info?.callsign || id },
|
||||
};
|
||||
parts.motion = createMotion({ flightState, services: svc, parts });
|
||||
if (envelopeM != null) {
|
||||
// A 3D model is the visual: its centre is the drawn position.
|
||||
parts.motion._trackedModelCenterWorld = () =>
|
||||
parts.motion._trackedDisplayCached();
|
||||
parts.motion._trackedModelEnvelopeM = () => envelopeM;
|
||||
}
|
||||
const tracking = createTracking({
|
||||
flightState,
|
||||
services: svc,
|
||||
parts,
|
||||
layer: {},
|
||||
});
|
||||
parts.tracking = tracking;
|
||||
const realDateNow = Date.now;
|
||||
Date.now = () => clock;
|
||||
// The live head the last frame drew (the trail's head, set each frame
|
||||
// before it draws).
|
||||
const head = () => headPositions;
|
||||
/** Drawn icon positions, one per frame. */
|
||||
const drawn = [];
|
||||
// Where the frame draws the icon: read in the same frame as the head.
|
||||
renderer.frame.on('preRender', () => {
|
||||
const icon = parts.motion._trackedDisplayPosition(ICAO);
|
||||
if (icon) drawn.push(Cesium.Cartesian3.clone(icon));
|
||||
});
|
||||
const frame = () => {
|
||||
renderer.frame.requestRender('test');
|
||||
renderer.testing.tick();
|
||||
};
|
||||
const run = (toMs, { frameMs = 100, readHead = true } = {}) => {
|
||||
while (clock < toMs) {
|
||||
clock = Math.min(toMs, clock + frameMs);
|
||||
frame({ readHead });
|
||||
}
|
||||
};
|
||||
return {
|
||||
flightState,
|
||||
tracking,
|
||||
motion: parts.motion,
|
||||
head,
|
||||
drawn,
|
||||
run,
|
||||
body: () => segmentsCalls.at(-1) ?? [],
|
||||
bodyPoints: () => (segmentsCalls.at(-1) ?? []).flat(),
|
||||
restore: () => {
|
||||
Date.now = realDateNow;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Distance from p to the nearest point of a polyline. */
|
||||
function distanceToPath(p, path) {
|
||||
let best = Infinity;
|
||||
const ab = new Cesium.Cartesian3();
|
||||
const ap = new Cesium.Cartesian3();
|
||||
const closest = new Cesium.Cartesian3();
|
||||
if (path.length === 1) return Cesium.Cartesian3.distance(p, path[0]);
|
||||
for (let i = 1; i < path.length; i++) {
|
||||
Cesium.Cartesian3.subtract(path[i], path[i - 1], ab);
|
||||
Cesium.Cartesian3.subtract(p, path[i - 1], ap);
|
||||
const len2 = Cesium.Cartesian3.magnitudeSquared(ab);
|
||||
const t =
|
||||
len2 > 0
|
||||
? Math.max(0, Math.min(1, Cesium.Cartesian3.dot(ap, ab) / len2))
|
||||
: 0;
|
||||
Cesium.Cartesian3.add(
|
||||
path[i - 1],
|
||||
Cesium.Cartesian3.multiplyByScalar(ab, t, closest),
|
||||
closest,
|
||||
);
|
||||
best = Math.min(best, Cesium.Cartesian3.distance(p, closest));
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** No vertex turns the line back sharper than 120° over a short step. */
|
||||
function assertNoSpur(line, label) {
|
||||
const u = new Cesium.Cartesian3();
|
||||
const v = new Cesium.Cartesian3();
|
||||
for (let i = 1; i < line.length - 1; i++) {
|
||||
Cesium.Cartesian3.subtract(line[i], line[i - 1], u);
|
||||
Cesium.Cartesian3.subtract(line[i + 1], line[i], v);
|
||||
const lu = Cesium.Cartesian3.magnitude(u);
|
||||
const lv = Cesium.Cartesian3.magnitude(v);
|
||||
if (!(lu > 0 && lv > 0) || Math.min(lu, lv) > 500) continue;
|
||||
const cos = Cesium.Cartesian3.dot(u, v) / (lu * lv);
|
||||
assert.ok(
|
||||
cos >= -0.5,
|
||||
`${label}: spur at vertex ${i} of ${line.length} (turn ${(
|
||||
(Math.acos(cos) * 180) /
|
||||
Math.PI
|
||||
).toFixed(0)}°)`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const indexOfPoint = (line, p) =>
|
||||
line.findIndex((q) => Cesium.Cartesian3.distance(p, q) < 0.01);
|
||||
|
||||
// A departing jet: four northbound climb reports, then a left turn through
|
||||
// west to south with no report while the icon flies it.
|
||||
function departure() {
|
||||
const fixes = [
|
||||
fix(T0, 37.6329, -122.3661, 213, 85, 8),
|
||||
fix(T0 + 30 * SEC, 37.6542, -122.3616, 495, 95, 0),
|
||||
fix(T0 + 60 * SEC, 37.6813, -122.3615, 808, 104, 350),
|
||||
fix(T0 + 90 * SEC, 37.7066, -122.3755, 1257, 112, 340),
|
||||
];
|
||||
const info = {
|
||||
altitude: 1257,
|
||||
renderAltitudeM: 1257,
|
||||
rawLat: 37.7066,
|
||||
rawLon: -122.3755,
|
||||
velocity: 112,
|
||||
true_track: 340,
|
||||
turnRateDps: -2,
|
||||
onGround: false,
|
||||
wasAirborne: true,
|
||||
lastContactEpochMs: T0 + 200 * SEC,
|
||||
};
|
||||
return { fixes, info };
|
||||
}
|
||||
|
||||
test('a report newer than the display time arrives mid-turn: the trail between the two reports stays on the drawn arc', () => {
|
||||
const { fixes, info } = departure();
|
||||
const start = T0 + 90 * SEC + RENDER_DELAY_SEC * SEC;
|
||||
const h = harness({ fixes, info, nowMs: start });
|
||||
try {
|
||||
h.tracking._startTrail(ICAO);
|
||||
// 40 s of turn with no new report: the icon flies the arc.
|
||||
h.run(start + 40 * SEC);
|
||||
const arc = h.drawn.slice();
|
||||
// The next report is where the plane really was 60 s after the last one,
|
||||
// still ahead of the display time (normal 30 s delay, slow feed). The icon
|
||||
// now interpolates the straight line between the two reports and is eased
|
||||
// onto it.
|
||||
const at60 = h.motion._deadReckon(
|
||||
ICAO,
|
||||
new Cesium.Cartesian3(),
|
||||
Cesium.JulianDate.fromDate(new Date(T0 + 150 * SEC)),
|
||||
);
|
||||
const c = Cesium.Cartographic.fromCartesian(at60);
|
||||
const report = fix(
|
||||
T0 + 150 * SEC,
|
||||
Cesium.Math.toDegrees(c.latitude),
|
||||
Cesium.Math.toDegrees(c.longitude),
|
||||
c.height,
|
||||
112,
|
||||
220,
|
||||
);
|
||||
fixes.push(report);
|
||||
info.true_track = 220;
|
||||
h.tracking._appendTrailFix(
|
||||
Cesium.Cartesian3.clone(report.position),
|
||||
report.epochMs,
|
||||
);
|
||||
// The display passes the new report.
|
||||
h.run(start + 75 * SEC);
|
||||
const line = h.bodyPoints();
|
||||
const from = indexOfPoint(line, fixes[3].position);
|
||||
const to = indexOfPoint(line, report.position);
|
||||
assert.ok(from >= 0 && to > from, 'both reports are on the trail');
|
||||
const between = line.slice(from, to + 1);
|
||||
// Every vertex between the reports is where the icon was drawn...
|
||||
const drawnPath = [fixes[3].position, ...h.drawn, report.position];
|
||||
for (const vertex of between) {
|
||||
const off = distanceToPath(vertex, drawnPath);
|
||||
assert.ok(
|
||||
off < 50,
|
||||
`trail vertex ${off.toFixed(0)} m off the drawn path`,
|
||||
);
|
||||
}
|
||||
// ...and the arc the icon flew is still there: no straight chord. (The
|
||||
// arc strays far from the chord, so a chord would fail this.)
|
||||
const chord = [fixes[3].position, report.position];
|
||||
assert.ok(Math.max(...arc.map((p) => distanceToPath(p, chord))) > 300);
|
||||
// The last 10 s of the arc are exempt: the correction pulled the icon back
|
||||
// over them, and keeping them would fold the line back on itself.
|
||||
for (const point of arc.slice(0, -100)) {
|
||||
const off = distanceToPath(point, between);
|
||||
assert.ok(off < 50, `drawn arc point ${off.toFixed(0)} m from the trail`);
|
||||
}
|
||||
assertNoSpur(line, 'trail');
|
||||
assertNoSpur(h.head(), 'head');
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('a fresh report after a hold resumes with no backward spur', () => {
|
||||
const fixes = [0, 1, 2, 3].map((i) =>
|
||||
fix(T0 + i * 15 * SEC, 40, -100 + i * 0.04, 10_000, 230, 90),
|
||||
);
|
||||
const info = {
|
||||
altitude: 10_000,
|
||||
renderAltitudeM: 10_000,
|
||||
rawLat: 40,
|
||||
rawLon: -100 + 0.12,
|
||||
velocity: 230,
|
||||
true_track: 90,
|
||||
turnRateDps: 0,
|
||||
onGround: false,
|
||||
wasAirborne: true,
|
||||
lastContactEpochMs: T0 + 45 * SEC,
|
||||
};
|
||||
const start = T0 + 45 * SEC + RENDER_DELAY_SEC * SEC;
|
||||
const h = harness({ fixes, info, nowMs: start });
|
||||
try {
|
||||
h.tracking._startTrail(ICAO);
|
||||
// The contact coasts five minutes, then holds; recording stops while it
|
||||
// holds.
|
||||
h.run(start + 320 * SEC);
|
||||
const held = h.bodyPoints().length;
|
||||
h.run(start + 360 * SEC);
|
||||
assert.equal(h.bodyPoints().length, held, 'the trail grew during a hold');
|
||||
// A fresh report, a little north of the track, ahead of the display.
|
||||
const display = start + 360 * SEC - RENDER_DELAY_SEC * SEC;
|
||||
// Just past where it held: five minutes and ten seconds at 230 m/s.
|
||||
const aheadDeg = (230 * 310) / (111_320 * Math.cos((40 * Math.PI) / 180));
|
||||
const fresh = fix(
|
||||
display + 10 * SEC,
|
||||
40.01,
|
||||
-100 + 0.12 + aheadDeg,
|
||||
10_000,
|
||||
230,
|
||||
80,
|
||||
);
|
||||
fixes.push(fresh);
|
||||
info.lastContactEpochMs = fresh.epochMs;
|
||||
h.tracking._appendTrailFix(
|
||||
Cesium.Cartesian3.clone(fresh.position),
|
||||
fresh.epochMs,
|
||||
);
|
||||
h.run(start + 390 * SEC);
|
||||
assertNoSpur(h.bodyPoints(), 'trail');
|
||||
assertNoSpur(h.head(), 'head');
|
||||
assert.ok(indexOfPoint(h.bodyPoints(), fresh.position) >= 0);
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('with the head hidden the body keeps advancing, and untracking clears the recording', () => {
|
||||
const { fixes, info } = departure();
|
||||
const start = T0 + 90 * SEC + RENDER_DELAY_SEC * SEC;
|
||||
const h = harness({ fixes, info, nowMs: start });
|
||||
try {
|
||||
h.tracking._startTrail(ICAO);
|
||||
h.run(start + 5 * SEC);
|
||||
const before = h.bodyPoints().at(-1);
|
||||
// Cockpit view: the head is hidden and its callback never runs.
|
||||
h.run(start + 30 * SEC, { readHead: false });
|
||||
// The body's end keeps following the icon; straight stretches are thinned.
|
||||
const end = h.bodyPoints().at(-1);
|
||||
assert.ok(
|
||||
Cesium.Cartesian3.distance(end, before) > 1_000,
|
||||
'the body stopped advancing',
|
||||
);
|
||||
assert.ok(Cesium.Cartesian3.distance(end, h.drawn.at(-1)) < 300);
|
||||
h.tracking._clearTrail();
|
||||
assert.equal(h.flightState._trailFixes.length, 0);
|
||||
// A new track of the same plane starts from reports only.
|
||||
h.tracking._startTrail(ICAO);
|
||||
assert.equal(
|
||||
h.flightState._trailFixes.filter((entry) => entry.drawn).length,
|
||||
0,
|
||||
);
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('a live fix with no altitude breaks the line and puts no point at an invented height', () => {
|
||||
const { fixes, info } = departure();
|
||||
const start = T0 + 90 * SEC + RENDER_DELAY_SEC * SEC;
|
||||
const h = harness({ fixes, info, nowMs: start });
|
||||
try {
|
||||
h.tracking._startTrail(ICAO);
|
||||
const invented = Cesium.Cartesian3.fromDegrees(-122.38, 37.71, 10_000);
|
||||
h.tracking._appendTrailFix(invented, T0 + 95 * SEC, { nullAltitude: true });
|
||||
const later = Cesium.Cartesian3.fromDegrees(-122.39, 37.715, 1400);
|
||||
h.tracking._appendTrailFix(later, T0 + 100 * SEC);
|
||||
h.run(T0 + 100 * SEC + RENDER_DELAY_SEC * SEC + SEC, { frameMs: 500 });
|
||||
for (const point of h.bodyPoints())
|
||||
assert.ok(Cesium.Cartographic.fromCartesian(point).height < 5_000);
|
||||
// The reports on either side of it are not joined.
|
||||
const segments = h.body();
|
||||
const holding = (p) =>
|
||||
segments.findIndex((segment) =>
|
||||
segment.some((q) => Cesium.Cartesian3.distance(p, q) < 0.01),
|
||||
);
|
||||
assert.notEqual(holding(fixes[3].position), holding(later));
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('with a 3D model as the visual, the trail stops outside the model and the head runs from there to the plane', () => {
|
||||
const { fixes, info } = departure();
|
||||
info.turnRateDps = 0;
|
||||
const start = T0 + 90 * SEC + RENDER_DELAY_SEC * SEC;
|
||||
const envelopeM = 300;
|
||||
const h = harness({ fixes, info, nowMs: start, envelopeM });
|
||||
try {
|
||||
h.tracking._startTrail(ICAO);
|
||||
h.run(start + 30 * SEC);
|
||||
const icon = h.drawn.at(-1);
|
||||
const body = h.bodyPoints();
|
||||
const head = h.head();
|
||||
assert.ok(head.length >= 2, 'no head is drawn');
|
||||
assert.ok(Cesium.Cartesian3.distance(head.at(-1), icon) < 0.01);
|
||||
// No trail point inside the model, and the head starts where the body ends.
|
||||
for (const point of body)
|
||||
assert.ok(Cesium.Cartesian3.distance(point, icon) >= envelopeM - 1);
|
||||
assert.ok(Cesium.Cartesian3.distance(head[0], body.at(-1)) < 0.01);
|
||||
// Body and head together follow where the icon was drawn.
|
||||
const line = body.concat(head);
|
||||
for (const point of h.drawn) {
|
||||
const off = distanceToPath(point, line);
|
||||
assert.ok(off < 35, `drawn icon ${off.toFixed(0)} m off the trail`);
|
||||
}
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('a report the display already passed replaces the guess drawn after it, with no spike', () => {
|
||||
const { fixes, info } = departure();
|
||||
const start = T0 + 90 * SEC + RENDER_DELAY_SEC * SEC;
|
||||
const h = harness({ fixes, info, nowMs: start });
|
||||
try {
|
||||
h.tracking._startTrail(ICAO);
|
||||
h.run(start + 40 * SEC);
|
||||
const displayMs = T0 + 130 * SEC;
|
||||
// A report for 10 s before the display time, 400 m inside the drawn arc.
|
||||
const guess = h.motion._deadReckon(
|
||||
ICAO,
|
||||
new Cesium.Cartesian3(),
|
||||
Cesium.JulianDate.fromDate(new Date(T0 + 120 * SEC)),
|
||||
);
|
||||
const c = Cesium.Cartographic.fromCartesian(guess);
|
||||
const report = fix(
|
||||
T0 + 120 * SEC,
|
||||
Cesium.Math.toDegrees(c.latitude) - 400 / 111_320,
|
||||
Cesium.Math.toDegrees(c.longitude),
|
||||
c.height,
|
||||
112,
|
||||
250,
|
||||
);
|
||||
fixes.push(report);
|
||||
info.true_track = 250;
|
||||
h.tracking._appendTrailFix(
|
||||
Cesium.Cartesian3.clone(report.position),
|
||||
report.epochMs,
|
||||
);
|
||||
h.run(start + 55 * SEC);
|
||||
const recorded = h.flightState._trailFixes.filter((entry) => entry.drawn);
|
||||
// Nothing recorded between the report and the end of the ease.
|
||||
assert.deepEqual(
|
||||
recorded
|
||||
.filter(
|
||||
(entry) =>
|
||||
entry.timeMs > report.epochMs && entry.timeMs < displayMs + 900,
|
||||
)
|
||||
.map((entry) => entry.timeMs - T0),
|
||||
[],
|
||||
);
|
||||
const line = h.bodyPoints();
|
||||
assert.ok(indexOfPoint(line, report.position) >= 0);
|
||||
assertNoSpur(line, 'trail');
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('a history report at an invented height is seeded with no position, and nothing is recorded next to it', () => {
|
||||
const { fixes, info } = departure();
|
||||
fixes[3].inventedHeight = true;
|
||||
const start = T0 + 90 * SEC + RENDER_DELAY_SEC * SEC;
|
||||
const h = harness({ fixes, info, nowMs: start });
|
||||
try {
|
||||
h.tracking._startTrail(ICAO);
|
||||
const seeded = h.flightState._trailFixes.find(
|
||||
(entry) => entry.timeMs === fixes[3].epochMs,
|
||||
);
|
||||
assert.equal(seeded.position, null);
|
||||
assert.equal(seeded.nullAltitude, true);
|
||||
h.run(start + 10 * SEC);
|
||||
assert.equal(
|
||||
h.flightState._trailFixes.filter((entry) => entry.drawn).length,
|
||||
0,
|
||||
);
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
// A turboprop at FL210 flying east out of receiver coverage: its last
|
||||
// position is at T0 + 30 s, and contact goes on for four more minutes.
|
||||
function outOfCoverage() {
|
||||
const fixes = [
|
||||
fix(T0, 43, -108.1, 6_400, 140, 90),
|
||||
fix(T0 + 30 * SEC, 43, -108.05, 6_400, 140, 90),
|
||||
];
|
||||
const info = {
|
||||
altitude: 6_400,
|
||||
renderAltitudeM: 6_400,
|
||||
rawLat: 43,
|
||||
rawLon: -108.05,
|
||||
velocity: 140,
|
||||
true_track: 90,
|
||||
callsign: 'TEST7',
|
||||
turnRateDps: 0,
|
||||
onGround: false,
|
||||
wasAirborne: true,
|
||||
lastContactEpochMs: T0 + 30 * SEC + 240 * SEC,
|
||||
};
|
||||
return { fixes, info };
|
||||
}
|
||||
|
||||
/** Display time (ms) `afterSec` past the last report. */
|
||||
const pastReport = (afterSec) =>
|
||||
T0 + 30 * SEC + RENDER_DELAY_SEC * SEC + afterSec * SEC;
|
||||
|
||||
test('a plane that stops reporting keeps moving dimmed as STALE from its first missed update, then stops as SIGNAL LOST', () => {
|
||||
const { fixes, info } = outOfCoverage();
|
||||
const h = harness({ fixes, info, nowMs: pastReport(-5) });
|
||||
try {
|
||||
h.tracking._startTrail(ICAO);
|
||||
h.run(pastReport(30));
|
||||
assert.deepEqual(h.tracking._trackedStaleCue(ICAO), {
|
||||
text: '',
|
||||
dimmed: false,
|
||||
});
|
||||
assert.equal(h.tracking._trackedIconColor()[3], 1);
|
||||
// The first missed update.
|
||||
h.flightState.records.missingPolls.set(ICAO, 1);
|
||||
assert.deepEqual(h.tracking._trackedStaleCue(ICAO), {
|
||||
text: 'STALE',
|
||||
dimmed: true,
|
||||
});
|
||||
assert.match(h.tracking._trackedLabelText(ICAO), /STALE/);
|
||||
// Drawn with the fleet's stale fade.
|
||||
assert.equal(h.tracking._trackedIconColor()[3], STALE_ALPHA);
|
||||
// Still moving well past 90 s.
|
||||
h.run(pastReport(200));
|
||||
assert.ok(
|
||||
Cesium.Cartesian3.distance(h.drawn.at(-1), h.drawn.at(-11)) > 100,
|
||||
);
|
||||
// The coast ends 300 s past the report; the plane stops there.
|
||||
h.run(pastReport(310));
|
||||
const recorded = h.flightState._trailFixes.filter((e) => e.drawn).length;
|
||||
h.run(pastReport(330));
|
||||
assert.ok(
|
||||
Cesium.Cartesian3.distance(h.drawn.at(-1), h.drawn.at(-50)) < 0.01,
|
||||
);
|
||||
assert.equal(
|
||||
h.flightState._trailFixes.filter((e) => e.drawn).length,
|
||||
recorded,
|
||||
'the trail kept recording a stopped plane',
|
||||
);
|
||||
// 330 s of display past the report is 330 s + the display delay of wall time.
|
||||
const minutes = Math.floor((330 + RENDER_DELAY_SEC) / 60);
|
||||
assert.deepEqual(h.tracking._trackedStaleCue(ICAO), {
|
||||
text: `SIGNAL LOST · ${minutes} min`,
|
||||
dimmed: true,
|
||||
});
|
||||
assert.match(
|
||||
h.tracking._trackedLabelText(ICAO),
|
||||
new RegExp(`SIGNAL LOST · ${minutes} min`),
|
||||
);
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('a plane held at its last report shows SIGNAL LOST in seconds under a minute', () => {
|
||||
// Its last report is 100 m above a known ground height: it holds there.
|
||||
const { fixes, info } = outOfCoverage();
|
||||
const h = harness({
|
||||
fixes,
|
||||
info,
|
||||
nowMs: pastReport(-5),
|
||||
ground: () => 6_300,
|
||||
});
|
||||
try {
|
||||
h.tracking._startTrail(ICAO);
|
||||
h.flightState.records.missingPolls.set(ICAO, 1);
|
||||
h.run(pastReport(10));
|
||||
assert.ok(10 + RENDER_DELAY_SEC < 60);
|
||||
assert.deepEqual(h.tracking._trackedStaleCue(ICAO), {
|
||||
text: `SIGNAL LOST · ${10 + RENDER_DELAY_SEC} s`,
|
||||
dimmed: true,
|
||||
});
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('a report arriving 200 s into a coast: the plane eases onto it and the trail drops what was drawn after it', () => {
|
||||
const { fixes, info } = outOfCoverage();
|
||||
const h = harness({ fixes, info, nowMs: pastReport(-5) });
|
||||
try {
|
||||
h.tracking._startTrail(ICAO);
|
||||
h.run(pastReport(200));
|
||||
// Heard again: the report is for 10 s before the display time, 2 km north
|
||||
// of where the coast put it.
|
||||
const at = T0 + 30 * SEC + 190 * SEC;
|
||||
const guess = h.motion._deadReckon(
|
||||
ICAO,
|
||||
new Cesium.Cartesian3(),
|
||||
Cesium.JulianDate.fromDate(new Date(at)),
|
||||
);
|
||||
const c = Cesium.Cartographic.fromCartesian(guess);
|
||||
const report = fix(
|
||||
at,
|
||||
Cesium.Math.toDegrees(c.latitude) + 2_000 / 111_320,
|
||||
Cesium.Math.toDegrees(c.longitude),
|
||||
c.height,
|
||||
140,
|
||||
90,
|
||||
);
|
||||
fixes.push(report);
|
||||
h.tracking._appendTrailFix(
|
||||
Cesium.Cartesian3.clone(report.position),
|
||||
report.epochMs,
|
||||
);
|
||||
assert.deepEqual(
|
||||
h.flightState._trailFixes.filter(
|
||||
(e) => e.drawn && e.timeMs > report.epochMs,
|
||||
),
|
||||
[],
|
||||
);
|
||||
const from = h.drawn.length;
|
||||
h.run(pastReport(203));
|
||||
const after = h.drawn.slice(from - 1);
|
||||
for (let i = 1; i < after.length; i++)
|
||||
assert.ok(
|
||||
Cesium.Cartesian3.distance(after[i], after[i - 1]) < 400,
|
||||
'the plane jumped instead of easing',
|
||||
);
|
||||
// Eased onto the path from the report: 13 s on from it at 140 m/s.
|
||||
const off = Cesium.Cartesian3.distance(after.at(-1), report.position);
|
||||
assert.ok(
|
||||
Math.abs(off - 140 * 13) < 150,
|
||||
`${off.toFixed(0)} m from the report`,
|
||||
);
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('a tracked plane that stops reporting: STALE from the first missed poll, SIGNAL LOST after the five-minute coast, kept at 9 min, removed at 10 min', () => {
|
||||
const { fixes, info } = outOfCoverage();
|
||||
const fixMs = fixes.at(-1).epochMs;
|
||||
// Contact stops with the position: the plane left coverage.
|
||||
info.lastContactEpochMs = fixMs;
|
||||
info.newestFixMs = fixMs;
|
||||
const h = harness({ fixes, info, nowMs: fixMs + 5 * SEC });
|
||||
try {
|
||||
h.tracking._startTrail(ICAO);
|
||||
const records = h.flightState.records;
|
||||
const polls = new Map();
|
||||
let removedAtSec = null;
|
||||
// A poll every 10 s that lists the plane without a position.
|
||||
for (let afterSec = 10; afterSec <= 660; afterSec += 10) {
|
||||
h.run(fixMs + afterSec * SEC, { frameMs: 500, readHead: false });
|
||||
const result = records.absence(ICAO, {
|
||||
complete: true,
|
||||
retainIds: new Set([ICAO]),
|
||||
likelyLanded: false,
|
||||
tracked: true,
|
||||
});
|
||||
if (result === 'remove') {
|
||||
removedAtSec = afterSec;
|
||||
break;
|
||||
}
|
||||
polls.set(afterSec, {
|
||||
cue: h.tracking._trackedStaleCue(ICAO),
|
||||
drawn: Cesium.Cartesian3.clone(h.drawn.at(-1)),
|
||||
});
|
||||
}
|
||||
// Wall time when the display reaches the end of the coast.
|
||||
const coastEndSec = 300 + RENDER_DELAY_SEC;
|
||||
for (const [afterSec, { cue }] of polls) {
|
||||
if (afterSec <= coastEndSec) {
|
||||
assert.deepEqual(cue, { text: 'STALE', dimmed: true }, `${afterSec} s`);
|
||||
} else {
|
||||
assert.deepEqual(
|
||||
cue,
|
||||
{
|
||||
text: `SIGNAL LOST · ${Math.floor(afterSec / 60)} min`,
|
||||
dimmed: true,
|
||||
},
|
||||
`${afterSec} s`,
|
||||
);
|
||||
}
|
||||
}
|
||||
const moved = (a, b) =>
|
||||
Cesium.Cartesian3.distance(polls.get(a).drawn, polls.get(b).drawn);
|
||||
// Moving through the coast, still at its last speed at four minutes.
|
||||
assert.ok(Math.abs(moved(230, 240) - 140 * 10) < 20);
|
||||
// Stopped once the coast has ended.
|
||||
const after = Math.ceil(coastEndSec / 10) * 10;
|
||||
assert.ok(moved(after, 540) < 0.01);
|
||||
assert.equal(polls.get(300).cue.text, 'STALE');
|
||||
assert.deepEqual(polls.get(540).cue, {
|
||||
text: 'SIGNAL LOST · 9 min',
|
||||
dimmed: true,
|
||||
});
|
||||
assert.equal(removedAtSec, 600);
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('a repeated old fix counts as a missed update for the tracked plane', () => {
|
||||
const { fixes, info } = outOfCoverage();
|
||||
const h = harness({ fixes, info, nowMs: pastReport(-5) });
|
||||
try {
|
||||
h.tracking._startTrail(ICAO);
|
||||
h.run(pastReport(-2));
|
||||
assert.deepEqual(h.tracking._trackedStaleCue(ICAO), {
|
||||
text: '',
|
||||
dimmed: false,
|
||||
});
|
||||
// The feed re-sends the last position: its fix time did not advance.
|
||||
h.flightState.records.fixRepeated.add(ICAO);
|
||||
assert.deepEqual(h.tracking._trackedStaleCue(ICAO), {
|
||||
text: 'STALE',
|
||||
dimmed: true,
|
||||
});
|
||||
assert.equal(h.tracking._trackedIconColor()[3], STALE_ALPHA);
|
||||
assert.equal(h.flightState.records.missingPolls.has(ICAO), false);
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('a stalled feed dims the tracked plane as STALE', () => {
|
||||
const { fixes, info } = outOfCoverage();
|
||||
const h = harness({ fixes, info, nowMs: pastReport(-5) });
|
||||
try {
|
||||
h.tracking._startTrail(ICAO);
|
||||
h.run(pastReport(-2));
|
||||
// The whole feed is backing off: no poll counts a miss, and no newer
|
||||
// position is coming in.
|
||||
h.flightState.feed._backoff = true;
|
||||
assert.deepEqual(h.tracking._trackedStaleCue(ICAO), {
|
||||
text: 'STALE',
|
||||
dimmed: true,
|
||||
});
|
||||
assert.equal(h.tracking._trackedIconColor()[3], STALE_ALPHA);
|
||||
assert.equal(h.flightState.records.missingPolls.has(ICAO), false);
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('a report arriving after the plane has stopped: it eases in with no spur, and the trail keeps everything up to the stop', () => {
|
||||
const { fixes, info } = outOfCoverage();
|
||||
info.lastContactEpochMs = fixes.at(-1).epochMs;
|
||||
const h = harness({ fixes, info, nowMs: pastReport(-5) });
|
||||
try {
|
||||
h.tracking._startTrail(ICAO);
|
||||
h.run(pastReport(360));
|
||||
const stop = Cesium.Cartesian3.clone(h.drawn.at(-1));
|
||||
assert.ok(Cesium.Cartesian3.distance(stop, h.drawn.at(-100)) < 0.01);
|
||||
const kept = h.flightState._trailFixes
|
||||
.filter((e) => e.drawn)
|
||||
.map((e) => Cesium.Cartesian3.clone(e.position));
|
||||
// The thinned straight coast, recorded up to where the plane stopped.
|
||||
assert.ok(kept.length >= 2);
|
||||
assert.ok(Cesium.Cartesian3.distance(kept.at(-1), stop) < 300);
|
||||
// Heard again, for 20 s before the display time: the plane flew on, a
|
||||
// little north of its old heading.
|
||||
const at = T0 + 30 * SEC + 340 * SEC;
|
||||
const lonDeg =
|
||||
-108.05 + (140 * 340) / (111_320 * Math.cos((43 * Math.PI) / 180));
|
||||
const report = fix(at, 43 + 1_000 / 111_320, lonDeg, 6_400, 140, 90);
|
||||
fixes.push(report);
|
||||
h.tracking._appendTrailFix(
|
||||
Cesium.Cartesian3.clone(report.position),
|
||||
report.epochMs,
|
||||
);
|
||||
// Nothing was recorded after the stop, so nothing is dropped.
|
||||
const after = h.flightState._trailFixes
|
||||
.filter((e) => e.drawn)
|
||||
.map((e) => e.position);
|
||||
assert.equal(after.length, kept.length);
|
||||
kept.forEach((p, i) =>
|
||||
assert.ok(Cesium.Cartesian3.distance(p, after[i]) < 0.01),
|
||||
);
|
||||
const from = h.drawn.length;
|
||||
h.run(pastReport(365));
|
||||
const eased = h.drawn.slice(from - 1);
|
||||
const jump = Cesium.Cartesian3.distance(eased[0], eased.at(-1));
|
||||
for (let i = 1; i < eased.length; i++)
|
||||
assert.ok(
|
||||
Cesium.Cartesian3.distance(eased[i], eased[i - 1]) < jump / 2,
|
||||
'the plane jumped instead of easing',
|
||||
);
|
||||
// On the path from the report: 25 s on from it at 140 m/s.
|
||||
const off = Cesium.Cartesian3.distance(eased.at(-1), report.position);
|
||||
assert.ok(Math.abs(off - 140 * 25) < 150, `${off.toFixed(0)} m`);
|
||||
assertNoSpur(h.bodyPoints(), 'trail');
|
||||
assertNoSpur(h.head(), 'head');
|
||||
assert.ok(indexOfPoint(h.bodyPoints(), report.position) >= 0);
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* What the layer drops when the world clock moves it to another time (its
|
||||
* source declares a timeline; see src/time/snapshotTimeline.js).
|
||||
*/
|
||||
export function createClockFollow({ flightState, parts }) {
|
||||
/**
|
||||
* Forget how every contact moved, before the snapshot at another time takes
|
||||
* the place of every contact: their fixes, courses and the tracked trail
|
||||
* belong to the time the clock left.
|
||||
*/
|
||||
function resetMotion() {
|
||||
flightState.records.reset();
|
||||
flightState._positionHistory.clear();
|
||||
flightState._displayCourse.clear();
|
||||
flightState._groundSnap.clear();
|
||||
flightState._drReconcileValid = false;
|
||||
flightState._cachedDRFrame = -1;
|
||||
flightState._cachedDRPosition = null;
|
||||
parts.tracking._clearTrail();
|
||||
flightState._lastCamPoseSig = '';
|
||||
}
|
||||
|
||||
/** Drop every contact: the time has none to show, or the clock went live. */
|
||||
function clear() {
|
||||
if (flightState._trackedIcao)
|
||||
parts.tracking._clearTracking(false, { evicted: true });
|
||||
resetMotion();
|
||||
// Each contact's icon row and 3D model go with it.
|
||||
for (const icao24 of [...(flightState._icons?.ids() ?? [])])
|
||||
parts.icons._forgetContact(icao24);
|
||||
flightState._detectionObjects.clear();
|
||||
flightState.feed._count = 0;
|
||||
flightState.feed._lastUpdate = null;
|
||||
}
|
||||
|
||||
return { resetMotion, clear };
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { MilitaryFlightRecords } from './records.js';
|
||||
import { createIngestion, createMilitaryFeed } from './ingestion.js';
|
||||
import { displayDelayMs, RENDER_DELAY_SEC } from './policy.js';
|
||||
|
||||
// Military aircraft follow the world clock only while their source declares
|
||||
// a timeline (src/time/snapshotTimeline.js); these cover the layer's side.
|
||||
|
||||
const T = 1_800_000_000_000;
|
||||
|
||||
test('military contacts are drawn behind the live edge, and at the time following the clock', () => {
|
||||
assert.equal(displayDelayMs({ timeline: null }), RENDER_DELAY_SEC * 1000);
|
||||
assert.equal(displayDelayMs({ timeline: { active: () => false } }), 15_000);
|
||||
assert.equal(displayDelayMs({ timeline: { active: () => true } }), 0);
|
||||
});
|
||||
|
||||
test('military records judge absence at the layer clock and reset at a jump', () => {
|
||||
let now = T;
|
||||
const store = new MilitaryFlightRecords({
|
||||
geoidHeight: () => 0,
|
||||
cachedGroundFloor: () => null,
|
||||
floorAltitudeM: (altitude) => altitude,
|
||||
now: () => now,
|
||||
});
|
||||
const { meta } = store.receive(
|
||||
{
|
||||
id: 'ae0001',
|
||||
reference: 'ae0001',
|
||||
latitude: 39,
|
||||
longitude: -77,
|
||||
baroAltitudeM: 3000,
|
||||
onGround: false,
|
||||
positionTimeMs: T - 1_000,
|
||||
},
|
||||
{ observedAtMs: T, floorWarmPoints: [] },
|
||||
);
|
||||
assert.equal(meta.observedReceiptMs, T);
|
||||
assert.equal(
|
||||
store.absence('ae0001', { complete: true, tracked: true }),
|
||||
'stale',
|
||||
);
|
||||
now = T + 11 * 60_000;
|
||||
assert.equal(
|
||||
store.absence('ae0001', { complete: true, tracked: true }),
|
||||
'remove',
|
||||
);
|
||||
store.receive(
|
||||
{ id: 'ae0001', latitude: 39, longitude: -77, positionTimeMs: T },
|
||||
{ observedAtMs: T, floorWarmPoints: [] },
|
||||
);
|
||||
store.absence('ae0001', { complete: true });
|
||||
store.reset();
|
||||
assert.equal(store.data.size, 0);
|
||||
assert.equal(store.missingPolls.size, 0);
|
||||
assert.equal(store.lastSnapshotMs, null);
|
||||
});
|
||||
|
||||
test('military polls carry no time; a snapshot at a time carries it, and polls stop following', async () => {
|
||||
const queries = [];
|
||||
const applied = [];
|
||||
let follows = false;
|
||||
const feed = createMilitaryFeed({
|
||||
async getSnapshot(query) {
|
||||
queries.push(query);
|
||||
return { records: [], observedAtMs: T, freshness: 'current' };
|
||||
},
|
||||
});
|
||||
const { methods } = createIngestion({
|
||||
feed,
|
||||
applySnapshot: (_snapshot, _viewer, options) => {
|
||||
applied.push(options);
|
||||
return { count: 0, ids: new Set() };
|
||||
},
|
||||
setSourceLabel: () => {},
|
||||
applyPendingTrackingRestore: () => {},
|
||||
followsClock: () => follows,
|
||||
});
|
||||
await methods.update(null);
|
||||
assert.deepEqual(queries, [{}]);
|
||||
assert.deepEqual(applied, [undefined]);
|
||||
follows = true;
|
||||
await methods.update(null);
|
||||
assert.equal(queries.length, 1, 'no poll while following');
|
||||
assert.equal(await methods.loadAt(T, { replace: true }), true);
|
||||
assert.deepEqual(queries[1], { atMs: T });
|
||||
assert.deepEqual(applied[1], { replace: true });
|
||||
});
|
||||
@@ -3,6 +3,8 @@ import {
|
||||
COCKPIT_CONTACT_SIZE_PX,
|
||||
COURSE_MAX_DPS,
|
||||
RENDER_DELAY_SEC,
|
||||
STALE_ALPHA,
|
||||
followsClock,
|
||||
} from './policy.js';
|
||||
|
||||
/** The military layer's contacts as one icon set (`createAircraftIcons`). */
|
||||
@@ -13,6 +15,8 @@ export function createIcons({ flightState, services, parts }) {
|
||||
parts,
|
||||
layerId: 'military',
|
||||
renderDelaySec: RENDER_DELAY_SEC,
|
||||
followsClock: () => followsClock(flightState),
|
||||
staleAlpha: STALE_ALPHA,
|
||||
courseMaxDps: COURSE_MAX_DPS,
|
||||
cockpitContactSizePx: COCKPIT_CONTACT_SIZE_PX,
|
||||
});
|
||||
|
||||
@@ -9,6 +9,9 @@ import { createIngestion } from './ingestion.js';
|
||||
import { createLifecycle } from './lifecycle.js';
|
||||
import { createTesting } from './testing.js';
|
||||
import { createQueries } from './queries.js';
|
||||
import { createClockFollow } from './clockFollow.js';
|
||||
import { createSnapshotTimeline } from '../../time/snapshotTimeline.js';
|
||||
import { worldClock } from '../../time/worldClock.js';
|
||||
/** Compose one military-flight layer with application-owned scene services. */
|
||||
export function createMilitaryFlightLayer({
|
||||
source,
|
||||
@@ -27,6 +30,7 @@ export function createMilitaryFlightLayer({
|
||||
parts.lifecycle = createLifecycle(context);
|
||||
parts.testing = createTesting(context);
|
||||
parts.queries = createQueries(context);
|
||||
parts.clockFollow = createClockFollow(context);
|
||||
const applySnapshot = createMilitarySnapshotRenderer({
|
||||
flightState,
|
||||
records: flightState.records,
|
||||
@@ -40,7 +44,11 @@ export function createMilitaryFlightLayer({
|
||||
});
|
||||
parts.ingestion = createIngestion({
|
||||
feed: flightState.feed,
|
||||
applySnapshot,
|
||||
applySnapshot: (snapshot, viewer, options) => {
|
||||
if (options?.replace) parts.clockFollow.resetMotion();
|
||||
return applySnapshot(snapshot, viewer, options);
|
||||
},
|
||||
followsClock: () => flightState.timeline.active(),
|
||||
setSourceLabel: (source) => {
|
||||
layer.source = source;
|
||||
},
|
||||
@@ -48,6 +56,19 @@ export function createMilitaryFlightLayer({
|
||||
parts.tracking._applyPendingTrackingRestore(),
|
||||
});
|
||||
|
||||
// Contacts follow the world clock while the source declares a timeline.
|
||||
flightState.timeline = createSnapshotTimeline({
|
||||
id: 'military',
|
||||
clock: worldClock,
|
||||
source: () => flightState.feed._source,
|
||||
load: (atMs, { signal, replace }) =>
|
||||
parts.ingestion.methods.loadAt(atMs, { signal, replace }),
|
||||
clear: () => parts.clockFollow.clear(),
|
||||
resumeLive: () => {
|
||||
layer.update(flightState._viewer).catch(() => {});
|
||||
},
|
||||
});
|
||||
|
||||
Object.assign(
|
||||
layer,
|
||||
parts.queries.methods,
|
||||
|
||||
@@ -10,78 +10,110 @@ export function createIngestion({
|
||||
applySnapshot,
|
||||
setSourceLabel,
|
||||
applyPendingTrackingRestore,
|
||||
followsClock = () => false,
|
||||
}) {
|
||||
const methods = {
|
||||
async update(viewer, { signal = null } = {}) {
|
||||
const nowMs = Date.now();
|
||||
const trackingRefreshEpoch = ++feed._trackingRefreshEpoch;
|
||||
feed._lastTrackingRefreshOutcome = {
|
||||
epoch: trackingRefreshEpoch,
|
||||
status: 'source-unavailable',
|
||||
ids: new Set(),
|
||||
source: feed._lastSource,
|
||||
};
|
||||
if (feed._retryAt && nowMs < feed._retryAt) {
|
||||
feed._backoff = true;
|
||||
return;
|
||||
}
|
||||
// Following the world clock, the layer shows the snapshots loadAt
|
||||
// applies; polling the live feed would put the live edge among them.
|
||||
if (followsClock()) return;
|
||||
await acquire(viewer, { signal });
|
||||
},
|
||||
|
||||
const resourceController = new AbortController();
|
||||
feed._activeUpdateControllers.add(resourceController);
|
||||
const updateSignal = signal
|
||||
? AbortSignal.any([signal, resourceController.signal])
|
||||
: resourceController.signal;
|
||||
try {
|
||||
updateSignal.throwIfAborted();
|
||||
const snapshot = await feed._source.getSnapshot(
|
||||
{},
|
||||
{ signal: updateSignal },
|
||||
);
|
||||
updateSignal.throwIfAborted();
|
||||
feed._lastStatus = snapshot.status ?? 200;
|
||||
feed._lastSource = snapshot.source;
|
||||
setSourceLabel(feed._lastSource);
|
||||
feed._backoff = snapshot.stale || snapshot.freshness === 'unknown';
|
||||
feed._retryAt = 0;
|
||||
feed._lastError =
|
||||
snapshot.reason ||
|
||||
(snapshot.freshness === 'unknown'
|
||||
? msg('Source snapshot time unavailable')
|
||||
: null);
|
||||
const accepted = applySnapshot(snapshot, viewer);
|
||||
feed._count = accepted.count;
|
||||
feed._lastUpdate = snapshot.observedAtMs;
|
||||
feed._lastTrackingRefreshOutcome = {
|
||||
epoch: trackingRefreshEpoch,
|
||||
status: 'accepted',
|
||||
ids: accepted.ids,
|
||||
source: feed._lastSource,
|
||||
};
|
||||
console.log(`[Data:Military] Updated: ${feed._count} aircraft`);
|
||||
applyPendingTrackingRestore();
|
||||
} catch (e) {
|
||||
if (updateSignal.aborted || e?.name === 'AbortError') {
|
||||
throw new DOMException('Military update aborted', 'AbortError');
|
||||
}
|
||||
console.warn('[Data:Military] Fetch error:', e);
|
||||
feed._backoff = true;
|
||||
feed._retryAt =
|
||||
Date.now() + (e?.retryAfterMs ?? ERROR_BACKOFF_INTERVAL);
|
||||
feed._lastStatus = e?.status ?? null;
|
||||
if (e?.source) {
|
||||
feed._lastSource = e.source;
|
||||
setSourceLabel(feed._lastSource);
|
||||
}
|
||||
feed._lastError =
|
||||
e?.name === 'LiveSourceError'
|
||||
? e.message
|
||||
: msg('Live data unavailable');
|
||||
} finally {
|
||||
feed._activeUpdateControllers.delete(resourceController);
|
||||
}
|
||||
/**
|
||||
* Apply the source's snapshot at world time `atMs` (its timeline says it
|
||||
* can answer one), in place of every contact when `replace`. Resolves
|
||||
* whether it was applied.
|
||||
* @param {number} atMs
|
||||
* @param {{signal?: AbortSignal|null, replace?: boolean, viewer?: object}} [options]
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
async loadAt(atMs, { signal = null, replace = false, viewer = null } = {}) {
|
||||
// Whatever polls or loads for another time no longer applies.
|
||||
if (replace)
|
||||
for (const controller of feed._activeUpdateControllers)
|
||||
controller.abort();
|
||||
return acquire(viewer, { signal, atMs, replace });
|
||||
},
|
||||
};
|
||||
|
||||
async function acquire(viewer, { signal = null, atMs, replace = false }) {
|
||||
const nowMs = Date.now();
|
||||
const timed = atMs !== undefined;
|
||||
const trackingRefreshEpoch = ++feed._trackingRefreshEpoch;
|
||||
feed._lastTrackingRefreshOutcome = {
|
||||
epoch: trackingRefreshEpoch,
|
||||
status: 'source-unavailable',
|
||||
ids: new Set(),
|
||||
source: feed._lastSource,
|
||||
};
|
||||
if (!timed && feed._retryAt && nowMs < feed._retryAt) {
|
||||
feed._backoff = true;
|
||||
return;
|
||||
}
|
||||
|
||||
const resourceController = new AbortController();
|
||||
feed._activeUpdateControllers.add(resourceController);
|
||||
const updateSignal = signal
|
||||
? AbortSignal.any([signal, resourceController.signal])
|
||||
: resourceController.signal;
|
||||
try {
|
||||
updateSignal.throwIfAborted();
|
||||
const snapshot = await feed._source.getSnapshot(timed ? { atMs } : {}, {
|
||||
signal: updateSignal,
|
||||
});
|
||||
updateSignal.throwIfAborted();
|
||||
// The clock left the live edge while this poll was out.
|
||||
if (!timed && followsClock()) return;
|
||||
feed._lastStatus = snapshot.status ?? 200;
|
||||
feed._lastSource = snapshot.source;
|
||||
setSourceLabel(feed._lastSource);
|
||||
feed._backoff = snapshot.stale || snapshot.freshness === 'unknown';
|
||||
feed._retryAt = 0;
|
||||
feed._lastError =
|
||||
snapshot.reason ||
|
||||
(snapshot.freshness === 'unknown'
|
||||
? msg('Source snapshot time unavailable')
|
||||
: null);
|
||||
const accepted = timed
|
||||
? applySnapshot(snapshot, viewer, { replace })
|
||||
: applySnapshot(snapshot, viewer);
|
||||
feed._count = accepted.count;
|
||||
feed._lastUpdate = snapshot.observedAtMs;
|
||||
feed._lastTrackingRefreshOutcome = {
|
||||
epoch: trackingRefreshEpoch,
|
||||
status: 'accepted',
|
||||
ids: accepted.ids,
|
||||
source: feed._lastSource,
|
||||
};
|
||||
console.log(`[Data:Military] Updated: ${feed._count} aircraft`);
|
||||
applyPendingTrackingRestore();
|
||||
return true;
|
||||
} catch (e) {
|
||||
if (updateSignal.aborted || e?.name === 'AbortError') {
|
||||
throw new DOMException('Military update aborted', 'AbortError');
|
||||
}
|
||||
console.warn('[Data:Military] Fetch error:', e);
|
||||
feed._backoff = true;
|
||||
// A snapshot at a time is asked again by the clock's follower.
|
||||
if (!timed)
|
||||
feed._retryAt =
|
||||
Date.now() + (e?.retryAfterMs ?? ERROR_BACKOFF_INTERVAL);
|
||||
feed._lastStatus = e?.status ?? null;
|
||||
if (e?.source) {
|
||||
feed._lastSource = e.source;
|
||||
setSourceLabel(feed._lastSource);
|
||||
}
|
||||
feed._lastError =
|
||||
e?.name === 'LiveSourceError'
|
||||
? e.message
|
||||
: msg('Live data unavailable');
|
||||
return false;
|
||||
} finally {
|
||||
feed._activeUpdateControllers.delete(resourceController);
|
||||
}
|
||||
}
|
||||
|
||||
return { methods };
|
||||
}
|
||||
|
||||
|
||||
@@ -131,6 +131,7 @@ export function createLifecycle({
|
||||
flightState._lastFleetTickMs = 0;
|
||||
});
|
||||
}
|
||||
flightState.timeline?.start();
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -139,6 +140,7 @@ export function createLifecycle({
|
||||
* @param {object} viewer - The Cesium viewer instance
|
||||
*/
|
||||
disable(viewer) {
|
||||
flightState.timeline?.stop();
|
||||
parts.controller._abortActiveUpdates();
|
||||
parts.tracking._cancelPendingTrackingRestore();
|
||||
if (flightState._icons) flightState._icons.show = false;
|
||||
@@ -179,6 +181,7 @@ export function createLifecycle({
|
||||
* @param {object} viewer - The Cesium viewer instance
|
||||
*/
|
||||
destroy(viewer) {
|
||||
flightState.timeline?.stop();
|
||||
flightState.lifetime.abort();
|
||||
parts.controller._abortActiveUpdates();
|
||||
releaseContinuousRender('military'); // direct-destroy path (perf wave 2 fix)
|
||||
|
||||
@@ -21,6 +21,8 @@ import {
|
||||
import {
|
||||
lerpAngleDeg,
|
||||
COURSE_HOLD_SPEED_MPS,
|
||||
floorCoastedPosition,
|
||||
staleHoldsForFix,
|
||||
arcOffsetEnu,
|
||||
courseSlewCapDps,
|
||||
limitCourseStep,
|
||||
@@ -31,7 +33,8 @@ import {
|
||||
modelAnchorWorld,
|
||||
} from '../../data/modelVisualAnchor.js';
|
||||
import {
|
||||
RENDER_DELAY_SEC,
|
||||
displayDelayMs,
|
||||
followsClock,
|
||||
TRACKED_MODEL_MAX_PX,
|
||||
TRACKED_MODEL_MIN_PX,
|
||||
BILLBOARD_SCALE,
|
||||
@@ -51,6 +54,7 @@ import {
|
||||
julianAt,
|
||||
fixSpeedMps,
|
||||
fixTrackDeg,
|
||||
staleCoastSeconds,
|
||||
} from '../../data/aircraftMotionRegime.js';
|
||||
|
||||
/** Where a military record carries its reported speed and track. */
|
||||
@@ -126,7 +130,7 @@ export function createMotion({
|
||||
// two KNOWN fixes whenever possible (see RENDER_DELAY_SEC rationale).
|
||||
const renderTime = addSeconds(
|
||||
julianFromEpochMs(flightState.now()),
|
||||
-RENDER_DELAY_SEC,
|
||||
-displayDelayMs(flightState) / 1000,
|
||||
flightState._scratchRenderTime,
|
||||
);
|
||||
|
||||
@@ -148,7 +152,11 @@ export function createMotion({
|
||||
regime.minDt,
|
||||
regime.maxDt,
|
||||
);
|
||||
return _extrapolateFix(regime.fix, info, dt, out, regime.turnRateDps);
|
||||
_extrapolateFix(regime.fix, info, dt, out, regime.turnRateDps);
|
||||
// A coast never goes below the ground.
|
||||
return dt > 0
|
||||
? floorCoastedPosition(out, services.groundFloor?.cachedGroundFloor)
|
||||
: out;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -164,9 +172,39 @@ export function createMotion({
|
||||
renderTime,
|
||||
RECORD_FIELDS,
|
||||
regime,
|
||||
{ cachedGroundFloor: services.groundFloor?.cachedGroundFloor },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a contact has stopped where its coast ended (or held at its last
|
||||
* report) with no newer report, and since when it has had none.
|
||||
* @param {string} icao24
|
||||
* @returns {{reportEpochMs: number, holds: boolean}|null} Null while a
|
||||
* report is ahead of the display time or the contact is still coasting.
|
||||
*/
|
||||
function _signalLost(icao24) {
|
||||
const newest = flightState._positionHistory.get(icao24)?.at(-1);
|
||||
if (!newest) return null;
|
||||
const newestMs = fixEpochMs(newest);
|
||||
const elapsedSec =
|
||||
(flightState.now() - displayDelayMs(flightState) - newestMs) / 1000;
|
||||
if (!(elapsedSec > 0)) return null;
|
||||
const info = flightState.records.data.get(icao24);
|
||||
const cachedGroundFloor = services.groundFloor?.cachedGroundFloor;
|
||||
const coastSec = staleCoastSeconds(newest, info, cachedGroundFloor);
|
||||
if (!(elapsedSec > coastSec)) return null;
|
||||
return {
|
||||
reportEpochMs: Number.isFinite(newest.reportEpochMs)
|
||||
? newest.reportEpochMs
|
||||
: newestMs,
|
||||
holds: staleHoldsForFix(newest, {
|
||||
onGround: info?.onGround,
|
||||
cachedGroundFloor,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Dead-reckon a fix along its own velocity/track by `dt` seconds, integrating a
|
||||
* constant-rate-turn arc when `turnRateDps` is significant (straight line
|
||||
@@ -220,7 +258,7 @@ export function createMotion({
|
||||
if (!history || history.length === 0) return true;
|
||||
const renderTime = addSeconds(
|
||||
julianFromEpochMs(flightState.now()),
|
||||
-RENDER_DELAY_SEC,
|
||||
-displayDelayMs(flightState) / 1000,
|
||||
flightState._scratchWarmupTime,
|
||||
);
|
||||
return julianLessThan(renderTime, history[0].time);
|
||||
@@ -302,9 +340,15 @@ export function createMotion({
|
||||
}
|
||||
|
||||
const nowMs = Date.now();
|
||||
// How far the contact may move between frames goes by the world's time,
|
||||
// which plays faster than the wall clock when following it at a rate.
|
||||
const worldMs = followsClock(flightState) ? flightState.now() : nowMs;
|
||||
const info = flightState.records.data.get(icao24);
|
||||
if (sameTrack) {
|
||||
const dtSec = Math.max(0.001, (nowMs - flightState._drPrevMs) / 1000);
|
||||
const dtSec = Math.max(
|
||||
0.001,
|
||||
(worldMs - flightState._drPrevWorldMs) / 1000,
|
||||
);
|
||||
const speed = (info && info.speedMps) || 0;
|
||||
// Plausible single-frame motion (m): real velocity × frame Δt, ×4 slack + 25 m base.
|
||||
const plausible = speed * dtSec * 4 + 25;
|
||||
@@ -332,6 +376,7 @@ export function createMotion({
|
||||
copyInto(raw, flightState._drPrevRaw);
|
||||
copyInto(display, flightState._drPrevDisplay);
|
||||
flightState._drPrevMs = nowMs;
|
||||
flightState._drPrevWorldMs = worldMs;
|
||||
flightState._drReconcileValid = true;
|
||||
flightState._cachedDRPosition = display;
|
||||
const focusSizePx = _trackedFocusSizePx(
|
||||
@@ -571,6 +616,7 @@ export function createMotion({
|
||||
_motionRegime,
|
||||
_displayTimeAt,
|
||||
_fixEpochMs: fixEpochMs,
|
||||
_signalLost,
|
||||
_extrapolateFix,
|
||||
_isTrackWarmingUp,
|
||||
_trackedFocusSizePx,
|
||||
|
||||
@@ -173,7 +173,7 @@ export const TRAIL_COLOR = '#FFB800';
|
||||
|
||||
/** @constant {number} Combined cap on trail vertices (backfill + live accumulation). */
|
||||
|
||||
export const TRAIL_MAX_POINTS = 400;
|
||||
export const TRAIL_MAX_POINTS = 2000;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Render-behind smoothing (mirrors flights.js): the fleet renders at
|
||||
@@ -187,6 +187,15 @@ export const TRAIL_MAX_POINTS = 400;
|
||||
|
||||
export const RENDER_DELAY_SEC = 15;
|
||||
|
||||
/** Whether the layer shows the world clock's time instead of the live feed:
|
||||
* its source declares a timeline and the clock is away from live. */
|
||||
export const followsClock = (state) => state.timeline?.active() === true;
|
||||
|
||||
/** How far behind the time contacts are drawn: RENDER_DELAY_SEC live, none
|
||||
* following the clock, whose snapshots are loaded ahead of the time. */
|
||||
export const displayDelayMs = (state) =>
|
||||
followsClock(state) ? 0 : RENDER_DELAY_SEC * 1000;
|
||||
|
||||
/** @constant {number} Polls an aircraft may miss before removal (transient adsb.lol dropouts). */
|
||||
|
||||
// --- Landed-plane fast cull (mirror of flights.js; owner field report
|
||||
@@ -248,3 +257,6 @@ export const DR_CORRECTION_MS = 900;
|
||||
export const TRACKED_MODEL_MAX_LOAD_FAILS = 3;
|
||||
|
||||
export const TRACKED_MODEL_RETRY_BACKOFF_MS = 1500;
|
||||
|
||||
/** Alpha of a contact that has missed an update or lost its signal: the stale fade, for the fleet and the tracked aircraft alike. */
|
||||
export const STALE_ALPHA = 0.45;
|
||||
@@ -12,7 +12,11 @@ import {
|
||||
contactMatchWins,
|
||||
CONTACT_MATCH_TIER,
|
||||
} from '../../data/contactMatch.js';
|
||||
import { LANDED_ALT_MAX_FT, LANDED_SPEED_MAX_MPS } from './policy.js';
|
||||
import {
|
||||
LANDED_ALT_MAX_FT,
|
||||
LANDED_SPEED_MAX_MPS,
|
||||
followsClock,
|
||||
} from './policy.js';
|
||||
import { emergencyBroadcastPhrase } from '../../data/aircraftEmergency.js';
|
||||
|
||||
export function createQueries({
|
||||
@@ -806,6 +810,8 @@ export function createQueries({
|
||||
retryInSec,
|
||||
source: flightState.feed._lastSource,
|
||||
fallback: false,
|
||||
// Following the world clock, the snapshot's age is told from its time.
|
||||
...(followsClock(flightState) && { atMs: flightState.now() }),
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
@@ -6,4 +6,8 @@ export const LANDED_MISSING_POLL_LIMIT = 1;
|
||||
|
||||
export const MISSING_POLL_LIMIT = 3;
|
||||
|
||||
/** The tracked contact is kept this long after its newest fix: five minutes
|
||||
* coasting, then five stopped as SIGNAL LOST. */
|
||||
export const TRACKED_RETENTION_MS = 10 * 60_000;
|
||||
|
||||
export const ERROR_BACKOFF_INTERVAL = 20000;
|
||||
@@ -6,17 +6,60 @@ import {
|
||||
GROUND_FLOOR_WARM_MAX_ALT_M,
|
||||
LANDED_MISSING_POLL_LIMIT,
|
||||
MISSING_POLL_LIMIT,
|
||||
TRACKED_RETENTION_MS,
|
||||
} from './recordPolicy.js';
|
||||
|
||||
/** Portable military aircraft metadata and bounded missing-poll retention. */
|
||||
export class MilitaryFlightRecords {
|
||||
constructor({ geoidHeight, cachedGroundFloor, floorAltitudeM }) {
|
||||
constructor({
|
||||
geoidHeight,
|
||||
cachedGroundFloor,
|
||||
floorAltitudeM,
|
||||
now = () => Date.now(),
|
||||
}) {
|
||||
this.services = { geoidHeight, cachedGroundFloor, floorAltitudeM };
|
||||
/** The time records are judged at: the layer's clock. */
|
||||
this.now = now;
|
||||
this.data = new Map();
|
||||
this.missingPolls = new Map();
|
||||
// Contacts whose last poll re-sent a fix no newer than the one before.
|
||||
this.fixRepeated = new Set();
|
||||
this.lastSnapshotMs = null;
|
||||
this.snapshotAdvanced = true;
|
||||
this.geoidNCache = new Map();
|
||||
this.geoidReady = false;
|
||||
}
|
||||
/**
|
||||
* Start reading a snapshot taken at `observedAtMs`. A fix re-sent in a
|
||||
* newer snapshot marks its contact as not updated; the same snapshot read
|
||||
* again does not.
|
||||
* @param {number} observedAtMs
|
||||
*/
|
||||
beginSnapshot(observedAtMs) {
|
||||
this.snapshotAdvanced =
|
||||
!Number.isFinite(observedAtMs) ||
|
||||
!Number.isFinite(this.lastSnapshotMs) ||
|
||||
observedAtMs > this.lastSnapshotMs;
|
||||
if (Number.isFinite(observedAtMs))
|
||||
this.lastSnapshotMs = Math.max(
|
||||
this.lastSnapshotMs ?? -Infinity,
|
||||
observedAtMs,
|
||||
);
|
||||
}
|
||||
|
||||
/** Note a received fix: the newest fix time, and whether it advanced. */
|
||||
_noteFix(id, prevMeta, fixEpochMs) {
|
||||
const prevFixMs = prevMeta?.newestFixMs;
|
||||
// A fix counts as new only when it moves on by a second: feeds that
|
||||
// derive fix time from receipt (readsb `now − seen_pos`, 0.1 s) jitter.
|
||||
if (!Number.isFinite(prevFixMs) || fixEpochMs >= prevFixMs + 1000) {
|
||||
this.fixRepeated.delete(id);
|
||||
return fixEpochMs;
|
||||
}
|
||||
if (this.snapshotAdvanced) this.fixRepeated.add(id);
|
||||
return prevFixMs;
|
||||
}
|
||||
|
||||
receive(
|
||||
aircraft,
|
||||
{ observedAtMs, floorWarmPoints: _floorWarmPoints, modelOwnsVisual },
|
||||
@@ -88,6 +131,10 @@ export class MilitaryFlightRecords {
|
||||
// already uses (which also carries the on-ground 0 m / last-known-baro
|
||||
// case), so the two never disagree on the "no data yet" case.
|
||||
let renderAltitudeM = pickedAltM != null ? pickedAltM : altitudeM;
|
||||
// No altitude for an airborne contact: the height is the airborne
|
||||
// default, invented. The tracked trail keeps no point there.
|
||||
const renderAltitudeInvented =
|
||||
pickedAltM == null && !onGround && aircraft.baroAltitudeM == null;
|
||||
// Field-test fix (RS46 heli-in-hillside, 2026-07-06): a baro-only
|
||||
// AIRBORNE contact near steep terrain can compute a render height
|
||||
// BELOW the local surface (no alt_geom; baro+N carries QNH error
|
||||
@@ -127,9 +174,11 @@ export class MilitaryFlightRecords {
|
||||
// Sticky merge — adsb.lol intermittently drops flight/t/r/ownOp; hold
|
||||
// last-known-good (bounded by the layer's eviction, which deletes the entry).
|
||||
const stickyType = stickyText(type, prevMeta?.type);
|
||||
const fixEpochMs = aircraft.positionTimeMs ?? observedAtMs;
|
||||
const meta = {
|
||||
sourceReference: aircraft.reference,
|
||||
observedReceiptMs: Date.now(),
|
||||
observedReceiptMs: this.now(),
|
||||
newestFixMs: this._noteFix(icao24, prevMeta, fixEpochMs),
|
||||
callsign: stickyText(callsign, prevMeta?.callsign),
|
||||
type: stickyType,
|
||||
// Type outranks category automatically inside classifyAircraft.
|
||||
@@ -146,6 +195,7 @@ export class MilitaryFlightRecords {
|
||||
// altitudeFt/baro).
|
||||
geoAltitudeM,
|
||||
renderAltitudeM,
|
||||
renderAltitudeInvented,
|
||||
// A poll that omits track/speed holds the last values, like the civil
|
||||
// records; 0 only until one is known. A grounded row without a speed
|
||||
// reads 0, so a parked plane never coasts at its landing speed.
|
||||
@@ -184,19 +234,36 @@ export class MilitaryFlightRecords {
|
||||
prevMeta,
|
||||
meta,
|
||||
groundFlipped,
|
||||
fixEpochMs: aircraft.positionTimeMs ?? observedAtMs,
|
||||
fixEpochMs,
|
||||
};
|
||||
}
|
||||
absence(id, { complete, retainIds, likelyLanded }) {
|
||||
absence(
|
||||
id,
|
||||
{ complete, retainIds, likelyLanded, tracked = false, nowMs = this.now() },
|
||||
) {
|
||||
const misses = (this.missingPolls.get(id) || 0) + 1;
|
||||
// The tracked contact has missed an update: it is stale from the first
|
||||
// one, and kept (so the camera keeps its target) until ten minutes after
|
||||
// its newest fix, whatever the snapshot says. With no fix time known it
|
||||
// takes the ordinary limits below.
|
||||
const meta = this.data.get(id);
|
||||
const fixMs = meta?.newestFixMs ?? meta?.observedReceiptMs;
|
||||
if (tracked && Number.isFinite(fixMs)) {
|
||||
if (nowMs - fixMs < TRACKED_RETENTION_MS) {
|
||||
this.missingPolls.set(id, misses);
|
||||
return 'stale';
|
||||
}
|
||||
this.missingPolls.delete(id);
|
||||
return 'remove';
|
||||
}
|
||||
// Partial admissions and position-less rows do not prove absence, but
|
||||
// retention remains bounded; a likely-landed position-less contact
|
||||
// still takes the landed limit.
|
||||
if (
|
||||
(!complete || (retainIds?.has(id) && !likelyLanded)) &&
|
||||
Date.now() - (this.data.get(id)?.observedReceiptMs ?? 0) < 300000
|
||||
nowMs - (this.data.get(id)?.observedReceiptMs ?? 0) < 300000
|
||||
)
|
||||
return 'retain';
|
||||
const misses = (this.missingPolls.get(id) || 0) + 1;
|
||||
const limit = likelyLanded ? LANDED_MISSING_POLL_LIMIT : MISSING_POLL_LIMIT;
|
||||
if (misses < limit) {
|
||||
this.missingPolls.set(id, misses);
|
||||
@@ -205,9 +272,18 @@ export class MilitaryFlightRecords {
|
||||
this.missingPolls.delete(id);
|
||||
return 'remove';
|
||||
}
|
||||
/** Forget every observation, as when the world clock jumps to another time. */
|
||||
reset() {
|
||||
this.data.clear();
|
||||
this.missingPolls.clear();
|
||||
this.fixRepeated.clear();
|
||||
this.lastSnapshotMs = null;
|
||||
this.snapshotAdvanced = true;
|
||||
}
|
||||
forget(id) {
|
||||
this.data.delete(id);
|
||||
this.missingPolls.delete(id);
|
||||
this.fixRepeated.delete(id);
|
||||
this.geoidNCache.delete(id);
|
||||
}
|
||||
}
|
||||
@@ -174,3 +174,98 @@ test('military records hold the last track and speed when a poll omits them', ()
|
||||
assert.equal(parked.meta.speedMps, 0);
|
||||
assert.equal(parked.meta.track, 90);
|
||||
});
|
||||
|
||||
test('an airborne military contact reported with no altitude is marked as drawn at an invented height', () => {
|
||||
const records = store();
|
||||
const none = records.receive(
|
||||
observation({ baroAltitudeM: null, ellipsoidAltitudeM: null }),
|
||||
context(),
|
||||
);
|
||||
assert.equal(none.meta.renderAltitudeInvented, true);
|
||||
const known = records.receive(
|
||||
observation({ positionTimeMs: 1700000005000 }),
|
||||
context(),
|
||||
);
|
||||
assert.equal(known.meta.renderAltitudeInvented, false);
|
||||
const parked = store().receive(
|
||||
observation({ baroAltitudeM: null, onGround: true }),
|
||||
context(),
|
||||
);
|
||||
assert.equal(parked.meta.renderAltitudeInvented, false);
|
||||
});
|
||||
|
||||
test('the tracked military contact is stale from its first missed update and kept until ten minutes after its newest fix', () => {
|
||||
const realNow = Date.now;
|
||||
const fixMs = Date.UTC(2026, 10, 9, 20, 0);
|
||||
let clock = fixMs + 5_000;
|
||||
Date.now = () => clock;
|
||||
try {
|
||||
for (const snapshot of [
|
||||
{ complete: true },
|
||||
{ complete: true, retainIds: new Set(['aaa001']) },
|
||||
{ complete: false },
|
||||
]) {
|
||||
const records = store();
|
||||
records.receive(
|
||||
observation({ positionTimeMs: fixMs }),
|
||||
context({ observedAtMs: fixMs + 1_000 }),
|
||||
);
|
||||
const absent = (tracked) =>
|
||||
records.absence('aaa001', {
|
||||
...snapshot,
|
||||
likelyLanded: false,
|
||||
tracked,
|
||||
});
|
||||
clock = fixMs + 15_000;
|
||||
assert.equal(absent(true), 'stale');
|
||||
assert.equal(records.missingPolls.get('aaa001'), 1);
|
||||
clock = fixMs + 9 * 60_000;
|
||||
assert.equal(absent(true), 'stale');
|
||||
clock = fixMs + 10 * 60_000 - 1;
|
||||
assert.equal(absent(true), 'stale');
|
||||
clock = fixMs + 10 * 60_000;
|
||||
assert.equal(absent(true), 'remove');
|
||||
assert.equal(records.missingPolls.has('aaa001'), false);
|
||||
}
|
||||
const records = store();
|
||||
records.receive(
|
||||
observation({ positionTimeMs: fixMs }),
|
||||
context({ observedAtMs: fixMs + 1_000 }),
|
||||
);
|
||||
clock = fixMs + 15_000;
|
||||
const untracked = (snapshot) =>
|
||||
records.absence('aaa001', { ...snapshot, likelyLanded: false });
|
||||
assert.equal(untracked({ complete: false }), 'retain');
|
||||
assert.deepEqual(
|
||||
[1, 2, 3].map(() => untracked({ complete: true })),
|
||||
['stale', 'stale', 'remove'],
|
||||
);
|
||||
} finally {
|
||||
Date.now = realNow;
|
||||
}
|
||||
});
|
||||
|
||||
test('a repeated military fix time marks the contact as not updated; removal is unchanged', () => {
|
||||
const records = store();
|
||||
const fixMs = Date.UTC(2026, 10, 9, 20, 0);
|
||||
const poll = (snapshotMs, positionTimeMs) => {
|
||||
records.beginSnapshot(snapshotMs);
|
||||
records.receive(
|
||||
observation({ positionTimeMs }),
|
||||
context({ observedAtMs: snapshotMs }),
|
||||
);
|
||||
};
|
||||
poll(fixMs + 2_000, fixMs);
|
||||
assert.equal(records.fixRepeated.has('aaa001'), false);
|
||||
// adsb.lol re-sends the last position for up to a minute.
|
||||
poll(fixMs + 12_000, fixMs);
|
||||
assert.equal(records.fixRepeated.has('aaa001'), true);
|
||||
assert.equal(records.missingPolls.has('aaa001'), false);
|
||||
poll(fixMs + 12_000, fixMs);
|
||||
assert.equal(records.fixRepeated.has('aaa001'), true);
|
||||
poll(fixMs + 22_000, fixMs + 10_000);
|
||||
assert.equal(records.fixRepeated.has('aaa001'), false);
|
||||
poll(fixMs + 32_000, fixMs + 10_000);
|
||||
records.forget('aaa001');
|
||||
assert.equal(records.fixRepeated.has('aaa001'), false);
|
||||
});
|
||||
@@ -2,9 +2,11 @@ import { findCamera } from '../../render/rendererOf.js';
|
||||
import {
|
||||
turnRateFromFixHistory,
|
||||
liftRepeatedGroundFix,
|
||||
staleHoldsForFix,
|
||||
synthesizeForwardKinematicsFix,
|
||||
} from '../../data/motionModel.js';
|
||||
import { POSITION_HISTORY_LIMIT } from './recordPolicy.js';
|
||||
import { followsClock } from './policy.js';
|
||||
|
||||
/** Apply military record changes to the layer's drawing and existing follow operations. */
|
||||
export function createMilitarySnapshotRenderer({
|
||||
@@ -18,13 +20,18 @@ export function createMilitarySnapshotRenderer({
|
||||
icons,
|
||||
queries,
|
||||
}) {
|
||||
const { warmGroundFloor } = groundFloor;
|
||||
const { warmGroundFloor, cachedGroundFloor } = groundFloor;
|
||||
const { registerMilitaryIcaos } = militaryRegistry;
|
||||
return function applySnapshot(snapshot, viewer) {
|
||||
/**
|
||||
* `replace`: the snapshot is the world at another time (the world clock
|
||||
* jumped), so it stands in for every contact: one it lacks is gone at once.
|
||||
*/
|
||||
return function applySnapshot(snapshot, viewer, { replace = false } = {}) {
|
||||
// Before init (or after destroy) there is no icon set to draw into.
|
||||
if (!flightState._icons) return { count: 0, ids: new Set() };
|
||||
const currentIcaos = new Set();
|
||||
const receiptNowMs = snapshot.observedAtMs;
|
||||
records.beginSnapshot(snapshot.observedAtMs);
|
||||
// Field-test fix (RS46): coarse floor cells to warm for the below-ground
|
||||
// clamp — collected during the loop (low airborne contacts only),
|
||||
// batch-resolved once after it. Never a fetch inside the loop.
|
||||
@@ -70,9 +77,17 @@ export function createMilitarySnapshotRenderer({
|
||||
// Per-fix kinematics: the fix's own velocity/track ride along so the
|
||||
// extrapolation paths use the values that BELONG to the fix they
|
||||
// extend, not whatever the latest poll reported.
|
||||
history.push(
|
||||
motion._historyFix(fixEpochMs, position, meta.speedMps, meta.track),
|
||||
);
|
||||
history.push({
|
||||
...motion._historyFix(
|
||||
fixEpochMs,
|
||||
position,
|
||||
meta.speedMps,
|
||||
meta.track,
|
||||
),
|
||||
// Drawn at an invented height: a trail seeded from history keeps no
|
||||
// position for it.
|
||||
inventedHeight: meta.renderAltitudeInvented === true,
|
||||
});
|
||||
if (history.length > POSITION_HISTORY_LIMIT) {
|
||||
history.shift();
|
||||
}
|
||||
@@ -84,29 +99,39 @@ export function createMilitarySnapshotRenderer({
|
||||
// (owner): ground traffic appends too — taxi history stays live
|
||||
// after touchdown; _appendTrailFix floors grounded positions at
|
||||
// the surface so the ground leg drapes instead of diving.
|
||||
if (isTracked) tracking._appendTrailFix(motion._copyPosition(position));
|
||||
if (isTracked)
|
||||
tracking._appendTrailFix(motion._copyPosition(position), fixEpochMs, {
|
||||
nullAltitude: meta.renderAltitudeInvented === true,
|
||||
});
|
||||
} else {
|
||||
const modelOwnsGroundVisual = rendering._modelOwnsVisual(icao24);
|
||||
if (!modelOwnsGroundVisual) {
|
||||
liftRepeatedGroundFix(newest, position, meta.onGround);
|
||||
}
|
||||
// A forward synthetic fix follows the stale rules (none while the
|
||||
// contact holds at its report, a coast capped from the real report,
|
||||
// never below the ground) and is a motion aid, never a trail report.
|
||||
const kinematicsChanged =
|
||||
newest.velocity !== meta.speedMps || newest.track !== meta.track;
|
||||
if (kinematicsChanged) {
|
||||
const holds = staleHoldsForFix(newest, {
|
||||
onGround: meta.onGround,
|
||||
cachedGroundFloor,
|
||||
});
|
||||
if (kinematicsChanged && !holds) {
|
||||
const synthetic = synthesizeForwardKinematicsFix(newest, {
|
||||
epochMs: Date.now(),
|
||||
// Following the clock, the snapshot's time is the moment it moves on from.
|
||||
epochMs: followsClock(flightState)
|
||||
? snapshot.observedAtMs
|
||||
: Date.now(),
|
||||
velocity: meta.speedMps,
|
||||
track: meta.track,
|
||||
turnRateDps: meta.turnRateDps,
|
||||
cachedGroundFloor,
|
||||
});
|
||||
if (synthetic) {
|
||||
history.push(synthetic);
|
||||
if (history.length > POSITION_HISTORY_LIMIT) history.shift();
|
||||
meta.turnRateDps = turnRateFromFixHistory(history);
|
||||
if (isTracked)
|
||||
tracking._appendTrailFix(
|
||||
motion._copyPosition(synthetic.position),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -172,11 +197,15 @@ export function createMilitarySnapshotRenderer({
|
||||
if (!currentIcaos.has(icao24)) absentIds.push(icao24);
|
||||
}
|
||||
for (const icao24 of absentIds) {
|
||||
const absence = records.absence(icao24, {
|
||||
complete: snapshot.complete,
|
||||
retainIds: snapshot.retainIds,
|
||||
likelyLanded: queries._likelyLanded(icao24),
|
||||
});
|
||||
const absence = replace
|
||||
? 'remove'
|
||||
: records.absence(icao24, {
|
||||
complete: snapshot.complete,
|
||||
retainIds: snapshot.retainIds,
|
||||
likelyLanded: queries._likelyLanded(icao24),
|
||||
tracked: icao24 === flightState._trackedIcao,
|
||||
nowMs: flightState.now?.(),
|
||||
});
|
||||
if (absence === 'retain') continue;
|
||||
if (absence === 'stale') {
|
||||
icons._applyIconPresentation(icao24); // the faded freshness alpha
|
||||
@@ -203,6 +232,14 @@ export function createMilitarySnapshotRenderer({
|
||||
icons._forgetContact(icao24); // aged out: its 3D model goes too (no orphan / cap leak)
|
||||
}
|
||||
|
||||
// The tracked contact at the new time: its trail starts there.
|
||||
if (
|
||||
replace &&
|
||||
flightState._trackedIcao &&
|
||||
currentIcaos.has(flightState._trackedIcao)
|
||||
)
|
||||
tracking._startTrail(flightState._trackedIcao);
|
||||
|
||||
// Feed the shared registry so the flights layer can classify/suppress
|
||||
registerMilitaryIcaos(currentIcaos);
|
||||
|
||||
|
||||
@@ -60,6 +60,7 @@ function harness({ viewer = null, floor = null } = {}) {
|
||||
parts.motion = createMotion({ flightState, services, parts, layer: {} });
|
||||
let fix = null;
|
||||
const records = {
|
||||
beginSnapshot() {},
|
||||
receive(aircraft) {
|
||||
const meta = {
|
||||
rawLon: aircraft.lon,
|
||||
@@ -78,7 +79,7 @@ function harness({ viewer = null, floor = null } = {}) {
|
||||
const apply = createMilitarySnapshotRenderer({
|
||||
flightState,
|
||||
records,
|
||||
groundFloor: { warmGroundFloor() {} },
|
||||
groundFloor: { warmGroundFloor() {}, cachedGroundFloor: () => floor },
|
||||
militaryRegistry: { registerMilitaryIcaos() {} },
|
||||
rendering: parts.rendering,
|
||||
tracking: {},
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { createMilitarySnapshotRenderer } from './snapshotRenderer.js';
|
||||
import { createMotion } from './motion.js';
|
||||
import { createFlightState } from './state.js';
|
||||
|
||||
// A poll that repeats a contact's last position with new speed or course
|
||||
// must not move it past where the stale rules allow, and never adds a
|
||||
// report to the tracked trail.
|
||||
|
||||
const ICAO = '00a005';
|
||||
const SEC = 1000;
|
||||
|
||||
/** Any property is a no-op function unless given. */
|
||||
function stub(overrides = {}) {
|
||||
return new Proxy(overrides, {
|
||||
get: (target, key) => (key in target ? target[key] : () => undefined),
|
||||
});
|
||||
}
|
||||
|
||||
function harness({ ground = () => null }) {
|
||||
const appended = [];
|
||||
const history = [];
|
||||
const iconIds = new Set();
|
||||
const groundFloor = stub({
|
||||
cachedGroundFloor: ground,
|
||||
GROUND_FLOOR_LIFT_M: 0.5,
|
||||
});
|
||||
const services = stub({
|
||||
camera: stub(),
|
||||
focus: stub(),
|
||||
groundFloor,
|
||||
meshFloor: stub(),
|
||||
groundSnap: stub({ createGroundSnap: () => stub() }),
|
||||
});
|
||||
const flightState = createFlightState({
|
||||
services,
|
||||
source: { label: 'Fixture aircraft' },
|
||||
});
|
||||
// The shared icon set the layer draws its contacts into.
|
||||
flightState._icons = {
|
||||
has: (id) => iconIds.has(id),
|
||||
ids: () => [...iconIds],
|
||||
get count() {
|
||||
return iconIds.size;
|
||||
},
|
||||
};
|
||||
flightState._trackedIcao = ICAO;
|
||||
flightState._positionHistory.set(ICAO, history);
|
||||
const parts = {
|
||||
rendering: stub({
|
||||
_modelOwnsVisual: () => false,
|
||||
_groundSampleExclusions: () => ({ sets: [] }),
|
||||
}),
|
||||
icons: stub({
|
||||
_iconIds: () => [...iconIds],
|
||||
_addIcon: (id) => iconIds.add(id),
|
||||
_forgetContact: (id) => iconIds.delete(id),
|
||||
}),
|
||||
};
|
||||
parts.motion = createMotion({ flightState, services, parts, layer: {} });
|
||||
let meta = null;
|
||||
let fixEpochMs = 0;
|
||||
const records = stub({
|
||||
receive: () => {
|
||||
flightState.records.data.set(ICAO, meta);
|
||||
return { prevMeta: meta, meta, groundFlipped: false, fixEpochMs };
|
||||
},
|
||||
absence: () => 'retain',
|
||||
});
|
||||
const apply = createMilitarySnapshotRenderer({
|
||||
flightState,
|
||||
records,
|
||||
militaryRegistry: stub(),
|
||||
groundFloor,
|
||||
meshFloor: stub(),
|
||||
rendering: parts.rendering,
|
||||
tracking: stub({
|
||||
_militaryLayerSuppresses: () => false,
|
||||
_appendTrailFix: (position, epochMs) =>
|
||||
appended.push({ position, epochMs }),
|
||||
}),
|
||||
motion: parts.motion,
|
||||
icons: parts.icons,
|
||||
queries: stub({ _likelyLanded: () => false }),
|
||||
});
|
||||
return {
|
||||
history,
|
||||
appended,
|
||||
poll(nextMeta, epochMs) {
|
||||
meta = nextMeta;
|
||||
fixEpochMs = epochMs;
|
||||
apply({ records: [{ id: ICAO }], complete: true }, null);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const lightAircraft = (velocity, track) => ({
|
||||
rawLat: 38.1436,
|
||||
rawLon: -122.5561,
|
||||
renderAltitudeM: 10,
|
||||
altitudeFt: 130,
|
||||
speedMps: velocity,
|
||||
track,
|
||||
onGround: false,
|
||||
wasAirborne: true,
|
||||
klass: 'light',
|
||||
});
|
||||
|
||||
test('military: a low contact whose position repeats while its speed changes is not moved and adds nothing to the trail', (t) => {
|
||||
const t0 = Date.UTC(2026, 10, 9, 20, 0);
|
||||
t.mock.timers.enable({ apis: ['Date'], now: t0 });
|
||||
const h = harness({ ground: () => -30 });
|
||||
h.poll(lightAircraft(36.4, 63), t0);
|
||||
const first = h.history[0].position;
|
||||
for (const [i, velocity] of [30, 22, 14, 9].entries()) {
|
||||
t.mock.timers.tick(10 * SEC);
|
||||
h.poll(lightAircraft(velocity, 63 + i * 20), t0);
|
||||
}
|
||||
assert.equal(h.history.length, 1, 'a synthetic fix moved a holding contact');
|
||||
assert.equal(h.history[0].position, first);
|
||||
assert.equal(h.appended.length, 1, 'only the real report joins the trail');
|
||||
});
|
||||
|
||||
test('military: a cruising contact whose position repeats coasts no further than the stale cap, and the synthetic fix is not a report', (t) => {
|
||||
const t0 = Date.UTC(2026, 10, 9, 20, 0);
|
||||
t.mock.timers.enable({ apis: ['Date'], now: t0 });
|
||||
const h = harness({});
|
||||
const cruise = (velocity, track) => ({
|
||||
rawLat: 36,
|
||||
rawLon: -115,
|
||||
renderAltitudeM: 9_000,
|
||||
altitudeFt: 29_500,
|
||||
speedMps: velocity,
|
||||
track,
|
||||
onGround: false,
|
||||
wasAirborne: true,
|
||||
klass: 'jet',
|
||||
});
|
||||
h.poll(cruise(220, 90), t0);
|
||||
const report = h.history[0].position;
|
||||
t.mock.timers.tick(300 * SEC);
|
||||
h.poll(cruise(200, 100), t0);
|
||||
assert.equal(h.history.length, 2);
|
||||
const moved = Cesium.Cartesian3.distance(report, h.history[1].position);
|
||||
assert.ok(
|
||||
moved <= 220 * 300 + 1,
|
||||
`the synthetic fix coasted ${moved.toFixed(0)} m`,
|
||||
);
|
||||
assert.equal(h.appended.length, 1, 'the synthetic fix joined the trail');
|
||||
});
|
||||
|
||||
test('military: a report drawn at an invented height says so on its history fix', (t) => {
|
||||
const t0 = Date.UTC(2026, 10, 9, 20, 0);
|
||||
t.mock.timers.enable({ apis: ['Date'], now: t0 });
|
||||
const h = harness({});
|
||||
h.poll({ ...lightAircraft(60, 90), renderAltitudeInvented: true }, t0);
|
||||
h.poll({ ...lightAircraft(60, 90), rawLon: -122.55 }, t0 + 10 * SEC);
|
||||
assert.equal(h.history[0].inventedHeight, true);
|
||||
assert.equal(h.history[1].inventedHeight, false);
|
||||
});
|
||||
|
||||
test('military: with the ground unknown, a low barometric altitude alone does not hold a contact', (t) => {
|
||||
const t0 = Date.UTC(2026, 10, 9, 20, 0);
|
||||
t.mock.timers.enable({ apis: ['Date'], now: t0 });
|
||||
const h = harness({});
|
||||
h.poll(lightAircraft(36.4, 63), t0);
|
||||
t.mock.timers.tick(10 * SEC);
|
||||
h.poll(lightAircraft(30, 80), t0);
|
||||
assert.equal(h.history.length, 2);
|
||||
assert.equal(h.history[0].staleHolds, false);
|
||||
assert.equal(h.appended.length, 1);
|
||||
});
|
||||
@@ -0,0 +1,196 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { createMotion } from './motion.js';
|
||||
import { createFlightState } from './state.js';
|
||||
import { createTracking } from './tracking.js';
|
||||
import { TRAIL_CONTINUITY_MAX_SPEED_KT } from '../../data/trailContinuity.js';
|
||||
import { RENDER_DELAY_SEC } from './policy.js';
|
||||
|
||||
const SEC = 1000;
|
||||
|
||||
function motionFixture({ info, fixes, nowMs, ground = () => null }) {
|
||||
const flightState = {
|
||||
records: { data: new Map([['00a003', info]]) },
|
||||
_positionHistory: new Map([['00a003', fixes]]),
|
||||
_scratchArc: {},
|
||||
_scratchOffset: new Cesium.Cartesian3(),
|
||||
_scratchEnu: new Cesium.Matrix4(),
|
||||
_scratchRenderTime: new Cesium.JulianDate(),
|
||||
now: () => nowMs,
|
||||
};
|
||||
const motion = createMotion({
|
||||
flightState,
|
||||
services: {
|
||||
groundFloor: { cachedGroundFloor: ground },
|
||||
camera: {},
|
||||
focus: {},
|
||||
},
|
||||
parts: {},
|
||||
});
|
||||
return motion;
|
||||
}
|
||||
|
||||
function fix(timeMs, lat, lon, heightM, velocity, track) {
|
||||
return {
|
||||
time: Cesium.JulianDate.fromDate(new Date(timeMs)),
|
||||
epochMs: timeMs,
|
||||
position: Cesium.Cartesian3.fromDegrees(lon, lat, heightM),
|
||||
velocity,
|
||||
track,
|
||||
};
|
||||
}
|
||||
|
||||
test('a military contact stale after a low approach holds at its last report', () => {
|
||||
const t0 = Date.UTC(2026, 10, 9, 20, 0);
|
||||
const ground = 1_590; // An airbase, ellipsoidal.
|
||||
const fixes = [
|
||||
fix(t0, 35.03, -106.58, ground + 300, 75, 260),
|
||||
fix(t0 + 10 * SEC, 35.03, -106.588, ground + 40, 70, 260),
|
||||
];
|
||||
const info = {
|
||||
altitudeFt: 5_350,
|
||||
renderAltitudeM: ground + 40,
|
||||
rawLat: 35.03,
|
||||
rawLon: -106.588,
|
||||
speedMps: 70,
|
||||
track: 260,
|
||||
onGround: false,
|
||||
};
|
||||
for (const afterSec of [10, 60, 200]) {
|
||||
const motion = motionFixture({
|
||||
info,
|
||||
fixes,
|
||||
nowMs: t0 + 10 * SEC + RENDER_DELAY_SEC * SEC + afterSec * SEC,
|
||||
ground: () => ground,
|
||||
});
|
||||
const drawn = motion._deadReckon('00a003', new Cesium.Cartesian3());
|
||||
assert.ok(Cesium.Cartesian3.distance(drawn, fixes[1].position) < 0.01);
|
||||
}
|
||||
});
|
||||
|
||||
test('a cruising military contact still heard after its last position coasts past 90 s, for up to 5 minutes, then stops', () => {
|
||||
const t0 = Date.UTC(2026, 10, 9, 20, 0);
|
||||
const fixes = [
|
||||
fix(t0, 36, -115, 9_000, 220, 90),
|
||||
fix(t0 + 10 * SEC, 36, -114.975, 9_000, 220, 90),
|
||||
];
|
||||
const info = {
|
||||
altitudeFt: 29_500,
|
||||
renderAltitudeM: 9_000,
|
||||
rawLat: 36,
|
||||
rawLon: -114.975,
|
||||
speedMps: 220,
|
||||
track: 90,
|
||||
onGround: false,
|
||||
lastContactEpochMs: t0 + 10 * SEC + 300 * SEC,
|
||||
};
|
||||
const at = (afterSec) =>
|
||||
motionFixture({
|
||||
info,
|
||||
fixes,
|
||||
nowMs: t0 + 10 * SEC + RENDER_DELAY_SEC * SEC + afterSec * SEC,
|
||||
})._deadReckon('00a003', new Cesium.Cartesian3());
|
||||
const d = (p) => Cesium.Cartesian3.distance(p, fixes[1].position);
|
||||
const near = (got, want) => Math.abs(got - want) < want * 0.005 + 50;
|
||||
assert.ok(near(d(at(45)), 220 * 45));
|
||||
assert.ok(near(d(at(250)), 220 * 250), 'still moving at 250 s');
|
||||
assert.ok(near(d(at(400)), 220 * 300), 'stopped at 300 s');
|
||||
});
|
||||
|
||||
test('a bad military speed coasts no faster than the 1,500 kt continuity limit', () => {
|
||||
const t0 = Date.UTC(2026, 10, 9, 20, 0);
|
||||
const fixes = [
|
||||
fix(t0, 36, -115, 9_000, 2_000, 90),
|
||||
fix(t0 + 10 * SEC, 36, -114.975, 9_000, 2_000, 90),
|
||||
];
|
||||
const info = {
|
||||
altitudeFt: 29_500,
|
||||
renderAltitudeM: 9_000,
|
||||
rawLat: 36,
|
||||
rawLon: -114.975,
|
||||
speedMps: 2_000,
|
||||
track: 90,
|
||||
onGround: false,
|
||||
};
|
||||
const drawn = motionFixture({
|
||||
info,
|
||||
fixes,
|
||||
nowMs: t0 + 10 * SEC + RENDER_DELAY_SEC * SEC + 300 * SEC,
|
||||
})._deadReckon('00a003', new Cesium.Cartesian3());
|
||||
const limitMps = (TRAIL_CONTINUITY_MAX_SPEED_KT * 1852) / 3600;
|
||||
const d = Cesium.Cartesian3.distance(drawn, fixes[1].position);
|
||||
assert.ok(Math.abs(d - limitMps * 300) < 1_500, `${d.toFixed(0)} m`);
|
||||
});
|
||||
|
||||
test('a holding military contact draws no head and its trail ends at the last report', () => {
|
||||
const t0 = Date.UTC(2026, 10, 9, 20, 0);
|
||||
const fixes = [0, 1, 2].map((i) =>
|
||||
fix(t0 + i * 10 * SEC, 35.03, -106.57 - i * 0.008, 1_700, 70, 260),
|
||||
);
|
||||
const svc = {
|
||||
...Object.fromEntries(
|
||||
[
|
||||
'picking',
|
||||
'sprites',
|
||||
'aircraftPresentation',
|
||||
'camera',
|
||||
'militaryRegistry',
|
||||
'labels',
|
||||
'meshFloor',
|
||||
'focus',
|
||||
'readout',
|
||||
'context',
|
||||
'render',
|
||||
'recession',
|
||||
].map((name) => [name, {}]),
|
||||
),
|
||||
groundSnap: { createGroundSnap: () => ({ clear() {} }) },
|
||||
geoid: { ensureGeoidReady: async () => {}, geoidHeight: () => 0 },
|
||||
groundFloor: {
|
||||
resolveGroundFloorCellsBounded: async () => {},
|
||||
cachedGroundFloor: () => null,
|
||||
floorAltitudeM: (alt) => alt,
|
||||
},
|
||||
};
|
||||
const calls = [];
|
||||
svc.trails = {
|
||||
createTrail: () => ({
|
||||
setSegments: (segments) => calls.push(segments.flat()),
|
||||
setPositions: (positions) => calls.push(positions.slice()),
|
||||
setVisible() {},
|
||||
clear() {},
|
||||
destroy() {},
|
||||
}),
|
||||
};
|
||||
const flightState = createFlightState({ services: svc, source: {} });
|
||||
const added = [];
|
||||
flightState._viewer = {
|
||||
isDestroyed: () => false,
|
||||
entities: {
|
||||
add: (definition) => (added.push(definition), definition),
|
||||
remove() {},
|
||||
},
|
||||
};
|
||||
flightState._trackedIcao = '00a003';
|
||||
flightState.now = () => t0 + 20 * SEC + RENDER_DELAY_SEC * SEC + 120 * SEC;
|
||||
flightState._positionHistory.set('00a003', fixes);
|
||||
const last = Cesium.Cartesian3.clone(fixes[2].position);
|
||||
const tracking = createTracking({
|
||||
flightState,
|
||||
services: svc,
|
||||
parts: {
|
||||
motion: {
|
||||
_isTrackWarmingUp: () => false,
|
||||
_trackedTrailCached: () => last,
|
||||
_trackedDisplayPosition: () => last,
|
||||
_trackedModelCenterWorld: () => null,
|
||||
_trackedModelEnvelopeM: () => null,
|
||||
},
|
||||
},
|
||||
layer: {},
|
||||
});
|
||||
tracking._startTrail('00a003');
|
||||
assert.equal(calls.at(-1).length, 3);
|
||||
assert.deepEqual(tracking._trailHeadPositions(), []);
|
||||
});
|
||||
@@ -9,9 +9,13 @@ export function createFlightState({ source, services }) {
|
||||
flightState.records = new MilitaryFlightRecords({
|
||||
...services.geoid,
|
||||
...services.groundFloor,
|
||||
now: () => flightState.now(),
|
||||
});
|
||||
/** The time contacts are drawn behind by the render delay, in epoch ms. */
|
||||
flightState.now = worldTimeFor('military');
|
||||
/** Follows the world clock while the source declares a timeline (set by the
|
||||
* layer); see followsClock and displayDelayMs in policy.js. */
|
||||
flightState.timeline = null;
|
||||
|
||||
/** Per-class model spec for THIS layer (2026-08-16, owner playtest ask:
|
||||
* military contacts should read as their WEIGHT CLASS, always in this layer's
|
||||
@@ -130,9 +134,32 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._trailHeadOff = null;
|
||||
|
||||
/** @type {{x: number, y: number, z: number}[]} Chronological tracked-aircraft fixes (oldest first) */
|
||||
/** @type {{position: {x: number, y: number, z: number}|null, timeMs: number, nullAltitude: boolean, breakBefore: boolean, drawn?: boolean}[]}
|
||||
* Chronological tracked-aircraft trail (oldest first): reports, and
|
||||
* (`drawn`) where the icon was drawn between them; `breakBefore` starts a
|
||||
* new segment. */
|
||||
|
||||
flightState._trailPositions = [];
|
||||
flightState._trailFixes = [];
|
||||
|
||||
/** @type {number} Body fixes drawn: those at or before the display time. */
|
||||
|
||||
flightState._trailBodyCount = 0;
|
||||
|
||||
/** @type {{x: number, y: number, z: number}|null} Where the tracked icon was last recorded into the trail. */
|
||||
|
||||
flightState._trailRecordPosition = null;
|
||||
|
||||
/** @type {number} Display time (epoch ms) of that recording. */
|
||||
|
||||
flightState._trailRecordMs = -Infinity;
|
||||
|
||||
/** @type {string|undefined} The stale cue last written into the tracked label (see `_staleCueTick`). */
|
||||
|
||||
flightState._trackedStaleCueText = undefined;
|
||||
|
||||
/** @type {{key: string, cue: {text: string, dimmed: boolean}}|null} This frame's tracked stale cue (see `_trackedStaleCue`). */
|
||||
|
||||
flightState._trackedStaleCueCache = null;
|
||||
|
||||
/** @type {number} Monotonic token — invalidates in-flight backfill responses */
|
||||
|
||||
@@ -244,6 +271,9 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._drPrevMs = 0;
|
||||
|
||||
/** World time of that frame: the wall clock live, the cursor following the clock. */
|
||||
flightState._drPrevWorldMs = 0;
|
||||
|
||||
flightState._drReconcileValid = false;
|
||||
|
||||
/** @type {string|null} icao the reconciliation state currently belongs to */
|
||||
|
||||
+299
-111
@@ -4,7 +4,8 @@ import {
|
||||
onFollowChanged,
|
||||
stopFollowing,
|
||||
} from '../../data/followed.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
import { formatNumber, t } from '../../i18n/index.js';
|
||||
import { unitLabel } from '../../ui/unitLabels.js';
|
||||
import { nextCockpitNearContacts } from '../../data/cockpitAirLod.js';
|
||||
import { aircraftIcon, TRACKED_ICON_PX } from '../../data/aircraftIcons.js';
|
||||
import { trackedModelZoomActive } from '../../data/trackedModelRegime.js';
|
||||
@@ -18,13 +19,9 @@ import {
|
||||
trackedContactHolder,
|
||||
} from '../../data/trackedAircraftIcon.js';
|
||||
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
|
||||
import {
|
||||
addSeconds,
|
||||
julianLessThanOrEquals,
|
||||
julianFromEpochMs,
|
||||
julianToEpochMs,
|
||||
} from '../../geo/julian.js';
|
||||
import { clone, distanceSquared, vec } from '../../geo/vector.js';
|
||||
import { julianToEpochMs } from '../../geo/julian.js';
|
||||
import { renderedFrames } from '../../data/renderedFrames.js';
|
||||
import { clone, distance, distanceSquared, vec } from '../../geo/vector.js';
|
||||
import { trailHeadStart } from '../../data/modelVisualAnchor.js';
|
||||
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
|
||||
import {
|
||||
@@ -34,13 +31,31 @@ import {
|
||||
import { inputFor } from '../../input/dispatcher.js';
|
||||
import {
|
||||
TRAIL_MAX_POINTS,
|
||||
RENDER_DELAY_SEC,
|
||||
DR_CORRECTION_MS,
|
||||
displayDelayMs,
|
||||
followsClock,
|
||||
STALE_ALPHA,
|
||||
TRAIL_COLOR,
|
||||
BILLBOARD_SCALE,
|
||||
AMBER_TRANSPARENT,
|
||||
TRACKED_ICON_COLOR,
|
||||
TRACKED_BILLBOARD_SCALE_BY_DISTANCE,
|
||||
} from './policy.js';
|
||||
import {
|
||||
drawTrailSegments,
|
||||
historyFixEpochMs,
|
||||
insertTrailFix,
|
||||
joinTrailBackfill,
|
||||
recordTrailPoint,
|
||||
trailBackfillFixes,
|
||||
trailBodyCount,
|
||||
trailBodyCountOutsideModel,
|
||||
trailBodySegments,
|
||||
trailHeadStartFix,
|
||||
trailRecordingBlocked,
|
||||
TRAIL_RECORD_STEP_M,
|
||||
TRAIL_RECORD_STEP_MS,
|
||||
} from '../../data/trailContinuity.js';
|
||||
import { roundHeadingDegrees } from '../../data/headingDegrees.js';
|
||||
import { entityRecord } from '../../data/entityRecords.js';
|
||||
|
||||
@@ -55,6 +70,11 @@ function aircraftPickId(hit) {
|
||||
return isOtherTrackedIconSet(hit.set, 'military') ? undefined : hit.id;
|
||||
}
|
||||
|
||||
const STALE_TRACKED_COLOR = Object.freeze([
|
||||
...TRACKED_ICON_COLOR.slice(0, 3),
|
||||
STALE_ALPHA,
|
||||
]);
|
||||
|
||||
export function createTracking({
|
||||
flightState,
|
||||
services,
|
||||
@@ -243,24 +263,97 @@ export function createTracking({
|
||||
_setCockpitContactMode(active);
|
||||
}
|
||||
|
||||
/**
|
||||
* The tracked plane's stale cue and whether it is drawn with the stale fade.
|
||||
* - SIGNAL LOST · <time since its last report>, dimmed: its coast has ended
|
||||
* (or it holds at its last report after a missed update) and no newer
|
||||
* report has come.
|
||||
* - STALE, dimmed: it has missed an update and still coasts, or the whole
|
||||
* feed is backing off.
|
||||
* @param {string} icao24
|
||||
* @returns {{text: string, dimmed: boolean}}
|
||||
*/
|
||||
|
||||
function _trackedStaleCue(icao24) {
|
||||
const records = flightState.records;
|
||||
const misses = records.missingPolls.get(icao24) || 0;
|
||||
const repeated = records.fixRepeated?.has(icao24) === true;
|
||||
const backoff = flightState.feed._backoff === true;
|
||||
// Computed once per frame for the label, the icon colour and the model
|
||||
// fade; a poll between frames changes the key.
|
||||
const frame = renderedFrames(flightState._viewer);
|
||||
const key =
|
||||
frame >= 0 ? `${frame}|${icao24}|${misses}|${repeated}|${backoff}` : null;
|
||||
const cached = flightState._trackedStaleCueCache;
|
||||
if (key !== null && cached?.key === key) return cached.cue;
|
||||
const cue = _computeTrackedStaleCue(
|
||||
icao24,
|
||||
misses > 0 || repeated,
|
||||
backoff,
|
||||
);
|
||||
flightState._trackedStaleCueCache = key === null ? null : { key, cue };
|
||||
return cue;
|
||||
}
|
||||
|
||||
/** `_trackedStaleCue` without the per-frame cache. A repeated fix counts as missed. */
|
||||
|
||||
function _computeTrackedStaleCue(icao24, missed, backoff) {
|
||||
const lost = parts.motion._signalLost(icao24);
|
||||
if (lost && (missed || !lost.holds)) {
|
||||
const sec = Math.max(
|
||||
0,
|
||||
Math.floor((flightState.now() - lost.reportEpochMs) / 1000),
|
||||
);
|
||||
const time =
|
||||
sec < 60
|
||||
? `${formatNumber(sec, { useGrouping: false })} ${unitLabel('s')}`
|
||||
: `${formatNumber(Math.floor(sec / 60), { useGrouping: false })} ${unitLabel('min')}`;
|
||||
return { text: t('SIGNAL LOST · {time}', { time }), dimmed: true };
|
||||
}
|
||||
// A missed update or a stalled feed: no newer position is coming in.
|
||||
if (missed || backoff) return { text: t('STALE'), dimmed: true };
|
||||
return { text: '', dimmed: false };
|
||||
}
|
||||
|
||||
/** The tracked billboard's colour: amber, faded while stale, clear while the 3D model is the visual. */
|
||||
|
||||
function _trackedIconColor() {
|
||||
if (parts.rendering._modelOwnsVisual(flightState._trackedIcao))
|
||||
return AMBER_TRANSPARENT;
|
||||
return _trackedStaleCue(flightState._trackedIcao).dimmed
|
||||
? STALE_TRACKED_COLOR
|
||||
: TRACKED_ICON_COLOR;
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-word the tracked label when its stale cue changes (STALE, SIGNAL LOST,
|
||||
* each new second or minute of it). Run from the layer's per-frame pass.
|
||||
*/
|
||||
|
||||
function _staleCueTick() {
|
||||
const icao24 = flightState._trackedIcao;
|
||||
if (!icao24 || !flightState._trackedEntity) return;
|
||||
const text = _trackedStaleCue(icao24).text;
|
||||
if (text === flightState._trackedStaleCueText) return;
|
||||
flightState._trackedStaleCueText = text;
|
||||
_updateTrackedLabelModel(icao24);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the multi-line presentation text for the protected tracked host card.
|
||||
* Lines: callsign, type/registration, operator/altitude.
|
||||
* While the plane is in its missed-poll grace (coasting on dead reckoning
|
||||
* with sticky metadata) the first line carries a "· STALE" cue — the fleet's
|
||||
* 45%-alpha billboard fade doesn't apply to the tracked plane (its entity
|
||||
* owns the visual), so without this the readout would present last-known
|
||||
* altitude/speed as live.
|
||||
* The first line carries the stale cue (`_trackedStaleCue`): STALE while
|
||||
* the plane coasts on dead reckoning after a missed update, SIGNAL LOST
|
||||
* once the coast has ended, so last-known altitude/speed are never
|
||||
* presented as live.
|
||||
* @param {Object|null} info - Flight metadata from _flightData
|
||||
* @param {string} icao24 - ICAO hex identifier (fallback display name)
|
||||
* @returns {string} Newline-separated label text
|
||||
*/
|
||||
|
||||
function _buildTrackedLabel(info, icao24) {
|
||||
const stale =
|
||||
flightState.records.missingPolls.get(icao24) || flightState.feed._backoff
|
||||
? ` · ${t('STALE')}`
|
||||
: '';
|
||||
const cue = _trackedStaleCue(icao24).text;
|
||||
const stale = cue ? ` · ${cue}` : '';
|
||||
const callsign =
|
||||
(parts.queries._toCleanText(info?.callsign) ||
|
||||
parts.queries._toCleanText(info?.registration) ||
|
||||
@@ -464,33 +557,109 @@ export function createTracking({
|
||||
}
|
||||
|
||||
/**
|
||||
* Append one fix to the tracked aircraft's trail accumulation and refresh
|
||||
* the rendered trail. Caller passes an owned (cloned) Cartesian3.
|
||||
* @param {{x: number, y: number, z: number}} position - New ECEF fix, appended at the head.
|
||||
* Put one report into the tracked aircraft's trail, in time order, and
|
||||
* refresh the rendered trail. Caller passes an owned (cloned) position. A
|
||||
* report that breaks from its neighbour starts a new segment (see
|
||||
* trailContinuity).
|
||||
* @param {{x: number, y: number, z: number}} position - The report's ECEF position.
|
||||
* @param {number} [epochMs] - The report's time; defaults to the tracked
|
||||
* aircraft's newest position-history fix, which every caller has just pushed.
|
||||
* @param {{nullAltitude?: boolean}} [options] - `nullAltitude`: the report
|
||||
* had no altitude, so its position is not kept and the line breaks there.
|
||||
* A report for a time the display has already passed replaces what was
|
||||
* drawn after it (see `insertTrailFix`).
|
||||
*/
|
||||
|
||||
function _appendTrailFix(position) {
|
||||
flightState._trailPositions.push(_trailFloorPosition(position));
|
||||
if (flightState._trailPositions.length > TRAIL_MAX_POINTS)
|
||||
flightState._trailPositions.shift();
|
||||
function _appendTrailFix(position, epochMs, { nullAltitude = false } = {}) {
|
||||
const history = flightState._positionHistory.get(flightState._trackedIcao);
|
||||
const timeMs = Number.isFinite(epochMs)
|
||||
? epochMs
|
||||
: historyFixEpochMs(history?.[history.length - 1]);
|
||||
insertTrailFix(
|
||||
flightState._trailFixes,
|
||||
_trailFloorPosition(position),
|
||||
timeMs,
|
||||
TRAIL_MAX_POINTS,
|
||||
{
|
||||
nullAltitude,
|
||||
displayMs: flightState.now() - displayDelayMs(flightState),
|
||||
settleMs: DR_CORRECTION_MS,
|
||||
},
|
||||
);
|
||||
_refreshTrailDisplay();
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the trail BODY — the accumulated fixes EXCLUDING the newest raw one. That
|
||||
* newest fix is at ~now, ~one poll interval AHEAD of the delayed icon (rendered at
|
||||
* now − RENDER_DELAY_SEC), so drawing it would push the trail in FRONT of the plane.
|
||||
* The cheap per-frame trail head segment bridges the last body point to the
|
||||
* delayed dead-reckoned head, so this primitive only rebuilds on a real fix (poll
|
||||
* cadence), never at motion cadence.
|
||||
* Per-frame trail work, run before each frame draws whether or not the
|
||||
* head is visible: record where the tracked icon is drawn (at most once a
|
||||
* second or every 150 m, floored like the head) and move the body on as
|
||||
* the display time passes reports. The head only reads the result.
|
||||
*/
|
||||
|
||||
function _trailTick() {
|
||||
if (!flightState._trackedIcao || !flightState._trail) return;
|
||||
const displayMs = flightState.now() - displayDelayMs(flightState);
|
||||
let changed = false;
|
||||
if (
|
||||
flightState._trailFixes.length &&
|
||||
!parts.motion._isTrackWarmingUp() &&
|
||||
!trailRecordingBlocked(flightState._trailFixes, displayMs)
|
||||
) {
|
||||
const drawn = parts.motion._trackedDisplayPosition(
|
||||
flightState._trackedIcao,
|
||||
);
|
||||
const last = flightState._trailRecordPosition;
|
||||
if (
|
||||
drawn &&
|
||||
(!last ||
|
||||
displayMs - flightState._trailRecordMs >= TRAIL_RECORD_STEP_MS ||
|
||||
distance(last, drawn) >= TRAIL_RECORD_STEP_M)
|
||||
) {
|
||||
flightState._trailRecordMs = displayMs;
|
||||
flightState._trailRecordPosition = clone(drawn);
|
||||
changed = recordTrailPoint(
|
||||
flightState._trailFixes,
|
||||
_trailFloorPosition(clone(drawn)),
|
||||
displayMs,
|
||||
TRAIL_MAX_POINTS,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (changed || _trailBodyCountNow() !== flightState._trailBodyCount)
|
||||
_refreshTrailDisplay();
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the trail BODY — the accumulated fixes at or before the delayed display
|
||||
* time (now − RENDER_DELAY_SEC). Newer fixes are AHEAD of the icon, so drawing them
|
||||
* would push the trail in FRONT of the plane. The cheap per-frame trail head line
|
||||
* bridges the last body point to the delayed dead-reckoned head, so the body
|
||||
* rebuilds only on a real fix or when the display time passes one, never at motion
|
||||
* cadence. A break lifts the pen: each segment is its own line, nothing between
|
||||
* them.
|
||||
*/
|
||||
|
||||
function _refreshTrailDisplay() {
|
||||
if (!flightState._trail) return;
|
||||
flightState._trail.setPositions(
|
||||
flightState._trailPositions.length > 1
|
||||
? flightState._trailPositions.slice(0, -1)
|
||||
: flightState._trailPositions,
|
||||
flightState._trailBodyCount = _trailBodyCountNow();
|
||||
drawTrailSegments(
|
||||
flightState._trail,
|
||||
trailBodySegments(flightState._trailFixes, flightState._trailBodyCount),
|
||||
);
|
||||
}
|
||||
|
||||
/** Fixes at or before the time the aircraft is drawn (now − RENDER_DELAY_SEC),
|
||||
* less the newest recorded points inside its 3D model. */
|
||||
|
||||
function _trailBodyCountNow() {
|
||||
return trailBodyCountOutsideModel(
|
||||
flightState._trailFixes,
|
||||
trailBodyCount(
|
||||
flightState._trailFixes,
|
||||
flightState.now() - displayDelayMs(flightState),
|
||||
),
|
||||
parts.motion._trackedModelCenterWorld(),
|
||||
parts.motion._trackedModelEnvelopeM(),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -500,14 +669,13 @@ export function createTracking({
|
||||
* @returns {Array<{x: number, y: number, z: number}>}
|
||||
*/
|
||||
function _trailHeadPositions() {
|
||||
// Need ≥2 accumulated points: the body draws all-but-newest, so the head must
|
||||
// start at the last DISPLAYED body point (index n−2). With a single fix that
|
||||
// point would be the sole raw fix — ~now, AHEAD of the delayed icon — so the
|
||||
// segment would draw IN FRONT of the plane. Likewise during warm-up the icon
|
||||
// predates all real history, so there is no valid body point behind it.
|
||||
// The head starts at the last DISPLAYED body point, the newest fix at or
|
||||
// before the delayed display time; a fix ahead of the icon would draw the
|
||||
// segment IN FRONT of the plane. During warm-up the icon predates all real
|
||||
// history, so there is no valid body point behind it.
|
||||
if (
|
||||
!flightState._trackedIcao ||
|
||||
flightState._trailPositions.length < 2 ||
|
||||
!flightState._trailFixes.length ||
|
||||
parts.motion._isTrackWarmingUp()
|
||||
)
|
||||
return [];
|
||||
@@ -515,10 +683,18 @@ export function createTracking({
|
||||
parts.motion._trackedTrailCached() ||
|
||||
parts.motion._trackedDisplayPosition(flightState._trackedIcao);
|
||||
if (!head) return [];
|
||||
// body[n−2] (last displayed body point) → delayed head: runs FORWARD, never a
|
||||
// backward/reversing segment.
|
||||
const start =
|
||||
flightState._trailPositions[flightState._trailPositions.length - 2];
|
||||
// The last body point (a report, or where the icon was drawn a moment
|
||||
// ago) → the icon. No head across a break: a body point more than 150 km
|
||||
// away, or too long ago or too far to be one path, stays detached; none
|
||||
// while the aircraft holds at its last point.
|
||||
const last = trailHeadStartFix(
|
||||
flightState._trailFixes,
|
||||
head,
|
||||
flightState.now(),
|
||||
flightState._trailBodyCount,
|
||||
);
|
||||
if (!last) return [];
|
||||
const start = last.position;
|
||||
// Floor the head too (round 2): a grounded tracked contact's DR
|
||||
// display height is the pre-datum default — without this the last
|
||||
// segment dives underground while taxiing.
|
||||
@@ -541,8 +717,10 @@ export function createTracking({
|
||||
return [from, end];
|
||||
}
|
||||
|
||||
/** Each drawn frame, before it draws: the live head where the aircraft is now. */
|
||||
/** Each drawn frame, before it draws: the trail moved on, then the live
|
||||
* head where the aircraft is now. */
|
||||
function _drawTrailHead() {
|
||||
_trailTick();
|
||||
flightState._trail?.setHead(_trailHeadPositions());
|
||||
}
|
||||
|
||||
@@ -555,25 +733,27 @@ export function createTracking({
|
||||
|
||||
function _startTrail(icao24) {
|
||||
flightState._trailBackfillToken += 1;
|
||||
flightState._trailPositions = [];
|
||||
flightState._trailFixes = [];
|
||||
flightState._trailRecordPosition = null;
|
||||
flightState._trailRecordMs = -Infinity;
|
||||
const history = flightState._positionHistory.get(icao24) || [];
|
||||
// Seed only fixes at/behind the DELAYED display time (now − RENDER_DELAY_SEC). The
|
||||
// newest ~RENDER_DELAY_SEC of fixes are AHEAD of the displayed icon; including them
|
||||
// would draw the trail in front of the plane. They join via _appendTrailFix as they age.
|
||||
const seedRenderTime = addSeconds(
|
||||
julianFromEpochMs(flightState.now()),
|
||||
-RENDER_DELAY_SEC,
|
||||
flightState._scratchWarmupTime,
|
||||
);
|
||||
// Seed every report. The body only draws those at or before the delayed
|
||||
// display time (now − RENDER_DELAY_SEC); newer ones join it as the display
|
||||
// passes them. A synthetic forward fix (it carries `reportEpochMs`) is a
|
||||
// motion aid, never a report. A report drawn at an invented height keeps
|
||||
// no position and breaks the line.
|
||||
for (const fix of history) {
|
||||
if (julianLessThanOrEquals(fix.time, seedRenderTime)) {
|
||||
// Floor grounded-history seeds (round 2): a grounded contact's stored
|
||||
// fixes carry the pre-datum default height — the trail copy sits on
|
||||
// the surface instead (pure lift; airborne fixes pass through).
|
||||
flightState._trailPositions.push(
|
||||
_trailFloorPosition(clone(fix.position)),
|
||||
);
|
||||
}
|
||||
if (Number.isFinite(fix.reportEpochMs)) continue;
|
||||
// Floor grounded-history seeds (round 2): a grounded contact's stored
|
||||
// fixes carry the pre-datum default height — the trail copy sits on
|
||||
// the surface instead (pure lift; airborne fixes pass through).
|
||||
insertTrailFix(
|
||||
flightState._trailFixes,
|
||||
_trailFloorPosition(clone(fix.position)),
|
||||
historyFixEpochMs(fix),
|
||||
TRAIL_MAX_POINTS,
|
||||
{ nullAltitude: fix.inventedHeight === true },
|
||||
);
|
||||
}
|
||||
if (!flightState._trail && flightState._viewer) {
|
||||
flightState._trail = createTrail(flightState._viewer, {
|
||||
@@ -599,10 +779,10 @@ export function createTracking({
|
||||
}
|
||||
|
||||
/**
|
||||
* Fire-and-forget optional source history backfill (PRD F2). Trace points are
|
||||
* stride-thinned to the remaining vertex budget, then spliced strictly older
|
||||
* than the oldest seeded fix AHEAD of the locally accumulated fine segment,
|
||||
* capped at TRAIL_MAX_POINTS (newest kept). Any failure (404/timeout/
|
||||
* Fire-and-forget optional source history backfill (PRD F2). Every trace
|
||||
* point strictly older than the oldest seeded fix is spliced AHEAD of the
|
||||
* locally accumulated fine segment, each leg its own segment, capped at
|
||||
* TRAIL_MAX_POINTS (newest kept). Any failure (404/timeout/
|
||||
* malformed) silently keeps the local-only trail.
|
||||
* @param {string} icao24 - ICAO hex identifier being tracked.
|
||||
* @param {number} token - Backfill token captured at request time.
|
||||
@@ -612,15 +792,16 @@ export function createTracking({
|
||||
|
||||
async function _backfillTrail(icao24, token, oldestFixEpochSec) {
|
||||
let trace = null;
|
||||
// Following the world clock, the track ends at the world's time.
|
||||
const atMs = followsClock(flightState) ? flightState.now() : undefined;
|
||||
try {
|
||||
const signal = AbortSignal.any([
|
||||
flightState.lifetime.signal,
|
||||
AbortSignal.timeout(8000),
|
||||
]);
|
||||
const track = await flightState.feed._source.getTrack?.(
|
||||
flightState.records.data.get(icao24)?.sourceReference ?? icao24,
|
||||
{
|
||||
signal: AbortSignal.any([
|
||||
flightState.lifetime.signal,
|
||||
AbortSignal.timeout(8000),
|
||||
]),
|
||||
},
|
||||
atMs === undefined ? { signal } : { signal, atMs },
|
||||
);
|
||||
trace = track?.records ?? null;
|
||||
} catch {
|
||||
@@ -648,7 +829,14 @@ export function createTracking({
|
||||
lon = point.longitude;
|
||||
if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue;
|
||||
if (!Number.isFinite(t) || t >= oldestFixEpochSec) continue;
|
||||
parsed.push({ lat, lon, baroAltitudeM: point.baroAltitudeM });
|
||||
if (atMs !== undefined && !(point.observedAtMs <= atMs)) continue;
|
||||
parsed.push({
|
||||
lat,
|
||||
lon,
|
||||
baroAltitudeM: point.baroAltitudeM,
|
||||
onGround: point.onGround === true,
|
||||
timeMs: point.observedAtMs,
|
||||
});
|
||||
}
|
||||
if (!parsed.length) return;
|
||||
|
||||
@@ -671,39 +859,33 @@ export function createTracking({
|
||||
)
|
||||
return;
|
||||
|
||||
let older = [];
|
||||
let lastAltM = null; // carry-forward for ground points whose cell isn't warm yet
|
||||
for (const { lat, lon, baroAltitudeM } of parsed) {
|
||||
const baroM =
|
||||
baroAltitudeM == null ? null : baroAltitudeM + geoidHeight(lat, lon);
|
||||
let altM = floorAltitudeM(baroM, cachedGroundFloor(lat, lon));
|
||||
// Ground/no-alt point with an unresolved floor: hold the previous
|
||||
// waypoint's altitude (continuity — never a dive to a made-up depth).
|
||||
// Leading points with nothing to carry keep the old low breadcrumb
|
||||
// sentinel (an arbitrary placeholder, never a reported altitude).
|
||||
if (altM == null) altM = lastAltM != null ? lastAltM : 50;
|
||||
lastAltM = altM;
|
||||
older.push(fromDegrees(lon, lat, altM));
|
||||
}
|
||||
|
||||
// Stride-thin the backfill so it plus the live fine segment fit the cap.
|
||||
const budget = Math.max(
|
||||
1,
|
||||
TRAIL_MAX_POINTS - flightState._trailPositions.length,
|
||||
// Every trace point is kept, each leg its own segment. A 'ground' point
|
||||
// is at altitude 0, floored at the ground. A point with no altitude is a
|
||||
// break on both sides: it sits on the ground where the floor is known and
|
||||
// is skipped otherwise; a skipped point still breaks the line.
|
||||
const backfill = trailBackfillFixes(
|
||||
parsed.map(({ lat, lon, baroAltitudeM, onGround, timeMs }) => {
|
||||
const known = Number.isFinite(baroAltitudeM)
|
||||
? baroAltitudeM
|
||||
: onGround
|
||||
? 0
|
||||
: null;
|
||||
const altM = floorAltitudeM(
|
||||
known == null ? null : known + geoidHeight(lat, lon),
|
||||
cachedGroundFloor(lat, lon),
|
||||
);
|
||||
return {
|
||||
position: altM == null ? null : fromDegrees(lon, lat, altM),
|
||||
timeMs,
|
||||
nullAltitude: known == null,
|
||||
};
|
||||
}),
|
||||
);
|
||||
flightState._trailFixes = joinTrailBackfill(
|
||||
backfill,
|
||||
flightState._trailFixes,
|
||||
TRAIL_MAX_POINTS,
|
||||
);
|
||||
if (older.length > budget) {
|
||||
const stride = Math.ceil(older.length / budget);
|
||||
const thinned = [];
|
||||
for (let i = 0; i < older.length; i += stride) thinned.push(older[i]);
|
||||
older = thinned;
|
||||
}
|
||||
|
||||
flightState._trailPositions = older.concat(flightState._trailPositions);
|
||||
if (flightState._trailPositions.length > TRAIL_MAX_POINTS) {
|
||||
flightState._trailPositions = flightState._trailPositions.slice(
|
||||
flightState._trailPositions.length - TRAIL_MAX_POINTS,
|
||||
);
|
||||
}
|
||||
_refreshTrailDisplay();
|
||||
}
|
||||
|
||||
@@ -713,7 +895,9 @@ export function createTracking({
|
||||
|
||||
function _clearTrail() {
|
||||
flightState._trailBackfillToken += 1;
|
||||
flightState._trailPositions = [];
|
||||
flightState._trailFixes = [];
|
||||
flightState._trailRecordPosition = null;
|
||||
flightState._trailRecordMs = -Infinity;
|
||||
if (flightState._trail) flightState._trail.clear();
|
||||
flightState._trailHeadOff?.();
|
||||
flightState._trailHeadOff = null;
|
||||
@@ -907,10 +1091,8 @@ export function createTracking({
|
||||
position: getTrackedPosition,
|
||||
// Solid amber when the billboard is the visual (zoomed out, 3D off, or model still loading);
|
||||
// transparent once the tracked model is actually up (ready + shown).
|
||||
color: () =>
|
||||
parts.rendering._modelOwnsVisual(flightState._trackedIcao)
|
||||
? AMBER_TRANSPARENT
|
||||
: TRACKED_ICON_COLOR,
|
||||
// Amber (faded while stale), transparent once the tracked model is the visual.
|
||||
color: _trackedIconColor,
|
||||
// Screen-projected rotation, evaluated per frame on the camera's own
|
||||
// axes, so it stays exact through a tracked orbit. The tracked target
|
||||
// must never vanish into tile geometry — tracking a taxiing plane at
|
||||
@@ -1095,6 +1277,9 @@ export function createTracking({
|
||||
_setCockpitContactMode,
|
||||
_applyCockpitState,
|
||||
_buildTrackedLabel,
|
||||
_trackedStaleCue,
|
||||
_trackedIconColor,
|
||||
_staleCueTick,
|
||||
_updateTrackedLabelModel,
|
||||
_syncTrackedBillboardImage,
|
||||
_refreshTr3bContact,
|
||||
@@ -1104,6 +1289,9 @@ export function createTracking({
|
||||
_syncTracked2dRotation,
|
||||
_trailFloorPosition,
|
||||
_appendTrailFix,
|
||||
_trailTick,
|
||||
_drawTrailHead,
|
||||
_trailHeadPositions,
|
||||
_refreshTrailDisplay,
|
||||
_startTrail,
|
||||
_backfillTrail,
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { createFlightState } from './state.js';
|
||||
import { createTracking } from './tracking.js';
|
||||
import { TRAIL_MAX_POINTS } from './policy.js';
|
||||
|
||||
const MINUTE = 60_000;
|
||||
const HOUR = 60 * MINUTE;
|
||||
|
||||
function services({ trails, floor = () => null } = {}) {
|
||||
const names = [
|
||||
'picking',
|
||||
'sprites',
|
||||
'aircraftPresentation',
|
||||
'camera',
|
||||
'militaryRegistry',
|
||||
'labels',
|
||||
'meshFloor',
|
||||
'focus',
|
||||
'readout',
|
||||
'context',
|
||||
'render',
|
||||
'recession',
|
||||
];
|
||||
return {
|
||||
...Object.fromEntries(names.map((name) => [name, {}])),
|
||||
groundSnap: { createGroundSnap: () => ({ clear() {} }) },
|
||||
trails,
|
||||
geoid: { ensureGeoidReady: async () => {}, geoidHeight: () => 0 },
|
||||
groundFloor: {
|
||||
resolveGroundFloorCellsBounded: async () => {},
|
||||
cachedGroundFloor: floor,
|
||||
floorAltitudeM: (alt, ground) =>
|
||||
Number.isFinite(alt) && Number.isFinite(ground)
|
||||
? Math.max(alt, ground + 1)
|
||||
: Number.isFinite(alt)
|
||||
? alt
|
||||
: Number.isFinite(ground)
|
||||
? ground + 1
|
||||
: null,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** A fake trail that records what draws: segments of two or more points. */
|
||||
function recordingTrail() {
|
||||
const calls = [];
|
||||
return {
|
||||
last: () =>
|
||||
(calls[calls.length - 1] ?? []).filter((segment) => segment.length >= 2),
|
||||
createTrail: () => ({
|
||||
setSegments(segments) {
|
||||
calls.push(segments.map((segment) => segment.slice()));
|
||||
},
|
||||
setPositions(positions) {
|
||||
calls.push([positions.slice()]);
|
||||
},
|
||||
setVisible() {},
|
||||
clear() {
|
||||
calls.push([]);
|
||||
},
|
||||
destroy() {},
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function trackedHarness({ liveFixes = [], trace = null, nowMs, floor, head }) {
|
||||
const trail = recordingTrail();
|
||||
const svc = services({ trails: trail, floor });
|
||||
const flightState = createFlightState({
|
||||
services: svc,
|
||||
source: {
|
||||
label: 'Fixture military aircraft',
|
||||
async getTrack() {
|
||||
if (!trace) throw new Error('404');
|
||||
return { records: trace };
|
||||
},
|
||||
},
|
||||
});
|
||||
const added = [];
|
||||
flightState._viewer = {
|
||||
isDestroyed: () => false,
|
||||
entities: {
|
||||
add(definition) {
|
||||
added.push(definition);
|
||||
return definition;
|
||||
},
|
||||
remove() {},
|
||||
},
|
||||
};
|
||||
flightState._trackedIcao = 'ae0001';
|
||||
flightState.now = () => nowMs;
|
||||
flightState._positionHistory.set(
|
||||
'ae0001',
|
||||
liveFixes.map((fix) => ({
|
||||
time: Cesium.JulianDate.fromDate(new Date(fix.timeMs)),
|
||||
epochMs: fix.timeMs,
|
||||
position: Cesium.Cartesian3.fromDegrees(fix.lon, fix.lat, 9_000),
|
||||
})),
|
||||
);
|
||||
const tracking = createTracking({
|
||||
flightState,
|
||||
services: svc,
|
||||
parts: {
|
||||
motion: {
|
||||
_isTrackWarmingUp: () => false,
|
||||
_trackedTrailCached: () => head ?? null,
|
||||
_trackedDisplayPosition: () => head ?? null,
|
||||
_trackedModelCenterWorld: () => null,
|
||||
_trackedModelEnvelopeM: () => null,
|
||||
},
|
||||
},
|
||||
layer: {},
|
||||
});
|
||||
// The live head the trail would draw now.
|
||||
const headPositions = () => {
|
||||
return tracking._trailHeadPositions();
|
||||
};
|
||||
return { trail, tracking, flightState, headPositions };
|
||||
}
|
||||
|
||||
const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
/** readsb-shaped trace points as the military source parses them. */
|
||||
function point(timeMs, lat, lon, baroAltitudeM = 9_000, onGround = false) {
|
||||
return {
|
||||
observedAtMs: timeMs,
|
||||
latitude: lat,
|
||||
longitude: lon,
|
||||
baroAltitudeM,
|
||||
onGround,
|
||||
};
|
||||
}
|
||||
|
||||
function leg(startMs, lat, lon, count) {
|
||||
return Array.from({ length: count }, (_, i) =>
|
||||
point(startMs + i * MINUTE, lat, lon + i * 0.12),
|
||||
);
|
||||
}
|
||||
|
||||
test('a multi-leg military trace becomes separate segments with no line across a gap', async () => {
|
||||
const t0 = Date.UTC(2026, 10, 8, 0, 0);
|
||||
const first = leg(t0, 36, -115, 5);
|
||||
const second = leg(t0 + 5 * MINUTE + 3 * HOUR, 35, -106, 5);
|
||||
const third = leg(t0 + 10 * MINUTE + 5 * HOUR, 38, -77, 5);
|
||||
const trace = [...first, ...second, ...third];
|
||||
const liveStart = t0 + 15 * MINUTE + 5 * HOUR;
|
||||
const liveFixes = [0, 1, 2].map((i) => ({
|
||||
timeMs: liveStart + i * MINUTE,
|
||||
lat: 38,
|
||||
lon: -77 + 0.6 + i * 0.12,
|
||||
}));
|
||||
const { trail, flightState, tracking } = trackedHarness({
|
||||
liveFixes,
|
||||
trace,
|
||||
nowMs: liveStart + 3 * MINUTE,
|
||||
});
|
||||
tracking._startTrail('ae0001');
|
||||
await settle();
|
||||
assert.equal(flightState._trailFixes.length, trace.length + 3);
|
||||
assert.deepEqual(
|
||||
trail.last().map((segment) => segment.length),
|
||||
[5, 5, 8],
|
||||
);
|
||||
});
|
||||
|
||||
test('a military trace point with no altitude breaks the line and is never given a made-up height', async () => {
|
||||
const t0 = Date.UTC(2026, 10, 8, 0, 0);
|
||||
const trace = leg(t0, 35, -106, 7);
|
||||
trace[3] = point(trace[3].observedAtMs, 35, -105.64, null);
|
||||
const liveFixes = [{ timeMs: t0 + 7 * MINUTE, lat: 35, lon: -105.16 }];
|
||||
const { trail, flightState, tracking } = trackedHarness({
|
||||
liveFixes,
|
||||
trace,
|
||||
nowMs: t0 + 9 * MINUTE,
|
||||
});
|
||||
tracking._startTrail('ae0001');
|
||||
await settle();
|
||||
// Skipped (no floor known): 3 + 3 + the live fix drawn.
|
||||
assert.equal(flightState._trailFixes.length, trace.length - 1 + 1);
|
||||
assert.deepEqual(
|
||||
trail.last().map((segment) => segment.length),
|
||||
[3, 4],
|
||||
);
|
||||
for (const fix of flightState._trailFixes) {
|
||||
const height = Cesium.Cartographic.fromCartesian(fix.position).height;
|
||||
assert.ok(Math.abs(height - 9_000) < 1, `no invented height: ${height}`);
|
||||
}
|
||||
});
|
||||
|
||||
test('a military ground point is drawn on the ground and stays joined', async () => {
|
||||
const t0 = Date.UTC(2026, 10, 8, 0, 0);
|
||||
// Taxiing: 'ground' points a few hundred metres apart, one minute apart.
|
||||
const trace = Array.from({ length: 4 }, (_, i) =>
|
||||
point(t0 + i * MINUTE, 35, -106.6 + i * 0.004, null, true),
|
||||
);
|
||||
const liveFixes = [{ timeMs: t0 + 4 * MINUTE, lat: 35, lon: -106.584 }];
|
||||
const { trail, flightState, tracking } = trackedHarness({
|
||||
liveFixes,
|
||||
trace,
|
||||
nowMs: t0 + 6 * MINUTE,
|
||||
floor: () => 1_590,
|
||||
});
|
||||
tracking._startTrail('ae0001');
|
||||
await settle();
|
||||
assert.deepEqual(
|
||||
trail.last().map((segment) => segment.length),
|
||||
[5],
|
||||
);
|
||||
const height = Cesium.Cartographic.fromCartesian(
|
||||
flightState._trailFixes[0].position,
|
||||
).height;
|
||||
assert.ok(Math.abs(height - 1_591) < 1);
|
||||
});
|
||||
|
||||
test('the military head is drawn to a nearby aircraft and not to one more than 150 km away', () => {
|
||||
const t0 = Date.UTC(2026, 10, 8, 0, 0);
|
||||
const liveFixes = [0, 1, 2].map((i) => ({
|
||||
timeMs: t0 + i * MINUTE,
|
||||
lat: 35,
|
||||
lon: -106 + i * 0.12,
|
||||
}));
|
||||
const near = Cesium.Cartesian3.fromDegrees(-105.7, 35, 9_000);
|
||||
const joined = trackedHarness({
|
||||
liveFixes,
|
||||
nowMs: t0 + 3 * MINUTE,
|
||||
head: near,
|
||||
});
|
||||
joined.tracking._startTrail('ae0001');
|
||||
assert.equal(joined.headPositions().length, 2);
|
||||
|
||||
const far = Cesium.Cartesian3.fromDegrees(-103, 35, 9_000);
|
||||
const detached = trackedHarness({
|
||||
liveFixes,
|
||||
nowMs: t0 + 3 * MINUTE,
|
||||
head: far,
|
||||
});
|
||||
detached.tracking._startTrail('ae0001');
|
||||
assert.deepEqual(detached.headPositions(), []);
|
||||
});
|
||||
|
||||
test('a full 24 h military trace fits within TRAIL_MAX_POINTS without thinning', async () => {
|
||||
const day = 24 * 60;
|
||||
const t0 = Date.UTC(2026, 10, 8, 0, 0);
|
||||
const trace = leg(t0, 20, -150, day);
|
||||
const liveStart = t0 + day * MINUTE;
|
||||
const liveFixes = [{ timeMs: liveStart, lat: 20, lon: -150 + day * 0.12 }];
|
||||
const { flightState, tracking } = trackedHarness({
|
||||
liveFixes,
|
||||
trace,
|
||||
nowMs: liveStart + MINUTE,
|
||||
});
|
||||
tracking._startTrail('ae0001');
|
||||
await settle();
|
||||
assert.ok(TRAIL_MAX_POINTS >= day + 500);
|
||||
assert.equal(flightState._trailFixes.length, day + 1);
|
||||
});
|
||||
@@ -0,0 +1,684 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { bindRenderer } from '../../render/rendererOf.js';
|
||||
import { createStubRenderer } from '../../render/stub/index.js';
|
||||
import { createMotion } from './motion.js';
|
||||
import { createFlightState } from './state.js';
|
||||
import { createTracking } from './tracking.js';
|
||||
import { RENDER_DELAY_SEC, STALE_ALPHA } from './policy.js';
|
||||
|
||||
// A tracked military contact's trail between reports is the path its icon
|
||||
// was drawn along, recorded from the real display path frame by frame.
|
||||
|
||||
const SEC = 1000;
|
||||
const ICAO = '00a004';
|
||||
const T0 = Date.UTC(2026, 10, 9, 21, 0);
|
||||
|
||||
function fix(timeMs, lat, lon, heightM, velocity, track) {
|
||||
return {
|
||||
time: Cesium.JulianDate.fromDate(new Date(timeMs)),
|
||||
epochMs: timeMs,
|
||||
position: Cesium.Cartesian3.fromDegrees(lon, lat, heightM),
|
||||
velocity,
|
||||
track,
|
||||
};
|
||||
}
|
||||
|
||||
function services(trail, ground) {
|
||||
const names = [
|
||||
'picking',
|
||||
'sprites',
|
||||
'aircraftPresentation',
|
||||
'camera',
|
||||
'militaryRegistry',
|
||||
'labels',
|
||||
'meshFloor',
|
||||
'focus',
|
||||
'readout',
|
||||
'context',
|
||||
'render',
|
||||
'recession',
|
||||
];
|
||||
return {
|
||||
...Object.fromEntries(names.map((name) => [name, {}])),
|
||||
aircraftPresentation: {
|
||||
isTr3b: () => false,
|
||||
tr3bTypeLabel: (id, label) => label,
|
||||
},
|
||||
focus: {
|
||||
nearFarScalarValueAtDistance: () => 1,
|
||||
clearFocusTarget() {},
|
||||
publishFocusTargetAt() {},
|
||||
publishFocusTargetFromCachedPosition() {},
|
||||
},
|
||||
groundSnap: { createGroundSnap: () => ({ clear() {} }) },
|
||||
trails: trail,
|
||||
geoid: { ensureGeoidReady: async () => {}, geoidHeight: () => 0 },
|
||||
groundFloor: {
|
||||
resolveGroundFloorCellsBounded: async () => {},
|
||||
cachedGroundFloor: ground,
|
||||
floorAltitudeM: (alt, g) =>
|
||||
Number.isFinite(g) && Number.isFinite(alt)
|
||||
? Math.max(alt, g + 1.5)
|
||||
: alt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Real motion, real display position and real tracking over one contact.
|
||||
* `frame()` runs one rendered frame: a frame of the stub renderer, whose
|
||||
* preRender pass moves the trail on and then draws its head.
|
||||
*/
|
||||
function harness({ fixes, info, nowMs, ground = () => null }) {
|
||||
const segmentsCalls = [];
|
||||
let headPositions = [];
|
||||
const trail = {
|
||||
createTrail: () => ({
|
||||
setSegments(segments) {
|
||||
segmentsCalls.push(segments.map((segment) => segment.slice()));
|
||||
},
|
||||
setPositions(positions) {
|
||||
segmentsCalls.push([positions.slice()]);
|
||||
},
|
||||
setHead(positions) {
|
||||
headPositions = positions.slice();
|
||||
},
|
||||
setVisible() {},
|
||||
clear() {},
|
||||
destroy() {},
|
||||
}),
|
||||
};
|
||||
const svc = services(trail, ground);
|
||||
const flightState = createFlightState({ services: svc, source: {} });
|
||||
flightState.records.data.set(ICAO, info);
|
||||
// The scene, on the stub renderer: each frame runs its preRender pass
|
||||
// (the trail moves on, then its head is drawn) and counts as drawn.
|
||||
const renderer = createStubRenderer();
|
||||
flightState._viewer = {};
|
||||
bindRenderer(flightState._viewer, renderer);
|
||||
flightState._trackedIcao = ICAO;
|
||||
let clock = nowMs;
|
||||
flightState.now = () => clock;
|
||||
flightState._positionHistory.set(ICAO, fixes);
|
||||
const parts = {
|
||||
rendering: { _modelOwnsVisual: () => false, _modelSpec: () => ({}) },
|
||||
queries: {
|
||||
_toCleanText: (value) => (typeof value === 'string' ? value.trim() : ''),
|
||||
_formatAltitude: (ft) => `${ft} ft`,
|
||||
},
|
||||
};
|
||||
parts.motion = createMotion({ flightState, services: svc, parts });
|
||||
const tracking = createTracking({
|
||||
flightState,
|
||||
services: svc,
|
||||
parts,
|
||||
layer: {},
|
||||
});
|
||||
parts.tracking = tracking;
|
||||
const realDateNow = Date.now;
|
||||
Date.now = () => clock;
|
||||
// The live head the last frame drew (the trail's head, set each frame
|
||||
// before it draws).
|
||||
const head = () => headPositions;
|
||||
/** Drawn icon positions, one per frame. */
|
||||
const drawn = [];
|
||||
// Where the frame draws the icon: read in the same frame as the head.
|
||||
renderer.frame.on('preRender', () => {
|
||||
const icon = parts.motion._trackedDisplayPosition(ICAO);
|
||||
if (icon) drawn.push(Cesium.Cartesian3.clone(icon));
|
||||
});
|
||||
const frame = () => {
|
||||
renderer.frame.requestRender('test');
|
||||
renderer.testing.tick();
|
||||
};
|
||||
const run = (toMs, { frameMs = 100, readHead = true } = {}) => {
|
||||
while (clock < toMs) {
|
||||
clock = Math.min(toMs, clock + frameMs);
|
||||
frame({ readHead });
|
||||
}
|
||||
};
|
||||
return {
|
||||
flightState,
|
||||
tracking,
|
||||
motion: parts.motion,
|
||||
head,
|
||||
drawn,
|
||||
run,
|
||||
body: () => segmentsCalls.at(-1) ?? [],
|
||||
bodyPoints: () => (segmentsCalls.at(-1) ?? []).flat(),
|
||||
restore: () => {
|
||||
Date.now = realDateNow;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Distance from p to the nearest point of a polyline. */
|
||||
function distanceToPath(p, path) {
|
||||
let best = Infinity;
|
||||
const ab = new Cesium.Cartesian3();
|
||||
const ap = new Cesium.Cartesian3();
|
||||
const closest = new Cesium.Cartesian3();
|
||||
if (path.length === 1) return Cesium.Cartesian3.distance(p, path[0]);
|
||||
for (let i = 1; i < path.length; i++) {
|
||||
Cesium.Cartesian3.subtract(path[i], path[i - 1], ab);
|
||||
Cesium.Cartesian3.subtract(p, path[i - 1], ap);
|
||||
const len2 = Cesium.Cartesian3.magnitudeSquared(ab);
|
||||
const t =
|
||||
len2 > 0
|
||||
? Math.max(0, Math.min(1, Cesium.Cartesian3.dot(ap, ab) / len2))
|
||||
: 0;
|
||||
Cesium.Cartesian3.add(
|
||||
path[i - 1],
|
||||
Cesium.Cartesian3.multiplyByScalar(ab, t, closest),
|
||||
closest,
|
||||
);
|
||||
best = Math.min(best, Cesium.Cartesian3.distance(p, closest));
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** No vertex turns the line back sharper than 120° over a short step. */
|
||||
function assertNoSpur(line, label) {
|
||||
const u = new Cesium.Cartesian3();
|
||||
const v = new Cesium.Cartesian3();
|
||||
for (let i = 1; i < line.length - 1; i++) {
|
||||
Cesium.Cartesian3.subtract(line[i], line[i - 1], u);
|
||||
Cesium.Cartesian3.subtract(line[i + 1], line[i], v);
|
||||
const lu = Cesium.Cartesian3.magnitude(u);
|
||||
const lv = Cesium.Cartesian3.magnitude(v);
|
||||
if (!(lu > 0 && lv > 0) || Math.min(lu, lv) > 500) continue;
|
||||
const cos = Cesium.Cartesian3.dot(u, v) / (lu * lv);
|
||||
assert.ok(
|
||||
cos >= -0.5,
|
||||
`${label}: spur at vertex ${i} of ${line.length} (turn ${(
|
||||
(Math.acos(cos) * 180) /
|
||||
Math.PI
|
||||
).toFixed(0)}°)`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const indexOfPoint = (line, p) =>
|
||||
line.findIndex((q) => Cesium.Cartesian3.distance(p, q) < 0.01);
|
||||
|
||||
// A departing jet: four northbound climb reports, then a left turn through
|
||||
// west to south with no report while the icon flies it.
|
||||
function departure() {
|
||||
const fixes = [
|
||||
fix(T0, 37.6329, -122.3661, 213, 85, 8),
|
||||
fix(T0 + 30 * SEC, 37.6542, -122.3616, 495, 95, 0),
|
||||
fix(T0 + 60 * SEC, 37.6813, -122.3615, 808, 104, 350),
|
||||
fix(T0 + 90 * SEC, 37.7066, -122.3755, 1257, 112, 340),
|
||||
];
|
||||
const info = {
|
||||
altitudeFt: 4_124,
|
||||
renderAltitudeM: 1257,
|
||||
rawLat: 37.7066,
|
||||
rawLon: -122.3755,
|
||||
speedMps: 112,
|
||||
track: 340,
|
||||
turnRateDps: -2,
|
||||
onGround: false,
|
||||
wasAirborne: true,
|
||||
lastContactEpochMs: T0 + 200 * SEC,
|
||||
};
|
||||
return { fixes, info };
|
||||
}
|
||||
|
||||
test('military: a report newer than the display time arrives mid-turn, and the trail between the reports stays on the drawn arc', () => {
|
||||
const { fixes, info } = departure();
|
||||
const start = T0 + 90 * SEC + RENDER_DELAY_SEC * SEC;
|
||||
const h = harness({ fixes, info, nowMs: start });
|
||||
try {
|
||||
h.tracking._startTrail(ICAO);
|
||||
// 40 s of turn with no new report: the icon flies the arc.
|
||||
h.run(start + 40 * SEC);
|
||||
const arc = h.drawn.slice();
|
||||
// The next report is where the plane really was 60 s after the last one,
|
||||
// still ahead of the display time (normal 30 s delay, slow feed). The icon
|
||||
// now interpolates the straight line between the two reports and is eased
|
||||
// onto it.
|
||||
const at60 = h.motion._deadReckon(
|
||||
ICAO,
|
||||
new Cesium.Cartesian3(),
|
||||
Cesium.JulianDate.fromDate(new Date(T0 + 150 * SEC)),
|
||||
);
|
||||
const c = Cesium.Cartographic.fromCartesian(at60);
|
||||
const report = fix(
|
||||
T0 + 150 * SEC,
|
||||
Cesium.Math.toDegrees(c.latitude),
|
||||
Cesium.Math.toDegrees(c.longitude),
|
||||
c.height,
|
||||
112,
|
||||
220,
|
||||
);
|
||||
fixes.push(report);
|
||||
info.track = 220;
|
||||
h.tracking._appendTrailFix(
|
||||
Cesium.Cartesian3.clone(report.position),
|
||||
report.epochMs,
|
||||
);
|
||||
// The display passes the new report.
|
||||
h.run(start + 75 * SEC);
|
||||
const line = h.bodyPoints();
|
||||
const from = indexOfPoint(line, fixes[3].position);
|
||||
const to = indexOfPoint(line, report.position);
|
||||
assert.ok(from >= 0 && to > from, 'both reports are on the trail');
|
||||
const between = line.slice(from, to + 1);
|
||||
// Every vertex between the reports is where the icon was drawn...
|
||||
const drawnPath = [fixes[3].position, ...h.drawn, report.position];
|
||||
for (const vertex of between) {
|
||||
const off = distanceToPath(vertex, drawnPath);
|
||||
assert.ok(
|
||||
off < 50,
|
||||
`trail vertex ${off.toFixed(0)} m off the drawn path`,
|
||||
);
|
||||
}
|
||||
// ...and the arc the icon flew is still there: no straight chord. (The
|
||||
// arc strays far from the chord, so a chord would fail this.)
|
||||
const chord = [fixes[3].position, report.position];
|
||||
assert.ok(Math.max(...arc.map((p) => distanceToPath(p, chord))) > 300);
|
||||
// The last 10 s of the arc are exempt: the correction pulled the icon back
|
||||
// over them, and keeping them would fold the line back on itself.
|
||||
for (const point of arc.slice(0, -100)) {
|
||||
const off = distanceToPath(point, between);
|
||||
assert.ok(off < 50, `drawn arc point ${off.toFixed(0)} m from the trail`);
|
||||
}
|
||||
assertNoSpur(line, 'trail');
|
||||
assertNoSpur(h.head(), 'head');
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('military: a report the display already passed replaces the guess drawn after it, with no spike', () => {
|
||||
const { fixes, info } = departure();
|
||||
const start = T0 + 90 * SEC + RENDER_DELAY_SEC * SEC;
|
||||
const h = harness({ fixes, info, nowMs: start });
|
||||
try {
|
||||
h.tracking._startTrail(ICAO);
|
||||
h.run(start + 40 * SEC);
|
||||
const displayMs = T0 + 130 * SEC;
|
||||
// A report for 10 s before the display time, 400 m inside the drawn arc.
|
||||
const guess = h.motion._deadReckon(
|
||||
ICAO,
|
||||
new Cesium.Cartesian3(),
|
||||
Cesium.JulianDate.fromDate(new Date(T0 + 120 * SEC)),
|
||||
);
|
||||
const c = Cesium.Cartographic.fromCartesian(guess);
|
||||
const report = fix(
|
||||
T0 + 120 * SEC,
|
||||
Cesium.Math.toDegrees(c.latitude) - 400 / 111_320,
|
||||
Cesium.Math.toDegrees(c.longitude),
|
||||
c.height,
|
||||
112,
|
||||
250,
|
||||
);
|
||||
fixes.push(report);
|
||||
info.track = 250;
|
||||
h.tracking._appendTrailFix(
|
||||
Cesium.Cartesian3.clone(report.position),
|
||||
report.epochMs,
|
||||
);
|
||||
h.run(start + 55 * SEC);
|
||||
const recorded = h.flightState._trailFixes.filter((entry) => entry.drawn);
|
||||
// Nothing recorded between the report and the end of the ease.
|
||||
assert.deepEqual(
|
||||
recorded
|
||||
.filter(
|
||||
(entry) =>
|
||||
entry.timeMs > report.epochMs && entry.timeMs < displayMs + 900,
|
||||
)
|
||||
.map((entry) => entry.timeMs - T0),
|
||||
[],
|
||||
);
|
||||
const line = h.bodyPoints();
|
||||
assert.ok(indexOfPoint(line, report.position) >= 0);
|
||||
assertNoSpur(line, 'trail');
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('military: a history report at an invented height is seeded with no position, and nothing is recorded next to it', () => {
|
||||
const { fixes, info } = departure();
|
||||
fixes[3].inventedHeight = true;
|
||||
const start = T0 + 90 * SEC + RENDER_DELAY_SEC * SEC;
|
||||
const h = harness({ fixes, info, nowMs: start });
|
||||
try {
|
||||
h.tracking._startTrail(ICAO);
|
||||
const seeded = h.flightState._trailFixes.find(
|
||||
(entry) => entry.timeMs === fixes[3].epochMs,
|
||||
);
|
||||
assert.equal(seeded.position, null);
|
||||
assert.equal(seeded.nullAltitude, true);
|
||||
h.run(start + 10 * SEC);
|
||||
assert.equal(
|
||||
h.flightState._trailFixes.filter((entry) => entry.drawn).length,
|
||||
0,
|
||||
);
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
// A turboprop at FL210 flying east out of receiver coverage: its last
|
||||
// position is at T0 + 30 s, and contact goes on for four more minutes.
|
||||
function outOfCoverage() {
|
||||
const fixes = [
|
||||
fix(T0, 43, -108.1, 6_400, 140, 90),
|
||||
fix(T0 + 30 * SEC, 43, -108.05, 6_400, 140, 90),
|
||||
];
|
||||
const info = {
|
||||
altitudeFt: 21_000,
|
||||
renderAltitudeM: 6_400,
|
||||
rawLat: 43,
|
||||
rawLon: -108.05,
|
||||
speedMps: 140,
|
||||
track: 90,
|
||||
callsign: 'TEST7',
|
||||
turnRateDps: 0,
|
||||
onGround: false,
|
||||
wasAirborne: true,
|
||||
lastContactEpochMs: T0 + 30 * SEC + 240 * SEC,
|
||||
};
|
||||
return { fixes, info };
|
||||
}
|
||||
|
||||
/** Display time (ms) `afterSec` past the last report. */
|
||||
const pastReport = (afterSec) =>
|
||||
T0 + 30 * SEC + RENDER_DELAY_SEC * SEC + afterSec * SEC;
|
||||
|
||||
test('military: a plane that stops reporting keeps moving dimmed as STALE from its first missed update, then stops as SIGNAL LOST', () => {
|
||||
const { fixes, info } = outOfCoverage();
|
||||
const h = harness({ fixes, info, nowMs: pastReport(-5) });
|
||||
try {
|
||||
h.tracking._startTrail(ICAO);
|
||||
h.run(pastReport(30));
|
||||
assert.deepEqual(h.tracking._trackedStaleCue(ICAO), {
|
||||
text: '',
|
||||
dimmed: false,
|
||||
});
|
||||
assert.equal(h.tracking._trackedIconColor()[3], 1);
|
||||
// The first missed update.
|
||||
h.flightState.records.missingPolls.set(ICAO, 1);
|
||||
assert.deepEqual(h.tracking._trackedStaleCue(ICAO), {
|
||||
text: 'STALE',
|
||||
dimmed: true,
|
||||
});
|
||||
assert.match(
|
||||
h.tracking._buildTrackedLabel(h.flightState.records.data.get(ICAO), ICAO),
|
||||
/STALE/,
|
||||
);
|
||||
// Drawn with the fleet's stale fade.
|
||||
assert.equal(h.tracking._trackedIconColor()[3], STALE_ALPHA);
|
||||
// Still moving well past 90 s.
|
||||
h.run(pastReport(200));
|
||||
assert.ok(
|
||||
Cesium.Cartesian3.distance(h.drawn.at(-1), h.drawn.at(-11)) > 100,
|
||||
);
|
||||
// The coast ends 300 s past the report; the plane stops there.
|
||||
h.run(pastReport(310));
|
||||
const recorded = h.flightState._trailFixes.filter((e) => e.drawn).length;
|
||||
h.run(pastReport(330));
|
||||
assert.ok(
|
||||
Cesium.Cartesian3.distance(h.drawn.at(-1), h.drawn.at(-50)) < 0.01,
|
||||
);
|
||||
assert.equal(
|
||||
h.flightState._trailFixes.filter((e) => e.drawn).length,
|
||||
recorded,
|
||||
'the trail kept recording a stopped plane',
|
||||
);
|
||||
// 330 s of display past the report is 330 s + the display delay of wall time.
|
||||
const minutes = Math.floor((330 + RENDER_DELAY_SEC) / 60);
|
||||
assert.deepEqual(h.tracking._trackedStaleCue(ICAO), {
|
||||
text: `SIGNAL LOST · ${minutes} min`,
|
||||
dimmed: true,
|
||||
});
|
||||
assert.match(
|
||||
h.tracking._buildTrackedLabel(h.flightState.records.data.get(ICAO), ICAO),
|
||||
new RegExp(`SIGNAL LOST · ${minutes} min`),
|
||||
);
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('military: a plane held at its last report shows SIGNAL LOST in seconds under a minute', () => {
|
||||
// Its last report is 100 m above a known ground height: it holds there.
|
||||
const { fixes, info } = outOfCoverage();
|
||||
const h = harness({
|
||||
fixes,
|
||||
info,
|
||||
nowMs: pastReport(-5),
|
||||
ground: () => 6_300,
|
||||
});
|
||||
try {
|
||||
h.tracking._startTrail(ICAO);
|
||||
h.flightState.records.missingPolls.set(ICAO, 1);
|
||||
h.run(pastReport(10));
|
||||
assert.ok(10 + RENDER_DELAY_SEC < 60);
|
||||
assert.deepEqual(h.tracking._trackedStaleCue(ICAO), {
|
||||
text: `SIGNAL LOST · ${10 + RENDER_DELAY_SEC} s`,
|
||||
dimmed: true,
|
||||
});
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('military: a report arriving 200 s into a coast: the plane eases onto it and the trail drops what was drawn after it', () => {
|
||||
const { fixes, info } = outOfCoverage();
|
||||
const h = harness({ fixes, info, nowMs: pastReport(-5) });
|
||||
try {
|
||||
h.tracking._startTrail(ICAO);
|
||||
h.run(pastReport(200));
|
||||
// Heard again: the report is for 10 s before the display time, 2 km north
|
||||
// of where the coast put it.
|
||||
const at = T0 + 30 * SEC + 190 * SEC;
|
||||
const guess = h.motion._deadReckon(
|
||||
ICAO,
|
||||
new Cesium.Cartesian3(),
|
||||
Cesium.JulianDate.fromDate(new Date(at)),
|
||||
);
|
||||
const c = Cesium.Cartographic.fromCartesian(guess);
|
||||
const report = fix(
|
||||
at,
|
||||
Cesium.Math.toDegrees(c.latitude) + 2_000 / 111_320,
|
||||
Cesium.Math.toDegrees(c.longitude),
|
||||
c.height,
|
||||
140,
|
||||
90,
|
||||
);
|
||||
fixes.push(report);
|
||||
h.tracking._appendTrailFix(
|
||||
Cesium.Cartesian3.clone(report.position),
|
||||
report.epochMs,
|
||||
);
|
||||
assert.deepEqual(
|
||||
h.flightState._trailFixes.filter(
|
||||
(e) => e.drawn && e.timeMs > report.epochMs,
|
||||
),
|
||||
[],
|
||||
);
|
||||
const from = h.drawn.length;
|
||||
h.run(pastReport(203));
|
||||
const after = h.drawn.slice(from - 1);
|
||||
for (let i = 1; i < after.length; i++)
|
||||
assert.ok(
|
||||
Cesium.Cartesian3.distance(after[i], after[i - 1]) < 400,
|
||||
'the plane jumped instead of easing',
|
||||
);
|
||||
// Eased onto the path from the report: 13 s on from it at 140 m/s.
|
||||
const off = Cesium.Cartesian3.distance(after.at(-1), report.position);
|
||||
assert.ok(
|
||||
Math.abs(off - 140 * 13) < 150,
|
||||
`${off.toFixed(0)} m from the report`,
|
||||
);
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('military: a tracked plane that stops reporting: STALE from the first missed poll, SIGNAL LOST after the five-minute coast, kept at 9 min, removed at 10 min', () => {
|
||||
const { fixes, info } = outOfCoverage();
|
||||
const fixMs = fixes.at(-1).epochMs;
|
||||
// Contact stops with the position: the plane left coverage.
|
||||
info.lastContactEpochMs = fixMs;
|
||||
info.newestFixMs = fixMs;
|
||||
const h = harness({ fixes, info, nowMs: fixMs + 5 * SEC });
|
||||
try {
|
||||
h.tracking._startTrail(ICAO);
|
||||
const records = h.flightState.records;
|
||||
const polls = new Map();
|
||||
let removedAtSec = null;
|
||||
// A poll every 10 s that lists the plane without a position.
|
||||
for (let afterSec = 10; afterSec <= 660; afterSec += 10) {
|
||||
h.run(fixMs + afterSec * SEC, { frameMs: 500, readHead: false });
|
||||
const result = records.absence(ICAO, {
|
||||
complete: true,
|
||||
retainIds: new Set([ICAO]),
|
||||
likelyLanded: false,
|
||||
tracked: true,
|
||||
});
|
||||
if (result === 'remove') {
|
||||
removedAtSec = afterSec;
|
||||
break;
|
||||
}
|
||||
polls.set(afterSec, {
|
||||
cue: h.tracking._trackedStaleCue(ICAO),
|
||||
drawn: Cesium.Cartesian3.clone(h.drawn.at(-1)),
|
||||
});
|
||||
}
|
||||
// Wall time when the display reaches the end of the coast.
|
||||
const coastEndSec = 300 + RENDER_DELAY_SEC;
|
||||
for (const [afterSec, { cue }] of polls) {
|
||||
if (afterSec <= coastEndSec) {
|
||||
assert.deepEqual(cue, { text: 'STALE', dimmed: true }, `${afterSec} s`);
|
||||
} else {
|
||||
assert.deepEqual(
|
||||
cue,
|
||||
{
|
||||
text: `SIGNAL LOST · ${Math.floor(afterSec / 60)} min`,
|
||||
dimmed: true,
|
||||
},
|
||||
`${afterSec} s`,
|
||||
);
|
||||
}
|
||||
}
|
||||
const moved = (a, b) =>
|
||||
Cesium.Cartesian3.distance(polls.get(a).drawn, polls.get(b).drawn);
|
||||
// Moving through the coast, still at its last speed at four minutes.
|
||||
assert.ok(Math.abs(moved(230, 240) - 140 * 10) < 20);
|
||||
// Stopped once the coast has ended.
|
||||
const after = Math.ceil(coastEndSec / 10) * 10;
|
||||
assert.ok(moved(after, 540) < 0.01);
|
||||
assert.equal(polls.get(300).cue.text, 'STALE');
|
||||
assert.deepEqual(polls.get(540).cue, {
|
||||
text: 'SIGNAL LOST · 9 min',
|
||||
dimmed: true,
|
||||
});
|
||||
assert.equal(removedAtSec, 600);
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('military: a repeated old fix counts as a missed update for the tracked plane', () => {
|
||||
const { fixes, info } = outOfCoverage();
|
||||
const h = harness({ fixes, info, nowMs: pastReport(-5) });
|
||||
try {
|
||||
h.tracking._startTrail(ICAO);
|
||||
h.run(pastReport(-2));
|
||||
assert.deepEqual(h.tracking._trackedStaleCue(ICAO), {
|
||||
text: '',
|
||||
dimmed: false,
|
||||
});
|
||||
// The feed re-sends the last position: its fix time did not advance.
|
||||
h.flightState.records.fixRepeated.add(ICAO);
|
||||
assert.deepEqual(h.tracking._trackedStaleCue(ICAO), {
|
||||
text: 'STALE',
|
||||
dimmed: true,
|
||||
});
|
||||
assert.equal(h.tracking._trackedIconColor()[3], STALE_ALPHA);
|
||||
assert.equal(h.flightState.records.missingPolls.has(ICAO), false);
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('military: a stalled feed dims the tracked plane as STALE', () => {
|
||||
const { fixes, info } = outOfCoverage();
|
||||
const h = harness({ fixes, info, nowMs: pastReport(-5) });
|
||||
try {
|
||||
h.tracking._startTrail(ICAO);
|
||||
h.run(pastReport(-2));
|
||||
// The whole feed is backing off: no poll counts a miss, and no newer
|
||||
// position is coming in.
|
||||
h.flightState.feed._backoff = true;
|
||||
assert.deepEqual(h.tracking._trackedStaleCue(ICAO), {
|
||||
text: 'STALE',
|
||||
dimmed: true,
|
||||
});
|
||||
assert.equal(h.tracking._trackedIconColor()[3], STALE_ALPHA);
|
||||
assert.equal(h.flightState.records.missingPolls.has(ICAO), false);
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('military: a report arriving after the plane has stopped: it eases in with no spur, and the trail keeps everything up to the stop', () => {
|
||||
const { fixes, info } = outOfCoverage();
|
||||
info.lastContactEpochMs = fixes.at(-1).epochMs;
|
||||
const h = harness({ fixes, info, nowMs: pastReport(-5) });
|
||||
try {
|
||||
h.tracking._startTrail(ICAO);
|
||||
h.run(pastReport(360));
|
||||
const stop = Cesium.Cartesian3.clone(h.drawn.at(-1));
|
||||
assert.ok(Cesium.Cartesian3.distance(stop, h.drawn.at(-100)) < 0.01);
|
||||
const kept = h.flightState._trailFixes
|
||||
.filter((e) => e.drawn)
|
||||
.map((e) => Cesium.Cartesian3.clone(e.position));
|
||||
// The thinned straight coast, recorded up to where the plane stopped.
|
||||
assert.ok(kept.length >= 2);
|
||||
assert.ok(Cesium.Cartesian3.distance(kept.at(-1), stop) < 300);
|
||||
// Heard again, for 20 s before the display time: the plane flew on, a
|
||||
// little north of its old heading.
|
||||
const at = T0 + 30 * SEC + 340 * SEC;
|
||||
const lonDeg =
|
||||
-108.05 + (140 * 340) / (111_320 * Math.cos((43 * Math.PI) / 180));
|
||||
const report = fix(at, 43 + 1_000 / 111_320, lonDeg, 6_400, 140, 90);
|
||||
fixes.push(report);
|
||||
h.tracking._appendTrailFix(
|
||||
Cesium.Cartesian3.clone(report.position),
|
||||
report.epochMs,
|
||||
);
|
||||
// Nothing was recorded after the stop, so nothing is dropped.
|
||||
const after = h.flightState._trailFixes
|
||||
.filter((e) => e.drawn)
|
||||
.map((e) => e.position);
|
||||
assert.equal(after.length, kept.length);
|
||||
kept.forEach((p, i) =>
|
||||
assert.ok(Cesium.Cartesian3.distance(p, after[i]) < 0.01),
|
||||
);
|
||||
const from = h.drawn.length;
|
||||
h.run(pastReport(365));
|
||||
const eased = h.drawn.slice(from - 1);
|
||||
const jump = Cesium.Cartesian3.distance(eased[0], eased.at(-1));
|
||||
for (let i = 1; i < eased.length; i++)
|
||||
assert.ok(
|
||||
Cesium.Cartesian3.distance(eased[i], eased[i - 1]) < jump / 2,
|
||||
'the plane jumped instead of easing',
|
||||
);
|
||||
// On the path from the report: 25 s on from it at 140 m/s.
|
||||
const off = Cesium.Cartesian3.distance(eased.at(-1), report.position);
|
||||
assert.ok(Math.abs(off - 140 * 25) < 150, `${off.toFixed(0)} m`);
|
||||
assertNoSpur(h.bodyPoints(), 'trail');
|
||||
assertNoSpur(h.head(), 'head');
|
||||
assert.ok(indexOfPoint(h.bodyPoints(), report.position) >= 0);
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,236 @@
|
||||
// Event cards on the globe: a picture, the headline in two lines, and "age ·
|
||||
// sources · sides", with the severity colour down the left edge and the
|
||||
// event's marker as a badge on the picture. Painted on a canvas and handed to
|
||||
// the world overlay as a thumbnail entry, so the overlay places them, keeps
|
||||
// them apart and draws their leader to the marker, as it does CCTV cards.
|
||||
//
|
||||
// The picture is the publisher's own (hotlinked, never copied, credited on
|
||||
// the card); until it loads, or without one, the card shows a tile in the
|
||||
// severity colour with the category icon.
|
||||
|
||||
import { WORLD_OVERLAY_STYLE } from '../../overlays/worldOverlayTokens.js';
|
||||
import { NEWS_SEVERITY } from './model.js';
|
||||
import { paintMarker } from './sprites.js';
|
||||
|
||||
/** Card size in CSS pixels. */
|
||||
export const CARD_W = 168;
|
||||
export const CARD_H = 136;
|
||||
const PAD = 4;
|
||||
const PIC_H = 84;
|
||||
const EDGE = 3;
|
||||
const SCALE = 2; // canvas pixels per CSS pixel
|
||||
const TITLE_FONT = '600 11px Inter, "Noto Sans Arabic", system-ui, sans-serif';
|
||||
const META_FONT = '9px "JetBrains Mono", "Noto Sans Arabic", monospace';
|
||||
const CREDIT_FONT = '8px Inter, "Noto Sans Arabic", system-ui, sans-serif';
|
||||
// The map shows about ten cards plus the clicked one; a few more stay ready
|
||||
// for a pan back. The least recently drawn card goes, and its picture with it.
|
||||
export const MAX_CARDS = 24;
|
||||
|
||||
const pictures = new Map(); // url → {image, state: 'loading'|'ok'|'failed', waiters}
|
||||
const cards = new Map(); // event id → {canvas, key, view, look, pic}, oldest first
|
||||
|
||||
/** Forget a picture no kept card shows any more. */
|
||||
function releasePicture(url) {
|
||||
if (!url || [...cards.values()].some((card) => card.view.image === url))
|
||||
return;
|
||||
const entry = pictures.get(url);
|
||||
if (!entry) return;
|
||||
entry.waiters.clear();
|
||||
entry.image.onload = entry.image.onerror = null;
|
||||
pictures.delete(url);
|
||||
}
|
||||
|
||||
function picture(url, onLoad) {
|
||||
let entry = pictures.get(url);
|
||||
if (!entry) {
|
||||
const image = new Image();
|
||||
// No referrer: the publisher sees a plain image request, as from a link preview.
|
||||
image.referrerPolicy = 'no-referrer';
|
||||
image.decoding = 'async';
|
||||
entry = { image, state: 'loading', waiters: new Set() };
|
||||
pictures.set(url, entry);
|
||||
image.onload = () => {
|
||||
entry.state = 'ok';
|
||||
for (const done of entry.waiters) done();
|
||||
entry.waiters.clear();
|
||||
};
|
||||
image.onerror = () => {
|
||||
entry.state = 'failed';
|
||||
entry.waiters.clear();
|
||||
};
|
||||
image.src = url;
|
||||
}
|
||||
if (entry.state === 'loading' && onLoad) entry.waiters.add(onLoad);
|
||||
return entry;
|
||||
}
|
||||
|
||||
function roundRect(ctx, x, y, w, h, r) {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x + r, y);
|
||||
ctx.arcTo(x + w, y, x + w, y + h, r);
|
||||
ctx.arcTo(x + w, y + h, x, y + h, r);
|
||||
ctx.arcTo(x, y + h, x, y, r);
|
||||
ctx.arcTo(x, y, x + w, y, r);
|
||||
ctx.closePath();
|
||||
}
|
||||
|
||||
/** `text` in at most `lines` lines of `width`, the last cut with an ellipsis. */
|
||||
export function wrapLines(ctx, text, width, lines) {
|
||||
const words = String(text || '')
|
||||
.split(/\s+/)
|
||||
.filter(Boolean);
|
||||
const out = [];
|
||||
let line = '';
|
||||
for (let i = 0; i < words.length; i++) {
|
||||
const next = line ? `${line} ${words[i]}` : words[i];
|
||||
if (ctx.measureText(next).width <= width || !line) {
|
||||
line = next;
|
||||
continue;
|
||||
}
|
||||
out.push(line);
|
||||
line = words[i];
|
||||
if (out.length === lines - 1) {
|
||||
line = words.slice(i).join(' ');
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (line) out.push(line);
|
||||
const last = out.length - 1;
|
||||
if (last >= 0 && ctx.measureText(out[last]).width > width) {
|
||||
let cut = out[last];
|
||||
while (cut && ctx.measureText(`${cut}…`).width > width)
|
||||
cut = cut.slice(0, -1);
|
||||
out[last] = `${cut.trimEnd()}…`;
|
||||
}
|
||||
return out.slice(0, lines);
|
||||
}
|
||||
|
||||
/** Cover-fit an image into a box. */
|
||||
function drawCover(ctx, image, x, y, w, h) {
|
||||
const iw = image.naturalWidth || image.width;
|
||||
const ih = image.naturalHeight || image.height;
|
||||
if (!iw || !ih) return;
|
||||
const s = Math.max(w / iw, h / ih);
|
||||
const sw = w / s;
|
||||
const sh = h / s;
|
||||
ctx.drawImage(image, (iw - sw) / 2, (ih - sh) / 2, sw, sh, x, y, w, h);
|
||||
}
|
||||
|
||||
function paint(canvas, view, look, pic) {
|
||||
const ctx = canvas.getContext('2d');
|
||||
ctx.setTransform(SCALE, 0, 0, SCALE, 0, 0);
|
||||
ctx.clearRect(0, 0, CARD_W, CARD_H);
|
||||
const color = (NEWS_SEVERITY[look.severity] || NEWS_SEVERITY[0]).color;
|
||||
|
||||
roundRect(ctx, 0.5, 0.5, CARD_W - 1, CARD_H - 1, WORLD_OVERLAY_STYLE.radius);
|
||||
ctx.fillStyle = WORLD_OVERLAY_STYLE.selectedBackground;
|
||||
ctx.fill();
|
||||
ctx.strokeStyle = WORLD_OVERLAY_STYLE.border;
|
||||
ctx.lineWidth = 1;
|
||||
ctx.stroke();
|
||||
// Severity down the left edge.
|
||||
ctx.save();
|
||||
roundRect(ctx, 0.5, 0.5, CARD_W - 1, CARD_H - 1, WORLD_OVERLAY_STYLE.radius);
|
||||
ctx.clip();
|
||||
ctx.fillStyle = color;
|
||||
ctx.fillRect(0, 0, EDGE, CARD_H);
|
||||
ctx.restore();
|
||||
|
||||
const px = PAD + EDGE;
|
||||
const pw = CARD_W - px - PAD;
|
||||
ctx.save();
|
||||
roundRect(ctx, px, PAD, pw, PIC_H, 3);
|
||||
ctx.clip();
|
||||
if (pic?.state === 'ok') {
|
||||
try {
|
||||
drawCover(ctx, pic.image, px, PAD, pw, PIC_H);
|
||||
} catch {
|
||||
pic.state = 'failed';
|
||||
}
|
||||
}
|
||||
if (pic?.state !== 'ok') {
|
||||
// No picture: a plain glass tile with the event's marker.
|
||||
ctx.fillStyle = WORLD_OVERLAY_STYLE.background;
|
||||
ctx.fillRect(px, PAD, pw, PIC_H);
|
||||
ctx.fillStyle = 'rgba(255, 255, 255, 0.04)';
|
||||
ctx.fillRect(px, PAD, pw, PIC_H);
|
||||
paintMarker(ctx, look, px + pw / 2, PAD + PIC_H / 2, 34);
|
||||
}
|
||||
ctx.restore();
|
||||
// The event's marker as a badge, so the card reads with the map.
|
||||
if (pic?.state === 'ok') paintMarker(ctx, look, px + 13, PAD + 13, 18);
|
||||
// The picture's publisher, always named on it.
|
||||
if (pic?.state === 'ok' && view.credit) {
|
||||
ctx.font = CREDIT_FONT;
|
||||
const w = Math.min(pw - 30, ctx.measureText(view.credit).width + 8);
|
||||
ctx.fillStyle = 'rgba(0, 0, 0, 0.6)';
|
||||
ctx.fillRect(px + pw - w, PAD + PIC_H - 12, w, 12);
|
||||
ctx.fillStyle = WORLD_OVERLAY_STYLE.title;
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.fillText(
|
||||
wrapLines(ctx, view.credit, w - 8, 1)[0] || '',
|
||||
px + pw - w + 4,
|
||||
PAD + PIC_H - 6,
|
||||
);
|
||||
}
|
||||
|
||||
ctx.textBaseline = 'alphabetic';
|
||||
ctx.fillStyle = WORLD_OVERLAY_STYLE.title;
|
||||
ctx.font = TITLE_FONT;
|
||||
wrapLines(ctx, view.title, pw, 2).forEach((line, i) =>
|
||||
ctx.fillText(line, px, PAD + PIC_H + 14 + i * 13),
|
||||
);
|
||||
ctx.fillStyle = WORLD_OVERLAY_STYLE.detail;
|
||||
ctx.font = META_FONT;
|
||||
ctx.fillText(wrapLines(ctx, view.meta, pw, 1)[0] || '', px, CARD_H - PAD - 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* The canvas of an event's card, one per event: a change in what it shows
|
||||
* (the age in its meta line ticks by the minute) repaints the same canvas.
|
||||
* `onChange` runs when its picture arrives and the canvas has been repainted
|
||||
* (ask the scene for a frame).
|
||||
* @returns {HTMLCanvasElement|null} null where there is no canvas
|
||||
*/
|
||||
export function eventCard(id, view, look, onChange) {
|
||||
const key = `${look.severity}|${look.category}|${look.rim}|${view.image || ''}|${view.credit || ''}|${view.title}|${view.meta}`;
|
||||
let card = cards.get(id);
|
||||
if (card) {
|
||||
// Most recently drawn last.
|
||||
cards.delete(id);
|
||||
cards.set(id, card);
|
||||
if (card.key === key) return card.canvas;
|
||||
} else {
|
||||
const canvas = globalThis.document?.createElement?.('canvas');
|
||||
if (
|
||||
!canvas?.getContext?.('2d') ||
|
||||
typeof globalThis.Path2D !== 'function' ||
|
||||
typeof globalThis.Image !== 'function'
|
||||
)
|
||||
return null;
|
||||
canvas.width = CARD_W * SCALE;
|
||||
canvas.height = CARD_H * SCALE;
|
||||
card = { canvas, key: null, view: {}, look, pic: null };
|
||||
cards.set(id, card);
|
||||
while (cards.size > MAX_CARDS) {
|
||||
const [oldest, gone] = cards.entries().next().value;
|
||||
cards.delete(oldest);
|
||||
releasePicture(gone.view.image);
|
||||
}
|
||||
}
|
||||
const previous = card.view.image;
|
||||
card.key = key;
|
||||
card.view = view;
|
||||
card.look = look;
|
||||
const shown = card;
|
||||
card.pic = view.image
|
||||
? picture(view.image, () => {
|
||||
if (cards.get(id) !== shown || shown.view.image !== view.image) return;
|
||||
paint(shown.canvas, shown.view, shown.look, shown.pic);
|
||||
onChange?.();
|
||||
})
|
||||
: null;
|
||||
if (previous && previous !== view.image) releasePicture(previous);
|
||||
paint(card.canvas, view, look, card.pic);
|
||||
return card.canvas;
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { MAX_CARDS, eventCard } from './cards.js';
|
||||
|
||||
const look = { severity: 3, category: 'strike', rim: 'confirmed', size: 20 };
|
||||
const view = (extra = {}) => ({
|
||||
title: 'Strike on Kharkiv',
|
||||
meta: '10 min · 6 sources · UA, RU',
|
||||
image: 'https://a.test/p.jpg',
|
||||
credit: 'A',
|
||||
...extra,
|
||||
});
|
||||
|
||||
// Node has no canvas: a 2D context that accepts every call, and an Image that
|
||||
// records what was asked for.
|
||||
function fakeBrowser(t) {
|
||||
const saved = {
|
||||
document: globalThis.document,
|
||||
Path2D: globalThis.Path2D,
|
||||
Image: globalThis.Image,
|
||||
};
|
||||
const images = [];
|
||||
const ctx = new Proxy(
|
||||
{},
|
||||
{
|
||||
get: (_target, name) =>
|
||||
name === 'measureText'
|
||||
? (text) => ({ width: String(text).length * 5 })
|
||||
: name === 'createLinearGradient'
|
||||
? () => ({ addColorStop() {} })
|
||||
: () => {},
|
||||
set: () => true,
|
||||
},
|
||||
);
|
||||
let canvases = 0;
|
||||
globalThis.document = {
|
||||
createElement: () => {
|
||||
canvases++;
|
||||
return { getContext: () => ctx };
|
||||
},
|
||||
};
|
||||
globalThis.Path2D = class {};
|
||||
globalThis.Image = class {
|
||||
constructor() {
|
||||
images.push(this);
|
||||
}
|
||||
};
|
||||
t.after(() => {
|
||||
for (const [name, value] of Object.entries(saved))
|
||||
if (value === undefined) delete globalThis[name];
|
||||
else globalThis[name] = value;
|
||||
});
|
||||
return { images, canvases: () => canvases };
|
||||
}
|
||||
|
||||
test('a card keeps one canvas per event while its age ticks', (t) => {
|
||||
const browser = fakeBrowser(t);
|
||||
const first = eventCard('ev-a', view(), look);
|
||||
assert.ok(first);
|
||||
// The meta line's minute-level age changes: the same canvas, repainted.
|
||||
const later = eventCard('ev-a', view({ meta: '11 min · 6 sources' }), look);
|
||||
assert.equal(later, first);
|
||||
assert.equal(browser.canvases(), 1);
|
||||
// One picture request for the event, however often it is drawn.
|
||||
assert.equal(browser.images.length, 1);
|
||||
// Its picture arriving repaints and asks for a frame once; a card with no
|
||||
// picture never does.
|
||||
let frames = 0;
|
||||
const pictured = eventCard(
|
||||
'ev-b',
|
||||
view({ image: 'https://b.test/p.jpg' }),
|
||||
look,
|
||||
() => frames++,
|
||||
);
|
||||
assert.ok(pictured);
|
||||
browser.images.at(-1).onload();
|
||||
assert.equal(frames, 1);
|
||||
assert.ok(eventCard('ev-c', view({ image: null }), look));
|
||||
});
|
||||
|
||||
test('the card cache is bounded and evicts pictures with their cards', (t) => {
|
||||
const browser = fakeBrowser(t);
|
||||
const kept = eventCard('keep', view({ image: 'https://k.test/0.jpg' }), look);
|
||||
for (let i = 0; i < MAX_CARDS * 3; i++) {
|
||||
eventCard(`ev-${i}`, view({ image: `https://p.test/${i}.jpg` }), look);
|
||||
// A card drawn every frame stays: the least recently drawn goes first.
|
||||
assert.equal(
|
||||
eventCard('keep', view({ image: 'https://k.test/0.jpg' }), look),
|
||||
kept,
|
||||
);
|
||||
}
|
||||
const requested = browser.images.length;
|
||||
// The first event was evicted with its picture: drawing it again paints a
|
||||
// new canvas and asks for the picture anew.
|
||||
const again = eventCard(
|
||||
'ev-0',
|
||||
view({ image: 'https://p.test/0.jpg' }),
|
||||
look,
|
||||
);
|
||||
assert.ok(again);
|
||||
assert.equal(browser.images.length, requested + 1);
|
||||
// Evicted pictures are let go: their load handlers are cleared.
|
||||
assert.equal(browser.images[1].onload, null);
|
||||
// The recent ones are still cached.
|
||||
const recent = MAX_CARDS * 3 - 1;
|
||||
eventCard(
|
||||
`ev-${recent}`,
|
||||
view({ image: `https://p.test/${recent}.jpg` }),
|
||||
look,
|
||||
);
|
||||
assert.equal(browser.images.length, requested + 1);
|
||||
});
|
||||
|
||||
test('without a canvas no card is made and nothing is cached', (t) => {
|
||||
fakeBrowser(t);
|
||||
globalThis.document = { createElement: () => ({ getContext: () => null }) };
|
||||
assert.equal(eventCard('none', view(), look), null);
|
||||
globalThis.document = undefined;
|
||||
assert.equal(eventCard('none', view(), look), null);
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,826 @@
|
||||
// Pure presentation model for the news layer: severity, category glyphs,
|
||||
// attestation, marker looks and placement, the feed's filters and paging, and
|
||||
// the event cards the News panel and the globe show. No renderer, no DOM.
|
||||
|
||||
import { getLocale, msg, t, tn } from '../../i18n/index.js';
|
||||
|
||||
export const NEWS_LAYER_ID = 'news';
|
||||
export const NEWS_OVERLAY_SOURCE_ID = 'news';
|
||||
export const NEWS_PICK_PREFIX = 'news:';
|
||||
export const NEWS_FEED_PAGE = 60;
|
||||
export const NEWS_MAP_LIMIT = 500;
|
||||
/** News is real time only: nothing older than a day is shown anywhere. */
|
||||
export const NEWS_WINDOW_MS = 24 * 3_600_000;
|
||||
|
||||
/**
|
||||
* The window a server serves, in ms: its `windowHours` (a whole number of
|
||||
* hours up to 24; a host may serve fewer), else the full day.
|
||||
*/
|
||||
export function newsWindowMs(hours) {
|
||||
return Number.isInteger(hours) && hours >= 1 && hours <= 24
|
||||
? hours * 3_600_000
|
||||
: NEWS_WINDOW_MS;
|
||||
}
|
||||
|
||||
/** The windows the News panel offers, longest first. */
|
||||
export const NEWS_WINDOW_CHOICES = Object.freeze([24, 12, 6, 3, 1]);
|
||||
|
||||
/**
|
||||
* The windows offered under a server's own window of `maxHours`: that window
|
||||
* itself, then each shorter choice.
|
||||
*/
|
||||
export function newsWindowChoices(maxHours) {
|
||||
const cap = newsWindowMs(maxHours) / 3_600_000;
|
||||
return [cap, ...NEWS_WINDOW_CHOICES.filter((hours) => hours < cap)];
|
||||
}
|
||||
// A publish time this far ahead of the clock is skew, not a future story
|
||||
// (as data/regionalNewsWindow.js).
|
||||
const NEWS_CLOCK_SKEW_MS = 15 * 60_000;
|
||||
/** At most this many reports are kept in the feed list, newest first. */
|
||||
export const NEWS_FEED_MAX = 600;
|
||||
// Above this camera height the layer shows one beacon per hotspot; below it
|
||||
// (or once a hotspot is chosen) the outlines and individual reports.
|
||||
export const NEWS_DETAIL_MAX_HEIGHT_M = 2_500_000;
|
||||
// "In view": reports near the view centre, only once the camera is low enough
|
||||
// for "here" to mean a region, read again when it settles in a new cell.
|
||||
// Near is inside the area the server names there (a country, a large
|
||||
// country's state, a disputed area), else, at sea, within the radius.
|
||||
export const NEWS_IN_VIEW_MAX_HEIGHT_M = 3_000_000;
|
||||
export const NEWS_IN_VIEW_RADIUS_KM = 500;
|
||||
export const NEWS_IN_VIEW_LIMIT = 12;
|
||||
/** The Local section lists at most this many reports near the view centre. */
|
||||
export const NEWS_LOCAL_LIMIT = 40;
|
||||
/**
|
||||
* The News panel's sections: Conflicts (the hotspots' significant news, on the
|
||||
* map whenever the layer is on) and Local (everything near the view centre,
|
||||
* on the map while the section is chosen).
|
||||
*/
|
||||
export const NEWS_SECTIONS = Object.freeze(['conflicts', 'local']);
|
||||
export const NEWS_SETTLE_MS = 800;
|
||||
export const NEWS_CELL_DEG = 0.5;
|
||||
/** A feed card's click flies the camera to this height over the event. */
|
||||
export const NEWS_FOCUS_HEIGHT_M = 150_000;
|
||||
// Minor news (a broad outlet's prices, sport, health) is left out unless asked for.
|
||||
export const NEWS_RELEVANT = 'core,related';
|
||||
|
||||
const SOURCE_LABEL = msg('Source');
|
||||
const DISPUTED = msg('Disputed: {name}');
|
||||
const VIA = msg('via {source}');
|
||||
const MEDIA_LABELS = { video: msg('Video'), photo: msg('Photos') };
|
||||
const CLAIMED_BY = msg('Claimed by {who}');
|
||||
const CLAIMED = msg('Claimed');
|
||||
const UNCONFIRMED = msg('Not yet confirmed by others');
|
||||
const REPORTED_BY_SIDE = msg('Reported by {side} sources');
|
||||
const REPORTED_BY_SIDES = msg('Reported by {sides}');
|
||||
const SIDE_SOURCES = msg('{side} sources');
|
||||
const OFFICIAL = msg('Official');
|
||||
const OFFICIAL_AFFILIATIONS = new Set(['military', 'state']);
|
||||
const ATTESTATION = {
|
||||
'both-sides': msg('Reported by both sides'),
|
||||
independent: msg('Independently reported'),
|
||||
single: msg('Single source'),
|
||||
};
|
||||
const NEUTRAL_SIDES = Object.freeze({
|
||||
intl: msg('International'),
|
||||
independent: msg('Independent'),
|
||||
unknown: msg('Unattributed'),
|
||||
external: msg('Outside party'),
|
||||
});
|
||||
|
||||
/**
|
||||
* Short chip names for the curated hotspots; the API's own English name is
|
||||
* the fallback for any other.
|
||||
*/
|
||||
export const NEWS_HOTSPOT_LABELS = Object.freeze({
|
||||
'ua-ru-war': msg('Ukraine–Russia'),
|
||||
'israel-gaza-lebanon': msg('Israel–Gaza–Lebanon'),
|
||||
'iran-hormuz': msg('Iran–Hormuz'),
|
||||
yemen: msg('Yemen–Red Sea'),
|
||||
'sudan-war': msg('Sudan'),
|
||||
sahel: msg('Sahel'),
|
||||
elsewhere: msg('Elsewhere'),
|
||||
// Core's own news (no news server): the world is one hotspot.
|
||||
worldwide: msg('Worldwide'),
|
||||
});
|
||||
|
||||
/** A hotspot's chip label in the interface language. */
|
||||
export function hotspotLabel(hotspot) {
|
||||
const key = NEWS_HOTSPOT_LABELS[hotspot?.id];
|
||||
if (key) return t(key);
|
||||
return hotspot?.catchAll ? t(NEWS_HOTSPOT_LABELS.elsewhere) : hotspot?.name;
|
||||
}
|
||||
|
||||
/** A country's name in the interface language, from its ISO code. */
|
||||
export function countryName(code) {
|
||||
if (!code) return '';
|
||||
try {
|
||||
return (
|
||||
new Intl.DisplayNames([getLocale(), 'en'], { type: 'region' }).of(code) ||
|
||||
code
|
||||
);
|
||||
} catch {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
|
||||
const AREA_IN_COUNTRY = msg('{region}, {country}');
|
||||
|
||||
/**
|
||||
* The Local section's area in the interface language: a country by its code,
|
||||
* a state with its country, a disputed area by its own name only.
|
||||
*/
|
||||
export function areaLabel(area) {
|
||||
if (!area) return '';
|
||||
if (area.kind === 'disputed' || !area.country) return area.name;
|
||||
if (area.kind === 'country') return countryName(area.country);
|
||||
return t(AREA_IN_COUNTRY, {
|
||||
region: area.name,
|
||||
country: countryName(area.country),
|
||||
});
|
||||
}
|
||||
|
||||
/** Label for a disputed area on the map: its name, marked as disputed. */
|
||||
export const disputedLabel = (area) => t(DISPUTED, { name: area.name });
|
||||
|
||||
// A category is told by its icon (a 16-unit SVG path, filled or stroked). On
|
||||
// the map and in the feed colour is severity (NEWS_SEVERITY), never the type
|
||||
// of event or a side.
|
||||
export const NEWS_CATEGORIES = Object.freeze({
|
||||
strike: {
|
||||
label: msg('Strike'),
|
||||
icon: 'M8 0.8 L9.6 5.2 L14.2 3.6 L11.2 7.6 L15.2 10.6 L10.3 10.6 L8 15.2 L5.7 10.6 L0.8 10.6 L4.8 7.6 L1.8 3.6 L6.4 5.2 Z',
|
||||
solid: true,
|
||||
},
|
||||
// A threat on its way (a drone's course, an air-raid alert): nothing has
|
||||
// hit yet. Not a physical event, so never a picture card.
|
||||
alert: {
|
||||
label: msg('Alert'),
|
||||
icon: 'M1.5 8 H11.5 M8 4.5 L11.5 8 L8 11.5 M14.5 3.5 V12.5',
|
||||
},
|
||||
'air-defence': {
|
||||
label: msg('Air defence'),
|
||||
icon: 'M8 1.5 L13.5 3.5 V8 C13.5 11.3 10.8 13.4 8 14.6 C5.2 13.4 2.5 11.3 2.5 8 V3.5 Z M8 4.5 V11',
|
||||
},
|
||||
ground: {
|
||||
label: msg('Ground fighting'),
|
||||
icon: 'M3 13 L12 4 M8.5 3.5 H12.5 V7.5 M13 13 L4 4 M3.5 7.5 V3.5 H7.5',
|
||||
},
|
||||
casualties: {
|
||||
label: msg('Casualties'),
|
||||
icon: 'M6.2 2 H9.8 V6.2 H14 V9.8 H9.8 V14 H6.2 V9.8 H2 V6.2 H6.2 Z',
|
||||
solid: true,
|
||||
},
|
||||
humanitarian: {
|
||||
label: msg('Humanitarian'),
|
||||
icon: 'M8 2.5 L14.5 13.5 H1.5 Z M8 2.5 V13.5',
|
||||
},
|
||||
infrastructure: {
|
||||
label: msg('Infrastructure'),
|
||||
icon: 'M9.2 1 L3.2 9 H7.6 L6.6 15 L12.8 6.8 H8.4 Z',
|
||||
solid: true,
|
||||
},
|
||||
disaster: {
|
||||
label: msg('Disaster'),
|
||||
icon: 'M1.5 6.5 C3.5 4.5 5.5 4.5 7.5 6.5 S11.5 8.5 14.5 6.5 M1.5 10.5 C3.5 8.5 5.5 8.5 7.5 10.5 S11.5 12.5 14.5 10.5',
|
||||
},
|
||||
protest: {
|
||||
label: msg('Protest'),
|
||||
icon: 'M2.5 6.2 V9.8 H5 L12.5 13.2 V2.8 L5 6.2 Z',
|
||||
},
|
||||
political: {
|
||||
label: msg('Political'),
|
||||
icon: 'M2 14 H14 M2.5 5.5 H13.5 M8 1.8 L14 4.8 H2 Z M4.2 6.5 V12 M8 6.5 V12 M11.8 6.5 V12',
|
||||
},
|
||||
// Business, trade and industry: a national feed's news in Local.
|
||||
economy: {
|
||||
label: msg('Economy'),
|
||||
icon: 'M2 13.5 H14 M2.5 11 L6 7.5 L8.5 9.5 L13.5 4.5 M10.5 4.5 H13.5 V7.5',
|
||||
},
|
||||
other: {
|
||||
label: msg('Other'),
|
||||
icon: 'M8 4.5 A3.5 3.5 0 1 0 8.01 4.5 Z',
|
||||
solid: true,
|
||||
},
|
||||
});
|
||||
|
||||
// Severity 0–3, in colours GEV already uses: its dim and primary text, the
|
||||
// military layers' amber and the Cockpit's emergency red. They are drawn on
|
||||
// a dark disc, so from minor up lightness falls as severity rises and the
|
||||
// ramp still reads under colour blindness and in greyscale.
|
||||
export const NEWS_SEVERITY = Object.freeze([
|
||||
{ label: msg('No physical event'), color: '#7c878d' },
|
||||
{ label: msg('Minor incident'), color: '#e8eaed' },
|
||||
{ label: msg('Significant'), color: '#ffb800' },
|
||||
{ label: msg('Major'), color: '#ff4444' },
|
||||
]);
|
||||
/** The feed's default floor: significant and major events. */
|
||||
export const NEWS_DEFAULT_MIN_SEVERITY = 2;
|
||||
const PHYSICAL = new Set([
|
||||
'strike',
|
||||
'air-defence',
|
||||
'ground',
|
||||
'casualties',
|
||||
'infrastructure',
|
||||
'disaster',
|
||||
]);
|
||||
|
||||
export const categoryStyle = (category) =>
|
||||
NEWS_CATEGORIES[category] || NEWS_CATEGORIES.other;
|
||||
export const categoryLabel = (category) => t(categoryStyle(category).label);
|
||||
/** Party codes (UA, RU, IL…) are shown as-is; neutral sides are translated. */
|
||||
export const sideLabel = (side) =>
|
||||
Object.hasOwn(NEUTRAL_SIDES, side) ? t(NEUTRAL_SIDES[side]) : side;
|
||||
|
||||
/**
|
||||
* A report's severity, 0–3: the server's (the local model's reading, else
|
||||
* its rules, raised to its event's), or a fallback from the category.
|
||||
*/
|
||||
export function reportSeverity(report) {
|
||||
const own = Number.isInteger(report?.severity) ? report.severity : null;
|
||||
const event = Number.isInteger(report?.event?.severity)
|
||||
? report.event.severity
|
||||
: null;
|
||||
if (own === null && event === null)
|
||||
return PHYSICAL.has(report?.category) ? 1 : 0;
|
||||
return Math.max(own ?? 0, event ?? 0);
|
||||
}
|
||||
export const severityStyle = (report) => NEWS_SEVERITY[reportSeverity(report)];
|
||||
export const severityLabel = (report) => t(severityStyle(report).label);
|
||||
|
||||
/** When a report (or its event) was last heard of, in ms; NaN when unknown. */
|
||||
const lastHeard = (report) =>
|
||||
Date.parse(report?.event?.lastAt || report?.publishedAt || '');
|
||||
|
||||
/**
|
||||
* Whether a time is inside the window (the last 24 hours unless the server
|
||||
* serves fewer; the only news shown); one more than 15 minutes ahead of the
|
||||
* clock is not.
|
||||
*/
|
||||
function inWindow(value, now, windowMs = NEWS_WINDOW_MS) {
|
||||
const at = Date.parse(value || '');
|
||||
return (
|
||||
Number.isFinite(at) &&
|
||||
now - at <= windowMs &&
|
||||
at - now <= NEWS_CLOCK_SKEW_MS
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether a report is inside the window (the only news shown). */
|
||||
export function withinNewsWindow(
|
||||
report,
|
||||
now = Date.now(),
|
||||
windowMs = NEWS_WINDOW_MS,
|
||||
) {
|
||||
return inWindow(report?.publishedAt, now, windowMs);
|
||||
}
|
||||
|
||||
/** The event's one-report-per-side list, inside the last 24 hours only. */
|
||||
const recentSides = (report, now) =>
|
||||
(report?.event?.sides || []).filter((s) => inWindow(s.publishedAt, now));
|
||||
|
||||
/**
|
||||
* How a report or its event is attested, as a chip: `claimed` (someone's
|
||||
* claim, named where known), `confirmed` (both sides, or an independent
|
||||
* source), `side` (one party's own press), `single` (one report), or null.
|
||||
*/
|
||||
export function attestation(report) {
|
||||
const event = report?.event;
|
||||
const status = event?.status || (report?.claim ? 'claimed' : null);
|
||||
if (status === 'claimed') {
|
||||
const who = event?.claimedBy || report?.claim?.by;
|
||||
return {
|
||||
kind: 'claimed',
|
||||
label: who ? t(CLAIMED_BY, { who }) : t(CLAIMED),
|
||||
};
|
||||
}
|
||||
if (status === 'both-sides' || status === 'independent')
|
||||
return { kind: 'confirmed', label: t(ATTESTATION[status]) };
|
||||
if (status === 'side' && event.reportedSide)
|
||||
return {
|
||||
kind: 'side',
|
||||
label: t(REPORTED_BY_SIDE, { side: sideLabel(event.reportedSide) }),
|
||||
};
|
||||
if (status === 'single')
|
||||
return { kind: 'single', label: t(ATTESTATION.single) };
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The attestation chip under a report. An official channel's own post is
|
||||
* already marked Official: "Claimed by" itself would read as doubt about an
|
||||
* alert. It says only that nobody else has reported it yet, and nothing for
|
||||
* an alert, which is the channel's own notice.
|
||||
*/
|
||||
function ownClaimChip(report) {
|
||||
const chip = attestation(report);
|
||||
if (
|
||||
chip?.kind !== 'claimed' ||
|
||||
!OFFICIAL_AFFILIATIONS.has(report.affiliation)
|
||||
)
|
||||
return chip;
|
||||
const who = report.event?.claimedBy || report.claim?.by;
|
||||
if (who && who !== report.sourceName && who !== report.publisher) return chip;
|
||||
return report.category === 'alert'
|
||||
? null
|
||||
: { kind: 'claimed', label: t(UNCONFIRMED) };
|
||||
}
|
||||
|
||||
// The map card is a label, not a reader: long headlines are cut.
|
||||
export const NEWS_CARD_TITLE_MAX = 90;
|
||||
|
||||
/** A headline cut at a word to fit `max` characters. */
|
||||
export function shortTitle(title, max = NEWS_CARD_TITLE_MAX) {
|
||||
const text = String(title || '');
|
||||
if (text.length <= max) return text;
|
||||
const cut = text.slice(0, max - 1);
|
||||
const word = cut.lastIndexOf(' ');
|
||||
return `${word > max * 0.6 ? cut.slice(0, word) : cut}…`;
|
||||
}
|
||||
|
||||
/** The media a post carries ("Video", "Photos"), translated. */
|
||||
export function mediaLabels(report) {
|
||||
return (report?.media || [])
|
||||
.map((m) => (MEDIA_LABELS[m] ? t(MEDIA_LABELS[m]) : ''))
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
/**
|
||||
* How long ago, in few words: "now" under a minute, "N min" under an hour,
|
||||
* "N h" under a day. Older is never shown; it reads
|
||||
* "24 h".
|
||||
*/
|
||||
export function ageWords(at, now = Date.now()) {
|
||||
const minutes = Math.max(0, Math.floor((now - Date.parse(at)) / 60_000));
|
||||
if (!Number.isFinite(minutes)) return '';
|
||||
if (minutes < 1) return t('now', { context: 'age' });
|
||||
if (minutes < 60) return t('{minutes} min', { minutes });
|
||||
return t('{hours} h', { hours: Math.min(24, Math.floor(minutes / 60)) });
|
||||
}
|
||||
|
||||
/**
|
||||
* How a report's marker looks: colour = severity, icon = category, rim =
|
||||
* attestation (`confirmed` solid, `claimed` dashed, else thin), size =
|
||||
* sources, opacity = age (fading to 45 % over a day).
|
||||
*/
|
||||
export function markerStyle(report, now = Date.now()) {
|
||||
const kind = attestation(report)?.kind;
|
||||
const at = lastHeard(report);
|
||||
const hours = Number.isFinite(at) ? Math.max(0, (now - at) / 3_600_000) : 0;
|
||||
return {
|
||||
category: Object.hasOwn(NEWS_CATEGORIES, report?.category)
|
||||
? report.category
|
||||
: 'other',
|
||||
severity: reportSeverity(report),
|
||||
rim: kind === 'confirmed' || kind === 'claimed' ? kind : 'thin',
|
||||
size: eventPixelSize(report?.event?.size),
|
||||
alpha: Math.max(0.45, 1 - (0.55 * Math.min(hours, 24)) / 24),
|
||||
};
|
||||
}
|
||||
|
||||
function hash(text) {
|
||||
let h = 2166136261;
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
h ^= text.charCodeAt(i);
|
||||
h = Math.imul(h, 16777619);
|
||||
}
|
||||
return h >>> 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Trend glyph for a hotspot: ▲/▼ when the last 24 h differ from the 24 h
|
||||
* before by more than a fifth, nothing when flat or without a prior day.
|
||||
*/
|
||||
export function hotspotTrend(last24h, prev24h) {
|
||||
if (!(prev24h > 0)) return '';
|
||||
if (last24h > prev24h * 1.2) return '▲';
|
||||
if (last24h < prev24h * 0.8) return '▼';
|
||||
return '';
|
||||
}
|
||||
|
||||
/** Beacon size in pixels: grows with the square root of daily activity. */
|
||||
export const beaconPixelSize = (last24h) =>
|
||||
Math.round(Math.min(26, 10 + Math.sqrt(Math.max(0, last24h)) * 1.4));
|
||||
|
||||
/** Marker size for an event: grows with the number of distinct sources. */
|
||||
export function eventPixelSize(sources = 1) {
|
||||
return Math.round(
|
||||
// No smaller than 24: the category icon is half the disc and unreadable
|
||||
// below that.
|
||||
Math.min(36, 24 + 3 * Math.log2(Math.max(1, Number(sources) || 1))),
|
||||
);
|
||||
}
|
||||
|
||||
// An event several sources report within the last few hours gets a halo.
|
||||
export const NEWS_PRESSING_SOURCES = 5;
|
||||
const PRESSING_MS = 3 * 3_600_000;
|
||||
|
||||
/** Whether an event is fresh and widely reported, or fresh and major. */
|
||||
export function isPressing(report, now = Date.now()) {
|
||||
const event = report?.event;
|
||||
const fresh = now - lastHeard(report) <= PRESSING_MS;
|
||||
return Boolean(
|
||||
fresh &&
|
||||
((event && event.size >= NEWS_PRESSING_SOURCES) ||
|
||||
reportSeverity(report) === 3),
|
||||
);
|
||||
}
|
||||
|
||||
// The big events stand as picture cards over their marker: several
|
||||
// sources, and major or pressing.
|
||||
export const NEWS_CARD_LIMIT = 10;
|
||||
export const NEWS_CARD_MIN_SOURCES = 2;
|
||||
|
||||
/** Whether an event gets a card on the map: physical events only, not statements. */
|
||||
export function isCardEvent(report, now = Date.now()) {
|
||||
return Boolean(
|
||||
report?.event?.size >= NEWS_CARD_MIN_SOURCES &&
|
||||
PHYSICAL.has(report.category) &&
|
||||
(reportSeverity(report) === 3 || isPressing(report, now)),
|
||||
);
|
||||
}
|
||||
|
||||
/** The card events among `reports`, most severe, most reported and newest first. */
|
||||
export function cardEvents(reports, now = Date.now(), limit = NEWS_CARD_LIMIT) {
|
||||
return reports
|
||||
.filter((r) => r.pins?.length && isCardEvent(r, now))
|
||||
.sort(
|
||||
(a, b) =>
|
||||
reportSeverity(b) - reportSeverity(a) ||
|
||||
b.event.size - a.event.size ||
|
||||
(b.event.lastAt || '').localeCompare(a.event.lastAt || ''),
|
||||
)
|
||||
.slice(0, limit);
|
||||
}
|
||||
|
||||
/** The distinct sides an event was reported by in the last day, lead first. */
|
||||
function eventSides(report, now) {
|
||||
const sides = recentSides(report, now).map((s) => s.side);
|
||||
return [...new Set(sides.length ? sides : [report?.side].filter(Boolean))];
|
||||
}
|
||||
|
||||
/**
|
||||
* "Reported by UA sources · RU sources", or '' when no side is known; an
|
||||
* unattributed side is left out.
|
||||
*/
|
||||
export function sidesLine(report, now = Date.now()) {
|
||||
const sides = eventSides(report, now).filter((side) => side !== 'unknown');
|
||||
if (!sides.length) return '';
|
||||
if (sides.length === 1)
|
||||
return t(REPORTED_BY_SIDE, { side: sideLabel(sides[0]) });
|
||||
return t(REPORTED_BY_SIDES, {
|
||||
sides: sides
|
||||
.map((side) => t(SIDE_SOURCES, { side: sideLabel(side) }))
|
||||
.join(' · '),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The event's picture, the publisher named, and its clip when it has one. The
|
||||
* panel shows it for any event; the globe's picture cards are for events of
|
||||
* two or more sources (isCardEvent).
|
||||
*/
|
||||
export function eventPicture(report) {
|
||||
const image = report?.event?.image;
|
||||
if (!image) return null;
|
||||
return {
|
||||
url: image.url,
|
||||
credit: image.publisher || '',
|
||||
...(image.video ? { video: image.video } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** What an event's picture card on the globe shows. */
|
||||
export function cardView(report, now = Date.now()) {
|
||||
const event = report.event;
|
||||
const sides = eventSides(report, now).map(sideLabel);
|
||||
// A globe card's picture needs two or more sources, as the card does.
|
||||
const picture =
|
||||
report?.event?.size >= NEWS_CARD_MIN_SOURCES ? eventPicture(report) : null;
|
||||
return {
|
||||
title: report.titleEn || report.title,
|
||||
meta: [
|
||||
ageWords(event?.lastAt || report.publishedAt, now),
|
||||
tn(event?.size || 1, '{count} source', '{count} sources'),
|
||||
sides.slice(0, 3).join(', ') + (sides.length > 3 ? '…' : ''),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · '),
|
||||
image: picture?.url || null,
|
||||
credit: picture?.credit || '',
|
||||
};
|
||||
}
|
||||
|
||||
/** "Source: host ↗" line for a report's card; the card opens the article. */
|
||||
export function sourceLinkLabel(url) {
|
||||
let host = '';
|
||||
try {
|
||||
host = new URL(url).hostname.replace(/^www\./, '');
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
return `${t(SOURCE_LABEL)}: ${host} ↗`;
|
||||
}
|
||||
|
||||
/**
|
||||
* "via GDELT Project": the service a report was read through, which asks to
|
||||
* be credited where its reports show; '' when the server names none.
|
||||
*/
|
||||
export function attributionLabel(report) {
|
||||
return report?.attribution ? t(VIA, { source: report.attribution }) : '';
|
||||
}
|
||||
|
||||
/** The places a report is pinned at, joined, or null. */
|
||||
function placeLine(report) {
|
||||
return (
|
||||
(report.pins?.length ? report.pins : [report.geo])
|
||||
.map((p) => p?.place)
|
||||
.filter(Boolean)
|
||||
.join(' · ') || null
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* One event card in the News panel: picture,
|
||||
* headline, a mono meta line (severity, category, place, sources, age, the
|
||||
* service it came through), the sides line, then attestation and media chips. Labels and colours are
|
||||
* resolved here so the panel imports no layer code.
|
||||
*/
|
||||
export function feedCardView(report, now = Date.now()) {
|
||||
const severity = reportSeverity(report);
|
||||
const style = categoryStyle(report.category);
|
||||
const size = report.event?.size || 1;
|
||||
const translated = Boolean(report.titleEn && report.titleEn !== report.title);
|
||||
return {
|
||||
id: report.id,
|
||||
url: report.url,
|
||||
title: translated ? report.titleEn : report.title,
|
||||
// The local model's English headline over a post in another language:
|
||||
// the original stays beside it.
|
||||
original: translated ? report.title : null,
|
||||
snippet: report.snippet,
|
||||
severity,
|
||||
severityLabel: t(NEWS_SEVERITY[severity].label),
|
||||
color: NEWS_SEVERITY[severity].color,
|
||||
icon: style.icon,
|
||||
solid: Boolean(style.solid),
|
||||
category: categoryLabel(report.category),
|
||||
place: placeLine(report),
|
||||
placedByModel: Boolean(report.geo?.byModel),
|
||||
mappable: Boolean(report.pins?.length),
|
||||
sources: tn(size, '{count} source', '{count} sources'),
|
||||
age: ageWords(report.event?.lastAt || report.publishedAt, now),
|
||||
publisher: report.publisher,
|
||||
via: attributionLabel(report),
|
||||
sides: sidesLine(report, now),
|
||||
sourceLink: sourceLinkLabel(report.url),
|
||||
picture: eventPicture(report),
|
||||
chips: [
|
||||
// An official channel speaking for itself (a ministry, the armed
|
||||
// forces, a press service), not an outlet that quotes one.
|
||||
OFFICIAL_AFFILIATIONS.has(report.affiliation)
|
||||
? { kind: 'official', label: t(OFFICIAL) }
|
||||
: null,
|
||||
ownClaimChip(report),
|
||||
...mediaLabels(report).map((label) => ({ kind: 'media', label })),
|
||||
].filter(Boolean),
|
||||
// The event's first report from each other side, under the lead.
|
||||
others: recentSides(report, now)
|
||||
.slice(1)
|
||||
.map((s) => ({
|
||||
side: sideLabel(s.side),
|
||||
publisher: s.publisher,
|
||||
title: s.title,
|
||||
url: s.url,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a report is placed no closer than a country: it has no spot of its
|
||||
* own on the map.
|
||||
*/
|
||||
export const countryOnly = (report) =>
|
||||
report.pins?.length > 0 &&
|
||||
report.pins.every((pin) => pin.precision === 'country');
|
||||
|
||||
/**
|
||||
* Country-only reports as one group per country, in the order met:
|
||||
* `{key, place, lat, lon, count}`. They are drawn as one badge with a count,
|
||||
* not as markers piled on the country's centre.
|
||||
*/
|
||||
export function countryGroups(reports) {
|
||||
const groups = new Map();
|
||||
for (const report of reports) {
|
||||
if (!countryOnly(report)) continue;
|
||||
const { lat, lon, place } = report.pins[0];
|
||||
const key = place || `${lat.toFixed(1)},${lon.toFixed(1)}`;
|
||||
const group = groups.get(key);
|
||||
if (group) group.count += 1;
|
||||
else groups.set(key, { key, place: place || '', lat, lon, count: 1 });
|
||||
}
|
||||
return [...groups.values()];
|
||||
}
|
||||
|
||||
/**
|
||||
* Marker position for a report. Many reports name the same city and would
|
||||
* stack on one centroid, so each is spread on a small deterministic ring
|
||||
* (about 1.5 km for a place, 6 km for a region, 28 km for a country) to stay
|
||||
* individually clickable. The spread is display-only; cards show the place.
|
||||
*/
|
||||
export function reportMarkerPosition(report, pin = 0) {
|
||||
const { lat, lon, precision } = report.pins?.[pin] || report.geo;
|
||||
const h = hash(pin ? `${report.id}~${pin}` : report.id);
|
||||
const angle = ((h % 3600) / 3600) * 2 * Math.PI;
|
||||
const radiusDeg =
|
||||
(precision === 'country' ? 0.25 : precision === 'region' ? 0.055 : 0.014) *
|
||||
(0.35 + ((h >>> 12) % 65) / 100);
|
||||
return {
|
||||
lat: lat + radiusDeg * Math.sin(angle),
|
||||
lon: lon + (radiusDeg * Math.cos(angle)) / Math.cos((lat * Math.PI) / 180),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge a page into the feed, newest first, one row per report id, keeping
|
||||
* only the window and at most `max` rows (a long session does not grow
|
||||
* the list). `mode` 'head' refreshes the top and keeps the older cursor;
|
||||
* 'append' adds an older page and takes its cursor; 'replace' starts over.
|
||||
* A head page that has older pages behind it and shares no row with the list
|
||||
* left a gap (more than a page arrived since), so it starts over too.
|
||||
*/
|
||||
export function mergeFeedPage(
|
||||
feed,
|
||||
page,
|
||||
mode,
|
||||
now = Date.now(),
|
||||
max = NEWS_FEED_MAX,
|
||||
windowMs = NEWS_WINDOW_MS,
|
||||
) {
|
||||
const byId = new Map();
|
||||
if (mode === 'head' && page.nextBefore && feed.items.length) {
|
||||
const held = new Set(feed.items.map((item) => item.id));
|
||||
if (!page.reports.some((item) => held.has(item.id))) mode = 'replace';
|
||||
}
|
||||
const items =
|
||||
mode === 'replace'
|
||||
? page.reports
|
||||
: mode === 'append'
|
||||
? [...feed.items, ...page.reports]
|
||||
: [...page.reports, ...feed.items];
|
||||
for (const item of items)
|
||||
if (!byId.has(item.id) && withinNewsWindow(item, now, windowMs))
|
||||
byId.set(item.id, item);
|
||||
return {
|
||||
items: [...byId.values()]
|
||||
.sort((a, b) => b.publishedAt.localeCompare(a.publishedAt))
|
||||
.slice(0, max),
|
||||
nextBefore:
|
||||
mode === 'head' && feed.items.length ? feed.nextBefore : page.nextBefore,
|
||||
};
|
||||
}
|
||||
|
||||
/** Normalised filters; anything unknown falls back to its default. */
|
||||
export function normalizeFilters(next = {}, hotspots = [], previous = {}) {
|
||||
const merged = { ...previous, ...next };
|
||||
const hotspot = hotspots.some((h) => h.id === merged.hotspot)
|
||||
? merged.hotspot
|
||||
: 'all';
|
||||
const category = Object.hasOwn(NEWS_CATEGORIES, merged.category)
|
||||
? merged.category
|
||||
: 'all';
|
||||
const minSeverity =
|
||||
Number.isInteger(merged.minSeverity) &&
|
||||
merged.minSeverity >= 0 &&
|
||||
merged.minSeverity <= 3
|
||||
? merged.minSeverity
|
||||
: NEWS_DEFAULT_MIN_SEVERITY;
|
||||
return {
|
||||
hotspot,
|
||||
category,
|
||||
minSeverity,
|
||||
section: NEWS_SECTIONS.includes(merged.section)
|
||||
? merged.section
|
||||
: 'conflicts',
|
||||
// A shorter window than the server's; null shows all it serves.
|
||||
hours: NEWS_WINDOW_CHOICES.includes(merged.hours) ? merged.hours : null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Whether a report passes the filters the server does not apply. */
|
||||
export function passesFilters(
|
||||
report,
|
||||
filters,
|
||||
now = Date.now(),
|
||||
windowMs = NEWS_WINDOW_MS,
|
||||
) {
|
||||
return (
|
||||
withinNewsWindow(report, now, windowMs) &&
|
||||
reportSeverity(report) >= filters.minSeverity
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether a report belongs on the map under the current filters. */
|
||||
export function visibleOnMap(
|
||||
report,
|
||||
filters,
|
||||
now = Date.now(),
|
||||
windowMs = NEWS_WINDOW_MS,
|
||||
) {
|
||||
return (
|
||||
(filters.hotspot === 'all' ||
|
||||
(report.hotspotIds || [report.hotspotId]).includes(filters.hotspot)) &&
|
||||
(filters.category === 'all' || report.category === filters.category) &&
|
||||
passesFilters(report, filters, now, windowMs)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The filters Local applies: every hotspot and every severity, near the view
|
||||
* centre; the category and the window still hold.
|
||||
*/
|
||||
export const localFilters = (filters) => ({
|
||||
...filters,
|
||||
hotspot: 'all',
|
||||
minSeverity: 0,
|
||||
});
|
||||
|
||||
/** API query for the Conflicts feed under the current filters: the window only. */
|
||||
export function feedQueryFor(filters, extra = {}) {
|
||||
return {
|
||||
events: true,
|
||||
today: true,
|
||||
relevance: NEWS_RELEVANT,
|
||||
hotspot: filters.hotspot,
|
||||
category: filters.category === 'all' ? '' : filters.category,
|
||||
limit: NEWS_FEED_PAGE,
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
/** The half-degree cell a point lies in, as a key. */
|
||||
export function viewCell({ lat, lon }) {
|
||||
return `${Math.floor(lat / NEWS_CELL_DEG)}:${Math.floor(lon / NEWS_CELL_DEG)}`;
|
||||
}
|
||||
|
||||
/** Great-circle distance in kilometres. */
|
||||
export function distanceKm(a, b) {
|
||||
const rad = Math.PI / 180;
|
||||
const dLat = (b.lat - a.lat) * rad;
|
||||
const dLon = (b.lon - a.lon) * rad;
|
||||
const s =
|
||||
Math.sin(dLat / 2) ** 2 +
|
||||
Math.cos(a.lat * rad) * Math.cos(b.lat * rad) * Math.sin(dLon / 2) ** 2;
|
||||
return 2 * 6371 * Math.asin(Math.min(1, Math.sqrt(s)));
|
||||
}
|
||||
|
||||
function inRing(ring, { lat, lon }) {
|
||||
let inside = false;
|
||||
for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
|
||||
const [xi, yi] = ring[i];
|
||||
const [xj, yj] = ring[j];
|
||||
if (
|
||||
yi > lat !== yj > lat &&
|
||||
lon < ((xj - xi) * (lat - yi)) / (yj - yi) + xi
|
||||
)
|
||||
inside = !inside;
|
||||
}
|
||||
return inside;
|
||||
}
|
||||
|
||||
/** Whether a point lies in an outline's polygons (`{outer, holes}`). */
|
||||
export function inPolygons(polygons, point) {
|
||||
return polygons.some(
|
||||
({ outer, holes }) =>
|
||||
inRing(outer, point) && !holes.some((hole) => inRing(hole, point)),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The reports near `centre` that pass the filters, newest first: any pin
|
||||
* inside `area` (outline polygons), or without one within
|
||||
* NEWS_IN_VIEW_RADIUS_KM. Newest, not most severe: an area's own news often
|
||||
* carries no severity, and the area's fighting would otherwise crowd it out.
|
||||
*/
|
||||
export function reportsInView(
|
||||
reports,
|
||||
centre,
|
||||
filters,
|
||||
now = Date.now(),
|
||||
limit = NEWS_IN_VIEW_LIMIT,
|
||||
windowMs = NEWS_WINDOW_MS,
|
||||
area = null,
|
||||
) {
|
||||
if (!centre) return [];
|
||||
const near = area?.length
|
||||
? (pin) => inPolygons(area, pin)
|
||||
: (pin) => distanceKm(pin, centre) <= NEWS_IN_VIEW_RADIUS_KM;
|
||||
return reports
|
||||
.filter(
|
||||
(r) =>
|
||||
passesFilters(r, filters, now, windowMs) &&
|
||||
(filters.category === 'all' || r.category === filters.category) &&
|
||||
r.pins?.some(near),
|
||||
)
|
||||
.sort((a, b) => b.publishedAt.localeCompare(a.publishedAt))
|
||||
.slice(0, limit);
|
||||
}
|
||||
@@ -0,0 +1,765 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
normalizeFeedPayload,
|
||||
normalizeHotspotsPayload,
|
||||
normalizeOutlinePayload,
|
||||
} from './records.js';
|
||||
import {
|
||||
NEWS_IN_VIEW_RADIUS_KM,
|
||||
ageWords,
|
||||
areaLabel,
|
||||
beaconPixelSize,
|
||||
cardEvents,
|
||||
cardView,
|
||||
distanceKm,
|
||||
eventPixelSize,
|
||||
feedCardView,
|
||||
feedQueryFor,
|
||||
hotspotLabel,
|
||||
hotspotTrend,
|
||||
inPolygons,
|
||||
isPressing,
|
||||
markerStyle,
|
||||
mergeFeedPage,
|
||||
newsWindowChoices,
|
||||
newsWindowMs,
|
||||
normalizeFilters,
|
||||
passesFilters,
|
||||
reportMarkerPosition,
|
||||
reportSeverity,
|
||||
reportsInView,
|
||||
sidesLine,
|
||||
sourceLinkLabel,
|
||||
viewCell,
|
||||
visibleOnMap,
|
||||
withinNewsWindow,
|
||||
} from './model.js';
|
||||
import { newsFeedQuery } from './source.js';
|
||||
|
||||
const NOW = Date.parse('2026-10-28T10:00:00Z');
|
||||
const report = (id, publishedAt, extra = {}) => ({
|
||||
id,
|
||||
title: `Report ${id}`,
|
||||
url: `https://example.com/${id}`,
|
||||
publishedAt,
|
||||
publisher: 'Example',
|
||||
side: 'UA',
|
||||
category: 'strike',
|
||||
hotspotIds: ['ua'],
|
||||
geo: {
|
||||
lat: 50,
|
||||
lon: 36,
|
||||
place: 'Kharkiv',
|
||||
precision: 'city',
|
||||
mappable: true,
|
||||
},
|
||||
pins: [
|
||||
{ lat: 50, lon: 36, place: 'Kharkiv', precision: 'city', mappable: true },
|
||||
],
|
||||
...extra,
|
||||
});
|
||||
const event = (extra = {}) => ({
|
||||
status: 'both-sides',
|
||||
size: 6,
|
||||
severity: 3,
|
||||
lastAt: '2026-10-28T09:30:00Z',
|
||||
sides: [
|
||||
{
|
||||
side: 'UA',
|
||||
title: 'a',
|
||||
url: 'https://a.test/',
|
||||
publisher: 'A',
|
||||
publishedAt: '2026-10-28T09:00:00Z',
|
||||
},
|
||||
{
|
||||
side: 'RU',
|
||||
title: 'b',
|
||||
url: 'https://b.test/',
|
||||
publisher: 'B',
|
||||
publishedAt: '2026-10-28T09:20:00Z',
|
||||
},
|
||||
],
|
||||
image: { url: 'https://a.test/p.jpg', publisher: 'A' },
|
||||
...extra,
|
||||
});
|
||||
|
||||
test('payloads are validated record by record; empty and malformed payloads', () => {
|
||||
const hotspots = normalizeHotspotsPayload({
|
||||
hotspots: [
|
||||
{
|
||||
id: 'ua',
|
||||
name: 'UA',
|
||||
bbox: [22, 44, 42, 56],
|
||||
parties: ['UA', 'RU', '<x>'],
|
||||
counts: { last24h: 3 },
|
||||
},
|
||||
{ id: 'bad', name: 'Bad', bbox: [42, 44, 22, 56] },
|
||||
{ id: '../x', name: 'Bad id', bbox: [22, 44, 42, 56] },
|
||||
],
|
||||
ingest: { lastRunAt: '2026-10-28T10:00:00Z' },
|
||||
});
|
||||
assert.deepEqual(
|
||||
hotspots.hotspots.map((h) => [h.id, h.parties, h.last24h]),
|
||||
[['ua', ['UA', 'RU'], 3]],
|
||||
);
|
||||
assert.equal(hotspots.lastRunAt, '2026-10-28T10:00:00.000Z');
|
||||
assert.equal(normalizeHotspotsPayload({}), null);
|
||||
assert.equal(normalizeHotspotsPayload(null), null);
|
||||
assert.deepEqual(normalizeHotspotsPayload({ hotspots: [] }).hotspots, []);
|
||||
|
||||
const feed = normalizeFeedPayload({
|
||||
reports: [
|
||||
{
|
||||
id: 'r_1',
|
||||
title: ' Strike on Kharkiv ',
|
||||
url: 'https://x.test/a',
|
||||
publishedAt: '2026-10-28T09:00:00Z',
|
||||
geo: { lat: 50, lon: 36, mappable: true },
|
||||
media: ['video', 'video', 'audio'],
|
||||
event: { size: 3, image: { url: 'http://x.test/p.jpg' } },
|
||||
},
|
||||
{
|
||||
id: 'r_2',
|
||||
title: 'Bad link',
|
||||
url: 'javascript:alert(1)',
|
||||
publishedAt: '2026-10-28T09:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 'r_3',
|
||||
title: 'Bad geo',
|
||||
url: 'https://user:[email protected]/c',
|
||||
publishedAt: '2026-10-28T09:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 'r_4',
|
||||
title: 'Off the globe',
|
||||
url: 'https://x.test/d',
|
||||
publishedAt: '2026-10-28T09:00:00Z',
|
||||
geo: { lat: 200, lon: 36 },
|
||||
},
|
||||
],
|
||||
nextBefore: '2026-10-28T08:00:00Z',
|
||||
});
|
||||
assert.deepEqual(
|
||||
feed.reports.map((r) => [r.id, r.title, Boolean(r.geo), r.pins.length]),
|
||||
[
|
||||
['r_1', 'Strike on Kharkiv', true, 1],
|
||||
['r_4', 'Off the globe', false, 0],
|
||||
],
|
||||
);
|
||||
assert.deepEqual(feed.reports[0].media, ['video']);
|
||||
// A picture must be HTTPS on the publisher's site.
|
||||
assert.equal(feed.reports[0].event.image, null);
|
||||
assert.equal(feed.nextBefore, '2026-10-28T08:00:00.000Z');
|
||||
assert.equal(normalizeFeedPayload({ reports: 'x' }), null);
|
||||
assert.deepEqual(normalizeFeedPayload({ reports: [] }), {
|
||||
reports: [],
|
||||
nextBefore: null,
|
||||
});
|
||||
});
|
||||
|
||||
test("an event's clip is kept only as an HTTPS file a browser plays itself", () => {
|
||||
const clip = (video) =>
|
||||
normalizeFeedPayload({
|
||||
reports: [
|
||||
{
|
||||
id: 'r',
|
||||
title: 'T',
|
||||
url: 'https://x.test/r',
|
||||
publishedAt: '2026-10-28T09:00:00Z',
|
||||
event: {
|
||||
size: 1,
|
||||
image: { url: 'https://cdn.test/p.jpg', publisher: 'P', video },
|
||||
},
|
||||
},
|
||||
],
|
||||
}).reports[0].event.image.video;
|
||||
assert.equal(
|
||||
clip('https://cdn.test/v.mp4?token=a'),
|
||||
'https://cdn.test/v.mp4?token=a',
|
||||
);
|
||||
assert.equal(clip('https://cdn.test/v.webm'), 'https://cdn.test/v.webm');
|
||||
assert.equal(clip('http://cdn.test/v.mp4'), undefined);
|
||||
assert.equal(clip('https://cdn.test/v.m3u8'), undefined);
|
||||
assert.equal(clip(undefined), undefined);
|
||||
});
|
||||
|
||||
test('outlines keep valid rings, borders and named disputed areas', () => {
|
||||
const ring = [
|
||||
[30, 45],
|
||||
[31, 45],
|
||||
[31, 46],
|
||||
];
|
||||
const outline = normalizeOutlinePayload({
|
||||
polygons: [{ outer: ring, holes: [[[0, 0]]] }, { outer: [[1, 2]] }],
|
||||
borders: [ring, 'x'],
|
||||
disputed: [
|
||||
{
|
||||
name: 'Crimea',
|
||||
kind: 'held',
|
||||
heldBy: 'RU',
|
||||
claimedBy: 'UA',
|
||||
rings: [ring],
|
||||
},
|
||||
{ name: 'No rings', rings: [] },
|
||||
{ name: 'Odd kind', kind: 'zzz', heldBy: 'nope', rings: [ring] },
|
||||
],
|
||||
});
|
||||
assert.equal(outline.polygons.length, 1);
|
||||
assert.deepEqual(outline.polygons[0].holes, []);
|
||||
assert.equal(outline.borders.length, 1);
|
||||
assert.deepEqual(
|
||||
outline.disputed.map((d) => [d.name, d.kind, d.heldBy]),
|
||||
[
|
||||
['Crimea', 'held', 'RU'],
|
||||
['Odd kind', 'held', null],
|
||||
],
|
||||
);
|
||||
assert.deepEqual(normalizeOutlinePayload(null), {
|
||||
polygons: [],
|
||||
borders: [],
|
||||
disputed: [],
|
||||
area: null,
|
||||
});
|
||||
// Indonesia's 208 islands are all kept.
|
||||
const islands = Array.from({ length: 208 }, () => ({ outer: ring }));
|
||||
assert.equal(
|
||||
normalizeOutlinePayload({ polygons: islands }).polygons.length,
|
||||
208,
|
||||
);
|
||||
});
|
||||
|
||||
test('a point outline names its area, and Local keeps to it', () => {
|
||||
const box = [
|
||||
[35, 48],
|
||||
[37, 48],
|
||||
[37, 50.5],
|
||||
[35, 50.5],
|
||||
];
|
||||
const { area, polygons } = normalizeOutlinePayload({
|
||||
area: { key: 'US-TX', name: 'Texas', kind: 'region', country: 'US' },
|
||||
polygons: [{ outer: box, holes: [] }],
|
||||
});
|
||||
assert.deepEqual(area, {
|
||||
key: 'US-TX',
|
||||
name: 'Texas',
|
||||
kind: 'region',
|
||||
country: 'US',
|
||||
});
|
||||
assert.equal(areaLabel(area), 'Texas, United States');
|
||||
assert.equal(
|
||||
areaLabel({ ...area, kind: 'country', country: 'UA' }),
|
||||
'Ukraine',
|
||||
);
|
||||
// A disputed area is named as itself, never as either side's.
|
||||
assert.equal(
|
||||
areaLabel({ key: 'disputed:Crimea', name: 'Crimea', kind: 'disputed' }),
|
||||
'Crimea',
|
||||
);
|
||||
assert.equal(normalizeOutlinePayload({ area: { key: 'X' } }).area, null);
|
||||
const at = (id, lat, lon) =>
|
||||
report(id, '2026-10-28T09:00:00Z', {
|
||||
pins: [{ lat, lon, mappable: true }],
|
||||
});
|
||||
const reports = [at('inside', 50, 36), at('beyond', 49, 39)];
|
||||
const filters = normalizeFilters({ minSeverity: 0 });
|
||||
const centre = { lat: 49, lon: 36 };
|
||||
const now = Date.parse('2026-10-28T10:00:00Z');
|
||||
const ids = (area) =>
|
||||
reportsInView(reports, centre, filters, now, 10, undefined, area).map(
|
||||
(r) => r.id,
|
||||
);
|
||||
// Within 500 km both; inside the area only the one.
|
||||
assert.deepEqual(ids(null), ['inside', 'beyond']);
|
||||
assert.deepEqual(ids(polygons), ['inside']);
|
||||
assert.ok(inPolygons(polygons, { lat: 49, lon: 36 }));
|
||||
assert.ok(!inPolygons([{ outer: box, holes: [box] }], { lat: 49, lon: 36 }));
|
||||
});
|
||||
|
||||
test('feed pages merge newest first without duplicates', () => {
|
||||
const a = report('a', '2026-10-28T10:00:00Z');
|
||||
const b = report('b', '2026-10-28T09:00:00Z');
|
||||
const c = report('c', '2026-10-28T08:00:00Z');
|
||||
let feed = mergeFeedPage(
|
||||
{ items: [] },
|
||||
{ reports: [a, b], nextBefore: 'B' },
|
||||
'replace',
|
||||
NOW,
|
||||
);
|
||||
assert.deepEqual(
|
||||
[feed.items.map((r) => r.id), feed.nextBefore],
|
||||
[['a', 'b'], 'B'],
|
||||
);
|
||||
feed = mergeFeedPage(
|
||||
feed,
|
||||
{ reports: [b, c], nextBefore: null },
|
||||
'append',
|
||||
NOW,
|
||||
);
|
||||
assert.deepEqual(
|
||||
[feed.items.map((r) => r.id), feed.nextBefore],
|
||||
[['a', 'b', 'c'], null],
|
||||
);
|
||||
const newer = report('n', '2026-10-28T11:00:00Z');
|
||||
feed = mergeFeedPage(
|
||||
{ ...feed, nextBefore: 'C' },
|
||||
{ reports: [newer, a], nextBefore: 'X' },
|
||||
'head',
|
||||
NOW + 3_600_000,
|
||||
);
|
||||
assert.deepEqual(
|
||||
[feed.items.map((r) => r.id), feed.nextBefore],
|
||||
[['n', 'a', 'b', 'c'], 'C'],
|
||||
);
|
||||
assert.deepEqual(
|
||||
mergeFeedPage({ items: [] }, { reports: [], nextBefore: null }, 'replace'),
|
||||
{ items: [], nextBefore: null },
|
||||
);
|
||||
});
|
||||
|
||||
test('a head page that does not reach the rows held starts the list over', () => {
|
||||
const held = report('h', '2026-10-28T06:00:00Z');
|
||||
const fresh = report('n', '2026-10-28T09:30:00Z');
|
||||
// More than a page arrived since the last refresh (a suspended tab): the
|
||||
// reports between this page and the rows held are behind its cursor.
|
||||
const feed = mergeFeedPage(
|
||||
{ items: [held], nextBefore: 'OLD' },
|
||||
{ reports: [fresh], nextBefore: 'NEW' },
|
||||
'head',
|
||||
NOW,
|
||||
);
|
||||
assert.deepEqual(
|
||||
[feed.items.map((r) => r.id), feed.nextBefore],
|
||||
[['n'], 'NEW'],
|
||||
);
|
||||
});
|
||||
|
||||
test('the feed list keeps only the last 24 hours and at most its cap', () => {
|
||||
const fresh = report('f', '2026-10-28T09:00:00Z');
|
||||
const stale = report('s', '2026-10-27T09:00:00Z');
|
||||
const ahead = report('x', '2026-10-28T11:00:00Z');
|
||||
// A long session: yesterday's rows already held fall out on the next merge.
|
||||
const feed = mergeFeedPage(
|
||||
{ items: [stale], nextBefore: 'S' },
|
||||
{ reports: [fresh, ahead], nextBefore: 'F' },
|
||||
'head',
|
||||
NOW,
|
||||
);
|
||||
assert.deepEqual(
|
||||
feed.items.map((r) => r.id),
|
||||
['f'],
|
||||
);
|
||||
const many = Array.from({ length: 30 }, (_, i) =>
|
||||
report(`r${i}`, new Date(NOW - (i + 1) * 60_000).toISOString()),
|
||||
);
|
||||
const capped = mergeFeedPage(
|
||||
{ items: [] },
|
||||
{ reports: many, nextBefore: null },
|
||||
'replace',
|
||||
NOW,
|
||||
10,
|
||||
);
|
||||
assert.equal(capped.items.length, 10);
|
||||
assert.equal(capped.items[0].id, 'r0');
|
||||
assert.equal(capped.items.at(-1).id, 'r9');
|
||||
// Everything outside the window: an empty list, not an error.
|
||||
assert.deepEqual(
|
||||
mergeFeedPage(
|
||||
{ items: [] },
|
||||
{ reports: [stale], nextBefore: null },
|
||||
'replace',
|
||||
NOW,
|
||||
).items,
|
||||
[],
|
||||
);
|
||||
});
|
||||
|
||||
test('filters default to significant news and map to a last-24-hours query', () => {
|
||||
const hotspots = [{ id: 'ua' }, { id: 'me' }];
|
||||
const filters = normalizeFilters(
|
||||
{ hotspot: 'ua', category: 'nope', minSeverity: 9 },
|
||||
hotspots,
|
||||
);
|
||||
assert.deepEqual(filters, {
|
||||
hotspot: 'ua',
|
||||
category: 'all',
|
||||
minSeverity: 2,
|
||||
section: 'conflicts',
|
||||
hours: null,
|
||||
});
|
||||
assert.equal(
|
||||
normalizeFilters({ section: 'local' }, hotspots).section,
|
||||
'local',
|
||||
);
|
||||
assert.equal(
|
||||
normalizeFilters({ section: 'nope' }, hotspots).section,
|
||||
'conflicts',
|
||||
);
|
||||
assert.equal(normalizeFilters({ hours: 6 }, hotspots).hours, 6);
|
||||
assert.equal(normalizeFilters({ hours: 5 }, hotspots).hours, null);
|
||||
assert.equal(normalizeFilters({ minSeverity: 0 }, hotspots).minSeverity, 0);
|
||||
assert.equal(normalizeFilters({ hotspot: 'gone' }, hotspots).hotspot, 'all');
|
||||
assert.equal(
|
||||
newsFeedQuery(
|
||||
feedQueryFor(filters, { before: '2026-10-28T08:00:00.000Z' }),
|
||||
),
|
||||
'hotspot=ua&before=2026-10-28T08%3A00%3A00.000Z&limit=60&relevance=core%2Crelated&today=1&events=1',
|
||||
);
|
||||
// The Conflicts feed reads the same whichever section is chosen.
|
||||
assert.equal(
|
||||
newsFeedQuery(feedQueryFor({ ...filters, section: 'local' })),
|
||||
newsFeedQuery(feedQueryFor(filters)),
|
||||
);
|
||||
});
|
||||
|
||||
test('only the last 24 hours pass, and the severity floor applies', () => {
|
||||
const filters = normalizeFilters();
|
||||
const fresh = report('f', '2026-10-28T09:00:00Z', { severity: 2 });
|
||||
const minor = report('m', '2026-10-28T09:00:00Z', { severity: 1 });
|
||||
const old = report('o', '2026-10-27T09:00:00Z', { severity: 3 });
|
||||
assert.equal(withinNewsWindow(fresh, NOW), true);
|
||||
assert.equal(withinNewsWindow(old, NOW), false);
|
||||
assert.equal(withinNewsWindow({ publishedAt: 'x' }, NOW), false);
|
||||
// Clock skew up to 15 min ahead passes; further ahead is not news yet.
|
||||
const skew = report('k', '2026-10-28T10:14:00Z');
|
||||
const future = report('z', '2026-10-28T10:16:00Z');
|
||||
assert.equal(withinNewsWindow(skew, NOW), true);
|
||||
assert.equal(withinNewsWindow(future, NOW), false);
|
||||
assert.deepEqual(
|
||||
[fresh, minor, old]
|
||||
.filter((r) => passesFilters(r, filters, NOW))
|
||||
.map((r) => r.id),
|
||||
['f'],
|
||||
);
|
||||
assert.equal(visibleOnMap(minor, { ...filters, minSeverity: 0 }, NOW), true);
|
||||
assert.equal(visibleOnMap(fresh, { ...filters, hotspot: 'me' }, NOW), false);
|
||||
});
|
||||
|
||||
test('ageWords says now, minutes or hours', () => {
|
||||
assert.equal(ageWords('2026-10-28T09:59:30Z', NOW), 'now');
|
||||
assert.equal(ageWords('2026-10-28T09:55:00Z', NOW), '5 min');
|
||||
assert.equal(ageWords('2026-10-28T07:10:00Z', NOW), '2 h');
|
||||
assert.equal(ageWords('2026-10-26T07:10:00Z', NOW), '24 h');
|
||||
assert.equal(ageWords('not a date', NOW), '');
|
||||
});
|
||||
|
||||
test('markers spread deterministically near their place; source link line', () => {
|
||||
const r = report('r_spread', '2026-10-28T10:00:00Z');
|
||||
const p1 = reportMarkerPosition(r);
|
||||
assert.deepEqual(reportMarkerPosition(r), p1);
|
||||
assert.ok(Math.abs(p1.lat - 50) < 0.02 && Math.abs(p1.lon - 36) < 0.04);
|
||||
assert.notDeepEqual(
|
||||
reportMarkerPosition(report('r_other', r.publishedAt)),
|
||||
p1,
|
||||
);
|
||||
assert.equal(
|
||||
sourceLinkLabel('https://www.reliefweb.int/report/x'),
|
||||
'Source: reliefweb.int ↗',
|
||||
);
|
||||
assert.equal(sourceLinkLabel('not a url'), '');
|
||||
});
|
||||
|
||||
test('beacons carry a focus, a size by activity and a trend only against a prior day', () => {
|
||||
const { hotspots } = normalizeHotspotsPayload({
|
||||
hotspots: [
|
||||
{
|
||||
id: 'a',
|
||||
name: 'A',
|
||||
bbox: [20, 40, 40, 50],
|
||||
focus: { lat: 45, lon: 30 },
|
||||
counts: { last24h: 120, prev24h: 80 },
|
||||
},
|
||||
{
|
||||
id: 'b',
|
||||
name: 'B',
|
||||
bbox: [20, 40, 40, 50],
|
||||
focus: { lat: 80, lon: 30 },
|
||||
},
|
||||
],
|
||||
});
|
||||
assert.deepEqual(
|
||||
hotspots.map((h) => h.focus),
|
||||
[
|
||||
{ lat: 45, lon: 30 },
|
||||
{ lat: 45, lon: 30 },
|
||||
],
|
||||
);
|
||||
assert.equal(hotspotTrend(120, 80), '▲');
|
||||
assert.equal(hotspotTrend(50, 80), '▼');
|
||||
assert.equal(hotspotTrend(85, 80), '');
|
||||
assert.equal(hotspotTrend(40, 0), '');
|
||||
assert.equal(beaconPixelSize(0), 10);
|
||||
assert.equal(beaconPixelSize(10_000), 26);
|
||||
assert.equal(
|
||||
hotspotLabel({ id: 'ua-ru-war', name: 'Russia–Ukraine war' }),
|
||||
'Ukraine–Russia',
|
||||
);
|
||||
assert.equal(hotspotLabel({ id: 'new-one', name: 'New one' }), 'New one');
|
||||
assert.equal(
|
||||
hotspotLabel({ id: 'x', name: 'X', catchAll: true }),
|
||||
'Elsewhere',
|
||||
);
|
||||
assert.equal(
|
||||
hotspotLabel({ id: 'worldwide', name: 'Worldwide', catchAll: true }),
|
||||
'Worldwide',
|
||||
);
|
||||
});
|
||||
|
||||
test('marker style: severity fill, attestation rim, size by sources, fading with age', () => {
|
||||
const r = report('r_style', '2026-10-28T10:00:00Z', {
|
||||
severity: 2,
|
||||
event: event({
|
||||
status: 'claimed',
|
||||
size: 4,
|
||||
lastAt: '2026-10-28T10:00:00Z',
|
||||
}),
|
||||
});
|
||||
const fresh = markerStyle(r, NOW);
|
||||
assert.equal(fresh.severity, 3); // the event's, when higher than the report's
|
||||
assert.equal(fresh.rim, 'claimed');
|
||||
assert.equal(fresh.size, eventPixelSize(4));
|
||||
// The icon is half the disc: no marker is too small to read it.
|
||||
assert.equal(eventPixelSize(1), 24);
|
||||
assert.equal(eventPixelSize(1000), 36);
|
||||
assert.equal(fresh.alpha, 1);
|
||||
assert.equal(markerStyle(r, NOW + 48 * 3_600_000).alpha, 0.45);
|
||||
assert.equal(reportSeverity({ category: 'political' }), 0);
|
||||
assert.equal(reportSeverity({ category: 'strike' }), 1);
|
||||
});
|
||||
|
||||
test('picture cards: physical, two or more sources, major or pressing, at most ten', () => {
|
||||
const big = report('big', '2026-10-28T09:30:00Z', { event: event() });
|
||||
const statement = report('st', '2026-10-28T09:30:00Z', {
|
||||
category: 'political',
|
||||
event: event(),
|
||||
});
|
||||
const lone = report('lone', '2026-10-28T09:30:00Z', {
|
||||
event: event({ size: 1 }),
|
||||
});
|
||||
const stale = report('stale', '2026-10-28T01:00:00Z', {
|
||||
event: event({ severity: 2, lastAt: '2026-10-28T01:00:00Z' }),
|
||||
});
|
||||
assert.equal(isPressing(big, NOW), true);
|
||||
assert.deepEqual(
|
||||
cardEvents([statement, lone, stale, big], NOW).map((r) => r.id),
|
||||
['big'],
|
||||
);
|
||||
const many = Array.from({ length: 14 }, (_, i) =>
|
||||
report(`m${i}`, '2026-10-28T09:30:00Z', { event: event() }),
|
||||
);
|
||||
assert.equal(cardEvents(many, NOW).length, 10);
|
||||
const view = cardView(big, NOW);
|
||||
assert.equal(view.image, 'https://a.test/p.jpg');
|
||||
assert.equal(view.credit, 'A');
|
||||
assert.equal(view.meta, '30 min · 6 sources · UA, RU');
|
||||
assert.equal(cardView(lone, NOW).image, null);
|
||||
});
|
||||
|
||||
test('feed cards: headline, meta parts, sides and chips', () => {
|
||||
const r = report('fc', '2026-10-28T09:00:00Z', {
|
||||
title: 'Удар по Харкову',
|
||||
titleEn: 'Strike on Kharkiv',
|
||||
affiliation: 'military',
|
||||
media: ['video', 'photo'],
|
||||
geo: { lat: 50, lon: 36, place: 'Kharkiv', mappable: true, byModel: true },
|
||||
event: event({ lastAt: '2026-10-28T09:50:00Z' }),
|
||||
});
|
||||
const view = feedCardView(r, NOW);
|
||||
assert.equal(view.title, 'Strike on Kharkiv');
|
||||
assert.equal(view.original, 'Удар по Харкову');
|
||||
assert.equal(view.placedByModel, true);
|
||||
assert.equal(view.severityLabel, 'Major');
|
||||
assert.equal(view.color, '#ff4444');
|
||||
assert.equal(view.category, 'Strike');
|
||||
assert.equal(view.place, 'Kharkiv');
|
||||
assert.equal(view.sources, '6 sources');
|
||||
assert.equal(view.age, '10 min');
|
||||
assert.equal(view.sides, 'Reported by UA sources · RU sources');
|
||||
assert.deepEqual(view.picture, { url: 'https://a.test/p.jpg', credit: 'A' });
|
||||
assert.deepEqual(
|
||||
view.chips.map((c) => [c.kind, c.label]),
|
||||
[
|
||||
['official', 'Official'],
|
||||
['confirmed', 'Reported by both sides'],
|
||||
['media', 'Video'],
|
||||
['media', 'Photos'],
|
||||
],
|
||||
);
|
||||
assert.deepEqual(
|
||||
view.others.map((o) => o.side),
|
||||
['RU'],
|
||||
);
|
||||
// A lone report: its own side, no picture, one source.
|
||||
const single = feedCardView(report('s', '2026-10-28T09:00:00Z'), NOW);
|
||||
assert.equal(single.sides, 'Reported by UA sources');
|
||||
assert.equal(single.picture, null);
|
||||
// A one-source event (a Telegram post) shows its picture and its clip in
|
||||
// the panel, though the globe's picture cards need two sources.
|
||||
const post = report('p', '2026-10-28T09:00:00Z', {
|
||||
event: {
|
||||
size: 1,
|
||||
sides: [],
|
||||
image: {
|
||||
url: 'https://cdn4.telesco.pe/file/v.jpg',
|
||||
publisher: 'Channel',
|
||||
video: 'https://cdn4.telesco.pe/file/v.mp4?token=x',
|
||||
},
|
||||
},
|
||||
});
|
||||
assert.deepEqual(feedCardView(post, NOW).picture, {
|
||||
url: 'https://cdn4.telesco.pe/file/v.jpg',
|
||||
credit: 'Channel',
|
||||
video: 'https://cdn4.telesco.pe/file/v.mp4?token=x',
|
||||
});
|
||||
assert.equal(single.original, null);
|
||||
assert.equal(sidesLine({ side: 'unknown' }), '');
|
||||
});
|
||||
|
||||
test('event sides older than a day are left out of the card and its sides line', () => {
|
||||
const r = report('w', '2026-10-28T09:00:00Z', {
|
||||
event: event({
|
||||
sides: [
|
||||
{
|
||||
side: 'UA',
|
||||
title: 'a',
|
||||
url: 'https://a.test/',
|
||||
publisher: 'A',
|
||||
publishedAt: '2026-10-28T08:00:00Z',
|
||||
},
|
||||
{
|
||||
side: 'RU',
|
||||
title: 'old',
|
||||
url: 'https://b.test/',
|
||||
publisher: 'B',
|
||||
publishedAt: '2026-10-26T08:00:00Z',
|
||||
},
|
||||
{
|
||||
side: 'unknown',
|
||||
title: 'c',
|
||||
url: 'https://c.test/',
|
||||
publisher: 'C',
|
||||
publishedAt: '2026-10-28T09:10:00Z',
|
||||
},
|
||||
// No date: nothing shows it is recent.
|
||||
{ side: 'IL', title: 'd', url: 'https://d.test/', publisher: 'D' },
|
||||
],
|
||||
}),
|
||||
});
|
||||
const view = feedCardView(r, NOW);
|
||||
assert.deepEqual(
|
||||
view.others.map((o) => [o.side, o.title]),
|
||||
[['Unattributed', 'c']],
|
||||
);
|
||||
// The unattributed side is not named in the sides line.
|
||||
assert.equal(view.sides, 'Reported by UA sources');
|
||||
assert.equal(cardView(r, NOW).meta, '30 min · 6 sources · UA, Unattributed');
|
||||
// All sides outside the window: no others, the report's own side remains.
|
||||
const stale = report('v', '2026-10-28T09:00:00Z', {
|
||||
event: event({
|
||||
sides: [
|
||||
{
|
||||
side: 'RU',
|
||||
title: 'old',
|
||||
url: 'https://b.test/',
|
||||
publisher: 'B',
|
||||
publishedAt: '2026-10-26T08:00:00Z',
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
assert.deepEqual(feedCardView(stale, NOW).others, []);
|
||||
assert.equal(feedCardView(stale, NOW).sides, 'Reported by UA sources');
|
||||
});
|
||||
|
||||
test('in view: half-degree cells and reports within 500 km of the centre', () => {
|
||||
assert.equal(viewCell({ lat: 50.2, lon: 36.7 }), '100:73');
|
||||
assert.equal(viewCell({ lat: 50.4, lon: 36.9 }), '100:73');
|
||||
assert.notEqual(viewCell({ lat: 50.6, lon: 36.7 }), '100:73');
|
||||
assert.ok(
|
||||
Math.abs(distanceKm({ lat: 0, lon: 0 }, { lat: 0, lon: 1 }) - 111.2) < 0.5,
|
||||
);
|
||||
const filters = normalizeFilters({ minSeverity: 0 });
|
||||
const near = report('near', '2026-10-28T09:00:00Z', { severity: 1 });
|
||||
const major = report('major', '2026-10-28T08:00:00Z', { severity: 3 });
|
||||
const far = report('far', '2026-10-28T09:00:00Z', {
|
||||
pins: [{ lat: 31.5, lon: 34.4, place: 'Gaza', mappable: true }],
|
||||
});
|
||||
const old = report('old', '2026-10-27T08:00:00Z');
|
||||
const centre = { lat: 49, lon: 36 };
|
||||
assert.ok(distanceKm(centre, far.pins[0]) > NEWS_IN_VIEW_RADIUS_KM);
|
||||
assert.deepEqual(
|
||||
reportsInView([near, far, old, major], centre, filters, NOW).map(
|
||||
(r) => r.id,
|
||||
),
|
||||
['near', 'major'],
|
||||
);
|
||||
assert.deepEqual(reportsInView([near], null, filters, NOW), []);
|
||||
assert.deepEqual(reportsInView([], centre, filters, NOW), []);
|
||||
});
|
||||
|
||||
test('a server may serve fewer hours than the day, never more', () => {
|
||||
assert.equal(newsWindowMs(12), 12 * 3_600_000);
|
||||
assert.equal(newsWindowMs(24), 24 * 3_600_000);
|
||||
for (const bad of [0, 25, 12.5, '12', null, undefined])
|
||||
assert.equal(newsWindowMs(bad), 24 * 3_600_000);
|
||||
const page = {
|
||||
reports: [
|
||||
report('fresh', '2026-10-28T02:00:00Z'),
|
||||
report('old', '2026-10-27T20:00:00Z'),
|
||||
],
|
||||
nextBefore: null,
|
||||
};
|
||||
const empty = { items: [], nextBefore: null };
|
||||
const ids = (windowMs) =>
|
||||
mergeFeedPage(empty, page, 'replace', NOW, undefined, windowMs).items.map(
|
||||
(r) => r.id,
|
||||
);
|
||||
assert.deepEqual(ids(newsWindowMs(12)), ['fresh']);
|
||||
assert.deepEqual(ids(newsWindowMs(24)), ['fresh', 'old']);
|
||||
});
|
||||
|
||||
test('the hotspots answer carries the window it was counted over', () => {
|
||||
const base = {
|
||||
hotspots: [],
|
||||
ingest: { lastRunAt: '2026-10-28T09:00:00Z' },
|
||||
};
|
||||
assert.equal(
|
||||
normalizeHotspotsPayload({ ...base, windowHours: 12 }).windowHours,
|
||||
12,
|
||||
);
|
||||
assert.equal(normalizeHotspotsPayload(base).windowHours, null);
|
||||
assert.equal(
|
||||
normalizeHotspotsPayload({ ...base, windowHours: 48 }).windowHours,
|
||||
null,
|
||||
);
|
||||
const shorter = normalizeHotspotsPayload({
|
||||
...base,
|
||||
windowHours: 3,
|
||||
maxWindowHours: 12,
|
||||
});
|
||||
assert.deepEqual([shorter.windowHours, shorter.maxWindowHours], [3, 12]);
|
||||
assert.equal(normalizeHotspotsPayload(base).maxWindowHours, null);
|
||||
});
|
||||
|
||||
test('the window choices stop at the window the server serves', () => {
|
||||
assert.deepEqual(newsWindowChoices(24), [24, 12, 6, 3, 1]);
|
||||
assert.deepEqual(newsWindowChoices(12), [12, 6, 3, 1]);
|
||||
assert.deepEqual(newsWindowChoices(8), [8, 6, 3, 1]);
|
||||
assert.deepEqual(newsWindowChoices(1), [1]);
|
||||
assert.deepEqual(newsWindowChoices(null), [24, 12, 6, 3, 1]);
|
||||
});
|
||||
|
||||
test('a checked severity keeps saying who set it', () => {
|
||||
const page = normalizeFeedPayload({
|
||||
reports: ['label', 'model', 'guess'].map((by, i) => ({
|
||||
...report(`r${i}`, '2026-10-28T09:00:00Z'),
|
||||
severity: 2,
|
||||
severityBy: by,
|
||||
})),
|
||||
});
|
||||
assert.deepEqual(
|
||||
page.reports.map((r) => r.severityBy),
|
||||
['label', 'model', 'rules'],
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,366 @@
|
||||
// Validate /api/news payloads before they reach the scene or the DOM. Every
|
||||
// string is bounded, every URL is http(s), every position is finite; a record
|
||||
// that fails is dropped, a payload that fails is rejected whole. A portable
|
||||
// export (layers/news/source): no i18n here.
|
||||
|
||||
const CATEGORY = /^[a-z][a-z-]{1,31}$/;
|
||||
const CODE = /^[A-Za-z][A-Za-z0-9-]{0,31}$/;
|
||||
const ID = /^[a-z0-9][a-z0-9_-]{0,63}$/i;
|
||||
const EVENT_STATUSES = Object.freeze([
|
||||
'both-sides',
|
||||
'independent',
|
||||
'claimed',
|
||||
'reported',
|
||||
'side',
|
||||
'single',
|
||||
]);
|
||||
|
||||
const text = (value, max) =>
|
||||
typeof value === 'string' && value.trim()
|
||||
? value.replace(/\s+/g, ' ').trim().slice(0, max)
|
||||
: null;
|
||||
const finite = (value, min, max) =>
|
||||
Number.isFinite(value) && value >= min && value <= max ? value : null;
|
||||
const iso = (value) => {
|
||||
const ms = Date.parse(value);
|
||||
return Number.isFinite(ms) ? new Date(ms).toISOString() : null;
|
||||
};
|
||||
const code = (value) =>
|
||||
typeof value === 'string' && CODE.test(value) ? value : null;
|
||||
const severity = (value) =>
|
||||
Number.isInteger(value) && value >= 0 && value <= 3 ? value : null;
|
||||
|
||||
/** An http(s) URL without credentials, as its normalised href, or null. */
|
||||
export function httpUrl(value) {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return ['http:', 'https:'].includes(url.protocol) &&
|
||||
!url.username &&
|
||||
!url.password
|
||||
? url.href
|
||||
: null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeBbox(bbox) {
|
||||
if (!Array.isArray(bbox) || bbox.length !== 4) return null;
|
||||
const [west, south, east, north] = bbox;
|
||||
if (
|
||||
finite(west, -180, 180) === null ||
|
||||
finite(east, -180, 180) === null ||
|
||||
finite(south, -90, 90) === null ||
|
||||
finite(north, -90, 90) === null ||
|
||||
west >= east ||
|
||||
south >= north
|
||||
)
|
||||
return null;
|
||||
return [west, south, east, north];
|
||||
}
|
||||
|
||||
/** Beacon position: the curated focus point, else the bbox centre. */
|
||||
function normalizeFocus(focus, [west, south, east, north]) {
|
||||
const lat = finite(focus?.lat, south, north);
|
||||
const lon = finite(focus?.lon, west, east);
|
||||
return lat !== null && lon !== null
|
||||
? { lat, lon }
|
||||
: { lat: (south + north) / 2, lon: (west + east) / 2 };
|
||||
}
|
||||
|
||||
function normalizeDeveloping(items) {
|
||||
const out = [];
|
||||
for (const raw of Array.isArray(items) ? items.slice(0, 16) : []) {
|
||||
const lat = finite(raw?.focus?.lat, -90, 90);
|
||||
const lon = finite(raw?.focus?.lon, -180, 180);
|
||||
const country =
|
||||
typeof raw?.country === 'string' && /^[A-Z]{2}$/.test(raw.country)
|
||||
? raw.country
|
||||
: null;
|
||||
if (lat === null || lon === null || !country) continue;
|
||||
// A state where the catch-all flags states ("US-FL"), else the country.
|
||||
const area =
|
||||
typeof raw.area === 'string' && /^[A-Z]{2}-[A-Z0-9]{1,3}$/.test(raw.area)
|
||||
? raw.area
|
||||
: null;
|
||||
out.push({
|
||||
country,
|
||||
key: area || country,
|
||||
name: text(raw.name, 80) || country,
|
||||
events: Math.max(0, Math.floor(Number(raw.events) || 0)),
|
||||
reports: Math.max(0, Math.floor(Number(raw.reports) || 0)),
|
||||
focus: { lat, lon },
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const hoursOrNull = (hours) =>
|
||||
Number.isInteger(hours) && hours >= 1 && hours <= 24 ? hours : null;
|
||||
|
||||
/**
|
||||
* `/api/news/hotspots` → `{hotspots, categories, lastRunAt, windowHours,
|
||||
* maxWindowHours}`, or null when the payload has no hotspot list.
|
||||
* `windowHours` is the window the counts cover and `maxWindowHours` the
|
||||
* longest the server serves this reader; each is null when the server names
|
||||
* none.
|
||||
*/
|
||||
export function normalizeHotspotsPayload(payload) {
|
||||
if (!Array.isArray(payload?.hotspots)) return null;
|
||||
const hotspots = [];
|
||||
for (const raw of payload.hotspots.slice(0, 64)) {
|
||||
const id = typeof raw?.id === 'string' && ID.test(raw.id) ? raw.id : null;
|
||||
const name = text(raw?.name, 80);
|
||||
const bbox = normalizeBbox(raw?.bbox);
|
||||
if (!id || !name || !bbox) continue;
|
||||
const counts = raw.counts || {};
|
||||
hotspots.push({
|
||||
id,
|
||||
name,
|
||||
kind: text(raw.kind, 16) || 'conflict',
|
||||
catchAll: raw.catchAll === true,
|
||||
developing: normalizeDeveloping(raw.developing),
|
||||
bbox,
|
||||
parties: Array.isArray(raw.parties)
|
||||
? raw.parties.filter((p) => code(p))
|
||||
: [],
|
||||
last24h: Math.max(0, Math.floor(Number(counts.last24h) || 0)),
|
||||
mapped24h: Math.max(0, Math.floor(Number(counts.mapped24h) || 0)),
|
||||
prev24h: Number.isFinite(counts.prev24h)
|
||||
? Math.max(0, Math.floor(counts.prev24h))
|
||||
: null,
|
||||
focus: normalizeFocus(raw.focus, bbox),
|
||||
latestAt: iso(raw.latestAt),
|
||||
});
|
||||
}
|
||||
return {
|
||||
hotspots,
|
||||
categories: Array.isArray(payload.categories)
|
||||
? payload.categories.filter(
|
||||
(c) => typeof c === 'string' && CATEGORY.test(c),
|
||||
)
|
||||
: [],
|
||||
lastRunAt: iso(payload.ingest?.lastRunAt),
|
||||
windowHours: hoursOrNull(payload.windowHours),
|
||||
maxWindowHours: hoursOrNull(payload.maxWindowHours),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeGeo(geo) {
|
||||
if (!geo || typeof geo !== 'object') return null;
|
||||
const lat = finite(geo.lat, -90, 90);
|
||||
const lon = finite(geo.lon, -180, 180);
|
||||
if (lat === null || lon === null) return null;
|
||||
return {
|
||||
lat,
|
||||
lon,
|
||||
place: text(geo.place, 80),
|
||||
precision: text(geo.precision, 16) || 'city',
|
||||
confidence: finite(geo.confidence, 0, 1) ?? 0,
|
||||
mappable: geo.mappable === true,
|
||||
byModel: geo.method === 'llm',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The event's picture: an HTTPS URL on the publisher's site, and whose it is;
|
||||
* with the post's own clip when it has one a browser plays itself (an HTTPS
|
||||
* MP4 or WebM file), the picture then its poster.
|
||||
*/
|
||||
function eventImage(image) {
|
||||
const url = httpUrl(image?.url);
|
||||
if (!url?.startsWith('https://')) return null;
|
||||
const video = httpUrl(image.video);
|
||||
const playable =
|
||||
video?.startsWith('https://') &&
|
||||
/\.(?:mp4|m4v|webm)$/i.test(new URL(video).pathname);
|
||||
return {
|
||||
url,
|
||||
publisher: text(image.publisher, 80) || '',
|
||||
...(playable ? { video } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** An event summary from `/feed?events=1`: size and one report per side. */
|
||||
function normalizeEvent(event) {
|
||||
if (!event || typeof event !== 'object') return null;
|
||||
const count = (value) => Math.max(1, Math.floor(Number(value) || 1));
|
||||
const sides = [];
|
||||
for (const side of Array.isArray(event.sides)
|
||||
? event.sides.slice(0, 8)
|
||||
: []) {
|
||||
const url = httpUrl(side?.url);
|
||||
const title = text(side?.title, 300);
|
||||
if (!url || !title) continue;
|
||||
sides.push({
|
||||
side: code(side.side) || 'unknown',
|
||||
title,
|
||||
url,
|
||||
publisher: text(side.publisher, 80) || '',
|
||||
publishedAt: iso(side.publishedAt),
|
||||
});
|
||||
}
|
||||
return {
|
||||
id: typeof event.id === 'string' && ID.test(event.id) ? event.id : null,
|
||||
status: EVENT_STATUSES.includes(event.status) ? event.status : null,
|
||||
claimedBy: text(event.claimedBy, 80),
|
||||
reportedSide: code(event.reportedSide),
|
||||
size: count(event.size),
|
||||
reports: count(event.reports),
|
||||
severity: severity(event.severity),
|
||||
firstAt: iso(event.firstAt),
|
||||
lastAt: iso(event.lastAt),
|
||||
sides,
|
||||
image: eventImage(event.image),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeReport(raw) {
|
||||
const id = typeof raw?.id === 'string' && ID.test(raw.id) ? raw.id : null;
|
||||
const title = text(raw?.title, 300);
|
||||
const url = httpUrl(raw?.url);
|
||||
const publishedAt = iso(raw?.publishedAt);
|
||||
if (!id || !title || !url || !publishedAt) return null;
|
||||
const source = raw.source || {};
|
||||
const geo = normalizeGeo(raw.geo);
|
||||
// Map positions: the report's own place plus any other hotspot its title
|
||||
// names (a roundup is pinned in each).
|
||||
const pins = [];
|
||||
for (const place of [
|
||||
geo,
|
||||
...(Array.isArray(raw.locations)
|
||||
? raw.locations.slice(0, 8).map(normalizeGeo)
|
||||
: []),
|
||||
])
|
||||
if (
|
||||
place?.mappable &&
|
||||
!pins.some((p) => p.lat === place.lat && p.lon === place.lon)
|
||||
)
|
||||
pins.push(place);
|
||||
const hotspotId = typeof raw.hotspotId === 'string' ? raw.hotspotId : null;
|
||||
return {
|
||||
id,
|
||||
hotspotId,
|
||||
hotspotIds: Array.isArray(raw.hotspotIds)
|
||||
? raw.hotspotIds.filter((h) => typeof h === 'string').slice(0, 8)
|
||||
: [hotspotId].filter(Boolean),
|
||||
title,
|
||||
url,
|
||||
snippet: text(raw.snippet, 400),
|
||||
publisher: text(raw.publisher, 80) || text(source.name, 80) || '',
|
||||
sourceName: text(source.name, 80) || text(raw.publisher, 80) || '',
|
||||
kind: text(raw.kind, 16) || 'rss',
|
||||
side: code(raw.side) || 'unknown',
|
||||
affiliation: text(raw.affiliation, 32),
|
||||
attribution: text(source.attribution, 120),
|
||||
category:
|
||||
typeof raw.category === 'string' && CATEGORY.test(raw.category)
|
||||
? raw.category
|
||||
: 'other',
|
||||
publishedAt,
|
||||
geo,
|
||||
pins,
|
||||
event: normalizeEvent(raw.event),
|
||||
titleEn: text(raw.titleEn, 200),
|
||||
relevance: ['core', 'related', 'minor'].includes(raw.relevance)
|
||||
? raw.relevance
|
||||
: 'related',
|
||||
severity: severity(raw.severity),
|
||||
severityBy: ['model', 'label'].includes(raw.severityBy)
|
||||
? raw.severityBy
|
||||
: 'rules',
|
||||
claim:
|
||||
raw.claim && typeof raw.claim === 'object'
|
||||
? { by: text(raw.claim.by, 80) }
|
||||
: null,
|
||||
media: Array.isArray(raw.media)
|
||||
? [...new Set(raw.media.filter((m) => m === 'video' || m === 'photo'))]
|
||||
: [],
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeRing(ring) {
|
||||
if (!Array.isArray(ring) || ring.length < 3) return null;
|
||||
const points = [];
|
||||
for (const point of ring.slice(0, 20_000)) {
|
||||
const lon = finite(point?.[0], -180, 180);
|
||||
const lat = finite(point?.[1], -90, 90);
|
||||
if (lon !== null && lat !== null) points.push([lon, lat]);
|
||||
}
|
||||
return points.length >= 3 ? points : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* `/api/news/outline` → `{polygons, borders, disputed, area}`: the dissolved
|
||||
* extent (`{outer, holes}`), the national borders inside it (rings), its
|
||||
* disputed areas and, answering a point, the area named there (else null),
|
||||
* invalid parts dropped.
|
||||
*/
|
||||
export function normalizeOutlinePayload(payload) {
|
||||
const polygons = [];
|
||||
// Above every country's island count (Indonesia's is 208): an outline cut
|
||||
// short leaves islands outside the area, read again on each settle there.
|
||||
for (const raw of Array.isArray(payload?.polygons)
|
||||
? payload.polygons.slice(0, 300)
|
||||
: []) {
|
||||
const outer = normalizeRing(raw?.outer);
|
||||
if (!outer) continue;
|
||||
const holes = (Array.isArray(raw.holes) ? raw.holes.slice(0, 200) : [])
|
||||
.map(normalizeRing)
|
||||
.filter(Boolean);
|
||||
polygons.push({ outer, holes });
|
||||
}
|
||||
const borders = (
|
||||
Array.isArray(payload?.borders) ? payload.borders.slice(0, 50) : []
|
||||
)
|
||||
.map(normalizeRing)
|
||||
.filter(Boolean);
|
||||
const KINDS = ['held', 'self', 'un', 'unclaimed'];
|
||||
const country = (value) =>
|
||||
typeof value === 'string' && /^[A-Z]{2}$/.test(value) ? value : null;
|
||||
const disputed = [];
|
||||
for (const raw of Array.isArray(payload?.disputed)
|
||||
? payload.disputed.slice(0, 30)
|
||||
: []) {
|
||||
const rings = (Array.isArray(raw?.rings) ? raw.rings.slice(0, 20) : [])
|
||||
.map(normalizeRing)
|
||||
.filter(Boolean);
|
||||
const name = text(raw?.name, 60);
|
||||
if (!rings.length || !name) continue;
|
||||
disputed.push({
|
||||
name,
|
||||
kind: KINDS.includes(raw.kind) ? raw.kind : 'held',
|
||||
heldBy: country(raw.heldBy),
|
||||
claimedBy: country(raw.claimedBy),
|
||||
rings,
|
||||
});
|
||||
}
|
||||
return { polygons, borders, disputed, area: outlineArea(payload?.area) };
|
||||
}
|
||||
|
||||
const AREA_KINDS = ['country', 'region', 'disputed'];
|
||||
function outlineArea(raw) {
|
||||
const key = text(raw?.key, 80);
|
||||
const name = text(raw?.name, 80);
|
||||
if (!key || !name) return null;
|
||||
return {
|
||||
key,
|
||||
name,
|
||||
kind: AREA_KINDS.includes(raw.kind) ? raw.kind : 'country',
|
||||
country:
|
||||
typeof raw.country === 'string' && /^[A-Z]{2}$/.test(raw.country)
|
||||
? raw.country
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
/** `/api/news/feed` → `{reports, nextBefore}`, or null without a report list. */
|
||||
export function normalizeFeedPayload(payload) {
|
||||
if (!Array.isArray(payload?.reports)) return null;
|
||||
const reports = [];
|
||||
for (const raw of payload.reports.slice(0, 500)) {
|
||||
const report = normalizeReport(raw);
|
||||
if (report) reports.push(report);
|
||||
}
|
||||
return { reports, nextBefore: iso(payload.nextBefore) };
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
import { readResponseJsonCapped } from '../../sources/httpBody.js';
|
||||
import { isUnavailableCapability } from '../../sources/capability.js';
|
||||
import {
|
||||
normalizeFeedPayload,
|
||||
normalizeHotspotsPayload,
|
||||
normalizeOutlinePayload,
|
||||
} from './records.js';
|
||||
|
||||
// A portable export (package.json): no i18n here. Failures stay English data;
|
||||
// the layer shows them translated.
|
||||
const msg = (text) => text;
|
||||
|
||||
const MAX_BYTES = 4 * 1024 * 1024;
|
||||
const BASE_PATH = '/api/news';
|
||||
// The outline geometry version the client draws (disputed areas included).
|
||||
const OUTLINE_VERSION = '4';
|
||||
|
||||
/** The three read routes the news layer calls, for a host's path allowlist. */
|
||||
export const NEWS_API_PATHS = Object.freeze([
|
||||
`${BASE_PATH}/hotspots`,
|
||||
`${BASE_PATH}/feed`,
|
||||
`${BASE_PATH}/outline`,
|
||||
]);
|
||||
|
||||
const FEED_KEYS = Object.freeze([
|
||||
'hotspot',
|
||||
'before',
|
||||
'since',
|
||||
'limit',
|
||||
'category',
|
||||
'relevance',
|
||||
'at',
|
||||
]);
|
||||
const FLAG_KEYS = Object.freeze(['geo', 'today', 'events']);
|
||||
const ISO = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,3})?Z$/;
|
||||
const LIST = /^[a-z][a-z,-]{0,127}$/;
|
||||
// A point to two decimals (~1 km), as areaPoint writes it.
|
||||
const AT = /^-?\d{1,2}(?:\.\d{1,2})?,-?\d{1,3}(?:\.\d{1,2})?$/;
|
||||
// A coordinate to two decimals, without trailing zeros ("50.4", "-97.74").
|
||||
const areaPoint = (value) => String(Math.round(value * 100) / 100);
|
||||
const FEED_VALUE = {
|
||||
hotspot: (v) => /^[a-z0-9][a-z0-9_-]{0,63}$/i.test(v),
|
||||
before: (v) => ISO.test(v),
|
||||
since: (v) => ISO.test(v),
|
||||
limit: (v) => /^\d{1,3}$/.test(v) && Number(v) >= 1 && Number(v) <= 500,
|
||||
category: (v) => LIST.test(v),
|
||||
relevance: (v) => LIST.test(v),
|
||||
at: (v) => AT.test(v),
|
||||
};
|
||||
|
||||
/**
|
||||
* Feed query string from a plain object; unknown keys and empty values are
|
||||
* dropped. `at` is a point (`{lat, lon}`), the Local section's area there.
|
||||
*/
|
||||
export function newsFeedQuery(query = {}) {
|
||||
const params = new URLSearchParams();
|
||||
for (const key of FEED_KEYS) {
|
||||
const value =
|
||||
key === 'at' && query.at
|
||||
? `${areaPoint(query.at.lat)},${areaPoint(query.at.lon)}`
|
||||
: query[key];
|
||||
if (value !== undefined && value !== null && value !== '')
|
||||
params.set(key, String(value));
|
||||
}
|
||||
for (const key of FLAG_KEYS) if (query[key]) params.set(key, '1');
|
||||
return params.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a request URL is one this client sends: a known route, known keys
|
||||
* only, each value in its form. A host proxying the routes can admit exactly
|
||||
* these and refuse the rest.
|
||||
* @param {URL} url
|
||||
*/
|
||||
export function newsQueryAllowed(url) {
|
||||
const params = [...url.searchParams];
|
||||
if (new Set(params.map(([key]) => key)).size !== params.length) return false;
|
||||
if (url.pathname === `${BASE_PATH}/hotspots`)
|
||||
return (
|
||||
params.length === 0 ||
|
||||
(params.length === 1 &&
|
||||
params[0][0] === 'hours' &&
|
||||
/^\d{1,2}$/.test(params[0][1]) &&
|
||||
Number(params[0][1]) >= 1 &&
|
||||
Number(params[0][1]) <= 24)
|
||||
);
|
||||
if (url.pathname === `${BASE_PATH}/outline`) {
|
||||
const keys = params.map(([key]) => key).sort();
|
||||
const value = url.searchParams;
|
||||
return (
|
||||
params.length === 2 &&
|
||||
keys[1] === 'v' &&
|
||||
value.get('v') === OUTLINE_VERSION &&
|
||||
((keys[0] === 'hotspot' && FEED_VALUE.hotspot(value.get('hotspot'))) ||
|
||||
(keys[0] === 'country' &&
|
||||
/^[A-Z]{2}(?:-[A-Z0-9]{1,3})?$/.test(value.get('country'))) ||
|
||||
(keys[0] === 'at' && AT.test(value.get('at'))))
|
||||
);
|
||||
}
|
||||
if (url.pathname !== `${BASE_PATH}/feed`) return false;
|
||||
return params.every(([key, value]) =>
|
||||
FLAG_KEYS.includes(key)
|
||||
? value === '1'
|
||||
: Object.hasOwn(FEED_VALUE, key) && FEED_VALUE[key](value),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A failed read: a server without the news routes is a permanent miss; one
|
||||
* that reads a section from a key it lacks (503 `no_key`, `key_rejected` or,
|
||||
* its allowance for the day spent, `key_quota`, naming the key registry's id)
|
||||
* says which, and is asked again later.
|
||||
*/
|
||||
async function responseError(response) {
|
||||
let body = null;
|
||||
try {
|
||||
body = await readResponseJsonCapped(response, 16 * 1024);
|
||||
} catch {
|
||||
await response.body?.cancel?.().catch?.(() => {});
|
||||
}
|
||||
if (
|
||||
response.status === 503 &&
|
||||
['no_key', 'key_rejected', 'key_quota'].includes(body?.error) &&
|
||||
typeof body.key === 'string' &&
|
||||
/^[a-z][a-z0-9-]{0,31}$/.test(body.key)
|
||||
)
|
||||
return Object.assign(new Error(msg('News key required')), {
|
||||
status: 503,
|
||||
code: body.error,
|
||||
keyRequired: true,
|
||||
keyRejected: body.error === 'key_rejected',
|
||||
keyQuota: body.error === 'key_quota',
|
||||
keyId: body.key,
|
||||
unavailable: false,
|
||||
retryable: true,
|
||||
});
|
||||
const unavailable =
|
||||
response.status === 404 ||
|
||||
(response.status === 503 && isUnavailableCapability(body));
|
||||
return Object.assign(
|
||||
new Error(
|
||||
unavailable
|
||||
? msg('News feed not configured on this server')
|
||||
: msg('News feed unavailable'),
|
||||
),
|
||||
{
|
||||
status: response.status,
|
||||
code: unavailable ? 'unavailable' : 'http',
|
||||
unavailable,
|
||||
retryable: !unavailable,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/** Read hotspots, reports and outlines from the server's /api/news routes. */
|
||||
export function createNewsSource({
|
||||
fetchImpl = (...args) => globalThis.fetch(...args),
|
||||
timeoutMs = 15_000,
|
||||
} = {}) {
|
||||
async function get(path, { signal } = {}) {
|
||||
signal?.throwIfAborted();
|
||||
const timeout = AbortSignal.timeout(timeoutMs);
|
||||
const request = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
||||
try {
|
||||
const response = await fetchImpl(`${BASE_PATH}${path}`, {
|
||||
signal: request,
|
||||
cache: 'no-store',
|
||||
redirect: 'error',
|
||||
});
|
||||
if (!response.ok) throw await responseError(response);
|
||||
return await readResponseJsonCapped(response, MAX_BYTES, request);
|
||||
} catch (cause) {
|
||||
// Out of time the feed reads unavailable, not the browser's own words
|
||||
// ("signal timed out"); the caller's own abort stays an abort.
|
||||
if (timeout.aborted && !signal?.aborted)
|
||||
throw Object.assign(new Error(msg('News feed unavailable')), {
|
||||
code: 'timeout',
|
||||
unavailable: false,
|
||||
retryable: true,
|
||||
});
|
||||
throw cause;
|
||||
}
|
||||
}
|
||||
return {
|
||||
// `hours` asks for counts over a shorter window than the server's own.
|
||||
async getHotspots({ signal, hours } = {}) {
|
||||
const payload = normalizeHotspotsPayload(
|
||||
await get(hours ? `/hotspots?hours=${hours}` : '/hotspots', {
|
||||
signal,
|
||||
}),
|
||||
);
|
||||
if (!payload) throw new Error(msg('Malformed news hotspots response'));
|
||||
return payload;
|
||||
},
|
||||
async getOutline(hotspotId, { signal } = {}) {
|
||||
return normalizeOutlinePayload(
|
||||
await get(
|
||||
`/outline?hotspot=${encodeURIComponent(hotspotId)}&v=${OUTLINE_VERSION}`,
|
||||
{ signal },
|
||||
),
|
||||
);
|
||||
},
|
||||
async getCountryOutline(country, { signal } = {}) {
|
||||
return normalizeOutlinePayload(
|
||||
await get(
|
||||
`/outline?country=${encodeURIComponent(country)}&v=${OUTLINE_VERSION}`,
|
||||
{ signal },
|
||||
),
|
||||
);
|
||||
},
|
||||
// The area the Local section reads at a point, with its outline.
|
||||
async getAreaOutline({ lat, lon }, { signal } = {}) {
|
||||
return normalizeOutlinePayload(
|
||||
await get(
|
||||
`/outline?at=${areaPoint(lat)},${areaPoint(lon)}&v=${OUTLINE_VERSION}`,
|
||||
{ signal },
|
||||
),
|
||||
);
|
||||
},
|
||||
async getFeed(query = {}, { signal } = {}) {
|
||||
const payload = normalizeFeedPayload(
|
||||
await get(`/feed?${newsFeedQuery(query)}`, { signal }),
|
||||
);
|
||||
if (!payload) throw new Error(msg('Malformed news feed response'));
|
||||
return payload;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
NEWS_API_PATHS,
|
||||
createNewsSource,
|
||||
newsFeedQuery,
|
||||
newsQueryAllowed,
|
||||
} from './source.js';
|
||||
|
||||
const json = (body, status = 200) =>
|
||||
new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
function recorder(respond) {
|
||||
const calls = [];
|
||||
return {
|
||||
calls,
|
||||
fetchImpl: async (url, init) => {
|
||||
calls.push({ url, init });
|
||||
return respond(url, init);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('reads validated hotspots, feed and outlines from the same-origin routes', async () => {
|
||||
const { calls, fetchImpl } = recorder((url) => {
|
||||
if (url.startsWith('/api/news/hotspots'))
|
||||
return json({
|
||||
hotspots: [{ id: 'ua', name: 'UA', bbox: [22, 44, 42, 56] }],
|
||||
});
|
||||
if (url.startsWith('/api/news/feed'))
|
||||
return json({
|
||||
reports: [
|
||||
{
|
||||
id: 'r1',
|
||||
title: 'T',
|
||||
url: 'https://x.test/',
|
||||
publishedAt: '2026-10-28T09:00:00Z',
|
||||
},
|
||||
],
|
||||
nextBefore: null,
|
||||
});
|
||||
return json({ polygons: [], borders: [], disputed: [] });
|
||||
});
|
||||
const source = createNewsSource({ fetchImpl });
|
||||
assert.equal((await source.getHotspots()).hotspots[0].id, 'ua');
|
||||
assert.equal(
|
||||
(await source.getFeed({ hotspot: 'all', today: true, limit: 60 }))
|
||||
.reports[0].id,
|
||||
'r1',
|
||||
);
|
||||
assert.deepEqual((await source.getOutline('ua')).polygons, []);
|
||||
await source.getCountryOutline('SD');
|
||||
await source.getHotspots({ hours: 6 });
|
||||
await source.getAreaOutline({ lat: 30.26666, lon: -97.7 });
|
||||
await source.getFeed({ hotspot: 'all', at: { lat: 30.26666, lon: -97.7 } });
|
||||
assert.deepEqual(
|
||||
calls.map((c) => c.url),
|
||||
[
|
||||
'/api/news/hotspots',
|
||||
'/api/news/feed?hotspot=all&limit=60&today=1',
|
||||
'/api/news/outline?hotspot=ua&v=4',
|
||||
'/api/news/outline?country=SD&v=4',
|
||||
'/api/news/hotspots?hours=6',
|
||||
'/api/news/outline?at=30.27,-97.7&v=4',
|
||||
'/api/news/feed?hotspot=all&at=30.27%2C-97.7',
|
||||
],
|
||||
);
|
||||
for (const { url, init } of calls) {
|
||||
assert.equal(init.redirect, 'error');
|
||||
assert.equal(init.cache, 'no-store');
|
||||
assert.ok(init.signal instanceof AbortSignal);
|
||||
// Every URL the client sends is one a host's allowlist admits.
|
||||
assert.equal(newsQueryAllowed(new URL(url, 'http://h')), true, url);
|
||||
}
|
||||
});
|
||||
|
||||
test('malformed, failed and unconfigured reads reject; a server without news is a permanent miss', async () => {
|
||||
const malformed = createNewsSource({ fetchImpl: async () => json({}) });
|
||||
await assert.rejects(malformed.getHotspots(), /Malformed news hotspots/);
|
||||
await assert.rejects(malformed.getFeed(), /Malformed news feed/);
|
||||
|
||||
const down = createNewsSource({
|
||||
fetchImpl: async () => json({ error: 'upstream' }, 502),
|
||||
});
|
||||
await assert.rejects(down.getHotspots(), (error) => {
|
||||
assert.equal(error.message, 'News feed unavailable');
|
||||
assert.equal(error.retryable, true);
|
||||
assert.equal(error.unavailable, false);
|
||||
return true;
|
||||
});
|
||||
|
||||
const unconfigured = createNewsSource({
|
||||
fetchImpl: async () =>
|
||||
json(
|
||||
{ error: 'news_not_configured', unavailable: true, retryable: false },
|
||||
503,
|
||||
),
|
||||
});
|
||||
await assert.rejects(unconfigured.getHotspots(), (error) => {
|
||||
assert.equal(error.message, 'News feed not configured on this server');
|
||||
assert.equal(error.code, 'unavailable');
|
||||
assert.equal(error.unavailable, true);
|
||||
assert.equal(error.retryable, false);
|
||||
return true;
|
||||
});
|
||||
const missing = createNewsSource({
|
||||
fetchImpl: async () => new Response('Not found', { status: 404 }),
|
||||
});
|
||||
await assert.rejects(missing.getFeed(), { unavailable: true });
|
||||
const broken = createNewsSource({
|
||||
fetchImpl: async () => new Response('{', { status: 200 }),
|
||||
});
|
||||
await assert.rejects(broken.getHotspots(), SyntaxError);
|
||||
});
|
||||
|
||||
test('a section read from a key the server lacks names the key and is asked again', async () => {
|
||||
const answer = (body) =>
|
||||
createNewsSource({
|
||||
fetchImpl: async () =>
|
||||
new Response(JSON.stringify(body), {
|
||||
status: 503,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}),
|
||||
});
|
||||
await assert.rejects(
|
||||
answer({ error: 'no_key', key: 'liveuamap' }).getHotspots(),
|
||||
(error) => {
|
||||
assert.equal(error.keyRequired, true);
|
||||
assert.equal(error.keyRejected, false);
|
||||
assert.equal(error.keyId, 'liveuamap');
|
||||
assert.equal(error.unavailable, false);
|
||||
assert.equal(error.retryable, true);
|
||||
return true;
|
||||
},
|
||||
);
|
||||
await assert.rejects(
|
||||
answer({ error: 'key_rejected', key: 'worldnewsapi' }).getFeed({
|
||||
at: { lat: 51.13, lon: 71.43 },
|
||||
}),
|
||||
{ keyRequired: true, keyRejected: true, keyId: 'worldnewsapi' },
|
||||
);
|
||||
// The day's allowance spent: still the key's matter, back tomorrow.
|
||||
await assert.rejects(
|
||||
answer({ error: 'key_quota', key: 'worldnewsapi' }).getFeed(),
|
||||
{
|
||||
keyRequired: true,
|
||||
keyRejected: false,
|
||||
keyQuota: true,
|
||||
keyId: 'worldnewsapi',
|
||||
unavailable: false,
|
||||
},
|
||||
);
|
||||
// A key name not in the registry's form is an ordinary failure.
|
||||
await assert.rejects(
|
||||
answer({ error: 'no_key', key: '<script>' }).getHotspots(),
|
||||
(error) => error.keyRequired === undefined && error.code === 'http',
|
||||
);
|
||||
});
|
||||
|
||||
test('reads time out and follow the caller signal', async () => {
|
||||
// AbortSignal.timeout does not hold the event loop open: the hanging fetch
|
||||
// does, until its signal aborts, so the run cannot end before it.
|
||||
const hang = (_url, { signal }) =>
|
||||
new Promise((_, reject) => {
|
||||
const alive = setTimeout(() => {}, 60_000);
|
||||
signal.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
clearTimeout(alive);
|
||||
reject(signal.reason);
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
});
|
||||
const slow = createNewsSource({ fetchImpl: hang, timeoutMs: 20 });
|
||||
// Out of time it reads unavailable, in the app's words, as retryable.
|
||||
await assert.rejects(slow.getHotspots(), {
|
||||
message: 'News feed unavailable',
|
||||
code: 'timeout',
|
||||
retryable: true,
|
||||
});
|
||||
// The caller's abort stays its own, even once the time is up too.
|
||||
const late = (_url, { signal }) =>
|
||||
new Promise((_, reject) => {
|
||||
setTimeout(() => reject(signal.reason), 40);
|
||||
});
|
||||
const leaving = new AbortController();
|
||||
const gone = createNewsSource({ fetchImpl: late, timeoutMs: 20 }).getFeed(
|
||||
{},
|
||||
{ signal: leaving.signal },
|
||||
);
|
||||
leaving.abort(new Error('gone'));
|
||||
await assert.rejects(gone, /gone/);
|
||||
const caller = new AbortController();
|
||||
const pending = createNewsSource({ fetchImpl: hang }).getFeed(
|
||||
{},
|
||||
{ signal: caller.signal },
|
||||
);
|
||||
caller.abort(new Error('gone'));
|
||||
await assert.rejects(pending, /gone/);
|
||||
await assert.rejects(
|
||||
createNewsSource({ fetchImpl: hang }).getHotspots({
|
||||
signal: AbortSignal.abort(new Error('already')),
|
||||
}),
|
||||
/already/,
|
||||
);
|
||||
});
|
||||
|
||||
test('the host allowlist admits the client routes and refuses anything else', () => {
|
||||
const allowed = (path) => newsQueryAllowed(new URL(path, 'http://h'));
|
||||
assert.deepEqual(NEWS_API_PATHS, [
|
||||
'/api/news/hotspots',
|
||||
'/api/news/feed',
|
||||
'/api/news/outline',
|
||||
]);
|
||||
assert.equal(
|
||||
allowed(
|
||||
`/api/news/feed?${newsFeedQuery({ hotspot: 'ua-ru-war', before: '2026-10-28T08:00:00.000Z', limit: 500, category: 'strike', relevance: 'core,related', geo: true, today: true, events: true })}`,
|
||||
),
|
||||
true,
|
||||
);
|
||||
assert.equal(allowed('/api/news/hotspots?hours=6'), true);
|
||||
for (const path of [
|
||||
'/api/news/hotspots?hours=0',
|
||||
'/api/news/hotspots?hours=25',
|
||||
'/api/news/hotspots?hours=6&hours=3',
|
||||
'/api/news/hotspots?hours=6&x=1',
|
||||
'/api/news/hotspots?x=1',
|
||||
'/api/news/feed?limit=501',
|
||||
'/api/news/feed?limit=0',
|
||||
'/api/news/feed?hotspot=all&hotspot=ua',
|
||||
'/api/news/feed?since=yesterday',
|
||||
'/api/news/feed?geo=yes',
|
||||
'/api/news/feed?side=UA',
|
||||
'/api/news/air-alerts',
|
||||
'/api/news/outline?hotspot=ua',
|
||||
'/api/news/outline?hotspot=ua&v=2',
|
||||
'/api/news/outline?country=ukraine&v=4',
|
||||
'/api/news/outline?at=30.267,-97.7&v=4',
|
||||
'/api/news/outline?at=30.27&v=4',
|
||||
'/api/news/outline?at=30.27,-97.7&country=US&v=4',
|
||||
'/api/news/feed?at=30.267,-97.7',
|
||||
])
|
||||
assert.equal(allowed(path), false, path);
|
||||
});
|
||||
@@ -0,0 +1,131 @@
|
||||
// Marker sprites for news reports: a dark disc with the category's icon and
|
||||
// a rim in the severity colour, the rim's form telling attestation. Drawn once per look
|
||||
// on a canvas and handed to the renderer as a data URL, so its texture atlas keeps
|
||||
// one copy per look however often the layer re-renders.
|
||||
|
||||
import { NEWS_CATEGORIES, NEWS_SEVERITY } from './model.js';
|
||||
|
||||
const CANVAS = 64;
|
||||
const BODY = 52; // disc diameter inside the canvas; the rest is rim and ring
|
||||
const INK = 'rgba(10, 10, 15, 0.92)';
|
||||
const SELECTED = '#00d4ff';
|
||||
const COUNT_INK = '#e8eaed';
|
||||
|
||||
/** Canvas pixels per marker pixel: the billboard is drawn at this ratio. */
|
||||
export const SPRITE_SCALE = CANVAS / BODY;
|
||||
|
||||
const cache = new Map();
|
||||
|
||||
/**
|
||||
* Paint one marker look centred at (cx, cy) with a disc of `body` pixels: the
|
||||
* sprites and the event cards' badges draw the same thing.
|
||||
*/
|
||||
export function paintMarker(ctx, { category, severity, rim }, cx, cy, body) {
|
||||
const k = body / BODY; // the strokes below are tuned for the 52 px body
|
||||
const r = body / 2;
|
||||
// A dark edge keeps the lightest fills apart from bright ground.
|
||||
ctx.beginPath();
|
||||
ctx.arc(cx, cy, r + 1.5 * k, 0, 2 * Math.PI);
|
||||
ctx.fillStyle = 'rgba(0, 0, 0, 0.85)';
|
||||
ctx.fill();
|
||||
// GEV's dark glass disc, as its HUD buttons are; severity colours the rim
|
||||
// and the icon rather than filling the disc.
|
||||
ctx.beginPath();
|
||||
ctx.arc(cx, cy, r, 0, 2 * Math.PI);
|
||||
ctx.fillStyle = INK;
|
||||
ctx.fill();
|
||||
const color = (NEWS_SEVERITY[severity] || NEWS_SEVERITY[0]).color;
|
||||
|
||||
// Attestation is the rim's form, never its colour.
|
||||
ctx.beginPath();
|
||||
ctx.arc(cx, cy, r - 3 * k, 0, 2 * Math.PI);
|
||||
ctx.setLineDash(rim === 'claimed' ? [7 * k, 5 * k] : []);
|
||||
ctx.lineWidth = (rim === 'thin' ? 2.5 : 6) * k;
|
||||
ctx.strokeStyle = color;
|
||||
ctx.stroke();
|
||||
ctx.setLineDash([]);
|
||||
|
||||
const style = NEWS_CATEGORIES[category] || NEWS_CATEGORIES.other;
|
||||
const icon = body * 0.5;
|
||||
ctx.save();
|
||||
ctx.translate(cx - icon / 2, cy - icon / 2);
|
||||
ctx.scale(icon / 16, icon / 16);
|
||||
const path = new Path2D(style.icon);
|
||||
ctx.lineCap = 'round';
|
||||
ctx.lineJoin = 'round';
|
||||
ctx.lineWidth = 1.7;
|
||||
ctx.strokeStyle = color;
|
||||
if (style.solid) {
|
||||
ctx.fillStyle = color;
|
||||
ctx.fill(path);
|
||||
} else ctx.stroke(path);
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
/**
|
||||
* Data URL of the sprite for a look, or null where there is no canvas (the
|
||||
* layer then falls back to a plain point).
|
||||
* @param {{category: string, severity: number, rim: 'confirmed'|'claimed'|'thin', selected?: boolean}} look
|
||||
*/
|
||||
export function markerSprite({ category, severity, rim, selected = false }) {
|
||||
const key = `${category}|${severity}|${rim}|${selected ? 1 : 0}`;
|
||||
if (cache.has(key)) return cache.get(key);
|
||||
const canvas = globalThis.document?.createElement?.('canvas');
|
||||
const ctx = canvas?.getContext?.('2d');
|
||||
if (!ctx || typeof globalThis.Path2D !== 'function') return null;
|
||||
canvas.width = canvas.height = CANVAS;
|
||||
const c = CANVAS / 2;
|
||||
paintMarker(ctx, { category, severity, rim }, c, c, BODY);
|
||||
if (selected) {
|
||||
ctx.beginPath();
|
||||
ctx.arc(c, c, CANVAS / 2 - 2, 0, 2 * Math.PI);
|
||||
ctx.lineWidth = 3.5;
|
||||
ctx.strokeStyle = SELECTED;
|
||||
ctx.stroke();
|
||||
}
|
||||
const url = canvas.toDataURL('image/png');
|
||||
cache.set(key, url);
|
||||
return url;
|
||||
}
|
||||
|
||||
/**
|
||||
* Data URL of a country badge: the dark disc with a light rim and the number
|
||||
* of reports it stands for, drawn at the pixels it is shown at so the digits
|
||||
* stay sharp. Null where there is no canvas.
|
||||
* @param {number} count Reports the badge stands for.
|
||||
* @param {number} pixels The disc's diameter in drawn pixels.
|
||||
*/
|
||||
export function countSprite(count, pixels) {
|
||||
const body = Math.max(1, Math.round(pixels));
|
||||
const text = count > 99 ? '99+' : String(count);
|
||||
const key = `count|${text}|${body}`;
|
||||
if (cache.has(key)) return cache.get(key);
|
||||
const canvas = globalThis.document?.createElement?.('canvas');
|
||||
const ctx = canvas?.getContext?.('2d');
|
||||
if (!ctx) return null;
|
||||
const k = body / BODY;
|
||||
canvas.width = canvas.height = Math.round(CANVAS * k);
|
||||
const c = canvas.width / 2;
|
||||
const r = body / 2;
|
||||
ctx.beginPath();
|
||||
ctx.arc(c, c, r + 1.5 * k, 0, 2 * Math.PI);
|
||||
ctx.fillStyle = 'rgba(0, 0, 0, 0.85)';
|
||||
ctx.fill();
|
||||
ctx.beginPath();
|
||||
ctx.arc(c, c, r, 0, 2 * Math.PI);
|
||||
ctx.fillStyle = INK;
|
||||
ctx.fill();
|
||||
ctx.beginPath();
|
||||
ctx.arc(c, c, r - 2 * k, 0, 2 * Math.PI);
|
||||
ctx.lineWidth = 3 * k;
|
||||
ctx.strokeStyle = COUNT_INK;
|
||||
ctx.stroke();
|
||||
ctx.fillStyle = COUNT_INK;
|
||||
ctx.font = `600 ${Math.round(body * (text.length > 2 ? 0.34 : 0.44))}px ui-monospace, Menlo, monospace`;
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.fillText(text, c, c + k);
|
||||
const url = canvas.toDataURL('image/png');
|
||||
cache.set(key, url);
|
||||
return url;
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import { formatDate, formatNumber, msg, t } from '../../i18n/index.js';
|
||||
import { EMODNET_PAGE_URL } from './records.js';
|
||||
|
||||
export const ERA_LABELS = Object.freeze({
|
||||
'before-1900': msg('Before 1900'),
|
||||
'1900-1945': msg('1900–1945'),
|
||||
'after-1945': msg('After 1945'),
|
||||
undated: msg('Date unknown'),
|
||||
});
|
||||
|
||||
export const ERA_COLORS = Object.freeze({
|
||||
'before-1900': '#c79a5b',
|
||||
'1900-1945': '#ff6b5e',
|
||||
'after-1945': '#4fc3f7',
|
||||
undated: '#9aa7b4',
|
||||
});
|
||||
|
||||
function formatDay(date) {
|
||||
const match = /^(-?\d{4})-(\d{2})-(\d{2})$/.exec(date || '');
|
||||
if (!match) return '';
|
||||
return formatDate(
|
||||
Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3])),
|
||||
{ day: 'numeric', month: 'short', year: 'numeric', timeZone: 'UTC' },
|
||||
);
|
||||
}
|
||||
|
||||
function meters(value) {
|
||||
return formatNumber(value, {
|
||||
maximumFractionDigits: value < 10 ? 1 : 0,
|
||||
});
|
||||
}
|
||||
|
||||
/** How well the position is known, as one card line (or null). */
|
||||
export function positionLine(record) {
|
||||
if (record.positionNote) return t('Position: centre of the protected area');
|
||||
const accuracy = record.positionAccuracy;
|
||||
if (!Number.isFinite(accuracy)) return null;
|
||||
// 1852 m is EMODnet's "within a nautical mile" for old, reported positions.
|
||||
if (accuracy >= 1000)
|
||||
return t('Position approximate (within about {km} km)', {
|
||||
km: formatNumber(accuracy / 1000, { maximumFractionDigits: 1 }),
|
||||
});
|
||||
return t('Position surveyed (within about {m} m)', { m: meters(accuracy) });
|
||||
}
|
||||
|
||||
/**
|
||||
* The link a click on the card opens: the Wikipedia (or Wikidata) page, the
|
||||
* wreck's own page when EMODnet lists one, else EMODnet's portal.
|
||||
* @param {object} record
|
||||
* @returns {string}
|
||||
*/
|
||||
export function cardLink(record) {
|
||||
return record?.url || EMODNET_PAGE_URL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Title and detail lines for one wreck card: deaths first, then when and
|
||||
* where, then the ship facts. Victims appear as a count only; free text that
|
||||
* refers to a person by a title or role is dropped by a keyword filter (see
|
||||
* records.js), which a bare name can still pass.
|
||||
* @param {object} record A normalized shipwreck record.
|
||||
* @returns {{title: string, details: string[], link: string}}
|
||||
*/
|
||||
export function describeShipwreck(record) {
|
||||
const titleParts = [t('Shipwreck')];
|
||||
if (record.name) titleParts.push(record.name);
|
||||
const details = [];
|
||||
// Deaths first, right under the title: the fact readers look for.
|
||||
const toll = [];
|
||||
if (Number.isFinite(record.casualties))
|
||||
toll.push(
|
||||
t('Fatalities: {count}', { count: formatNumber(record.casualties) }),
|
||||
);
|
||||
if (record.survivors)
|
||||
toll.push(
|
||||
t('Survivors: {count}', { count: formatNumber(record.survivors) }),
|
||||
);
|
||||
if (toll.length) details.push(toll.join(' · '));
|
||||
const when =
|
||||
formatDay(record.date) ||
|
||||
(Number.isInteger(record.year) ? String(record.year) : '') ||
|
||||
record.dating ||
|
||||
'';
|
||||
const where = [when, record.country].filter(Boolean);
|
||||
if (where.length) details.push(where.join(' · '));
|
||||
if (record.vesselType)
|
||||
details.push(t('Vessel: {value}', { value: record.vesselType }));
|
||||
if (record.cause)
|
||||
details.push(t('What happened: {value}', { value: record.cause }));
|
||||
if (Number.isFinite(record.depth))
|
||||
details.push(
|
||||
record.depthQuality
|
||||
? t('Depth: {m} m ({quality})', {
|
||||
m: meters(record.depth),
|
||||
quality: record.depthQuality,
|
||||
})
|
||||
: t('Depth: {m} m', { m: meters(record.depth) }),
|
||||
);
|
||||
const position = positionLine(record);
|
||||
if (position) details.push(position);
|
||||
if (record.notes) details.push(t('Notes: {value}', { value: record.notes }));
|
||||
if (record.cargo)
|
||||
details.push(t('Cargo or finds: {value}', { value: record.cargo }));
|
||||
if (record.protected) details.push(t('Protected wreck'));
|
||||
const sources =
|
||||
record.source === 'wikidata'
|
||||
? record.alsoIn === 'emodnet'
|
||||
? 'Wikidata · EMODnet'
|
||||
: 'Wikidata'
|
||||
: record.originator
|
||||
? `EMODnet (${record.originator})`
|
||||
: 'EMODnet';
|
||||
details.push(t('Source: {value}', { value: sources }));
|
||||
const link = cardLink(record);
|
||||
details.push(
|
||||
link === EMODNET_PAGE_URL
|
||||
? t('Click the card to open EMODnet ↗')
|
||||
: link.includes('.wikipedia.org/')
|
||||
? t('Click the card to open the article ↗')
|
||||
: t('Click the card to open the source ↗'),
|
||||
);
|
||||
return { title: titleParts.join(' · '), details, link };
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { describeShipwreck, positionLine } from './cards.js';
|
||||
import { EMODNET_PAGE_URL } from './records.js';
|
||||
|
||||
test('a Wikidata card shows the ship facts and links its article', () => {
|
||||
const card = describeShipwreck({
|
||||
source: 'wikidata',
|
||||
alsoIn: 'emodnet',
|
||||
name: 'HMS Havant',
|
||||
vesselType: 'destroyer',
|
||||
date: '1940-06-01',
|
||||
year: 1940,
|
||||
cause: 'Was sunk on 06/01/1940 by the German air force',
|
||||
casualties: 8,
|
||||
survivors: 120,
|
||||
depth: 14.72,
|
||||
depthQuality: 'Least depth known',
|
||||
positionAccuracy: 3.1,
|
||||
notes: '1939 G and H-class destroyer',
|
||||
country: 'France',
|
||||
url: 'https://en.wikipedia.org/wiki/HMS_Havant_(H32)',
|
||||
});
|
||||
assert.equal(card.title, 'Shipwreck · HMS Havant');
|
||||
assert.equal(card.link, 'https://en.wikipedia.org/wiki/HMS_Havant_(H32)');
|
||||
const text = card.details.join('\n');
|
||||
assert.equal(card.details[0], 'Fatalities: 8 · Survivors: 120');
|
||||
assert.match(card.details[1], /1940 · France$/);
|
||||
assert.match(text, /Vessel: destroyer/);
|
||||
assert.match(text, /What happened: Was sunk/);
|
||||
assert.match(text, /Depth: 15 m \(Least depth known\)/);
|
||||
assert.match(text, /Position surveyed \(within about 3\.1 m\)/);
|
||||
assert.match(text, /Source: Wikidata · EMODnet/);
|
||||
assert.match(text, /open the article/);
|
||||
});
|
||||
|
||||
test('an EMODnet card without a page links the portal', () => {
|
||||
const card = describeShipwreck({
|
||||
source: 'emodnet',
|
||||
name: null,
|
||||
year: null,
|
||||
dating: 'C1st AD',
|
||||
originator: 'The Oxford Roman Economy Project',
|
||||
protected: true,
|
||||
url: null,
|
||||
});
|
||||
assert.equal(card.title, 'Shipwreck');
|
||||
assert.equal(card.link, EMODNET_PAGE_URL);
|
||||
const text = card.details.join('\n');
|
||||
assert.equal(card.details[0], 'C1st AD');
|
||||
assert.match(text, /Protected wreck/);
|
||||
assert.match(text, /EMODnet \(The Oxford Roman Economy Project\)/);
|
||||
assert.match(text, /open EMODnet/);
|
||||
});
|
||||
|
||||
test('position lines read the accuracy', () => {
|
||||
assert.equal(positionLine({}), null);
|
||||
assert.match(positionLine({ positionAccuracy: 1852 }), /about 1\.9 km/);
|
||||
assert.match(
|
||||
positionLine({ positionNote: 'x' }),
|
||||
/centre of the protected area/,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
/** Era chips, oldest first; a wreck with no known year sits in its own chip. */
|
||||
export const SHIPWRECK_ERAS = Object.freeze([
|
||||
'before-1900',
|
||||
'1900-1945',
|
||||
'after-1945',
|
||||
'undated',
|
||||
]);
|
||||
|
||||
/**
|
||||
* The era a wreck belongs to. Ancient wrecks dated only by period
|
||||
* ("Roman Imperial", "C1st AD") count as before 1900.
|
||||
* @param {{year?: number|null, ancient?: boolean}} record
|
||||
* @returns {string}
|
||||
*/
|
||||
export function eraOf(record) {
|
||||
const year = Number.isInteger(record?.year) ? record.year : null;
|
||||
if (year === null) return record?.ancient ? 'before-1900' : 'undated';
|
||||
if (year < 1900) return 'before-1900';
|
||||
if (year <= 1945) return '1900-1945';
|
||||
return 'after-1945';
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { eraOf } from './eras.js';
|
||||
|
||||
test('each wreck falls in one era', () => {
|
||||
assert.equal(eraOf({ year: 1588 }), 'before-1900');
|
||||
assert.equal(eraOf({ year: null, ancient: true }), 'before-1900');
|
||||
assert.equal(eraOf({ year: 1900 }), '1900-1945');
|
||||
assert.equal(eraOf({ year: 1945 }), '1900-1945');
|
||||
assert.equal(eraOf({ year: 1946 }), 'after-1945');
|
||||
assert.equal(eraOf({ year: null }), 'undated');
|
||||
assert.equal(eraOf(null), 'undated');
|
||||
});
|
||||
@@ -0,0 +1,539 @@
|
||||
import { formatNumber, msg, t, tn } from '../../i18n/index.js';
|
||||
import { spriteDrawOrder } from '../../data/spriteOrder.js';
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { drawOf, findFrame } from '../../render/rendererOf.js';
|
||||
import { inputFor } from '../../input/dispatcher.js';
|
||||
import { createHorizonCull } from '../streetLevel/view.js';
|
||||
import { ERA_COLORS, ERA_LABELS, describeShipwreck } from './cards.js';
|
||||
import { SHIPWRECK_ERAS, eraOf } from './eras.js';
|
||||
import {
|
||||
inPeriod,
|
||||
normalizePeriod,
|
||||
periodRange,
|
||||
yearExtent,
|
||||
} from './period.js';
|
||||
export * from './records.js';
|
||||
export * from './cards.js';
|
||||
export * from './eras.js';
|
||||
export * from './period.js';
|
||||
export { createShipwrecksSource } from './source.js';
|
||||
|
||||
export const SHIPWRECKS_LAYER_ID = 'shipwrecks';
|
||||
export const SHIPWRECKS_OVERLAY_SOURCE_ID = 'shipwrecks';
|
||||
const PICK_PREFIX = 'shipwreck:';
|
||||
const CARD_HOST_OPTIONS = Object.freeze({
|
||||
cohortLimit: 1,
|
||||
collisionCapacity: 1,
|
||||
moving: false,
|
||||
});
|
||||
const MAX_CARD_LINES = 14;
|
||||
/** Wrecks not refreshed for this long leave the map (the proxy's own limit). */
|
||||
const MAX_SHOWN_AGE_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* When the shown wrecks leave the map if the page cannot refresh, on this
|
||||
* page's clock: the age the proxy reports (its own clock) is subtracted from
|
||||
* the limit, so the two clocks are never compared, and the newest source
|
||||
* decides. A wreck both sources list is one merged record, so the snapshot
|
||||
* goes as a whole, not per source. With no age reported, the snapshot counts
|
||||
* as fresh when it arrives.
|
||||
*/
|
||||
export function snapshotDeadline(snapshot, at) {
|
||||
const limit = snapshot.maxAgeMs ?? MAX_SHOWN_AGE_MS;
|
||||
const ages = ['emodnet', 'wikidata']
|
||||
.filter((name) => snapshot.sources?.[name] !== false)
|
||||
.map((name) => snapshot.ages?.[name] ?? 0);
|
||||
const newest = ages.length ? Math.min(...ages) : 0;
|
||||
return at + limit - newest;
|
||||
}
|
||||
/**
|
||||
* Marker size in pixels: grows with the death toll, from 16 px (no deaths known) to 36 px (about a thousand or more).
|
||||
*/
|
||||
export function markerPixelSize(casualties) {
|
||||
const n = Number.isFinite(casualties) && casualties > 0 ? casualties : 0;
|
||||
return Math.round(16 + Math.min(20, Math.log2(1 + n) * 2));
|
||||
}
|
||||
|
||||
/**
|
||||
* A round marker in the era's colour with a sinking hull and mast in the
|
||||
* middle, as an SVG data URL. It is rasterized at 144 px, four times the
|
||||
* largest marker, so big markers stay sharp on high-density screens.
|
||||
* @param {string} color CSS colour.
|
||||
* @returns {string}
|
||||
*/
|
||||
export function wreckMarkerImage(color) {
|
||||
const svg =
|
||||
`<svg xmlns="http://www.w3.org/2000/svg" width="144" height="144" viewBox="0 0 36 36">` +
|
||||
`<circle cx="18" cy="18" r="16" fill="${color}" stroke="#ffffff" stroke-width="2"/>` +
|
||||
`<path d="M8 21h20l-3.5 5h-13z" fill="#0b1420"/>` +
|
||||
`<path d="M17 8v12M17 9l6 7h-6" fill="none" stroke="#0b1420" stroke-width="2.2" stroke-linejoin="round"/>` +
|
||||
`</svg>`;
|
||||
return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shipwrecks: EMODnet's European heritage wrecks and Wikidata's notable
|
||||
* wrecks worldwide, one marker each, with a card and era chips.
|
||||
*/
|
||||
export function createShipwrecksLayer({
|
||||
source,
|
||||
overlayHost = null,
|
||||
picking = null,
|
||||
pointer = null,
|
||||
openExternal = null,
|
||||
now = () => Date.now(),
|
||||
// The clicks on the globe: the application's input dispatcher.
|
||||
input = (viewer) => inputFor(viewer),
|
||||
} = {}) {
|
||||
if (typeof source?.getSnapshot !== 'function')
|
||||
throw new TypeError('Shipwrecks require a snapshot source');
|
||||
let _viewer = null;
|
||||
let _enabled = false;
|
||||
let _markers = null;
|
||||
let _request = null;
|
||||
let _records = new Map();
|
||||
let _pins = [];
|
||||
let _snapshot = null;
|
||||
let _deadline = null;
|
||||
let _lastError = null;
|
||||
let _clickHandler = null;
|
||||
let _rowListener = null;
|
||||
let _selectedId = null;
|
||||
let _selectedCardId = null;
|
||||
let _selectedLink = null;
|
||||
let _period = { from: null, to: null };
|
||||
let _extent = null;
|
||||
let _range = null;
|
||||
const _images = Object.fromEntries(
|
||||
SHIPWRECK_ERAS.map((era) => [era, wreckMarkerImage(ERA_COLORS[era])]),
|
||||
);
|
||||
|
||||
const render = () => {
|
||||
flushPins();
|
||||
if (_viewer) findFrame(_viewer)?.requestRender('shipwrecks');
|
||||
};
|
||||
const notifyRow = () => _rowListener?.();
|
||||
const canSelect = () => overlayHost && picking;
|
||||
/** Pins whose marker changed since the set was last written. */
|
||||
const changedPins = new Set();
|
||||
// Markers skip the depth test so terrain does not swallow them; the
|
||||
// horizon cull hides the far side of the planet instead.
|
||||
const _horizon = createHorizonCull({
|
||||
getViewer: () => _viewer,
|
||||
items: () => _pins,
|
||||
onChange: render,
|
||||
});
|
||||
|
||||
/** Shown: its year is inside the period (undated ones only for all years). */
|
||||
function visible(record) {
|
||||
return Boolean(record) && inPeriod(record, _range);
|
||||
}
|
||||
|
||||
function applyPin(pin) {
|
||||
const show = pin.inFront && visible(pin.record);
|
||||
if (pin.item.show === show) return;
|
||||
pin.item = { ...pin.item, show };
|
||||
changedPins.add(pin);
|
||||
}
|
||||
|
||||
/** Send the markers that changed to the set. */
|
||||
function flushPins() {
|
||||
if (!changedPins.size) return;
|
||||
const items = [...changedPins].map((pin) => pin.item);
|
||||
changedPins.clear();
|
||||
_markers?.upsert(items);
|
||||
}
|
||||
|
||||
/** Re-apply the period to every marker and the open card. */
|
||||
function applyFilter() {
|
||||
for (const pin of _pins) applyPin(pin);
|
||||
if (_selectedId && !visible(_records.get(_selectedId))) clearSelection();
|
||||
notifyRow();
|
||||
render();
|
||||
}
|
||||
|
||||
function rebuild(records) {
|
||||
_records = new Map(records.map((record) => [record.id, record]));
|
||||
_extent = yearExtent(records);
|
||||
_range = periodRange(_period, _extent);
|
||||
_pins = [];
|
||||
changedPins.clear();
|
||||
if (!_markers) return;
|
||||
// Within one set later markers draw on top: add by rising death toll so
|
||||
// a bigger toll covers smaller neighbours.
|
||||
const ordered = [...records].sort(
|
||||
(a, b) => (a.casualties || 0) - (b.casualties || 0),
|
||||
);
|
||||
for (const record of ordered) {
|
||||
const position = fromDegrees(record.lon, record.lat);
|
||||
const size = markerPixelSize(record.casualties);
|
||||
const pin = {
|
||||
// The marker as the set draws it.
|
||||
item: {
|
||||
id: `${PICK_PREFIX}${record.id}`,
|
||||
pos: position,
|
||||
image: _images[eraOf(record)],
|
||||
size: [size, size],
|
||||
height: 'clampGround',
|
||||
disableDepthTest: Number.POSITIVE_INFINITY,
|
||||
show: true,
|
||||
},
|
||||
record,
|
||||
position,
|
||||
inFront: true,
|
||||
get show() {
|
||||
return this.inFront;
|
||||
},
|
||||
set show(value) {
|
||||
this.inFront = value;
|
||||
applyPin(this);
|
||||
},
|
||||
};
|
||||
applyPin(pin);
|
||||
_pins.push(pin);
|
||||
}
|
||||
changedPins.clear();
|
||||
_markers.set(_pins.map((pin) => pin.item));
|
||||
_horizon.update();
|
||||
if (_selectedId && !_records.has(_selectedId)) clearSelection();
|
||||
else if (_selectedId) publishCard();
|
||||
render();
|
||||
}
|
||||
|
||||
// ---- selection card ----------------------------------------------------
|
||||
function publishCard() {
|
||||
if (!canSelect()) return;
|
||||
const record = _selectedId ? _records.get(_selectedId) : null;
|
||||
if (!visible(record)) {
|
||||
clearSelection();
|
||||
return;
|
||||
}
|
||||
const { title, details, link } = describeShipwreck(record);
|
||||
_selectedLink = link && openExternal ? link : null;
|
||||
const card = {
|
||||
id: `shipwreck-card:${record.id}`,
|
||||
selected: true,
|
||||
interactive: Boolean(_selectedLink),
|
||||
title,
|
||||
details: details.slice(0, MAX_CARD_LINES),
|
||||
accent: ERA_COLORS[eraOf(record)],
|
||||
priority: Number.MAX_SAFE_INTEGER,
|
||||
gapPx: 15,
|
||||
verticalOnly: true,
|
||||
placement: 'above',
|
||||
stateless: true,
|
||||
horizonCull: true,
|
||||
position: fromDegrees(record.lon, record.lat),
|
||||
};
|
||||
if (card.interactive) {
|
||||
const target = _selectedLink;
|
||||
card.accessibilityLabel = t('Open the source for {title}', { title });
|
||||
card.activate = () => {
|
||||
openExternal(target);
|
||||
return true;
|
||||
};
|
||||
}
|
||||
_selectedCardId = card.id;
|
||||
overlayHost.setEntries(
|
||||
SHIPWRECKS_OVERLAY_SOURCE_ID,
|
||||
[card],
|
||||
CARD_HOST_OPTIONS,
|
||||
);
|
||||
overlayHost.setVisible?.(SHIPWRECKS_OVERLAY_SOURCE_ID, true);
|
||||
}
|
||||
|
||||
function clearSelection() {
|
||||
_selectedId = null;
|
||||
_selectedCardId = null;
|
||||
_selectedLink = null;
|
||||
overlayHost?.setEntries(
|
||||
SHIPWRECKS_OVERLAY_SOURCE_ID,
|
||||
[],
|
||||
CARD_HOST_OPTIONS,
|
||||
);
|
||||
}
|
||||
|
||||
function pickedRecordId(pickId) {
|
||||
if (typeof pickId !== 'string' || !pickId.startsWith(PICK_PREFIX))
|
||||
return null;
|
||||
const id = pickId.slice(PICK_PREFIX.length);
|
||||
return _records.has(id) ? id : null;
|
||||
}
|
||||
|
||||
function installClickHandler() {
|
||||
if (!canSelect() || _clickHandler || !_viewer) return;
|
||||
picking.registerPickOwner?.(
|
||||
SHIPWRECKS_LAYER_ID,
|
||||
(pickedId) =>
|
||||
typeof pickedId === 'string' && pickedId.startsWith(PICK_PREFIX),
|
||||
);
|
||||
// A viewer with no renderer input bound takes no clicks.
|
||||
let clicks = null;
|
||||
try {
|
||||
clicks = input(_viewer) ?? null;
|
||||
} catch {
|
||||
clicks = null;
|
||||
}
|
||||
if (!clicks) return;
|
||||
_clickHandler = clicks.onClick((click) => {
|
||||
if (pointer && !pointer.isPointerFree()) return;
|
||||
const at = click.screenPosition;
|
||||
const cardHit = overlayHost.hitTest?.(at?.x, at?.y, {
|
||||
sourceId: SHIPWRECKS_OVERLAY_SOURCE_ID,
|
||||
});
|
||||
if (cardHit && cardHit.entryId === _selectedCardId) {
|
||||
if (_selectedLink) openExternal(_selectedLink);
|
||||
return;
|
||||
}
|
||||
// A marker's item id is its pick id, `shipwreck:<id>`.
|
||||
const pickId = click.id ?? null;
|
||||
const id = pickedRecordId(pickId);
|
||||
if (id) {
|
||||
_selectedId = id;
|
||||
publishCard();
|
||||
render();
|
||||
return;
|
||||
}
|
||||
if (pickId && picking.isOwnedByOtherLayer(SHIPWRECKS_LAYER_ID, pickId))
|
||||
return;
|
||||
if (_selectedId) {
|
||||
clearSelection();
|
||||
render();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function removeClickHandler() {
|
||||
_clickHandler?.();
|
||||
_clickHandler = null;
|
||||
picking?.unregisterPickOwner?.(SHIPWRECKS_LAYER_ID);
|
||||
}
|
||||
|
||||
/** Wrecks shown per era, in one pass over the records. */
|
||||
function eraCounts() {
|
||||
const counts = Object.fromEntries(SHIPWRECK_ERAS.map((era) => [era, 0]));
|
||||
for (const record of _records.values())
|
||||
if (inPeriod(record, _range)) counts[eraOf(record)]++;
|
||||
return counts;
|
||||
}
|
||||
|
||||
/** The years that have a dated wreck, plus `extra` ones, newest first. */
|
||||
function yearsInData(extra = []) {
|
||||
const years = new Set(extra);
|
||||
for (const record of _records.values())
|
||||
if (Number.isInteger(record.year)) years.add(record.year);
|
||||
return [...years].sort((a, b) => b - a);
|
||||
}
|
||||
|
||||
/** The start and end year pickers, side by side. */
|
||||
function periodControls() {
|
||||
if (!_extent || _extent.min === _extent.max) return {};
|
||||
const range = periodRange(_period, _extent);
|
||||
const valueText = range.all
|
||||
? t('All years')
|
||||
: range.from === range.to
|
||||
? String(range.from)
|
||||
: `${range.from}–${range.to}`;
|
||||
// Only years with a wreck: a picker of every year since the oldest
|
||||
// dated wreck would run to well over a thousand entries.
|
||||
// The chosen ends stay listed even when no wreck sank that year.
|
||||
const options = yearsInData([range.from, range.to]).map((year) => ({
|
||||
value: year,
|
||||
label: String(year),
|
||||
}));
|
||||
return {
|
||||
range: {
|
||||
id: 'period',
|
||||
label: t('Period'),
|
||||
valueText,
|
||||
from: {
|
||||
label: t('From'),
|
||||
ariaLabel: t('First year of the shipwreck period'),
|
||||
value: range.from,
|
||||
},
|
||||
to: {
|
||||
label: t('To'),
|
||||
ariaLabel: t('Last year of the shipwreck period'),
|
||||
value: range.to,
|
||||
},
|
||||
options,
|
||||
params: (end, value) => ({ [end]: Number(value) }),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const layer = {
|
||||
id: SHIPWRECKS_LAYER_ID,
|
||||
name: 'Shipwrecks',
|
||||
icon: '⚓',
|
||||
source: 'EMODnet · Wikidata',
|
||||
// The proxy refreshes once a day; this only notices a new snapshot.
|
||||
updateInterval: 6 * 60 * 60 * 1000,
|
||||
|
||||
init(viewer) {
|
||||
if (_viewer) throw new Error('Shipwrecks layer is already initialized');
|
||||
_viewer = viewer;
|
||||
// One set for every wreck marker (thousands of them), under the other
|
||||
// sprite layers (`SPRITE_LAYER_ORDER`).
|
||||
_markers = drawOf(viewer).icons({
|
||||
id: 'shipwrecks:markers',
|
||||
drawOrder: spriteDrawOrder(SHIPWRECKS_LAYER_ID),
|
||||
show: false,
|
||||
});
|
||||
},
|
||||
|
||||
enable() {
|
||||
_enabled = true;
|
||||
if (_markers) _markers.show = true;
|
||||
installClickHandler();
|
||||
if (_pins.length) _horizon.update();
|
||||
render();
|
||||
},
|
||||
|
||||
disable() {
|
||||
_enabled = false;
|
||||
_request?.abort();
|
||||
_request = null;
|
||||
if (_markers) _markers.show = false;
|
||||
removeClickHandler();
|
||||
clearSelection();
|
||||
_horizon.stop();
|
||||
render();
|
||||
},
|
||||
|
||||
async update() {
|
||||
if (!_enabled || !_markers) return false;
|
||||
_request?.abort();
|
||||
const request = new AbortController();
|
||||
_request = request;
|
||||
try {
|
||||
const snapshot = await source.getSnapshot({ signal: request.signal });
|
||||
if (request.signal.aborted || _request !== request || !_enabled)
|
||||
return false;
|
||||
// The page checks every 6 h; the proxy refreshes once a day. Only a
|
||||
// new snapshot rebuilds the markers.
|
||||
const unchanged =
|
||||
typeof snapshot.version === 'string' &&
|
||||
snapshot.version === _snapshot?.version &&
|
||||
_pins.length > 0;
|
||||
_snapshot = snapshot;
|
||||
_deadline = snapshotDeadline(snapshot, now());
|
||||
_lastError =
|
||||
snapshot.sources.emodnet && snapshot.sources.wikidata
|
||||
? null
|
||||
: snapshot.sources.emodnet
|
||||
? msg('Wikidata unavailable; showing EMODnet only')
|
||||
: msg('EMODnet unavailable; showing Wikidata only');
|
||||
if (!unchanged) rebuild(snapshot.records);
|
||||
notifyRow();
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (request.signal.aborted || _request !== request || !_enabled)
|
||||
return false;
|
||||
console.warn('[Data:Shipwrecks] Fetch error:', error);
|
||||
_lastError = error?.message || msg('Shipwrecks unavailable');
|
||||
// What is on the map was not refreshed: say so, and drop it once
|
||||
// even its newest source is older than the proxy would serve.
|
||||
if (_snapshot) {
|
||||
if (now() >= _deadline) {
|
||||
_snapshot = null;
|
||||
_deadline = null;
|
||||
rebuild([]);
|
||||
} else _snapshot = { ..._snapshot, stale: true };
|
||||
}
|
||||
notifyRow();
|
||||
return false;
|
||||
} finally {
|
||||
if (_request === request) _request = null;
|
||||
}
|
||||
},
|
||||
|
||||
destroy() {
|
||||
layer.disable();
|
||||
if (_markers) {
|
||||
_markers.dispose();
|
||||
_markers = null;
|
||||
}
|
||||
_records = new Map();
|
||||
_pins = [];
|
||||
_snapshot = null;
|
||||
_deadline = null;
|
||||
_viewer = null;
|
||||
_rowListener = null;
|
||||
},
|
||||
|
||||
/** The period filter: `from` and `to` are years (null = oldest / latest in the data). */
|
||||
getParams() {
|
||||
return { ..._period };
|
||||
},
|
||||
|
||||
setParams(params = {}) {
|
||||
const next = normalizePeriod(params, _period);
|
||||
if (next.from === _period.from && next.to === _period.to) return true;
|
||||
_period = next;
|
||||
_range = periodRange(_period, _extent);
|
||||
applyFilter();
|
||||
return true;
|
||||
},
|
||||
|
||||
setRowControlsListener(listener) {
|
||||
_rowListener = listener;
|
||||
},
|
||||
|
||||
getRowControls() {
|
||||
const counts = eraCounts();
|
||||
return {
|
||||
chips: [],
|
||||
...periodControls(),
|
||||
// The colours are a legend: when the ship sank.
|
||||
legend: SHIPWRECK_ERAS.map((era) => ({
|
||||
label: t(ERA_LABELS[era]),
|
||||
count: counts[era],
|
||||
color: ERA_COLORS[era],
|
||||
blurb: tn(counts[era], '{count} wreck', '{count} wrecks', {
|
||||
count: formatNumber(counts[era]),
|
||||
}),
|
||||
})),
|
||||
info: t('EMODnet (European waters) · Wikidata (worldwide)'),
|
||||
infoTitle: t(
|
||||
'European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.',
|
||||
),
|
||||
};
|
||||
},
|
||||
|
||||
getStats() {
|
||||
let shown = 0;
|
||||
for (const record of _records.values()) if (visible(record)) shown++;
|
||||
return {
|
||||
count: shown,
|
||||
lastUpdate: _snapshot?.fetchedAt ?? null,
|
||||
stale: _snapshot?.stale === true,
|
||||
error: _lastError,
|
||||
};
|
||||
},
|
||||
|
||||
/** Loaded records as plain JSON-safe objects, for tools and QA. */
|
||||
getAnalystRecords(maxCount = 2000) {
|
||||
if (!_enabled) return [];
|
||||
const out = [];
|
||||
for (const record of _records.values()) {
|
||||
if (out.length >= maxCount) break;
|
||||
if (!visible(record)) continue;
|
||||
out.push({
|
||||
id: record.id,
|
||||
source: record.source,
|
||||
name: record.name,
|
||||
vesselType: record.vesselType,
|
||||
year: record.year,
|
||||
era: eraOf(record),
|
||||
lat: record.lat,
|
||||
lon: record.lon,
|
||||
depth: record.depth,
|
||||
casualties: record.casualties,
|
||||
});
|
||||
}
|
||||
return out;
|
||||
},
|
||||
};
|
||||
return layer;
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
import {
|
||||
createShipwrecksLayer,
|
||||
markerPixelSize,
|
||||
snapshotDeadline,
|
||||
} from './index.js';
|
||||
|
||||
const wreck = (id, extra = {}) => ({
|
||||
id,
|
||||
source: 'wikidata',
|
||||
name: id,
|
||||
lat: 50,
|
||||
lon: -1,
|
||||
year: 1912,
|
||||
date: null,
|
||||
casualties: null,
|
||||
...extra,
|
||||
});
|
||||
|
||||
const snapshot = (records, version = 'v1') => ({
|
||||
records,
|
||||
fetchedAt: 1,
|
||||
stale: false,
|
||||
version,
|
||||
sources: { emodnet: true, wikidata: true },
|
||||
});
|
||||
|
||||
function deferred() {
|
||||
let resolve;
|
||||
const promise = new Promise((done) => {
|
||||
resolve = done;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
function harness({ snapshots, now = () => 1 } = {}) {
|
||||
const cards = [];
|
||||
const handlers = [];
|
||||
const opened = [];
|
||||
let pickResult = null;
|
||||
const viewer = {};
|
||||
const { draw } = bindFakeDraw(viewer);
|
||||
const queue = [...(snapshots || [])];
|
||||
const requests = [];
|
||||
const layer = createShipwrecksLayer({
|
||||
source: {
|
||||
getSnapshot({ signal }) {
|
||||
requests.push(signal);
|
||||
const next = queue.shift();
|
||||
if (next instanceof Error) return Promise.reject(next);
|
||||
return next instanceof Promise ? next : Promise.resolve(next);
|
||||
},
|
||||
},
|
||||
overlayHost: {
|
||||
setEntries: (_source, entries) => cards.push(entries),
|
||||
setVisible() {},
|
||||
hitTest: () => null,
|
||||
},
|
||||
// The globe's clicks: one listener per click handler installed.
|
||||
input: () => ({
|
||||
onClick(callback) {
|
||||
const handler = {
|
||||
click: (event) => callback({ ...event, id: pickResult }),
|
||||
destroyed: false,
|
||||
};
|
||||
handlers.push(handler);
|
||||
return () => {
|
||||
handler.destroyed = true;
|
||||
};
|
||||
},
|
||||
}),
|
||||
picking,
|
||||
pointer: { isPointerFree: () => true },
|
||||
openExternal: (url) => opened.push(url),
|
||||
now: () => now(),
|
||||
});
|
||||
layer.init(viewer);
|
||||
const markerSet = () => draw.find('shipwrecks:');
|
||||
return {
|
||||
layer,
|
||||
// The markers' set, its items in drawing order.
|
||||
markers: {
|
||||
get set() {
|
||||
return markerSet();
|
||||
},
|
||||
get show() {
|
||||
return markerSet()?.show;
|
||||
},
|
||||
get billboards() {
|
||||
const set = markerSet();
|
||||
return set && !set.disposed ? [...set.items.values()] : [];
|
||||
},
|
||||
},
|
||||
cards,
|
||||
handlers,
|
||||
requests,
|
||||
opened,
|
||||
pick(id) {
|
||||
pickResult = id ? `shipwreck:${id}` : null;
|
||||
},
|
||||
lastCard: () => cards.at(-1),
|
||||
};
|
||||
}
|
||||
|
||||
test('markers live in one set, shown only while the layer is on', async () => {
|
||||
const h = harness({ snapshots: [snapshot([wreck('a'), wreck('b')])] });
|
||||
assert.ok(h.markers.set, 'one set for every marker');
|
||||
assert.equal(h.markers.show, false);
|
||||
h.layer.enable();
|
||||
assert.equal(h.markers.show, true);
|
||||
assert.equal(await h.layer.update(), true);
|
||||
assert.equal(h.markers.billboards.length, 2);
|
||||
assert.equal(h.layer.getStats().count, 2);
|
||||
h.layer.disable();
|
||||
assert.equal(h.markers.show, false);
|
||||
assert.equal(h.handlers[0].destroyed, true);
|
||||
h.layer.destroy();
|
||||
assert.equal(h.markers.set, undefined, 'the set is disposed');
|
||||
});
|
||||
|
||||
test('markers sit on the wreck: no eye offset, bigger toll drawn last', async () => {
|
||||
const h = harness({
|
||||
snapshots: [
|
||||
snapshot([
|
||||
wreck('big', { casualties: 1500 }),
|
||||
wreck('none'),
|
||||
wreck('small', { casualties: 3 }),
|
||||
]),
|
||||
],
|
||||
});
|
||||
h.layer.enable();
|
||||
await h.layer.update();
|
||||
const ids = h.markers.billboards.map((billboard) => billboard.id);
|
||||
assert.deepEqual(ids, ['shipwreck:none', 'shipwreck:small', 'shipwreck:big']);
|
||||
for (const billboard of h.markers.billboards)
|
||||
assert.equal(billboard.eyeOffset, undefined);
|
||||
assert.deepEqual(h.markers.billboards[2].size, [
|
||||
markerPixelSize(1500),
|
||||
markerPixelSize(1500),
|
||||
]);
|
||||
});
|
||||
|
||||
test('an unchanged snapshot does not rebuild the markers', async () => {
|
||||
const records = [wreck('a')];
|
||||
const h = harness({
|
||||
snapshots: [
|
||||
snapshot(records, 'v1'),
|
||||
snapshot(records, 'v1'),
|
||||
snapshot([wreck('a'), wreck('b')], 'v2'),
|
||||
],
|
||||
});
|
||||
h.layer.enable();
|
||||
await h.layer.update();
|
||||
await h.layer.update();
|
||||
assert.equal(h.markers.set.writes, 1);
|
||||
await h.layer.update();
|
||||
assert.equal(h.markers.set.writes, 2);
|
||||
assert.equal(h.markers.billboards.length, 2);
|
||||
});
|
||||
|
||||
test('a response that arrives after the layer is turned off is ignored', async () => {
|
||||
const late = deferred();
|
||||
const h = harness({ snapshots: [late.promise] });
|
||||
h.layer.enable();
|
||||
const pending = h.layer.update();
|
||||
h.layer.disable();
|
||||
assert.equal(h.requests[0].aborted, true);
|
||||
late.resolve(snapshot([wreck('a')]));
|
||||
assert.equal(await pending, false);
|
||||
assert.equal(h.markers.billboards.length, 0);
|
||||
});
|
||||
|
||||
test('a click opens the card; a period that excludes the wreck closes it', async () => {
|
||||
const h = harness({
|
||||
snapshots: [
|
||||
snapshot([wreck('old', { year: 1850 }), wreck('new', { year: 1990 })]),
|
||||
],
|
||||
});
|
||||
h.layer.enable();
|
||||
await h.layer.update();
|
||||
h.pick('old');
|
||||
h.handlers[0].click({ screenPosition: { x: 1, y: 1 } });
|
||||
const [card] = h.lastCard();
|
||||
assert.equal(card.id, 'shipwreck-card:old');
|
||||
h.layer.setParams({ from: 1900, to: 1990 });
|
||||
assert.deepEqual(h.lastCard(), [], 'the hidden wreck loses its card');
|
||||
const shown = h.markers.billboards.filter((billboard) => billboard.show);
|
||||
assert.deepEqual(
|
||||
shown.map((billboard) => billboard.id),
|
||||
['shipwreck:new'],
|
||||
);
|
||||
assert.equal(h.layer.getStats().count, 1);
|
||||
});
|
||||
|
||||
test('the year pickers list only years with a wreck, and each era is counted', async () => {
|
||||
const h = harness({
|
||||
snapshots: [
|
||||
snapshot([
|
||||
wreck('a', { year: 300 }),
|
||||
wreck('b', { year: 1912 }),
|
||||
wreck('c', { year: 1912 }),
|
||||
wreck('d', { year: 1990 }),
|
||||
wreck('e', { year: null }),
|
||||
]),
|
||||
],
|
||||
});
|
||||
h.layer.enable();
|
||||
await h.layer.update();
|
||||
let controls = h.layer.getRowControls();
|
||||
assert.deepEqual(
|
||||
controls.range.options.map((option) => option.value),
|
||||
[1990, 1912, 300],
|
||||
);
|
||||
assert.deepEqual(
|
||||
controls.legend.map((era) => era.count),
|
||||
[1, 2, 1, 1],
|
||||
);
|
||||
h.layer.setParams({ from: 1900, to: 1950 });
|
||||
controls = h.layer.getRowControls();
|
||||
assert.deepEqual(
|
||||
controls.range.options.map((option) => option.value),
|
||||
[1990, 1950, 1912, 1900, 300],
|
||||
'the chosen ends are listed too',
|
||||
);
|
||||
assert.deepEqual(
|
||||
controls.legend.map((era) => era.count),
|
||||
[0, 2, 0, 0],
|
||||
);
|
||||
});
|
||||
|
||||
test('a source without a version rebuilds on every new snapshot', async () => {
|
||||
const bare = (records) => {
|
||||
const value = snapshot(records);
|
||||
delete value.version;
|
||||
return value;
|
||||
};
|
||||
const h = harness({
|
||||
snapshots: [
|
||||
bare([wreck('a')]),
|
||||
bare([wreck('a'), wreck('b')]),
|
||||
{ ...snapshot([wreck('a')]), version: null },
|
||||
{ ...snapshot([wreck('a'), wreck('b'), wreck('c')]), version: null },
|
||||
],
|
||||
});
|
||||
h.layer.enable();
|
||||
for (const expected of [1, 2, 1, 3]) {
|
||||
await h.layer.update();
|
||||
assert.equal(h.markers.billboards.length, expected);
|
||||
}
|
||||
});
|
||||
|
||||
test('a failed refresh marks the shown wrecks stale, and clears them after seven days', async () => {
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
let clock = 1;
|
||||
const h = harness({
|
||||
now: () => clock,
|
||||
snapshots: [
|
||||
snapshot([wreck('a')]),
|
||||
new Error('Shipwrecks unavailable (HTTP 502)'),
|
||||
new Error('Shipwrecks unavailable (HTTP 502)'),
|
||||
],
|
||||
});
|
||||
h.layer.enable();
|
||||
await h.layer.update();
|
||||
assert.equal(h.layer.getStats().stale, false);
|
||||
clock = 1 + 2 * DAY;
|
||||
assert.equal(await h.layer.update(), false);
|
||||
assert.equal(h.layer.getStats().stale, true);
|
||||
assert.equal(h.layer.getStats().count, 1, 'still shown, as stale');
|
||||
clock = 1 + 8 * DAY;
|
||||
await h.layer.update();
|
||||
assert.equal(h.layer.getStats().count, 0, 'expired wrecks leave the map');
|
||||
assert.equal(h.markers.billboards.length, 0);
|
||||
});
|
||||
|
||||
test('expiry runs on the page clock and keeps every wreck until the newest source is too old', async () => {
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
const down = () => new Error('Shipwrecks unavailable (HTTP 502)');
|
||||
// The page clock is far from the proxy's fetchedAt: only reported ages count.
|
||||
let clock = 5e12;
|
||||
const h = harness({
|
||||
now: () => clock,
|
||||
snapshots: [
|
||||
{
|
||||
...snapshot([
|
||||
wreck('fresh', { source: 'emodnet' }),
|
||||
wreck('merged', { source: 'wikidata', alsoIn: 'emodnet' }),
|
||||
]),
|
||||
fetchedAt: 1,
|
||||
ages: { emodnet: 0, wikidata: 6.5 * DAY },
|
||||
maxAgeMs: 7 * DAY,
|
||||
},
|
||||
down(),
|
||||
down(),
|
||||
],
|
||||
});
|
||||
h.layer.enable();
|
||||
await h.layer.update();
|
||||
clock += 1 * DAY;
|
||||
await h.layer.update();
|
||||
assert.equal(
|
||||
h.layer.getStats().count,
|
||||
2,
|
||||
'nothing leaves while EMODnet is in date',
|
||||
);
|
||||
assert.equal(h.layer.getStats().stale, true);
|
||||
clock += 6.5 * DAY;
|
||||
await h.layer.update();
|
||||
assert.equal(
|
||||
h.layer.getStats().count,
|
||||
0,
|
||||
'all leave once the newest is too old',
|
||||
);
|
||||
});
|
||||
|
||||
test('a snapshot with no timestamp or ages still expires seven days after it arrived', async () => {
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
let clock = 100;
|
||||
const h = harness({
|
||||
now: () => clock,
|
||||
snapshots: [
|
||||
{ ...snapshot([wreck('a')]), fetchedAt: null },
|
||||
new Error('down'),
|
||||
],
|
||||
});
|
||||
h.layer.enable();
|
||||
await h.layer.update();
|
||||
clock += 8 * DAY;
|
||||
await h.layer.update();
|
||||
assert.equal(h.layer.getStats().count, 0);
|
||||
});
|
||||
|
||||
test('the page deadline subtracts the newest available source age from the limit', () => {
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
const both = { emodnet: true, wikidata: true };
|
||||
assert.equal(
|
||||
snapshotDeadline(
|
||||
{
|
||||
sources: both,
|
||||
ages: { emodnet: 2 * DAY, wikidata: 6.5 * DAY },
|
||||
maxAgeMs: 5 * DAY,
|
||||
},
|
||||
100,
|
||||
),
|
||||
100 + 3 * DAY,
|
||||
);
|
||||
assert.equal(
|
||||
snapshotDeadline(
|
||||
{
|
||||
sources: { emodnet: false, wikidata: true },
|
||||
ages: { emodnet: null, wikidata: 4 * DAY },
|
||||
maxAgeMs: 5 * DAY,
|
||||
},
|
||||
0,
|
||||
),
|
||||
1 * DAY,
|
||||
'an unavailable source does not count',
|
||||
);
|
||||
assert.equal(snapshotDeadline({ sources: both }, 0), 7 * DAY, 'defaults');
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* The sinking year, or null when it is unknown (ancient wrecks dated only by
|
||||
* period, "C1st AD", have none).
|
||||
*/
|
||||
export function recordYear(record) {
|
||||
return Number.isInteger(record?.year) ? record.year : null;
|
||||
}
|
||||
|
||||
/** First and last year present in the records (null when none is dated). */
|
||||
export function yearExtent(records) {
|
||||
let min = Infinity;
|
||||
let max = -Infinity;
|
||||
for (const record of records) {
|
||||
const year = recordYear(record);
|
||||
if (year === null) continue;
|
||||
if (year < min) min = year;
|
||||
if (year > max) max = year;
|
||||
}
|
||||
return Number.isFinite(min) ? { min, max } : null;
|
||||
}
|
||||
|
||||
function yearParam(value) {
|
||||
if (value === null) return null;
|
||||
const year =
|
||||
typeof value === 'string' && /^-?\d+$/.test(value) ? Number(value) : value;
|
||||
return Number.isInteger(year) && Math.abs(year) < 10000 ? year : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge a (partial) period request into the current one. `from: null` means
|
||||
* the first year in the data and `to: null` the latest; an invalid year keeps
|
||||
* the current one, and a start after the end is stored as the reverse.
|
||||
* @param {{from?: number|string|null, to?: number|string|null}} params
|
||||
* @param {{from: number|null, to: number|null}} current
|
||||
* @returns {{from: number|null, to: number|null}}
|
||||
*/
|
||||
export function normalizePeriod(
|
||||
params = {},
|
||||
current = { from: null, to: null },
|
||||
) {
|
||||
const next = { ...current };
|
||||
for (const end of ['from', 'to']) {
|
||||
if (!(end in params)) continue;
|
||||
const year = yearParam(params[end]);
|
||||
if (year !== undefined) next[end] = year;
|
||||
}
|
||||
// Stored in the order it is shown, so a later edit to one end (the picker
|
||||
// sends only that end) changes the end the reader picked, not the other.
|
||||
if (Number.isInteger(next.from) && Number.isInteger(next.to))
|
||||
if (next.from > next.to) [next.from, next.to] = [next.to, next.from];
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* The inclusive year range a period covers over the data's extent. Years are
|
||||
* clamped to the data, and a start after the end is read as the reverse.
|
||||
* @returns {{from: number, to: number, all: boolean}|null}
|
||||
*/
|
||||
export function periodRange(period, extent) {
|
||||
if (!extent) return null;
|
||||
const clamp = (year, fallback) =>
|
||||
Math.min(extent.max, Math.max(extent.min, year ?? fallback));
|
||||
const start = clamp(period.from, extent.min);
|
||||
const end = clamp(period.to, extent.max);
|
||||
const from = Math.min(start, end);
|
||||
const to = Math.max(start, end);
|
||||
return { from, to, all: from === extent.min && to === extent.max };
|
||||
}
|
||||
|
||||
/** Whether a record falls in the range; undated records only when all years show. */
|
||||
export function inPeriod(record, range) {
|
||||
if (!range || range.all) return true;
|
||||
const year = recordYear(record);
|
||||
return year !== null && year >= range.from && year <= range.to;
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
inPeriod,
|
||||
normalizePeriod,
|
||||
periodRange,
|
||||
recordYear,
|
||||
yearExtent,
|
||||
} from './period.js';
|
||||
|
||||
const RECORDS = [
|
||||
{ year: 1588 },
|
||||
{ year: 1912 },
|
||||
{ year: 2012 },
|
||||
{ year: null, ancient: true },
|
||||
];
|
||||
|
||||
test('years come from the record; the extent ignores undated wrecks', () => {
|
||||
assert.equal(recordYear(RECORDS[1]), 1912);
|
||||
assert.equal(recordYear(RECORDS[3]), null);
|
||||
assert.deepEqual(yearExtent(RECORDS), { min: 1588, max: 2012 });
|
||||
assert.equal(yearExtent([{ year: null }]), null);
|
||||
});
|
||||
|
||||
test('all years show every wreck; a narrower period hides undated ones', () => {
|
||||
const extent = yearExtent(RECORDS);
|
||||
const all = periodRange({ from: null, to: null }, extent);
|
||||
assert.deepEqual(all, { from: 1588, to: 2012, all: true });
|
||||
assert.ok(RECORDS.every((record) => inPeriod(record, all)));
|
||||
const wars = periodRange(normalizePeriod({ from: '1914', to: 1945 }), extent);
|
||||
assert.deepEqual(
|
||||
RECORDS.map((record) => inPeriod(record, wars)),
|
||||
[false, false, false, false],
|
||||
);
|
||||
const reversed = periodRange({ from: 1950, to: 1900 }, extent);
|
||||
assert.deepEqual(reversed, { from: 1900, to: 1950, all: false });
|
||||
assert.equal(inPeriod(RECORDS[1], reversed), true);
|
||||
});
|
||||
|
||||
test('a reversed period is stored as shown, so editing one end keeps the other', () => {
|
||||
const reversed = normalizePeriod({ from: 1950, to: 1900 });
|
||||
assert.deepEqual(reversed, { from: 1900, to: 1950 });
|
||||
// The picker shows 1900–1950; the reader changes "From" to 1920.
|
||||
assert.deepEqual(normalizePeriod({ from: 1920 }, reversed), {
|
||||
from: 1920,
|
||||
to: 1950,
|
||||
});
|
||||
// Moving "From" past "To" reads as the reverse, never an empty range.
|
||||
assert.deepEqual(normalizePeriod({ from: 1960 }, { from: 1900, to: 1950 }), {
|
||||
from: 1950,
|
||||
to: 1960,
|
||||
});
|
||||
// One open end stays open.
|
||||
assert.deepEqual(normalizePeriod({ from: 1960 }, { from: null, to: null }), {
|
||||
from: 1960,
|
||||
to: null,
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,455 @@
|
||||
// Shared by the server proxy (server/providers/shipwrecks.js) and the browser
|
||||
// layer, so it must not load the i18n catalogs: values stay data.
|
||||
|
||||
/** EMODnet Human Activities "Cultural Heritage – Ship wrecks" (CC BY 4.0). */
|
||||
export const EMODNET_WFS_URL =
|
||||
'https://ows.emodnet-humanactivities.eu/wfs?service=WFS&request=GetFeature' +
|
||||
'&version=2.0.0&typeNames=emodnet:heritageshipwrecks' +
|
||||
'&outputFormat=application/json&srsName=EPSG:4326';
|
||||
/** Landing page shown when an EMODnet wreck has no web page of its own. */
|
||||
export const EMODNET_PAGE_URL =
|
||||
'https://emodnet.ec.europa.eu/en/human-activities';
|
||||
|
||||
export const SHIPWRECK_SOURCES = Object.freeze(['emodnet', 'wikidata']);
|
||||
|
||||
/**
|
||||
* Wikidata (CC0): shipwreck items that have at least one Wikipedia article,
|
||||
* so the worldwide set stays to notable wrecks and skips bulk register
|
||||
* imports, plus sinking events ("sinking of the RMS Titanic"), which are where
|
||||
* Wikidata keeps the death toll. Dates, the end of service (P576) included,
|
||||
* come with their precision so a month-precise date is not shown as the 1st.
|
||||
* Only ship and event facts are read: no items about people.
|
||||
*/
|
||||
export const WIKIDATA_QUERY = `SELECT ?item ?itemLabel ?itemDescription ?coord ?sunk ?sunkPrecision ?end ?endPrecision ?deaths ?survivors ?typeLabel ?enwiki ?event WHERE {
|
||||
{
|
||||
?item wdt:P31/wdt:P279* wd:Q852190 ; wdt:P625 ?coord ; wikibase:sitelinks ?links .
|
||||
FILTER(?links > 0)
|
||||
OPTIONAL { ?item p:P793 ?wreck . ?wreck ps:P793 wd:Q906512 ; pqv:P585 [ wikibase:timeValue ?sunk ; wikibase:timePrecision ?sunkPrecision ] }
|
||||
OPTIONAL { ?item p:P576 [ a wikibase:BestRank ; psv:P576 [ wikibase:timeValue ?end ; wikibase:timePrecision ?endPrecision ] ] }
|
||||
OPTIONAL { ?item wdt:P31 ?type . FILTER(?type != wd:Q852190) }
|
||||
} UNION {
|
||||
?item wdt:P31/wdt:P279* wd:Q906512 ; wdt:P625 ?coord .
|
||||
BIND("event" AS ?event)
|
||||
OPTIONAL { ?item p:P585/psv:P585 [ wikibase:timeValue ?sunk ; wikibase:timePrecision ?sunkPrecision ] }
|
||||
OPTIONAL { ?item wdt:P1561 ?survivors }
|
||||
}
|
||||
OPTIONAL { ?item wdt:P1120 ?deaths }
|
||||
OPTIONAL { ?enwiki schema:about ?item ; schema:isPartOf <https://en.wikipedia.org/> }
|
||||
SERVICE wikibase:label { bd:serviceParam wikibase:language "en,mul,fr,de,es,it,pt,ru,uk,ja,zh,ar". }
|
||||
}`;
|
||||
|
||||
const MAX_TEXT = 160;
|
||||
const MAX_NOTE = 260;
|
||||
/** Same name within this distance: one wreck seen by both sources. */
|
||||
const SAME_WRECK_KM = 3;
|
||||
|
||||
// Free text sometimes names people (owners, masters, divers who reported a
|
||||
// wreck). The layer is about ships, so text that refers to a person by a title
|
||||
// or role is dropped whole. This is a keyword filter: a bare name with none of
|
||||
// these words still passes.
|
||||
const PERSON_TEXT =
|
||||
/\b(mr|mrs|ms|dr|capt|captain|master|skipper|owner|owned|crew|body|bodies|drowned|reported by|according to)\b/i;
|
||||
|
||||
/** EMODnet writes "n/a" or nothing where a value is unknown. */
|
||||
function clean(value, max = MAX_TEXT) {
|
||||
if (typeof value !== 'string') return null;
|
||||
const text = value
|
||||
.replace(/[\u0000-\u001f<>]/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
if (!text || /^(n\/a|null|unknown|none|-)$/i.test(text)) return null;
|
||||
return text.length > max ? `${text.slice(0, max - 1).trimEnd()}…` : text;
|
||||
}
|
||||
|
||||
/** Free text with none of the person keywords in it, or null. */
|
||||
function impersonalText(value, max) {
|
||||
const text = clean(value, max);
|
||||
return text && !PERSON_TEXT.test(text) ? text : null;
|
||||
}
|
||||
|
||||
function positiveNumber(value, max) {
|
||||
const n = typeof value === 'number' ? value : Number(value);
|
||||
return Number.isFinite(n) && n > 0 && n <= max ? n : null;
|
||||
}
|
||||
|
||||
function count(value) {
|
||||
const text = String(value ?? '').replace(/\.0+$/, '');
|
||||
if (!/^\d{1,6}$/.test(text)) return null;
|
||||
return Number(text);
|
||||
}
|
||||
|
||||
/** A sinking year from "1917", "1917-1918" or "c. 1917"; null otherwise. */
|
||||
export function parseYear(value, maxYear = new Date().getUTCFullYear()) {
|
||||
const match = /(?:^|\D)(\d{3,4})(?:\D|$)/.exec(String(value ?? ''));
|
||||
if (!match) return null;
|
||||
const year = Number(match[1]);
|
||||
return year >= 100 && year <= maxYear ? year : null;
|
||||
}
|
||||
|
||||
function validPoint(lat, lon) {
|
||||
return (
|
||||
Number.isFinite(lat) &&
|
||||
Number.isFinite(lon) &&
|
||||
Math.abs(lat) <= 90 &&
|
||||
Math.abs(lon) <= 180 &&
|
||||
!(lat === 0 && lon === 0)
|
||||
);
|
||||
}
|
||||
|
||||
function httpUrl(value) {
|
||||
const text = clean(value, 400);
|
||||
if (!text) return null;
|
||||
try {
|
||||
const url = new URL(text);
|
||||
return url.protocol === 'https:' || url.protocol === 'http:'
|
||||
? url.href
|
||||
: null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether a provenance or link value points at wrecksite.eu, in any form. */
|
||||
function fromWrecksite(value) {
|
||||
return typeof value === 'string' && /wrecksite/i.test(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize EMODnet's shipwreck GeoJSON. Records the portal took from
|
||||
* wrecksite.eu, named in the provenance or linked as the record's page, are
|
||||
* skipped: that site's data is not openly licensed.
|
||||
* @param {object} payload WFS GeoJSON FeatureCollection.
|
||||
* @returns {object[]} Shipwreck records.
|
||||
*/
|
||||
export function normalizeEmodnetFeatures(payload) {
|
||||
const features = payload?.features;
|
||||
if (!Array.isArray(features)) return [];
|
||||
const out = [];
|
||||
const ids = new Set();
|
||||
for (const feature of features) {
|
||||
const p = feature?.properties || {};
|
||||
const coords = feature?.geometry?.coordinates;
|
||||
if (feature?.geometry?.type !== 'Point' || !Array.isArray(coords)) continue;
|
||||
const lon = Number(coords[0]);
|
||||
const lat = Number(coords[1]);
|
||||
if (!validPoint(lat, lon)) continue;
|
||||
// Checked on the raw values: the shown origin is cut to 80 characters,
|
||||
// and a long provenance list can name wrecksite.eu after the cut.
|
||||
if (fromWrecksite(p.source_inf) || fromWrecksite(p.website1)) continue;
|
||||
const origin = clean(p.source_inf, 80);
|
||||
const key = clean(String(feature.id ?? p.source_id ?? ''), 80);
|
||||
if (!key) continue;
|
||||
const id = `emodnet:${key}`;
|
||||
if (ids.has(id)) continue;
|
||||
ids.add(id);
|
||||
const year = parseYear(p.sink_yr);
|
||||
const dating = clean(p.dating, 60);
|
||||
const period = clean(p.period, 60);
|
||||
const vesselType =
|
||||
clean(p.obj_type, 60) ||
|
||||
(() => {
|
||||
// ship_char is sometimes a short type ("Trawler"), sometimes a long
|
||||
// history that can name people; only the short form is a type.
|
||||
const text = clean(p.ship_char, 40);
|
||||
return text && !/\d/.test(text) && !PERSON_TEXT.test(text)
|
||||
? text
|
||||
: null;
|
||||
})();
|
||||
out.push({
|
||||
id,
|
||||
source: 'emodnet',
|
||||
lat,
|
||||
lon,
|
||||
name: clean(p.name, 100),
|
||||
vesselType,
|
||||
year,
|
||||
date: null,
|
||||
dating: year ? null : dating,
|
||||
ancient: !year && Boolean(period || dating),
|
||||
cause: impersonalText(p.sink_context, MAX_NOTE),
|
||||
notes: period && dating ? `${period} (${dating})` : period,
|
||||
cargo: impersonalText(p.artefacts, 120),
|
||||
protected: /protected/i.test(p.statutory || ''),
|
||||
depth: positiveNumber(p.least_depth, 11000),
|
||||
depthQuality: clean(p.depth_prec, 80),
|
||||
positionAccuracy: positiveNumber(p.loc_prec, 100000),
|
||||
positionNote: /centroid/i.test(p.point_info || '')
|
||||
? 'Centre of the protected area'
|
||||
: null,
|
||||
casualties: null,
|
||||
survivors: null,
|
||||
country: clean(p.country, 60),
|
||||
originator: origin,
|
||||
url: httpUrl(p.website1),
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function wikiUrl(value) {
|
||||
const url = httpUrl(value);
|
||||
return url && /^https:\/\/[a-z]{2,3}\.wikipedia\.org\/wiki\//.test(url)
|
||||
? url
|
||||
: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A Wikidata time as a day ("1912-04-15") when it is day-precise, else as a
|
||||
* year only: a month- or year-precise value reads back as the 1st. A year
|
||||
* before AD 100 ("-0299", 300 BC) has no place on the year picker, so it is
|
||||
* kept as ancient with its year as text, like EMODnet's period-dated wrecks.
|
||||
* @returns {{date: string|null, year: number|null, dating: string|null}}
|
||||
*/
|
||||
function wikidataTime(value, precision) {
|
||||
const none = { date: null, year: null, dating: null };
|
||||
const match = /^([+-]?)(\d{4,})-(\d{2})-(\d{2})T/.exec(value || '');
|
||||
if (!match) return none;
|
||||
// A value without a precision is only trusted to the year.
|
||||
const p = precision == null ? 9 : Number(precision);
|
||||
// 11 = day; 10 = month; 9 = year; below 9 is a decade or coarser.
|
||||
if (!Number.isFinite(p) || p < 9) return none;
|
||||
const signed = Number(`${match[1] === '-' ? '-' : ''}${match[2]}`);
|
||||
if (signed < 100) {
|
||||
// The query service writes XSD 1.1 years: 0000 is 1 BC, -0299 is 300 BC.
|
||||
const dating = signed <= 0 ? `${1 - signed} BC` : `AD ${signed}`;
|
||||
return { date: null, year: null, dating };
|
||||
}
|
||||
const year = parseYear(String(signed));
|
||||
if (year === null) return none;
|
||||
if (p >= 11)
|
||||
return { date: `${match[2]}-${match[3]}-${match[4]}`, year, dating: null };
|
||||
return { date: null, year, dating: null };
|
||||
}
|
||||
|
||||
/** Whether a record (or a parsed time) says when the ship sank. */
|
||||
function hasWhen(when) {
|
||||
return Boolean(when.date || Number.isInteger(when.year) || when.dating);
|
||||
}
|
||||
|
||||
/** Copy when a ship sank from one record (or parsed time) to another. */
|
||||
function takeWhen(target, from) {
|
||||
target.date = from.date ?? null;
|
||||
target.year = from.year ?? null;
|
||||
target.dating = from.dating ?? null;
|
||||
target.ancient = Boolean(from.dating) || Boolean(from.ancient);
|
||||
}
|
||||
|
||||
/** "sinking of the RMS Titanic" → "Sinking of the RMS Titanic". */
|
||||
function sentenceCase(text) {
|
||||
return text ? text.charAt(0).toUpperCase() + text.slice(1) : text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize Wikidata SPARQL results to shipwreck records (one per item).
|
||||
* Sinking events are folded into the ship they sank when both are listed.
|
||||
* @param {object} payload SPARQL JSON results.
|
||||
* @returns {object[]}
|
||||
*/
|
||||
export function normalizeWikidataResults(payload) {
|
||||
const bindings = payload?.results?.bindings;
|
||||
if (!Array.isArray(bindings)) return [];
|
||||
const byItem = new Map();
|
||||
for (const binding of bindings) {
|
||||
const value = (key) => binding?.[key]?.value;
|
||||
const qid = /\/entity\/(Q\d{1,12})$/.exec(value('item') || '')?.[1];
|
||||
if (!qid) continue;
|
||||
const sunk = wikidataTime(value('sunk'), value('sunkPrecision'));
|
||||
const ended = wikidataTime(value('end'), value('endPrecision'));
|
||||
const known = byItem.get(qid);
|
||||
if (known) {
|
||||
// Extra rows only add what the first one lacked.
|
||||
known.vesselType ||= clean(value('typeLabel'), 60);
|
||||
if (!hasWhen(known)) takeWhen(known, hasWhen(sunk) ? sunk : ended);
|
||||
known.casualties ??= count(value('deaths'));
|
||||
known.survivors ??= count(value('survivors'));
|
||||
continue;
|
||||
}
|
||||
const point = /^Point\(([-\d.eE]+) ([-\d.eE]+)\)$/.exec(
|
||||
value('coord') || '',
|
||||
);
|
||||
const lon = point ? Number(point[1]) : NaN;
|
||||
const lat = point ? Number(point[2]) : NaN;
|
||||
if (!validPoint(lat, lon)) continue;
|
||||
const name = clean(value('itemLabel'), 100);
|
||||
const event = value('event') === 'event';
|
||||
const when = hasWhen(sunk) ? sunk : ended;
|
||||
byItem.set(qid, {
|
||||
id: `wikidata:${qid}`,
|
||||
source: 'wikidata',
|
||||
event,
|
||||
lat,
|
||||
lon,
|
||||
// An unlabelled item reads back as its own Q-id; that is no name.
|
||||
name: name && name !== qid ? (event ? sentenceCase(name) : name) : null,
|
||||
vesselType: event ? null : clean(value('typeLabel'), 60),
|
||||
year: when.year,
|
||||
date: when.date,
|
||||
dating: when.dating,
|
||||
ancient: Boolean(when.dating),
|
||||
cause: null,
|
||||
notes: impersonalText(value('itemDescription'), MAX_TEXT),
|
||||
cargo: null,
|
||||
protected: false,
|
||||
depth: null,
|
||||
depthQuality: null,
|
||||
positionAccuracy: null,
|
||||
positionNote: null,
|
||||
casualties: count(value('deaths')),
|
||||
survivors: count(value('survivors')),
|
||||
country: null,
|
||||
originator: null,
|
||||
url:
|
||||
// English Wikipedia, else the Wikidata item, which links the
|
||||
// article in every language that has one.
|
||||
wikiUrl(value('enwiki')) || `https://www.wikidata.org/wiki/${qid}`,
|
||||
});
|
||||
}
|
||||
return foldSinkingEvents([...byItem.values()]);
|
||||
}
|
||||
|
||||
/** An event this far from a listed ship whose name it contains is that ship's sinking. */
|
||||
const SAME_SINKING_KM = 50;
|
||||
|
||||
/**
|
||||
* "Sinking of the RMS Titanic" near the RMS Titanic wreck is one marker: the
|
||||
* ship keeps its article and takes the event's date, deaths and survivors.
|
||||
*/
|
||||
function foldSinkingEvents(records) {
|
||||
// Wikidata sometimes has both the ship and its wreck as items at one spot
|
||||
// ("Titanic", "wreck of the RMS Titanic"): keep the ship, one marker.
|
||||
const isWreckItem = (record) => (/^wreck\b/i.test(record.name || '') ? 1 : 0);
|
||||
const ships = [];
|
||||
const candidates = records
|
||||
.filter((record) => !record.event)
|
||||
.sort((a, b) => isWreckItem(a) - isWreckItem(b));
|
||||
for (const record of candidates) {
|
||||
const key = nameKey(record.name);
|
||||
const twin =
|
||||
key &&
|
||||
ships.find(
|
||||
(ship) =>
|
||||
nameKey(ship.name) === key &&
|
||||
distanceKm(ship, record) <= SAME_WRECK_KM,
|
||||
);
|
||||
if (!twin) {
|
||||
ships.push(record);
|
||||
continue;
|
||||
}
|
||||
twin.vesselType ||= record.vesselType;
|
||||
if (!hasWhen(twin)) takeWhen(twin, record);
|
||||
twin.casualties ??= record.casualties;
|
||||
twin.survivors ??= record.survivors;
|
||||
}
|
||||
const out = [...ships];
|
||||
for (const event of records.filter((record) => record.event)) {
|
||||
const eventKey = ` ${nameKey(event.name)} `;
|
||||
const ship = ships.find((candidate) => {
|
||||
const key = nameKey(candidate.name);
|
||||
return (
|
||||
key.length >= 3 &&
|
||||
eventKey.includes(` ${key} `) &&
|
||||
distanceKm(candidate, event) <= SAME_SINKING_KM
|
||||
);
|
||||
});
|
||||
if (!ship) {
|
||||
out.push(event);
|
||||
continue;
|
||||
}
|
||||
if (!hasWhen(ship)) {
|
||||
takeWhen(ship, event);
|
||||
} else if (!ship.date && event.date && event.year === ship.year) {
|
||||
ship.date = event.date;
|
||||
}
|
||||
ship.casualties ??= event.casualties;
|
||||
ship.survivors ??= event.survivors;
|
||||
}
|
||||
for (const record of out) delete record.event;
|
||||
return out;
|
||||
}
|
||||
|
||||
function nameKey(name) {
|
||||
return String(name || '')
|
||||
.normalize('NFD')
|
||||
.replace(/[̀-ͯ]/g, '')
|
||||
.toLowerCase()
|
||||
.replace(/\([^)]*\)/g, ' ')
|
||||
.replace(/\b(wreck|sinking|loss|disaster|of)\b/g, ' ')
|
||||
.replace(
|
||||
/\b(hms|hmt|hmhs|hmas|sms|ss|ms|mv|rms|uss|hm|s\/s|m\/v|the)\b/g,
|
||||
' ',
|
||||
)
|
||||
.replace(/[^a-z0-9]+/g, ' ')
|
||||
.trim();
|
||||
}
|
||||
|
||||
function distanceKm(a, b) {
|
||||
const rad = Math.PI / 180;
|
||||
const dLat = (b.lat - a.lat) * rad;
|
||||
const dLon = (b.lon - a.lon) * rad;
|
||||
const h =
|
||||
Math.sin(dLat / 2) ** 2 +
|
||||
Math.cos(a.lat * rad) * Math.cos(b.lat * rad) * Math.sin(dLon / 2) ** 2;
|
||||
return 12742 * Math.asin(Math.min(1, Math.sqrt(h)));
|
||||
}
|
||||
|
||||
/**
|
||||
* One list from both sources. A wreck in both (same name, a few km apart)
|
||||
* keeps the Wikidata record, which links an article, and takes EMODnet's
|
||||
* survey facts (depth, sinking text, year) that Wikidata lacks.
|
||||
*/
|
||||
export function mergeShipwreckRecords(emodnet = [], wikidata = []) {
|
||||
const byName = new Map();
|
||||
for (const record of wikidata) {
|
||||
const key = nameKey(record.name);
|
||||
if (!key) continue;
|
||||
if (!byName.has(key)) byName.set(key, []);
|
||||
byName.get(key).push(record);
|
||||
}
|
||||
const kept = [];
|
||||
for (const record of emodnet) {
|
||||
const twin = (byName.get(nameKey(record.name)) || []).find(
|
||||
(candidate) => distanceKm(candidate, record) <= SAME_WRECK_KM,
|
||||
);
|
||||
if (!twin) {
|
||||
kept.push(record);
|
||||
continue;
|
||||
}
|
||||
if (!hasWhen(twin)) takeWhen(twin, record);
|
||||
twin.vesselType ||= record.vesselType;
|
||||
twin.cause ||= record.cause;
|
||||
twin.depth ??= record.depth;
|
||||
twin.depthQuality ||= record.depthQuality;
|
||||
twin.positionAccuracy ??= record.positionAccuracy;
|
||||
twin.country ||= record.country;
|
||||
twin.protected ||= record.protected;
|
||||
twin.alsoIn = 'emodnet';
|
||||
}
|
||||
return [...wikidata, ...kept];
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the proxy's snapshot in the browser.
|
||||
* @returns {object[]|null} Records, or null when the payload is malformed.
|
||||
*/
|
||||
export function normalizeShipwreckSnapshot(payload) {
|
||||
if (!Array.isArray(payload?.records)) return null;
|
||||
const rows = [];
|
||||
const ids = new Set();
|
||||
for (const record of payload.records) {
|
||||
if (
|
||||
!record ||
|
||||
typeof record.id !== 'string' ||
|
||||
ids.has(record.id) ||
|
||||
!SHIPWRECK_SOURCES.includes(record.source) ||
|
||||
!validPoint(record.lat, record.lon)
|
||||
)
|
||||
continue;
|
||||
ids.add(record.id);
|
||||
rows.push({
|
||||
...record,
|
||||
year: Number.isInteger(record.year) ? record.year : null,
|
||||
url: httpUrl(record.url),
|
||||
});
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
mergeShipwreckRecords,
|
||||
normalizeEmodnetFeatures,
|
||||
normalizeShipwreckSnapshot,
|
||||
normalizeWikidataResults,
|
||||
parseYear,
|
||||
WIKIDATA_QUERY,
|
||||
} from './records.js';
|
||||
|
||||
function feature(id, properties, coordinates = [-4.35, 54.13]) {
|
||||
return {
|
||||
type: 'Feature',
|
||||
id,
|
||||
geometry: { type: 'Point', coordinates },
|
||||
properties,
|
||||
};
|
||||
}
|
||||
|
||||
test('EMODnet wrecks keep ship facts and drop text that names people', () => {
|
||||
const [wreck, roman] = normalizeEmodnetFeatures({
|
||||
features: [
|
||||
feature('w.1', {
|
||||
name: 'MAINA-NUI',
|
||||
sink_yr: '1987',
|
||||
sink_context: 'Sank on 07/02/1987',
|
||||
obj_type: 'Pusher or tug',
|
||||
least_depth: 12.5,
|
||||
depth_prec: 'Least depth known',
|
||||
loc_prec: 50,
|
||||
country: 'France',
|
||||
source_inf: 'SHOM',
|
||||
statutory: 'n/a',
|
||||
website1: 'n/a',
|
||||
}),
|
||||
feature('w.2', {
|
||||
name: 'Lerici',
|
||||
sink_yr: '',
|
||||
dating: 'C1st-2nd AD',
|
||||
period: 'Roman Imperial',
|
||||
artefacts: 'Marble, Columns',
|
||||
obj_type: 'n/a',
|
||||
ship_char: 'Owned by J. Smith, master was A. Jones',
|
||||
sink_context: 'Wrecked here, reported by Mr Smith',
|
||||
}),
|
||||
feature('w.3', { name: 'Copied', source_inf: 'www.wrecksite.eu' }),
|
||||
feature('w.4', { name: 'Null island' }, [0, 0]),
|
||||
],
|
||||
});
|
||||
const ids = normalizeEmodnetFeatures({
|
||||
features: [
|
||||
feature('w.3', { name: 'Copied', source_inf: 'www.wrecksite.eu' }),
|
||||
feature('w.5', {
|
||||
source_inf: `${'SHOM; '.repeat(20)}wrecksite.eu`,
|
||||
}),
|
||||
feature('w.6', { website1: 'https://www.wrecksite.eu/wreck.aspx?1' }),
|
||||
feature('w.7', { website1: 'wrecksite.eu/wreck/1' }),
|
||||
feature('w.8', { name: 'Kept', source_inf: 'SHOM' }),
|
||||
],
|
||||
}).map((record) => record.id);
|
||||
assert.deepEqual(ids, ['emodnet:w.8'], 'wrecksite.eu rows are all skipped');
|
||||
assert.equal(wreck.id, 'emodnet:w.1');
|
||||
assert.equal(wreck.year, 1987);
|
||||
assert.equal(wreck.vesselType, 'Pusher or tug');
|
||||
assert.equal(wreck.cause, 'Sank on 07/02/1987');
|
||||
assert.equal(wreck.depth, 12.5);
|
||||
assert.equal(wreck.positionAccuracy, 50);
|
||||
assert.equal(wreck.url, null);
|
||||
assert.equal(roman.year, null);
|
||||
assert.equal(roman.ancient, true);
|
||||
assert.equal(roman.dating, 'C1st-2nd AD');
|
||||
assert.equal(roman.notes, 'Roman Imperial (C1st-2nd AD)');
|
||||
assert.equal(roman.cargo, 'Marble, Columns');
|
||||
assert.equal(roman.vesselType, null, 'a history naming people is no type');
|
||||
assert.equal(roman.cause, null, 'text naming a person is dropped');
|
||||
});
|
||||
|
||||
test('Wikidata rows fold into one record per item', () => {
|
||||
const item = 'http://www.wikidata.org/entity/Q1471525';
|
||||
const records = normalizeWikidataResults({
|
||||
results: {
|
||||
bindings: [
|
||||
{
|
||||
item: { value: item },
|
||||
itemLabel: { value: 'HMS Havant' },
|
||||
itemDescription: { value: '1939 G and H-class destroyer' },
|
||||
coord: { value: 'Point(2.26 51.13)' },
|
||||
sunk: { value: '1940-06-01T00:00:00Z' },
|
||||
sunkPrecision: { value: '11' },
|
||||
enwiki: { value: 'https://en.wikipedia.org/wiki/HMS_Havant_(H32)' },
|
||||
},
|
||||
{
|
||||
item: { value: item },
|
||||
typeLabel: { value: 'destroyer' },
|
||||
deaths: { value: '8' },
|
||||
coord: { value: 'Point(2.26 51.13)' },
|
||||
},
|
||||
{
|
||||
item: { value: 'http://www.wikidata.org/entity/Q9' },
|
||||
itemLabel: { value: 'Q9' },
|
||||
coord: { value: 'Point(10 10)' },
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
assert.equal(records.length, 2);
|
||||
const [havant, unnamed] = records;
|
||||
assert.equal(havant.date, '1940-06-01');
|
||||
assert.equal(havant.year, 1940);
|
||||
assert.equal(havant.vesselType, 'destroyer');
|
||||
assert.equal(havant.casualties, 8);
|
||||
assert.equal(havant.url, 'https://en.wikipedia.org/wiki/HMS_Havant_(H32)');
|
||||
assert.equal(unnamed.name, null);
|
||||
assert.equal(unnamed.url, 'https://www.wikidata.org/wiki/Q9');
|
||||
});
|
||||
|
||||
test('a wreck in both sources keeps Wikidata and takes EMODnet survey facts', () => {
|
||||
const wikidata = [
|
||||
{
|
||||
id: 'wikidata:Q1',
|
||||
source: 'wikidata',
|
||||
name: 'HMS Havant',
|
||||
lat: 51.13,
|
||||
lon: 2.26,
|
||||
year: null,
|
||||
depth: null,
|
||||
},
|
||||
];
|
||||
const emodnet = [
|
||||
{
|
||||
id: 'emodnet:a',
|
||||
source: 'emodnet',
|
||||
name: 'Havant (HMS)',
|
||||
lat: 51.131,
|
||||
lon: 2.262,
|
||||
year: 1940,
|
||||
depth: 14.7,
|
||||
},
|
||||
{
|
||||
id: 'emodnet:b',
|
||||
source: 'emodnet',
|
||||
name: 'HMS Havant',
|
||||
lat: 45,
|
||||
lon: -10,
|
||||
year: 1950,
|
||||
},
|
||||
];
|
||||
const merged = mergeShipwreckRecords(emodnet, wikidata);
|
||||
assert.deepEqual(
|
||||
merged.map((record) => record.id),
|
||||
['wikidata:Q1', 'emodnet:b'],
|
||||
);
|
||||
assert.equal(merged[0].year, 1940);
|
||||
assert.equal(merged[0].depth, 14.7);
|
||||
assert.equal(merged[0].alsoIn, 'emodnet');
|
||||
});
|
||||
|
||||
test('years and snapshots are validated', () => {
|
||||
assert.equal(parseYear('1917-1918'), 1917);
|
||||
assert.equal(parseYear('c. 1588'), 1588);
|
||||
assert.equal(parseYear(''), null);
|
||||
assert.equal(parseYear('3000'), null);
|
||||
assert.equal(normalizeShipwreckSnapshot({}), null);
|
||||
const rows = normalizeShipwreckSnapshot({
|
||||
records: [
|
||||
{ id: 'a', source: 'emodnet', lat: 1, lon: 2, url: 'javascript:x' },
|
||||
{ id: 'a', source: 'emodnet', lat: 1, lon: 2 },
|
||||
{ id: 'b', source: 'other', lat: 1, lon: 2 },
|
||||
{ id: 'c', source: 'wikidata', lat: 91, lon: 2 },
|
||||
],
|
||||
});
|
||||
assert.equal(rows.length, 1);
|
||||
assert.equal(rows[0].url, null);
|
||||
});
|
||||
|
||||
test('a sinking event folds into its ship; month-precise dates keep the year only', () => {
|
||||
const entity = (q) => ({ value: `http://www.wikidata.org/entity/${q}` });
|
||||
const records = normalizeWikidataResults({
|
||||
results: {
|
||||
bindings: [
|
||||
{
|
||||
item: entity('Q25173'),
|
||||
itemLabel: { value: 'Titanic' },
|
||||
coord: { value: 'Point(-49.9469 41.7325)' },
|
||||
},
|
||||
{
|
||||
item: entity('Q3018259'),
|
||||
itemLabel: { value: 'wreck of the RMS Titanic' },
|
||||
coord: { value: 'Point(-49.9469 41.7325)' },
|
||||
},
|
||||
{
|
||||
item: entity('Q2577588'),
|
||||
itemLabel: { value: 'sinking of the RMS Titanic' },
|
||||
coord: { value: 'Point(-49.9458 41.7319)' },
|
||||
event: { value: 'event' },
|
||||
sunk: { value: '1912-04-01T00:00:00Z' },
|
||||
sunkPrecision: { value: '10' },
|
||||
deaths: { value: '1501' },
|
||||
survivors: { value: '712' },
|
||||
},
|
||||
{
|
||||
item: entity('Q1245004'),
|
||||
itemLabel: { value: 'Costa Concordia disaster' },
|
||||
coord: { value: 'Point(10.92 42.37)' },
|
||||
event: { value: 'event' },
|
||||
sunk: { value: '2012-01-13T00:00:00Z' },
|
||||
sunkPrecision: { value: '11' },
|
||||
deaths: { value: '32' },
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
assert.deepEqual(
|
||||
records.map((record) => record.id),
|
||||
['wikidata:Q25173', 'wikidata:Q1245004'],
|
||||
);
|
||||
const [titanic, concordia] = records;
|
||||
assert.equal(titanic.date, null);
|
||||
assert.equal(titanic.year, 1912);
|
||||
assert.equal(titanic.casualties, 1501);
|
||||
assert.equal(titanic.survivors, 712);
|
||||
assert.equal(concordia.name, 'Costa Concordia disaster');
|
||||
assert.equal(concordia.date, '2012-01-13');
|
||||
assert.equal('event' in concordia, false);
|
||||
});
|
||||
|
||||
test('a date before AD 100 is kept as ancient text, never read as an AD year', () => {
|
||||
const entity = (q) => ({ value: `http://www.wikidata.org/entity/${q}` });
|
||||
const [bc, earlyAd, roman] = normalizeWikidataResults({
|
||||
results: {
|
||||
bindings: [
|
||||
{
|
||||
item: entity('Q1'),
|
||||
itemLabel: { value: 'Antikythera wreck' },
|
||||
coord: { value: 'Point(23.3 35.9)' },
|
||||
sunk: { value: '-0299-01-01T00:00:00Z' },
|
||||
sunkPrecision: { value: '11' },
|
||||
},
|
||||
{
|
||||
item: entity('Q2'),
|
||||
itemLabel: { value: 'Early wreck' },
|
||||
coord: { value: 'Point(12 40)' },
|
||||
sunk: { value: '0050-01-01T00:00:00Z' },
|
||||
sunkPrecision: { value: '9' },
|
||||
},
|
||||
{
|
||||
item: entity('Q3'),
|
||||
itemLabel: { value: 'Roman wreck' },
|
||||
coord: { value: 'Point(13 41)' },
|
||||
sunk: { value: '0300-01-01T00:00:00Z' },
|
||||
sunkPrecision: { value: '9' },
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
assert.equal(bc.year, null, '300 BC is not the year 300');
|
||||
assert.equal(bc.date, null, 'no day for a BC date');
|
||||
assert.equal(bc.dating, '300 BC');
|
||||
assert.equal(bc.ancient, true);
|
||||
assert.equal(earlyAd.year, null);
|
||||
assert.equal(earlyAd.dating, 'AD 50');
|
||||
assert.equal(earlyAd.ancient, true);
|
||||
assert.equal(roman.year, 300);
|
||||
assert.equal(roman.dating, null);
|
||||
});
|
||||
|
||||
test('an end-of-service date keeps its precision: a year-only one is no day', () => {
|
||||
const entity = (q) => ({ value: `http://www.wikidata.org/entity/${q}` });
|
||||
const [yearOnly, dayPrecise, unknown] = normalizeWikidataResults({
|
||||
results: {
|
||||
bindings: [
|
||||
{
|
||||
item: entity('Q11'),
|
||||
itemLabel: { value: 'Year only' },
|
||||
coord: { value: 'Point(1 50)' },
|
||||
end: { value: '1917-01-01T00:00:00Z' },
|
||||
endPrecision: { value: '9' },
|
||||
},
|
||||
{
|
||||
item: entity('Q12'),
|
||||
itemLabel: { value: 'Day precise' },
|
||||
coord: { value: 'Point(2 50)' },
|
||||
end: { value: '1917-03-04T00:00:00Z' },
|
||||
endPrecision: { value: '11' },
|
||||
},
|
||||
{
|
||||
item: entity('Q13'),
|
||||
itemLabel: { value: 'No precision' },
|
||||
coord: { value: 'Point(3 50)' },
|
||||
end: { value: '1917-01-01T00:00:00Z' },
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
assert.equal(yearOnly.date, null, 'not shown as 1 Jan 1917');
|
||||
assert.equal(yearOnly.year, 1917);
|
||||
assert.equal(dayPrecise.date, '1917-03-04');
|
||||
assert.equal(unknown.date, null, 'an unknown precision is a year only');
|
||||
assert.equal(unknown.year, 1917);
|
||||
});
|
||||
|
||||
test('the query reads the end of service with its precision', () => {
|
||||
assert.match(
|
||||
WIKIDATA_QUERY,
|
||||
/psv:P576 \[ wikibase:timeValue \?end ; wikibase:timePrecision \?endPrecision \]/,
|
||||
);
|
||||
assert.doesNotMatch(WIKIDATA_QUERY, /wdt:P576/);
|
||||
});
|
||||
|
||||
test('labels and links do not default to one other language', () => {
|
||||
assert.doesNotMatch(WIKIDATA_QUERY, /ptwiki|pt\.wikipedia/);
|
||||
assert.match(WIKIDATA_QUERY, /wikibase:language "en,mul,/);
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import { readResponseJsonCapped } from '../../sources/httpBody.js';
|
||||
import { normalizeShipwreckSnapshot } from './records.js';
|
||||
|
||||
const age = (value) => (Number.isFinite(value) && value >= 0 ? value : null);
|
||||
|
||||
/** Same-origin source for the proxy's EMODnet + Wikidata shipwreck snapshot. */
|
||||
export function createShipwrecksSource({
|
||||
fetchImpl = (...args) => globalThis.fetch(...args),
|
||||
} = {}) {
|
||||
return {
|
||||
async getSnapshot({ signal } = {}) {
|
||||
signal?.throwIfAborted();
|
||||
const response = await fetchImpl('/api/shipwrecks', { signal });
|
||||
if (!response.ok)
|
||||
throw new Error(`Shipwrecks unavailable (HTTP ${response.status})`);
|
||||
const payload = await readResponseJsonCapped(
|
||||
response,
|
||||
16 * 1024 * 1024,
|
||||
signal,
|
||||
);
|
||||
signal?.throwIfAborted();
|
||||
const records = normalizeShipwreckSnapshot(payload);
|
||||
if (!records) throw new Error('Malformed shipwrecks response');
|
||||
return {
|
||||
records,
|
||||
fetchedAt: Number.isFinite(payload.fetchedAt)
|
||||
? payload.fetchedAt
|
||||
: null,
|
||||
stale: payload.stale === true,
|
||||
// Changes whenever either source's data does; null from an older proxy.
|
||||
version: typeof payload.version === 'string' ? payload.version : null,
|
||||
// Each source's age on the proxy's clock (null when unknown).
|
||||
ages: {
|
||||
emodnet: age(payload.ages?.emodnet),
|
||||
wikidata: age(payload.ages?.wikidata),
|
||||
},
|
||||
maxAgeMs: age(payload.maxAgeMs),
|
||||
sources: {
|
||||
emodnet: payload.sources?.emodnet !== false,
|
||||
wikidata: payload.sources?.wikidata !== false,
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createShipwrecksSource } from './source.js';
|
||||
|
||||
const respond = (payload) =>
|
||||
createShipwrecksSource({ fetchImpl: async () => Response.json(payload) });
|
||||
|
||||
test('the snapshot keeps valid source ages and drops malformed ones', async () => {
|
||||
const record = { id: 'a', source: 'emodnet', lat: 50, lon: -1 };
|
||||
const good = await respond({
|
||||
records: [record],
|
||||
version: 'v',
|
||||
ages: { emodnet: 0, wikidata: 3600 },
|
||||
maxAgeMs: 604800000,
|
||||
}).getSnapshot();
|
||||
assert.deepEqual(good.ages, { emodnet: 0, wikidata: 3600 });
|
||||
assert.equal(good.maxAgeMs, 604800000);
|
||||
assert.equal(good.version, 'v');
|
||||
const bad = await respond({
|
||||
records: [record],
|
||||
ages: { emodnet: -5, wikidata: 'x' },
|
||||
maxAgeMs: Number.NaN,
|
||||
}).getSnapshot();
|
||||
assert.deepEqual(bad.ages, { emodnet: null, wikidata: null });
|
||||
assert.equal(bad.maxAgeMs, null);
|
||||
assert.equal(bad.version, null);
|
||||
});
|
||||
Vendored
+3
@@ -301,6 +301,9 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
position: pos,
|
||||
id: `VEH-${String(layerState._dots[i].id).padStart(4, '0')}`,
|
||||
type: 'VEH',
|
||||
// The dots are depth-tested, so the overlay hides a contact's
|
||||
// bracket and callout wherever the scene hides its dot.
|
||||
depthTested: true,
|
||||
};
|
||||
// Live mode: the detection bracket carries the congestion signal —
|
||||
// its canvas sits ABOVE the post-FX chain, so tier colors survive
|
||||
|
||||
@@ -67,6 +67,13 @@ export function createRendering({
|
||||
* cannot drape draws them over the surface instead (the draw port's
|
||||
* `overlay`).
|
||||
*
|
||||
* One build runs at a time. A city loads in progressive paints, each asking
|
||||
* for a rebuild, and every build drapes up to the cap of polylines
|
||||
* asynchronously. A rebuild asked for while lines are building only replaces
|
||||
* the one waiting, which retireHeatLines starts when the build finishes, so
|
||||
* the scene never holds more than the lines drawn and the lines building.
|
||||
* Turning the lines off is never deferred.
|
||||
*
|
||||
* @param {Array} roads - Road objects visible in the current render.
|
||||
*/
|
||||
|
||||
|
||||
@@ -596,11 +596,16 @@ export function createRendering({ state, services, parts }) {
|
||||
const displayPx = basePx * presetSpriteScale(style, selected);
|
||||
const frame = haloFrame(halo, displayPx);
|
||||
const px = displayPx * frame.ratio;
|
||||
// A glyph with a front only when there is a course to point it along:
|
||||
// without one the billboard sits at rotation 0 and a nose would say north.
|
||||
const heading = Number.isFinite(entry.courseDeg);
|
||||
entry.iconHeading = heading;
|
||||
marker.image = transitIcon(
|
||||
entry.mode,
|
||||
selected ? SELECTED_ICON_PX : undefined,
|
||||
{
|
||||
style,
|
||||
heading,
|
||||
},
|
||||
);
|
||||
marker.width = px;
|
||||
@@ -616,6 +621,12 @@ export function createRendering({ state, services, parts }) {
|
||||
dirty.add(entry);
|
||||
}
|
||||
|
||||
/** Swap between the pointed and the neutral glyph when a course appears or is lost. */
|
||||
function syncHeadingIcon(entry) {
|
||||
if (entry.marker && entry.iconHeading !== Number.isFinite(entry.courseDeg))
|
||||
applySpriteStyle(entry);
|
||||
}
|
||||
|
||||
function addMarker(key, entry) {
|
||||
const at = entry.toCart;
|
||||
const marker = {
|
||||
@@ -703,6 +714,7 @@ export function createRendering({ state, services, parts }) {
|
||||
for (const entry of state._visible) {
|
||||
// Idle contacts still need a course when their first usable bearing arrives.
|
||||
if (!state._moving.has(entry)) applyDisplayCourse(entry, monoNow);
|
||||
syncHeadingIcon(entry);
|
||||
if (entry.key === state._selectedKey) continue;
|
||||
const marker = entry.marker;
|
||||
const course = entry.courseDeg;
|
||||
@@ -814,6 +826,7 @@ export function createRendering({ state, services, parts }) {
|
||||
refreshRotations(Date.now());
|
||||
const selected = state._vehicles.get(state._selectedKey);
|
||||
if (selected && state._visible.has(selected)) {
|
||||
syncHeadingIcon(selected);
|
||||
const marker = selected.marker;
|
||||
const pose = Number.isFinite(selected.courseDeg) ? cameraPose() : null;
|
||||
const query = pose?.position ? findQuery(state._viewer) : null;
|
||||
|
||||
@@ -60,7 +60,7 @@ export function createCards({
|
||||
parts.push(`${roundHeadingDegrees(direction)}°`);
|
||||
return {
|
||||
id: vesselOverlayEntryId(record),
|
||||
actionable: Boolean(record?.mmsi),
|
||||
actionable: Boolean(record?.id),
|
||||
position: components.rendering.iconPosition(record),
|
||||
gapPx: 10,
|
||||
accent: accentForVesselType(record.type),
|
||||
@@ -99,7 +99,7 @@ export function createCards({
|
||||
);
|
||||
return {
|
||||
id: vesselOverlayEntryId(record),
|
||||
actionable: Boolean(record?.mmsi),
|
||||
actionable: Boolean(record?.id),
|
||||
position: components.rendering.iconPosition(record),
|
||||
gapPx: 12,
|
||||
accent: accentForVesselType(record.type),
|
||||
@@ -110,11 +110,11 @@ export function createCards({
|
||||
};
|
||||
}
|
||||
|
||||
/** Stable overlay identity for MMSI-keyed and source-retained unkeyed rows. */
|
||||
/** Stable overlay identity for keyed and source-retained unkeyed rows. */
|
||||
|
||||
function vesselOverlayEntryId(record) {
|
||||
const mmsi = String(record?.mmsi || '').trim();
|
||||
if (mmsi) return `vessel:${mmsi}`;
|
||||
const id = String(record?.id || '').trim();
|
||||
if (id) return `vessel:${id}`;
|
||||
const name = String(record?.name || 'VESSEL').trim() || 'VESSEL';
|
||||
const lat = Number.isFinite(record?.lat) ? record.lat.toFixed(5) : 'x';
|
||||
const lon = Number.isFinite(record?.lon) ? record.lon.toFixed(5) : 'x';
|
||||
@@ -157,7 +157,9 @@ export function createCards({
|
||||
|
||||
function displayVesselName(record) {
|
||||
const name = String(record.name || '').trim();
|
||||
if (name && name !== 'VESSEL' && name !== record.mmsi) return name;
|
||||
// A source may name a vessel by its id when it has no name.
|
||||
if (name && name !== 'VESSEL' && name !== record.mmsi && name !== record.id)
|
||||
return name;
|
||||
return record.mmsi ? `MMSI ${record.mmsi}` : t('VESSEL');
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { VesselRecords } from './records.js';
|
||||
import { createIngestion, createVesselFeed } from './ingestion.js';
|
||||
|
||||
// Vessels follow the world clock only while their source declares a
|
||||
// timeline (src/time/snapshotTimeline.js); these cover the layer's side.
|
||||
|
||||
const row = (mmsi, fields = {}) => ({
|
||||
mmsi,
|
||||
lat: 51.93,
|
||||
lon: 4.05,
|
||||
name: mmsi,
|
||||
last_position_epoch: 1_000,
|
||||
...fields,
|
||||
});
|
||||
|
||||
function store() {
|
||||
const records = new VesselRecords({ now: () => 5_000_000 });
|
||||
const events = [];
|
||||
const effects = {
|
||||
add: (record) => events.push(['add', record.mmsi]),
|
||||
beforeUpdate: () => null,
|
||||
updated: (record) => events.push(['update', record.mmsi]),
|
||||
remove: (record, evicted) => events.push(['remove', record.mmsi, evicted]),
|
||||
removed: (mmsi) => events.push(['removed', mmsi]),
|
||||
staleSelected: (record) => events.push(['stale', record.mmsi]),
|
||||
};
|
||||
return {
|
||||
records,
|
||||
events,
|
||||
reconcile: (rows, options = {}) =>
|
||||
records.reconcile(rows, options, effects),
|
||||
};
|
||||
}
|
||||
|
||||
test('rows at another time stand in for every vessel, selected or not', () => {
|
||||
const probe = store();
|
||||
probe.reconcile([row('111'), row('222')]);
|
||||
const selectedRecord = probe.records.byId.get('222');
|
||||
probe.reconcile([row('111', { last_position_epoch: 900 })], {
|
||||
complete: false,
|
||||
selectedRecord,
|
||||
replace: true,
|
||||
});
|
||||
assert.deepEqual([...probe.records.byId.keys()], ['111']);
|
||||
assert.deepEqual(probe.events.slice(-3), [
|
||||
['update', '111'],
|
||||
['remove', '222', true],
|
||||
['removed', '222'],
|
||||
]);
|
||||
assert.equal(probe.records.byId.get('111').motion, null);
|
||||
});
|
||||
|
||||
test('following the clock, a vessel keeps where its fix moved from', () => {
|
||||
const probe = store();
|
||||
probe.reconcile([row('111')]);
|
||||
probe.reconcile([row('111', { lat: 52, last_position_epoch: 1_010 })], {
|
||||
follow: true,
|
||||
});
|
||||
const record = probe.records.byId.get('111');
|
||||
assert.deepEqual(record.motion, {
|
||||
fromLat: 51.93,
|
||||
fromLon: 4.05,
|
||||
fromMs: 1_000_000,
|
||||
toLat: 52,
|
||||
toLon: 4.05,
|
||||
toMs: 1_010_000,
|
||||
});
|
||||
probe.reconcile([row('111', { lat: 52, last_position_epoch: 1_010 })], {
|
||||
follow: true,
|
||||
});
|
||||
assert.equal(record.motion.toMs, 1_010_000, 'a repeated fix keeps its move');
|
||||
const live = store();
|
||||
live.reconcile([row('111')]);
|
||||
live.reconcile([row('111', { lat: 52, last_position_epoch: 1_010 })]);
|
||||
assert.equal(
|
||||
Object.hasOwn(live.records.byId.get('111'), 'motion'),
|
||||
false,
|
||||
'live records are as before',
|
||||
);
|
||||
});
|
||||
|
||||
function ingestion(source) {
|
||||
const feed = createVesselFeed();
|
||||
feed.enabled = true;
|
||||
feed.sessionId = 1;
|
||||
const applied = [];
|
||||
const state = { follows: false, reloads: 0, radiusKm: 50 };
|
||||
const methods = createIngestion({
|
||||
feed,
|
||||
readSource: () => source,
|
||||
readViewer: () => ({}),
|
||||
readArea: () => ({ lat: 1, lon: 2, radiusKm: state.radiusKm }),
|
||||
getRowLimit: () => 500,
|
||||
readCount: () => applied.at(-1)?.rows.length ?? 0,
|
||||
now: () => 9999,
|
||||
setSourceLabel: () => {},
|
||||
applyRows: (_viewer, rows, options) => applied.push({ rows, options }),
|
||||
classifySnapshot: (payload) => ({
|
||||
acceptedRows: payload.rows,
|
||||
acceptedRowCount: payload.rows.length,
|
||||
rawRowCount: payload.rows.length,
|
||||
transportStatus: payload.status,
|
||||
lastMessageAt: payload.lastMessageAt,
|
||||
error: null,
|
||||
}),
|
||||
isDefinitiveTransportFailure: () => false,
|
||||
isGraceEligibleTransport: () => false,
|
||||
markUnavailable: () => {},
|
||||
settleFirstConnect: () => {},
|
||||
followsClock: () => state.follows,
|
||||
reloadAtClock: () => {
|
||||
state.reloads += 1;
|
||||
},
|
||||
});
|
||||
return { feed, applied, state, ...methods };
|
||||
}
|
||||
|
||||
test('vessel polls carry no time; a snapshot at a time carries it and replaces', async () => {
|
||||
const queries = [];
|
||||
const probe = ingestion({
|
||||
async getSnapshot(query) {
|
||||
queries.push(query);
|
||||
return {
|
||||
records: [{ id: '111', latitude: 1, longitude: 2, observedAtMs: 5 }],
|
||||
observedAtMs: 5,
|
||||
freshness: 'current',
|
||||
complete: true,
|
||||
transportStatus: 'live',
|
||||
};
|
||||
},
|
||||
});
|
||||
await probe.methods.update();
|
||||
assert.equal(Object.hasOwn(queries[0], 'atMs'), false);
|
||||
assert.deepEqual(probe.applied[0].options, { complete: true });
|
||||
probe.state.follows = true;
|
||||
await probe.methods.update();
|
||||
assert.equal(queries.length, 1, 'no poll while following');
|
||||
assert.equal(await probe.loadAt(5_000, { replace: true }), true);
|
||||
assert.equal(queries[1].atMs, 5_000);
|
||||
assert.deepEqual(probe.applied[1].options, { complete: true, replace: true });
|
||||
assert.equal(probe.feed.lastUpdate, 5);
|
||||
// Following the clock, a moved view reloads the time shown.
|
||||
probe.state.radiusKm = 2_000;
|
||||
await probe.refreshIfMoved({});
|
||||
assert.equal(probe.state.reloads, 1);
|
||||
assert.equal(queries.length, 2);
|
||||
});
|
||||
|
||||
test('an empty vessel snapshot at another time shows no vessels', async () => {
|
||||
const probe = ingestion({
|
||||
async getSnapshot() {
|
||||
return { records: [], observedAtMs: 5, freshness: 'current' };
|
||||
},
|
||||
});
|
||||
probe.state.follows = true;
|
||||
await probe.loadAt(5_000, { replace: true });
|
||||
assert.deepEqual(probe.applied, [
|
||||
{ rows: [], options: { complete: true, replace: true } },
|
||||
]);
|
||||
});
|
||||
|
||||
test('a vessel snapshot at a time the source drops for a newer one is no failure', async () => {
|
||||
const probe = ingestion({
|
||||
async getSnapshot() {
|
||||
throw new DOMException('Superseded', 'AbortError');
|
||||
},
|
||||
});
|
||||
probe.state.follows = true;
|
||||
await assert.rejects(probe.loadAt(5_000, { replace: true }), {
|
||||
name: 'AbortError',
|
||||
});
|
||||
assert.equal(probe.feed.error, null);
|
||||
assert.equal(probe.feed.loading, false);
|
||||
assert.deepEqual(probe.applied, []);
|
||||
});
|
||||
@@ -99,7 +99,7 @@ function finiteOrNull(value) {
|
||||
* @returns {object|null} Subject info, or null without a usable fix.
|
||||
*/
|
||||
export function vesselCockpitInfo(record) {
|
||||
if (!record?.mmsi) return null;
|
||||
if (!record?.id) return null;
|
||||
const latitude = Number(record.lat);
|
||||
const longitude = Number(record.lon);
|
||||
if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return null;
|
||||
@@ -111,9 +111,9 @@ export function vesselCockpitInfo(record) {
|
||||
return {
|
||||
kind: 'vessel',
|
||||
layerId: VESSEL_COCKPIT_LAYER_ID,
|
||||
id: String(record.mmsi),
|
||||
mmsi: String(record.mmsi),
|
||||
name: String(record.name || record.mmsi),
|
||||
id: String(record.id),
|
||||
mmsi: String(record.mmsi || ''),
|
||||
name: String(record.name || record.mmsi || record.id),
|
||||
type: String(record.type || ''),
|
||||
typeLabel: displayVesselType(record.type),
|
||||
destination: String(record.destination || '').trim(),
|
||||
|
||||
@@ -43,6 +43,7 @@ test('an unknown or missing type has no eye height of its own', () => {
|
||||
|
||||
test('vessel info faces the true heading and moves along course over ground', () => {
|
||||
const info = vesselCockpitInfo({
|
||||
id: '211000000',
|
||||
mmsi: '211000000',
|
||||
name: 'NORDIC STAR',
|
||||
type: '70',
|
||||
@@ -58,6 +59,7 @@ test('vessel info faces the true heading and moves along course over ground', ()
|
||||
assert.equal(info.kind, 'vessel');
|
||||
assert.equal(info.layerId, VESSEL_COCKPIT_LAYER_ID);
|
||||
assert.equal(info.id, '211000000');
|
||||
assert.equal(info.mmsi, '211000000');
|
||||
assert.equal(info.typeLabel, 'CARGO');
|
||||
assert.equal(info.track, 90);
|
||||
assert.equal(info.motionCourse, 95);
|
||||
@@ -70,7 +72,7 @@ test('vessel info faces the true heading and moves along course over ground', ()
|
||||
});
|
||||
|
||||
test('a missing heading or course falls back to the other', () => {
|
||||
const base = { mmsi: '1', lat: 1, lon: 1, speed: 3 };
|
||||
const base = { id: '1', mmsi: '1', lat: 1, lon: 1, speed: 3 };
|
||||
assert.equal(vesselCockpitInfo({ ...base, course: 40 }).track, 40);
|
||||
assert.equal(vesselCockpitInfo({ ...base, heading: 50 }).motionCourse, 50);
|
||||
const neither = vesselCockpitInfo(base);
|
||||
@@ -79,7 +81,7 @@ test('a missing heading or course falls back to the other', () => {
|
||||
});
|
||||
|
||||
test('the subject says whether its track is the heading or the course', () => {
|
||||
const base = { mmsi: '1', lat: 1, lon: 1, speed: 3 };
|
||||
const base = { id: '1', mmsi: '1', lat: 1, lon: 1, speed: 3 };
|
||||
assert.equal(
|
||||
vesselCockpitInfo({ ...base, heading: 50, course: 40 }).trackSource,
|
||||
'heading',
|
||||
@@ -99,11 +101,12 @@ test('the subject says whether its track is the heading or the course', () => {
|
||||
test('a vessel without identity or position is not a subject', () => {
|
||||
assert.equal(vesselCockpitInfo(null), null);
|
||||
assert.equal(vesselCockpitInfo({ lat: 1, lon: 1 }), null);
|
||||
assert.equal(vesselCockpitInfo({ mmsi: '1', lat: 'x', lon: 1 }), null);
|
||||
assert.equal(vesselCockpitInfo({ id: '1', mmsi: '1', lat: 'x', lon: 1 }), null);
|
||||
});
|
||||
|
||||
test('a vessel missing from recent refreshes reads as stale', () => {
|
||||
const info = vesselCockpitInfo({
|
||||
id: '1',
|
||||
mmsi: '1',
|
||||
lat: 1,
|
||||
lon: 1,
|
||||
@@ -111,3 +114,20 @@ test('a vessel missing from recent refreshes reads as stale', () => {
|
||||
});
|
||||
assert.equal(info.stale, true);
|
||||
});
|
||||
|
||||
test('a vessel is the subject by its id; an MMSI is only shown when known', () => {
|
||||
const info = vesselCockpitInfo({
|
||||
id: 'b6a7c1e2-provider-id',
|
||||
mmsi: '',
|
||||
name: 'NORDIC STAR',
|
||||
lat: 54.5,
|
||||
lon: 10.2,
|
||||
});
|
||||
assert.equal(info.id, 'b6a7c1e2-provider-id');
|
||||
assert.equal(info.mmsi, '');
|
||||
assert.equal(
|
||||
vesselCockpitInfo({ mmsi: '211000000', lat: 54.5, lon: 10.2 }),
|
||||
null,
|
||||
'a record with no id is unkeyed and cannot be ridden',
|
||||
);
|
||||
});
|
||||
@@ -45,7 +45,7 @@ export function createEvidence({
|
||||
const position = drawn ? visual.position : null;
|
||||
const screen = position ? query?.project(position) : null;
|
||||
return {
|
||||
id: record.mmsi,
|
||||
id: record.id,
|
||||
show: drawn && visual.visible === true,
|
||||
alpha: drawn ? state.icons.focus(visual.iconId) : null,
|
||||
x: screen?.x ?? null,
|
||||
|
||||
@@ -10,6 +10,9 @@ import { createCards } from './cards.js';
|
||||
import { createTesting } from './testing.js';
|
||||
import { createEvidence } from './evidence.js';
|
||||
import { createQueries } from './queries.js';
|
||||
import { followsClock } from './policy.js';
|
||||
import { createSnapshotTimeline } from '../../time/snapshotTimeline.js';
|
||||
import { worldClock } from '../../time/worldClock.js';
|
||||
/** Compose one vessel layer with application-owned scene services. */
|
||||
export function createVesselLayer({ source, services, options = {} } = {}) {
|
||||
const vesselState = createVesselState({ source, services });
|
||||
@@ -31,6 +34,7 @@ export function createVesselLayer({ source, services, options = {} } = {}) {
|
||||
tracking: parts.tracking,
|
||||
selection: parts.selection,
|
||||
cards: parts.cards,
|
||||
followsClock: () => followsClock(vesselState),
|
||||
});
|
||||
|
||||
parts.ingestion = createIngestion({
|
||||
@@ -50,6 +54,29 @@ export function createVesselLayer({ source, services, options = {} } = {}) {
|
||||
setSourceLabel: (source) => {
|
||||
layer.source = source;
|
||||
},
|
||||
followsClock: () => followsClock(vesselState),
|
||||
reloadAtClock: () => vesselState.timeline.reload(),
|
||||
});
|
||||
// Vessels follow the world clock while the source declares a timeline.
|
||||
vesselState.timeline = createSnapshotTimeline({
|
||||
id: 'ais-live-vessels',
|
||||
clock: worldClock,
|
||||
source: () => vesselState._source,
|
||||
load: (atMs, { signal, replace }) =>
|
||||
parts.ingestion.loadAt(atMs, { signal, replace }),
|
||||
clear: () => {
|
||||
const { state } = vesselState;
|
||||
if (state.viewer)
|
||||
parts.snapshots.reconcileVessels(state.viewer, [], {
|
||||
complete: true,
|
||||
replace: true,
|
||||
});
|
||||
state.feed.count = state.records.all.length;
|
||||
state.feed.lastUpdate = null;
|
||||
},
|
||||
resumeLive: () => {
|
||||
void parts.ingestion.loadLivePositions(vesselState.state.viewer);
|
||||
},
|
||||
});
|
||||
Object.assign(
|
||||
layer,
|
||||
|
||||
@@ -21,9 +21,36 @@ export function createIngestion({
|
||||
settleFirstConnect,
|
||||
now,
|
||||
setSourceLabel,
|
||||
followsClock = () => false,
|
||||
reloadAtClock = () => {},
|
||||
}) {
|
||||
async function loadLivePositions(viewer) {
|
||||
if (!viewer || feed.loading) return;
|
||||
// Following the world clock, the layer shows the snapshots loadAt applies.
|
||||
if (followsClock()) return;
|
||||
await loadPositions(viewer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply the source's snapshot at world time `atMs` (its timeline says it
|
||||
* can answer one), in place of every vessel when `replace`. Resolves
|
||||
* whether it was applied.
|
||||
* @param {number} atMs
|
||||
* @param {{signal?: AbortSignal|null, replace?: boolean}} [options]
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
async function loadAt(atMs, { signal = null, replace = false } = {}) {
|
||||
// Whatever polls or loads for another time no longer applies.
|
||||
if (replace && feed.loading) {
|
||||
feed.abort?.abort();
|
||||
feed.loading = false;
|
||||
feed.abort = null;
|
||||
}
|
||||
return loadPositions(readViewer(), { atMs, replace, signal });
|
||||
}
|
||||
|
||||
async function loadPositions(viewer, { atMs, replace = false, signal } = {}) {
|
||||
const timed = atMs !== undefined;
|
||||
if (!viewer || feed.loading) return false;
|
||||
feed.loading = true;
|
||||
feed.loadingLabel = feed.loaded ? 'refreshing...' : 'loading...';
|
||||
const requestController = new AbortController();
|
||||
@@ -33,21 +60,29 @@ export function createIngestion({
|
||||
try {
|
||||
// Combine the layer's teardown-abort with a hard timeout so a hung upstream
|
||||
// can't wedge the poll indefinitely (parity with the track fetch + flights).
|
||||
const signal =
|
||||
const requestSignal =
|
||||
typeof AbortSignal.any === 'function'
|
||||
? AbortSignal.any([
|
||||
requestController.signal,
|
||||
AbortSignal.timeout(10000),
|
||||
...(signal ? [signal] : []),
|
||||
])
|
||||
: requestController.signal;
|
||||
// Ask for the vessels in view; a wide view asks for every vessel.
|
||||
const area = readArea(viewer);
|
||||
feed.lastArea = area;
|
||||
const snapshot = await readSource().getSnapshot(
|
||||
{ maxRows: getRowLimit(), ...(area ? { area } : {}) },
|
||||
{ signal },
|
||||
{
|
||||
maxRows: getRowLimit(),
|
||||
...(area ? { area } : {}),
|
||||
...(timed ? { atMs } : {}),
|
||||
},
|
||||
{ signal: requestSignal },
|
||||
);
|
||||
if (!ownsAisRequest(requestController, requestSessionId)) return;
|
||||
if (!ownsAisRequest(requestController, requestSessionId)) return false;
|
||||
if (signal?.aborted) return false;
|
||||
// The clock left the live edge while this poll was out.
|
||||
if (!timed && followsClock()) return false;
|
||||
setSourceLabel(snapshot.source);
|
||||
// Map observations into the existing display store; source fields stop here.
|
||||
applyAisFeedSnapshot(viewer, {
|
||||
@@ -67,8 +102,12 @@ export function createIngestion({
|
||||
: new Date(snapshot.observedAtMs).toISOString(),
|
||||
silentForMs: snapshot.silentForMs,
|
||||
reconnectAttempt: snapshot.reconnectAttempt,
|
||||
...(replace && { replace }),
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
// A snapshot at a time the source dropped for a newer one is no failure.
|
||||
if (timed && error?.name === 'AbortError') throw error;
|
||||
if (
|
||||
ownsAisRequest(requestController, requestSessionId) &&
|
||||
error?.name !== 'AbortError'
|
||||
@@ -76,6 +115,7 @@ export function createIngestion({
|
||||
markUnavailable(error?.message || msg('AIS live load failed'));
|
||||
console.warn('[Data:ais-live-vessels]', feed.error, error);
|
||||
}
|
||||
return false;
|
||||
} finally {
|
||||
if (
|
||||
feed.abort === requestController &&
|
||||
@@ -113,6 +153,9 @@ export function createIngestion({
|
||||
feed.acceptedRowCount = snapshot.acceptedRowCount;
|
||||
feed.partial = payload?.complete === false;
|
||||
|
||||
// At another time, a snapshot with no vessels shows none, not the last.
|
||||
if (payload?.replace && snapshot.acceptedRowCount === 0)
|
||||
applyRows(viewer, [], { complete: true, replace: true });
|
||||
if (snapshot.acceptedRowCount === 0 && !snapshot.emptyCoverage) {
|
||||
feed.count = readCount();
|
||||
feed.stale = feed.count > 0 || Boolean(payload?.refreshing);
|
||||
@@ -139,6 +182,7 @@ export function createIngestion({
|
||||
settleFirstConnect('ready');
|
||||
applyRows(viewer, snapshot.acceptedRows, {
|
||||
complete: payload?.complete !== false,
|
||||
...(payload?.replace && { replace: true }),
|
||||
});
|
||||
feed.count = readCount();
|
||||
feed.stale =
|
||||
@@ -157,9 +201,11 @@ export function createIngestion({
|
||||
return { reconciled: true, ...snapshot };
|
||||
}
|
||||
|
||||
/** The layer's row for a source record: keyed by its id, MMSI shown when known. */
|
||||
function vesselDisplayRow(record) {
|
||||
return {
|
||||
mmsi: record.id,
|
||||
id: record.id,
|
||||
mmsi: String(record.mmsi ?? '').trim(),
|
||||
reference: record.reference,
|
||||
lat: record.latitude,
|
||||
lon: record.longitude,
|
||||
@@ -180,10 +226,16 @@ export function createIngestion({
|
||||
}
|
||||
/** Ask again when the view moved away from the last area asked for. */
|
||||
function refreshIfMoved(viewer) {
|
||||
if (!feed.enabled || feed.loading) return Promise.resolve();
|
||||
const following = followsClock();
|
||||
if (!feed.enabled || (feed.loading && !following)) return Promise.resolve();
|
||||
const active = viewer || readViewer();
|
||||
if (!viewAreaMovedEnough(feed.lastArea ?? null, readArea(active)))
|
||||
return Promise.resolve();
|
||||
// Following the world clock, the new area is asked for at the same time.
|
||||
if (following) {
|
||||
reloadAtClock();
|
||||
return Promise.resolve();
|
||||
}
|
||||
return loadLivePositions(active);
|
||||
}
|
||||
|
||||
@@ -196,6 +248,7 @@ export function createIngestion({
|
||||
|
||||
return {
|
||||
loadLivePositions,
|
||||
loadAt,
|
||||
refreshIfMoved,
|
||||
ownsAisRequest,
|
||||
applyAisFeedSnapshot,
|
||||
|
||||
@@ -116,7 +116,7 @@ export function createLifecycle({
|
||||
state.feed.abort = null;
|
||||
state.icons = null;
|
||||
state.records.all = [];
|
||||
state.records.byMmsi = new Map();
|
||||
state.records.byId = new Map();
|
||||
state.records.unkeyed = [];
|
||||
state.clickSubscription = null;
|
||||
state.keyTarget = null;
|
||||
@@ -132,7 +132,7 @@ export function createLifecycle({
|
||||
state.selectedRecord = null;
|
||||
state.trail = null;
|
||||
state.trailPositions = [];
|
||||
state.trailMmsi = null;
|
||||
state.trailId = null;
|
||||
state.trailBackfillToken = 0;
|
||||
}
|
||||
const methods = {
|
||||
@@ -185,9 +185,9 @@ export function createLifecycle({
|
||||
/* grid failed to load — anchors stay at ellipsoid 0 */
|
||||
});
|
||||
}
|
||||
// Pick-ownership (H2): a vessel icon's pick id is its row id, the MMSI.
|
||||
// Pick-ownership (H2): a vessel icon's pick id is its row id, the record's id.
|
||||
registerPickOwner('ais-live-vessels', (pickedId) =>
|
||||
state.records.byMmsi.has(pickedId),
|
||||
state.records.byId.has(pickedId),
|
||||
);
|
||||
// Vessels are asked for by view, so ask again when the view moves away.
|
||||
removeViewListener();
|
||||
@@ -196,10 +196,12 @@ export function createLifecycle({
|
||||
state.feed.removeViewListener = camera.on('moveEnd', () => {
|
||||
components.ingestion.refreshIfMoved(activeViewer);
|
||||
});
|
||||
vesselState.timeline?.start();
|
||||
return components.ingestion.loadLivePositions(activeViewer);
|
||||
},
|
||||
|
||||
disable() {
|
||||
vesselState.timeline?.stop();
|
||||
removeViewListener();
|
||||
state.feed.enabled = false;
|
||||
invalidateAisSession();
|
||||
@@ -220,6 +222,7 @@ export function createLifecycle({
|
||||
},
|
||||
|
||||
destroy(viewer) {
|
||||
vesselState.timeline?.stop();
|
||||
removeViewListener();
|
||||
const activeViewer = viewer || state.viewer;
|
||||
invalidateAisSession();
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* Where a vessel is at world time `tMs` while the layer follows the world
|
||||
* clock: between the fix it moved from and the fix it moved to, along the
|
||||
* great circle; at the earlier fix before it, at the newer fix after it. A
|
||||
* vessel is never projected past its newest fix.
|
||||
* @param {{lat: number, lon: number, motion?: {fromLat: number, fromLon: number,
|
||||
* fromMs: number, toLat: number, toLon: number, toMs: number}|null}} record
|
||||
* @param {number} tMs
|
||||
* @returns {{lat: number, lon: number}}
|
||||
*/
|
||||
export function vesselPositionAt(record, tMs) {
|
||||
const motion = record?.motion;
|
||||
if (
|
||||
!motion ||
|
||||
!Number.isFinite(tMs) ||
|
||||
!(motion.toMs > motion.fromMs) ||
|
||||
tMs >= motion.toMs
|
||||
)
|
||||
return record;
|
||||
if (tMs <= motion.fromMs) return { lat: motion.fromLat, lon: motion.fromLon };
|
||||
const fraction = (tMs - motion.fromMs) / (motion.toMs - motion.fromMs);
|
||||
return greatCircleAt(
|
||||
motion.fromLat,
|
||||
motion.fromLon,
|
||||
motion.toLat,
|
||||
motion.toLon,
|
||||
fraction,
|
||||
);
|
||||
}
|
||||
|
||||
const RAD = Math.PI / 180;
|
||||
|
||||
/** The point `fraction` of the way from one position to another. */
|
||||
function greatCircleAt(lat1, lon1, lat2, lon2, fraction) {
|
||||
const p1 = unit(lat1, lon1);
|
||||
const p2 = unit(lat2, lon2);
|
||||
const dot = Math.min(
|
||||
1,
|
||||
Math.max(-1, p1[0] * p2[0] + p1[1] * p2[1] + p1[2] * p2[2]),
|
||||
);
|
||||
const angle = Math.acos(dot);
|
||||
if (angle < 1e-12) return { lat: lat2, lon: lon2 };
|
||||
const a = Math.sin((1 - fraction) * angle) / Math.sin(angle);
|
||||
const b = Math.sin(fraction * angle) / Math.sin(angle);
|
||||
const x = a * p1[0] + b * p2[0];
|
||||
const y = a * p1[1] + b * p2[1];
|
||||
const z = a * p1[2] + b * p2[2];
|
||||
return {
|
||||
lat: Math.atan2(z, Math.hypot(x, y)) / RAD,
|
||||
lon: Math.atan2(y, x) / RAD,
|
||||
};
|
||||
}
|
||||
|
||||
function unit(lat, lon) {
|
||||
const phi = lat * RAD;
|
||||
const lambda = lon * RAD;
|
||||
return [
|
||||
Math.cos(phi) * Math.cos(lambda),
|
||||
Math.cos(phi) * Math.sin(lambda),
|
||||
Math.sin(phi),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { vesselPositionAt } from './motion.js';
|
||||
|
||||
const record = {
|
||||
lat: 1,
|
||||
lon: 1,
|
||||
motion: {
|
||||
fromLat: 0,
|
||||
fromLon: 0,
|
||||
fromMs: 1_000,
|
||||
toLat: 1,
|
||||
toLon: 1,
|
||||
toMs: 3_000,
|
||||
},
|
||||
};
|
||||
|
||||
test('a vessel holds at its fixes and moves between them along the great circle', () => {
|
||||
assert.deepEqual(vesselPositionAt(record, 500), { lat: 0, lon: 0 });
|
||||
assert.equal(vesselPositionAt(record, 3_000), record);
|
||||
assert.equal(vesselPositionAt(record, 9_000), record, 'never projected past');
|
||||
const half = vesselPositionAt(record, 2_000);
|
||||
assert.ok(Math.abs(half.lat - 0.5) < 1e-3);
|
||||
assert.ok(Math.abs(half.lon - 0.5) < 1e-3);
|
||||
});
|
||||
|
||||
test('a vessel with no move is at its record', () => {
|
||||
const still = { lat: 4, lon: 5 };
|
||||
assert.equal(vesselPositionAt(still, 2_000), still);
|
||||
assert.equal(vesselPositionAt({ ...still, motion: null }, 2_000).lat, 4);
|
||||
});
|
||||
@@ -101,7 +101,7 @@ test('vessel construction is inert and each instance owns its records, icon cach
|
||||
const two = createVesselState({ source, services: services() });
|
||||
for (const key of ['state', 'shipIconCache'])
|
||||
assert.notEqual(one[key], two[key]);
|
||||
assert.notEqual(one.state.records.byMmsi, two.state.records.byMmsi);
|
||||
assert.notEqual(one.state.records.byId, two.state.records.byId);
|
||||
assert.notEqual(one.state.feed, two.state.feed);
|
||||
assert.notEqual(one.state.records.all, two.state.records.all);
|
||||
assert.notEqual(one.state.records.unkeyed, two.state.records.unkeyed);
|
||||
@@ -275,7 +275,7 @@ test('partial-feed expiry releases a selected vessel and its pending trail', asy
|
||||
layer.selectById('222');
|
||||
current = snapshot([observation('111')], { complete: false });
|
||||
await layer.update();
|
||||
assert.equal(layer.getSelectedInfo().mmsi, '222');
|
||||
assert.equal(layer.getSelectedInfo().id, '222');
|
||||
assert.equal(signal.aborted, false);
|
||||
advance(5 * 60 * 1000);
|
||||
await layer.update();
|
||||
@@ -463,3 +463,96 @@ test('vessel stats name the provider the last snapshot reported', async () => {
|
||||
await layer.update();
|
||||
assert.equal(layer.getStats().source, 'Datalastic');
|
||||
});
|
||||
|
||||
test('two vessels sharing an MMSI under different ids stay two vessels', async () => {
|
||||
const shared = (id, longitude) => ({
|
||||
...observation(id),
|
||||
mmsi: '123456789',
|
||||
longitude,
|
||||
name: `HULL ${id}`,
|
||||
});
|
||||
const { layer, icons } = setup({
|
||||
getSnapshot: async () =>
|
||||
snapshot([shared('hull-a', 4.05), shared('hull-b', 4.25)]),
|
||||
});
|
||||
await layer.update();
|
||||
assert.equal(layer.getStats().count, 2);
|
||||
assert.equal(icons.size, 2);
|
||||
assert.equal(layer.hasContact('hull-a'), true);
|
||||
assert.equal(layer.hasContact('hull-b'), true);
|
||||
// An MMSI is not a key, but a link naming one still finds a vessel with it.
|
||||
assert.equal(layer.hasContact('123456789'), true);
|
||||
assert.equal(layer.hasContact('987654321'), false);
|
||||
assert.deepEqual(
|
||||
layer
|
||||
.getAllPositions()
|
||||
.map(({ id }) => id)
|
||||
.sort(),
|
||||
['hull-a', 'hull-b'],
|
||||
);
|
||||
assert.equal(layer.selectById('hull-b'), true);
|
||||
assert.deepEqual(
|
||||
[layer.getSelectedInfo().id, layer.getSelectedInfo().mmsi],
|
||||
['hull-b', '123456789'],
|
||||
);
|
||||
assert.equal(
|
||||
layer.selectById('123456789'),
|
||||
true,
|
||||
'a link naming the MMSI selects a vessel with it',
|
||||
);
|
||||
assert.equal(layer.getSelectedInfo().mmsi, '123456789');
|
||||
assert.equal(layer.selectById('hull-b'), true);
|
||||
// A lookup by the shared MMSI still finds a vessel that has it.
|
||||
assert.equal(layer.findByQuery('123456789').mmsi, '123456789');
|
||||
});
|
||||
|
||||
test('a vessel with an id and no MMSI renders and can be selected', async () => {
|
||||
const { layer, icons } = setup({
|
||||
getSnapshot: async () =>
|
||||
snapshot([{ ...observation('7f3c9a10-provider-id'), name: 'NO MMSI' }]),
|
||||
});
|
||||
await layer.update();
|
||||
// Its icon row is keyed by its id.
|
||||
assert.deepEqual(icons.ids(), ['7f3c9a10-provider-id']);
|
||||
assert.equal(layer.findByQuery('7f3c9a10-provider-id').mmsi, '');
|
||||
assert.equal(layer.selectById('7f3c9a10-provider-id'), true);
|
||||
const info = layer.getSelectedInfo();
|
||||
assert.equal(info.id, '7f3c9a10-provider-id');
|
||||
assert.equal(info.mmsi, '');
|
||||
assert.equal(layer.getCockpitSubject().id, '7f3c9a10-provider-id');
|
||||
assert.equal(layer.testing._getVesselStateForTest().trailId, info.id);
|
||||
});
|
||||
|
||||
test('a vessel keyed by a UUID is found in any case and names its drawn fix', async () => {
|
||||
const uuid = '0770e3ca-b896-c307-f499-4f9df2b8f86b';
|
||||
const { layer } = setup({
|
||||
getSnapshot: async () =>
|
||||
snapshot([{ ...observation(uuid.toUpperCase()), name: 'UUID HULL' }]),
|
||||
});
|
||||
await layer.update();
|
||||
assert.equal(layer.getSelectedFix(), null, 'nothing selected');
|
||||
// A share link carries the UUID in lowercase.
|
||||
assert.equal(layer.hasContact(uuid), true);
|
||||
assert.equal(layer.selectById(uuid), true);
|
||||
const fix = layer.getSelectedFix();
|
||||
assert.equal(fix.id, uuid.toUpperCase());
|
||||
assert.ok(fix.position, 'where the vessel is drawn');
|
||||
assert.equal(fix.observedAtMs, 500);
|
||||
assert.equal(layer.hasContact('0770e3ca-b896-c307-f499-4f9df2b8f86c'), false);
|
||||
});
|
||||
|
||||
test('AIS feed rows stay keyed by their MMSI', async () => {
|
||||
const { vesselSnapshot } = await import('../../sources/live/vessels.js');
|
||||
const row = { mmsi: '235000001', lat: 51.93, lon: 4.05, name: 'TERN' };
|
||||
const { layer } = setup({
|
||||
getSnapshot: async () =>
|
||||
vesselSnapshot({ rows: [row, { ...row, lon: 4.2 }], status: 'live' }),
|
||||
});
|
||||
await layer.update();
|
||||
assert.equal(layer.getStats().count, 1, 'one MMSI is one vessel on AIS');
|
||||
assert.equal(layer.selectById('235000001'), true);
|
||||
assert.deepEqual(
|
||||
[layer.getSelectedInfo().id, layer.getSelectedInfo().mmsi],
|
||||
['235000001', '235000001'],
|
||||
);
|
||||
});
|
||||
@@ -53,6 +53,11 @@ export const TRAIL_MAX_POINTS = 400;
|
||||
|
||||
export const TRAIL_MIN_MOVE_M = 25;
|
||||
|
||||
/** Whether the layer shows the world clock's time instead of the live feed:
|
||||
* its source declares a timeline and the clock is away from live. */
|
||||
export const followsClock = (vesselState) =>
|
||||
vesselState.timeline?.active() === true;
|
||||
|
||||
export const DEFAULT_AIS_RUNTIME = Object.freeze({
|
||||
now: () => Date.now(),
|
||||
setTimeout: (callback, delayMs) => setTimeout(callback, delayMs),
|
||||
|
||||
+116
-49
@@ -24,7 +24,12 @@ import {
|
||||
REFRESH_MS,
|
||||
FOCUS_EVIDENCE_DEV,
|
||||
VESSEL_LIFT_M,
|
||||
followsClock,
|
||||
} from './policy.js';
|
||||
import { VESSEL_OVERLAY_SOURCE_ID } from '../../data/vesselLabels.js';
|
||||
|
||||
const UUID_KEY =
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
export function createQueries({
|
||||
vesselState,
|
||||
@@ -36,6 +41,28 @@ export function createQueries({
|
||||
const { state } = vesselState;
|
||||
const { formatKnots } = services.labels;
|
||||
|
||||
/**
|
||||
* The vessel keyed `id`, else the first whose MMSI is `id`: a link or a
|
||||
* caller that names a vessel by its MMSI still finds it. A share link
|
||||
* carries a UUID key in lowercase, so a UUID matches in any case.
|
||||
* @param {string} id
|
||||
* @returns {object|null}
|
||||
*/
|
||||
function recordFor(id) {
|
||||
const record = state.records.byId?.get(id);
|
||||
if (record) return record;
|
||||
if (UUID_KEY.test(id)) {
|
||||
const wanted = id.toLowerCase();
|
||||
for (const candidate of state.records.byId?.values() ?? [])
|
||||
if (candidate.id.toLowerCase() === wanted) return candidate;
|
||||
return null;
|
||||
}
|
||||
if (!/^\d{1,10}$/.test(id)) return null;
|
||||
for (const candidate of state.records.byId?.values() ?? [])
|
||||
if (candidate.mmsi === id) return candidate;
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Seconds until the server's next reconnect attempt, or 0 when none is
|
||||
* scheduled. Mirrors the flights layer's `retryInSec` chip affordance.
|
||||
@@ -173,8 +200,9 @@ export function createQueries({
|
||||
* fields are null, never NaN/undefined. navStatus is always null: the
|
||||
* /api/vessels proxy does not surface AIS NavigationalStatus, so it
|
||||
* cannot be derived client-side.
|
||||
* @param {Object|null|undefined} record - `state.records.byMmsi`/`state.records.all` entry.
|
||||
* @returns {{id: string|null, mmsi: string|null, name: string|null,
|
||||
* @param {Object|null|undefined} record - `state.records.byId`/`state.records.all` entry.
|
||||
* @returns {{id: string|null, vesselId: string|null, mmsi: string|null,
|
||||
* name: string|null,
|
||||
* lat: number|null, lon: number|null, speedKts: number|null,
|
||||
* courseDeg: number|null, shipType: string|null, destination: string|null,
|
||||
* navStatus: null}}
|
||||
@@ -186,10 +214,14 @@ export function createQueries({
|
||||
const t = String(v ?? '').trim();
|
||||
return t || null;
|
||||
};
|
||||
const vesselId = text(record?.id);
|
||||
const mmsi = text(record?.mmsi);
|
||||
const name = text(record?.name);
|
||||
return {
|
||||
id: name || mmsi,
|
||||
// A display label, as every layer's analyst `id` is; `vesselId` is the
|
||||
// key and `mmsi` the vessel's MMSI when known.
|
||||
id: name || mmsi || vesselId,
|
||||
vesselId,
|
||||
mmsi,
|
||||
name,
|
||||
lat: num(record?.lat),
|
||||
@@ -223,32 +255,32 @@ export function createQueries({
|
||||
* trail picks as no-ops. The interaction wire also reserves sibling-owned
|
||||
* picks before this reducer so their camera action cannot mutate AIS state.
|
||||
*
|
||||
* @param {{selectedMmsi?: string|number|null, pickedMmsi?: string|number|null,
|
||||
* @param {{selectedId?: string|number|null, pickedId?: string|number|null,
|
||||
* gesture?: 'click'|'escape'}} input - Current selection plus owned pick.
|
||||
* @returns {{action: 'none'|'select'|'deselect'}}
|
||||
*/
|
||||
|
||||
function reduceVesselSelection(input = {}) {
|
||||
const selectedMmsi = normalizeSelectionMmsi(input.selectedMmsi);
|
||||
const pickedMmsi = normalizeSelectionMmsi(input.pickedMmsi);
|
||||
const selectedId = normalizeSelectionId(input.selectedId);
|
||||
const pickedId = normalizeSelectionId(input.pickedId);
|
||||
const gesture = input.gesture || 'click';
|
||||
|
||||
if (gesture === 'escape') {
|
||||
return selectedMmsi ? { action: 'deselect' } : { action: 'none' };
|
||||
return selectedId ? { action: 'deselect' } : { action: 'none' };
|
||||
}
|
||||
if (gesture !== 'click') {
|
||||
return { action: 'none' };
|
||||
}
|
||||
if (pickedMmsi) {
|
||||
if (pickedMmsi === selectedMmsi) {
|
||||
if (pickedId) {
|
||||
if (pickedId === selectedId) {
|
||||
return { action: 'none' };
|
||||
}
|
||||
return { action: 'select' };
|
||||
}
|
||||
return selectedMmsi ? { action: 'deselect' } : { action: 'none' };
|
||||
return selectedId ? { action: 'deselect' } : { action: 'none' };
|
||||
}
|
||||
|
||||
function normalizeSelectionMmsi(value) {
|
||||
function normalizeSelectionId(value) {
|
||||
if (value === null || value === undefined) return null;
|
||||
const text = String(value).trim();
|
||||
return text || null;
|
||||
@@ -273,9 +305,10 @@ export function createQueries({
|
||||
statsRefreshInterval: 1000,
|
||||
|
||||
/**
|
||||
* Find a vessel by exact MMSI or case-insensitive name substring.
|
||||
* @param {string|number} query MMSI or partial vessel name.
|
||||
* @returns {{ mmsi: string, name: string, position: {x: number, y: number, z: number}, latitude: number, longitude: number, speedKt: number|null, course: number|null, type: string }|null}
|
||||
* Find a vessel by its exact id, exact MMSI or case-insensitive name
|
||||
* substring. Vessels can share an MMSI; the first that has it is found.
|
||||
* @param {string|number} query Vessel id, MMSI or partial vessel name.
|
||||
* @returns {{ id: string, mmsi: string, name: string, position: {x: number, y: number, z: number}, latitude: number, longitude: number, speedKt: number|null, course: number|null, type: string }|null}
|
||||
*/
|
||||
findByQuery(query) {
|
||||
if (query === null || query === undefined) return null;
|
||||
@@ -284,9 +317,9 @@ export function createQueries({
|
||||
const q = String(query).trim();
|
||||
if (!q) return null;
|
||||
|
||||
let record = null;
|
||||
if (/^\d+$/.test(q)) {
|
||||
record = state.records.byMmsi.get(q) || null;
|
||||
let record = state.records.byId.get(q) || null;
|
||||
if (!record && /^\d+$/.test(q)) {
|
||||
record = records.find((r) => r.mmsi === q) || null;
|
||||
}
|
||||
if (!record) {
|
||||
const lower = q.toLowerCase();
|
||||
@@ -302,6 +335,7 @@ export function createQueries({
|
||||
const position = components.rendering.iconPosition(record);
|
||||
if (!position) return null;
|
||||
return {
|
||||
id: record.id,
|
||||
mmsi: record.mmsi,
|
||||
name: record.name,
|
||||
position,
|
||||
@@ -318,7 +352,7 @@ export function createQueries({
|
||||
* @param {{x: number, y: number, z: number}} centerCartesian ECEF centre of the search.
|
||||
* @param {number} rangeM Max distance in meters (non-finite = unbounded).
|
||||
* @param {number} [maxCount=25] Maximum entries to return.
|
||||
* @returns {Array<{ mmsi: string, name: string, position: {x: number, y: number, z: number}, distanceM: number }>}
|
||||
* @returns {Array<{ id: string, mmsi: string, name: string, position: {x: number, y: number, z: number}, distanceM: number }>}
|
||||
*/
|
||||
getNearby(centerCartesian, rangeM, maxCount = 25) {
|
||||
const records = state.records.all;
|
||||
@@ -337,6 +371,7 @@ export function createQueries({
|
||||
const distanceM = distance(centerCartesian, position);
|
||||
if (!Number.isFinite(distanceM) || distanceM > range) continue;
|
||||
entries.push({
|
||||
id: record.id,
|
||||
mmsi: record.mmsi,
|
||||
name: record.name,
|
||||
position,
|
||||
@@ -358,7 +393,7 @@ export function createQueries({
|
||||
* @returns {Array<{ id: string, name: string, latitude: number,
|
||||
* longitude: number, course: number|null, heading: number|null,
|
||||
* type: string, color: string, stale: boolean }>} Empty while the
|
||||
* layer is off. A ship with no MMSI has an `unkeyed:` id.
|
||||
* layer is off. A ship with no id has an `unkeyed:` id.
|
||||
*/
|
||||
getRadarContacts(lat, lon, rangeM, maxCount = 60) {
|
||||
const records = state.records.all;
|
||||
@@ -368,7 +403,7 @@ export function createQueries({
|
||||
const cap =
|
||||
Number.isFinite(maxCount) && maxCount > 0 ? Math.floor(maxCount) : 60;
|
||||
const center = { lat, lon };
|
||||
const subject = state.cockpitSubjectMmsi;
|
||||
const subject = state.cockpitSubjectId;
|
||||
const finite = (value) => {
|
||||
if (value === null || value === undefined || value === '') return null;
|
||||
const number = Number(value);
|
||||
@@ -377,7 +412,7 @@ export function createQueries({
|
||||
|
||||
const entries = [];
|
||||
records.forEach((record, index) => {
|
||||
if (subject && String(record.mmsi) === subject) return;
|
||||
if (subject && String(record.id) === subject) return;
|
||||
const distanceM = greatCircleMeters(center, {
|
||||
lat: record.lat,
|
||||
lon: record.lon,
|
||||
@@ -387,8 +422,8 @@ export function createQueries({
|
||||
});
|
||||
entries.sort((a, b) => a.distanceM - b.distanceM);
|
||||
return entries.slice(0, cap).map(({ record, index }) => ({
|
||||
// A ship with no MMSI still needs a key of its own on the scope.
|
||||
id: record.mmsi ? String(record.mmsi) : `unkeyed:${index}`,
|
||||
// A ship with no id still needs a key of its own on the scope.
|
||||
id: record.id ? String(record.id) : `unkeyed:${index}`,
|
||||
name: String(record.name || record.mmsi || ''),
|
||||
latitude: record.lat,
|
||||
longitude: record.lon,
|
||||
@@ -409,22 +444,22 @@ export function createQueries({
|
||||
* Whether this layer still carries a vessel, in O(1).
|
||||
*
|
||||
* Mirror of `flights.hasContact`: presence consumers must not infer absence
|
||||
* from the capped `getAllPositions` rows. `vesselMap` is MMSI-keyed.
|
||||
* from the capped `getAllPositions` rows. Records are keyed by id.
|
||||
* A disabled layer keeps its records, so it must decline rather than answer
|
||||
* from data the user can no longer see.
|
||||
* @param {string} mmsi Vessel identifier.
|
||||
* @param {string} id Vessel id.
|
||||
* @returns {boolean|null} Presence, or null when the layer is disabled or
|
||||
* holds no data and therefore cannot answer.
|
||||
*/
|
||||
hasContact(mmsi) {
|
||||
hasContact(id) {
|
||||
if (
|
||||
!state.feed.enabled ||
|
||||
!state.records.byMmsi ||
|
||||
state.records.byMmsi.size === 0
|
||||
!state.records.byId ||
|
||||
state.records.byId.size === 0
|
||||
)
|
||||
return null;
|
||||
if (!mmsi) return false;
|
||||
return state.records.byMmsi.has(String(mmsi).trim());
|
||||
if (!id) return false;
|
||||
return Boolean(recordFor(String(id).trim()));
|
||||
},
|
||||
|
||||
getAllPositions(maxCount = 800) {
|
||||
@@ -439,8 +474,8 @@ export function createQueries({
|
||||
const position = components.rendering.iconPosition(record);
|
||||
if (!position) continue;
|
||||
result.push({
|
||||
id: record.mmsi,
|
||||
label: record.name || record.mmsi,
|
||||
id: record.id,
|
||||
label: record.name || record.mmsi || record.id,
|
||||
position,
|
||||
latitude: record.lat,
|
||||
longitude: record.lon,
|
||||
@@ -473,16 +508,16 @@ export function createQueries({
|
||||
},
|
||||
|
||||
/**
|
||||
* Select a vessel by MMSI via the same path as a map click
|
||||
* (highlight + HUD update).
|
||||
* @param {string|number} mmsi Vessel MMSI.
|
||||
* Select a vessel by id via the same path as a map click
|
||||
* (highlight + HUD update). An AIS feed's vessels are keyed by MMSI.
|
||||
* @param {string|number} id Vessel id.
|
||||
* @returns {boolean} True if a matching vessel was selected.
|
||||
*/
|
||||
selectById(mmsi) {
|
||||
if (mmsi === null || mmsi === undefined) return false;
|
||||
const target = String(mmsi).trim();
|
||||
selectById(id) {
|
||||
if (id === null || id === undefined) return false;
|
||||
const target = String(id).trim();
|
||||
if (!target) return false;
|
||||
const record = state.records.byMmsi.get(target);
|
||||
const record = recordFor(target);
|
||||
if (!record) return false;
|
||||
components.selection.selectVessel(record);
|
||||
return true;
|
||||
@@ -499,12 +534,13 @@ export function createQueries({
|
||||
|
||||
/**
|
||||
* Get info about the currently selected vessel.
|
||||
* @returns {{ mmsi: string, name: string, latitude: number, longitude: number, speedKt: number|null, course: number|null, type: string }|null}
|
||||
* @returns {{ id: string, mmsi: string, name: string, latitude: number, longitude: number, speedKt: number|null, course: number|null, type: string }|null}
|
||||
*/
|
||||
getSelectedInfo() {
|
||||
const record = state.selectedRecord;
|
||||
if (!record) return null;
|
||||
return {
|
||||
id: record.id,
|
||||
mmsi: record.mmsi,
|
||||
name: record.name,
|
||||
latitude: record.lat,
|
||||
@@ -515,6 +551,32 @@ export function createQueries({
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Where the selected vessel is drawn now, for a share link that names it:
|
||||
* its id, its drawn position and the time that position stands for (the
|
||||
* world time while the layer follows the clock, else its fix's time).
|
||||
* @returns {{ id: string, position: {x: number, y: number, z: number}, observedAtMs: number|null }|null}
|
||||
* Null when the layer is off, nothing is selected or it is not drawn.
|
||||
*/
|
||||
getSelectedFix() {
|
||||
if (!state.feed.enabled) return null;
|
||||
const record = state.selectedRecord;
|
||||
if (!record?.id) return null;
|
||||
const position = components.rendering.iconPosition(record);
|
||||
if (!position) return null;
|
||||
const fixEpoch = record.lastPositionEpoch;
|
||||
const observedAtMs = followsClock(vesselState)
|
||||
? vesselState.worldNow()
|
||||
: Number.isFinite(fixEpoch)
|
||||
? fixEpoch * 1000
|
||||
: (record.fixReceivedAtMs ?? null);
|
||||
return {
|
||||
id: record.id,
|
||||
position,
|
||||
observedAtMs: Number.isFinite(observedAtMs) ? observedAtMs : null,
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Describe the selected vessel for the Cockpit bridge view.
|
||||
* @returns {object|null} `vesselCockpitInfo` fields plus `seaSurfaceHeightM`
|
||||
@@ -540,16 +602,16 @@ export function createQueries({
|
||||
/**
|
||||
* Mark the vessel whose bridge the Cockpit camera occupies, or release it.
|
||||
* Its sprite, card and detection bracket stay hidden while it is held.
|
||||
* @param {string|number|null} mmsi Subject MMSI, or null to release.
|
||||
* @param {string|number|null} id Subject vessel id, or null to release.
|
||||
* @returns {boolean} Always true.
|
||||
*/
|
||||
setCockpitSubject(mmsi) {
|
||||
const next = normalizeSelectionMmsi(mmsi);
|
||||
if (state.cockpitSubjectMmsi === next) return true;
|
||||
state.cockpitSubjectMmsi = next;
|
||||
setCockpitSubject(id) {
|
||||
const next = normalizeSelectionId(id);
|
||||
if (state.cockpitSubjectId === next) return true;
|
||||
state.cockpitSubjectId = next;
|
||||
// The ridden ship's trail runs from under the eye: hidden, its history
|
||||
// kept, while the bridge holds the ship it belongs to.
|
||||
state.trail?.setVisible?.(!next || next !== state.trailMmsi);
|
||||
state.trail?.setVisible?.(!next || next !== state.trailId);
|
||||
components.rendering.updateVisibility(true);
|
||||
return true;
|
||||
},
|
||||
@@ -571,7 +633,7 @@ export function createQueries({
|
||||
* @param {Object} [options={}] - Options from the detection system.
|
||||
* @param {number} [options.maxCount] - Maximum objects to return (defaults to all).
|
||||
* @param {number} [options.seed] - Seed offset for stride sampling.
|
||||
* @returns {Array<{position: {x: number, y: number, z: number}, id: string, type: string, skipLabel: boolean}>}
|
||||
* @returns {Array<{position: {x: number, y: number, z: number}, id: string, type: string, skipLabel: boolean, cardSourceId: string, cardEntryId: string}>}
|
||||
*/
|
||||
getDetectableObjects(options = {}) {
|
||||
if (!state.feed.enabled || !state.icons?.show) return [];
|
||||
@@ -597,10 +659,13 @@ export function createQueries({
|
||||
if (!position) continue;
|
||||
result.push({
|
||||
position,
|
||||
sourceId: record.mmsi,
|
||||
sourceId: record.id,
|
||||
id: record.name || record.mmsi || 'VESSEL',
|
||||
type: 'SEA',
|
||||
skipLabel: record === selected,
|
||||
// Detection hides the callout while this card paints.
|
||||
cardSourceId: VESSEL_OVERLAY_SOURCE_ID,
|
||||
cardEntryId: components.cards.vesselOverlayEntryId(record),
|
||||
klass: record.type
|
||||
? String(record.type).toUpperCase().slice(0, 14)
|
||||
: undefined,
|
||||
@@ -647,6 +712,8 @@ export function createQueries({
|
||||
retryInSec: aisRetryInSec(),
|
||||
// Same field as flights and military, so Contacts names the provider.
|
||||
source: layer.source,
|
||||
// Following the world clock, the snapshot's age is told from its time.
|
||||
...(followsClock(vesselState) && { atMs: vesselState.worldNow() }),
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -660,7 +727,7 @@ export function createQueries({
|
||||
mapAnalystRecord,
|
||||
vesselDatumHeightM,
|
||||
reduceVesselSelection,
|
||||
normalizeSelectionMmsi,
|
||||
normalizeSelectionId,
|
||||
methods,
|
||||
};
|
||||
}
|
||||
@@ -134,7 +134,7 @@ test("the ridden ship's trail is hidden while the bridge holds it", () => {
|
||||
};
|
||||
const layer = layerWith([record('own', 0), record('other', 2)], {
|
||||
trail,
|
||||
trailMmsi: 'own',
|
||||
trailId: 'own',
|
||||
});
|
||||
layer.setCockpitSubject('own');
|
||||
assert.deepEqual(shown, [false]);
|
||||
|
||||
@@ -3,17 +3,25 @@ import {
|
||||
SELECTED_PIN_REFRESHES,
|
||||
} from './recordPolicy.js';
|
||||
|
||||
/** Normalize AIS display fields without allocating scene resources. */
|
||||
/**
|
||||
* Normalize AIS display fields without allocating scene resources. `id` is the
|
||||
* vessel's key, the stable id its source gives; a row that names none (an
|
||||
* AIS feed's own rows) is keyed by its MMSI. `mmsi` is only an attribute,
|
||||
* shown when known: vessels can share one. A row with neither is unkeyed.
|
||||
*/
|
||||
export function normalizeVessel(row) {
|
||||
const lat = Number(row.lat);
|
||||
const lon = Number(row.lon);
|
||||
if (!Number.isFinite(lat) || !Number.isFinite(lon)) return null;
|
||||
const mmsi = String(row.mmsi || '').trim();
|
||||
const id = String(row.id ?? mmsi).trim();
|
||||
return {
|
||||
lat,
|
||||
lon,
|
||||
name: String(row.name || row.mmsi || 'VESSEL'),
|
||||
mmsi: String(row.mmsi || '').trim(),
|
||||
reference: row.reference ?? String(row.mmsi || '').trim(),
|
||||
name: String(row.name || mmsi || 'VESSEL'),
|
||||
id,
|
||||
mmsi,
|
||||
reference: row.reference ?? id,
|
||||
imo: String(row.imo || ''),
|
||||
type: String(row.type || ''),
|
||||
destination: String(row.destination || ''),
|
||||
@@ -44,17 +52,51 @@ function finiteNumber(value) {
|
||||
return Number.isFinite(number) ? number : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The move from a record's fix to the next row's, when the fix moves on in
|
||||
* time; otherwise the move it was making, if the row repeats its fix.
|
||||
*/
|
||||
function motionBetween(record, next) {
|
||||
const fromEpoch = record.lastPositionEpoch;
|
||||
const toEpoch = next.lastPositionEpoch;
|
||||
if (fromEpoch === toEpoch) return record.motion ?? null;
|
||||
if (!Number.isFinite(fromEpoch) || !Number.isFinite(toEpoch)) return null;
|
||||
if (!(toEpoch > fromEpoch)) return null;
|
||||
return {
|
||||
fromLat: record.lat,
|
||||
fromLon: record.lon,
|
||||
fromMs: fromEpoch * 1000,
|
||||
toLat: next.lat,
|
||||
toLon: next.lon,
|
||||
toMs: toEpoch * 1000,
|
||||
};
|
||||
}
|
||||
|
||||
/** Own stable vessel records and bounded incomplete/selected retention. */
|
||||
export class VesselRecords {
|
||||
constructor({ now = () => Date.now() } = {}) {
|
||||
this.now = now;
|
||||
this.byMmsi = new Map();
|
||||
this.byId = new Map();
|
||||
this.unkeyed = [];
|
||||
this.all = [];
|
||||
}
|
||||
/**
|
||||
* Fold a refresh into the records. Following the world clock (`follow`),
|
||||
* a vessel whose fix moves on keeps where it moved from, so it can be drawn
|
||||
* between the two (see motion.js). `replace`: the rows are the world at
|
||||
* another time (the clock jumped), so they stand in for every vessel: one
|
||||
* they lack is gone at once, selected or not, and none moves from where it
|
||||
* was at the time the clock left.
|
||||
*/
|
||||
reconcile(
|
||||
rows,
|
||||
{ complete = true, selectedRecord = null, cap = Infinity },
|
||||
{
|
||||
complete = true,
|
||||
selectedRecord = null,
|
||||
cap = Infinity,
|
||||
replace = false,
|
||||
follow = false,
|
||||
},
|
||||
effects,
|
||||
) {
|
||||
const receivedAtMs = this.now();
|
||||
@@ -78,14 +120,14 @@ export class VesselRecords {
|
||||
if (!next) continue;
|
||||
next.receivedAtMs = receivedAtMs;
|
||||
stampFix(next, receivedAtMs, feedLatestEpoch);
|
||||
if (!next.mmsi) {
|
||||
if (!next.id) {
|
||||
effects.add(next);
|
||||
this.unkeyed.push(next);
|
||||
continue;
|
||||
}
|
||||
if (seen.has(next.mmsi)) continue;
|
||||
seen.add(next.mmsi);
|
||||
const record = this.byMmsi.get(next.mmsi);
|
||||
if (seen.has(next.id)) continue;
|
||||
seen.add(next.id);
|
||||
const record = this.byId.get(next.id);
|
||||
if (record) {
|
||||
// A feed re-serving a cached row repeats its fix: the fix keeps the
|
||||
// time it was first received, so it goes on ageing.
|
||||
@@ -93,7 +135,10 @@ export class VesselRecords {
|
||||
record.fixReceivedAtMs = next.fixReceivedAtMs;
|
||||
record.fixFeedEpoch = next.fixFeedEpoch;
|
||||
}
|
||||
if (replace) record.motion = null;
|
||||
else if (follow) record.motion = motionBetween(record, next);
|
||||
record.reference = next.reference;
|
||||
record.mmsi = next.mmsi;
|
||||
record.receivedAtMs = next.receivedAtMs;
|
||||
record.lat = next.lat;
|
||||
record.lon = next.lon;
|
||||
@@ -111,11 +156,17 @@ export class VesselRecords {
|
||||
effects.updated(record);
|
||||
} else {
|
||||
effects.add(next);
|
||||
this.byMmsi.set(next.mmsi, next);
|
||||
this.byId.set(next.id, next);
|
||||
}
|
||||
}
|
||||
for (const [mmsi, record] of this.byMmsi) {
|
||||
if (seen.has(mmsi)) continue;
|
||||
for (const [id, record] of this.byId) {
|
||||
if (seen.has(id)) continue;
|
||||
if (replace) {
|
||||
effects.remove(record, record === selectedRecord);
|
||||
this.byId.delete(id);
|
||||
effects.removed(id);
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
!complete &&
|
||||
Number.isFinite(record.receivedAtMs) &&
|
||||
@@ -136,18 +187,18 @@ export class VesselRecords {
|
||||
}
|
||||
// Selection teardown still sees the record before its store entry is removed.
|
||||
effects.remove(record, record === selectedRecord);
|
||||
this.byMmsi.delete(mmsi);
|
||||
effects.removed(mmsi);
|
||||
this.byId.delete(id);
|
||||
effects.removed(id);
|
||||
}
|
||||
if (this.byMmsi.size + this.unkeyed.length > cap) {
|
||||
for (const [mmsi, record] of this.byMmsi) {
|
||||
if (this.byMmsi.size + this.unkeyed.length <= cap) break;
|
||||
if (seen.has(mmsi) || record === selectedRecord) continue;
|
||||
if (this.byId.size + this.unkeyed.length > cap) {
|
||||
for (const [id, record] of this.byId) {
|
||||
if (this.byId.size + this.unkeyed.length <= cap) break;
|
||||
if (seen.has(id) || record === selectedRecord) continue;
|
||||
effects.remove(record, false);
|
||||
this.byMmsi.delete(mmsi);
|
||||
effects.removed(mmsi);
|
||||
this.byId.delete(id);
|
||||
effects.removed(id);
|
||||
}
|
||||
}
|
||||
this.all = [...this.byMmsi.values(), ...this.unkeyed];
|
||||
this.all = [...this.byId.values(), ...this.unkeyed];
|
||||
}
|
||||
}
|
||||
@@ -17,8 +17,8 @@ function setup() {
|
||||
add: (record) => events.push(['add', record]),
|
||||
updated: (record) => events.push(['update', record]),
|
||||
remove: (record, evicted) =>
|
||||
events.push(['remove', record, evicted, store.byMmsi.has(record.mmsi)]),
|
||||
removed: (id) => events.push(['removed', id, store.byMmsi.has(id)]),
|
||||
events.push(['remove', record, evicted, store.byId.has(record.id)]),
|
||||
removed: (id) => events.push(['removed', id, store.byId.has(id)]),
|
||||
staleSelected: (record) => events.push(['stale', record]),
|
||||
};
|
||||
return {
|
||||
@@ -39,15 +39,15 @@ test('vessel reconciliation preserves record identity and first duplicate while
|
||||
row('222', { name: 'duplicate' }),
|
||||
row('bad', { lat: NaN }),
|
||||
]);
|
||||
assert.equal(probe.store.byMmsi.size, 2);
|
||||
assert.equal(probe.store.byMmsi.get('222').name, '222');
|
||||
const record = probe.store.byMmsi.get('111');
|
||||
assert.equal(probe.store.byId.size, 2);
|
||||
assert.equal(probe.store.byId.get('222').name, '222');
|
||||
const record = probe.store.byId.get('111');
|
||||
probe.reconcile([row('111', { lat: 51.94, type: 'Tanker' })]);
|
||||
assert.equal(probe.store.byMmsi.get('111'), record);
|
||||
assert.equal(probe.store.byId.get('111'), record);
|
||||
assert.equal(record.lat, 51.94);
|
||||
assert.equal(probe.events.find((event) => event[0] === 'update')[1], record);
|
||||
assert.equal(record.type, 'Tanker');
|
||||
assert.equal(probe.store.byMmsi.has('222'), false);
|
||||
assert.equal(probe.store.byId.has('222'), false);
|
||||
for (const field of [
|
||||
'position',
|
||||
'surfacePosition',
|
||||
@@ -62,14 +62,14 @@ test('vessel reconciliation preserves record identity and first duplicate while
|
||||
test('selected vessel remains pinned for three complete misses and teardown precedes removal', () => {
|
||||
const probe = setup();
|
||||
probe.reconcile([row('111'), row('222')]);
|
||||
const selectedRecord = probe.store.byMmsi.get('111');
|
||||
const selectedRecord = probe.store.byId.get('111');
|
||||
for (let i = 1; i <= 3; i++) {
|
||||
probe.reconcile([row('222')], { selectedRecord });
|
||||
assert.equal(probe.store.byMmsi.get('111'), selectedRecord);
|
||||
assert.equal(probe.store.byId.get('111'), selectedRecord);
|
||||
assert.equal(selectedRecord.missedRefreshes, i);
|
||||
}
|
||||
probe.reconcile([row('222')], { selectedRecord });
|
||||
assert.equal(probe.store.byMmsi.has('111'), false);
|
||||
assert.equal(probe.store.byId.has('111'), false);
|
||||
const removal = probe.events.find(
|
||||
(event) => event[0] === 'remove' && event[1] === selectedRecord,
|
||||
);
|
||||
@@ -83,13 +83,13 @@ test('selected vessel remains pinned for three complete misses and teardown prec
|
||||
test('partial retention respects age and row cap while preserving the selected contact', () => {
|
||||
const probe = setup();
|
||||
probe.reconcile([row('111'), row('222')], { cap: 2 });
|
||||
const selectedRecord = probe.store.byMmsi.get('111');
|
||||
const selectedRecord = probe.store.byId.get('111');
|
||||
probe.reconcile([row('333')], { complete: false, selectedRecord, cap: 2 });
|
||||
assert.deepEqual([...probe.store.byMmsi.keys()], ['111', '333']);
|
||||
assert.deepEqual([...probe.store.byId.keys()], ['111', '333']);
|
||||
assert.equal(selectedRecord.missedRefreshes, 1);
|
||||
probe.advance(5 * 60 * 1000);
|
||||
probe.reconcile([row('333')], { complete: false, selectedRecord, cap: 2 });
|
||||
assert.equal(probe.store.byMmsi.has('111'), false);
|
||||
assert.equal(probe.store.byId.has('111'), false);
|
||||
assert.equal(
|
||||
probe.events.find(
|
||||
(event) => event[0] === 'remove' && event[1] === selectedRecord,
|
||||
@@ -113,7 +113,7 @@ test('unkeyed records rebuild on each refresh and numeric coercion keeps unknown
|
||||
),
|
||||
true,
|
||||
);
|
||||
assert.equal(probe.store.byMmsi.size, 0);
|
||||
assert.equal(probe.store.byId.size, 0);
|
||||
assert.equal(probe.store.all.length, 1);
|
||||
assert.equal(normalizeVessel(row('bad', { lon: Infinity })), null);
|
||||
});
|
||||
@@ -126,14 +126,14 @@ test("each fix keeps when it was first received and its refresh's newest fix", (
|
||||
row('333'),
|
||||
]);
|
||||
for (const mmsi of ['111', '222', '333']) {
|
||||
const record = probe.store.byMmsi.get(mmsi);
|
||||
const record = probe.store.byId.get(mmsi);
|
||||
assert.equal(record.fixFeedEpoch, 1_800_000_030, mmsi);
|
||||
assert.equal(record.fixReceivedAtMs, 1000, mmsi);
|
||||
}
|
||||
// A new fix is stamped afresh.
|
||||
probe.advance(60_000);
|
||||
probe.reconcile([row('111', { last_position_epoch: 1_800_000_050 })]);
|
||||
const record = probe.store.byMmsi.get('111');
|
||||
const record = probe.store.byId.get('111');
|
||||
assert.equal(record.fixFeedEpoch, 1_800_000_050);
|
||||
assert.equal(record.fixReceivedAtMs, 61_000);
|
||||
// The same fix re-served by later polls keeps its first receipt, while
|
||||
@@ -147,3 +147,43 @@ test("each fix keeps when it was first received and its refresh's newest fix", (
|
||||
assert.equal(record.fixFeedEpoch, 1_800_000_050);
|
||||
assert.equal(record.receivedAtMs, 91_000);
|
||||
});
|
||||
|
||||
test('vessels are keyed by their source id; a shared MMSI is only an attribute', () => {
|
||||
const probe = setup();
|
||||
probe.reconcile([
|
||||
row('123456789', { id: 'hull-a', name: 'A' }),
|
||||
row('123456789', { id: 'hull-b', name: 'B' }),
|
||||
row('', { id: 'hull-c', name: 'C' }),
|
||||
]);
|
||||
assert.deepEqual(
|
||||
[...probe.store.byId.keys()],
|
||||
['hull-a', 'hull-b', 'hull-c'],
|
||||
);
|
||||
assert.equal(probe.store.unkeyed.length, 0);
|
||||
const [a, b, c] = probe.store.all;
|
||||
assert.deepEqual([a.mmsi, b.mmsi, c.mmsi], ['123456789', '123456789', '']);
|
||||
assert.equal(a.reference, 'hull-a');
|
||||
// The number moves to another hull: the vessel keeps its id.
|
||||
probe.reconcile([
|
||||
row('', { id: 'hull-a', name: 'A' }),
|
||||
row('123456789', { id: 'hull-b', name: 'B' }),
|
||||
row('123456789', { id: 'hull-c', name: 'C' }),
|
||||
]);
|
||||
assert.equal(probe.store.byId.get('hull-a'), a);
|
||||
assert.equal(a.mmsi, '');
|
||||
assert.equal(probe.store.byId.get('hull-c').mmsi, '123456789');
|
||||
});
|
||||
|
||||
test('an AIS row with no id is keyed by its MMSI; one with neither is unkeyed', () => {
|
||||
assert.deepEqual(
|
||||
[
|
||||
normalizeVessel(row('366999712')).id,
|
||||
normalizeVessel(row('366999712')).mmsi,
|
||||
],
|
||||
['366999712', '366999712'],
|
||||
);
|
||||
const probe = setup();
|
||||
probe.reconcile([row(''), row('', { id: '' })]);
|
||||
assert.equal(probe.store.byId.size, 0);
|
||||
assert.equal(probe.store.unkeyed.length, 2);
|
||||
});
|
||||
@@ -26,7 +26,12 @@ import {
|
||||
FOCUS_UPDATE_MS,
|
||||
LABEL_GRID_PX,
|
||||
CARD_MIN_SEP_PX,
|
||||
followsClock,
|
||||
} from './policy.js';
|
||||
import { vesselPositionAt } from './motion.js';
|
||||
|
||||
/** How often vessels move on as the world clock plays (wall ms). */
|
||||
const FOLLOW_POSITION_MS = 250;
|
||||
|
||||
/** The ship artwork's own raster size (px). */
|
||||
const SHIP_ICON_PX = 32;
|
||||
@@ -56,11 +61,11 @@ export function createRendering({
|
||||
function prepareRecordVisual(record) {
|
||||
let visual = visualRecords.get(record);
|
||||
if (!visual) {
|
||||
// Unkeyed records (no MMSI) are rebuilt every poll, so their rows take
|
||||
// a fresh id that no MMSI can collide with.
|
||||
// Unkeyed records (no id) are rebuilt every poll, so their rows take
|
||||
// a fresh id that no vessel id can collide with.
|
||||
visual = {
|
||||
iconId:
|
||||
record.mmsi || `ais-unkeyed:${++vesselState._unkeyedIconSequence}`,
|
||||
record.id || `ais-unkeyed:${++vesselState._unkeyedIconSequence}`,
|
||||
visible: false,
|
||||
};
|
||||
visualRecords.set(record, visual);
|
||||
@@ -71,17 +76,21 @@ export function createRendering({
|
||||
|
||||
/**
|
||||
* Where a record's icon is anchored: VESSEL_LIFT_M above the sea surface
|
||||
* (the geoid, once its grid has loaded).
|
||||
* (the geoid, once its grid has loaded). Following the world clock, a
|
||||
* vessel is drawn where it was at the time.
|
||||
* @param {Object} record - Vessel record with a finite lat/lon.
|
||||
* @returns {{x: number, y: number, z: number}} ECEF metres: icon items,
|
||||
* focus and the layer's queries take it as it is.
|
||||
*/
|
||||
function anchorPosition(record) {
|
||||
const { lat, lon } = followsClock(vesselState)
|
||||
? vesselPositionAt(record, vesselState.worldNow())
|
||||
: record;
|
||||
const heightM = components.queries.vesselDatumHeightM(
|
||||
components.tracking.currentGeoidN(record.lat, record.lon),
|
||||
components.tracking.currentGeoidN(lat, lon),
|
||||
VESSEL_LIFT_M,
|
||||
);
|
||||
return fromDegrees(record.lon, record.lat, heightM);
|
||||
return fromDegrees(lon, lat, heightM);
|
||||
}
|
||||
|
||||
// Reused projection buffers for the card pass, grown to the candidates.
|
||||
@@ -155,8 +164,7 @@ export function createRendering({
|
||||
/** Whether the Cockpit's bridge camera rides this record's ship. */
|
||||
function isCockpitSubject(record) {
|
||||
return (
|
||||
Boolean(state.cockpitSubjectMmsi) &&
|
||||
record.mmsi === state.cockpitSubjectMmsi
|
||||
Boolean(state.cockpitSubjectId) && record.id === state.cockpitSubjectId
|
||||
);
|
||||
}
|
||||
|
||||
@@ -166,12 +174,12 @@ export function createRendering({
|
||||
* view, so it is hidden while held.
|
||||
*/
|
||||
function syncCockpitSubjectIcon() {
|
||||
const held = state.cockpitSubjectMmsi || null;
|
||||
if (vesselState._iconHiddenMmsi === held) return;
|
||||
const before = vesselState._iconHiddenMmsi;
|
||||
vesselState._iconHiddenMmsi = held;
|
||||
for (const mmsi of [before, held]) {
|
||||
const record = mmsi ? state.records.byMmsi.get(mmsi) : null;
|
||||
const held = state.cockpitSubjectId || null;
|
||||
if (vesselState._iconHiddenId === held) return;
|
||||
const before = vesselState._iconHiddenId;
|
||||
vesselState._iconHiddenId = held;
|
||||
for (const id of [before, held]) {
|
||||
const record = id ? state.records.byId.get(id) : null;
|
||||
if (record) syncRecordIcon(record);
|
||||
}
|
||||
}
|
||||
@@ -302,7 +310,27 @@ export function createRendering({
|
||||
function installRuntime(viewer) {
|
||||
if (state.preRenderRemover || !viewer) return;
|
||||
state.preRenderRemover =
|
||||
findFrame(viewer)?.on('preRender', () => updateVisibility()) ?? null;
|
||||
findFrame(viewer)?.on('preRender', () => {
|
||||
if (followsClock(vesselState)) followClockPositions();
|
||||
updateVisibility();
|
||||
}) ?? null;
|
||||
}
|
||||
|
||||
// As the world clock plays, vessels between two fixes move on along them.
|
||||
let followedAtWallMs = -Infinity;
|
||||
let followedAtMs = null;
|
||||
function followClockPositions() {
|
||||
const wallMs = performance.now();
|
||||
if (wallMs - followedAtWallMs < FOLLOW_POSITION_MS) return;
|
||||
followedAtWallMs = wallMs;
|
||||
const atMs = vesselState.worldNow();
|
||||
if (atMs === followedAtMs) return;
|
||||
followedAtMs = atMs;
|
||||
for (const record of state.records.all) {
|
||||
if (!record.motion) continue;
|
||||
prepareRecordVisual(record);
|
||||
syncRecordIcon(record);
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleTrailingVisibilityPass(now) {
|
||||
@@ -494,8 +522,7 @@ export function createRendering({
|
||||
const selected = state.selectedRecord;
|
||||
// From the bridge, the selected vessel is the viewer; its card would be
|
||||
// pinned to the camera position.
|
||||
const selectedCarded =
|
||||
selected && selected.mmsi !== state.cockpitSubjectMmsi;
|
||||
const selectedCarded = selected && selected.id !== state.cockpitSubjectId;
|
||||
const entries = selectedCarded
|
||||
? [components.cards.buildSelectedVesselCard(selected)]
|
||||
: [];
|
||||
@@ -591,17 +618,17 @@ export function createRendering({
|
||||
VESSEL_CARD_FADE_DISTANCE_M,
|
||||
);
|
||||
if (!card.interactive) return card;
|
||||
const mmsi = String(card.id || '').startsWith('vessel:')
|
||||
const id = String(card.id || '').startsWith('vessel:')
|
||||
? card.id.slice('vessel:'.length)
|
||||
: '';
|
||||
const mmsi = state.records.byId.get(id)?.mmsi || '';
|
||||
return {
|
||||
...card,
|
||||
accessibilityLabel: t('Focus vessel {name}, MMSI {mmsi}', {
|
||||
name: card.title,
|
||||
mmsi,
|
||||
}),
|
||||
accessibilityLabel: mmsi
|
||||
? t('Focus vessel {name}, MMSI {mmsi}', { name: card.title, mmsi })
|
||||
: t('Focus {label}', { label: card.title }),
|
||||
activate: () => {
|
||||
const record = state.records.byMmsi.get(mmsi);
|
||||
const record = state.records.byId.get(id);
|
||||
if (!record) return false;
|
||||
components.selection.selectAndFocusVessel(record);
|
||||
return true;
|
||||
@@ -633,7 +660,8 @@ export function createRendering({
|
||||
text &&
|
||||
text !== 'VESSEL' &&
|
||||
!/^MMSI\s*\d+$/i.test(text) &&
|
||||
text !== record.mmsi,
|
||||
text !== record.mmsi &&
|
||||
text !== record.id,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -29,13 +29,13 @@ export function createSelection({
|
||||
if (!state.feed.enabled) return;
|
||||
// The bridge view owns the selection: a click on open water must not
|
||||
// deselect the vessel the camera is riding.
|
||||
if (state.cockpitSubjectMmsi) return;
|
||||
if (state.cockpitSubjectId) return;
|
||||
const pickedId = event.id;
|
||||
let record = pickedId ? state.records.byMmsi.get(pickedId) : null;
|
||||
let record = pickedId ? state.records.byId.get(pickedId) : null;
|
||||
// A vessel icon's pick is an item of the layer's icon set, whose id is
|
||||
// its row id: the MMSI, or an unkeyed row's. Removing a row removes its
|
||||
// item, so an evicted vessel cannot be picked at all; a live row whose
|
||||
// record is gone stays a no-op below.
|
||||
// its row id: the record's id, or an unkeyed row's. Removing a row
|
||||
// removes its item, so an evicted vessel cannot be picked at all; a
|
||||
// live row whose record is gone stays a no-op below.
|
||||
const hit = event.drawHit;
|
||||
const ownRecordPick =
|
||||
Boolean(hit) &&
|
||||
@@ -78,10 +78,10 @@ export function createSelection({
|
||||
if (cycloneBackground && cardHit?.sourceId !== VESSEL_OVERLAY_SOURCE_ID)
|
||||
return;
|
||||
if (!record && cardHit) {
|
||||
const mmsi = String(cardHit.entryId || '').startsWith('vessel:')
|
||||
const id = String(cardHit.entryId || '').startsWith('vessel:')
|
||||
? cardHit.entryId.slice('vessel:'.length)
|
||||
: null;
|
||||
record = mmsi ? state.records.byMmsi.get(mmsi) || null : null;
|
||||
record = id ? state.records.byId.get(id) || null : null;
|
||||
// A stale card id is not empty terrain and must not clear a newer
|
||||
// selection. The next paint will evict its hit rectangle.
|
||||
if (!record) return;
|
||||
@@ -93,8 +93,8 @@ export function createSelection({
|
||||
selectAndFocusVessel(record);
|
||||
} else {
|
||||
const transition = components.queries.reduceVesselSelection({
|
||||
selectedMmsi: state.selectedRecord?.mmsi,
|
||||
pickedMmsi: null,
|
||||
selectedId: state.selectedRecord?.id,
|
||||
pickedId: null,
|
||||
gesture: 'click',
|
||||
});
|
||||
if (transition.action === 'deselect') clearVesselInspection();
|
||||
@@ -113,17 +113,17 @@ export function createSelection({
|
||||
/** Select one live vessel and request one UI-owned camera transfer. */
|
||||
|
||||
function selectAndFocusVessel(record) {
|
||||
if (!record?.mmsi) return false;
|
||||
if (!record?.id) return false;
|
||||
const transition = components.queries.reduceVesselSelection({
|
||||
selectedMmsi: state.selectedRecord?.mmsi,
|
||||
pickedMmsi: record.mmsi,
|
||||
selectedId: state.selectedRecord?.id,
|
||||
pickedId: record.id,
|
||||
gesture: 'click',
|
||||
});
|
||||
if (transition.action === 'select') selectVessel(record);
|
||||
requestWorldFocus({
|
||||
kind: 'vessel',
|
||||
id: record.mmsi,
|
||||
label: record.name || record.mmsi,
|
||||
id: record.id,
|
||||
label: record.name || record.mmsi || record.id,
|
||||
position: components.rendering.iconPosition(record),
|
||||
});
|
||||
return true;
|
||||
@@ -146,7 +146,7 @@ export function createSelection({
|
||||
function onVesselKeyDown(event) {
|
||||
if (!state.feed.enabled || event.key !== 'Escape') return;
|
||||
const transition = components.queries.reduceVesselSelection({
|
||||
selectedMmsi: state.selectedRecord?.mmsi,
|
||||
selectedId: state.selectedRecord?.id,
|
||||
gesture: 'escape',
|
||||
});
|
||||
if (transition.action === 'deselect') {
|
||||
@@ -155,8 +155,8 @@ export function createSelection({
|
||||
}
|
||||
|
||||
function selectVessel(record) {
|
||||
if (!record?.mmsi) return;
|
||||
const reuseTrail = state.trailMmsi === record.mmsi;
|
||||
if (!record?.id) return;
|
||||
const reuseTrail = state.trailId === record.id;
|
||||
clearSelection({ preserveTrail: reuseTrail });
|
||||
state.selectedRecord = record;
|
||||
record.missedRefreshes = 0;
|
||||
@@ -169,7 +169,7 @@ export function createSelection({
|
||||
selectEntityContext(record);
|
||||
}
|
||||
// Track-history trail (PRD F3/F4): seed with the current position + async
|
||||
// backfill from the server-side per-MMSI ring buffer.
|
||||
// backfill from the source's recent track for this vessel.
|
||||
if (reuseTrail) {
|
||||
components.tracking.appendSelectedVesselTrailFix(record);
|
||||
} else {
|
||||
@@ -185,10 +185,10 @@ export function createSelection({
|
||||
*/
|
||||
|
||||
function registerSelectedContext(record) {
|
||||
if (!record?.mmsi) return null;
|
||||
if (!record?.id) return null;
|
||||
try {
|
||||
return registerEntityContext(record, {
|
||||
id: `ais-${record.mmsi}`,
|
||||
id: `ais-${record.id}`,
|
||||
layerId: 'ais-live-vessels',
|
||||
layerName: 'Live AIS Vessels',
|
||||
source: aisLiveVesselsLayer.source,
|
||||
@@ -196,7 +196,8 @@ export function createSelection({
|
||||
latitude: record.lat,
|
||||
longitude: record.lon,
|
||||
properties: {
|
||||
mmsi: record.mmsi,
|
||||
vesselId: record.id,
|
||||
mmsi: record.mmsi || null,
|
||||
type: record.type,
|
||||
speedKt: record.speed,
|
||||
course: record.course,
|
||||
|
||||
@@ -7,16 +7,25 @@ export function createVesselSnapshotRenderer({
|
||||
tracking,
|
||||
selection,
|
||||
cards,
|
||||
followsClock = () => false,
|
||||
}) {
|
||||
function reconcileVessels(viewer, rows, { complete = true } = {}) {
|
||||
/** `replace`: the rows are the world at another time (see VesselRecords). */
|
||||
function reconcileVessels(
|
||||
viewer,
|
||||
rows,
|
||||
{ complete = true, replace = false } = {},
|
||||
) {
|
||||
rendering.ensureCollections(viewer);
|
||||
const occluder = rendering.makeOccluder();
|
||||
const follow = followsClock();
|
||||
records.reconcile(
|
||||
rows,
|
||||
{
|
||||
complete,
|
||||
selectedRecord: state.selectedRecord,
|
||||
cap: rendering.renderRowLimit(),
|
||||
...(replace && { replace }),
|
||||
...(follow && { follow }),
|
||||
},
|
||||
{
|
||||
add(record) {
|
||||
@@ -27,7 +36,7 @@ export function createVesselSnapshotRenderer({
|
||||
const selected = record === state.selectedRecord;
|
||||
rendering.prepareRecordVisual(record);
|
||||
rendering.syncRecordIcon(record);
|
||||
if (record.mmsi === state.trailMmsi)
|
||||
if (record.id === state.trailId)
|
||||
tracking.appendSelectedVesselTrailFix(record);
|
||||
if (selected) {
|
||||
cards.updateSelectedVesselHud(record);
|
||||
@@ -38,14 +47,17 @@ export function createVesselSnapshotRenderer({
|
||||
if (evicted) selection.clearVesselInspection({ evicted: true });
|
||||
rendering.removeRecordPrimitives(record);
|
||||
},
|
||||
removed(mmsi) {
|
||||
if (state.trailMmsi === mmsi) tracking.clearSelectedVesselTrail();
|
||||
removed(id) {
|
||||
if (state.trailId === id) tracking.clearSelectedVesselTrail();
|
||||
},
|
||||
staleSelected(record) {
|
||||
cards.updateSelectedVesselHud(record);
|
||||
},
|
||||
},
|
||||
);
|
||||
// The selected vessel at the new time: its trail starts there.
|
||||
if (replace && state.selectedRecord && state.trailId)
|
||||
tracking.startSelectedVesselTrail(state.selectedRecord);
|
||||
state.lastVisibilityUpdate = 0;
|
||||
rendering.updateVisibility(true);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createVesselFeed } from './ingestion.js';
|
||||
import { VesselRecords } from './records.js';
|
||||
import { DEFAULT_AIS_RUNTIME } from './policy.js';
|
||||
import { DEFAULT_AIS_RUNTIME, followsClock } from './policy.js';
|
||||
import { worldTimeFor } from '../../time/worldClock.js';
|
||||
|
||||
export function createVesselState({ source, services }) {
|
||||
const {
|
||||
@@ -28,6 +29,19 @@ export function createVesselState({ source, services }) {
|
||||
|
||||
vesselState._aisRuntime = DEFAULT_AIS_RUNTIME;
|
||||
|
||||
/** Follows the world clock while the source declares a timeline (set by the
|
||||
* layer); see followsClock in policy.js. */
|
||||
vesselState.timeline = null;
|
||||
|
||||
/** The world time the layer draws at while it follows the clock. */
|
||||
vesselState.worldNow = worldTimeFor('ais-live-vessels');
|
||||
|
||||
/** The time records are judged at: the world's while following the clock. */
|
||||
vesselState.recordsNow = () =>
|
||||
followsClock(vesselState)
|
||||
? vesselState.worldNow()
|
||||
: vesselState._aisRuntime.now();
|
||||
|
||||
vesselState._aisSessionSequence = 0;
|
||||
|
||||
/**
|
||||
@@ -43,15 +57,15 @@ export function createVesselState({ source, services }) {
|
||||
|
||||
vesselState.shipIconCache = new Map();
|
||||
|
||||
/** Row ids for unkeyed (no-MMSI) records, which are rebuilt every poll. */
|
||||
/** Row ids for unkeyed (no-id) records, which are rebuilt every poll. */
|
||||
|
||||
vesselState._unkeyedIconSequence = 0;
|
||||
// The ship whose icon is hidden under the bridge camera (cockpit subject).
|
||||
vesselState._iconHiddenMmsi = null;
|
||||
vesselState._iconHiddenId = null;
|
||||
|
||||
vesselState.state = {
|
||||
feed: createVesselFeed(),
|
||||
records: new VesselRecords({ now: () => vesselState._aisRuntime.now() }),
|
||||
records: new VesselRecords({ now: () => vesselState.recordsNow() }),
|
||||
viewer: null,
|
||||
|
||||
/** The vessels' icons as drawn (`iconBook.js`), and their draw set. */
|
||||
@@ -75,14 +89,14 @@ export function createVesselState({ source, services }) {
|
||||
activeFocusCount: 0,
|
||||
activeLabelCount: 0,
|
||||
selectedRecord: null,
|
||||
/** @type {string|null} MMSI whose bridge the Cockpit camera occupies; its sprite and card stay hidden. */
|
||||
cockpitSubjectMmsi: null,
|
||||
/** @type {string|null} Id of the vessel whose bridge the Cockpit camera occupies; its sprite and card stay hidden. */
|
||||
cockpitSubjectId: null,
|
||||
/** @type {{setPositions: Function, clear: Function, destroy: Function}|null} Selected-vessel fading trail */
|
||||
trail: null,
|
||||
/** @type {{x: number, y: number, z: number}[]} Chronological ECEF trail vertices (oldest first) */
|
||||
trailPositions: [],
|
||||
/** @type {string|null} MMSI that owns the active selected-vessel trail. */
|
||||
trailMmsi: null,
|
||||
/** @type {string|null} Id of the vessel that owns the active selected-vessel trail. */
|
||||
trailId: null,
|
||||
/** @type {number} Monotonic token — invalidates in-flight backfill responses */
|
||||
trailBackfillToken: 0,
|
||||
trailAbort: null,
|
||||
|
||||
@@ -33,6 +33,11 @@ export function createTesting({
|
||||
function _setVesselStateForTest(options = {}) {
|
||||
components.lifecycle.resetState();
|
||||
const records = Array.isArray(options.records) ? options.records : [];
|
||||
// A test record that names no id is keyed by its MMSI, as an AIS feed's
|
||||
// own rows are (see normalizeVessel).
|
||||
for (const record of [...records, options.selectedRecord])
|
||||
if (record && typeof record === 'object' && record.id === undefined)
|
||||
record.id = String(record.mmsi || '').trim();
|
||||
state.viewer = options.viewer || null;
|
||||
state.feed.enabled = options.enabled !== false;
|
||||
state.feed.loaded = options.loaded === true;
|
||||
@@ -43,17 +48,17 @@ export function createTesting({
|
||||
state.feed.lastUpdate = options.lastUpdate ?? null;
|
||||
state.records.all = records;
|
||||
state.feed.count = records.length;
|
||||
state.records.byMmsi = new Map(
|
||||
state.records.byId = new Map(
|
||||
records
|
||||
.filter((record) => record?.mmsi)
|
||||
.map((record) => [record.mmsi, record]),
|
||||
.filter((record) => record?.id)
|
||||
.map((record) => [record.id, record]),
|
||||
);
|
||||
state.selectedRecord = options.selectedRecord || null;
|
||||
// `icons: null` leaves the layer to make its own draw set.
|
||||
state.icons =
|
||||
options.icons === null ? null : options.icons || createVesselIconBook();
|
||||
state.trail = options.trail || null;
|
||||
state.trailMmsi = options.trailMmsi || null;
|
||||
state.trailId = options.trailId || null;
|
||||
state.trailPositions = Array.isArray(options.trailPositions)
|
||||
? [...options.trailPositions]
|
||||
: [];
|
||||
@@ -143,8 +148,8 @@ export function createTesting({
|
||||
lastMessageAt: state.feed.lastMessageAt,
|
||||
rawRowCount: state.feed.rawRowCount,
|
||||
acceptedRowCount: state.feed.acceptedRowCount,
|
||||
selectedMmsi: state.selectedRecord?.mmsi || null,
|
||||
trailMmsi: state.trailMmsi,
|
||||
selectedId: state.selectedRecord?.id || null,
|
||||
trailId: state.trailId,
|
||||
trailPositionCount: state.trailPositions.length,
|
||||
sessionId: state.feed.sessionId,
|
||||
firstConnectPhase: state.feed.firstConnectPhase,
|
||||
@@ -168,14 +173,14 @@ export function createTesting({
|
||||
/**
|
||||
* Read lifecycle ownership state without exposing the mutable state object.
|
||||
* Test-only seam.
|
||||
* @returns {{trailMmsi: string|null, trailPositionCount: number, vesselCount: number}}
|
||||
* @returns {{trailId: string|null, trailPositionCount: number, vesselCount: number}}
|
||||
*/
|
||||
|
||||
function _getVesselStateForTest() {
|
||||
return {
|
||||
trailMmsi: state.trailMmsi,
|
||||
trailId: state.trailId,
|
||||
trailPositionCount: state.trailPositions.length,
|
||||
vesselCount: state.records.byMmsi.size,
|
||||
vesselCount: state.records.byId.size,
|
||||
};
|
||||
}
|
||||
return {
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
TRAIL_COLOR,
|
||||
TRAIL_MAX_POINTS,
|
||||
TRAIL_MIN_MOVE_M,
|
||||
followsClock,
|
||||
} from './policy.js';
|
||||
|
||||
export function createTracking({
|
||||
@@ -80,7 +81,7 @@ export function createTracking({
|
||||
state.trailAbort?.abort();
|
||||
state.trailAbort = new AbortController();
|
||||
state.trailBackfillToken += 1;
|
||||
state.trailMmsi = record.mmsi;
|
||||
state.trailId = record.id;
|
||||
state.trailPositions = [];
|
||||
const current = vesselTrailPosition(record);
|
||||
if (current) state.trailPositions.push(current);
|
||||
@@ -91,32 +92,33 @@ export function createTracking({
|
||||
});
|
||||
}
|
||||
if (state.trail) state.trail.setPositions(state.trailPositions);
|
||||
backfillVesselTrail(
|
||||
record.mmsi,
|
||||
state.trailBackfillToken,
|
||||
record.reference,
|
||||
);
|
||||
backfillVesselTrail(record.id, state.trailBackfillToken, record.reference);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fire-and-forget backfill from the server-side per-MMSI ring buffer
|
||||
* Fire-and-forget backfill from the server-side per-vessel ring buffer
|
||||
* (PRD F3 — "recent path" since server boot, not voyage history). Older
|
||||
* samples are spliced AHEAD of the live accumulation, capped at
|
||||
* TRAIL_MAX_POINTS (newest kept). Any failure (404/timeout/malformed)
|
||||
* silently keeps the live-only trail.
|
||||
* @param {string} mmsi - MMSI of the selected vessel.
|
||||
* @param {string} id - Key of the selected vessel.
|
||||
* @param {number} token - Backfill token captured at request time.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
|
||||
async function backfillVesselTrail(mmsi, token, reference = mmsi) {
|
||||
async function backfillVesselTrail(id, token, reference = id) {
|
||||
const owner = state.trailAbort;
|
||||
// Following the world clock, the track ends at the world's time.
|
||||
const atMs = followsClock(vesselState) ? vesselState.worldNow() : undefined;
|
||||
const signal = owner
|
||||
? AbortSignal.any([owner.signal, AbortSignal.timeout(8000)])
|
||||
: AbortSignal.timeout(8000);
|
||||
let samples = null;
|
||||
try {
|
||||
const track = await vesselState._source.getTrack?.(reference, { signal });
|
||||
const track = await vesselState._source.getTrack?.(
|
||||
reference,
|
||||
atMs === undefined ? { signal } : { signal, atMs },
|
||||
);
|
||||
samples = track?.records ?? null;
|
||||
} catch {
|
||||
return; // silent — keep the live-accumulated trail
|
||||
@@ -128,13 +130,19 @@ export function createTracking({
|
||||
token !== state.trailBackfillToken
|
||||
)
|
||||
return;
|
||||
if (state.trailMmsi !== mmsi) return;
|
||||
if (state.trailId !== id) return;
|
||||
|
||||
const older = [];
|
||||
for (const sample of samples) {
|
||||
const lat = Number(sample?.latitude);
|
||||
const lon = Number(sample?.longitude);
|
||||
if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue;
|
||||
// Following the clock, an undated sample may be later than the time.
|
||||
if (
|
||||
atMs !== undefined &&
|
||||
!(Number.isFinite(sample?.observedAtMs) && sample.observedAtMs <= atMs)
|
||||
)
|
||||
continue;
|
||||
// Per-sample N (≤ TRAIL_MAX_POINTS lookups) — same sea-surface datum as
|
||||
// the live vertices so the spliced trail is height-continuous.
|
||||
const heightM = components.queries.vesselDatumHeightM(
|
||||
@@ -180,7 +188,7 @@ export function createTracking({
|
||||
state.trailAbort?.abort();
|
||||
state.trailAbort = null;
|
||||
state.trailBackfillToken += 1;
|
||||
state.trailMmsi = null;
|
||||
state.trailId = null;
|
||||
state.trailPositions = [];
|
||||
if (state.trail) state.trail.clear();
|
||||
}
|
||||
|
||||
Loaded 100 of 331 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user