mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 16:22:20 +00:00
Merge main into german/transit-bikeshare-empty-state
Conflict in src/layers/transit/queries.js: keep the branch's shared note with the gate's enter altitude and main's distinct region count.
This commit is contained in:
commit
3a78f40024
218 files changed
+29736
-599
No files matched your search
@@ -17,6 +17,7 @@ import { CockpitCoordinator } from './cockpitCoordinator.js';
|
||||
import { ContextControls } from './context.js';
|
||||
import { CctvControls } from './cctv.js';
|
||||
import { StreetLevelControls } from './streetLevelControls.js';
|
||||
import { createWildlifeSightingCard } from './wildlifeSightingCard.js';
|
||||
import { RadioControls } from './radio.js';
|
||||
import { LocalSdrControls } from './localSdrControls.js';
|
||||
import { LocationNavigation } from './locationNavigation.js';
|
||||
@@ -589,6 +590,7 @@ export class StyleManager extends ShellFacade {
|
||||
this._initRadioPanel();
|
||||
this._initCctvPanel();
|
||||
this._initStreetLevelPanel();
|
||||
this._initWildlifeSightingCard();
|
||||
this._initGlobalContextPanel();
|
||||
this._initLocationBar();
|
||||
this._initMobileShell();
|
||||
@@ -1073,6 +1075,19 @@ export class StyleManager extends ShellFacade {
|
||||
return this._runExplicitNavigation('camera', () => focus(cameraId));
|
||||
}
|
||||
|
||||
/** Keep one compact card anchored to the selected wildlife sighting. */
|
||||
_initWildlifeSightingCard() {
|
||||
this._wildlifeSightingCard?.destroy();
|
||||
this._wildlifeSightingCard = null;
|
||||
const layer = this.services.wildlifeSightingsLayer;
|
||||
if (!layer) return;
|
||||
this._wildlifeSightingCard = createWildlifeSightingCard({
|
||||
layer,
|
||||
ui: this._ui,
|
||||
viewer: this.viewer,
|
||||
});
|
||||
}
|
||||
|
||||
/** Compose the Street Level panel controls from its layer and application actions. */
|
||||
_initStreetLevelPanel() {
|
||||
const { streetLevelLayer } = this.services;
|
||||
@@ -1791,6 +1806,7 @@ export class StyleManager extends ShellFacade {
|
||||
this._recording.destroy();
|
||||
this._mobileShell?.destroy();
|
||||
this._panelNavigation?.destroy();
|
||||
this._wildlifeSightingCard?.destroy();
|
||||
this._ui.destroy();
|
||||
this._panelChrome.destroy();
|
||||
this._feedback.destroy();
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
// src/ui/cockpitBodyClasses.test.mjs — the classes the Cockpit puts on
|
||||
// <body> must not also name an element's rule. A bare `.name { … }` written
|
||||
// for a panel matches <body> the moment <body> carries `name`, and its
|
||||
// pointer-events, position and overflow then apply to the whole page.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync, readdirSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const UI_ROOT = fileURLToPath(new URL('.', import.meta.url));
|
||||
const SRC_ROOT = path.resolve(UI_ROOT, '..');
|
||||
const CONTROLLER = path.join(UI_ROOT, 'cockpitTrackingController.js');
|
||||
|
||||
/** Every stylesheet the app ships. */
|
||||
function stylesheets(directory = SRC_ROOT) {
|
||||
const files = [];
|
||||
for (const entry of readdirSync(directory, { withFileTypes: true })) {
|
||||
const absolute = path.join(directory, entry.name);
|
||||
if (entry.isDirectory()) files.push(...stylesheets(absolute));
|
||||
else if (entry.isFile() && entry.name.endsWith('.css'))
|
||||
files.push(absolute);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
/** A selector list split on its top-level commas, not those in `:not(a, b)`. */
|
||||
function splitSelectorList(list) {
|
||||
const parts = [];
|
||||
let depth = 0;
|
||||
let start = 0;
|
||||
for (let i = 0; i < list.length; i += 1) {
|
||||
if (list[i] === '(') depth += 1;
|
||||
else if (list[i] === ')') depth -= 1;
|
||||
else if (list[i] === ',' && depth === 0) {
|
||||
parts.push(list.slice(start, i));
|
||||
start = i + 1;
|
||||
}
|
||||
}
|
||||
parts.push(list.slice(start));
|
||||
return parts;
|
||||
}
|
||||
|
||||
/** The classes the tracking controller adds to <body>. */
|
||||
function cockpitBodyClasses() {
|
||||
const source = readFileSync(CONTROLLER, 'utf8');
|
||||
const names = [
|
||||
...source.matchAll(/body\.classList\.add\(\s*'([a-z0-9-]+)'/g),
|
||||
].map((match) => match[1]);
|
||||
return [...new Set(names)];
|
||||
}
|
||||
|
||||
test('the Cockpit adds its subject classes to <body>', () => {
|
||||
const classes = cockpitBodyClasses();
|
||||
for (const name of ['cockpit-mode']) {
|
||||
assert.ok(classes.includes(name), `${name} is not added to <body>`);
|
||||
}
|
||||
});
|
||||
|
||||
test('no stylesheet rule matches a Cockpit body class on another element', () => {
|
||||
const offenders = [];
|
||||
for (const name of cockpitBodyClasses()) {
|
||||
// `.name` as a whole class token, not as `.name-suffix`.
|
||||
const token = new RegExp(`\\.${name}(?![\\w-])`);
|
||||
for (const file of stylesheets()) {
|
||||
const css = readFileSync(file, 'utf8').replace(/\/\*[\s\S]*?\*\//g, '');
|
||||
for (const [, selectors] of css.matchAll(/([^{}]+)\{/g)) {
|
||||
for (const selector of splitSelectorList(selectors)) {
|
||||
// Prettier wraps long `:not(\n .name\n)` arguments; unwrap them.
|
||||
const compound = selector
|
||||
.trim()
|
||||
.replace(/\(\s+/g, '(')
|
||||
.replace(/\s+\)/g, ')');
|
||||
if (!token.test(compound)) continue;
|
||||
// Allowed only on <body> itself: `body.name` or `body:not(.name)`.
|
||||
const onBody = new RegExp(
|
||||
`(^|[\\s>+~])body[^\\s>+~]*\\.${name}(?![\\w-])`,
|
||||
);
|
||||
if (onBody.test(compound)) continue;
|
||||
offenders.push(`${path.relative(SRC_ROOT, file)}: ${compound}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert.deepEqual(
|
||||
offenders,
|
||||
[],
|
||||
'Selectors that match a Cockpit body class without `body.`: ' +
|
||||
offenders.join('; '),
|
||||
);
|
||||
});
|
||||
+26
-5
@@ -19,6 +19,14 @@ import {
|
||||
COCKPIT_GROUND_WAIT_TIMEOUT_MS,
|
||||
} from './cockpitPresentation.js';
|
||||
|
||||
/** The aircraft eye: just ahead of and above the reported position. */
|
||||
const AIRCRAFT_CAMERA_PROFILE = Object.freeze({
|
||||
forwardM: COCKPIT_FORWARD_OFFSET_M,
|
||||
upM: COCKPIT_UP_OFFSET_M,
|
||||
pitchDeg: COCKPIT_VIEW_PITCH_DEG,
|
||||
minClearanceM: COCKPIT_MIN_GROUND_CLEARANCE_M,
|
||||
});
|
||||
|
||||
export function update() {
|
||||
if (this.destroyed) return false;
|
||||
if (!this.active) {
|
||||
@@ -75,7 +83,20 @@ export function update() {
|
||||
COCKPIT_HEADING_SLEW_DPS * dtSec,
|
||||
);
|
||||
}
|
||||
placeCamera.call(this, target, info, nowMs, dtSec, AIRCRAFT_CAMERA_PROFILE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Place the camera for one update: advance the inertial anchor, clamp it and
|
||||
* the eye against the rendered surface, and look along the slewed heading.
|
||||
* @param {Cesium.Cartesian3} target Authoritative subject position.
|
||||
* @param {object} info Subject info.
|
||||
* @param {number} nowMs Frame time.
|
||||
* @param {number} dtSec Seconds since the previous camera update.
|
||||
* @param {{forwardM: number, upM: number, pitchDeg: number,
|
||||
* minClearanceM: number}} profile Eye offsets for the subject kind.
|
||||
*/
|
||||
function placeCamera(target, info, nowMs, dtSec, profile) {
|
||||
if (!this.cockpitAnchorValid) {
|
||||
Cesium.Cartesian3.clone(target, this.cockpitAnchor);
|
||||
this.cockpitAnchorValid = true;
|
||||
@@ -89,7 +110,7 @@ export function update() {
|
||||
// 15/30-second interpolation and per-frame cache without exposing its
|
||||
// sample-boundary corrections to the camera.
|
||||
const headingRad = Cesium.Math.toRadians(this.heading ?? 0);
|
||||
const pitchRad = Cesium.Math.toRadians(COCKPIT_VIEW_PITCH_DEG);
|
||||
const pitchRad = Cesium.Math.toRadians(profile.pitchDeg);
|
||||
const speedMps = Number.isFinite(info.velocityMps)
|
||||
? Math.max(0, info.velocityMps)
|
||||
: 0;
|
||||
@@ -248,7 +269,7 @@ export function update() {
|
||||
const minimumAnchorHeightM = cockpitGroundSafeHeight(
|
||||
anchorCartographic.height,
|
||||
cockpitFloorM,
|
||||
COCKPIT_MIN_GROUND_CLEARANCE_M - COCKPIT_UP_OFFSET_M,
|
||||
profile.minClearanceM - profile.upM,
|
||||
);
|
||||
if (minimumAnchorHeightM !== anchorCartographic.height) {
|
||||
anchorCartographic.height = minimumAnchorHeightM;
|
||||
@@ -297,7 +318,7 @@ export function update() {
|
||||
|
||||
Cesium.Cartesian3.multiplyByScalar(
|
||||
this.scratchHorizontal,
|
||||
COCKPIT_FORWARD_OFFSET_M,
|
||||
profile.forwardM,
|
||||
this.scratchCamera,
|
||||
);
|
||||
Cesium.Cartesian3.add(
|
||||
@@ -309,7 +330,7 @@ export function update() {
|
||||
Cesium.Cartesian3.normalize(this.scratchTarget, this.scratchTarget);
|
||||
Cesium.Cartesian3.multiplyByScalar(
|
||||
this.scratchTarget,
|
||||
COCKPIT_UP_OFFSET_M,
|
||||
profile.upM,
|
||||
this.scratchTarget,
|
||||
);
|
||||
Cesium.Cartesian3.add(
|
||||
@@ -338,7 +359,7 @@ export function update() {
|
||||
const safeHeightM = cockpitGroundSafeHeight(
|
||||
cameraCartographic.height,
|
||||
cockpitFloorM,
|
||||
COCKPIT_MIN_GROUND_CLEARANCE_M,
|
||||
profile.minClearanceM,
|
||||
);
|
||||
if (safeHeightM !== cameraCartographic.height) {
|
||||
cameraCartographic.height = safeHeightM;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/** Contact readouts and nearby-signal presentation for the Cockpit controller. */
|
||||
import * as Cesium from 'cesium';
|
||||
import { formatNumber, t, tn } from '../i18n/index.js';
|
||||
import { sourceStatusLabel } from './layerNames.js';
|
||||
import { unitLabel } from './unitLabels.js';
|
||||
import {
|
||||
bearingBetweenCoordinates,
|
||||
@@ -24,6 +25,27 @@ const LOCALIZED_CONTEXT_SCOPE = Object.freeze({
|
||||
t('{scope} · INSTALLATIONS {coverage}', { scope, coverage }),
|
||||
});
|
||||
|
||||
/**
|
||||
* Which air feed the aircraft Cockpit's surrounding picture is missing. Entry
|
||||
* needs only the ridden aircraft's own layer, so the other one may be off;
|
||||
* the panels then say the picture is partial rather than present it as
|
||||
* complete. Null with both feeds on, or when the owner cannot tell.
|
||||
* @returns {?{title: string, detail: string}}
|
||||
*/
|
||||
export function readPartialPicture() {
|
||||
const isLayerEnabled = this.services.isLayerEnabled;
|
||||
if (typeof isLayerEnabled !== 'function') return null;
|
||||
const militaryOff = !isLayerEnabled('military');
|
||||
const flightsOff = !isLayerEnabled('flights');
|
||||
if (!militaryOff && !flightsOff) return null;
|
||||
return {
|
||||
title: militaryOff
|
||||
? t('MILITARY FEED OFF · PARTIAL PICTURE')
|
||||
: t('FLIGHTS FEED OFF · PARTIAL PICTURE'),
|
||||
detail: t('NEARBY AIRCRAFT INCOMPLETE · NOT AN ALL-CLEAR'),
|
||||
};
|
||||
}
|
||||
|
||||
/** Hand a fresh copy of the Contact card to the view. */
|
||||
export function publishContextView() {
|
||||
const view = this.contextView;
|
||||
@@ -52,7 +74,11 @@ export function updateContext(info, heading) {
|
||||
this.services.militaryAwarenessLayer.getContextSnapshot?.() || null;
|
||||
const trackedId = info.icao24 || info.id;
|
||||
const readout = resolveCockpitContextReadout({ snapshot, info });
|
||||
const partial = readPartialPicture.call(this);
|
||||
if (!readout.visible) {
|
||||
// Contacts just went off: the rows its snapshot built stop being
|
||||
// measured, so they go before the standby rows replace them.
|
||||
if (this.presence.context) this.dropContextSnapshotSignals?.();
|
||||
this.showContextCard(false);
|
||||
this.contextLayoutStamp = null;
|
||||
this.pushCockpitSignal(
|
||||
@@ -61,6 +87,14 @@ export function updateContext(info, heading) {
|
||||
t('CONTEXT STANDBY'),
|
||||
t('ENABLE GLOBAL CONTEXT FOR PROXIMITY PINGS'),
|
||||
);
|
||||
if (partial)
|
||||
this.pushCockpitSignal(
|
||||
'feed-status',
|
||||
'warning',
|
||||
partial.title,
|
||||
partial.detail,
|
||||
);
|
||||
else this.dropCockpitSignal?.('feed-status');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -110,6 +144,7 @@ export function updateContext(info, heading) {
|
||||
if (shown) {
|
||||
shown.count = cohort.count === null ? '?' : String(cohort.count);
|
||||
shown.unknown = cohort.relationship === 'UNKNOWN';
|
||||
shown.source = sourceStatusLabel(cohort.source, cohort.sourceStatus);
|
||||
}
|
||||
if (cohort.count === null) unknownCount += 1;
|
||||
for (const item of cohort.nearest) nearest.push({ ...item, cohort });
|
||||
@@ -171,19 +206,22 @@ export function updateContext(info, heading) {
|
||||
angle: `${String(Math.round(Math.abs(relative))).padStart(3, '0')}°`,
|
||||
});
|
||||
}
|
||||
view.uncertainty = unknownCount
|
||||
? tn(
|
||||
unknownCount,
|
||||
'{count} INPUT UNKNOWN · NOT AN ALL-CLEAR',
|
||||
'{count} INPUTS UNKNOWN · NOT AN ALL-CLEAR',
|
||||
)
|
||||
: t('AVAILABLE INPUTS CURRENT · NOT AN ALL-CLEAR');
|
||||
// A feed that is off outranks unknown inputs: the picture is partial.
|
||||
view.uncertainty = partial
|
||||
? partial.title
|
||||
: unknownCount
|
||||
? tn(
|
||||
unknownCount,
|
||||
'{count} INPUT UNKNOWN · NOT AN ALL-CLEAR',
|
||||
'{count} INPUTS UNKNOWN · NOT AN ALL-CLEAR',
|
||||
)
|
||||
: t('AVAILABLE INPUTS CURRENT · NOT AN ALL-CLEAR');
|
||||
view.updated = Number.isFinite(snapshot.evaluatedAt)
|
||||
? new Date(snapshot.evaluatedAt).toISOString().slice(11, 19) + 'Z'
|
||||
: '--:--:--Z';
|
||||
view.state = unknownCount ? 'uncertain' : 'current';
|
||||
view.state = unknownCount || partial ? 'uncertain' : 'current';
|
||||
this.publishContextView();
|
||||
this.updateCockpitSignals(snapshot, unknownCount);
|
||||
this.updateCockpitSignals(snapshot, unknownCount, partial);
|
||||
if (this.contextLayoutStamp !== snapshot.evaluatedAt) {
|
||||
this.contextLayoutStamp = snapshot.evaluatedAt;
|
||||
this.scheduleContextLayout();
|
||||
|
||||
@@ -12,6 +12,13 @@ import {
|
||||
updateContext,
|
||||
} from './cockpitContext.js';
|
||||
import { createContextState } from './cockpitContextState.js';
|
||||
import {
|
||||
dropCockpitSignal,
|
||||
dropContextSnapshotSignals,
|
||||
publishCockpitSignals,
|
||||
pushCockpitSignal,
|
||||
updateCockpitSignals,
|
||||
} from './cockpitSignals.js';
|
||||
import { syncWeatherToggle } from './cockpitInstruments.js';
|
||||
import { setContextCollapsed } from './cockpitLayout.js';
|
||||
import { useCockpitStore } from './stores/cockpit.js';
|
||||
@@ -96,6 +103,13 @@ test('before the controller presents, the card shows the state it starts in', (t
|
||||
),
|
||||
['—', '—', '—', '—'],
|
||||
);
|
||||
// No provider is named before a snapshot reports one.
|
||||
assert.deepEqual(
|
||||
[...document.querySelectorAll('[data-context-cohort] small')].map(
|
||||
(source) => source.textContent,
|
||||
),
|
||||
['—', '—', '—', '—'],
|
||||
);
|
||||
assert.equal(text('#cockpit-context-nearest-label'), 'NO AVAILABLE EXAMPLE');
|
||||
assert.equal(
|
||||
$('#cockpit-context-nearest-label').hasAttribute('aria-label'),
|
||||
@@ -159,6 +173,43 @@ test('a snapshot fills the card and keeps classes other code sets', async (t) =>
|
||||
assert.equal(layouts.length, 1);
|
||||
});
|
||||
|
||||
test('each count names the provider its snapshot reports, with its feed state', async (t) => {
|
||||
const reported = snapshot();
|
||||
reported.cohorts[0].source = 'adsb.lol';
|
||||
reported.cohorts[0].sourceStatus = 'fallback';
|
||||
reported.cohorts[1].source = 'Plane Finder';
|
||||
reported.cohorts.push(
|
||||
{
|
||||
id: 'ais-live-vessels',
|
||||
label: 'AIS vessels',
|
||||
source: 'Datalastic',
|
||||
sourceStatus: 'stale',
|
||||
count: 3,
|
||||
relationship: 'OBSERVED',
|
||||
nearest: [],
|
||||
},
|
||||
{
|
||||
id: 'military-installations',
|
||||
label: 'Mapped installations',
|
||||
source: 'OpenStreetMap',
|
||||
sourceStatus: null,
|
||||
count: 0,
|
||||
relationship: 'MAPPED',
|
||||
nearest: [],
|
||||
},
|
||||
);
|
||||
const { $, owner } = fixture(t, reported);
|
||||
updateContext.call(owner, INFO, 0);
|
||||
await nextTick();
|
||||
const source = (id) => $(`[data-context-cohort="${id}"] small`);
|
||||
assert.equal(source('flights').textContent, 'adsb.lol · FALLBACK');
|
||||
assert.equal(source('military').textContent, 'Plane Finder');
|
||||
assert.equal(source('ais-live-vessels').textContent, 'Datalastic · STALE');
|
||||
assert.equal(source('military-installations').textContent, 'OpenStreetMap');
|
||||
// The tile ellipsizes; the full name stays readable on hover.
|
||||
assert.equal(source('flights').title, 'adsb.lol · FALLBACK');
|
||||
});
|
||||
|
||||
test('a lost contact holds its readout behind the CONTACT LOST cue', async (t) => {
|
||||
const { $, text, owner, layouts } = fixture(t, snapshot());
|
||||
updateContext.call(owner, INFO, 0);
|
||||
@@ -204,6 +255,119 @@ test('without a snapshot the card stands by, hidden', async (t) => {
|
||||
assert.equal(signals.at(-1)[2], 'CONTEXT STANDBY');
|
||||
});
|
||||
|
||||
test('a feed that is off makes the card and Live Signals say the picture is partial', async (t) => {
|
||||
// Every input known, so only the feed that is off can make it partial.
|
||||
const { $, text, owner } = fixture(
|
||||
t,
|
||||
snapshot({
|
||||
cohorts: [
|
||||
{
|
||||
id: 'flights',
|
||||
label: 'Flights',
|
||||
count: 12,
|
||||
relationship: 'OBSERVED',
|
||||
nearest: [{ id: 'N1', distanceM: 4200 }],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
const rebuilt = [];
|
||||
owner.updateCockpitSignals = (...args) => rebuilt.push(args);
|
||||
owner.services.isLayerEnabled = () => true;
|
||||
updateContext.call(owner, INFO, 0);
|
||||
await nextTick();
|
||||
assert.equal($('#cockpit-context').dataset.state, 'current');
|
||||
assert.equal(rebuilt.at(-1)[2], null, 'both feeds on: nothing to add');
|
||||
|
||||
owner.services.isLayerEnabled = (layerId) => layerId !== 'military';
|
||||
updateContext.call(owner, INFO, 0);
|
||||
await nextTick();
|
||||
assert.equal($('#cockpit-context').dataset.state, 'uncertain');
|
||||
assert.equal(
|
||||
text('#cockpit-context-uncertainty'),
|
||||
'MILITARY FEED OFF · PARTIAL PICTURE',
|
||||
);
|
||||
assert.deepEqual(rebuilt.at(-1)[2], {
|
||||
title: 'MILITARY FEED OFF · PARTIAL PICTURE',
|
||||
detail: 'NEARBY AIRCRAFT INCOMPLETE · NOT AN ALL-CLEAR',
|
||||
});
|
||||
});
|
||||
|
||||
test('without Contacts, a feed that is off adds a signal until it is back', async (t) => {
|
||||
const { owner, signals } = fixture(t, null);
|
||||
const dropped = [];
|
||||
owner.dropCockpitSignal = (key) => dropped.push(key);
|
||||
// Riding a military aircraft with Live Flights off.
|
||||
owner.services.isLayerEnabled = (layerId) => layerId === 'military';
|
||||
updateContext.call(owner, { ...INFO, layerId: 'military' }, 0);
|
||||
assert.equal(signals.at(-2)[2], 'CONTEXT STANDBY');
|
||||
assert.deepEqual(signals.at(-1), [
|
||||
'feed-status',
|
||||
'warning',
|
||||
'FLIGHTS FEED OFF · PARTIAL PICTURE',
|
||||
'NEARBY AIRCRAFT INCOMPLETE · NOT AN ALL-CLEAR',
|
||||
]);
|
||||
owner.services.isLayerEnabled = () => true;
|
||||
updateContext.call(owner, { ...INFO, layerId: 'military' }, 0);
|
||||
assert.deepEqual(dropped, ['feed-status']);
|
||||
});
|
||||
|
||||
/** The fixture's owner with the real Live Signals presenters. */
|
||||
function withSignals(owner) {
|
||||
const published = [];
|
||||
Object.assign(owner, {
|
||||
signalItems: [],
|
||||
signalSignatures: new Map(),
|
||||
publishSignals: (rows) => published.push(rows),
|
||||
publishCockpitSignals,
|
||||
pushCockpitSignal,
|
||||
dropCockpitSignal,
|
||||
dropContextSnapshotSignals,
|
||||
updateCockpitSignals,
|
||||
});
|
||||
return () => published.at(-1).map((row) => row.title);
|
||||
}
|
||||
|
||||
test('Contacts going off clears its contact rows and leaves standby', async (t) => {
|
||||
const { owner } = fixture(t, snapshot());
|
||||
const rows = withSignals(owner);
|
||||
owner.services.isLayerEnabled = () => true;
|
||||
updateContext.call(owner, INFO, 0);
|
||||
assert.ok(
|
||||
owner.signalItems.some((item) => item.key.startsWith('flight:')),
|
||||
'Contacts fills the rows',
|
||||
);
|
||||
assert.ok(owner.signalItems.some((item) => item.key === 'input-status'));
|
||||
// Both feeds stay on; only Contacts goes.
|
||||
owner.snapshot = null;
|
||||
updateContext.call(owner, INFO, 0);
|
||||
assert.deepEqual(rows(), ['CONTEXT STANDBY']);
|
||||
updateContext.call(owner, INFO, 0);
|
||||
assert.deepEqual(rows(), ['CONTEXT STANDBY'], 'standby holds still');
|
||||
});
|
||||
|
||||
test('Contacts going off with a feed off keeps the feed row beside standby', async (t) => {
|
||||
const { owner } = fixture(t, snapshot());
|
||||
const rows = withSignals(owner);
|
||||
owner.services.isLayerEnabled = (layerId) => layerId !== 'military';
|
||||
updateContext.call(owner, INFO, 0);
|
||||
owner.snapshot = null;
|
||||
updateContext.call(owner, INFO, 0);
|
||||
assert.deepEqual(rows(), [
|
||||
'MILITARY FEED OFF · PARTIAL PICTURE',
|
||||
'CONTEXT STANDBY',
|
||||
]);
|
||||
});
|
||||
|
||||
test('standby without Contacts keeps the rows the session already shows', async (t) => {
|
||||
const { owner } = fixture(t, null);
|
||||
const rows = withSignals(owner);
|
||||
owner.services.isLayerEnabled = () => true;
|
||||
owner.pushCockpitSignal('track', 'track', 'TRACK ACQUIRED', 'UAL123');
|
||||
updateContext.call(owner, INFO, 0);
|
||||
assert.deepEqual(rows(), ['CONTEXT STANDBY', 'TRACK ACQUIRED']);
|
||||
});
|
||||
|
||||
test('the weather toggle renders its state and the action it offers', async (t) => {
|
||||
const { $, text, owner } = fixture(t);
|
||||
syncWeatherToggle.call(owner, true);
|
||||
|
||||
@@ -25,7 +25,10 @@ export function createContextState() {
|
||||
canPrevious: true,
|
||||
canNext: true,
|
||||
cohorts: Object.fromEntries(
|
||||
COCKPIT_CONTEXT_COHORTS.map((id) => [id, { count: '—', unknown: false }]),
|
||||
COCKPIT_CONTEXT_COHORTS.map((id) => [
|
||||
id,
|
||||
{ count: '—', unknown: false, source: '—' },
|
||||
]),
|
||||
),
|
||||
nearest: { label: t('NO AVAILABLE EXAMPLE'), ariaLabel: null },
|
||||
distance: { text: '—', ariaLabel: null },
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
/** Coordinate Cockpit lifecycle through supplied aircraft, terrain, rendering and briefing operations. */
|
||||
import {
|
||||
readAircraftInfo,
|
||||
readSubjectLayerId,
|
||||
resolveEntryKind,
|
||||
dispatchCockpitModeChanged,
|
||||
toggleTrackedTr3b,
|
||||
syncTr3bToggle,
|
||||
@@ -48,6 +50,8 @@ import {
|
||||
relocalizeBrief,
|
||||
} from './cockpitBriefing.js';
|
||||
import {
|
||||
dropCockpitSignal,
|
||||
dropContextSnapshotSignals,
|
||||
handleSignalClick,
|
||||
publishCockpitSignals,
|
||||
pushCockpitSignal,
|
||||
@@ -60,7 +64,11 @@ import {
|
||||
syncContextLayout,
|
||||
syncSignalLayout,
|
||||
} from './cockpitLayout.js';
|
||||
import { onKeyDown } from './cockpitInput.js';
|
||||
import {
|
||||
onKeyDown,
|
||||
onSceneDoubleClick,
|
||||
routeSceneDoubleClick,
|
||||
} from './cockpitInput.js';
|
||||
import * as Cesium from 'cesium';
|
||||
|
||||
export class CockpitViewController {
|
||||
@@ -75,6 +83,7 @@ export class CockpitViewController {
|
||||
isUtilityDisclosureOpen = null,
|
||||
onEntered = null,
|
||||
onExited = null,
|
||||
onRide = null,
|
||||
restoreTrackingFrame = null,
|
||||
publish = {},
|
||||
} = {},
|
||||
@@ -114,6 +123,7 @@ export class CockpitViewController {
|
||||
this.onCameraTakeover = onCameraTakeover;
|
||||
this.onEntered = onEntered;
|
||||
this.onExited = onExited;
|
||||
this.onRide = onRide;
|
||||
this.restoreTrackingFrame =
|
||||
typeof restoreTrackingFrame === 'function'
|
||||
? restoreTrackingFrame
|
||||
@@ -205,6 +215,13 @@ export class CockpitViewController {
|
||||
}),
|
||||
);
|
||||
this._listen(this.entry, 'click', () => this.enter());
|
||||
// Double-clicking the followed track is a third way in.
|
||||
this._listenerRemovers.push(routeSceneDoubleClick.call(this));
|
||||
// The readout's entry renders inside the Intel HUD, which may mount after
|
||||
// this controller, so its clicks are delegated.
|
||||
this._listen(document, 'click', (event) => {
|
||||
if (event.target?.closest?.('#cockpit-entry-readout')) this.enter();
|
||||
});
|
||||
this._listen(this.tr3bToggle, 'click', () => this.toggleTrackedTr3b());
|
||||
this._listen(this.mapViewButton, 'click', () => this.exit());
|
||||
this._listen(this.visionPrevious, 'click', () => this.cycleVisionMode(-1));
|
||||
@@ -272,6 +289,12 @@ export class CockpitViewController {
|
||||
readAircraftInfo() {
|
||||
return readAircraftInfo.call(this);
|
||||
}
|
||||
readSubjectLayerId() {
|
||||
return readSubjectLayerId.call(this);
|
||||
}
|
||||
resolveEntryKind() {
|
||||
return resolveEntryKind.call(this);
|
||||
}
|
||||
dispatchCockpitModeChanged(active, info) {
|
||||
return dispatchCockpitModeChanged.call(this, active, info);
|
||||
}
|
||||
@@ -371,8 +394,19 @@ export class CockpitViewController {
|
||||
pushCockpitSignal(key, tone, title, detail, target) {
|
||||
return pushCockpitSignal.call(this, key, tone, title, detail, target);
|
||||
}
|
||||
updateCockpitSignals(snapshot, unknownCount) {
|
||||
return updateCockpitSignals.call(this, snapshot, unknownCount);
|
||||
dropCockpitSignal(key) {
|
||||
return dropCockpitSignal.call(this, key);
|
||||
}
|
||||
dropContextSnapshotSignals() {
|
||||
return dropContextSnapshotSignals.call(this);
|
||||
}
|
||||
updateCockpitSignals(snapshot, unknownCount, partialPicture) {
|
||||
return updateCockpitSignals.call(
|
||||
this,
|
||||
snapshot,
|
||||
unknownCount,
|
||||
partialPicture,
|
||||
);
|
||||
}
|
||||
scheduleContextLayout() {
|
||||
return scheduleContextLayout.call(this);
|
||||
@@ -392,6 +426,9 @@ export class CockpitViewController {
|
||||
onKeyDown(event) {
|
||||
return onKeyDown.call(this, event);
|
||||
}
|
||||
onSceneDoubleClick(position) {
|
||||
return onSceneDoubleClick.call(this, position);
|
||||
}
|
||||
|
||||
handleSignalClick(event) {
|
||||
return handleSignalClick.call(this, event);
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { nextTick } from 'vue';
|
||||
import { CockpitViewController, CockpitDisplayPortal } from './cockpit.js';
|
||||
import { cockpitEntryAllowed } from '../contextModePolicy.js';
|
||||
import {
|
||||
COCKPIT_AIRCRAFT_LAYER_IDS,
|
||||
cockpitEntryAllowed,
|
||||
} from '../contextModePolicy.js';
|
||||
import { formatAwarenessLabel } from '../data/militaryAwarenessEngine.js';
|
||||
import { enterCockpitWithTracking } from '../cockpitTracking.js';
|
||||
import { cockpitVisionModeForStyle } from '../cockpitVisionPolicy.js';
|
||||
@@ -72,23 +75,29 @@ export class CockpitCoordinator {
|
||||
fetchRegionalBrief,
|
||||
regionalDistanceM,
|
||||
weatherCodeLabel,
|
||||
// The Contact card and Live Signals say which feeds are off.
|
||||
isLayerEnabled: (layerId) => this._isLayerEnabled(layerId),
|
||||
},
|
||||
onVisionChange: (mode, active, options) =>
|
||||
this._setCockpitVision(mode, active, options),
|
||||
getInitialVisionMode: () => cockpitVisionModeForStyle(this.activeStyle),
|
||||
onCameraTakeover: () =>
|
||||
this._stampNavigation({ cancelPendingSelection: false }),
|
||||
isEntryAllowed: () =>
|
||||
cockpitEntryAllowed({
|
||||
contextMode: this._contextMode,
|
||||
// Only the tracked aircraft's own layer gates entry (see the policy).
|
||||
isEntryAllowed: () => {
|
||||
const subjectLayerId =
|
||||
this.cockpitView?.readAircraftInfo?.()?.layerId ?? null;
|
||||
return cockpitEntryAllowed({
|
||||
subjectLayerId,
|
||||
subjectLayerEnabled: this._isLayerEnabled(subjectLayerId),
|
||||
contextModeChanging: this._contextModeChanging,
|
||||
flightsEnabled: !!this._dataManager?.isEnabled('flights'),
|
||||
militaryEnabled: !!this._dataManager?.isEnabled('military'),
|
||||
}),
|
||||
});
|
||||
},
|
||||
publish: this.publishCockpit,
|
||||
isUtilityDisclosureOpen: () => !!this.readUtilityDisclosureOpen?.(),
|
||||
onEntered: () => this.enterPanels(),
|
||||
onExited: () => this.exitPanels(),
|
||||
onRide: (layerId) => this._adoptRiddenLayer(layerId),
|
||||
restoreTrackingFrame: (entity) => {
|
||||
const [layerId, ...idParts] = String(entity?.gevTrackedId || '').split(
|
||||
':',
|
||||
@@ -115,6 +124,44 @@ export class CockpitCoordinator {
|
||||
get activeStyle() {
|
||||
return this.readActiveStyle();
|
||||
}
|
||||
/** Whether a data layer is enabled; false for no layer. */
|
||||
_isLayerEnabled(layerId) {
|
||||
return Boolean(layerId) && !!this._dataManager?.isEnabled(layerId);
|
||||
}
|
||||
/**
|
||||
* Make the ridden aircraft's layer the user's own while Contacts is on.
|
||||
* Contacts may have turned that layer on, and it releases the layers it
|
||||
* owns when it goes off; the Cockpit must outlive Contacts, so riding an
|
||||
* aircraft adopts its layer as a direct selection does. Contacts then stops
|
||||
* owning it and the Context restore keeps it (session `userAdded`).
|
||||
* @param {string|null} layerId The ridden aircraft's layer.
|
||||
*/
|
||||
_adoptRiddenLayer(layerId) {
|
||||
if (!COCKPIT_AIRCRAFT_LAYER_IDS.includes(layerId)) return;
|
||||
if (!this._isLayerEnabled('military-awareness')) return;
|
||||
this._dataManager?.adoptLayerVisibility?.(layerId, true, {
|
||||
origin: 'user',
|
||||
adoptedFromSelection: true,
|
||||
});
|
||||
}
|
||||
/** Whether either aircraft layer is on, so there is an aircraft to ride. */
|
||||
get _aircraftLayerEnabled() {
|
||||
return COCKPIT_AIRCRAFT_LAYER_IDS.some((layerId) =>
|
||||
this._isLayerEnabled(layerId),
|
||||
);
|
||||
}
|
||||
/**
|
||||
* Why voice entry must refuse before it touches tracking, or null. The
|
||||
* tracked aircraft's own layer is checked again by the entry itself.
|
||||
* @returns {string|null}
|
||||
*/
|
||||
_cockpitEntryRefusal() {
|
||||
if (this._contextModeChanging)
|
||||
return 'Context is still changing — try Cockpit again in a moment';
|
||||
if (!this._aircraftLayerEnabled)
|
||||
return 'No aircraft layer is on — turn on Flights or Military Flights and track an aircraft to enter Cockpit';
|
||||
return null;
|
||||
}
|
||||
getCockpitState() {
|
||||
const { militaryAwarenessLayer } = this.services;
|
||||
const snapshot = militaryAwarenessLayer.getContextSnapshot?.();
|
||||
@@ -129,19 +176,24 @@ export class CockpitCoordinator {
|
||||
const entryAllowed =
|
||||
!active &&
|
||||
Boolean(gateOpen && info && this.viewer?.trackedEntity?.position);
|
||||
// Entry needs only the ridden aircraft's own layer: with one tracked,
|
||||
// that layer; with none, any aircraft layer to track one from.
|
||||
const subjectLayerOff = info
|
||||
? !this._isLayerEnabled(info.layerId)
|
||||
: !this._aircraftLayerEnabled;
|
||||
return {
|
||||
active,
|
||||
entryAllowed,
|
||||
// Why entry is unavailable, so a refusal can be explained rather than
|
||||
// guessed at.
|
||||
// guessed at. Contacts is not required, so it is never the reason.
|
||||
entryBlockedReason:
|
||||
entryAllowed || active
|
||||
? null
|
||||
: !gateOpen
|
||||
? this._contextModeChanging
|
||||
? 'contacts-starting'
|
||||
: 'contacts-inactive'
|
||||
: 'no-tracked-aircraft',
|
||||
: this._contextModeChanging
|
||||
? 'contacts-starting'
|
||||
: subjectLayerOff
|
||||
? 'subject-layer-off'
|
||||
: 'no-tracked-aircraft',
|
||||
visionMode: this.cockpitView?.visionMode || null,
|
||||
subject: info
|
||||
? {
|
||||
@@ -260,17 +312,18 @@ export class CockpitCoordinator {
|
||||
};
|
||||
}
|
||||
if (normalized === 'enter') {
|
||||
// Entry is gated exactly as the manual entry chip is. Attempting it while
|
||||
// the gate is shut produced the half-entered look the operator reported
|
||||
// (a plane anchored under the camera with no cockpit around it), so
|
||||
// refuse with the reason instead of trying.
|
||||
if (!this.cockpitView.isEntryAllowed?.()) {
|
||||
// Attempting entry while the gate is shut produced the half-entered look
|
||||
// the operator reported (a plane anchored under the camera with no
|
||||
// cockpit around it), so refuse with the reason instead of trying. The
|
||||
// aircraft may not be tracked yet (a selection or a requested layer is
|
||||
// adopted below), so this checks what can be known now; the entry
|
||||
// itself then applies the manual chip's gate to the aircraft it rides.
|
||||
const refusal = this._cockpitEntryRefusal();
|
||||
if (refusal) {
|
||||
return {
|
||||
ok: false,
|
||||
action: 'control_cockpit',
|
||||
error: this._contextModeChanging
|
||||
? 'Contacts is still starting up — try Cockpit again in a moment'
|
||||
: 'Contacts must be active to enter Cockpit — say "open contacts" first',
|
||||
error: refusal,
|
||||
state: this.getCockpitState(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,467 @@
|
||||
// src/ui/cockpitEntryGate.test.mjs — first person needs only the layer of
|
||||
// the vehicle it rides: Contacts and the other feeds may be off before or
|
||||
// during a session, turning the ridden layer off ends it, Contacts ending
|
||||
// keeps the ridden layer it had turned on, and the voice gate and state say
|
||||
// so without claiming Contacts is required. Over happy-dom.
|
||||
import '../testSupport/registerDom.mjs';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createPinia } from 'pinia';
|
||||
import { createApp, defineComponent, h, nextTick } from 'vue';
|
||||
import { DataLayerManager } from '../data/manager.js';
|
||||
import { createDependencies } from '../layers/awareness/dependencies.js';
|
||||
import { CockpitCoordinator } from './cockpitCoordinator.js';
|
||||
import { ContextControls } from './contextControls.js';
|
||||
import { _handleContextLayerChange } from './contextLayerChanges.js';
|
||||
import { useCockpitStore } from './stores/cockpit.js';
|
||||
import { useHudStore } from './stores/hud.js';
|
||||
import ContextView from './views/ContextView.vue';
|
||||
import IntelHudView from './views/IntelHudView.vue';
|
||||
|
||||
const CIVIL = Object.freeze({
|
||||
icao24: 'abc123',
|
||||
callsign: 'UAL123',
|
||||
track: 92,
|
||||
latitude: 30,
|
||||
longitude: -97,
|
||||
});
|
||||
const MILITARY = Object.freeze({
|
||||
...CIVIL,
|
||||
icao24: 'ae0001',
|
||||
callsign: 'RCH1',
|
||||
});
|
||||
|
||||
function fixture(
|
||||
t,
|
||||
{
|
||||
enabled = [],
|
||||
tracked = null,
|
||||
contextMode = null,
|
||||
changing = false,
|
||||
dataManager: suppliedManager = null,
|
||||
readContext = null,
|
||||
} = {},
|
||||
) {
|
||||
document.body.replaceChildren();
|
||||
const host = document.body.appendChild(document.createElement('div'));
|
||||
const pinia = createPinia();
|
||||
const app = createApp(
|
||||
defineComponent(() => () => [h(ContextView), h(IntelHudView)]),
|
||||
).use(pinia);
|
||||
app.mount(host);
|
||||
const store = useCockpitStore(pinia);
|
||||
const layers = new Set(enabled);
|
||||
const dataManager = suppliedManager || {
|
||||
isEnabled: (layerId) => layers.has(layerId),
|
||||
};
|
||||
// A layer that is off has no tracked aircraft, as the flight layers clear
|
||||
// tracking on disable.
|
||||
const trackedFrom = (layerId) => () =>
|
||||
tracked?.layerId === layerId && dataManager.isEnabled(layerId)
|
||||
? tracked.info
|
||||
: null;
|
||||
const entityFor = (subject) => ({
|
||||
position: { getValue: () => null },
|
||||
show: true,
|
||||
gevTrackedId: subject ? `${subject.layerId}:${subject.info.icao24}` : '',
|
||||
});
|
||||
const entities = new Set();
|
||||
const entity = entityFor(tracked);
|
||||
entities.add(entity);
|
||||
const listeners = () => ({ addEventListener: () => () => {} });
|
||||
const viewer = {
|
||||
trackedEntity: tracked ? entity : undefined,
|
||||
clock: { currentTime: null },
|
||||
camera: { cancelFlight() {}, frustum: { fov: 1, aspectRatio: 1 } },
|
||||
entities: { contains: (candidate) => entities.has(candidate) },
|
||||
scene: {
|
||||
preUpdate: listeners(),
|
||||
screenSpaceCameraController: { enableInputs: true },
|
||||
},
|
||||
trackedEntityChanged: listeners(),
|
||||
};
|
||||
const context = { mode: contextMode, changing };
|
||||
const coordinator = new CockpitCoordinator({
|
||||
viewer,
|
||||
services: {
|
||||
flightsLayer: { getTrackedInfo: trackedFrom('flights') },
|
||||
militaryFlightsLayer: { getTrackedInfo: trackedFrom('military') },
|
||||
militaryAwarenessLayer: { getContextSnapshot: () => null },
|
||||
isTr3b: () => false,
|
||||
holdContinuousRender() {},
|
||||
releaseContinuousRender() {},
|
||||
},
|
||||
elements: {},
|
||||
operations: {
|
||||
publishCockpit: { presence: (view) => store.publishPresence(view) },
|
||||
_stampNavigation() {},
|
||||
getAircraftTrackingTarget: () =>
|
||||
tracked ? { layerId: tracked.layerId, id: tracked.info.icao24 } : null,
|
||||
},
|
||||
readDataManager: () => dataManager,
|
||||
readContext: readContext || (() => context),
|
||||
readActiveStyle: () => 'normal',
|
||||
readUtilityDisclosureOpen: () => false,
|
||||
enterPanels() {},
|
||||
exitPanels() {},
|
||||
});
|
||||
const cockpit = coordinator.cockpitView;
|
||||
// The HUD, briefing and signals have their own tests.
|
||||
Object.assign(cockpit, {
|
||||
updateHud() {},
|
||||
setVisionMode() {},
|
||||
showBriefPage() {},
|
||||
startBriefRotation() {},
|
||||
stopBriefRotation() {},
|
||||
pushCockpitSignal() {},
|
||||
scheduleContextLayout() {},
|
||||
clearPredictiveRoute() {},
|
||||
});
|
||||
t.after(() => {
|
||||
coordinator.stop();
|
||||
app.unmount();
|
||||
document.body.classList.remove('cockpit-mode');
|
||||
});
|
||||
/** Turn a layer off and tell the Context owner, as the data manager does. */
|
||||
const disable = (layerId) => {
|
||||
layers.delete(layerId);
|
||||
_handleContextLayerChange.call(
|
||||
{
|
||||
cockpitView: cockpit,
|
||||
_dataManager: dataManager,
|
||||
_contextMode: null,
|
||||
_contextModeChanging: false,
|
||||
_contextSessionSnapshot: null,
|
||||
_contextRestoreState: null,
|
||||
_syncContextModeButtons() {},
|
||||
},
|
||||
{ type: 'visibility', layerId, enabled: false, origin: 'user' },
|
||||
);
|
||||
};
|
||||
/** Track another aircraft, as Contacts navigation does mid-session. */
|
||||
const retrack = (subject) => {
|
||||
tracked = subject;
|
||||
viewer.trackedEntity = entityFor(subject);
|
||||
entities.add(viewer.trackedEntity);
|
||||
};
|
||||
const $ = (selector) => document.querySelector(selector);
|
||||
return { $, coordinator, cockpit, store, layers, disable, retrack, pinia };
|
||||
}
|
||||
|
||||
test('a civilian aircraft enters with Live Flights alone: no Contacts, no Military', (t) => {
|
||||
const { coordinator, cockpit } = fixture(t, {
|
||||
enabled: ['flights'],
|
||||
tracked: { layerId: 'flights', info: CIVIL },
|
||||
});
|
||||
const state = coordinator.getCockpitState();
|
||||
assert.equal(state.entryAllowed, true);
|
||||
assert.equal(state.entryBlockedReason, null);
|
||||
assert.equal(cockpit.enter(), true);
|
||||
});
|
||||
|
||||
test('a military aircraft enters with Military Flights alone', (t) => {
|
||||
const { coordinator, cockpit } = fixture(t, {
|
||||
enabled: ['military'],
|
||||
tracked: { layerId: 'military', info: MILITARY },
|
||||
});
|
||||
assert.equal(coordinator.getCockpitState().entryAllowed, true);
|
||||
assert.equal(cockpit.enter(), true);
|
||||
});
|
||||
|
||||
test('a Context change in flight still blocks entry, and says so', (t) => {
|
||||
const { coordinator, cockpit } = fixture(t, {
|
||||
enabled: ['flights', 'military'],
|
||||
tracked: { layerId: 'flights', info: CIVIL },
|
||||
contextMode: 'flights',
|
||||
changing: true,
|
||||
});
|
||||
const state = coordinator.getCockpitState();
|
||||
assert.equal(state.entryAllowed, false);
|
||||
assert.equal(state.entryBlockedReason, 'contacts-starting');
|
||||
assert.equal(cockpit.enter(), false);
|
||||
const voice = coordinator.controlCockpit('enter');
|
||||
assert.equal(voice.ok, false);
|
||||
assert.match(voice.error, /Context is still changing/);
|
||||
assert.equal(cockpit.active, false);
|
||||
});
|
||||
|
||||
test('with no aircraft layer on, entry is refused for that reason, never for Contacts', (t) => {
|
||||
const { coordinator, cockpit } = fixture(t);
|
||||
const state = coordinator.getCockpitState();
|
||||
assert.equal(state.entryBlockedReason, 'subject-layer-off');
|
||||
const voice = coordinator.controlCockpit('enter');
|
||||
assert.equal(voice.ok, false);
|
||||
assert.match(voice.error, /No aircraft layer is on/);
|
||||
assert.doesNotMatch(voice.error, /contacts/i);
|
||||
assert.equal(voice.state.entryBlockedReason, 'subject-layer-off');
|
||||
assert.equal(cockpit.active, false);
|
||||
});
|
||||
|
||||
test('with an aircraft layer on but nothing tracked, the reason is the missing aircraft', (t) => {
|
||||
const { coordinator } = fixture(t, { enabled: ['military'] });
|
||||
assert.equal(
|
||||
coordinator.getCockpitState().entryBlockedReason,
|
||||
'no-tracked-aircraft',
|
||||
);
|
||||
});
|
||||
|
||||
test('voice enters without Contacts when the ridden layer is on', (t) => {
|
||||
const { coordinator, cockpit } = fixture(t, {
|
||||
enabled: ['flights'],
|
||||
tracked: { layerId: 'flights', info: CIVIL },
|
||||
});
|
||||
const result = coordinator.controlCockpit('enter');
|
||||
assert.equal(result.ok, true, result.error);
|
||||
assert.equal(cockpit.active, true);
|
||||
});
|
||||
|
||||
test('other layers may be turned off during a session; the ridden layer ends it', (t) => {
|
||||
const { cockpit, disable } = fixture(t, {
|
||||
enabled: ['flights', 'military', 'ais-live-vessels'],
|
||||
tracked: { layerId: 'flights', info: CIVIL },
|
||||
});
|
||||
assert.equal(cockpit.enter(), true);
|
||||
disable('military');
|
||||
disable('ais-live-vessels');
|
||||
assert.equal(cockpit.active, true, 'other feeds are free to go off');
|
||||
disable('flights');
|
||||
assert.equal(cockpit.active, false, 'the ridden layer going off ends it');
|
||||
});
|
||||
|
||||
test('the readout offers the same entry, labelled by kind, and enters on click', async (t) => {
|
||||
const { $, cockpit, pinia } = fixture(t, {
|
||||
enabled: ['flights'],
|
||||
tracked: { layerId: 'flights', info: CIVIL },
|
||||
});
|
||||
useHudStore(pinia);
|
||||
const readoutEntry = $('#cockpit-entry-readout');
|
||||
assert.equal(readoutEntry.hidden, true, 'hidden until entry is available');
|
||||
cockpit.syncEntry();
|
||||
await nextTick();
|
||||
assert.equal(readoutEntry.hidden, false);
|
||||
assert.match(readoutEntry.textContent, /flight/);
|
||||
assert.match(readoutEntry.textContent, /COCKPIT/);
|
||||
assert.equal(
|
||||
$('#cockpit-entry').hidden,
|
||||
false,
|
||||
'the Contacts entry follows the same presence',
|
||||
);
|
||||
readoutEntry.click();
|
||||
await nextTick();
|
||||
assert.equal(cockpit.active, true);
|
||||
assert.equal(readoutEntry.hidden, true, 'inside, there is nothing to enter');
|
||||
});
|
||||
|
||||
const AIR_AND_SEA = [
|
||||
'flights',
|
||||
'military',
|
||||
'ais-live-vessels',
|
||||
'military-installations',
|
||||
];
|
||||
|
||||
/** A source layer that settles at once, as the data manager drives it. */
|
||||
function sourceLayer(id) {
|
||||
return {
|
||||
id,
|
||||
name: id,
|
||||
icon: '',
|
||||
source: 'test',
|
||||
updateInterval: -1,
|
||||
init() {},
|
||||
enable() {},
|
||||
disable() {},
|
||||
update() {},
|
||||
getStats: () => ({ count: 0, lastUpdate: null }),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Contacts as the manager sees it: a coordinator whose real dependency
|
||||
* ownership (src/layers/awareness/dependencies.js) turns on the air and sea
|
||||
* layers it finds off and releases them when it goes off.
|
||||
*/
|
||||
function contactsCoordinator() {
|
||||
const state = {
|
||||
dataManager: null,
|
||||
enabled: false,
|
||||
passive: true,
|
||||
activationId: 0,
|
||||
ownedDependencies: new Set(),
|
||||
subject: null,
|
||||
autoFocusRetryPending: false,
|
||||
};
|
||||
const dependencies = createDependencies({
|
||||
state,
|
||||
services: {},
|
||||
parts: { subject: {}, focus: {} },
|
||||
source: null,
|
||||
});
|
||||
return {
|
||||
id: 'military-awareness',
|
||||
name: 'Contacts',
|
||||
icon: '',
|
||||
source: 'test',
|
||||
showInTogglePanel: false,
|
||||
updateInterval: -1,
|
||||
attachDataManager(dataManager) {
|
||||
state.dataManager = dataManager;
|
||||
dependencies.watchAdoptions(dataManager);
|
||||
},
|
||||
setParams(params = {}) {
|
||||
if (typeof params.passive === 'boolean') state.passive = params.passive;
|
||||
},
|
||||
getParams: () => ({ passive: state.passive }),
|
||||
init() {},
|
||||
enable() {
|
||||
state.enabled = true;
|
||||
if (!state.passive) return dependencies.enableDependencies();
|
||||
return true;
|
||||
},
|
||||
disable() {
|
||||
state.enabled = false;
|
||||
state.passive = true;
|
||||
return dependencies.releaseOwnedDependencies(++state.activationId);
|
||||
},
|
||||
update() {},
|
||||
getStats: () => ({ count: 0, lastUpdate: null }),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The Cockpit beside the real Context owner and data manager, so a Contacts
|
||||
* exit runs its whole restore: the coordinator's releases, then the snapshot.
|
||||
*/
|
||||
async function liveFixture(t, { enabled = [], tracked = null } = {}) {
|
||||
const manager = new DataLayerManager({});
|
||||
for (const layerId of AIR_AND_SEA) manager.register(sourceLayer(layerId));
|
||||
const coordinatorModule = contactsCoordinator();
|
||||
manager.register(coordinatorModule);
|
||||
coordinatorModule.attachDataManager(manager);
|
||||
for (const layerId of enabled) await manager.setEnabled(layerId, true);
|
||||
let cockpit = null;
|
||||
const controls = new ContextControls({
|
||||
elements: {},
|
||||
installations: {},
|
||||
actions: {
|
||||
getCockpit: () => cockpit,
|
||||
claimVisualAuthority() {},
|
||||
showToast() {},
|
||||
setClearBusy() {},
|
||||
syncDetection() {},
|
||||
scheduleLayout() {},
|
||||
refreshRadio() {},
|
||||
setPanelCollapsed() {},
|
||||
},
|
||||
});
|
||||
controls.connect(manager);
|
||||
t.after(() => {
|
||||
controls.stop();
|
||||
controls.disconnect();
|
||||
});
|
||||
const base = fixture(t, {
|
||||
tracked,
|
||||
dataManager: manager,
|
||||
readContext: () => controls.getContextModeState(),
|
||||
});
|
||||
cockpit = base.cockpit;
|
||||
/** Let every Context reaction the last change started settle. */
|
||||
const settle = async () => {
|
||||
for (let turn = 0; turn < 5; turn += 1) {
|
||||
await controls._waitForContextLayerSettlement();
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
}
|
||||
};
|
||||
return { ...base, manager, controls, settle };
|
||||
}
|
||||
|
||||
const on = (manager) =>
|
||||
[...AIR_AND_SEA, 'military-awareness'].filter((layerId) =>
|
||||
manager.isEnabled(layerId),
|
||||
);
|
||||
|
||||
test('Contacts ending in a Cockpit session keeps the ridden layer it had turned on', async (t) => {
|
||||
for (const [label, endContacts] of [
|
||||
[
|
||||
'Military Flights off',
|
||||
({ manager }) =>
|
||||
manager.setEnabled('military', false, { origin: 'user' }),
|
||||
],
|
||||
[
|
||||
'Contacts off by its own layer',
|
||||
({ manager }) =>
|
||||
manager.setEnabled('military-awareness', false, { origin: 'user' }),
|
||||
],
|
||||
[
|
||||
'Contacts off from its chooser',
|
||||
({ controls }) => controls._selectContextMode(null),
|
||||
],
|
||||
]) {
|
||||
await t.test(label, async (t) => {
|
||||
// Live Flights is off on the map; Contacts turns it on as its own.
|
||||
const live = await liveFixture(t, {
|
||||
tracked: { layerId: 'flights', info: CIVIL },
|
||||
});
|
||||
const { manager, controls, cockpit, settle } = live;
|
||||
assert.equal(await controls._selectContextMode('flights'), true);
|
||||
await settle();
|
||||
assert.deepEqual(on(manager), [...AIR_AND_SEA, 'military-awareness']);
|
||||
assert.equal(cockpit.enter(), true);
|
||||
await endContacts(live);
|
||||
await settle();
|
||||
assert.equal(controls.getContextModeState().mode, null, 'Contacts ended');
|
||||
assert.equal(cockpit.active, true, 'the Cockpit rides on');
|
||||
assert.deepEqual(
|
||||
on(manager),
|
||||
['flights'],
|
||||
'only the ridden layer outlives the pre-Contacts restore',
|
||||
);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test('a ride handed to an aircraft on a layer Contacts turned on keeps that layer', async (t) => {
|
||||
const live = await liveFixture(t, {
|
||||
enabled: ['flights'],
|
||||
tracked: { layerId: 'flights', info: CIVIL },
|
||||
});
|
||||
const { manager, controls, cockpit, retrack, settle } = live;
|
||||
assert.equal(await controls._selectContextMode('flights'), true);
|
||||
await settle();
|
||||
assert.equal(cockpit.enter(), true);
|
||||
// NEXT hands the view to a military aircraft; Contacts turned its layer on.
|
||||
retrack({ layerId: 'military', info: MILITARY });
|
||||
assert.equal(cockpit._adoptTrackedEntity(performance.now()), true);
|
||||
assert.equal(cockpit.readSubjectLayerId(), 'military');
|
||||
await manager.setEnabled('ais-live-vessels', false, { origin: 'user' });
|
||||
await settle();
|
||||
assert.equal(controls.getContextModeState().mode, null);
|
||||
assert.equal(cockpit.active, true);
|
||||
assert.deepEqual(on(manager), ['flights', 'military']);
|
||||
});
|
||||
|
||||
test('the ridden layer still ends the Cockpit while Contacts is on', async (t) => {
|
||||
const live = await liveFixture(t, {
|
||||
tracked: { layerId: 'flights', info: CIVIL },
|
||||
});
|
||||
const { manager, controls, cockpit, settle } = live;
|
||||
assert.equal(await controls._selectContextMode('flights'), true);
|
||||
await settle();
|
||||
assert.equal(cockpit.enter(), true);
|
||||
await manager.setEnabled('flights', false, { origin: 'user' });
|
||||
await settle();
|
||||
assert.equal(cockpit.active, false);
|
||||
assert.equal(manager.isEnabled('flights'), false);
|
||||
});
|
||||
|
||||
test('without a Cockpit, ending Contacts restores the layers it found', async (t) => {
|
||||
const live = await liveFixture(t, {
|
||||
tracked: { layerId: 'flights', info: CIVIL },
|
||||
});
|
||||
const { manager, controls, settle } = live;
|
||||
assert.equal(await controls._selectContextMode('flights'), true);
|
||||
await settle();
|
||||
await manager.setEnabled('military', false, { origin: 'user' });
|
||||
await settle();
|
||||
assert.equal(controls.getContextModeState().mode, null);
|
||||
assert.deepEqual(on(manager), [], 'Live Flights goes back off');
|
||||
});
|
||||
@@ -1,5 +1,99 @@
|
||||
/** Route Cockpit keys while preserving the active disclosure and form-control owner. */
|
||||
import * as Cesium from 'cesium';
|
||||
import { isPointerFree } from '../data/inputOwnership.js';
|
||||
|
||||
/** How far from the followed track a double-click may land, CSS pixels. */
|
||||
export const SUBJECT_DOUBLE_CLICK_RADIUS_PX = 32;
|
||||
|
||||
/**
|
||||
* Whether a double-click landed on the followed track's mark.
|
||||
* @param {{x: number, y: number}|null} click Canvas position of the click.
|
||||
* @param {{x: number, y: number}|null|undefined} subject Canvas position of
|
||||
* the track, or nothing when it is off screen.
|
||||
* @param {number} [radiusPx]
|
||||
*/
|
||||
export function doubleClickHitsSubject(
|
||||
click,
|
||||
subject,
|
||||
radiusPx = SUBJECT_DOUBLE_CLICK_RADIUS_PX,
|
||||
) {
|
||||
if (!click || !subject) return false;
|
||||
const distance = Math.hypot(click.x - subject.x, click.y - subject.y);
|
||||
return Number.isFinite(distance) && distance <= radiusPx;
|
||||
}
|
||||
|
||||
/** Where the track `kind` would ride is drawn now, as a world position. */
|
||||
function subjectWorldPosition(kind) {
|
||||
if (kind !== 'aircraft') return null;
|
||||
return (
|
||||
this.viewer.trackedEntity?.position?.getValue?.(
|
||||
this.viewer.clock?.currentTime,
|
||||
) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
/** The followed track's canvas position now, or null off screen. */
|
||||
function subjectCanvasPosition() {
|
||||
const kind = this.resolveEntryKind();
|
||||
const world = kind ? subjectWorldPosition.call(this, kind) : null;
|
||||
const scene = this.viewer.scene;
|
||||
if (!world || typeof scene?.cartesianToCanvasCoordinates !== 'function')
|
||||
return null;
|
||||
return (
|
||||
scene.cartesianToCanvasCoordinates(world, new Cesium.Cartesian2()) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Enter first person when the followed track itself is double-clicked: the
|
||||
* same entry, and the same gates, as C and the entry buttons. A
|
||||
* double-click anywhere else, or one a tool owns (drawing ends a shape with
|
||||
* one), is left alone.
|
||||
* @param {{x: number, y: number}|null|undefined} position Canvas position.
|
||||
* @returns {boolean} True when it landed on the followed track, entered or
|
||||
* refused by the gate: the caller does nothing else with it.
|
||||
*/
|
||||
export function onSceneDoubleClick(position) {
|
||||
if (this.active || this.destroyed || !isPointerFree()) return false;
|
||||
if (!Number.isFinite(position?.x) || !Number.isFinite(position?.y))
|
||||
return false;
|
||||
if (!doubleClickHitsSubject(position, subjectCanvasPosition.call(this)))
|
||||
return false;
|
||||
this.enter();
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Take the scene's double-click through the Cockpit first. Cesium's Viewer
|
||||
* installs its own (pickAndTrackObject), which untracks whenever the pick is
|
||||
* not an Entity: on a followed aircraft's model, a primitive, it would drop
|
||||
* the very track the double-click means to ride. A double-click on the
|
||||
* followed track is the Cockpit's; any other goes on to Cesium's.
|
||||
* @returns {() => void} Puts Cesium's handler back, unless another owner
|
||||
* (the draw tool borrows it) has replaced ours since.
|
||||
*/
|
||||
export function routeSceneDoubleClick() {
|
||||
const handler = this.viewer.screenSpaceEventHandler;
|
||||
if (typeof handler?.setInputAction !== 'function') return () => {};
|
||||
const type = Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK;
|
||||
const stock = handler.getInputAction?.(type) ?? null;
|
||||
const routed = (event) => {
|
||||
if (this.onSceneDoubleClick(event?.position)) return;
|
||||
stock?.(event);
|
||||
};
|
||||
handler.setInputAction(routed, type);
|
||||
return () => {
|
||||
if (handler.isDestroyed?.() || handler.getInputAction?.(type) !== routed)
|
||||
return;
|
||||
if (stock) handler.setInputAction(stock, type);
|
||||
else handler.removeInputAction(type);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The Cockpit's capture-phase keydown: Escape and C.
|
||||
* @param {KeyboardEvent} event
|
||||
*/
|
||||
export function onKeyDown(event) {
|
||||
if (this.destroyed) return false;
|
||||
if (event.repeat || event.isComposing) return;
|
||||
|
||||
@@ -144,3 +144,21 @@ export function formatCockpitWindDirection(value) {
|
||||
const degrees = roundHeadingDegrees(value);
|
||||
return `${compassPointLabel(labels[Math.round(normalized / 45) % labels.length])} · ${degrees}°`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Cockpit entry for each subject it can ride: an aircraft's cockpit.
|
||||
* Both entry buttons (Contacts and the Intel HUD readout) show it.
|
||||
*/
|
||||
const COCKPIT_ENTRY_FACES = Object.freeze({
|
||||
aircraft: Object.freeze({ icon: 'flight', label: msg('COCKPIT') }),
|
||||
});
|
||||
|
||||
/**
|
||||
* The entry's glyph and localized label for the subject it would ride.
|
||||
* @param {'aircraft'|null|undefined} kind
|
||||
* @returns {{icon: string, label: string}}
|
||||
*/
|
||||
export function cockpitEntryFace(kind) {
|
||||
const face = COCKPIT_ENTRY_FACES[kind] ?? COCKPIT_ENTRY_FACES.aircraft;
|
||||
return { icon: face.icon, label: t(face.label) };
|
||||
}
|
||||
+75
-11
@@ -62,7 +62,52 @@ export function pushCockpitSignal(key, tone, title, detail, target = null) {
|
||||
this.publishCockpitSignals();
|
||||
}
|
||||
|
||||
export function updateCockpitSignals(snapshot, unknownCount) {
|
||||
/**
|
||||
* Take a status row off the list, as when the feed it warned about is back.
|
||||
* @param {string} key The row's key.
|
||||
*/
|
||||
export function dropCockpitSignal(key) {
|
||||
this.signalSignatures.delete(key);
|
||||
const kept = this.signalItems.filter((item) => item.key !== key);
|
||||
if (kept.length === this.signalItems.length) return;
|
||||
this.signalItems = kept;
|
||||
this.publishCockpitSignals();
|
||||
}
|
||||
|
||||
/** Whether a row is one a Contacts snapshot builds, with its status rows. */
|
||||
const isContextSnapshotRow = (key) =>
|
||||
key.startsWith('flight:') ||
|
||||
['input-status', 'feed-status', 'context-status'].includes(key);
|
||||
|
||||
/**
|
||||
* Take off every row a Contacts snapshot built, as when Contacts goes off:
|
||||
* its contacts, distances and CURRENT would otherwise read as live. Rows the
|
||||
* session made without Contacts, such as TRACK ACQUIRED, stay.
|
||||
*/
|
||||
export function dropContextSnapshotSignals() {
|
||||
for (const key of [...this.signalSignatures.keys()])
|
||||
if (isContextSnapshotRow(key)) this.signalSignatures.delete(key);
|
||||
const kept = this.signalItems.filter(
|
||||
(item) => !isContextSnapshotRow(item.key),
|
||||
);
|
||||
if (kept.length === this.signalItems.length) return;
|
||||
this.signalItems = kept;
|
||||
this.publishCockpitSignals();
|
||||
}
|
||||
|
||||
/**
|
||||
* Rebuild the rows from a Contacts snapshot: the nearest flights, a row for
|
||||
* unknown inputs and, first, a row naming an air feed that is off.
|
||||
* @param {object} snapshot `militaryAwareness.getContextSnapshot()` result.
|
||||
* @param {number} unknownCount Cohorts whose count is unknown.
|
||||
* @param {?{title: string, detail: string}} [partialPicture] The feed-off
|
||||
* row (see `readPartialPicture`), or null with every air feed on.
|
||||
*/
|
||||
export function updateCockpitSignals(
|
||||
snapshot,
|
||||
unknownCount,
|
||||
partialPicture = null,
|
||||
) {
|
||||
const previous = new Map(this.signalItems.map((item) => [item.key, item]));
|
||||
const contacts = [];
|
||||
const subject = snapshot.subject;
|
||||
@@ -110,7 +155,9 @@ export function updateCockpitSignals(snapshot, unknownCount) {
|
||||
}
|
||||
}
|
||||
contacts.sort((a, b) => a.distanceM - b.distanceM);
|
||||
const nextItems = contacts.slice(0, 5).map((item) => ({
|
||||
// A feed-off row leads, so the list never reads as the whole picture.
|
||||
const reserved = partialPicture ? 1 : 0;
|
||||
const nextItems = contacts.slice(0, 5 - reserved).map((item) => ({
|
||||
...item,
|
||||
timestamp:
|
||||
previous.get(item.key)?.timestamp || snapshot.evaluatedAt || Date.now(),
|
||||
@@ -120,18 +167,35 @@ export function updateCockpitSignals(snapshot, unknownCount) {
|
||||
.filter((cohort) => cohort.count === null)
|
||||
.map((cohort) => cohort.source)
|
||||
.join(' · ');
|
||||
nextItems.splice(4, Math.max(0, nextItems.length - 4), {
|
||||
key: 'input-status',
|
||||
nextItems.splice(
|
||||
4 - reserved,
|
||||
Math.max(0, nextItems.length - 4 + reserved),
|
||||
{
|
||||
key: 'input-status',
|
||||
tone: 'warning',
|
||||
title: tn(
|
||||
unknownCount,
|
||||
'{count} INPUT UNKNOWN',
|
||||
'{count} INPUTS UNKNOWN',
|
||||
),
|
||||
detail: sources || t('SOURCE STATUS UNAVAILABLE'),
|
||||
target: null,
|
||||
timestamp:
|
||||
previous.get('input-status')?.timestamp ||
|
||||
snapshot.evaluatedAt ||
|
||||
Date.now(),
|
||||
},
|
||||
);
|
||||
}
|
||||
if (partialPicture) {
|
||||
nextItems.unshift({
|
||||
key: 'feed-status',
|
||||
tone: 'warning',
|
||||
title: tn(
|
||||
unknownCount,
|
||||
'{count} INPUT UNKNOWN',
|
||||
'{count} INPUTS UNKNOWN',
|
||||
),
|
||||
detail: sources || t('SOURCE STATUS UNAVAILABLE'),
|
||||
title: partialPicture.title,
|
||||
detail: partialPicture.detail,
|
||||
target: null,
|
||||
timestamp:
|
||||
previous.get('input-status')?.timestamp ||
|
||||
previous.get('feed-status')?.timestamp ||
|
||||
snapshot.evaluatedAt ||
|
||||
Date.now(),
|
||||
});
|
||||
|
||||
@@ -17,6 +17,30 @@ export function readAircraftInfo() {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The layer the active view rides: the aircraft's own layer. It is read from
|
||||
* the tracked entity's id once the layer has dropped its tracking, so a layer
|
||||
* turned off still names itself.
|
||||
* @returns {'flights'|'military'|null}
|
||||
*/
|
||||
export function readSubjectLayerId() {
|
||||
if (!this.active) return null;
|
||||
const layerId = this.readAircraftInfo()?.layerId;
|
||||
if (layerId) return layerId;
|
||||
const [prefix] = String(this.trackedEntity?.gevTrackedId || '').split(':');
|
||||
return ['flights', 'military'].includes(prefix) ? prefix : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The subject entry would take: a Cesium-tracked aircraft.
|
||||
* @returns {'aircraft'|null}
|
||||
*/
|
||||
export function resolveEntryKind() {
|
||||
return this.readAircraftInfo() && this.viewer.trackedEntity?.position
|
||||
? 'aircraft'
|
||||
: null;
|
||||
}
|
||||
|
||||
export function dispatchCockpitModeChanged(active, info = null) {
|
||||
const subjectId = active
|
||||
? String(info?.icao24 || '')
|
||||
@@ -131,6 +155,7 @@ export function _adoptTrackedEntity(nowMs, suppliedInfo = null) {
|
||||
this.lastContextUpdateMs = 0;
|
||||
this.lastCameraUpdateMs = 0;
|
||||
this.contextNavigationDeadlineMs = 0;
|
||||
this.onRide?.(info.layerId);
|
||||
this.dispatchCockpitModeChanged(true, info);
|
||||
return true;
|
||||
}
|
||||
@@ -206,6 +231,7 @@ export function enter() {
|
||||
this.mapViewButton?.focus({ preventScroll: true });
|
||||
});
|
||||
this.onEntered?.();
|
||||
this.onRide?.(info.layerId);
|
||||
this.dispatchCockpitModeChanged(true, info);
|
||||
return true;
|
||||
}
|
||||
@@ -247,9 +273,12 @@ export function exit({ restoreTracking = true } = {}) {
|
||||
this.restoreTrackingFrame(entity);
|
||||
}
|
||||
this.syncEntry();
|
||||
// Back to whichever entry was used: the Contacts button or the readout's.
|
||||
const readoutEntry = document.getElementById('cockpit-entry-readout');
|
||||
const restoreTarget =
|
||||
this.entryFocusOrigin === this.entry
|
||||
? this.entry
|
||||
this.entryFocusOrigin === this.entry ||
|
||||
(readoutEntry && this.entryFocusOrigin === readoutEntry)
|
||||
? this.entryFocusOrigin
|
||||
: this.entry || this.entryFocusOrigin;
|
||||
this.entryFocusOrigin = null;
|
||||
// The entry shows when Vue flushes the presence; read it after.
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { t, translateKnown } from '../i18n/index.js';
|
||||
import {
|
||||
SPACE_MISSIONS_LAYER_BLOCK_REASON,
|
||||
cockpitEntryAllowed,
|
||||
isExplicitUserIntentOrigin,
|
||||
parseContextLayerBlockReason,
|
||||
recordContextRestoreExplicitChange,
|
||||
@@ -245,15 +244,12 @@ export function _handleContextLayerChange(change) {
|
||||
);
|
||||
}
|
||||
}
|
||||
if (
|
||||
this.cockpitView?.active &&
|
||||
!cockpitEntryAllowed({
|
||||
contextMode: this._contextMode,
|
||||
contextModeChanging: this._contextModeChanging,
|
||||
flightsEnabled: !!this._dataManager?.isEnabled('flights'),
|
||||
militaryEnabled: !!this._dataManager?.isEnabled('military'),
|
||||
})
|
||||
) {
|
||||
// Turning off the layer the view rides ends it; every other layer may be
|
||||
// turned on or off freely during a session.
|
||||
const riddenLayerId = this.cockpitView?.active
|
||||
? this.cockpitView.readSubjectLayerId?.()
|
||||
: null;
|
||||
if (riddenLayerId && !this._dataManager?.isEnabled(riddenLayerId)) {
|
||||
this.cockpitView.exit({ restoreTracking: false });
|
||||
}
|
||||
this._syncContextModeButtons();
|
||||
|
||||
@@ -18,7 +18,10 @@ export async function _selectContextMode(
|
||||
this._contextModeChanging = true;
|
||||
this._syncContextModeButtons();
|
||||
try {
|
||||
if (mode !== 'flights' && this.cockpitView?.active) {
|
||||
// Cockpit does not need Contacts, so leaving it keeps the view; the
|
||||
// restore below ends it only by turning off the layer it rides. Another
|
||||
// mode takes the camera, so switching to one ends it.
|
||||
if (mode && mode !== 'flights' && this.cockpitView?.active) {
|
||||
this.cockpitView.exit({ restoreTracking: false });
|
||||
}
|
||||
if (!mode) {
|
||||
@@ -220,8 +223,8 @@ export async function _deactivateContextForLayerChange({
|
||||
this._contextMode = null;
|
||||
this._contextModeEntryIntent = null;
|
||||
this._contextModeReplacementIntent = null;
|
||||
if (this.cockpitView?.active)
|
||||
this.cockpitView.exit({ restoreTracking: false });
|
||||
// A layer turned off ends Contacts but not the Cockpit: the view ends only
|
||||
// when the layer it rides goes off (see _handleContextLayerChange).
|
||||
this._syncContextModeButtons();
|
||||
try {
|
||||
await this._restoreContextSession({ notificationToken });
|
||||
|
||||
@@ -36,6 +36,7 @@ export const LAYER_NAME_KEYS = Object.freeze({
|
||||
'fire-perimeters': msg('Fire Perimeters'),
|
||||
'gnss-integrity': msg('GNSS Integrity'),
|
||||
'drone-airspace': msg('Prohibited & Restricted Airspace'),
|
||||
'wildlife-sightings': msg('Wildlife Sightings'),
|
||||
's2-ghostmaps': msg('S2 GhostMaps'),
|
||||
wind: msg('Wind'),
|
||||
'weather-radar': msg('Rain radar'),
|
||||
@@ -141,3 +142,17 @@ export function sourceLabel(source) {
|
||||
? source.split(' · ').map(translateKnown).join(' · ')
|
||||
: translateKnown(source);
|
||||
}
|
||||
|
||||
/**
|
||||
* A provider name with the feed state it answered in, so a fallback or stale
|
||||
* snapshot does not read as the live primary feed.
|
||||
* @param {string} source English source name.
|
||||
* @param {'fallback'|'stale'|null} status Feed state from `layerFeedState`.
|
||||
* @returns {string}
|
||||
*/
|
||||
export function sourceStatusLabel(source, status) {
|
||||
const name = sourceLabel(source);
|
||||
if (status === 'fallback') return `${name} · ${t('FALLBACK')}`;
|
||||
if (status === 'stale') return `${name} · ${t('STALE')}`;
|
||||
return name;
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
LAYER_NAME_KEYS,
|
||||
PANEL_LABEL_KEYS,
|
||||
sourceLabel,
|
||||
sourceStatusLabel,
|
||||
} from './layerNames.js';
|
||||
|
||||
// Layers whose module name is a proper name and stays as it is in every
|
||||
@@ -51,3 +52,19 @@ for (const locale of ['es', 'ru']) {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test('a provider name carries the fallback or stale state it answered in', () => {
|
||||
assert.equal(sourceStatusLabel('Plane Finder', null), 'Plane Finder');
|
||||
assert.equal(sourceStatusLabel('adsb.lol', 'fallback'), 'adsb.lol · FALLBACK');
|
||||
assert.equal(sourceStatusLabel('OpenSky Network', 'stale'), 'OpenSky Network · STALE');
|
||||
setLocale('ru');
|
||||
try {
|
||||
assert.equal(
|
||||
sourceStatusLabel('adsb.lol', 'fallback'),
|
||||
`adsb.lol · ${t('FALLBACK')}`,
|
||||
);
|
||||
assert.notEqual(t('FALLBACK'), 'FALLBACK');
|
||||
} finally {
|
||||
setLocale('en');
|
||||
}
|
||||
});
|
||||
@@ -83,6 +83,10 @@ const PANEL_GROUPS = [
|
||||
's2-ghostmaps',
|
||||
],
|
||||
},
|
||||
{
|
||||
label: msg('Wildlife'),
|
||||
ids: ['wildlife-sightings'],
|
||||
},
|
||||
{
|
||||
label: msg('Weather'),
|
||||
ids: [
|
||||
|
||||
@@ -34,6 +34,27 @@ test('panel presentation places Transit between Street Traffic and Bike Share in
|
||||
assert.equal(order.filter(({ id }) => id === 'transit').length, 1);
|
||||
});
|
||||
|
||||
test('Wildlife follows Events and precedes Weather', () => {
|
||||
const source = readFileSync(
|
||||
new URL('./layerPanel.js', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
const declarations = source.slice(
|
||||
source.indexOf('const PANEL_GROUPS ='),
|
||||
source.indexOf('const PANEL_POSITIONS ='),
|
||||
);
|
||||
const order = JSON.parse(
|
||||
runInNewContext(
|
||||
`const msg = (text) => text;\n${declarations}\nJSON.stringify(PANEL_ORDER)`,
|
||||
),
|
||||
);
|
||||
const wildlife = order.findIndex(({ id }) => id === 'wildlife-sightings');
|
||||
assert.equal(order[wildlife].label, 'Wildlife');
|
||||
assert.equal(order[wildlife - 1].id, 's2-ghostmaps');
|
||||
assert.equal(order[wildlife + 1].id, 'air-quality');
|
||||
assert.equal(order.filter(({ id }) => id === 'wildlife-sightings').length, 1);
|
||||
});
|
||||
|
||||
test('partial feed controls distinguish incomplete records from stale data and outages', async () => {
|
||||
const { LayerPanel, layerFeedState, presentLayerToggle } =
|
||||
await import('./layerPanel.js');
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
export class ShellFacade {
|
||||
/** Observe camera ownership transfers through the navigation owner. */
|
||||
subscribeCameraHandoff(listener) {
|
||||
return this._navigation.subscribeCameraHandoff(listener);
|
||||
return this._navigation?.subscribeCameraHandoff(listener);
|
||||
}
|
||||
|
||||
get _models3dEnabled() {
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { ShellFacade } from './shellFacade.js';
|
||||
|
||||
// A shell assembled without its navigation owner (as unit tests build one
|
||||
// from the prototype) has no handoffs to report, like the facade's other
|
||||
// optional owners; the voice runner subscribes as it is created.
|
||||
test('camera handoffs without a navigation owner subscribe to nothing', () => {
|
||||
const shell = Object.create(ShellFacade.prototype);
|
||||
assert.equal(
|
||||
shell.subscribeCameraHandoff(() => {}),
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
test('camera handoffs reach listeners through the navigation owner', () => {
|
||||
const listeners = new Set();
|
||||
const shell = Object.create(ShellFacade.prototype);
|
||||
shell._navigation = {
|
||||
subscribeCameraHandoff(listener) {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
},
|
||||
};
|
||||
let handoffs = 0;
|
||||
const unsubscribe = shell.subscribeCameraHandoff(() => {
|
||||
handoffs += 1;
|
||||
});
|
||||
for (const listener of listeners) listener();
|
||||
assert.equal(handoffs, 1);
|
||||
unsubscribe();
|
||||
assert.equal(listeners.size, 0);
|
||||
});
|
||||
@@ -33,6 +33,36 @@
|
||||
color: #00dcff;
|
||||
font-size: 18px;
|
||||
}
|
||||
/* The same entry under the selected vehicle's Intel HUD readout. The HUD
|
||||
lets clicks through, so the button takes them back. */
|
||||
#intel-hud #cockpit-entry-readout {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin-top: 6px;
|
||||
min-height: 30px;
|
||||
padding: 0 10px;
|
||||
border: 1px solid var(--hud-border);
|
||||
border-radius: 6px;
|
||||
background: rgba(2, 12, 18, 0.72);
|
||||
font-size: 10px;
|
||||
letter-spacing: 0.14em;
|
||||
pointer-events: auto;
|
||||
cursor: pointer;
|
||||
}
|
||||
#intel-hud #cockpit-entry-readout[hidden] {
|
||||
display: none;
|
||||
}
|
||||
#intel-hud #cockpit-entry-readout:hover,
|
||||
#intel-hud #cockpit-entry-readout:focus-visible {
|
||||
border-color: var(--hud-color);
|
||||
outline: none;
|
||||
}
|
||||
#intel-hud #cockpit-entry-readout .material-symbols-outlined {
|
||||
font-family: 'Material Symbols Outlined';
|
||||
font-size: 16px;
|
||||
text-transform: none;
|
||||
}
|
||||
#cockpit-entry kbd {
|
||||
padding: 3px 5px;
|
||||
border: 1px solid rgba(220, 238, 255, 0.25);
|
||||
|
||||
@@ -716,6 +716,11 @@
|
||||
.data-icon::before {
|
||||
content: '⌁';
|
||||
}
|
||||
:root[data-ui-theme='cyber']
|
||||
.data-toggle-row[data-layer-id='wildlife-sightings']
|
||||
.data-icon::before {
|
||||
content: '✿';
|
||||
}
|
||||
:root[data-ui-theme='cyber']
|
||||
.data-toggle-row[data-layer-id='radio']
|
||||
.data-icon::before {
|
||||
@@ -1693,7 +1698,9 @@
|
||||
:root[data-ui-theme='cyber']
|
||||
body:not(.cockpit-mode)
|
||||
#left-panel-stack:has(> [data-panel-id]:not(.collapsed))
|
||||
> :is(#data-panel, #cctv-panel, #utilities-panel, #scene-panel):not(.collapsed) {
|
||||
> :is(#data-panel, #cctv-panel, #utilities-panel, #scene-panel):not(
|
||||
.collapsed
|
||||
) {
|
||||
flex: 1 1 auto;
|
||||
height: auto;
|
||||
max-height: none;
|
||||
|
||||
@@ -14,11 +14,14 @@ import MissionDetail from './panels/MissionDetail.vue';
|
||||
import MissionRoster from './panels/MissionRoster.vue';
|
||||
import RadioPanel from './panels/RadioPanel.vue';
|
||||
import UiButton from '../kit/UiButton.vue';
|
||||
import { cockpitEntryFace } from '../cockpitPresentation.js';
|
||||
|
||||
// ContextControls presents the mode switch and the nearby sites search and
|
||||
// publishes them; until it does, the panel shows its initial markup.
|
||||
const { view: ctx } = storeToRefs(useContextStore());
|
||||
const { presence: cockpit } = storeToRefs(useCockpitStore());
|
||||
// The entry rides the tracked aircraft (cockpitEntryFace).
|
||||
const entry = computed(() => cockpitEntryFace('aircraft'));
|
||||
// While the Bhote Koshi event is on, its panel is the rail's only content.
|
||||
const { panel: bhotePanel } = storeToRefs(useBhoteKoshiPanelStore());
|
||||
// The Scene runtime chip SceneControls presents while a scene plays.
|
||||
@@ -56,8 +59,8 @@ const sceneRuntime = computed(() => scenePanel.value?.runtime ?? '');
|
||||
<section id="context-flights-view" class="context-mode-view" role="tabpanel" aria-labelledby="global-context-flights-btn" :hidden="!ctx?.flightsActive">
|
||||
<div class="global-context-actions" :aria-label="t('Contact Context actions')">
|
||||
<button id="cockpit-entry" type="button" :hidden="!cockpit?.entryAvailable">
|
||||
<span class="material-symbols-outlined" aria-hidden="true">flight</span>
|
||||
<span>{{ t('COCKPIT') }}</span>
|
||||
<span class="material-symbols-outlined" aria-hidden="true">{{ entry.icon }}</span>
|
||||
<span>{{ entry.label }}</span>
|
||||
</button>
|
||||
<button id="installations-search-btn" class="panel-layer-toggle" type="button" :aria-disabled="ctx && String(ctx.installationsBusy)" :aria-busy="ctx && String(ctx.installationsBusy)">{{ t('SEARCH NEARBY SITES') }}</button>
|
||||
<UiButton id="tr3b-toggle" class="tr3b-toggle" :pressed="!!cockpit?.tr3b?.converted" :hidden="!cockpit?.tr3b" :aria-label="t('Reclassify tracked contact as TR-3B')" :title="cockpit?.tr3b?.converted ? t('Restore real aircraft') : t('Reclassify as TR-3B')">🛸</UiButton>
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
import { computed } from 'vue';
|
||||
import { storeToRefs } from 'pinia';
|
||||
import { useHudStore } from '../stores/hud.js';
|
||||
import { useCockpitStore } from '../stores/cockpit.js';
|
||||
import { cockpitEntryFace } from '../cockpitPresentation.js';
|
||||
|
||||
// The readouts, visibility, layout variant and colors IntelHUD publishes.
|
||||
const { hud } = storeToRefs(useHudStore());
|
||||
@@ -10,6 +12,12 @@ const { hud } = storeToRefs(useHudStore());
|
||||
// right after IntelHUD is built.
|
||||
const EMPTY = Object.freeze({ vessel: {}, sensor: [], recShown: null });
|
||||
const view = computed(() => hud.value ?? EMPTY);
|
||||
// The selected vehicle's readout offers the same entry as the Contacts
|
||||
// button, so first person needs no Contacts panel. The Cockpit controller
|
||||
// answers its clicks.
|
||||
const { presence: cockpit } = storeToRefs(useCockpitStore());
|
||||
// The entry rides the tracked aircraft (cockpitEntryFace).
|
||||
const entry = computed(() => cockpitEntryFace('aircraft'));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -46,6 +54,10 @@ const view = computed(() => hud.value ?? EMPTY);
|
||||
<div class="hud-readout"><div id="hud-gsd">{{ view.gsd }}</div></div>
|
||||
<div class="hud-readout"><div id="hud-alt">{{ view.alt }}</div></div>
|
||||
<div class="hud-readout"><div id="hud-ais-vessel" :class="['hud-ais-vessel', { active: view.vessel.active }]">{{ view.vessel.text }}</div></div>
|
||||
<button id="cockpit-entry-readout" type="button" :hidden="!cockpit?.entryAvailable">
|
||||
<span class="material-symbols-outlined" aria-hidden="true">{{ entry.icon }}</span>
|
||||
<span>{{ entry.label }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="hud-bracket">┘</div>
|
||||
</div>
|
||||
|
||||
@@ -49,10 +49,10 @@ const weatherLabel = computed(() =>
|
||||
<span class="cockpit-context-qualifier">{{ t('CONTEXT ONLY') }}</span>
|
||||
</header>
|
||||
<div class="cockpit-context-cohorts" role="list" :aria-label="t('Nearby cohort counts')">
|
||||
<div v-class-toggle="{ unknown: c.cohorts.flights.unknown }" role="listitem" data-context-cohort="flights"><span>{{ t('FLT') }}</span><strong>{{ c.cohorts.flights.count }}</strong><small translate="no">OpenSky</small></div>
|
||||
<div v-class-toggle="{ unknown: c.cohorts.military.unknown }" role="listitem" data-context-cohort="military"><span>{{ t('MIL') }}</span><strong>{{ c.cohorts.military.count }}</strong><small translate="no">adsb.lol</small></div>
|
||||
<div v-class-toggle="{ unknown: c.cohorts['ais-live-vessels'].unknown }" role="listitem" data-context-cohort="ais-live-vessels"><span translate="no">AIS</span><strong>{{ c.cohorts['ais-live-vessels'].count }}</strong><small translate="no">AISStream</small></div>
|
||||
<div v-class-toggle="{ unknown: c.cohorts['military-installations'].unknown }" role="listitem" data-context-cohort="military-installations"><span>{{ t('SITE') }}</span><strong>{{ c.cohorts['military-installations'].count }}</strong><small translate="no">OpenStreetMap</small></div>
|
||||
<div v-class-toggle="{ unknown: c.cohorts.flights.unknown }" role="listitem" data-context-cohort="flights"><span>{{ t('FLT') }}</span><strong>{{ c.cohorts.flights.count }}</strong><small translate="no" :title="c.cohorts.flights.source">{{ c.cohorts.flights.source }}</small></div>
|
||||
<div v-class-toggle="{ unknown: c.cohorts.military.unknown }" role="listitem" data-context-cohort="military"><span>{{ t('MIL') }}</span><strong>{{ c.cohorts.military.count }}</strong><small translate="no" :title="c.cohorts.military.source">{{ c.cohorts.military.source }}</small></div>
|
||||
<div v-class-toggle="{ unknown: c.cohorts['ais-live-vessels'].unknown }" role="listitem" data-context-cohort="ais-live-vessels"><span translate="no">AIS</span><strong>{{ c.cohorts['ais-live-vessels'].count }}</strong><small translate="no" :title="c.cohorts['ais-live-vessels'].source">{{ c.cohorts['ais-live-vessels'].source }}</small></div>
|
||||
<div v-class-toggle="{ unknown: c.cohorts['military-installations'].unknown }" role="listitem" data-context-cohort="military-installations"><span>{{ t('SITE') }}</span><strong>{{ c.cohorts['military-installations'].count }}</strong><small translate="no" :title="c.cohorts['military-installations'].source">{{ c.cohorts['military-installations'].source }}</small></div>
|
||||
</div>
|
||||
<div class="cockpit-context-nearest">
|
||||
<span id="cockpit-context-direction" v-class-toggle="{ unknown: c.direction.unknown }" class="material-symbols-outlined" :style="directionStyle" aria-hidden="true">navigation</span>
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
<script setup>
|
||||
import { computed, shallowRef, useTemplateRef, watch } from 'vue';
|
||||
import { formatDate, t, translateKnown } from '../../../i18n/index.js';
|
||||
import { photoCreator, formatAge } from '../../../layers/wildlifeSightings/photoText.js';
|
||||
import { ACARTIA_SITE, inatLicenceLabel, inatPhotoUrl, isOpenPhoto } from '../../../layers/wildlifeSightings/records.js';
|
||||
|
||||
const props = defineProps({
|
||||
sighting: { type: Object, required: true },
|
||||
nowMs: { type: Number, required: true },
|
||||
taxa: { type: String, default: 'all' },
|
||||
});
|
||||
const emit = defineEmits(['close', 'resize']);
|
||||
const acartia = computed(() => props.sighting.origin === 'acartia');
|
||||
const name = computed(() => translateKnown(props.sighting.commonName || props.sighting.scientificName) || t('SIGHTING'));
|
||||
const scientificName = computed(() => translateKnown(props.sighting.scientificName || ''));
|
||||
const photo = computed(() => {
|
||||
const row = props.sighting;
|
||||
if (row.obscured || acartia.value || !isOpenPhoto(row.photo)) return null;
|
||||
const src = inatPhotoUrl(row.photo.square ?? row.photo.url, 'medium');
|
||||
const creator = photoCreator(row.photo);
|
||||
return src && creator ? { src, creator, licence: inatLicenceLabel(row.photo.license_code ?? row.photo.licence) } : null;
|
||||
});
|
||||
const observedDay = computed(() => {
|
||||
const row = props.sighting;
|
||||
const day = row.observedOn || (!row.obscured && Number.isFinite(row.observedAt) ? new Date(row.observedAt).toISOString().slice(0, 10) : '');
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(day)) return '';
|
||||
const date = new Date(`${day}T00:00:00Z`);
|
||||
return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === day ? day : '';
|
||||
});
|
||||
const age = computed(() => {
|
||||
const row = props.sighting;
|
||||
const delta = props.nowMs - row.observedAt;
|
||||
if (row.obscured || !Number.isFinite(row.observedAt) || delta >= 30 * 86_400_000) return '';
|
||||
const compact = formatAge(Math.max(0, delta));
|
||||
return acartia.value ? t('seen {age} ago', { age: compact }) : t('observed {age} ago', { age: compact });
|
||||
});
|
||||
const observedDate = computed(() => observedDay.value ? formatDate(Date.parse(`${observedDay.value}T00:00:00Z`), { year: 'numeric', month: 'short', day: 'numeric', timeZone: 'UTC' }) : '');
|
||||
const link = computed(() => {
|
||||
// The "Acartia" label only ever points at the Acartia site, never a row URL.
|
||||
if (acartia.value) return ACARTIA_SITE;
|
||||
try {
|
||||
const url = new URL(props.sighting.link);
|
||||
return url.protocol === 'https:' && !url.username && !url.password ? url.href : null;
|
||||
} catch { return null; }
|
||||
});
|
||||
const providerCredit = computed(() => {
|
||||
if (!acartia.value) return '';
|
||||
const { name = '', entity = '' } = props.sighting.provider || {};
|
||||
return entity ? t('Reported by {name} ({entity})', { name, entity }) : t('Reported by {name}', { name });
|
||||
});
|
||||
const actionLabel = computed(() => acartia.value ? t('Open {name} on Acartia', { name: name.value }) : t('Open {name} on iNaturalist', { name: name.value }));
|
||||
const photoImage = useTemplateRef('photoImage');
|
||||
const loaded = shallowRef(false);
|
||||
const failed = shallowRef(false);
|
||||
const currentImage = (image) => image === photoImage.value && image?.dataset.sightingId === props.sighting.stableId && image?.getAttribute('src') === photo.value?.src;
|
||||
async function onPhotoLoad(event) {
|
||||
const image = event.currentTarget;
|
||||
// Ignore late decodes after a different observation replaces this photo.
|
||||
try { await image.decode?.(); } catch { /* onload is sufficient on older engines */ }
|
||||
if (!currentImage(image)) return;
|
||||
loaded.value = true;
|
||||
emit('resize');
|
||||
}
|
||||
function fail(event) {
|
||||
if (!currentImage(event.currentTarget)) return;
|
||||
failed.value = true;
|
||||
emit('resize');
|
||||
}
|
||||
watch([() => props.sighting.stableId, () => photo.value?.src], () => { loaded.value = false; failed.value = false; }, { flush: 'sync' });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="wildlife-sighting-card" data-wildlife-sighting-card tabindex="-1" :aria-label="name" @keydown.stop @keyup.stop>
|
||||
<button type="button" class="wildlife-sighting-card-close" :aria-label="t('Close sighting')" @click="emit('close')">×</button>
|
||||
<component :is="link ? 'a' : 'div'" class="wildlife-sighting-card-content" :href="link || undefined" :target="link ? '_blank' : undefined" :rel="link ? 'noopener noreferrer' : undefined" :aria-label="link ? actionLabel : undefined">
|
||||
<div v-if="photo" class="wildlife-sighting-card-photo" :aria-busy="!loaded && !failed">
|
||||
<p v-if="!loaded && !failed" role="status">{{ t('Loading photo...') }}</p>
|
||||
<p v-if="failed" role="status">{{ t('Photo unavailable') }}</p>
|
||||
<img v-show="!failed" ref="photoImage" :key="sighting.stableId + photo.src" :data-sighting-id="sighting.stableId" :src="photo.src" :alt="t('Photo of {name}', { name })" referrerpolicy="no-referrer" :class="{ loaded }" @load="onPhotoLoad" @error="fail" />
|
||||
</div>
|
||||
<div class="wildlife-sighting-card-caption">
|
||||
<h2>{{ name }}</h2>
|
||||
<p v-if="scientificName && scientificName !== name"><i>{{ scientificName }}</i></p>
|
||||
<p v-if="age || observedDay"><time :datetime="observedDay || undefined">{{ age || observedDate }}</time></p>
|
||||
<p v-if="sighting.obscured">{{ t('Location obscured to a 0.2° cell') }}</p>
|
||||
<!-- i18n-ignore: creator and licence are provider attribution, copied verbatim -->
|
||||
<p v-if="photo" class="wildlife-sighting-card-credit">© {{ photo.creator }} · {{ photo.licence }}</p>
|
||||
<p v-if="providerCredit" class="wildlife-sighting-card-credit">{{ providerCredit }}</p>
|
||||
<p v-if="acartia" class="wildlife-sighting-card-credit">{{ t('Acartia') }} · {{ t('CC BY 4.0') }} · {{ t('Salish Sea') }}</p>
|
||||
<p v-if="link" class="wildlife-sighting-card-source">{{ acartia ? t('Acartia') : t('iNaturalist') }} ↗</p>
|
||||
</div>
|
||||
</component>
|
||||
<p v-if="acartia || taxa === 'whales'" class="wildlife-sighting-card-guidance">
|
||||
<a href="https://www.bewhalewise.org" target="_blank" rel="noopener noreferrer">{{ t('Be Whale Wise') }}</a>
|
||||
</p>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.wildlife-sighting-card {
|
||||
position: relative;
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
max-height: inherit;
|
||||
overflow: auto;
|
||||
padding: 8px;
|
||||
border: 1px solid var(--glass-border-hover);
|
||||
border-radius: var(--btn-radius);
|
||||
background: var(--menu-bg);
|
||||
color: var(--text-primary);
|
||||
font: 11px/1.4 var(--font-mono);
|
||||
box-shadow: 0 3px 16px rgb(0 0 0 / 30%);
|
||||
}
|
||||
.wildlife-sighting-card-content { display: block; color: inherit; text-decoration: none; }
|
||||
.wildlife-sighting-card-content:focus-visible { outline: 2px solid var(--text-primary); outline-offset: 3px; }
|
||||
/* Script focus starts inside the card; tab focus still outlines its controls. */
|
||||
.wildlife-sighting-card:focus-visible { outline: none !important; }
|
||||
.wildlife-sighting-card-close { position: absolute; z-index: 1; inset-block-start: 4px; inset-inline-end: 4px; width: 24px; height: 24px; padding: 0; border: 0; border-radius: var(--btn-radius); background: transparent; color: inherit; font: 20px/1 var(--font-sans); cursor: pointer; }
|
||||
.wildlife-sighting-card-close:hover { background: var(--menu-bg); }
|
||||
.wildlife-sighting-card-close:focus-visible { outline: 2px solid var(--text-primary); outline-offset: 2px; }
|
||||
.wildlife-sighting-card-photo { position: relative; width: 100%; height: 180px; }
|
||||
.wildlife-sighting-card-photo > p { position: absolute; inset: 0; display: grid; place-items: center; margin: 0; }
|
||||
.wildlife-sighting-card-photo > img { display: block; width: 100%; height: 100%; object-fit: contain; opacity: 0; }
|
||||
.wildlife-sighting-card-photo > img.loaded { opacity: 1; }
|
||||
.wildlife-sighting-card-caption { padding-top: 6px; overflow-wrap: anywhere; }
|
||||
.wildlife-sighting-card-caption h2, .wildlife-sighting-card-caption p { margin: 0 0 3px; }
|
||||
.wildlife-sighting-card-caption h2 { padding-inline-end: 20px; font: inherit; font-weight: 700; }
|
||||
.wildlife-sighting-card-credit { color: var(--text-secondary); }
|
||||
.wildlife-sighting-card-guidance { display: flex; flex-wrap: wrap; gap: 4px 12px; margin: 4px 0 0; color: var(--text-secondary); }
|
||||
.wildlife-sighting-card-guidance a { color: inherit; }
|
||||
.wildlife-sighting-card-source { text-decoration: underline; text-underline-offset: 2px; }
|
||||
</style>
|
||||
@@ -0,0 +1,270 @@
|
||||
import { h, nextTick, shallowRef } from 'vue';
|
||||
import WildlifeSightingCard from './views/panels/WildlifeSightingCard.vue';
|
||||
import {
|
||||
panWildlifeSighting,
|
||||
placeWildlifeSightingCard,
|
||||
projectWildlifeSighting,
|
||||
readWildlifeCardSafeArea,
|
||||
WILDLIFE_SELECTED_CARD_WIDTH,
|
||||
WILDLIFE_CARD_CHROME_SELECTORS,
|
||||
} from './wildlifeSightingPlacement.js';
|
||||
|
||||
/** Anchor the selected sighting's photo and source link clear of map chrome. */
|
||||
export function createWildlifeSightingCard({
|
||||
layer,
|
||||
ui,
|
||||
viewer = null,
|
||||
documentRef = globalThis.document,
|
||||
windowRef = globalThis.window,
|
||||
now = () => Date.now(),
|
||||
project = projectWildlifeSighting,
|
||||
pan = panWildlifeSighting,
|
||||
}) {
|
||||
const selected = shallowRef(null);
|
||||
const host = documentRef.createElement('div');
|
||||
host.dataset.wildlifeSightingCardHost = '';
|
||||
Object.assign(host.style, {
|
||||
position: 'fixed',
|
||||
zIndex: '89',
|
||||
display: 'none',
|
||||
width: `${WILDLIFE_SELECTED_CARD_WIDTH}px`,
|
||||
});
|
||||
documentRef.body.append(host);
|
||||
let destroyed = false;
|
||||
let moving = false;
|
||||
let removeFrame = null;
|
||||
let returnFocus = null;
|
||||
let panForId = null;
|
||||
const removers = [];
|
||||
const observed = new Set();
|
||||
const resizeObserver = windowRef?.ResizeObserver
|
||||
? new windowRef.ResizeObserver(() => position())
|
||||
: null;
|
||||
const mutationObserver = windowRef?.MutationObserver
|
||||
? new windowRef.MutationObserver(() => position())
|
||||
: null;
|
||||
|
||||
const chromeSelector = WILDLIFE_CARD_CHROME_SELECTORS.join(',');
|
||||
const structureObserver = windowRef?.MutationObserver
|
||||
? new windowRef.MutationObserver((records) => {
|
||||
if (destroyed || !selected.value) return;
|
||||
const hasChromeChange = records.some((record) =>
|
||||
[...record.addedNodes, ...record.removedNodes].some(
|
||||
(node) =>
|
||||
node.nodeType === 1 &&
|
||||
!host.contains(node) &&
|
||||
(node.matches(chromeSelector) ||
|
||||
node.querySelector(chromeSelector)),
|
||||
),
|
||||
);
|
||||
if (!hasChromeChange) return;
|
||||
// Newly mounted chrome can cover a previously clear anchor.
|
||||
panForId = null;
|
||||
position({ allowPan: true });
|
||||
})
|
||||
: null;
|
||||
|
||||
function observeLayout(elements) {
|
||||
const next = new Set(
|
||||
[host.firstElementChild, viewer?.scene?.canvas, ...elements].filter(
|
||||
Boolean,
|
||||
),
|
||||
);
|
||||
let changed = false;
|
||||
for (const element of observed) {
|
||||
if (next.has(element)) continue;
|
||||
resizeObserver?.unobserve(element);
|
||||
observed.delete(element);
|
||||
changed = true;
|
||||
}
|
||||
for (const element of next) {
|
||||
if (observed.has(element)) continue;
|
||||
observed.add(element);
|
||||
resizeObserver?.observe(element);
|
||||
changed = true;
|
||||
}
|
||||
if (!changed) return;
|
||||
mutationObserver?.disconnect();
|
||||
for (const element of observed) {
|
||||
// Ignore HUD clock/text changes and the card's own positioning styles.
|
||||
if (!host.contains(element))
|
||||
mutationObserver?.observe(element, {
|
||||
attributes: true,
|
||||
attributeFilter: ['class', 'style', 'hidden'],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function position({ allowPan = false } = {}) {
|
||||
if (destroyed || !selected.value || !host.firstElementChild) return;
|
||||
const point = project(viewer, selected.value, layer);
|
||||
if (!point || !Number.isFinite(point.x) || !Number.isFinite(point.y)) {
|
||||
host.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
const safe = readWildlifeCardSafeArea({ documentRef, viewer, windowRef });
|
||||
observeLayout(safe.elements);
|
||||
host.style.width = `${Math.min(WILDLIFE_SELECTED_CARD_WIDTH, safe.bounds.width)}px`;
|
||||
host.style.maxHeight = `${safe.bounds.height}px`;
|
||||
host.style.display = 'block';
|
||||
const rect = host.firstElementChild.getBoundingClientRect();
|
||||
const result = placeWildlifeSightingCard(
|
||||
point,
|
||||
{
|
||||
width:
|
||||
rect.width ||
|
||||
Math.min(WILDLIFE_SELECTED_CARD_WIDTH, safe.bounds.width),
|
||||
height:
|
||||
rect.height ||
|
||||
(selected.value.photo &&
|
||||
!selected.value.obscured &&
|
||||
selected.value.origin !== 'acartia'
|
||||
? 300
|
||||
: 132),
|
||||
},
|
||||
safe,
|
||||
);
|
||||
if (!result) {
|
||||
host.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
if (
|
||||
(result.pan.x || result.pan.y) &&
|
||||
allowPan &&
|
||||
panForId !== selected.value.stableId
|
||||
) {
|
||||
panForId = selected.value.stableId;
|
||||
const reduced =
|
||||
windowRef?.matchMedia?.('(prefers-reduced-motion: reduce)').matches ===
|
||||
true;
|
||||
pan(viewer, point, result.anchor, reduced);
|
||||
}
|
||||
host.style.left = `${result.left}px`;
|
||||
host.style.top = `${result.top}px`;
|
||||
host.dataset.placement = result.placement;
|
||||
}
|
||||
|
||||
const unmount = ui.mount(
|
||||
{
|
||||
setup: () => () =>
|
||||
selected.value
|
||||
? h(WildlifeSightingCard, {
|
||||
sighting: selected.value,
|
||||
nowMs: now(),
|
||||
taxa: layer.getParams?.()?.taxa,
|
||||
onClose: () => {
|
||||
if (!destroyed) layer.clearSightingSelection();
|
||||
},
|
||||
onResize: () => position(),
|
||||
})
|
||||
: null,
|
||||
},
|
||||
host,
|
||||
);
|
||||
|
||||
function restoreFocus() {
|
||||
if (returnFocus?.isConnected) returnFocus.focus?.({ preventScroll: true });
|
||||
returnFocus = null;
|
||||
}
|
||||
const unsubscribe = layer.subscribeSelection((row, metadata) => {
|
||||
if (destroyed) return;
|
||||
const fresh = row?.stableId !== selected.value?.stableId;
|
||||
if (row && !selected.value) {
|
||||
returnFocus = documentRef.activeElement;
|
||||
structureObserver?.observe(documentRef.body, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
});
|
||||
}
|
||||
selected.value = row;
|
||||
if (!row) {
|
||||
host.style.display = 'none';
|
||||
panForId = null;
|
||||
removeFrame?.();
|
||||
removeFrame = null;
|
||||
resizeObserver?.disconnect();
|
||||
mutationObserver?.disconnect();
|
||||
structureObserver?.disconnect();
|
||||
observed.clear();
|
||||
restoreFocus();
|
||||
return;
|
||||
}
|
||||
if (fresh) panForId = null;
|
||||
nextTick(() => {
|
||||
if (destroyed || !selected.value) return;
|
||||
position({ allowPan: fresh || metadata?.explicitSelection === true });
|
||||
if (moving) startFrameUpdates();
|
||||
// Focus the container so keyboard navigation starts inside the card.
|
||||
if (fresh)
|
||||
host
|
||||
.querySelector('[data-wildlife-sighting-card]')
|
||||
?.focus?.({ preventScroll: true });
|
||||
});
|
||||
});
|
||||
|
||||
const keydown = (event) => {
|
||||
if (!selected.value || event.key !== 'Escape') return;
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
layer.clearSightingSelection();
|
||||
};
|
||||
const outside = (event) => {
|
||||
if (!selected.value || host.contains(event.target)) return;
|
||||
// The layer selects on pointer-up; its following click must keep the card open.
|
||||
const canvas = viewer?.scene?.canvas;
|
||||
if (canvas && (event.target === canvas || canvas.contains?.(event.target)))
|
||||
return;
|
||||
layer.clearSightingSelection();
|
||||
};
|
||||
documentRef.addEventListener('keydown', keydown, true);
|
||||
documentRef.addEventListener('click', outside, true);
|
||||
const onResize = () => position();
|
||||
windowRef?.addEventListener('resize', onResize);
|
||||
|
||||
function listen(event, callback) {
|
||||
const remove = event?.addEventListener?.(callback);
|
||||
if (typeof remove === 'function') removers.push(remove);
|
||||
else if (event?.removeEventListener)
|
||||
removers.push(() => event.removeEventListener(callback));
|
||||
}
|
||||
function startFrameUpdates() {
|
||||
if (!selected.value || removeFrame) return;
|
||||
// Installed only for camera motion; an idle card has zero per-frame work.
|
||||
removeFrame =
|
||||
viewer?.scene?.preRender?.addEventListener?.(() => position()) || null;
|
||||
}
|
||||
listen(viewer?.camera?.moveStart, () => {
|
||||
moving = true;
|
||||
startFrameUpdates();
|
||||
});
|
||||
listen(viewer?.camera?.moveEnd, () => {
|
||||
moving = false;
|
||||
removeFrame?.();
|
||||
removeFrame = null;
|
||||
position();
|
||||
});
|
||||
listen(viewer?.camera?.changed, () => {
|
||||
if (!moving) position();
|
||||
});
|
||||
|
||||
return {
|
||||
/** Release the card, selection subscription and placement listeners. */
|
||||
destroy() {
|
||||
if (destroyed) return;
|
||||
destroyed = true;
|
||||
unsubscribe?.();
|
||||
for (const remove of removers) remove();
|
||||
removeFrame?.();
|
||||
resizeObserver?.disconnect();
|
||||
mutationObserver?.disconnect();
|
||||
structureObserver?.disconnect();
|
||||
documentRef.removeEventListener('keydown', keydown, true);
|
||||
documentRef.removeEventListener('click', outside, true);
|
||||
windowRef?.removeEventListener('resize', onResize);
|
||||
unmount();
|
||||
host.remove();
|
||||
selected.value = null;
|
||||
restoreFocus();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,797 @@
|
||||
import '../testSupport/registerDom.mjs';
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import * as Cesium from 'cesium';
|
||||
import { nextTick } from 'vue';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { getLocale, setLocale, t } from '../i18n/index.js';
|
||||
import { LOCALES } from '../i18n/locale.js';
|
||||
import { createSelection } from '../layers/wildlifeSightings/selection.js';
|
||||
import { buildWildlifeThumbnailEntry } from '../layers/wildlifeSightings/cards.js';
|
||||
import { createWildlifeSightingCard } from './wildlifeSightingCard.js';
|
||||
import {
|
||||
panWildlifeSighting,
|
||||
placeWildlifeSightingCard,
|
||||
readWildlifeCardSafeArea,
|
||||
} from './wildlifeSightingPlacement.js';
|
||||
import { createUiRuntime } from './vueRuntime.js';
|
||||
import { PANEL_RAIL_ITEMS } from './panelRailCatalog.js';
|
||||
import { sheetForPanelId } from './mobileShell.js';
|
||||
|
||||
const NOW = Date.parse('2026-11-04T13:00:00Z');
|
||||
const square =
|
||||
'https://inaturalist-open-data.s3.amazonaws.com/photos/456/square.jpg';
|
||||
const row = {
|
||||
stableId: 'inat:456',
|
||||
origin: 'inaturalist',
|
||||
lat: 0,
|
||||
lon: 0,
|
||||
commonName: 'Synthetic bird',
|
||||
scientificName: 'Avis imaginaria',
|
||||
iconic: 'Aves',
|
||||
observedAt: NOW - 3_600_000,
|
||||
observedOn: '2026-11-04',
|
||||
obscured: false,
|
||||
photo: {
|
||||
square,
|
||||
attribution: '(c) Synthetic Photographer, some rights reserved (CC BY-SA)',
|
||||
licence: 'cc-by-sa',
|
||||
},
|
||||
link: 'https://www.inaturalist.org/observations/456',
|
||||
};
|
||||
const rect = (left, top, width, height) => ({
|
||||
left,
|
||||
top,
|
||||
width,
|
||||
height,
|
||||
right: left + width,
|
||||
bottom: top + height,
|
||||
});
|
||||
const events = () => {
|
||||
const listeners = new Set();
|
||||
return {
|
||||
addEventListener(fn) {
|
||||
listeners.add(fn);
|
||||
return () => listeners.delete(fn);
|
||||
},
|
||||
emit() {
|
||||
for (const fn of listeners) fn();
|
||||
},
|
||||
size: () => listeners.size,
|
||||
};
|
||||
};
|
||||
const settle = async () => {
|
||||
await nextTick();
|
||||
await Promise.resolve();
|
||||
await nextTick();
|
||||
};
|
||||
|
||||
// All scene rows, media events and rectangles are synthetic. Browser image
|
||||
// requests are disabled; decode resolution below proves the photo is exposed
|
||||
// only after it has loaded into the compact card.
|
||||
function fixture(
|
||||
context,
|
||||
initialRow = row,
|
||||
point = { x: 600, y: 450 },
|
||||
extraWindow = {},
|
||||
) {
|
||||
document.body.replaceChildren();
|
||||
const opener = document.body.appendChild(document.createElement('button'));
|
||||
opener.textContent = 'Globe';
|
||||
opener.focus();
|
||||
const canvas = document.body.appendChild(document.createElement('canvas'));
|
||||
canvas.getBoundingClientRect = () => rect(0, 0, 1200, 900);
|
||||
const windowRef = {
|
||||
innerWidth: 1200,
|
||||
innerHeight: 900,
|
||||
getComputedStyle: window.getComputedStyle.bind(window),
|
||||
addEventListener() {},
|
||||
removeEventListener() {},
|
||||
matchMedia: () => ({ matches: false }),
|
||||
...extraWindow,
|
||||
};
|
||||
const ui = createUiRuntime();
|
||||
const overlays = new Map();
|
||||
const moveStart = events();
|
||||
const moveEnd = events();
|
||||
const changed = events();
|
||||
const preRender = events();
|
||||
const viewer = {
|
||||
scene: { canvas, preRender, pick: () => picked },
|
||||
camera: { moveStart, moveEnd, changed },
|
||||
};
|
||||
const state = {
|
||||
enabled: true,
|
||||
destroyed: false,
|
||||
selectedId: null,
|
||||
selectedRow: null,
|
||||
ambientRows: [],
|
||||
rowById: new Map([[initialRow.stableId, initialRow]]),
|
||||
positions: new Map([[initialRow.stableId, { x: 1, y: 2, z: 3 }]]),
|
||||
contextIds: new Set(),
|
||||
viewer,
|
||||
};
|
||||
let picked = null;
|
||||
let hit = null;
|
||||
let onClick;
|
||||
let clears = 0;
|
||||
let staleListener;
|
||||
const subscriptions = new Set();
|
||||
const flights = [];
|
||||
const pans = [];
|
||||
const selection = createSelection({
|
||||
state,
|
||||
services: {
|
||||
now: () => NOW,
|
||||
cesium: { ScreenSpaceEventType: { LEFT_CLICK: 0 } },
|
||||
overlayHost: {
|
||||
setEntries: (id, entries) => overlays.set(id, entries),
|
||||
hitTest: (_x, _y, { sourceId }) =>
|
||||
hit?.sourceId === sourceId ? hit : null,
|
||||
},
|
||||
screenSpaceEventHandlerFactory: () => ({
|
||||
setInputAction(fn) {
|
||||
onClick = fn;
|
||||
},
|
||||
destroy() {},
|
||||
}),
|
||||
focus: { requestWorldFocus: (value) => flights.push(value) },
|
||||
},
|
||||
parts: {
|
||||
rendering: { refreshSelection() {}, requestRender() {} },
|
||||
},
|
||||
});
|
||||
const layer = {
|
||||
getParams: () => ({ taxa: 'all' }),
|
||||
subscribeSelection(listener) {
|
||||
staleListener = listener;
|
||||
subscriptions.add(listener);
|
||||
const off = selection.subscribe(listener);
|
||||
return () => {
|
||||
subscriptions.delete(listener);
|
||||
off();
|
||||
};
|
||||
},
|
||||
clearSightingSelection() {
|
||||
clears++;
|
||||
selection.clearAndRebuild();
|
||||
},
|
||||
};
|
||||
let currentPoint = point;
|
||||
let projections = 0;
|
||||
const card = createWildlifeSightingCard({
|
||||
layer,
|
||||
ui,
|
||||
viewer,
|
||||
documentRef: document,
|
||||
windowRef,
|
||||
now: () => NOW,
|
||||
project: () => {
|
||||
projections++;
|
||||
return currentPoint;
|
||||
},
|
||||
pan: (_viewer, from, to, reduced) => {
|
||||
pans.push({ from, to, reduced });
|
||||
currentPoint = to;
|
||||
return true;
|
||||
},
|
||||
});
|
||||
selection.install();
|
||||
context.after(() => {
|
||||
card.destroy();
|
||||
selection.destroy();
|
||||
ui.destroy();
|
||||
});
|
||||
return {
|
||||
state,
|
||||
selection,
|
||||
layer,
|
||||
card,
|
||||
viewer,
|
||||
windowRef,
|
||||
overlays,
|
||||
flights,
|
||||
pans,
|
||||
projections: () => projections,
|
||||
subscriptions,
|
||||
opener,
|
||||
canvas,
|
||||
moveStart,
|
||||
moveEnd,
|
||||
preRender,
|
||||
cardElement: () => document.querySelector('[data-wildlife-sighting-card]'),
|
||||
host: () => document.querySelector('[data-wildlife-sighting-card-host]'),
|
||||
staleListener: () => staleListener,
|
||||
clears: () => clears,
|
||||
async click(kind = 'dot', target = initialRow) {
|
||||
picked =
|
||||
kind === 'icon'
|
||||
? { primitive: { id: `wildlife:${target.stableId}` } }
|
||||
: { id: `wildlife:${target.stableId}` };
|
||||
hit =
|
||||
kind === 'ambient photo card'
|
||||
? {
|
||||
sourceId: 'wildlife-sightings',
|
||||
entry: buildWildlifeThumbnailEntry(target, NOW, {
|
||||
select: selection.selectAndFocus,
|
||||
}),
|
||||
}
|
||||
: null;
|
||||
onClick({ position: { x: 50, y: 50 } });
|
||||
await settle();
|
||||
},
|
||||
async publish(next) {
|
||||
if (next) {
|
||||
state.rowById.set(next.stableId, next);
|
||||
if (state.selectedId === next.stableId) state.selectedRow = next;
|
||||
}
|
||||
selection.notify();
|
||||
await settle();
|
||||
},
|
||||
obstacle(selector, bounds) {
|
||||
const element = document.body.appendChild(document.createElement('div'));
|
||||
if (selector.startsWith('#')) element.id = selector.slice(1);
|
||||
else element.className = selector.slice(1);
|
||||
element.getBoundingClientRect = () => bounds;
|
||||
return element;
|
||||
},
|
||||
setPoint(next) {
|
||||
currentPoint = next;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('dot, icon and ambient photo clicks open one contained medium-photo card at the sighting', async (context) => {
|
||||
for (const kind of ['dot', 'icon', 'ambient photo card'])
|
||||
await context.test(kind, async (context) => {
|
||||
const f = fixture(context);
|
||||
await f.click(kind);
|
||||
const card = f.cardElement();
|
||||
const image = card.querySelector('img');
|
||||
assert.equal(f.state.selectedId, row.stableId);
|
||||
assert.equal(
|
||||
document.querySelector('dialog'),
|
||||
null,
|
||||
'there is no fullscreen or modal dialog',
|
||||
);
|
||||
assert.equal(image.src, square.replace('/square.', '/medium.'));
|
||||
assert.equal(image.referrerPolicy, 'no-referrer');
|
||||
assert.equal(card.querySelector('h2').textContent, row.commonName);
|
||||
assert.equal(card.querySelector('i').textContent, row.scientificName);
|
||||
assert.equal(card.querySelector('time').textContent, 'observed 1h ago');
|
||||
assert.ok(
|
||||
card.textContent.includes('© Synthetic Photographer · CC BY-SA'),
|
||||
);
|
||||
const link = card.querySelector('a');
|
||||
assert.equal(link.href, row.link);
|
||||
assert.equal(link.target, '_blank');
|
||||
assert.equal(link.rel, 'noopener noreferrer');
|
||||
assert.equal(
|
||||
link.getAttribute('aria-label'),
|
||||
`Open ${row.commonName} on iNaturalist`,
|
||||
);
|
||||
assert.equal(
|
||||
link.querySelector('.wildlife-sighting-card-source').textContent,
|
||||
'iNaturalist ↗',
|
||||
);
|
||||
assert.ok(
|
||||
link.contains(image),
|
||||
'the photograph and text are one external action',
|
||||
);
|
||||
assert.equal(f.flights.length, 1);
|
||||
assert.equal(f.flights[0].kind, 'sighting');
|
||||
assert.deepEqual(
|
||||
f.flights[0].position,
|
||||
f.state.positions.get(row.stableId),
|
||||
);
|
||||
assert.equal(f.pans.length, 0);
|
||||
assert.equal(
|
||||
f.preRender.size(),
|
||||
0,
|
||||
'an idle card installs no frame work',
|
||||
);
|
||||
let decoded;
|
||||
image.decode = () =>
|
||||
new Promise((resolve) => {
|
||||
decoded = resolve;
|
||||
});
|
||||
image.dispatchEvent(new Event('load'));
|
||||
await settle();
|
||||
assert.equal(
|
||||
image.classList.contains('loaded'),
|
||||
false,
|
||||
'a request alone does not expose an empty frame',
|
||||
);
|
||||
decoded();
|
||||
await settle();
|
||||
assert.equal(
|
||||
image.classList.contains('loaded'),
|
||||
true,
|
||||
'the loaded medium photo is painted inside the card',
|
||||
);
|
||||
assert.equal(card.querySelector('[role=status]'), null);
|
||||
const style = readFileSync(
|
||||
new URL('./views/panels/WildlifeSightingCard.vue', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
assert.match(style, /object-fit: contain/);
|
||||
assert.match(style, /height: 180px/);
|
||||
});
|
||||
});
|
||||
|
||||
test('missing, restricted, obscured and Acartia photos all use the same compact text card', async (context) => {
|
||||
for (const [label, extra] of [
|
||||
['missing', { photo: null }],
|
||||
['restricted', { photo: { ...row.photo, licence: 'cc-by-nd' } }],
|
||||
[
|
||||
'untrusted',
|
||||
{ photo: { ...row.photo, square: 'https://other.example/square.jpg' } },
|
||||
],
|
||||
['uncredited', { photo: { ...row.photo, attribution: '' } }],
|
||||
['obscured', { obscured: true }],
|
||||
[
|
||||
'Acartia',
|
||||
{
|
||||
origin: 'acartia',
|
||||
stableId: 'acartia:456',
|
||||
provider: { name: 'Synthetic network' },
|
||||
link: 'https://acartia.io',
|
||||
},
|
||||
],
|
||||
])
|
||||
await context.test(label, async (context) => {
|
||||
const f = fixture(context, { ...row, ...extra });
|
||||
await f.click();
|
||||
const card = f.cardElement();
|
||||
assert.equal(card.querySelector('img'), null);
|
||||
assert.equal(card.querySelector('[role=status]'), null);
|
||||
assert.equal(card.querySelector('h2').textContent, row.commonName);
|
||||
assert.equal(card.querySelector('i').textContent, row.scientificName);
|
||||
assert.equal(document.querySelector('dialog'), null);
|
||||
if (extra.obscured) {
|
||||
assert.doesNotMatch(card.textContent, /ago|Photographer/);
|
||||
assert.ok(
|
||||
card.textContent.includes('Location obscured to a 0.2° cell'),
|
||||
);
|
||||
assert.equal(
|
||||
card.querySelector('time').getAttribute('datetime'),
|
||||
row.observedOn,
|
||||
);
|
||||
}
|
||||
if (extra.origin === 'acartia') {
|
||||
assert.ok(card.textContent.includes('seen 1h ago'));
|
||||
assert.ok(card.textContent.includes('Reported by Synthetic network'));
|
||||
assert.ok(
|
||||
card.textContent.includes('Acartia · CC BY 4.0 · Salish Sea'),
|
||||
);
|
||||
assert.ok(card.querySelector('a[href="https://www.bewhalewise.org"]'));
|
||||
assert.equal(
|
||||
card.querySelector('a').getAttribute('aria-label'),
|
||||
`Open ${row.commonName} on Acartia`,
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test('an Acartia card labels only the Acartia site as Acartia', async (context) => {
|
||||
for (const link of [
|
||||
'https://provider.example/photos/synthetic.jpg',
|
||||
'https://acartia.io.attacker.example/',
|
||||
'https://acartia.io/',
|
||||
])
|
||||
await context.test(link, async (context) => {
|
||||
const f = fixture(context, {
|
||||
...row,
|
||||
origin: 'acartia',
|
||||
stableId: 'acartia:456',
|
||||
provider: { name: 'Synthetic network' },
|
||||
link,
|
||||
});
|
||||
await f.click();
|
||||
const card = f.cardElement();
|
||||
const hrefs = [...card.querySelectorAll('a')].map((a) =>
|
||||
a.getAttribute('href'),
|
||||
);
|
||||
assert.deepEqual(hrefs, [
|
||||
'https://acartia.io/',
|
||||
'https://www.bewhalewise.org',
|
||||
]);
|
||||
assert.equal(
|
||||
card.querySelector('.wildlife-sighting-card-source').textContent,
|
||||
'Acartia ↗',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test('safe placements near each viewport edge exclude actual HUD, toolbar and rail rects', () => {
|
||||
const obstacles = [
|
||||
rect(0, 0, 260, 160),
|
||||
rect(450, 0, 300, 80),
|
||||
rect(1050, 200, 150, 500),
|
||||
rect(0, 760, 300, 140),
|
||||
];
|
||||
const safe = { bounds: rect(6, 6, 1188, 888), obstacles };
|
||||
for (const point of [
|
||||
{ x: 7, y: 450 },
|
||||
{ x: 1193, y: 750 },
|
||||
{ x: 850, y: 7 },
|
||||
{ x: 600, y: 893 },
|
||||
]) {
|
||||
const result = placeWildlifeSightingCard(
|
||||
point,
|
||||
{ width: 258, height: 300 },
|
||||
safe,
|
||||
);
|
||||
assert.ok(result);
|
||||
assert.deepEqual(result.pan, { x: 0, y: 0 });
|
||||
assert.ok(
|
||||
result.left >= safe.bounds.left && result.right <= safe.bounds.right,
|
||||
);
|
||||
assert.ok(
|
||||
result.top >= safe.bounds.top && result.bottom <= safe.bounds.bottom,
|
||||
);
|
||||
assert.ok(
|
||||
obstacles.every(
|
||||
(r) =>
|
||||
!(
|
||||
result.left < r.right &&
|
||||
result.right > r.left &&
|
||||
result.top < r.bottom &&
|
||||
result.bottom > r.top
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('a selected dot flies to its true position and its card pans clear of chrome', async (context) => {
|
||||
const f = fixture(context, row, { x: 100, y: 100 });
|
||||
const hud = f.obstacle('.hud-top-left', rect(0, 0, 260, 160));
|
||||
f.obstacle('#right-context-rail', rect(1040, 200, 160, 700));
|
||||
f.windowRef.matchMedia = () => ({ matches: true });
|
||||
await f.click();
|
||||
assert.equal(f.pans.length, 1);
|
||||
assert.equal(f.pans[0].reduced, true);
|
||||
assert.deepEqual(
|
||||
f.pans[0].to,
|
||||
{ x: 100, y: 178 },
|
||||
'nearest clear point follows the measured HUD bottom',
|
||||
);
|
||||
const safe = readWildlifeCardSafeArea({
|
||||
documentRef: document,
|
||||
viewer: f.viewer,
|
||||
windowRef: f.windowRef,
|
||||
});
|
||||
assert.equal(
|
||||
safe.obstacles[0].bottom,
|
||||
hud.getBoundingClientRect().bottom + 6,
|
||||
);
|
||||
assert.equal(f.flights.length, 1);
|
||||
assert.deepEqual(f.flights[0].position, f.state.positions.get(row.stableId));
|
||||
f.moveEnd.emit();
|
||||
await settle();
|
||||
assert.equal(f.pans.length, 1);
|
||||
f.layer.clearSightingSelection();
|
||||
await settle();
|
||||
f.setPoint({ x: -20, y: 400 });
|
||||
await f.click();
|
||||
assert.equal(f.pans.length, 2);
|
||||
assert.deepEqual(f.pans[1].to, { x: 18, y: 400 });
|
||||
});
|
||||
|
||||
test('the camera correction preserves altitude and orientation and honors reduced motion', () => {
|
||||
const flights = [];
|
||||
const camera = {
|
||||
positionWC: Cesium.Cartesian3.fromDegrees(0, 0, 250_000),
|
||||
positionCartographic: { height: 250_000 },
|
||||
heading: 0.2,
|
||||
pitch: -1.2,
|
||||
roll: 0.1,
|
||||
pickEllipsoid: (p) => Cesium.Cartesian3.fromDegrees(p.x / 100, p.y / 100),
|
||||
flyTo: (value) => flights.push(value),
|
||||
};
|
||||
const viewer = {
|
||||
camera,
|
||||
scene: {
|
||||
canvas: { getBoundingClientRect: () => rect(0, 0, 1200, 900) },
|
||||
globe: { ellipsoid: Cesium.Ellipsoid.WGS84 },
|
||||
},
|
||||
};
|
||||
for (const reduced of [false, true]) {
|
||||
assert.equal(
|
||||
panWildlifeSighting(viewer, { x: 10, y: 10 }, { x: 30, y: 50 }, reduced),
|
||||
true,
|
||||
);
|
||||
const flight = flights.at(-1);
|
||||
assert.ok(
|
||||
Math.abs(
|
||||
Cesium.Cartographic.fromCartesian(flight.destination).height - 250_000,
|
||||
) < 0.001,
|
||||
);
|
||||
assert.deepEqual(flight.orientation, {
|
||||
heading: 0.2,
|
||||
pitch: -1.2,
|
||||
roll: 0.1,
|
||||
});
|
||||
assert.equal(flight.duration, reduced ? 0 : 0.22);
|
||||
}
|
||||
});
|
||||
|
||||
test('the browser click that follows a globe selection does not close the card it opened', async (context) => {
|
||||
const f = fixture(context);
|
||||
await f.click();
|
||||
assert.ok(f.cardElement(), 'the globe click opened the card');
|
||||
assert.equal(
|
||||
document.activeElement,
|
||||
f.cardElement(),
|
||||
'focus lands on the card, not as a ring on its close button',
|
||||
);
|
||||
// Cesium selects on pointer-up; the DOM click event lands on the canvas
|
||||
// afterwards and must not count as an outside click.
|
||||
f.canvas.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||
await settle();
|
||||
assert.ok(f.cardElement(), 'the card stays open');
|
||||
assert.equal(f.clears(), 0);
|
||||
document.body.click();
|
||||
await settle();
|
||||
assert.equal(f.cardElement(), null, 'a real outside click still closes it');
|
||||
});
|
||||
|
||||
test('one card at a time, Escape, outside clicks and close all clear the selection', async (context) => {
|
||||
const f = fixture(context);
|
||||
await f.click();
|
||||
const second = {
|
||||
...row,
|
||||
stableId: 'inat:789',
|
||||
commonName: 'Another synthetic bird',
|
||||
};
|
||||
f.state.rowById.set(second.stableId, second);
|
||||
await f.click('dot', second);
|
||||
assert.equal(
|
||||
document.querySelectorAll('[data-wildlife-sighting-card]').length,
|
||||
1,
|
||||
);
|
||||
assert.equal(
|
||||
f.cardElement().querySelector('h2').textContent,
|
||||
second.commonName,
|
||||
);
|
||||
for (const close of ['Escape', 'outside', 'button']) {
|
||||
if (close === 'Escape')
|
||||
document.dispatchEvent(
|
||||
new KeyboardEvent('keydown', {
|
||||
key: 'Escape',
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
if (close === 'outside') document.body.click();
|
||||
if (close === 'button') f.cardElement().querySelector('button').click();
|
||||
await settle();
|
||||
assert.equal(f.cardElement(), null);
|
||||
assert.equal(f.state.selectedId, null);
|
||||
assert.deepEqual(f.overlays.get('wildlife-sightings-selected'), []);
|
||||
assert.equal(document.activeElement, f.opener);
|
||||
await f.click();
|
||||
}
|
||||
assert.equal(f.clears(), 3);
|
||||
});
|
||||
|
||||
test('camera movement repositions the same card and removes frame work at rest', async (context) => {
|
||||
const f = fixture(context);
|
||||
await f.click();
|
||||
const card = f.cardElement();
|
||||
const before = f.host().style.left;
|
||||
f.moveStart.emit();
|
||||
assert.equal(f.preRender.size(), 1);
|
||||
f.setPoint({ x: 800, y: 450 });
|
||||
f.preRender.emit();
|
||||
assert.equal(f.cardElement(), card);
|
||||
assert.notEqual(f.host().style.left, before);
|
||||
f.moveEnd.emit();
|
||||
assert.equal(f.preRender.size(), 0);
|
||||
await f.publish({ ...row, commonName: 'Updated synthetic bird' });
|
||||
assert.equal(f.cardElement(), card);
|
||||
assert.equal(card.querySelector('h2').textContent, 'Updated synthetic bird');
|
||||
f.state.rowById.delete(row.stableId);
|
||||
await f.publish(null);
|
||||
assert.equal(
|
||||
f.cardElement(),
|
||||
card,
|
||||
'a refreshed sample cannot close the selected card',
|
||||
);
|
||||
f.layer.clearSightingSelection();
|
||||
await settle();
|
||||
assert.equal(f.cardElement(), null);
|
||||
});
|
||||
|
||||
test('replacement photo loads cannot expose the previous image and failures retain the text card', async (context) => {
|
||||
const f = fixture(context);
|
||||
await f.click();
|
||||
const previous = f.cardElement().querySelector('img');
|
||||
let decoded;
|
||||
previous.decode = () =>
|
||||
new Promise((resolve) => {
|
||||
decoded = resolve;
|
||||
});
|
||||
previous.dispatchEvent(new Event('load'));
|
||||
await f.publish({
|
||||
...row,
|
||||
photo: { ...row.photo, square: square.replace('/456/', '/789/') },
|
||||
});
|
||||
const current = f.cardElement().querySelector('img');
|
||||
decoded();
|
||||
await settle();
|
||||
assert.equal(current.classList.contains('loaded'), false);
|
||||
current.dispatchEvent(new Event('error'));
|
||||
await settle();
|
||||
assert.equal(
|
||||
f.cardElement().querySelector('[role=status]').textContent,
|
||||
'Photo unavailable',
|
||||
);
|
||||
assert.equal(current.style.display, 'none');
|
||||
assert.equal(f.cardElement().querySelector('a').href, row.link);
|
||||
});
|
||||
|
||||
test('teardown removes subscriptions, placement listeners and host, and ignores stale notifications', async (context) => {
|
||||
const f = fixture(context);
|
||||
await f.click();
|
||||
f.moveStart.emit();
|
||||
const stale = f.staleListener();
|
||||
f.card.destroy();
|
||||
assert.equal(f.cardElement(), null);
|
||||
assert.equal(f.host(), null);
|
||||
assert.equal(f.subscriptions.size, 0);
|
||||
assert.equal(f.preRender.size(), 0);
|
||||
stale(row);
|
||||
await f.click();
|
||||
assert.equal(f.cardElement(), null);
|
||||
assert.equal(document.activeElement, f.opener);
|
||||
});
|
||||
|
||||
test('locale changes translate the card without replacing the image or credit', async (context) => {
|
||||
const before = getLocale();
|
||||
context.after(() => setLocale(before));
|
||||
const f = fixture(context);
|
||||
await f.click();
|
||||
const card = f.cardElement();
|
||||
const image = card.querySelector('img');
|
||||
for (const locale of LOCALES) {
|
||||
setLocale(locale);
|
||||
await settle();
|
||||
assert.equal(f.cardElement(), card);
|
||||
assert.equal(card.querySelector('img'), image);
|
||||
assert.equal(
|
||||
card.querySelector('button').getAttribute('aria-label'),
|
||||
t('Close sighting'),
|
||||
);
|
||||
assert.ok(card.textContent.includes('© Synthetic Photographer · CC BY-SA'));
|
||||
}
|
||||
});
|
||||
|
||||
test('date-only and unsafe-link rows remain readable, and no sighting rail or lightbox is shipped', async (context) => {
|
||||
const f = fixture(context, {
|
||||
...row,
|
||||
observedAt: null,
|
||||
photo: null,
|
||||
link: 'javascript:alert(1)',
|
||||
});
|
||||
await f.click();
|
||||
assert.equal(f.cardElement().querySelector('a'), null);
|
||||
assert.equal(
|
||||
f.cardElement().querySelector('time').getAttribute('datetime'),
|
||||
row.observedOn,
|
||||
);
|
||||
assert.equal(PANEL_RAIL_ITEMS['wildlife-sighting-panel'], undefined);
|
||||
assert.equal(sheetForPanelId('wildlife-sighting-panel'), null);
|
||||
const source = readFileSync(
|
||||
new URL('./wildlifeSightingCard.js', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
assert.doesNotMatch(
|
||||
source,
|
||||
/Lightbox|showModal|requestAnimationFrame|setInterval/,
|
||||
);
|
||||
});
|
||||
|
||||
test('WHALES cards retain compact whale guidance outside the observation action', async (context) => {
|
||||
const f = fixture(context);
|
||||
f.layer.getParams = () => ({ taxa: 'whales' });
|
||||
await f.click();
|
||||
const guidance = f
|
||||
.cardElement()
|
||||
.querySelector('a[href="https://www.bewhalewise.org"]');
|
||||
assert.equal(guidance.textContent, 'Be Whale Wise');
|
||||
assert.equal(
|
||||
guidance.parentElement.closest('a'),
|
||||
null,
|
||||
'the external guidance link never nests inside the observation action',
|
||||
);
|
||||
});
|
||||
|
||||
test('opening during camera motion tracks the card and closing stops frame work immediately', async (context) => {
|
||||
const f = fixture(context);
|
||||
f.moveStart.emit();
|
||||
assert.equal(f.preRender.size(), 0);
|
||||
await f.click();
|
||||
assert.equal(f.preRender.size(), 1);
|
||||
f.layer.clearSightingSelection();
|
||||
await settle();
|
||||
assert.equal(f.preRender.size(), 0);
|
||||
});
|
||||
|
||||
test('newly mounted chrome repositions the open card without camera events or idle text work', async (context) => {
|
||||
const observers = [];
|
||||
class MutationObserver {
|
||||
constructor(callback) {
|
||||
this.callback = callback;
|
||||
this.targets = [];
|
||||
observers.push(this);
|
||||
}
|
||||
observe(target, options) {
|
||||
this.targets.push({ target, options });
|
||||
}
|
||||
disconnect() {
|
||||
this.targets = [];
|
||||
}
|
||||
}
|
||||
const f = fixture(context, row, { x: 600, y: 450 }, { MutationObserver });
|
||||
await f.click();
|
||||
const structural = observers.find((observer) =>
|
||||
observer.targets.some(
|
||||
({ target, options }) =>
|
||||
target === document.body && options.childList && options.subtree,
|
||||
),
|
||||
);
|
||||
assert.ok(
|
||||
structural,
|
||||
'structural observation exists only while a card is open',
|
||||
);
|
||||
const original = f.cardElement();
|
||||
const before = f.host().style.top;
|
||||
const hudWrapper = document.body.appendChild(document.createElement('div'));
|
||||
const hud = hudWrapper.appendChild(document.createElement('div'));
|
||||
hud.className = 'hud-top-left';
|
||||
hud.getBoundingClientRect = () => rect(500, 350, 200, 200);
|
||||
structural.callback([{ addedNodes: [hudWrapper], removedNodes: [] }]);
|
||||
await settle();
|
||||
assert.equal(
|
||||
f.pans.length,
|
||||
1,
|
||||
'chrome newly covering the dot triggers one minimal pan',
|
||||
);
|
||||
assert.equal(f.cardElement(), original);
|
||||
assert.notEqual(f.host().style.top, before);
|
||||
assert.equal(f.preRender.size(), 0);
|
||||
const placed = rect(
|
||||
Number.parseFloat(f.host().style.left),
|
||||
Number.parseFloat(f.host().style.top),
|
||||
258,
|
||||
300,
|
||||
);
|
||||
assert.ok(
|
||||
placed.right <= 494 ||
|
||||
placed.left >= 706 ||
|
||||
placed.bottom <= 344 ||
|
||||
placed.top >= 556,
|
||||
'the card clears the measured HUD rect',
|
||||
);
|
||||
const afterChrome = f.projections();
|
||||
// The observer ignores text nodes, ordinary clock wrappers and the card's
|
||||
// own image/caption patches even though body observation sees their records.
|
||||
const clock = hud.appendChild(document.createElement('span'));
|
||||
const text = clock.appendChild(document.createTextNode('13:00:01'));
|
||||
structural.callback([
|
||||
{
|
||||
addedNodes: [clock, text, f.cardElement().querySelector('img')],
|
||||
removedNodes: [],
|
||||
},
|
||||
]);
|
||||
assert.equal(f.projections(), afterChrome);
|
||||
f.layer.clearSightingSelection();
|
||||
await settle();
|
||||
assert.equal(
|
||||
structural.targets.length,
|
||||
0,
|
||||
'closing disconnects structural observation',
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,274 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { WORLD_OVERLAY_OCCLUDER_SELECTORS } from '../overlays/worldOverlayChrome.js';
|
||||
|
||||
// DOM cards also avoid the HUD edges and responsive sheet containers.
|
||||
export const WILDLIFE_CARD_CHROME_SELECTORS = Object.freeze([
|
||||
...WORLD_OVERLAY_OCCLUDER_SELECTORS,
|
||||
'.hud-left-edge',
|
||||
'.hud-right-edge',
|
||||
'#right-panel-stack',
|
||||
'.gev-panel-rail',
|
||||
'#location-bar',
|
||||
'#control-panel',
|
||||
'#param-slider-panel',
|
||||
'#cockpit-hud .cockpit-topline',
|
||||
'[data-mobile-sheet]',
|
||||
]);
|
||||
const GAP = 12;
|
||||
const EDGE = 6;
|
||||
export const WILDLIFE_SELECTED_CARD_WIDTH = 258;
|
||||
|
||||
const overlaps = (a, b) =>
|
||||
a.left < b.right && a.right > b.left && a.top < b.bottom && a.bottom > b.top;
|
||||
const contains = (r, p) =>
|
||||
p.x >= r.left && p.x <= r.right && p.y >= r.top && p.y <= r.bottom;
|
||||
const clamp = (value, low, high) => Math.max(low, Math.min(high, value));
|
||||
const rectAt = (left, top, width, height) => ({
|
||||
left,
|
||||
top,
|
||||
right: left + width,
|
||||
bottom: top + height,
|
||||
width,
|
||||
height,
|
||||
});
|
||||
|
||||
/** Read visible chrome rectangles inside the viewer's usable screen area. */
|
||||
export function readWildlifeCardSafeArea({
|
||||
documentRef,
|
||||
viewer,
|
||||
windowRef = globalThis.window,
|
||||
}) {
|
||||
const canvasRect = viewer?.scene?.canvas?.getBoundingClientRect?.();
|
||||
const width =
|
||||
windowRef?.innerWidth || documentRef.documentElement.clientWidth;
|
||||
const height =
|
||||
windowRef?.innerHeight || documentRef.documentElement.clientHeight;
|
||||
const left = Math.max(0, canvasRect?.left || 0) + EDGE;
|
||||
const top = Math.max(0, canvasRect?.top || 0) + EDGE;
|
||||
const right =
|
||||
Math.min(width, canvasRect?.width > 0 ? canvasRect.right : width) - EDGE;
|
||||
const bottom =
|
||||
Math.min(height, canvasRect?.height > 0 ? canvasRect.bottom : height) -
|
||||
EDGE;
|
||||
const bounds = rectAt(
|
||||
left,
|
||||
top,
|
||||
Math.max(0, right - left),
|
||||
Math.max(0, bottom - top),
|
||||
);
|
||||
const obstacles = [];
|
||||
const elements = [
|
||||
...documentRef.querySelectorAll(WILDLIFE_CARD_CHROME_SELECTORS.join(',')),
|
||||
];
|
||||
for (const element of elements) {
|
||||
let hidden = false;
|
||||
for (
|
||||
let node = element;
|
||||
node && node !== documentRef.body;
|
||||
node = node.parentElement
|
||||
) {
|
||||
const style = windowRef?.getComputedStyle?.(node);
|
||||
if (
|
||||
node.hidden ||
|
||||
style?.display === 'none' ||
|
||||
style?.visibility === 'hidden' ||
|
||||
style?.opacity === '0'
|
||||
) {
|
||||
hidden = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (hidden) continue;
|
||||
const rect = element.getBoundingClientRect();
|
||||
if (!(rect.width > 0 && rect.height > 0) || !overlaps(rect, bounds))
|
||||
continue;
|
||||
obstacles.push(
|
||||
rectAt(
|
||||
rect.left - EDGE,
|
||||
rect.top - EDGE,
|
||||
rect.width + EDGE * 2,
|
||||
rect.height + EDGE * 2,
|
||||
),
|
||||
);
|
||||
}
|
||||
return { bounds, obstacles, elements };
|
||||
}
|
||||
|
||||
function nearestSafeAnchor(point, { bounds, obstacles }) {
|
||||
const xs = [clamp(point.x, bounds.left + GAP, bounds.right - GAP)];
|
||||
const ys = [clamp(point.y, bounds.top + GAP, bounds.bottom - GAP)];
|
||||
for (const rect of obstacles) {
|
||||
xs.push(
|
||||
clamp(rect.left - GAP, bounds.left + GAP, bounds.right - GAP),
|
||||
clamp(rect.right + GAP, bounds.left + GAP, bounds.right - GAP),
|
||||
);
|
||||
ys.push(
|
||||
clamp(rect.top - GAP, bounds.top + GAP, bounds.bottom - GAP),
|
||||
clamp(rect.bottom + GAP, bounds.top + GAP, bounds.bottom - GAP),
|
||||
);
|
||||
}
|
||||
return (
|
||||
xs
|
||||
.flatMap((x) => ys.map((y) => ({ x, y })))
|
||||
.filter(
|
||||
(p) => contains(bounds, p) && !obstacles.some((r) => contains(r, p)),
|
||||
)
|
||||
.sort(
|
||||
(a, b) =>
|
||||
Math.hypot(a.x - point.x, a.y - point.y) -
|
||||
Math.hypot(b.x - point.x, b.y - point.y),
|
||||
)[0] || null
|
||||
);
|
||||
}
|
||||
|
||||
/** Four anchored placements, clamped along their free axis. Chrome is a set of
|
||||
* actual DOM rectangles, so corner HUDs do not erase otherwise clear lanes. */
|
||||
export function placeWildlifeSightingCard(point, size, safeArea) {
|
||||
const { bounds, obstacles } = safeArea;
|
||||
const anchor =
|
||||
contains(bounds, point) && !obstacles.some((r) => contains(r, point))
|
||||
? point
|
||||
: nearestSafeAnchor(point, safeArea);
|
||||
if (!anchor) return null;
|
||||
const width = Math.min(size.width, bounds.width);
|
||||
const height = Math.min(size.height, bounds.height);
|
||||
const centeredX = clamp(
|
||||
anchor.x - width / 2,
|
||||
bounds.left,
|
||||
bounds.right - width,
|
||||
);
|
||||
const centeredY = clamp(
|
||||
anchor.y - height / 2,
|
||||
bounds.top,
|
||||
bounds.bottom - height,
|
||||
);
|
||||
const candidates = [
|
||||
{
|
||||
placement: 'above',
|
||||
...rectAt(centeredX, anchor.y - GAP - height, width, height),
|
||||
},
|
||||
{ placement: 'below', ...rectAt(centeredX, anchor.y + GAP, width, height) },
|
||||
{ placement: 'right', ...rectAt(anchor.x + GAP, centeredY, width, height) },
|
||||
{
|
||||
placement: 'left',
|
||||
...rectAt(anchor.x - GAP - width, centeredY, width, height),
|
||||
},
|
||||
];
|
||||
const fits = (rect) =>
|
||||
rect.left >= bounds.left &&
|
||||
rect.right <= bounds.right &&
|
||||
rect.top >= bounds.top &&
|
||||
rect.bottom <= bounds.bottom &&
|
||||
!obstacles.some((r) => overlaps(rect, r));
|
||||
let chosen = candidates.find(fits);
|
||||
if (!chosen) {
|
||||
// Crowded chrome may require sliding a side placement farther from its
|
||||
// anchor. Search only obstacle/bounds edges; no pixels or idle frame loop.
|
||||
const xs = [bounds.left, bounds.right - width, centeredX];
|
||||
const ys = [bounds.top, bounds.bottom - height, centeredY];
|
||||
for (const r of obstacles) {
|
||||
xs.push(r.left - width, r.right);
|
||||
ys.push(r.top - height, r.bottom);
|
||||
}
|
||||
const alternatives = xs
|
||||
.flatMap((x) =>
|
||||
ys.map((y) => ({
|
||||
placement:
|
||||
y + height <= anchor.y
|
||||
? 'above'
|
||||
: y >= anchor.y
|
||||
? 'below'
|
||||
: x >= anchor.x
|
||||
? 'right'
|
||||
: 'left',
|
||||
...rectAt(x, y, width, height),
|
||||
})),
|
||||
)
|
||||
.filter((r) => fits(r) && !contains(r, anchor));
|
||||
alternatives.sort(
|
||||
(a, b) =>
|
||||
Math.hypot(
|
||||
clamp(anchor.x, a.left, a.right) - anchor.x,
|
||||
clamp(anchor.y, a.top, a.bottom) - anchor.y,
|
||||
) -
|
||||
Math.hypot(
|
||||
clamp(anchor.x, b.left, b.right) - anchor.x,
|
||||
clamp(anchor.y, b.top, b.bottom) - anchor.y,
|
||||
),
|
||||
);
|
||||
chosen = alternatives[0];
|
||||
}
|
||||
return chosen
|
||||
? {
|
||||
...chosen,
|
||||
anchor,
|
||||
pan: { x: anchor.x - point.x, y: anchor.y - point.y },
|
||||
}
|
||||
: null;
|
||||
}
|
||||
|
||||
/** Project a front-side sighting into viewport coordinates. */
|
||||
export function projectWildlifeSighting(viewer, row, layer) {
|
||||
if (
|
||||
!viewer?.scene ||
|
||||
!Number.isFinite(row?.lat) ||
|
||||
!Number.isFinite(row?.lon)
|
||||
)
|
||||
return null;
|
||||
const position =
|
||||
layer?.getSightingPosition?.(row.stableId) ||
|
||||
Cesium.Cartesian3.fromDegrees(row.lon, row.lat);
|
||||
const ellipsoid = viewer.scene.globe?.ellipsoid || Cesium.Ellipsoid.WGS84;
|
||||
if (
|
||||
viewer.camera?.positionWC &&
|
||||
new Cesium.EllipsoidalOccluder(
|
||||
ellipsoid,
|
||||
viewer.camera.positionWC,
|
||||
).isPointVisible(position) !== true
|
||||
)
|
||||
return null;
|
||||
const point = Cesium.SceneTransforms.worldToWindowCoordinates(
|
||||
viewer.scene,
|
||||
position,
|
||||
);
|
||||
if (!point) return null;
|
||||
const rect = viewer.scene.canvas?.getBoundingClientRect?.();
|
||||
return { x: point.x + (rect?.left || 0), y: point.y + (rect?.top || 0) };
|
||||
}
|
||||
|
||||
/** Translate the camera by the smallest screen correction and preserve its
|
||||
* altitude/orientation. A card must never zoom merely to reveal its anchor. */
|
||||
export function panWildlifeSighting(viewer, from, to, reducedMotion = false) {
|
||||
const camera = viewer?.camera;
|
||||
if (!camera?.pickEllipsoid || !camera.flyTo) return false;
|
||||
const rect = viewer.scene.canvas.getBoundingClientRect();
|
||||
const local = (p) => new Cesium.Cartesian2(p.x - rect.left, p.y - rect.top);
|
||||
const ellipsoid = viewer.scene.globe?.ellipsoid || Cesium.Ellipsoid.WGS84;
|
||||
const start = camera.pickEllipsoid(local(from), ellipsoid);
|
||||
const finish = camera.pickEllipsoid(local(to), ellipsoid);
|
||||
if (!start || !finish || !camera.positionWC) return false;
|
||||
const delta = Cesium.Cartesian3.subtract(
|
||||
start,
|
||||
finish,
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
const destination = Cesium.Cartesian3.add(
|
||||
camera.positionWC,
|
||||
delta,
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
const cartographic = ellipsoid.cartesianToCartographic(destination);
|
||||
if (!cartographic) return false;
|
||||
cartographic.height = camera.positionCartographic.height;
|
||||
camera.flyTo({
|
||||
destination: ellipsoid.cartographicToCartesian(cartographic),
|
||||
orientation: {
|
||||
heading: camera.heading,
|
||||
pitch: camera.pitch,
|
||||
roll: camera.roll,
|
||||
},
|
||||
duration: reducedMotion ? 0 : 0.22,
|
||||
easingFunction: Cesium.EasingFunction.QUADRATIC_OUT,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
Reference in new issue
Block a user