mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 08:12:24 +00:00
Merge upstream/main into fix/taiwan-highway-cctv-fallback
This commit is contained in:
commit
cc3d390911
474 files changed
+68164
-2182
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;
|
||||
@@ -1792,6 +1807,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.
|
||||
|
||||
@@ -4,6 +4,19 @@ import {
|
||||
contextModeWord,
|
||||
} from '../contextModePolicy.js';
|
||||
|
||||
/** Why a Space Missions entry failed: its mission index never loaded, and
|
||||
* the error is no older than `since` (an earlier attempt's is not the cause). */
|
||||
export function spaceMissionsIndexFailure(dataManager, since = 0) {
|
||||
const stats = dataManager?.layers
|
||||
?.get('rocket-launches')
|
||||
?.module?.getStats?.();
|
||||
return stats?.error && stats.lastUpdate == null && stats.errorAt >= since
|
||||
? t(
|
||||
'Space Missions unavailable: the mission index could not load. Try again later.',
|
||||
)
|
||||
: null;
|
||||
}
|
||||
|
||||
export async function _runUserFacingContextAction(
|
||||
operation,
|
||||
message = t('Context could not restore every layer; try again'),
|
||||
@@ -19,7 +32,10 @@ export async function _runUserFacingContextAction(
|
||||
onFailure: (error) => {
|
||||
if (this.destroyed) return;
|
||||
console.warn('[Context] user-facing transition failed', error);
|
||||
this.showToast(localizedMessage || message);
|
||||
this.showToast(
|
||||
localizedMessage ||
|
||||
(typeof message === 'function' ? message() : message),
|
||||
);
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { spaceMissionsIndexFailure } from './contextActions.js';
|
||||
import { shouldExpandGlobalContextPanel } from '../rightRailPolicy.js';
|
||||
|
||||
export function _initGlobalContextPanel() {
|
||||
@@ -59,12 +60,15 @@ export function _initGlobalContextPanel() {
|
||||
const nextMode =
|
||||
this._contextMode === 'space-missions' ? null : 'space-missions';
|
||||
this._claimContextVisualAuthority();
|
||||
const startedAt = Date.now();
|
||||
void this._runUserFacingContextAction(
|
||||
(notificationToken) =>
|
||||
this._selectContextMode(nextMode, { notificationToken }),
|
||||
t(
|
||||
'Space Missions could not complete the requested transition; try again',
|
||||
),
|
||||
() =>
|
||||
(nextMode && spaceMissionsIndexFailure(this._dataManager, startedAt)) ||
|
||||
t(
|
||||
'Space Missions could not complete the requested transition; try again',
|
||||
),
|
||||
).then((succeeded) => {
|
||||
if (
|
||||
!this.destroyed &&
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { t, translateKnown } from '../i18n/index.js';
|
||||
import {
|
||||
SPACE_MISSIONS_LAYER_BLOCK_REASON,
|
||||
cockpitEntryAllowed,
|
||||
isExplicitUserIntentOrigin,
|
||||
parseContextLayerBlockReason,
|
||||
recordContextRestoreExplicitChange,
|
||||
@@ -10,6 +9,7 @@ import {
|
||||
spaceMissionEntryCancellationDisposition,
|
||||
} from '../contextModePolicy.js';
|
||||
import { localizeLayerName } from './layerNames.js';
|
||||
import { spaceMissionsIndexFailure } from './contextActions.js';
|
||||
|
||||
/**
|
||||
* A blocked-visibility reason in the UI language. Reasons stay English (voice
|
||||
@@ -121,10 +121,14 @@ export function _handleContextLayerChange(change) {
|
||||
return;
|
||||
}
|
||||
if (change?.type === 'visibility-failed') {
|
||||
const failureMessage = t('{layerId} could not {action} cleanly', {
|
||||
layerId: change.layerId,
|
||||
action: change.enabled ? t('start') : t('stop'),
|
||||
});
|
||||
const failureMessage =
|
||||
(change.layerId === 'rocket-launches' &&
|
||||
change.enabled &&
|
||||
spaceMissionsIndexFailure(this._dataManager)) ||
|
||||
t('{layerId} could not {action} cleanly', {
|
||||
layerId: change.layerId,
|
||||
action: change.enabled ? t('start') : t('stop'),
|
||||
});
|
||||
// A failed direct Context-shell START has already had its siblings
|
||||
// cleared by the visibility guard. Wait outside the synchronous manager
|
||||
// notification for this queue to settle, then reconcile the complete
|
||||
@@ -245,15 +249,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 });
|
||||
|
||||
@@ -117,3 +117,18 @@ test('a radio group moves from the focused option, an arrows group from the sele
|
||||
assert.deepEqual(arrows.emitted('update:modelValue'), [['a']]);
|
||||
arrows.unmount();
|
||||
});
|
||||
|
||||
test("an option's own tip wins; an icon option without one is titled by its label", () => {
|
||||
const wrapper = mountGroup({
|
||||
options: [
|
||||
{ value: 'a', label: 'Alpha', attrs: { title: 'Alpha tip' } },
|
||||
{ value: 'b', label: 'Beta', icon: 'star' },
|
||||
{ value: 'c', label: 'Gamma' },
|
||||
],
|
||||
});
|
||||
const titles = wrapper
|
||||
.findAll('button')
|
||||
.map((b) => b.attributes('title') ?? null);
|
||||
assert.deepEqual(titles, ['Alpha tip', 'Beta', null]);
|
||||
wrapper.unmount();
|
||||
});
|
||||
@@ -8,7 +8,8 @@ import { computed } from 'vue';
|
||||
// End). Each option may carry `attrs` (an id, data attributes, a tip), and
|
||||
// Core's classes sit beside the kit's: `gev-segmented`, `gev-segment` and the
|
||||
// selected option's `activeClass`. An option with an `icon` shows the glyph,
|
||||
// and its label becomes the button's accessible name and tooltip.
|
||||
// and its label becomes the button's accessible name and tooltip, unless its
|
||||
// `attrs` carry a tip of their own.
|
||||
const props = defineProps({
|
||||
modelValue: { type: String, default: undefined },
|
||||
/** `{value, label, icon?, disabled?, attrs?}`, labels already translated. */
|
||||
@@ -119,7 +120,7 @@ function onKey(event) {
|
||||
]"
|
||||
:aria-checked="String(option.value === props.modelValue)"
|
||||
:aria-label="option.icon ? option.label : undefined"
|
||||
:title="option.icon ? option.label : undefined"
|
||||
:title="option.attrs?.title ?? (option.icon ? option.label : undefined)"
|
||||
:disabled="optionOff(option)"
|
||||
:tabindex="tabindex(index)"
|
||||
@click="choose(index)"
|
||||
|
||||
@@ -141,6 +141,12 @@ export class LayerBindings {
|
||||
});
|
||||
this._weatherShellModules.push(layer);
|
||||
}
|
||||
// Active Fires drapes its far-zoom heatmap on the same imagery host.
|
||||
const fires = this._dataManager?.layers?.get('local-firms')?.module;
|
||||
if (typeof fires?.attachShellServices === 'function') {
|
||||
fires.attachShellServices({ imageryHost: this.services.imageryHost });
|
||||
this._weatherShellModules.push(fires);
|
||||
}
|
||||
}
|
||||
|
||||
_persistAwarenessSelection(event, cleared = false) {
|
||||
|
||||
@@ -30,10 +30,13 @@ export const LAYER_NAME_KEYS = Object.freeze({
|
||||
'telegeography-submarine-cables': msg('Submarine Cables'),
|
||||
'local-firms': msg('FIRMS Active Fires'),
|
||||
'local-adsb': msg('Local ADS-B'),
|
||||
'osm-places': msg('OSM Places'),
|
||||
transit: msg('Transit'),
|
||||
'recent-imagery': msg('Recent Imagery'),
|
||||
'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'),
|
||||
@@ -139,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');
|
||||
}
|
||||
});
|
||||
+41
-6
@@ -61,6 +61,7 @@ const PANEL_GROUPS = [
|
||||
ids: [
|
||||
'alpr-cameras',
|
||||
'military-installations',
|
||||
'drone-airspace',
|
||||
'local-datacenters',
|
||||
'telegeography-submarine-cables',
|
||||
'local-dams',
|
||||
@@ -79,6 +80,10 @@ const PANEL_GROUPS = [
|
||||
's2-ghostmaps',
|
||||
],
|
||||
},
|
||||
{
|
||||
label: msg('Wildlife'),
|
||||
ids: ['wildlife-sightings'],
|
||||
},
|
||||
{
|
||||
label: msg('Weather'),
|
||||
ids: [
|
||||
@@ -94,7 +99,7 @@ const PANEL_GROUPS = [
|
||||
// needs no heading there.
|
||||
{
|
||||
label: msg('Utilities'),
|
||||
ids: ['directions'],
|
||||
ids: ['directions', 'osm-places'],
|
||||
containerId: 'utilities-toggles',
|
||||
},
|
||||
{
|
||||
@@ -441,6 +446,8 @@ export class LayerPanel {
|
||||
this._selectChip(layerId, chipId, generation),
|
||||
onListItem: (layerId, itemId) =>
|
||||
this._selectListItem(layerId, itemId, generation),
|
||||
onSlider: (layerId, sliderId, value) =>
|
||||
this._moveSlider(layerId, sliderId, value, generation),
|
||||
}),
|
||||
id === null ? this._toggleContainer : this._groupContainers.get(id),
|
||||
);
|
||||
@@ -470,7 +477,8 @@ export class LayerPanel {
|
||||
}
|
||||
|
||||
/**
|
||||
* A layer's row chips, color legend, info line and ordered list. The block
|
||||
* A layer's row chips, one-of-many switch, slider, color legend, info line
|
||||
* and ordered list. The block
|
||||
* is hidden while the layer is off (or while a dependency owner has
|
||||
* surrendered it), so a quiet row stays quiet. Chips and list items are
|
||||
* keyed, so the refresh a chip's own click triggers keeps keyboard focus.
|
||||
@@ -494,11 +502,20 @@ export class LayerPanel {
|
||||
: `${item.label} ${formatCount(item.count)}`,
|
||||
}));
|
||||
const infoText = controls?.info ? String(controls.info) : '';
|
||||
const segmented = controls?.segmented || null;
|
||||
const slider = controls?.slider || null;
|
||||
// The info line, once shown, stays in place and hides when empty.
|
||||
if (infoText) row.info = true;
|
||||
return {
|
||||
hidden: chips.length === 0 && legend.length === 0 && !infoText,
|
||||
hidden:
|
||||
chips.length === 0 &&
|
||||
legend.length === 0 &&
|
||||
!infoText &&
|
||||
!segmented &&
|
||||
!slider,
|
||||
chips,
|
||||
segmented,
|
||||
slider,
|
||||
legend,
|
||||
info: row.info
|
||||
? { text: infoText, title: controls?.infoTitle || '' }
|
||||
@@ -536,15 +553,33 @@ export class LayerPanel {
|
||||
// listeners, so a click from a released generation is dropped.
|
||||
_selectChip(id, chipId, generation = this._generation) {
|
||||
if (this._destroyed || this._generation !== generation) return;
|
||||
const chip = this._rowControlsFor(id)?.chips?.find(
|
||||
(entry) => entry.id === chipId,
|
||||
);
|
||||
// A switch option carries the same fields as a chip.
|
||||
const live = this._rowControlsFor(id);
|
||||
const chip = [
|
||||
...(live?.chips || []),
|
||||
...(live?.segmented?.options || []),
|
||||
].find((entry) => entry.id === chipId);
|
||||
if (!chip || chip.disabled || !this.isEnabled(id)) return;
|
||||
if (typeof chip.onClick === 'function') chip.onClick();
|
||||
else if (chip.params)
|
||||
this.setLayerParams(id, chip.params, { origin: 'user' });
|
||||
}
|
||||
|
||||
// A row slider (e.g. the Active Fires minimum-FRP filter) maps its position
|
||||
// to params through the live descriptor on every tick.
|
||||
_moveSlider(id, sliderId, value, generation = this._generation) {
|
||||
if (this._destroyed || this._generation !== generation) return;
|
||||
const slider = this._rowControlsFor(id)?.slider;
|
||||
if (
|
||||
!slider ||
|
||||
slider.id !== sliderId ||
|
||||
typeof slider.params !== 'function' ||
|
||||
!this.isEnabled(id)
|
||||
)
|
||||
return;
|
||||
this.setLayerParams(id, slider.params(value), { origin: 'user' });
|
||||
}
|
||||
|
||||
_selectListItem(id, itemId, generation = this._generation) {
|
||||
if (this._destroyed || this._generation !== generation) return;
|
||||
const item = this._rowControlsFor(id)?.list?.items?.find(
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
<script setup>
|
||||
import RailChips from '../rail/RailChips.vue';
|
||||
import RailRowList from '../rail/RailRowList.vue';
|
||||
import RowSlider from './RowSlider.vue';
|
||||
import RowSwitch from './RowSwitch.vue';
|
||||
import RowText from './RowText.vue';
|
||||
import { vClassToggle } from '../rail/classToggle.js';
|
||||
|
||||
@@ -12,6 +14,7 @@ defineProps({
|
||||
onToggle: { type: Function, default: () => {} },
|
||||
onChip: { type: Function, default: () => {} },
|
||||
onListItem: { type: Function, default: () => {} },
|
||||
onSlider: { type: Function, default: () => {} },
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -55,6 +58,16 @@ defineProps({
|
||||
><RailChips
|
||||
:chips="item.controls.chips"
|
||||
:on-select="(chip) => onChip(item.id, chip.id)"
|
||||
/><RowSwitch
|
||||
v-if="item.controls.segmented"
|
||||
:segmented="item.controls.segmented"
|
||||
:on-select="(optionId) => onChip(item.id, optionId)"
|
||||
/><RowSlider
|
||||
v-if="item.controls.slider"
|
||||
:slider="item.controls.slider"
|
||||
:on-input="
|
||||
(value) => onSlider(item.id, item.controls.slider.id, value)
|
||||
"
|
||||
/><span
|
||||
v-for="(entry, index) in item.controls.legend"
|
||||
:key="index"
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
<script setup>
|
||||
import UiSlider from '../kit/UiSlider.js';
|
||||
|
||||
// A row's quantitative slider (e.g. the Active Fires minimum-FRP filter).
|
||||
// `track` is a CSS background painting the runnable track, so a color ramp
|
||||
// doubles as the legend; each tick sits at `at` (0..1) along it. The input
|
||||
// holds its position while focused, so a refresh from its own tick never
|
||||
// moves the thumb under the pointer.
|
||||
defineProps({
|
||||
slider: { type: Object, required: true },
|
||||
onInput: { type: Function, default: () => {} },
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="data-toggle-slider" :data-slider-id="slider.id"
|
||||
><div class="data-toggle-slider-head"
|
||||
><span class="data-toggle-slider-label">{{ slider.label }}</span
|
||||
><span class="data-toggle-slider-value gev-slider-value">{{
|
||||
slider.valueText
|
||||
}}</span></div
|
||||
><UiSlider
|
||||
class="data-toggle-slider-input"
|
||||
:data-slider-id="slider.id"
|
||||
:min="slider.min"
|
||||
:max="slider.max"
|
||||
:step="slider.step ?? 1"
|
||||
:model-value="slider.value"
|
||||
hold
|
||||
:aria-label="slider.ariaLabel || undefined"
|
||||
:aria-valuetext="slider.valueText || undefined"
|
||||
:style="slider.track ? { '--slider-track': slider.track } : undefined"
|
||||
@update:model-value="onInput"
|
||||
/><div class="data-toggle-slider-ticks"
|
||||
><span
|
||||
v-for="tick in slider.ticks || []"
|
||||
:key="tick.at"
|
||||
class="data-toggle-slider-tick"
|
||||
:style="{ '--at': `${(tick.at * 100).toFixed(2)}%` }"
|
||||
>{{ tick.label }}</span
|
||||
></div
|
||||
></div
|
||||
>
|
||||
</template>
|
||||
@@ -0,0 +1,38 @@
|
||||
<script setup>
|
||||
import UiSegmented from '../kit/UiSegmented.vue';
|
||||
|
||||
// A row's one-of-many switch (e.g. Active Fires confidence). Options carry
|
||||
// the same fields as chips, so the owner resolves a choice the way it
|
||||
// resolves a chip; `label` is an optional caption beside the group.
|
||||
defineProps({
|
||||
segmented: { type: Object, required: true },
|
||||
onSelect: { type: Function, default: () => {} },
|
||||
});
|
||||
|
||||
const options = (segmented) =>
|
||||
(segmented.options || []).map((option) => ({
|
||||
value: option.id,
|
||||
label: option.label,
|
||||
disabled: Boolean(option.disabled),
|
||||
attrs: { 'data-chip-id': option.id, title: option.title || undefined },
|
||||
}));
|
||||
const activeId = (segmented) =>
|
||||
(segmented.options || []).find((option) => option.active)?.id;
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span
|
||||
v-if="segmented.label"
|
||||
class="data-toggle-segmented-label"
|
||||
:data-segmented-caption-for="segmented.id"
|
||||
>{{ segmented.label }}</span
|
||||
><UiSegmented
|
||||
class="data-toggle-segmented"
|
||||
:data-segmented-id="segmented.id"
|
||||
:model-value="activeId(segmented)"
|
||||
:options="options(segmented)"
|
||||
:label="segmented.ariaLabel || segmented.label || ''"
|
||||
item-class="data-toggle-segment"
|
||||
@update:model-value="onSelect"
|
||||
/>
|
||||
</template>
|
||||
@@ -39,8 +39,123 @@ test('the count-line class toggles without dropping the voice highlight', () =>
|
||||
assert.equal(element.classList.contains('gev-voice-focus'), true);
|
||||
|
||||
render(h(LayerRows, { items: [row(false)] }), container);
|
||||
assert.equal(element.classList.contains('data-toggle-row--count-line'), false);
|
||||
assert.equal(
|
||||
element.classList.contains('data-toggle-row--count-line'),
|
||||
false,
|
||||
);
|
||||
assert.equal(element.classList.contains('gev-voice-focus'), true);
|
||||
assert.equal(element.classList.contains('data-toggle-row'), true);
|
||||
render(null, container);
|
||||
});
|
||||
|
||||
const fireRow = (value, active = 'all') => ({
|
||||
...row(false),
|
||||
key: 'fires',
|
||||
id: 'fires',
|
||||
controls: {
|
||||
hidden: false,
|
||||
chips: [],
|
||||
segmented: {
|
||||
id: 'confidence',
|
||||
label: 'Confidence',
|
||||
ariaLabel: 'Detection confidence',
|
||||
options: ['all', 'high'].map((mode) => ({
|
||||
id: `confidence-${mode}`,
|
||||
label: mode.toUpperCase(),
|
||||
title: `${mode} title`,
|
||||
active: mode === active,
|
||||
})),
|
||||
},
|
||||
slider: {
|
||||
id: 'min-frp',
|
||||
label: 'Fire intensity (FRP)',
|
||||
ariaLabel: 'Minimum fire radiative power, megawatts',
|
||||
valueText: value ? `≥ ${value} MW` : 'All',
|
||||
min: 0,
|
||||
max: 1000,
|
||||
step: 1,
|
||||
value,
|
||||
track: 'linear-gradient(90deg, #9e2a1b, #fff3b0)',
|
||||
ticks: [
|
||||
{ at: 0, label: '0' },
|
||||
{ at: 0.5, label: '30' },
|
||||
],
|
||||
},
|
||||
legend: [],
|
||||
info: null,
|
||||
list: null,
|
||||
},
|
||||
});
|
||||
|
||||
test('a row switch and slider render their markup and report choices', () => {
|
||||
document.body.replaceChildren();
|
||||
const container = document.body.appendChild(document.createElement('div'));
|
||||
const chips = [];
|
||||
const moves = [];
|
||||
const props = {
|
||||
onChip: (id, chipId) => chips.push([id, chipId]),
|
||||
onSlider: (id, sliderId, value) => moves.push([id, sliderId, value]),
|
||||
};
|
||||
render(h(LayerRows, { items: [fireRow(0)], ...props }), container);
|
||||
|
||||
const caption = container.querySelector('.data-toggle-segmented-label');
|
||||
assert.equal(caption.textContent, 'Confidence');
|
||||
const group = container.querySelector('.gev-segmented.data-toggle-segmented');
|
||||
assert.equal(group.getAttribute('role'), 'radiogroup');
|
||||
assert.equal(group.getAttribute('aria-label'), 'Detection confidence');
|
||||
const segments = [
|
||||
...group.querySelectorAll('.gev-segment.data-toggle-segment'),
|
||||
];
|
||||
assert.deepEqual(
|
||||
segments.map((button) => button.dataset.chipId),
|
||||
['confidence-all', 'confidence-high'],
|
||||
);
|
||||
assert.equal(segments[0].classList.contains('active'), true);
|
||||
assert.equal(segments[1].title, 'high title');
|
||||
segments[1].click();
|
||||
assert.deepEqual(chips, [['fires', 'confidence-high']]);
|
||||
|
||||
const block = container.querySelector('.data-toggle-slider');
|
||||
assert.equal(block.dataset.sliderId, 'min-frp');
|
||||
assert.equal(
|
||||
block.querySelector('.data-toggle-slider-label').textContent,
|
||||
'Fire intensity (FRP)',
|
||||
);
|
||||
assert.equal(
|
||||
block.querySelector('.data-toggle-slider-value').textContent,
|
||||
'All',
|
||||
);
|
||||
const input = block.querySelector('input.data-toggle-slider-input');
|
||||
assert.equal(input.classList.contains('gev-quantitative-slider'), true);
|
||||
assert.equal(input.type, 'range');
|
||||
assert.equal(input.max, '1000');
|
||||
assert.equal(
|
||||
input.getAttribute('aria-label'),
|
||||
'Minimum fire radiative power, megawatts',
|
||||
);
|
||||
assert.equal(input.getAttribute('aria-valuetext'), 'All');
|
||||
assert.match(
|
||||
input.style.getPropertyValue('--slider-track'),
|
||||
/^linear-gradient/,
|
||||
);
|
||||
const ticks = [...block.querySelectorAll('.data-toggle-slider-tick')];
|
||||
assert.deepEqual(
|
||||
ticks.map((tick) => tick.textContent),
|
||||
['0', '30'],
|
||||
);
|
||||
assert.equal(ticks[1].style.getPropertyValue('--at'), '50.00%');
|
||||
|
||||
input.value = '120';
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
assert.deepEqual(moves, [['fires', 'min-frp', 120]]);
|
||||
|
||||
// The refresh that tick triggers keeps the same nodes and updates the text.
|
||||
render(h(LayerRows, { items: [fireRow(120, 'high')], ...props }), container);
|
||||
assert.equal(
|
||||
container.querySelector('input.data-toggle-slider-input'),
|
||||
input,
|
||||
);
|
||||
assert.equal(input.getAttribute('aria-valuetext'), '≥ 120 MW');
|
||||
assert.equal(segments[1].classList.contains('active'), true);
|
||||
render(null, container);
|
||||
});
|
||||
@@ -37,6 +37,7 @@ const ESRI_NOTE = msg('Imagery on Esri · Google 3D returns when cleared');
|
||||
const LAYER_NOTICES = new Set([
|
||||
ESRI_NOTE,
|
||||
msg('Box and images cleared'),
|
||||
msg('Search cancelled'),
|
||||
msg('Esri map unavailable · no swipe'),
|
||||
msg('Swipe needs a globe map'),
|
||||
msg('Imagery stays on Esri · CLEAR to use Google 3D'),
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
+21
-1
@@ -35,5 +35,25 @@ export const useVoiceStore = defineStore('gev-voice', () => {
|
||||
bars.value = next && markRaw(next);
|
||||
}
|
||||
|
||||
return { view, publish, controls, connect, bars, publishBars };
|
||||
/**
|
||||
* The chat conversation, apart from the view: a typed reply reveals frame
|
||||
* by frame, and only the message list renders it.
|
||||
*/
|
||||
const chat = shallowRef([]);
|
||||
|
||||
/** @param {Array<{id: number, role: string, text: string}>} next */
|
||||
function publishChat(next) {
|
||||
chat.value = markRaw(next ?? []);
|
||||
}
|
||||
|
||||
return {
|
||||
view,
|
||||
publish,
|
||||
controls,
|
||||
connect,
|
||||
bars,
|
||||
publishBars,
|
||||
chat,
|
||||
publishChat,
|
||||
};
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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);
|
||||
|
||||
@@ -652,9 +652,8 @@ html:not([lang='en']) #gev-voice-control .gev-voice-help-detail {
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
#gev-voice-control:not([data-status='error']):hover .gev-voice-help-tray,
|
||||
#gev-voice-control:not([data-status='error'])
|
||||
#gev-voice-button:focus-visible
|
||||
#gev-voice-button:enabled:is(:hover, :focus-visible)
|
||||
~ .gev-voice-help-tray {
|
||||
visibility: visible;
|
||||
opacity: 1;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -1042,6 +1042,118 @@ html:not([lang='en']) .data-row-list-text {
|
||||
padding-top: 3px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* Optional per-layer one-of-many switch (Active Fires confidence). The shared
|
||||
.gev-segmented surface, sized to the chip row. */
|
||||
.data-toggle-controls .data-toggle-segmented {
|
||||
flex-basis: 100%;
|
||||
max-width: 220px;
|
||||
}
|
||||
|
||||
.data-toggle-segmented-label {
|
||||
flex-basis: 100%;
|
||||
padding-top: 2px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 8px;
|
||||
letter-spacing: 1.2px;
|
||||
color: var(--text-dim);
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.data-toggle-controls .data-toggle-segment {
|
||||
min-height: 20px;
|
||||
padding: 3px 6px;
|
||||
font-size: 8px;
|
||||
letter-spacing: 0.8px;
|
||||
}
|
||||
|
||||
/* Optional per-layer quantitative slider (Active Fires minimum FRP). The
|
||||
track is painted by the layer (`--slider-track`, a stepped color ramp), so
|
||||
the slider doubles as the marker legend; ticks sit under their thresholds. */
|
||||
.data-toggle-slider {
|
||||
flex-basis: 100%;
|
||||
display: grid;
|
||||
gap: 2px;
|
||||
padding-top: 2px;
|
||||
}
|
||||
|
||||
.data-toggle-slider-head {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 8px;
|
||||
letter-spacing: 1.2px;
|
||||
color: var(--text-dim);
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.data-toggle-slider-value {
|
||||
min-width: 0;
|
||||
font-size: 9px;
|
||||
letter-spacing: 0.5px;
|
||||
text-transform: none;
|
||||
}
|
||||
|
||||
.data-toggle-slider-input {
|
||||
height: 14px;
|
||||
}
|
||||
|
||||
.data-toggle-slider-input::-webkit-slider-runnable-track {
|
||||
height: 5px;
|
||||
border-radius: 3px;
|
||||
background: var(--slider-track, rgba(255, 255, 255, 0.08));
|
||||
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.35);
|
||||
}
|
||||
|
||||
.data-toggle-slider-input::-moz-range-track,
|
||||
.data-toggle-slider-input::-moz-range-progress {
|
||||
height: 5px;
|
||||
border-radius: 3px;
|
||||
background: var(--slider-track, rgba(255, 255, 255, 0.08));
|
||||
}
|
||||
|
||||
.data-toggle-slider-input::-webkit-slider-thumb {
|
||||
width: 11px;
|
||||
height: 11px;
|
||||
margin-top: -3px;
|
||||
background: var(--text-primary);
|
||||
box-shadow:
|
||||
0 0 0 1px rgba(0, 0, 0, 0.6),
|
||||
0 0 6px rgba(255, 255, 255, 0.35);
|
||||
}
|
||||
|
||||
.data-toggle-slider-input::-moz-range-thumb {
|
||||
width: 11px;
|
||||
height: 11px;
|
||||
background: var(--text-primary);
|
||||
box-shadow:
|
||||
0 0 0 1px rgba(0, 0, 0, 0.6),
|
||||
0 0 6px rgba(255, 255, 255, 0.35);
|
||||
}
|
||||
|
||||
.data-toggle-slider-ticks {
|
||||
position: relative;
|
||||
height: 10px;
|
||||
margin: 0 5px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 7px;
|
||||
letter-spacing: 0.4px;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
|
||||
.data-toggle-slider-tick {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: var(--at);
|
||||
transform: translateX(-50%);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.data-toggle-slider-tick:first-child {
|
||||
transform: none;
|
||||
}
|
||||
/* ── Local RTL-SDR card (FM + Local ADS-B receiver) ── */
|
||||
.sdr-radio-card {
|
||||
display: grid;
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
<script setup>
|
||||
import { nextTick, ref, watch } from 'vue';
|
||||
import { storeToRefs } from 'pinia';
|
||||
import { t } from '../../../i18n/index.js';
|
||||
import { useVoiceStore } from '../../stores/voice.js';
|
||||
import { ASSISTANT_NAME } from '../../../voice/control.js';
|
||||
import PanelLayoutButtons from './PanelLayoutButtons.vue';
|
||||
|
||||
// The typed chat in the command dock, as its owner (src/voice/chatControl.js)
|
||||
// writes the voice control presenter. Messages arrive apart from the view, so
|
||||
// a reply revealed frame by frame renders only this list.
|
||||
const props = defineProps({ view: { type: Object, required: true } });
|
||||
const store = useVoiceStore();
|
||||
const { controls, chat: messages } = storeToRefs(store);
|
||||
const emit = (name, ...args) => controls.value?.emit(name, ...args);
|
||||
const list = ref(null);
|
||||
const layerSelect = ref(null);
|
||||
const layerChoice = ref('');
|
||||
|
||||
// The input holds what the person types until its owner writes it (history
|
||||
// recall, a suggestion, clearing after send): only then is it replaced.
|
||||
const vOwnedDraft = {
|
||||
mounted(el, { value }) {
|
||||
el.value = value.text;
|
||||
},
|
||||
updated(el, { value, oldValue }) {
|
||||
if (value.revision !== oldValue?.revision && el.value !== value.text)
|
||||
el.value = value.text;
|
||||
},
|
||||
};
|
||||
|
||||
// Keep the newest message in view as the conversation grows, while the
|
||||
// reader is at the bottom: one who scrolled up to read stays there until
|
||||
// they send. The position is read on scroll, not on every reveal frame.
|
||||
let stuck = true;
|
||||
const onListScroll = () => {
|
||||
const el = list.value;
|
||||
if (el) stuck = el.scrollHeight - el.scrollTop - el.clientHeight < 24;
|
||||
};
|
||||
// A send is a new newest user message. The log is capped, so a full one
|
||||
// does not grow as it takes a message: compare ids, not lengths.
|
||||
const lastSent = (list) => list?.findLast((entry) => entry.role === 'user')?.id;
|
||||
watch(messages, (next, previous) => {
|
||||
const sent =
|
||||
next.at(-1)?.role === 'user' && lastSent(next) !== lastSent(previous);
|
||||
if (!stuck && !sent) return;
|
||||
void nextTick(() => {
|
||||
if (list.value) list.value.scrollTop = list.value.scrollHeight;
|
||||
});
|
||||
});
|
||||
|
||||
// Arrow keys only move the layer choice (a closed select changes on each
|
||||
// press on Windows and Linux); the Attach button or Enter attaches it.
|
||||
function attachLayer() {
|
||||
const value = layerChoice.value;
|
||||
layerChoice.value = '';
|
||||
if (layerSelect.value) layerSelect.value.value = '';
|
||||
if (value) emit('chat-layer', value);
|
||||
}
|
||||
|
||||
const quickPrompts = () => [t('Fly to Tokyo'), t('Show live flights')];
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section id="gev-chat-panel" :hidden="!props.view.chat.open" :data-minimized="props.view.chat.minimized ? 'true' : undefined" :aria-label="t('AI chat')">
|
||||
<header class="gev-chat-header">
|
||||
<div><strong>{{ t('GEV CHAT') }}</strong><p>{{ t('Ask about the map. Tell it where to go.') }}</p></div>
|
||||
<div id="gev-chat-header-actions">
|
||||
<PanelLayoutButtons :docked="props.view.layout.docked" :minimized="props.view.chat.minimized" @dock="emit('layout-dock')" @minimize="emit('chat-minimize')" />
|
||||
<button v-if="props.view.panel" id="gev-voice-settings-button" class="gev-voice-settings-button" type="button" :aria-label="t('Settings')" :title="t('Settings')" aria-controls="gev-voice-panel" :aria-expanded="String(props.view.voicePanel.settingsExpanded)" @click="emit('settings-button')"><span class="material-symbols-outlined gev-voice-settings-icon" aria-hidden="true">settings</span></button>
|
||||
<button id="gev-chat-close" type="button" :aria-label="t('Close chat')" @click="emit('chat-close')">×</button>
|
||||
</div>
|
||||
</header>
|
||||
<div id="gev-chat-messages" ref="list" role="log" :aria-label="t('Conversation')" aria-live="polite" :aria-busy="props.view.chat.busy || props.view.chat.revealing ? 'true' : undefined" @scroll.passive="onListScroll">
|
||||
<div id="gev-chat-empty" :hidden="!props.view.chat.empty">
|
||||
<svg viewBox="0 0 24 24" width="32" height="32" fill="none" stroke="currentColor" stroke-width="1" aria-hidden="true"><circle cx="12" cy="12" r="10"></circle><ellipse cx="12" cy="12" rx="4" ry="10"></ellipse><path d="M2 12h20"></path></svg>
|
||||
<h3>{{ t('Explore with a question') }}</h3>
|
||||
<p>{{ t('Find a place, explore live data, or change your view.') }}</p>
|
||||
<button v-for="prompt in quickPrompts()" :key="prompt" type="button" :hidden="!props.view.chat.quickChecked" @click="emit('chat-prompt', prompt)">{{ prompt }}</button>
|
||||
</div>
|
||||
<div v-for="message in messages" :key="message.id" class="gev-chat-message" :data-role="message.role">
|
||||
<small>{{ message.role === 'user' ? t('YOU') : ASSISTANT_NAME }}</small><span>{{ message.text }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<p id="gev-chat-status" role="status">{{ props.view.chat.status }}</p>
|
||||
<!-- Stays under the status for the whole conversation. -->
|
||||
<p v-if="props.view.chat.authNote" id="gev-chat-auth-note">{{ props.view.chat.authNote }}</p>
|
||||
<div id="gev-chat-attachments" :aria-label="t('Attachments')" :hidden="!props.view.chat.attachments.length">
|
||||
<button v-for="item in props.view.chat.attachments" :key="item.key" type="button" :disabled="props.view.chat.locked" :aria-label="`${t('Remove attachment')}: ${item.name}`" @click="emit('chat-attachment-remove', item.key)">{{ item.name }} ×</button>
|
||||
</div>
|
||||
<div id="gev-chat-attach-menu" :hidden="!props.view.chat.attachMenuOpen" @keydown="emit('chat-attach-keydown', $event)">
|
||||
<label for="gev-chat-layer">{{ t('Attach a map layer') }}</label>
|
||||
<div id="gev-chat-layer-row">
|
||||
<select id="gev-chat-layer" ref="layerSelect" :disabled="props.view.chat.locked" @change="layerChoice = $event.target.value" @keydown.enter.prevent="attachLayer()">
|
||||
<option value="">{{ t('Choose a layer…') }}</option>
|
||||
<option v-for="layer in props.view.chat.layers" :key="layer.value" :value="layer.value">{{ layer.label }}</option>
|
||||
</select>
|
||||
<button id="gev-chat-layer-attach" type="button" :disabled="props.view.chat.locked || !layerChoice" @click="attachLayer()">{{ t('Attach layer') }}</button>
|
||||
</div>
|
||||
<button id="gev-chat-file-button" type="button" :disabled="props.view.chat.locked" @click="emit('chat-file-button')">{{ t('Attach a file') }}</button>
|
||||
<p>{{ t('TXT, Markdown, CSV, JSON or GeoJSON · up to 10 KB in total. Attachments are sent to your AI provider with your message.') }}</p>
|
||||
<input id="gev-chat-file" type="file" accept=".txt,.md,.csv,.json,.geojson" multiple hidden @change="emit('chat-files', $event.target)" />
|
||||
</div>
|
||||
<aside id="gev-chat-mini-reply" :hidden="!props.view.chat.miniReply" :aria-label="t('Latest AI response')">
|
||||
<header><span translate="no">{{ ASSISTANT_NAME }}</span><button id="gev-chat-expand-reply" type="button" :aria-label="t('Expand conversation')" :title="t('Expand conversation')" @click="emit('chat-restore')"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path d="M14 4h6v6m0-6-7 7M10 20H4v-6m0 6 7-7"></path></svg></button></header>
|
||||
<p id="gev-chat-mini-text" aria-live="polite">{{ props.view.chat.miniReply }}</p>
|
||||
</aside>
|
||||
<div id="gev-chat-suggestions" :aria-label="t('Command suggestions')" :hidden="!props.view.chat.suggestions.length">
|
||||
<div v-for="group in props.view.chat.suggestions" :key="group.label">
|
||||
<small>{{ group.label }}</small>
|
||||
<button v-for="command in group.items" :key="command" type="button" :title="command" @click="emit('chat-suggestion', command)">{{ command }}</button>
|
||||
</div>
|
||||
</div>
|
||||
<form id="gev-chat-form" @submit.prevent="emit('chat-submit')">
|
||||
<button id="gev-chat-restore" type="button" :aria-label="t('Expand chat')" :title="t('Expand chat')" @click="emit('chat-restore')"><svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path d="M5 4h14a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H9l-6 4V6a2 2 0 0 1 2-2Z"></path></svg></button>
|
||||
<button id="gev-chat-attach" type="button" :disabled="props.view.chat.busy" :aria-label="t('Add attachment')" :aria-expanded="String(props.view.chat.attachMenuOpen)" aria-controls="gev-chat-attach-menu" @click="emit('chat-attach-toggle')" @keydown="emit('chat-attach-keydown', $event)"><svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path d="m8 12 6-6a3 3 0 0 1 4 4l-8 8a5 5 0 0 1-7-7l9-9"></path></svg></button>
|
||||
<textarea id="gev-chat-input" v-owned-draft="{ text: props.view.chat.draft, revision: props.view.chat.draftRevision }" :rows="props.view.chat.rows" maxlength="4000" :aria-label="t('Message GEV')" :placeholder="t('Ask GEV anything about the map…')" @input="emit('chat-input', $event.target.value)" @keydown="emit('chat-keydown', $event)"></textarea>
|
||||
<button id="gev-chat-send" :type="props.view.chat.busy ? 'button' : 'submit'" :disabled="props.view.chat.sendDisabled" :data-busy="String(props.view.chat.busy)" :aria-label="props.view.chat.busy ? t('Stop reply') : t('Send message')" :title="props.view.chat.busy ? t('Stop reply') : t('Send message')" @click="props.view.chat.busy && emit('chat-stop')"><svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path class="gev-chat-enter-icon" d="M19 5v8H5m5-5-5 5 5 5"></path><rect class="gev-chat-stop-icon" x="6" y="6" width="12" height="12" rx="1.5" fill="currentColor" stroke="none"></rect></svg></button>
|
||||
</form>
|
||||
</section>
|
||||
</template>
|
||||
@@ -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,18 @@
|
||||
<script setup>
|
||||
import { t } from '../../../i18n/index.js';
|
||||
|
||||
// Dock and minimize for an assistant panel (chat or voice). The owner
|
||||
// (src/voice/panelLayout.js) places the panel; this reports the choice.
|
||||
const props = defineProps({
|
||||
docked: { type: Boolean, default: false },
|
||||
minimized: { type: Boolean, default: false },
|
||||
});
|
||||
defineEmits(['dock', 'minimize']);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="gev-panel-layout" role="group" :aria-label="t('Panel position')">
|
||||
<button type="button" data-layout-dock :aria-pressed="String(props.docked)" :aria-label="props.docked ? t('Move above the dock') : t('Dock to the right')" :title="props.docked ? t('Move above the dock') : t('Dock to the right')" @click="$emit('dock')"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path :d="props.docked ? 'M4 5h16v14H4ZM4 14h16' : 'M4 5h16v14H4ZM14 5v14'"></path></svg></button>
|
||||
<button type="button" data-layout-minimize :aria-label="props.minimized ? t('Expand panel') : t('Minimize panel')" :title="props.minimized ? t('Expand panel') : t('Minimize panel')" @click="$emit('minimize')"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path :d="props.minimized ? 'M6 6h12v12H6Z' : 'M6 12h12'"></path></svg></button>
|
||||
</div>
|
||||
</template>
|
||||
@@ -3,8 +3,11 @@ import { storeToRefs } from 'pinia';
|
||||
import { formatNumber, t } from '../../../i18n/index.js';
|
||||
import { vClassToggle } from '../../rail/classToggle.js';
|
||||
import { useVoiceStore } from '../../stores/voice.js';
|
||||
import { ASSISTANT_NAME } from '../../../voice/control.js';
|
||||
import VoiceCard from './VoiceCard.vue';
|
||||
import VoiceVisualizer from './VoiceVisualizer.vue';
|
||||
import ChatPanel from './ChatPanel.vue';
|
||||
import PanelLayoutButtons from './PanelLayoutButtons.vue';
|
||||
import UiButton from '../../kit/UiButton.vue';
|
||||
import UiSelect from '../../kit/UiSelect.js';
|
||||
|
||||
@@ -49,16 +52,25 @@ const rootData = (root) => ({
|
||||
'data-push-to-talk': optional(root.pushToTalk),
|
||||
'data-microphone': optional(root.microphone),
|
||||
'data-row-grace': root.rowGrace ? 'true' : undefined,
|
||||
'data-assistant-mode': root.assistantMode,
|
||||
'data-chat-open': String(root.chatOpen),
|
||||
'data-chat-busy': String(root.chatBusy),
|
||||
'data-voice-exchange': root.voiceExchange ? 'true' : undefined,
|
||||
});
|
||||
// Settings opened from chat take chat's frame, so the switch does not jump.
|
||||
const frameStyle = (panel) => ({
|
||||
'--chat-frame-width': panel.frameWidth ? `${panel.frameWidth}px` : undefined,
|
||||
'--chat-frame-height': panel.frameHeight ? `${panel.frameHeight}px` : undefined,
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div id="gev-voice-control" v-bind="rootData(view.root)" v-class-toggle="{ 'error-dismissed': view.root.errorDismissed }" @pointerleave="emit('pointerleave', $event)" @pointerenter="emit('pointerenter', $event)">
|
||||
<label id="gev-voice-provider-field" class="gev-voice-provider-field" :hidden="view.provider.hidden">
|
||||
<span class="gev-active-border" aria-hidden="true"></span>
|
||||
<label v-if="!view.panel" id="gev-voice-provider-field" class="gev-voice-provider-field" :hidden="view.provider.hidden">
|
||||
<span>{{ t('Voice provider') }}</span>
|
||||
<UiSelect id="gev-voice-provider" class="gev-field" :aria-label="t('Voice provider')" :title="view.provider.title" :model-value="view.provider.value" @update:model-value="emit('provider-change', $event)"><option v-for="option in view.provider.options" :key="option.value" :value="option.value">{{ option.label }}</option></UiSelect>
|
||||
</label>
|
||||
<button v-if="view.panel" id="gev-voice-settings-button" class="gev-voice-settings-button" type="button" :aria-label="t('Voice Settings')" aria-controls="gev-voice-panel" :aria-expanded="String(view.voicePanel.settingsExpanded)" @click="emit('settings-button')"><span class="material-symbols-outlined gev-voice-settings-icon" aria-hidden="true">settings</span></button>
|
||||
<div class="gev-voice-heading">
|
||||
<div class="gev-voice-kicker">{{ t('AI AGENT') }}</div>
|
||||
<div id="gev-voice-status">{{ view.status.text }}</div>
|
||||
@@ -72,7 +84,12 @@ const rootData = (root) => ({
|
||||
<span class="gev-mic-orbit"><img src="/mic.svg" alt="" /></span>
|
||||
<span class="gev-mic-label">{{ view.mic.text }}</span>
|
||||
</UiButton>
|
||||
<button v-if="view.panel" id="gev-chat-button" type="button" :aria-label="t('Open AI chat')" aria-controls="gev-chat-panel" :aria-expanded="String(view.chat.open && !view.chat.minimized)" @click="emit('chat-button')"><svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path d="M5 4h14a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H9l-6 4V6a2 2 0 0 1 2-2Z"></path></svg><span class="gev-chat-label">{{ t('CHAT') }}</span></button>
|
||||
<ChatPanel v-if="view.panel" :view="view" />
|
||||
<VoiceVisualizer />
|
||||
<div class="gev-chat-thinking" aria-hidden="true"><span></span><span></span><span></span></div>
|
||||
<!-- Chat announces its phase in its own status line (#gev-chat-status); in chat mode this one stays silent. -->
|
||||
<div id="gev-assistant-phase" role="status" :aria-live="view.root.assistantMode === 'chat' ? 'off' : 'polite'" :aria-hidden="view.root.assistantMode === 'chat' ? 'true' : undefined">{{ view.phase.text }}</div>
|
||||
<div class="gev-voice-readout">
|
||||
<div id="gev-voice-detail" :title="optional(view.detail.title)">{{ view.detail.text }}</div>
|
||||
</div>
|
||||
@@ -80,21 +97,39 @@ const rootData = (root) => ({
|
||||
<span class="gev-voice-help-kicker">{{ t('VOICE CONTROL') }}</span>
|
||||
<span class="gev-voice-help-detail">{{ view.help.text }}</span>
|
||||
</div>
|
||||
<section v-if="view.panel" id="gev-voice-panel" class="gev-voice-panel" :hidden="view.voicePanel.hidden" :data-view="optional(view.voicePanel.view)" :aria-label="t('Voice Settings')" @keydown="emit('panel-keydown', $event)">
|
||||
<section v-if="view.panel" id="gev-voice-panel" class="gev-voice-panel" :hidden="view.voicePanel.hidden" :data-view="optional(view.voicePanel.view)" :data-minimized="view.voicePanel.minimized ? 'true' : undefined" :data-context="optional(view.voicePanel.context)" :style="frameStyle(view.voicePanel)" :aria-label="t('Voice Settings')" @keydown="emit('panel-keydown', $event)">
|
||||
<div class="gev-voice-panel-header">
|
||||
<button id="gev-chat-back" type="button" :hidden="!view.chat.backVisible" @click="emit('chat-back')"><svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" aria-hidden="true"><path d="M15 5l-7 7 7 7"></path></svg><span>{{ t('Back to chat') }}</span></button>
|
||||
<button id="gev-voice-back" type="button" @click="emit('voice-back')"><svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" aria-hidden="true"><path d="M15 5l-7 7 7 7"></path></svg><span>{{ t('Back to voice') }}</span></button>
|
||||
<span class="gev-voice-panel-title">{{ t('VOICE') }}</span>
|
||||
<div class="gev-voice-panel-tabs" role="tablist" :aria-label="t('Voice Settings')">
|
||||
<button id="gev-voice-preview-tab" class="gev-voice-panel-tab" type="button" role="tab" :aria-label="t('Preview')" :title="t('Preview')" :aria-selected="String(view.voicePanel.selected === 'preview')" :tabindex="view.voicePanel.selected === 'preview' ? 0 : -1" aria-controls="gev-voice-preview-panel" @click="emit('tab', 0)" @keydown="emit('tab-keydown', 0, $event)"><span class="material-symbols-outlined gev-voice-panel-tab-icon" aria-hidden="true">visibility</span></button>
|
||||
<button id="gev-voice-settings-tab" class="gev-voice-panel-tab" type="button" role="tab" :aria-label="t('Settings')" :title="t('Settings')" :aria-selected="String(view.voicePanel.selected === 'settings')" :tabindex="view.voicePanel.selected === 'settings' ? 0 : -1" aria-controls="gev-voice-settings-panel" @click="emit('tab', 1)" @keydown="emit('tab-keydown', 1, $event)"><span class="material-symbols-outlined gev-voice-panel-tab-icon" aria-hidden="true">settings</span></button>
|
||||
</div>
|
||||
<PanelLayoutButtons :docked="view.layout.docked" :minimized="view.voicePanel.minimized" @dock="emit('layout-dock')" @minimize="emit('voice-minimize')" />
|
||||
<button id="gev-voice-settings-close" type="button" :aria-label="t('Close voice panel')" @click="emit('settings-close')">×</button>
|
||||
</div>
|
||||
<div class="gev-voice-mini" role="group" :aria-label="t('Latest voice exchange')">
|
||||
<p :hidden="!view.mini.user"><span class="gev-voice-mini-who">{{ t('YOU') }}</span><span id="gev-voice-mini-user">{{ view.mini.user }}</span></p>
|
||||
<p :hidden="!view.mini.assistant"><span class="gev-voice-mini-who" translate="no">{{ ASSISTANT_NAME }}</span><span id="gev-voice-mini-assistant">{{ view.mini.assistant }}</span></p>
|
||||
</div>
|
||||
<div class="gev-voice-panel-body ui-scroll">
|
||||
<section id="gev-voice-preview-panel" role="tabpanel" aria-labelledby="gev-voice-preview-tab" :hidden="view.voicePanel.previewHidden">
|
||||
<p id="gev-voice-preview-empty" :hidden="view.previewEmpty.hidden">{{ view.previewEmpty.text }}</p>
|
||||
<div class="gev-voice-hints" role="group" :aria-label="t('Try saying')"><small>{{ t('Try saying') }}</small><q>{{ t('What am I looking at?') }}</q><q>{{ t('Fly to Tokyo') }}</q><q>{{ t('Show live flights') }}</q></div>
|
||||
<VoiceCard :card="view.card" @dismiss="emit('card-dismiss')" />
|
||||
</section>
|
||||
<section id="gev-voice-settings-panel" role="tabpanel" aria-labelledby="gev-voice-settings-tab" :hidden="view.voicePanel.settingsHidden">
|
||||
<label id="gev-voice-provider-field" class="gev-voice-provider-field" :hidden="view.provider.hidden">
|
||||
<span>{{ t('AI Provider') }}</span>
|
||||
<UiSelect id="gev-voice-provider" class="gev-field" :aria-label="t('AI Provider')" :title="view.provider.title" :model-value="view.provider.value" @update:model-value="emit('provider-change', $event)"><option v-for="option in view.provider.options" :key="option.value" :value="option.value">{{ option.label }}</option></UiSelect>
|
||||
</label>
|
||||
<p class="gev-voice-settings-note">{{ t('The selected AI provider is shared by voice and chat.') }}</p>
|
||||
<div id="gev-settings-chat">
|
||||
<label class="gev-voice-preference gev-voice-preference-toggle"><input id="gev-chat-quick" type="checkbox" v-checked="view.chat.quickChecked" @change="emit('chat-quick-change', $event.target.checked)" /><span>{{ t('Show quick commands') }}</span></label>
|
||||
<p>{{ t('Chat replies are silent. No microphone access is needed.') }}</p>
|
||||
</div>
|
||||
<div id="gev-settings-voice">
|
||||
<label class="gev-voice-preference gev-voice-preference-toggle"><input id="gev-voice-preview-enabled" type="checkbox" aria-describedby="gev-voice-preview-note" v-checked="view.preferences.previewChecked" @change="emit('preview-change', $event.target.checked)" /><span>{{ t('Show Voice Preview') }}</span></label>
|
||||
<p id="gev-voice-preview-note" class="gev-voice-settings-note">{{ view.preferences.previewNote }}</p>
|
||||
<div class="gev-voice-timeout-group">
|
||||
@@ -120,17 +155,18 @@ const rootData = (root) => ({
|
||||
<span id="gev-voice-cost-value" class="gev-voice-cost-value" :hidden="view.cost.hidden" :data-level="view.cost.level" :title="view.cost.title">{{ view.cost.text }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</section>
|
||||
<VoiceCard v-else :card="view.card" @dismiss="emit('card-dismiss')" />
|
||||
<div class="gev-voice-error-tray" role="alert" aria-live="assertive">
|
||||
<div class="gev-voice-error-header">
|
||||
<span>{{ t('VOICE SYSTEM ERROR') }}</span>
|
||||
<span>{{ view.error.typed ? `${t('Chat')} · ${t('ERROR', { context: 'voice' })}` : t('VOICE SYSTEM ERROR') }}</span>
|
||||
<button class="gev-voice-error-dismiss" type="button" @click="controls?.dismissError()">{{ t('DISMISS') }}</button>
|
||||
</div>
|
||||
<div id="gev-voice-error-detail">{{ view.error.text }}</div>
|
||||
<div class="gev-voice-error-hint">{{ t('Check microphone permission and network access, then try again.') }}</div>
|
||||
<div class="gev-voice-error-hint" :hidden="view.error.typed">{{ t('Check microphone permission and network access, then try again.') }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -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