Merge branch 'main' into fix/i18n-installations-note

# Conflicts:
#	scripts/package-boundaries.json
#	src/layers/installations/controls.js
This commit is contained in:
German Khokhlov committed 2026-11-18 16:35:52 +04:00
commit 93b091d082
2063 files changed
+322399 -46202

No files matched your search

+3 -1
View File
@@ -25,7 +25,9 @@ const items = computed(() =>
id: panel.id,
icon: item?.icon ?? PANEL_RAIL_FALLBACK_ICON,
// Static markup is translated at boot, so a host's title already is.
label: item ? t(item.label) : panel.title,
label: item
? t(item.label, item.context && { context: item.context })
: panel.title,
};
}),
);
+123 -35
View File
@@ -1,10 +1,16 @@
import { followedOf } from '../data/followed.js';
import { readEntityRecord } from '../data/entityRecords.js';
import { nextTick } from 'vue';
import { resolveImageryHost } from '../layers/weather/imageryHost.js';
import { ShellFacade } from './shellFacade.js';
import { AircraftDisplay } from './aircraftDisplay.js';
import { LayerBindings } from './layerBindings.js';
import { PanelChrome } from './panelChrome.js';
import { initMobileShell } from './mobileShell.js';
import {
initMobileShell,
MOBILE_SHELL_MEDIA_QUERY,
sheetForPanelId,
} from './mobileShell.js';
import { VisualSettings } from './visualSettings.js';
import { NavigationController } from './navigationController.js';
import { ShareRestoration } from './shareRestoration.js';
@@ -30,7 +36,10 @@ import {
setCyberSonarControls,
} from './cyberSonarControls.js';
import * as Cesium from 'cesium';
import { toDegrees, toRadians } from '../geo/index.js';
// A viewer with no renderer bound gets its ports (camera, effects, globe)
// once its owner has loaded the package's `./render/cesium/unbound` export.
import { cameraOf, canvasOf, findCamera } from '../render/rendererOf.js';
import { aircraftTrackingTarget } from '../cockpitTracking.js';
@@ -55,12 +64,16 @@ import { applicationPinia, createUiRuntime } from './vueRuntime.js';
import { useContextStore } from './stores/context.js';
import { useMissionReplayStore } from './stores/missionReplay.js';
import { useCelestialRingStore } from './stores/celestialRing.js';
import { icrfToFixedAxes } from '../sky/icrf.js';
import { useWorldOverlayActionsStore } from './stores/worldOverlayActions.js';
import { useAwarenessDirectionStore } from './stores/awarenessDirection.js';
import { useHudStore } from './stores/hud.js';
import { useDisplayStore } from './stores/display.js';
import { useLocaleStore } from './stores/locale.js';
import { useLocationStore } from './stores/location.js';
import { useOmnibarStore } from './stores/omnibar.js';
import { installEntityContext } from './entityContextBridge.js';
import { installRailEdgeScroll } from './railEdgeScroll.js';
import { useCockpitStore } from './stores/cockpit.js';
import { useGlobeActionsStore } from './stores/globeActions.js';
import { useRecordingStore } from './stores/recording.js';
@@ -89,10 +102,13 @@ import { preloadOwnerFlags } from './ownerFlag.js';
export class StyleManager extends ShellFacade {
/**
* @param {Cesium.Viewer} viewer - The CesiumJS viewer instance.
* @param {object} viewer - The scene object the renderer draws.
* @param {object} [options]
* @param {boolean} [options.localePicker=true] - false removes the language
* picker, for a host that does not initialize Core's locale.
* picker, for a host that offers its own language choice.
* @param {{lon: number, lat: number, height: number, heading?: number,
* pitch?: number}|null} [options.homeView] - where the title's logo goes
* back to (degrees): the view the app started from.
*/
constructor(
viewer,
@@ -103,6 +119,7 @@ export class StyleManager extends ShellFacade {
requestServices,
initialShareCode = null,
localePicker = true,
homeView = null,
} = {},
) {
super();
@@ -160,6 +177,14 @@ export class StyleManager extends ShellFacade {
});
// Vue views share this runtime and its stores; dispose unmounts them.
this._ui = createUiRuntime({ pinia: applicationPinia() });
// The omnibar and Context list and toggle data layers through the shell.
useOmnibarStore(applicationPinia()).connect({
layers: () => this._dataManager?.getAll?.() || [],
setLayer: (id, enabled) =>
this._dataManager?.setEnabled(id, enabled, { origin: 'user' }),
});
// Scrolling at a screen edge steps through that side's rail panels.
this._removeRailEdgeScroll = installRailEdgeScroll();
this._feedback = new ShellFeedback({
readLayers: () => withPlacePacks(this._dataManager?.getAll?.() || []),
});
@@ -171,6 +196,15 @@ export class StyleManager extends ShellFacade {
this._updateGlobalLoadingFeedback(),
);
this.viewer = viewer;
// A click on anything a layer can identify opens its card in Context.
this._removeEntityContext = installEntityContext({
viewer,
getDataManager: () => this._dataManager,
pinia: applicationPinia(),
pickWorld: services.pickWorldFromScreen,
regionalBrief: services.fetchRegionalBrief,
overlayHit: services.hitTestWorldOverlay,
});
this.mapStackController = mapStackController;
this.placeSearch = placeSearch;
@@ -205,8 +239,8 @@ export class StyleManager extends ShellFacade {
this._showGlobalStatusNotice(message, options),
feedback: this._feedback,
updateFeedback: () => this._updateGlobalLoadingFeedback(),
applyFollowOffset: (entity, offset) =>
applyShareFollowOffset(viewer, entity, offset),
applyFollowOffset: (followed, offset) =>
applyShareFollowOffset(viewer, followed, offset),
});
this._visualSettings = new VisualSettings({
@@ -219,6 +253,7 @@ export class StyleManager extends ShellFacade {
getDetectionTuning: services.getDetectionTuning,
getKeyholeFadeTuning: services.getKeyholeFadeTuning,
getScopeMaskFeather: services.getScopeMaskFeather,
getScopeMaskOpacity: services.getScopeMaskOpacity,
getScopeTerminusOverride: services.getScopeTerminusOverride,
governorRequestRender: services.governorRequestRender,
holdContinuousRender: services.holdContinuousRender,
@@ -232,6 +267,7 @@ export class StyleManager extends ShellFacade {
setKeyholeFadeTuning: services.setKeyholeFadeTuning,
setScopeMaskEnabled: services.setScopeMaskEnabled,
setScopeMaskFeather: services.setScopeMaskFeather,
setScopeMaskOpacity: services.setScopeMaskOpacity,
},
elements: {
_ppToggles: this._ppToggles,
@@ -309,6 +345,7 @@ export class StyleManager extends ShellFacade {
this._locationNavigation = new LocationNavigation({
viewer,
placeSearch,
homeView,
navigation: this._navigation,
readCockpit: () => this.cockpitView,
services: {
@@ -384,6 +421,13 @@ export class StyleManager extends ShellFacade {
meshFloorPreferred: services.meshFloorPreferred,
warmGroundFloor: services.warmGroundFloor,
sampleMeshFloorCells: services.sampleMeshFloorCells,
// Whether the aircraft Cockpit flies still draws: an entity of the
// viewer's own (the scene's `viewerDrawsEntity` says), or a tracked
// contact whose layer draws it through the draw port and says so in
// its entity record.
trackedEntityDrawn: (entity) =>
services.viewerDrawsEntity?.(entity) === true ||
readEntityRecord(entity)?.drawn?.() === true,
holdContinuousRender: services.holdContinuousRender,
releaseContinuousRender: services.releaseContinuousRender,
fetchRegionalBrief: services.fetchRegionalBrief,
@@ -396,6 +440,9 @@ export class StyleManager extends ShellFacade {
owner: 'cockpit-orbit',
switchPolicy: 'esri-if-photoreal',
}) ?? null,
// The application's own first-person subjects
// (src/cockpitSubjectProviders.js), checked by the coordinator.
cockpitSubjects: services.cockpitSubjects,
},
elements: {
_ppToggles: this._ppToggles,
@@ -453,6 +500,8 @@ export class StyleManager extends ShellFacade {
this.celestialRing = new CelestialRing(viewer, {
enabled: false,
store: useCelestialRingStore(applicationPinia()),
// The precise frame, once the sky has loaded its tables.
preciseFrameAt: icrfToFixedAxes,
onAutoDisable: () =>
this.setCelestialRingEnabled(false, {
syncShare: !!this.shareLinkManager,
@@ -467,12 +516,17 @@ export class StyleManager extends ShellFacade {
},
isNavigationCurrent: (generation) =>
generation === this._navigationGeneration,
cancelOwnedNavigation: () => this.viewer.camera.cancelFlight(),
cancelOwnedNavigation: () => cameraOf(this.viewer).cancelFlight(),
// A host may open a share code without a `/share/<code>` address.
initialShareCode,
});
this.shareLinkManager.setFollowSubjectProvider(({ nowMs }) =>
readShareFollowSubject({ viewer: this.viewer, nowMs }),
readShareFollowSubject({
viewer: this.viewer,
nowMs,
readSelectedVessel: () =>
this.services.aisLiveVesselsLayer?.getSelectedFix?.() ?? null,
}),
);
this.shareLinkManager.setPanelStateProvider(() =>
this._buildSharePanelState(),
@@ -579,6 +633,10 @@ export class StyleManager extends ShellFacade {
this._setDetectionAllocation(...args),
_setDetectionFade: (...args) => this._setDetectionFade(...args),
_setScope: (...args) => this._visualSettings._setScope(...args),
_applyGlobalPostDefaults: (...args) =>
this._applyGlobalPostDefaults(...args),
_adoptDetectionAsRestore: () =>
this._visualSettings.adoptDetectionAsRestore(),
setCelestialRingEnabled: (...args) =>
this.setCelestialRingEnabled(...args),
_setModels3dEnabled: (...args) => this._setModels3dEnabled(...args),
@@ -755,7 +813,7 @@ export class StyleManager extends ShellFacade {
this._lifetime.own(
onLocaleChange(() => nextTick(() => this._sizeDisplayLabelColumn())),
);
// A host that does not initialize Core's locale shows no picker.
// A host that offers its own language choice shows no picker.
if (this._localePickerEnabled === false) return;
this._publishLocalePicker();
}
@@ -1039,7 +1097,7 @@ export class StyleManager extends ShellFacade {
_radioVolumeValue: this._radioVolumeValue,
},
radio: radioLayer,
canvas: this.viewer?.canvas,
canvas: canvasOf(this.viewer) ?? undefined,
actions: {
isRegistered: () => this._dataManager?.layers?.has('radio'),
isEnabled: () => this._dataManager?.isEnabled('radio'),
@@ -1138,6 +1196,7 @@ export class StyleManager extends ShellFacade {
this._dataManager?.setLayerParams('street-level', params, options),
setPanelCollapsed: (collapsed, options) =>
this.setPanelCollapsed('street-level-panel', collapsed, options),
revealPanel: () => this.revealPanel('street-level-panel'),
showToast: (message) => this._showToast(message),
// Lets the panel open for a user, voice or tool switch-on, not a restore.
subscribeEnableRequests: (listener) =>
@@ -1187,6 +1246,11 @@ export class StyleManager extends ShellFacade {
toggleEnabled: (...args) => this._toggleCctvEnabled(...args),
runExplicitFocus: (...args) => this._runExplicitCctvFocus(...args),
setPanelCollapsed: (...args) => this.setPanelCollapsed(...args),
// Clear selected data layers and Context isolation switch the layer
// off without the user asking: the panel keeps its state for both.
preservePanelState: () =>
this._preservePanelStateDuringLayerClear ||
this._contextSuspendsLayer('cctv'),
showToast: (message) => this._showToast(message),
syncViewport: () => this._syncCctvPanelViewport(),
},
@@ -1214,7 +1278,7 @@ export class StyleManager extends ShellFacade {
setEnabled: (next) =>
this._dataManager.setEnabled('cctv', next, { origin: 'user' }),
readOwnership: () => ({
trackedEntity: this.viewer?.trackedEntity,
followed: followedOf(this.viewer),
cockpitActive: !!this.cockpitView?.active,
}),
shouldFocus: () =>
@@ -1253,6 +1317,20 @@ export class StyleManager extends ShellFacade {
return this._panelChrome.setPanelCollapsed(...arguments);
}
/**
* Bring a panel into view on a phone, where the rails show only as tab
* sheets: opens the sheet that holds it. Does nothing above 720px.
* @param {string} panelId - DOM id of the panel.
* @returns {void}
*/
revealPanel(panelId) {
const sheet = sheetForPanelId(panelId);
if (!globalThis.matchMedia?.(MOBILE_SHELL_MEDIA_QUERY)?.matches) return;
if (sheet) this._mobileShell?.setSheet(sheet);
// The sheet opens at its top; a panel lower in the rail is scrolled to.
document.getElementById(panelId)?.scrollIntoView?.({ block: 'nearest' });
}
/**
* Toggles "clean view" mode which hides all UI panels via a CSS body class.
* @param {boolean} [forceEnabled] - Explicit on/off. Omit to toggle.
@@ -1359,9 +1437,12 @@ export class StyleManager extends ShellFacade {
};
}
if (!target.available) {
// The controller knows why (Google 3D: no Maps key; others: no ion token).
return {
ok: false,
error: `${target.label} requires a Cesium ion token`,
error:
target.unavailableReason ||
`${target.label} requires a Cesium ion token`,
activeStack: this.mapStackController.getActiveId(),
};
}
@@ -1473,15 +1554,16 @@ export class StyleManager extends ShellFacade {
* @returns {{lat: number, lon: number, alt: number, heading: number, pitch: number, roll: number}|null}
*/
getCameraState() {
const carto = this.viewer.camera.positionCartographic;
if (!carto) return null;
const pose = findCamera(this.viewer)?.pose();
if (!pose || !Number.isFinite(pose.lat) || !Number.isFinite(pose.lon))
return null;
return {
lat: Cesium.Math.toDegrees(carto.latitude),
lon: Cesium.Math.toDegrees(carto.longitude),
alt: carto.height,
heading: Cesium.Math.toDegrees(this.viewer.camera.heading),
pitch: Cesium.Math.toDegrees(this.viewer.camera.pitch),
roll: Cesium.Math.toDegrees(this.viewer.camera.roll),
lat: pose.lat,
lon: pose.lon,
alt: pose.height,
heading: toDegrees(pose.heading),
pitch: toDegrees(pose.pitch),
roll: toDegrees(pose.roll),
};
}
@@ -1493,20 +1575,18 @@ export class StyleManager extends ShellFacade {
*/
applyCameraState(cameraState, duration = 2.8) {
if (!cameraState) return;
this.viewer.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(
cameraState.lon,
cameraState.lat,
cameraState.alt,
),
orientation: {
heading: Cesium.Math.toRadians(cameraState.heading || 0),
pitch: Cesium.Math.toRadians(cameraState.pitch || -35),
roll: Cesium.Math.toRadians(cameraState.roll || 0),
cameraOf(this.viewer).flyTo(
{ lon: cameraState.lon, lat: cameraState.lat, height: cameraState.alt },
{
orientation: {
heading: toRadians(cameraState.heading || 0),
pitch: toRadians(cameraState.pitch || -35),
roll: toRadians(cameraState.roll || 0),
},
durationS: Math.max(0.2, duration || 0),
easing: 'cubicInOut',
},
duration: Math.max(0.2, duration || 0),
easingFunction: Cesium.EasingFunction.CUBIC_IN_OUT,
});
);
}
/**
@@ -1642,7 +1722,12 @@ export class StyleManager extends ShellFacade {
const store = useGlobeActionsStore(applicationPinia());
if (this._resetToken) store.detach(this._resetToken);
this._resetToken = controls
? store.connect({ reset: () => controls.reset() })
? store.connect({
reset: () => controls.reset(),
home: () => {
if (!this._disposed) void this.returnToStart();
},
})
: null;
// A reset under way as the controls are replaced stays on the buttons.
if (this._resetToken && this._globeResetting != null)
@@ -1758,7 +1843,7 @@ export class StyleManager extends ShellFacade {
* altitude ceiling, and only the nearest MODEL_MAX in view are admitted, so
* the default costs nothing at globe scale. `all` is the deliberate opt-in;
* turning the toggle off returns the fleet to flat billboards. The TRACKED
* contact is independent of this toggle (see trackedModelRegime.js).
* contact follows the same rule: selecting a contact never changes its form.
* @returns {void}
*/
@@ -1821,6 +1906,9 @@ export class StyleManager extends ShellFacade {
const { destroyTrackedReadout, destroyWorldOverlay, destroyDetection } =
this.services;
if (this._disposed) return;
useOmnibarStore(applicationPinia()).connect(null);
this._removeRailEdgeScroll?.();
this._removeEntityContext?.();
this._shareRestoration.destroy();
this._feedback.clearLoadingStatus();
this._disposed = true;
+9 -1
View File
@@ -10,7 +10,8 @@ const STYLE_KEYS = Object.freeze({
/**
* Bind the application's existing bubbling keyboard shortcuts.
* Capture-phase surfaces keep first refusal. The caller owns each action and
* persistence; form controls keep native typing except for Escape.
* persistence; form controls keep native typing except for Escape, and a key
* held with Cmd, Ctrl or Alt is left to the browser.
* @param {object} options
* @param {Document} options.documentRef Keyboard event target.
* @param {HTMLElement} options.searchInput Additional editing target.
@@ -27,6 +28,13 @@ export function bindApplicationShortcuts({
event.target?.matches?.('select, input, textarea') ||
event.target === searchInput;
if (isFormControl && event.key !== 'Escape') return;
// Cmd+C, Ctrl+F, Cmd+1 and the like belong to the browser and the system.
// Shift is not a chord here: Shift+C is still C.
if (
(event.metaKey || event.ctrlKey || event.altKey) &&
event.key !== 'Escape'
)
return;
if (STYLE_KEYS[event.key]) actions.setStyle(STYLE_KEYS[event.key]);
if (event.key === 'Escape') actions.dismissSearch();
+70
View File
@@ -245,3 +245,73 @@ test('a repaint that leaves focus outside the panel does not pull it back', asyn
'an empty cohort renders no list',
);
});
const photo = (extra = {}) => ({
src: 'https://t.plnspttrs.net/1/abc123_280.jpg',
width: 280,
height: 186,
link: 'https://www.planespotters.net/photo/1/n123ab',
credit: 'Photo © Jane Doe',
...extra,
});
test('a tracked flight’s photo shows under its name, credited and linked to its page', async (t) => {
const { panel, publish } = fixture(t);
await publish({ ...results(), photo: photo() });
const root = panel();
const link = root.querySelector('a.military-awareness-photo');
assert.ok(link, 'the photo renders');
assert.equal(
root.querySelector('.military-awareness-subject').nextElementSibling,
link,
'directly under the subject line',
);
assert.equal(link.getAttribute('href'), photo().link);
assert.equal(link.getAttribute('target'), '_blank');
assert.equal(link.getAttribute('rel'), 'noopener');
const img = link.querySelector('img');
assert.equal(img.getAttribute('src'), photo().src);
assert.equal(img.getAttribute('alt'), '');
assert.equal(img.getAttribute('width'), '280');
assert.equal(img.getAttribute('height'), '186');
assert.equal(link.querySelector('small').textContent, 'Photo © Jane Doe');
});
test('no photo renders without one', async (t) => {
const { panel, publish } = fixture(t);
await publish({ ...results(), photo: null });
assert.equal(panel().querySelector('.military-awareness-photo') === null, true);
});
test('a photo whose image fails to load is hidden until another arrives', async (t) => {
const { panel, publish } = fixture(t);
await publish({ ...results(), photo: photo() });
panel()
.querySelector('.military-awareness-photo img')
.dispatchEvent(new Event('error'));
await nextTick();
assert.equal(panel().querySelector('.military-awareness-photo') === null, true);
// A repaint with the same photo keeps it hidden.
await publish({ ...results({ previousDisabled: false }), photo: photo() });
assert.equal(panel().querySelector('.military-awareness-photo') === null, true);
// Another plane's photo shows.
const next = photo({ src: 'https://t.plnspttrs.net/2/def456_280.jpg' });
await publish({ ...results(), photo: next });
assert.equal(
panel().querySelector('.military-awareness-photo img').getAttribute('src'),
next.src,
);
});
test('a late error from a previous photo’s image does not hide the current one', async (t) => {
const { panel, publish } = fixture(t);
const previous = photo();
const current = photo({ src: 'https://t.plnspttrs.net/2/def456_280.jpg' });
await publish({ ...results(), photo: current });
// The error belongs to the image that failed: here, one still on the old src.
const img = panel().querySelector('.military-awareness-photo img');
img.setAttribute('src', previous.src);
img.dispatchEvent(new Event('error'));
await nextTick();
assert.ok(panel().querySelector('.military-awareness-photo'));
});
+121 -126
View File
@@ -1,142 +1,139 @@
import * as Cesium from 'cesium';
import { isPickedWorldPosition } from '../data/scenePick.js';
import { t } from '../i18n/index.js';
import {
followedOf,
followedPosition,
isFollowing,
onFollowChanged,
} from '../data/followed.js';
import {
clamp,
eastNorthUp,
inverseFramePoint,
magnitude,
negativePiToPi,
toDegrees,
toRadians,
TWO_PI,
zeroToTwoPi,
} from '../geo/index.js';
import {
canvasOf,
findCamera,
findFrame,
findQuery,
} from '../render/rendererOf.js';
import { placeFollowEye } from './shareFollow.js';
function trackedTarget(viewer) {
const entity = viewer.trackedEntity;
// Read the visual's sample first; sampling a flight CallbackProperty twice
// can advance dead reckoning ahead of the displayed aircraft.
return (
entity?.gevDisplayPosition?.() ||
entity?.position?.getValue(viewer.clock?.currentTime)
);
// The visual's sample first: sampling a flight CallbackProperty twice can
// advance dead reckoning ahead of the displayed aircraft.
return followedPosition(viewer, followedOf(viewer));
}
export const OBLIQUE_PITCH = Cesium.Math.toRadians(-35);
export const STRAIGHT_DOWN_PITCH = Cesium.Math.toRadians(-89);
const OBLIQUE_THRESHOLD = Cesium.Math.toRadians(-60);
export const OBLIQUE_PITCH = toRadians(-35);
export const STRAIGHT_DOWN_PITCH = toRadians(-89);
const OBLIQUE_THRESHOLD = toRadians(-60);
const EPSILON10 = 1e-10;
function normalizedHeading(heading) {
const wrapped = Cesium.Math.zeroToTwoPi(
Number.isFinite(heading) ? heading : 0,
);
return Math.abs(wrapped - Cesium.Math.TWO_PI) < Cesium.Math.EPSILON10
? 0
: wrapped;
const wrapped = zeroToTwoPi(Number.isFinite(heading) ? heading : 0);
return Math.abs(wrapped - TWO_PI) < EPSILON10 ? 0 : wrapped;
}
/** The camera port's pose, or null when there is none to read. */
function poseOf(camera) {
try {
return camera?.pose() ?? null;
} catch {
return null;
}
}
/** Cubic ease in and out, 0..1 to 0..1. */
function cubicInOut(k) {
if (k < 0.5) return 4 * k * k * k;
const f = 2 * k - 2;
return 0.5 * f * f * f + 1;
}
/** Return the world position under the center of the canvas, when available. */
export function pickViewTarget(viewer) {
const scene = viewer?.scene;
const camera = viewer?.camera;
const canvas = scene?.canvas;
if (!scene || !camera || !canvas) return null;
const query = findQuery(viewer);
const canvas = canvasOf(viewer);
if (!query || !canvas) return null;
const width = canvas.clientWidth || canvas.width || 0;
const height = canvas.clientHeight || canvas.height || 0;
if (!width || !height) return null;
const center = new Cesium.Cartesian2(width / 2, height / 2);
let target = null;
if (scene.pickPositionSupported && typeof scene.pickPosition === 'function') {
const x = width / 2;
const y = height / 2;
const attempt = (pick) => {
try {
target = scene.pickPosition(center);
return pick();
} catch {
target = null;
return null;
}
}
// Terrain before the ellipsoid: globe.pick intersects the rendered surface,
// so over keyless elevated terrain it returns the ground the operator is
// looking at. pickEllipsoid answers with sea level, which on a plateau sits
// far below the view and would swing the camera on every tilt.
if (
!isPickedWorldPosition(target) &&
typeof camera.getPickRay === 'function'
) {
try {
target = scene.globe?.pick(camera.getPickRay(center), scene) || null;
} catch {
target = null;
}
}
if (
!isPickedWorldPosition(target) &&
typeof camera.pickEllipsoid === 'function'
) {
try {
target = camera.pickEllipsoid(center, Cesium.Ellipsoid.WGS84);
} catch {
target = null;
}
}
};
// Depth first: what is drawn under the centre, tiles included.
let target = attempt(() => query.pickPosition(x, y));
// Terrain before the ellipsoid: the globe pick intersects the rendered
// surface, so over keyless elevated terrain it returns the ground the
// operator is looking at. The ellipsoid answers with sea level, which on a
// plateau sits far below the view and would swing the camera on every tilt.
if (!isPickedWorldPosition(target))
target = attempt(() => query.pickGlobe(query.pickRay(x, y)));
if (!isPickedWorldPosition(target))
target = attempt(() => query.pickEllipsoid(x, y));
return isPickedWorldPosition(target) ? target : null;
}
/** Describe the camera as an orbit around the current viewport center. */
export function readCameraTargetFrame(viewer) {
const camera = viewer?.camera;
const target = viewer?.trackedEntity
const pose = poseOf(findCamera(viewer));
const target = isFollowing(viewer)
? trackedTarget(viewer)
: pickViewTarget(viewer);
if (!camera || !target || !isPickedWorldPosition(camera.positionWC))
return null;
if (!pose || !target || !isPickedWorldPosition(pose.position)) return null;
const transform = Cesium.Transforms.eastNorthUpToFixedFrame(target);
const inverse = Cesium.Matrix4.inverseTransformation(
transform,
new Cesium.Matrix4(),
);
const localOffset = Cesium.Matrix4.multiplyByPoint(
inverse,
camera.positionWC,
new Cesium.Cartesian3(),
);
const range = Cesium.Cartesian3.magnitude(localOffset);
const localOffset = inverseFramePoint(eastNorthUp(target), pose.position);
const range = magnitude(localOffset);
if (!Number.isFinite(range) || range < 1) return null;
const pitch = -Math.asin(Cesium.Math.clamp(localOffset.z / range, -1, 1));
// Cesium places a lookAt camera at range * (-sin h cos p, -cos h cos p,
// -sin p) in the target's east-north-up frame, so recovering h means
// negating BOTH horizontal components. Negating only the north one reads
// every heading as its mirror image (30 deg comes back as 330), which would
// make north-up rotate the wrong way from three quarters of the compass.
const pitch = -Math.asin(clamp(localOffset.z / range, -1, 1));
// A lookAt camera sits at range * (-sin h cos p, -cos h cos p, -sin p) in
// the target's east-north-up frame, so recovering h means negating BOTH
// horizontal components. Negating only the north one reads every heading
// as its mirror image (30 deg comes back as 330), which would make north-up
// rotate the wrong way from three quarters of the compass.
const targetHeading = Math.atan2(-localOffset.x, -localOffset.y);
const heading = normalizedHeading(
pitch < Cesium.Math.toRadians(-88.5) ? camera.heading : targetHeading,
pitch < toRadians(-88.5) ? pose.heading : targetHeading,
);
return { target, range, heading, pitch };
}
/** Apply an orbit frame, then return the camera to Cesium's fixed-world frame. */
/** Apply an orbit frame, then return the camera to the world frame. */
function setCameraTargetFrame(viewer, frame) {
const camera = viewer?.camera;
const camera = findCamera(viewer);
if (!camera || !frame?.target || !Number.isFinite(frame.range)) return false;
const offset = {
heading: normalizedHeading(frame.heading),
pitch: frame.pitch,
range: frame.range,
};
try {
const trackedTransform = viewer.trackedEntity
? Cesium.Matrix4.clone(camera.transform)
: null;
camera.lookAt(
frame.target,
new Cesium.HeadingPitchRange(
normalizedHeading(frame.heading),
frame.pitch,
frame.range,
),
);
if (trackedTransform) {
// Preserve EntityView's reference frame (including satellite frames).
// Its next update carries this new local offset along with the target.
camera.lookAtTransform(trackedTransform);
viewer.scene?.requestRender?.();
return true;
}
const destination = Cesium.Cartesian3.clone(camera.positionWC);
const direction = Cesium.Cartesian3.clone(camera.directionWC);
const up = Cesium.Cartesian3.clone(camera.upWC);
camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
if (destination && direction && up) {
camera.setView({ destination, orientation: { direction, up } });
}
viewer.scene?.requestRender?.();
// Following keeps the follow's own frame (satellite frames included):
// its next update carries the new offset along with the target.
if (isFollowing(viewer))
return placeFollowEye(viewer, frame.target, offset);
camera.lookAt(frame.target, offset);
const pose = camera.pose();
camera.release();
if (pose?.position && pose.direction && pose.up)
camera.setView({
destination: pose.position,
orientation: { direction: pose.direction, up: pose.up },
});
return true;
} catch {
return false;
@@ -179,8 +176,8 @@ export function resetCameraNorth(viewer) {
return setCameraTargetFrame(viewer, { ...frame, heading: 0 });
}
function headingDegrees(camera) {
return Cesium.Math.toDegrees(normalizedHeading(camera?.heading));
function headingDegrees(viewer) {
return toDegrees(normalizedHeading(poseOf(findCamera(viewer))?.heading));
}
/** Ease an orbit without handing off the entity that owns the follow camera. */
@@ -197,29 +194,28 @@ export function createCameraOrientationAnimator(
};
function animate(frame, destination) {
cancel();
if (!viewer.scene?.preUpdate?.addEventListener || duration <= 0)
const frames = findFrame(viewer);
if (!frames || duration <= 0)
return setCameraTargetFrame(viewer, { ...frame, ...destination });
const entity = viewer.trackedEntity;
const followed = followedOf(viewer);
pending = destination;
const start = now();
const headingDelta = Cesium.Math.negativePiToPi(
destination.heading - frame.heading,
);
remove = viewer.scene.preUpdate.addEventListener(() => {
if (viewer.isDestroyed?.() || viewer.trackedEntity !== entity) {
const headingDelta = negativePiToPi(destination.heading - frame.heading);
remove = frames.on('preUpdate', () => {
if (viewer.isDestroyed?.() || followedOf(viewer) !== followed) {
cancel();
return;
}
const progress = Cesium.Math.clamp((now() - start) / duration, 0, 1);
const eased = Cesium.EasingFunction.CUBIC_IN_OUT(progress);
const target = entity ? trackedTarget(viewer) : frame.target;
const progress = clamp((now() - start) / duration, 0, 1);
const eased = cubicInOut(progress);
const target = followed ? trackedTarget(viewer) : frame.target;
if (
!isPickedWorldPosition(target) ||
!setCameraTargetFrame(viewer, {
...frame,
target,
heading: frame.heading + headingDelta * eased,
pitch: Cesium.Math.lerp(frame.pitch, destination.pitch, eased),
pitch: (1 - eased) * frame.pitch + eased * destination.pitch,
})
) {
cancel();
@@ -227,7 +223,7 @@ export function createCameraOrientationAnimator(
}
if (progress === 1) cancel();
});
viewer.scene.requestRender?.();
frames.requestRender('camera-orientation');
return true;
}
return {
@@ -280,7 +276,7 @@ export function bindCameraOrientationControls({
if (destroyed) return;
const next = {
tilted,
heading: Math.round(headingDegrees(viewer?.camera)) % 360,
heading: Math.round(headingDegrees(viewer)) % 360,
};
publish?.(next);
}
@@ -326,20 +322,19 @@ export function bindCameraOrientationControls({
sync();
}
const subscribe = (event, handler) => {
const remove = event?.addEventListener?.(handler);
const subscribe = (remove) => {
if (typeof remove === 'function') removers.push(remove);
};
// The needle follows every frame the scene draws. `camera.changed` is NOT
// enough: it only fires past `camera.percentageChanged`, so a rotation of a
// few degrees leaves the needle pointing at the old bearing.
subscribe(viewer?.scene?.preRender, sync);
// The needle follows every frame the scene draws. The camera's `changed`
// is NOT enough: it only fires past its threshold, so a rotation of a few
// degrees leaves the needle pointing at the old bearing.
subscribe(findFrame(viewer)?.on('preRender', sync));
// The exact tilt state is refreshed once per gesture, not once per frame —
// moveEnd fires when the camera stops, which is where the pick is affordable.
subscribe(viewer?.camera?.moveEnd, refreshTilt);
subscribe(viewer?.trackedEntityChanged, animator.cancel);
subscribe(findCamera(viewer)?.on('moveEnd', refreshTilt));
if (viewer) removers.push(onFollowChanged(viewer, animator.cancel));
for (const type of ['pointerdown', 'wheel']) {
const canvas = viewer?.scene?.canvas;
const canvas = canvasOf(viewer);
canvas?.addEventListener?.(type, animator.cancel, { passive: true });
removers.push(() => canvas?.removeEventListener?.(type, animator.cancel));
}
+83 -26
View File
@@ -12,6 +12,39 @@ import {
toggleCameraTilt,
} from './cameraOrientationControls.js';
import { NavigationController } from './navigationController.js';
import { bindRenderer } from '../render/rendererOf.js';
import {
createCesiumQuery,
queryCapabilities,
} from '../render/cesium/query.js';
import {
bindFakeCesiumCamera,
followEntity,
followedEntity,
} from '../testSupport/fakeCameraPort.mjs';
import { entityFollowTarget } from '../data/followed.js';
import { fakeSceneFrame } from '../testSupport/fakeCesiumScene.mjs';
import { entityRecord } from '../data/entityRecords.js';
/**
* Bind the camera, query and frame ports over a viewer double, as the
* renderer does: the Cesium query port over its scene, and the frame
* phases from the scene's own events.
*/
function withPorts(viewer, { frames = true } = {}) {
return bindFakeCesiumCamera(viewer, {
query: createCesiumQuery({
scene: viewer.scene,
camera: viewer.camera,
draw: { sets: new Map(), version: () => 0 },
capabilities: new Set(queryCapabilities(viewer.scene)),
}),
...(frames ? { frame: fakeSceneFrame(viewer) } : {}),
});
}
/** Coordinates only, as the query port answers. */
const plain = (p) => ({ x: p.x, y: p.y, z: p.z });
function createViewer({ cameraPosition, target, pickPosition = null } = {}) {
const calls = [];
@@ -25,7 +58,7 @@ function createViewer({ cameraPosition, target, pickPosition = null } = {}) {
heading: Cesium.Math.toRadians(90),
changed,
pickEllipsoid: () => surface,
getPickRay: () => ({}),
getPickRay: () => new Cesium.Ray(),
lookAt(targetValue, offset) {
calls.push({ type: 'lookAt', target: targetValue, offset });
},
@@ -46,7 +79,7 @@ function createViewer({ cameraPosition, target, pickPosition = null } = {}) {
requestRender: () => calls.push({ type: 'requestRender' }),
},
};
return { viewer, calls, target: surface };
return { viewer: withPorts(viewer), calls, target: surface };
}
/**
@@ -96,8 +129,12 @@ function createRealCamera() {
return { camera, scene };
}
/** A viewer whose center pick is a fixed ground point and whose camera is real. */
function createRealViewer(target) {
/**
* A viewer whose center pick is a fixed ground point and whose camera is
* real. Without `frames` it has no frame loop, so orientation changes land
* at once rather than easing.
*/
function createRealViewer(target, { frames = true } = {}) {
const { camera, scene } = createRealCamera();
scene.pickPositionSupported = false;
scene.pickPosition = () => null;
@@ -106,8 +143,16 @@ function createRealViewer(target) {
// The binding drives the needle from the scene's per-frame signal, not from
// `camera.changed`, so the fixture has to carry one.
scene.preRender = new Cesium.Event();
camera.getPickRay = () => ({});
return { viewer: { camera, scene }, target };
camera.getPickRay = () => new Cesium.Ray();
// Cesium's entity tracking, without entities of its own: the camera port
// follows on a tracking widget of the fake's.
const viewer = {
camera,
scene,
trackedEntityChanged: new Cesium.Event(),
entities: {},
};
return { viewer: withPorts(viewer, { frames }), target };
}
/** Place a real camera in an orbit around `target` and release the frame. */
@@ -277,7 +322,7 @@ test('tilt alternates at globe range, not only at map range', () => {
test('the button shows the state the next click will produce, at every range', () => {
for (const range of [3_000, 18_000_000]) {
const { viewer } = createRealViewer(AUSTIN_GROUND);
const { viewer } = createRealViewer(AUSTIN_GROUND, { frames: false });
orbit(viewer, AUSTIN_GROUND, 0, STRAIGHT_DOWN_PITCH, range);
const bar = recorder();
const controls = bindCameraOrientationControls({
@@ -408,9 +453,13 @@ test('a sky-facing camera yields no frame and both actions decline', () => {
scene.pickPosition = () => null;
scene.globe.pick = () => undefined;
scene.requestRender = () => {};
camera.getPickRay = () => ({});
camera.pickEllipsoid = () => undefined;
const viewer = { camera, scene };
// 1000 km up, looking above the horizon: no ray from the centre meets
// the ellipsoid.
camera.setView({
destination: Cesium.Cartesian3.fromDegrees(-97.74, 30.27, 1_000_000),
orientation: { heading: 0, pitch: Cesium.Math.toRadians(30), roll: 0 },
});
const viewer = withPorts({ camera, scene });
assert.equal(readCameraTargetFrame(viewer), null);
assert.equal(toggleCameraTilt(viewer), false);
@@ -424,16 +473,16 @@ test('center picking prefers terrain over the ellipsoid and falls through an inv
const { viewer } = createViewer({ pickPosition: () => invalid });
viewer.scene.globe.pick = () => terrain;
viewer.camera.pickEllipsoid = () => sea;
assert.equal(
assert.deepEqual(
pickViewTarget(viewer),
terrain,
plain(terrain),
'the rendered ground wins over sea level',
);
viewer.scene.globe.pick = () => null;
assert.equal(
assert.deepEqual(
pickViewTarget(viewer),
sea,
plain(sea),
'the ellipsoid still answers when nothing is under the cursor',
);
});
@@ -453,7 +502,7 @@ test('tilt preserves the picked target and range while choosing oblique pitch',
const result = toggleCameraTilt(viewer);
const lookAt = calls.find((call) => call.type === 'lookAt');
assert.deepEqual(result, { tilted: true, pitch: OBLIQUE_PITCH });
assert.equal(lookAt.target, target);
assert.ok(Cesium.Cartesian3.equals(lookAt.target, target));
assert.equal(lookAt.offset.range, before.range);
assert.equal(lookAt.offset.pitch, OBLIQUE_PITCH);
assert.ok(calls.some((call) => call.type === 'lookAtTransform'));
@@ -523,8 +572,8 @@ for (const [label, altitude, range] of [
position: new Cesium.CallbackPositionProperty(() => target, false),
trackingReferenceFrame: Cesium.TrackingReferenceFrame.ENU,
});
entity.gevDisplayPosition = () => target;
viewer.trackedEntity = entity;
entityRecord(entity).displayPosition = () => target;
followEntity(viewer, entity);
const follow = new Cesium.EntityView(entity, viewer.scene);
follow.update(viewer.clock.currentTime);
viewer.camera.lookAt(
@@ -553,7 +602,7 @@ for (const [label, altitude, range] of [
follow.update(viewer.clock.currentTime);
const transform = Cesium.Matrix4.clone(viewer.camera.transform);
viewer.scene.preUpdate.raiseEvent();
assert.equal(viewer.trackedEntity, entity);
assert.equal(followedEntity(viewer), entity);
assert.ok(
Cesium.Matrix4.equalsEpsilon(
viewer.camera.transform,
@@ -573,7 +622,7 @@ for (const [label, altitude, range] of [
}
target = Cesium.Cartesian3.fromDegrees(-96, 31, altitude);
follow.update(viewer.clock.currentTime);
assert.equal(viewer.trackedEntity, entity);
assert.equal(followedEntity(viewer), entity);
assert.ok(Math.abs(readCameraTargetFrame(viewer).range - range) < 1e-5);
});
}
@@ -587,10 +636,10 @@ test('orientation animation cancels on replacement and explicit cancellation', (
animator.animate(frame, { heading: 0, pitch: STRAIGHT_DOWN_PITCH });
animator.animate(frame, { heading: 0, pitch: OBLIQUE_PITCH });
assert.equal(viewer.scene.preUpdate.numberOfListeners, 1);
viewer.trackedEntity = {};
followEntity(viewer, {});
viewer.scene.preUpdate.raiseEvent();
assert.equal(viewer.scene.preUpdate.numberOfListeners, 0);
viewer.trackedEntity = undefined;
followEntity(viewer, null);
animator.animate(frame, { heading: 0, pitch: STRAIGHT_DOWN_PITCH });
animator.cancel();
assert.equal(viewer.scene.preUpdate.numberOfListeners, 0);
@@ -599,10 +648,18 @@ test('orientation animation cancels on replacement and explicit cancellation', (
test('orientation navigation preserves follow and selection; new navigation cancels animation', () => {
const calls = [];
const entity = {};
const viewer = {
trackedEntity: entity,
camera: { cancelFlight: () => calls.push('cancel-flight') },
};
const viewer = {};
bindRenderer(viewer, {
camera: {
cancelFlight: () => calls.push('cancel-flight'),
// The camera follows `entity`.
followed: entityFollowTarget(entity, {}),
follow(target) {
this.followed = target;
},
on: () => () => {},
},
});
let cockpit = false;
const navigation = new NavigationController({
viewer,
@@ -619,7 +676,7 @@ test('orientation navigation preserves follow and selection; new navigation canc
navigation.runOrientation('camera', () => 'animated'),
'animated',
);
assert.equal(viewer.trackedEntity, entity);
assert.equal(followedEntity(viewer), entity);
assert.deepEqual(calls, [
'cancel-orientation',
'interrupt-motion',
+1
View File
@@ -54,6 +54,7 @@ export class CctvControls {
this._cctvSummaryTypingTimer = null;
this._lastCctvSummaryText = '';
this._lastSeenCctvActiveId = null;
this._wasCctvEnabled = false;
this._cctvChipHideTimer = null;
this._cctvChipWasBusy = false;
// The camera grid chip as last published; its label stays while hidden.
+45
View File
@@ -1,6 +1,7 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { CctvControls } from './cctvControls.js';
import { CCTV_FRAME_DECODE_WAIT_MS } from './cctvFrames.js';
function element() {
const classes = new Set();
@@ -59,6 +60,50 @@ test('a late image completion cannot replace a newer camera preview', (t) => {
assert.equal(controls._frame.cameraId, 'b');
});
test('a camera frame settles once decoded, and a stale decode cannot land', async (t) => {
const { controls, requests } = fixture(t);
const decodes = [];
const queue = (src, id) => {
controls._queueCctvFrame(src, id, true);
const request = requests.at(-1);
request.decode = () =>
new Promise((resolve) => decodes.push({ src, resolve }));
return request;
};
const first = queue('first.jpg', 'a');
first.onload();
assert.equal(controls._frame.hasFrame, false);
const second = queue('second.jpg', 'b');
second.onload();
decodes[1].resolve();
await Promise.resolve();
decodes[0].resolve();
await Promise.resolve();
assert.equal(controls._frame.src, 'second.jpg');
assert.equal(controls._frame.cameraId, 'b');
assert.equal(controls._frame.hasFrame, true);
});
test('a loaded frame shows when its decode rejects or never settles', async (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
const { controls, requests } = fixture(t);
controls._queueCctvFrame('broken.jpg', 'a', true);
requests[0].decode = () => Promise.reject(new Error('EncodingError'));
requests[0].onload();
await Promise.resolve();
await Promise.resolve();
assert.equal(controls._frame.src, 'broken.jpg');
assert.equal(controls._frame.hasFrame, true);
controls._queueCctvFrame('hidden.jpg', 'b', true);
requests[1].decode = () => new Promise(() => {});
requests[1].onload();
assert.equal(controls._frame.hasFrame, false);
t.mock.timers.tick(CCTV_FRAME_DECODE_WAIT_MS);
assert.equal(controls._frame.src, 'hidden.jpg');
assert.equal(controls._frame.hasFrame, true);
});
test('failed refresh preserves settled pixels, but changing cameras clears them', (t) => {
const { controls, requests } = fixture(t);
controls._queueCctvFrame('first.jpg', 'a', true);
+25 -1
View File
@@ -77,6 +77,9 @@ export function cctvSourceLabelText(label) {
return SOURCE_LABELS[text] ? t(SOURCE_LABELS[text]) : text;
}
/** Longest wait for a loaded frame's decode before it is shown anyway. */
export const CCTV_FRAME_DECODE_WAIT_MS = 1000;
/** The preview before any frame: nothing requested, nothing shown. */
export const EMPTY_CCTV_FRAME = Object.freeze({
cameraId: '',
@@ -127,7 +130,28 @@ export function _queueCctvFrame(src, cameraId, cameraChanged) {
const preloader = new Image();
this._cctvFramePreloader = preloader;
preloader.onload = () => this._settleCctvFrame(token, src, true);
// Settle once the image is decoded, not merely loaded: the panel's <img>
// then paints the frame the moment it takes the src, instead of showing
// its empty box for the decode.
// A decode that rejects after a load still has drawable data, as it was
// before decoding was awaited. A decode that never settles (a hidden tab may
// hold it until the page draws) shows the loaded frame after
// CCTV_FRAME_DECODE_WAIT_MS rather than leaving the preview loading.
preloader.onload = () => {
if (typeof preloader.decode !== 'function') {
this._settleCctvFrame(token, src, true);
return;
}
let settled = false;
const settle = () => {
if (settled) return;
settled = true;
clearTimeout(timer);
this._settleCctvFrame(token, src, true);
};
const timer = setTimeout(settle, CCTV_FRAME_DECODE_WAIT_MS);
preloader.decode().then(settle, settle);
};
preloader.onerror = () => this._settleCctvFrame(token, src, false);
preloader.src = src;
}
+93
View File
@@ -513,3 +513,96 @@ test('the panel meta line reads a bearing that rounds to north as HDG 0°', () =
assert.match(meta(359.4), /· HDG 359° ·/);
assert.match(meta(359.6), /· HDG 0° ·/);
});
/** The panel collapses the test asked for, as `[panelId, collapsed]` pairs. */
function collapseCalls(controls) {
const calls = [];
controls.actions.setPanelCollapsed = (panelId, collapsed) => {
calls.push([panelId, collapsed]);
// The panel chrome owns the class the controls read back.
controls._cctvPanel.classList.toggle('collapsed', collapsed);
};
return calls;
}
const activeState = {
enabled: true,
count: 1,
cameraIndex: [],
activeCameraId: camera.id,
activeCamera: camera,
};
test('switching the layer off collapses the panel it opened', (t) => {
const { controls } = panel(t);
const calls = collapseCalls(controls);
controls._renderCctvState(activeState);
assert.deepEqual(calls, [['cctv-panel', false]]);
// The layer keeps its active camera while off.
controls._renderCctvState({ ...activeState, enabled: false });
assert.deepEqual(calls.at(-1), ['cctv-panel', true]);
// A panel reopened by hand stays open through later notifications while
// the layer is off: only the on → off change collapses.
controls._cctvPanel.classList.remove('collapsed');
controls._renderCctvState({ ...activeState, enabled: false });
assert.equal(calls.length, 2);
assert.equal(controls._cctvPanel.classList.contains('collapsed'), false);
});
test('a layer that was never on leaves an open panel alone', (t) => {
const { controls } = panel(t);
const calls = collapseCalls(controls);
controls._renderCctvState({ enabled: false, count: 3, cameraIndex: [] });
controls._renderCctvState({ enabled: false, count: 3, cameraIndex: [] });
assert.deepEqual(calls, []);
});
test('the data manager switching the layer off collapses the panel too', (t) => {
const { controls } = panel(t);
const calls = collapseCalls(controls);
let on = true;
controls.actions.isEnabled = () => on;
controls._renderCctvState(activeState);
on = false;
controls._renderCctvState(activeState);
assert.deepEqual(calls.at(-1), ['cctv-panel', true]);
});
test('a layer the application suspends keeps its panel through the round trip', (t) => {
const { controls } = panel(t);
const calls = collapseCalls(controls);
// Clear selected data layers and Context isolation both answer true.
let suspended = true;
controls.actions.preservePanelState = () => suspended;
controls._renderCctvState(activeState);
controls._renderCctvState({ ...activeState, enabled: false });
assert.equal(controls._cctvPanel.classList.contains('collapsed'), false);
suspended = false;
controls._renderCctvState(activeState);
assert.equal(controls._cctvPanel.classList.contains('collapsed'), false);
assert.ok(calls.every(([, collapsed]) => collapsed === false));
// The next switch-off is the user's again.
controls._renderCctvState({ ...activeState, enabled: false });
assert.deepEqual(calls.at(-1), ['cctv-panel', true]);
});
test('a panel the accordion folded still has its saved state closed', (t) => {
const { controls } = panel(t);
controls._renderCctvState(activeState);
const calls = [];
controls.actions.setPanelCollapsed = (...args) => calls.push(args);
// Folded for layout only: the class is there, the saved state is open. The
// panel chrome tells the two apart, so the controls always ask it.
controls._cctvPanel.classList.add('collapsed');
controls._renderCctvState({ ...activeState, enabled: false });
assert.deepEqual(calls, [['cctv-panel', true]]);
});
test('the meta line of a disabled layer does not describe its last camera', () => {
const off = { ...activeState, enabled: false, count: 3 };
assert.equal(
presentCctvPanel(off, false).meta,
'3 cameras loaded · enable CCTV to activate',
);
assert.match(presentCctvPanel(activeState, true).meta, /^Austin · HDG /);
});
+17 -1
View File
@@ -90,7 +90,9 @@ export function presentCctvPanel(state, enabled) {
}
function metaText(state, enabled, activeCamera, catalogCount) {
if (activeCamera) {
// The layer keeps its active camera while off: a disabled panel must not
// describe a feed it no longer shows.
if (enabled && activeCamera) {
const provider = cctvSourceLabelText(
activeCamera.sourceLabel || activeCamera.provider || 'Configured Source',
);
@@ -188,6 +190,20 @@ export function _renderCctvState(state) {
});
}
this._lastSeenCctvActiveId = effectiveActiveId;
// Switching the layer off closes the panel it opened: nothing is left to
// show. Only the on → off change collapses, so a panel the user opens
// while the layer is off stays open. Clear selected data layers and
// Context isolation keep the panel: the layer comes back with it. The
// panel chrome decides whether anything changes: a panel the desktop
// accordion only folded still has an open saved state to close.
if (
this._wasCctvEnabled &&
!enabled &&
!this.actions.preservePanelState?.()
) {
this.actions.setPanelCollapsed('cctv-panel', true);
}
this._wasCctvEnabled = enabled;
this._updateCctvSyncChip(state?.loading, enabled);
+141 -20
View File
@@ -7,14 +7,22 @@ import assert from 'node:assert/strict';
import { createPinia } from 'pinia';
import { createApp, defineComponent, h, nextTick } from 'vue';
import { CockpitViewController } from './cockpitController.js';
import { setLocale } from '../i18n/index.js';
import { useCockpitStore } from './stores/cockpit.js';
import CockpitView from './views/CockpitView.vue';
import ContextView from './views/ContextView.vue';
import * as Cesium from 'cesium';
import {
bindFakeCesiumCamera,
followEntity,
followedEntity,
} from '../testSupport/fakeCameraPort.mjs';
import { fakeScenePorts } from '../testSupport/fakeCesiumScene.mjs';
import { vesselCockpitInfo } from '../layers/vessels/cockpitSubject.js';
import { VesselRecords } from '../layers/vessels/records.js';
const RECORD = Object.freeze({
id: '211000000',
mmsi: '211000000',
name: 'NORDIC STAR',
type: '70',
@@ -65,9 +73,9 @@ function vesselLayer(record) {
enabled && selected
? { ...vesselCockpitInfo(selected), seaSurfaceHeightM: 0 }
: null,
setCockpitSubject(mmsi) {
calls.push(['subject', mmsi]);
subject = mmsi;
setCockpitSubject(id) {
calls.push(['subject', id]);
subject = id;
return true;
},
// Like the layer, leaves out the ship whose bridge the Cockpit rides.
@@ -75,7 +83,7 @@ function vesselLayer(record) {
radarQueries.push({ lat, lon, rangeM, maxCount });
const own = {
...NEIGHBOUR,
id: record.mmsi,
id: record.id,
latitude: record.lat,
longitude: record.lon,
};
@@ -88,6 +96,54 @@ function vesselLayer(record) {
};
}
/**
* The query port over the test's fake scene, as the Cesium adapter answers
* it: a position is drawn where `scene.cartesianToCanvasCoordinates` says;
* heights come from `scene.sampleHeight` (loaded tiles, at once) and
* `scene.sampleHeightMostDetailed` (the full-detail read), per probe.
*/
/** The surfaces the bridge's height reads asked for, in order. */
const surfacesAsked = [];
function sceneQuery(viewer, ports) {
const scene = () => viewer.scene;
const cartographic = ({ lon, lat }) =>
Cesium.Cartographic.fromDegrees(lon, lat);
return {
...ports.query,
project: (position) =>
scene().cartesianToCanvasCoordinates?.(position, {}) ?? null,
sampleHeightNow(point, options = {}) {
surfacesAsked.push(options.against ?? 'surface');
const height = scene().sampleHeight?.(cartographic(point));
return Number.isFinite(height) ? height : null;
},
sampleHeight(points, { mostDetailed = false, against = 'surface' } = {}) {
surfacesAsked.push(against);
if (
!mostDetailed ||
typeof scene().sampleHeightMostDetailed !== 'function'
)
return Promise.resolve(points.map(() => null));
// Answered as soon as the scene's read lands, as the adapter does.
return scene()
.sampleHeightMostDetailed(points.map(cartographic))
.then((sampled) =>
(sampled || []).map((position) =>
Number.isFinite(position?.height)
? {
height: position.height,
confidence: 1,
source: 'tiles',
lod: 'finest',
}
: null,
),
);
},
};
}
function fixture(
t,
{ bridgeAllowed = true, record = RECORD, aircraftInfo = null } = {},
@@ -114,7 +170,6 @@ function fixture(
// Each placed camera: where it is and where it looks.
const shots = [];
const viewer = {
trackedEntity: undefined,
clock: { currentTime: null },
camera: {
cancelFlight() {},
@@ -141,6 +196,11 @@ function fixture(
const disableFlights = () => {
flightsEnabled = false;
};
// The Cockpit drives the camera, reads frames and queries the scene
// through ports: the Cesium camera port over the fake camera, and a query
// that answers from the test's scene (`sceneQuery`).
const ports = fakeScenePorts(viewer);
bindFakeCesiumCamera(viewer, { ...ports, query: sceneQuery(viewer, ports) });
const cockpit = new CockpitViewController(viewer, {
services: {
flightsLayer: {
@@ -257,7 +317,7 @@ test('entering the bridge hides the vessel and shows bridge readouts', async (t)
await settle();
assert.equal(cockpit.active, true);
assert.equal(cockpit.subjectKind, 'vessel');
assert.deepEqual(vessels.calls, [['subject', RECORD.mmsi]]);
assert.deepEqual(vessels.calls, [['subject', RECORD.id]]);
assert.equal(document.body.classList.contains('cockpit-mode'), true);
assert.equal(
@@ -303,7 +363,7 @@ test('exiting the bridge releases the vessel and returns to its map view', async
assert.equal(cockpit.active, false);
assert.equal(cockpit.subjectKind, null);
assert.deepEqual(vessels.calls, [
['subject', RECORD.mmsi],
['subject', RECORD.id],
['subject', null],
['focus'],
]);
@@ -354,6 +414,33 @@ test('the bridge radar shows nearby ships without its own and steps its range',
assert.ok(!$('#cockpit-radar') || $('#cockpit-radar').hidden);
});
test('the radar range and ring spacing agree with their distance (ru)', async (t) => {
const { $, cockpit } = fixture(t);
t.after(() => setLocale('en'));
setLocale('ru');
cockpit.enter();
await settle();
const shown = () => [
$('#cockpit-radar-range').textContent.trim(),
$('.cockpit-radar-rings').textContent.trim(),
];
// The ring spacing is a fraction at the short ranges: Intl.PluralRules
// gives 0.75 and 1.5 the form of their own.
const expected = [
['3 МОР. МИЛИ', 'КОЛЬЦА 0,75 МОР. МИЛИ'],
['6 МОР. МИЛЬ', 'КОЛЬЦА 1,5 МОР. МИЛИ'],
['12 МОР. МИЛЬ', 'КОЛЬЦА 3 МОР. МИЛИ'],
['24 МОР. МИЛИ', 'КОЛЬЦА 6 МОР. МИЛЬ'],
];
for (const [index, labels] of expected.entries()) {
if (index) {
$('#cockpit-radar-range').click();
await settle();
}
assert.deepEqual(shown(), labels);
}
});
test('contact navigation does not jump ship from the bridge', async (t) => {
const { cockpit, navigations } = fixture(t);
cockpit.enter();
@@ -368,17 +455,29 @@ test('tracking an aircraft from the bridge ends it without refocusing the vessel
const { cockpit, viewer, vessels, aircraft } = fixture(t);
cockpit.enter();
await settle();
viewer.trackedEntity = aircraft;
followEntity(viewer, aircraft);
cockpit.update();
assert.equal(cockpit.active, false);
assert.equal(viewer.trackedEntity, aircraft, 'the aircraft keeps tracking');
assert.equal(followedEntity(viewer), aircraft, 'the aircraft keeps tracking');
assert.equal(aircraft.show, true, 'the aircraft was never adopted');
assert.deepEqual(vessels.calls, [
['subject', RECORD.mmsi],
['subject', RECORD.id],
['subject', null],
]);
});
test('following a satellite or a site from the bridge ends it too', async (t) => {
const { cockpit, viewer, vessels } = fixture(t);
cockpit.enter();
await settle();
// A satellite's or an installation's follow carrier has no position of
// its own (the camera reads the follow target's).
followEntity(viewer, { id: 'satellites:25544', noradId: 25544 });
cockpit.update();
assert.equal(cockpit.active, false);
assert.deepEqual(vessels.calls.at(-1), ['subject', null]);
});
test('a vessel that leaves the selection ends the bridge', async (t) => {
const { cockpit, vessels } = fixture(t);
cockpit.enter();
@@ -414,7 +513,7 @@ test("turning off the ridden aircraft's layer ends the cockpit", async (t) => {
const { cockpit, viewer, aircraft, disableFlights } = fixture(t, {
aircraftInfo,
});
viewer.trackedEntity = aircraft;
followEntity(viewer, aircraft);
assert.equal(cockpit.enter({ kind: 'aircraft' }), true);
await settle();
cockpit.update();
@@ -817,7 +916,7 @@ test('arrows do nothing new in an aircraft cockpit', async (t) => {
const { cockpit, viewer, aircraft, shots, store } = fixture(t, {
aircraftInfo,
});
viewer.trackedEntity = aircraft;
followEntity(viewer, aircraft);
assert.equal(cockpit.enter({ kind: 'aircraft' }), true);
await settle();
assert.equal(cockpit.subjectKind, 'aircraft');
@@ -838,7 +937,7 @@ test('arrows do nothing new in an aircraft cockpit', async (t) => {
near(after.pitchDeg, before.pitchDeg, 'the aircraft pitch', 1e-6);
assert.deepEqual(cockpit.lookTarget, { yawDeg: 0, pitchDeg: -2 });
assert.equal(store.instruments.look.offset, false);
assert.equal(document.querySelector('.cockpit-look'), null);
assert.equal(document.querySelector('.cockpit-look') === null, true);
// The tape stays on the aircraft's heading, with no bow or stern marks.
const centre = store.instruments.compass.find(
(division) => division.slot === 0,
@@ -848,7 +947,7 @@ test('arrows do nothing new in an aircraft cockpit', async (t) => {
prograde: null,
retrograde: null,
});
assert.equal(document.querySelector('.cockpit-compass-marker'), null);
assert.equal(document.querySelector('.cockpit-compass-marker') === null, true);
assert.doesNotMatch(
document.querySelector('.cockpit-help').textContent,
/ARROWS LOOK/,
@@ -867,7 +966,7 @@ test('C neither enters nor leaves an aircraft cockpit', async (t) => {
onGround: false,
};
const { cockpit, viewer, aircraft } = fixture(t, { aircraftInfo });
viewer.trackedEntity = aircraft;
followEntity(viewer, aircraft);
const outside = press(cockpit, 'c');
await settle();
assert.equal(cockpit.active, false, 'C does not enter');
@@ -905,6 +1004,7 @@ test('a bridge on a river above sea level rides the water, not the geoid', async
clock.set(START_MS);
const record = { ...RECORD, lastPositionEpoch: START_MS / 1000 };
const river = fixture(t, { record });
surfacesAsked.length = 0;
const probed = [];
// The ship's own model reads 40 m; the ring finds the river at 27 m and
// a quay at 33 m.
@@ -928,6 +1028,10 @@ test('a bridge on a river above sea level rides the water, not the geoid', async
0.5,
);
assert.equal(probed[0], 9, 'the ship and eight probes around it');
// The drawn surface, the globe's terrain included, as the scene's own
// sample read it.
assert.ok(surfacesAsked.length > 0);
assert.deepEqual([...new Set(surfacesAsked)], ['surface']);
const reads = probed.length;
frames(river.cockpit, clock, river.shots, 20);
await settle();
@@ -1200,6 +1304,18 @@ test('a ship with no true heading is held, and labelled, on its course', async (
signals.some(([, , , detail]) => /COURSE 095°/.test(detail)),
JSON.stringify(signals),
);
// A ship's course has a word of its own: pt RUMO, an aircraft's CURSO.
t.after(() => setLocale('en'));
setLocale('pt');
signals.length = 0;
cockpit.exit();
await settle();
cockpit.enter();
await settle();
assert.ok(
signals.some(([, , , detail]) => /· RUMO 095°$/.test(detail)),
JSON.stringify(signals),
);
});
test('both entries name the subject the same way', async () => {
@@ -1247,7 +1363,7 @@ test('a ship with neither heading nor course makes up no direction', async (t) =
prograde: null,
retrograde: null,
});
assert.equal(document.querySelector('.cockpit-compass-marker'), null);
assert.equal(document.querySelector('.cockpit-compass-marker') === null, true);
assert.match(
$('.cockpit-visor-status-right').textContent,
/NO HEADING · AIS/,
@@ -1474,7 +1590,7 @@ test('a fix the feed keeps re-serving goes on ageing into a stale feed', async (
effects,
);
poll();
const record = records.byMmsi.get(RECORD.mmsi);
const record = records.byId.get(RECORD.id);
const { $, cockpit, shots } = fixture(t, { record });
cockpit.enter();
await settle();
@@ -1503,7 +1619,7 @@ test('a followed aircraft keeps its own double-click hit area', async (t) => {
onGround: false,
};
const { cockpit, viewer, aircraft } = fixture(t, { aircraftInfo });
viewer.trackedEntity = aircraft;
followEntity(viewer, aircraft);
heightSensitiveProjection(viewer);
// Drawn at (400, -2700) as the press begins, at (600, -2700) by the
// double-click: a click there is not on the aircraft.
@@ -1529,7 +1645,7 @@ test("a ship's double-click memory does not carry over to an aircraft followed s
// The press finds the ship at (400, 300).
cockpit.onScenePointerDown(1000);
// Within the memory, an aircraft is followed, drawn elsewhere.
viewer.trackedEntity = aircraft;
followEntity(viewer, aircraft);
heightSensitiveProjection(viewer, { x: 900 });
assert.equal(cockpit.onSceneDoubleClick({ x: 400, y: 300 }, 1250), false);
assert.equal(cockpit.active, false);
@@ -1540,7 +1656,12 @@ test("a ship's double-click memory does not carry over to another ship", async (
heightSensitiveProjection(viewer);
cockpit.onScenePointerDown(1000);
// Within the memory another ship is selected, drawn elsewhere.
vessels.select({ ...RECORD, mmsi: '211000009', name: 'OTHER' });
vessels.select({
...RECORD,
id: '211000009',
mmsi: '211000009',
name: 'OTHER',
});
heightSensitiveProjection(viewer, { x: 900 });
assert.equal(cockpit.onSceneDoubleClick({ x: 400, y: 300 }, 1250), false);
assert.equal(cockpit.active, false);
+23 -3
View File
@@ -1,9 +1,29 @@
/**
* The Cockpit briefing's pages and the state it starts in. It needs only the
* i18n module, so the controller and the view can both read it.
* i18n module and the regional-news window, so the controller and the view
* can both read it.
*/
import { REGIONAL_NEWS_WINDOW_HOURS } from '../data/regionalNewsWindow.js';
import { msg, t } from '../i18n/index.js';
// i18n-ignore: provider name
/** The news feed named before any briefing has answered. */
export const DEFAULT_NEWS_SOURCE = 'GOOGLE NEWS RSS';
/**
* The Regional News footer for a fresh, empty or unavailable list: the feed
* and the window its articles are held to.
* @param {string} [source]
* @param {number} [hours]
* @returns {string}
*/
export function newsWindowFooter(
source = DEFAULT_NEWS_SOURCE,
hours = REGIONAL_NEWS_WINDOW_HOURS,
) {
return t('{source} · LAST {hours} H', { source, hours });
}
export const COCKPIT_BRIEF_PAGES = [
{
id: 'signals',
@@ -15,8 +35,7 @@ export const COCKPIT_BRIEF_PAGES = [
id: 'news',
kickerKey: msg('REGIONAL NEWS'),
subtitleKey: msg('LATEST LOCATION-MATCHED REPORTING'),
sourceKey: msg('{source} · LOCATION QUERY · RECENT'),
sourceName: 'GOOGLE NEWS RSS', // i18n-ignore: provider name
// The news footer comes from the news state (`news.footer`), not here.
},
{
id: 'local',
@@ -60,6 +79,7 @@ export function createBriefState() {
statusHidden: false,
state: null,
status: t('ACQUIRING REGIONAL NEWS'),
footer: newsWindowFooter(),
articles: [],
},
local: {
+113 -21
View File
@@ -12,7 +12,14 @@ import {
COCKPIT_BRIEF_PAGES,
CYCLE_HELP_KEYS,
createBriefState,
newsWindowFooter,
} from './cockpitBriefPages.js';
import {
recentRegionalArticles,
regionalNewsWindowHours,
} from '../data/regionalNewsWindow.js';
const NEWS_ROWS = 4;
// regionalModel.weatherCodeLabel is shared with node code and returns
// English; translate it here.
@@ -52,9 +59,13 @@ export function showBriefPage(index, { manual = false } = {}) {
kicker: t(page.kickerKey),
subtitle: t(page.subtitleKey),
position: `${this.briefPageIndex + 1} / ${count}`,
source: page.sourceKey
? t(page.sourceKey, { source: page.sourceName })
: page.source,
// The news footer follows the news state, so it survives page changes.
source:
page.id === 'news'
? this.brief.news.footer
: page.sourceKey
? t(page.sourceKey)
: page.source,
});
this.publishBriefView();
if (manual && this.briefAutoRotateEnabled)
@@ -153,7 +164,7 @@ export function maybeRefreshRegionalBrief(info) {
!Number.isFinite(info.longitude)
)
return;
const subjectId = `${info.layerId || 'aircraft'}:${info.icao24 || info.mmsi || info.noradId || info.registration || info.callsign || 'unknown'}`;
const subjectId = `${info.layerId || 'aircraft'}:${info.icao24 || (info.kind === 'vessel' || info.generic === true ? info.id : '') || info.noradId || info.registration || info.callsign || 'unknown'}`;
if (subjectId !== this.regionalBriefSubjectId) {
this.regionalBriefAbort?.abort();
this.regionalBriefAbort = null;
@@ -176,6 +187,13 @@ export function maybeRefreshRegionalBrief(info) {
)
return;
// The brief held stands in after a failed refresh only near where its news
// was read; past the refresh distance it is another place's.
const previous =
this.services.regionalDistanceM(this.regionalBriefPoint, point) <
COCKPIT_REGIONAL_REFRESH_DISTANCE_M
? this.regionalBrief
: null;
this.regionalBriefAnchor = point;
this.regionalBriefFetchedAt = Date.now();
const controller = new AbortController();
@@ -193,8 +211,9 @@ export function maybeRefreshRegionalBrief(info) {
subjectId !== this.regionalBriefSubjectId
)
return;
this.regionalBrief = payload;
this.renderRegionalBrief(payload, info);
this.regionalBrief = withCachedNews(payload, previous);
if (this.regionalBrief === payload) this.regionalBriefPoint = point;
this.renderRegionalBrief(this.regionalBrief, info);
})
.catch((error) => {
if (
@@ -203,7 +222,14 @@ export function maybeRefreshRegionalBrief(info) {
requestToken === this.regionalBriefRequestToken &&
subjectId === this.regionalBriefSubjectId
) {
this.renderRegionalBriefStatus('unavailable', info);
if (previous) {
this.regionalBrief = cachedNews(previous, previous);
this.renderRegionalBrief(this.regionalBrief, info);
} else {
// Another place's brief: not to come back with a language change.
this.regionalBrief = null;
this.renderRegionalBriefStatus('unavailable', info);
}
}
})
.finally(() => {
@@ -212,6 +238,75 @@ export function maybeRefreshRegionalBrief(info) {
});
}
/**
* A brief whose news comes from `previous` after a refresh that brought none:
* the earlier articles stay, marked `cached` so they are labelled as such.
* @param {object} payload The brief to keep everything else from.
* @param {object} previous The last brief rendered for this subject.
*/
function cachedNews(payload, previous) {
return {
...payload,
newsStatus: 'cached',
newsSource: previous.newsSource,
newsWindowHours: previous.newsWindowHours,
newsFetchedAt: previous.newsFetchedAt ?? previous.retrievedAt ?? null,
articles: previous.articles,
};
}
// A refresh whose news read failed keeps the articles from before it.
function withCachedNews(payload, previous) {
return previous && payload?.newsStatus === 'unavailable'
? cachedNews(payload, previous)
: payload;
}
/**
* The Regional News state a brief presents. `ready` and `cached` have rows
* inside the window; `cached` is a refresh that failed (a client-side failure,
* or the local proxy's `stale` answer). `empty` is a source that answered with
* nothing in the window; anything else is `unavailable`.
* @returns {{state: string, status: string, footer: string, articles: object[]}}
*/
function regionalNewsView(payload) {
const hours = regionalNewsWindowHours(payload?.newsWindowHours);
// Old caches and the local path are held to the window here too.
const articles = recentRegionalArticles(payload?.articles, {
windowHours: hours,
limit: NEWS_ROWS,
});
const source = String(
payload?.newsSource || t('REGIONAL NEWS'),
).toUpperCase();
const refreshFailed =
payload?.newsStatus === 'cached' || payload?.status === 'stale';
if (articles.length && refreshFailed)
return {
state: 'cached',
status: t('CACHED · REFRESH FAILED'),
footer: t('{source} · CACHED {age}', {
source,
age: formatCockpitBriefAge(
payload?.newsFetchedAt ?? payload?.retrievedAt,
),
}),
articles,
};
const answered =
!refreshFailed && ['ready', 'empty'].includes(payload?.newsStatus);
return {
state: articles.length ? 'ready' : answered ? 'empty' : 'unavailable',
status: articles.length
? ''
: answered
? t('NO NEWS IN THE LAST {hours} H', { hours })
: t('REGIONAL NEWS UNAVAILABLE'),
footer: newsWindowFooter(source, hours),
articles,
};
}
export function renderRegionalBriefStatus(status, info) {
const { news, local } = this.brief;
news.statusHidden = false;
@@ -220,7 +315,10 @@ export function renderRegionalBriefStatus(status, info) {
status === 'loading'
? t('ACQUIRING REGIONAL NEWS')
: t('REGIONAL NEWS UNAVAILABLE');
if (status === 'unavailable') news.articles = [];
news.footer = newsWindowFooter();
// Only called with no brief for this subject: any rows are another's.
news.articles = [];
if (this.briefPageIndex === 1) this.brief.source = news.footer;
if (status === 'loading') local.place = t('RESOLVING REGION');
if (status === 'unavailable') local.place = t('REGION UNAVAILABLE');
local.coordinates = localCoordinates(info);
@@ -228,7 +326,7 @@ export function renderRegionalBriefStatus(status, info) {
}
export function renderRegionalBrief(payload, info) {
const articles = Array.isArray(payload?.articles) ? payload.articles : [];
const { state, status, footer, articles } = regionalNewsView(payload);
const seen = new Map();
const storyKey = (url) => {
const count = seen.get(url) ?? 0;
@@ -241,13 +339,11 @@ export function renderRegionalBrief(payload, info) {
const placeLabel =
payload?.place?.label || payload?.place?.country || t('REGION UNAVAILABLE');
this.brief.news = {
statusHidden: articles.length > 0,
state: payload?.newsStatus || 'unavailable',
status:
payload?.newsStatus === 'empty'
? t('NO RECENT LOCATION MATCHES')
: t('REGIONAL NEWS UNAVAILABLE'),
articles: articles.slice(0, 4).map((article) => ({
statusHidden: state === 'ready',
state,
status,
footer,
articles: articles.map((article) => ({
// A row keeps its node, and so its focus, only for the same story.
key: storyKey(article.url),
url: article.url,
@@ -281,11 +377,7 @@ export function renderRegionalBrief(payload, info) {
: '—',
};
this.brief.regionalStatus = payload?.status || 'partial';
if (this.briefPageIndex === 1) {
this.brief.source = t('{source} · LOCATION QUERY', {
source: String(payload?.newsSource || t('REGIONAL NEWS')).toUpperCase(),
});
}
if (this.briefPageIndex === 1) this.brief.source = footer;
this.publishBriefView();
this.scheduleContextLayout();
}
+365 -18
View File
@@ -3,11 +3,14 @@
import '../testSupport/registerDom.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { createPinia } from 'pinia';
import { createApp, nextTick } from 'vue';
import { setLocale } from '../i18n/index.js';
import { createBriefState } from './cockpitBriefPages.js';
import {
maybeRefreshRegionalBrief,
publishBriefView,
renderRegionalBrief,
renderRegionalBriefStatus,
@@ -88,10 +91,7 @@ test('pages, the cycle toggle and the source follow the controller', async (t) =
await nextTick();
assert.equal(text('#cockpit-brief-kicker'), 'REGIONAL NEWS');
assert.equal(text('#cockpit-brief-position'), '2 / 3');
assert.equal(
text('#cockpit-brief-source'),
'GOOGLE NEWS RSS · LOCATION QUERY · RECENT',
);
assert.equal(text('#cockpit-brief-source'), 'GOOGLE NEWS RSS · LAST 24 H');
assert.deepEqual(visiblePages(), ['news']);
assert.deepEqual(current(), ['false', 'true', 'false']);
assert.equal($('#cockpit-signal-stream').dataset.briefPage, 'news');
@@ -129,7 +129,8 @@ test('regional news and local conditions render what the region returned', async
url: `https://example.com/${index}`,
title: `Story ${index}`,
domain: 'example.com',
publishedAt: new Date().toISOString(),
// Newest first is the shown order, so Story 0 is the newest.
publishedAt: new Date(Date.now() - index * 60_000).toISOString(),
})),
weather: {
temperatureC: 21.6,
@@ -159,7 +160,7 @@ test('regional news and local conditions render what the region returned', async
assert.equal(text('#cockpit-local-condition'), 'RAIN');
assert.equal(text('#cockpit-local-cloud'), 'CLOUD 40%');
assert.equal(text('#cockpit-local-precipitation'), '1.3');
assert.equal(text('#cockpit-brief-source'), 'WIRE · LOCATION QUERY');
assert.equal(text('#cockpit-brief-source'), 'WIRE · LAST 24 H');
assert.equal($('#cockpit-signal-stream').dataset.regionalStatus, 'ok');
renderRegionalBriefStatus.call(owner, 'unavailable', {});
await nextTick();
@@ -170,11 +171,15 @@ test('regional news and local conditions render what the region returned', async
assert.equal(text('#cockpit-local-coordinates'), 'POSITION UNAVAILABLE');
});
// One time for every story: newest-first order then keeps the order a test
// lists them in. A clock read per story could tick between two of them and
// swap them.
const STORY_PUBLISHED_AT = new Date().toISOString();
const story = (id, url = `https://example.com/${id}`) => ({
url,
title: `Story ${id}`,
domain: 'example.com',
publishedAt: new Date().toISOString(),
publishedAt: STORY_PUBLISHED_AT,
});
test('a refreshed news list keeps a focused story on its own link', async (t) => {
@@ -210,26 +215,293 @@ test('a refreshed news list keeps a focused story on its own link', async (t) =>
assert.equal($('#cockpit-news-list').textContent.includes('Story y'), true);
});
test('the news source names the feed only while it is current on page 2', async (t) => {
// This contract changed on purpose: the footer used to fall back to a
// static "· RECENT" on every page change, which promised nothing. It now
// follows the news state and names the window it holds articles to.
test('the news footer follows the news state across page changes, not a static RECENT', async (t) => {
const { text, owner } = fixture(t);
showBriefPage.call(owner, 1);
renderRegionalBrief.call(owner, { newsSource: 'wire', articles: [] }, INFO);
renderRegionalBrief.call(
owner,
{
newsStatus: 'ready',
newsSource: 'wire',
newsWindowHours: 24,
articles: [story('a')],
},
INFO,
);
await nextTick();
assert.equal(text('#cockpit-brief-source'), 'WIRE · LOCATION QUERY');
assert.equal(text('#cockpit-brief-source'), 'WIRE · LAST 24 H');
showBriefPage.call(owner, 2);
showBriefPage.call(owner, 1);
await nextTick();
assert.equal(text('#cockpit-brief-source'), 'WIRE · LAST 24 H');
showBriefPage.call(owner, 0);
renderRegionalBrief.call(
owner,
{
newsStatus: 'ready',
newsSource: 'wire',
newsWindowHours: 12,
articles: [story('a')],
},
INFO,
);
await nextTick();
// Off page 2 the footer is the current page's.
assert.equal(
text('#cockpit-brief-source'),
'SOURCE-BACKED EVENTS · NO SYNTHETIC NEWS',
);
showBriefPage.call(owner, 1);
await nextTick();
assert.equal(text('#cockpit-brief-source'), 'WIRE · LAST 12 H');
});
test('the news banner is hidden by the stylesheet, not only by the attribute', async (t) => {
// happy-dom applies no author CSS by itself, so `hidden` alone proves
// nothing: `.cockpit-brief-status { display: grid }` used to beat it.
const css = readFileSync(
fileURLToPath(new URL('./styles/cockpit.css', import.meta.url)),
'utf8',
);
assert.match(
css,
/\.cockpit-brief-status\[hidden\]\s*\{\s*display:\s*none;?\s*\}/,
);
const { $, owner } = fixture(t);
const style = document.head.appendChild(document.createElement('style'));
t.after(() => style.remove());
style.textContent = css;
showBriefPage.call(owner, 1);
renderRegionalBrief.call(
owner,
{ newsStatus: 'ready', articles: [story('a')] },
INFO,
);
await nextTick();
const banner = $('#cockpit-news-status');
assert.equal(banner.hidden, true);
assert.equal(getComputedStyle(banner).display, 'none');
renderRegionalBrief.call(owner, { newsStatus: 'empty', articles: [] }, INFO);
await nextTick();
assert.equal(getComputedStyle(banner).display, 'grid');
});
const hoursAgo = (hours) =>
new Date(Date.now() - hours * 3_600_000).toISOString();
test('ready, cached, empty and unavailable each label the news differently', async (t) => {
const { $, text, owner } = fixture(t);
showBriefPage.call(owner, 1);
const rows = () =>
[...document.querySelectorAll('#cockpit-news-list strong')].map(
(row) => row.textContent,
);
const banner = () => ({
hidden: $('#cockpit-news-status').hidden,
state: $('#cockpit-news-status').dataset.state,
text: text('#cockpit-news-status'),
});
const ready = {
status: 'ready',
newsStatus: 'ready',
newsSource: 'Google News RSS',
newsWindowHours: 24,
newsFetchedAt: hoursAgo(0.5),
articles: [story('a'), story('b')],
};
renderRegionalBrief.call(owner, ready, INFO);
await nextTick();
assert.equal(banner().hidden, true);
assert.equal(banner().state, 'ready');
assert.deepEqual(rows(), ['Story a', 'Story b']);
assert.equal(text('#cockpit-brief-source'), 'GOOGLE NEWS RSS · LAST 24 H');
// The local proxy's stale answer is a refresh that failed.
renderRegionalBrief.call(owner, { ...ready, status: 'stale' }, INFO);
await nextTick();
assert.deepEqual(banner(), {
hidden: false,
state: 'cached',
text: 'CACHED · REFRESH FAILED',
});
assert.deepEqual(rows(), ['Story a', 'Story b']);
assert.equal(
text('#cockpit-brief-source'),
'GOOGLE NEWS RSS · CACHED 30M AGO',
);
renderRegionalBrief.call(
owner,
{
...ready,
newsStatus: 'empty',
newsSource: 'Google News RSS',
articles: [],
},
INFO,
);
await nextTick();
assert.deepEqual(banner(), {
hidden: false,
state: 'empty',
text: 'NO NEWS IN THE LAST 24 H',
});
assert.deepEqual(rows(), []);
renderRegionalBrief.call(
owner,
{ ...ready, newsStatus: 'unavailable', newsSource: null, articles: [] },
INFO,
);
await nextTick();
assert.deepEqual(banner(), {
hidden: false,
state: 'unavailable',
text: 'REGIONAL NEWS UNAVAILABLE',
});
assert.deepEqual(rows(), []);
});
test('articles outside the window are dropped even when a server sends them', async (t) => {
const { $, text, owner } = fixture(t);
showBriefPage.call(owner, 1);
const dated = (id, publishedAt) => ({ ...story(id), publishedAt });
// The reported case: 4, 104, 215 and 165 days old under "RECENT".
renderRegionalBrief.call(
owner,
{
newsStatus: 'ready',
articles: [
dated('old', hoursAgo(4 * 24)),
dated('older', hoursAgo(104 * 24)),
dated('undated', null),
dated('one', hoursAgo(20)),
dated('two', hoursAgo(2)),
],
},
INFO,
);
await nextTick();
assert.deepEqual(
[...document.querySelectorAll('#cockpit-news-list strong')].map(
(row) => row.textContent,
),
['Story two', 'Story one'],
);
assert.equal($('#cockpit-news-status').hidden, true);
renderRegionalBrief.call(
owner,
{ newsStatus: 'ready', articles: [dated('old', hoursAgo(25))] },
INFO,
);
await nextTick();
assert.equal(document.querySelectorAll('#cockpit-news-list li').length, 0);
assert.equal(text('#cockpit-news-status'), 'NO NEWS IN THE LAST 24 H');
});
test('a failed refresh keeps the earlier articles as cached, and clears only when there are none', async (t) => {
const { $, text, owner } = fixture(t);
const answers = [];
Object.assign(owner, {
active: true,
regionalBriefSubjectId: null,
regionalBriefAbort: null,
regionalBriefRequestToken: 0,
regionalBriefFetchedAt: 0,
regionalBrief: null,
renderRegionalBrief,
renderRegionalBriefStatus,
});
owner.services = {
...owner.services,
regionalDistanceM: () => 0,
fetchRegionalBrief: () => answers.shift()(),
};
const refresh = async (answer, info = { ...INFO, icao24: 'abc123' }) => {
answers.push(answer);
owner.regionalBriefFetchedAt = 0;
maybeRefreshRegionalBrief.call(owner, info);
await new Promise((resolve) => setTimeout(resolve, 0));
await nextTick();
};
const rows = () => document.querySelectorAll('#cockpit-news-list li').length;
showBriefPage.call(owner, 1);
// No earlier brief: an error clears and says unavailable.
await refresh(() => Promise.reject(new Error('503')));
assert.equal($('#cockpit-news-status').dataset.state, 'unavailable');
assert.equal(text('#cockpit-news-status'), 'REGIONAL NEWS UNAVAILABLE');
assert.equal(rows(), 0);
const fetchedAt = hoursAgo(1);
await refresh(() =>
Promise.resolve({
status: 'ready',
newsStatus: 'ready',
newsSource: 'Google News RSS',
newsWindowHours: 24,
newsFetchedAt: fetchedAt,
articles: [story('a'), story('b')],
}),
);
assert.equal($('#cockpit-news-status').hidden, true);
assert.equal(rows(), 2);
// A network failure keeps the rows and says so, with their age.
await refresh(() => Promise.reject(new TypeError('Failed to fetch')));
assert.equal($('#cockpit-news-status').hidden, false);
assert.equal(text('#cockpit-news-status'), 'CACHED · REFRESH FAILED');
assert.equal(rows(), 2);
assert.equal(
text('#cockpit-brief-source'),
'GOOGLE NEWS RSS · CACHED 1H AGO',
);
showBriefPage.call(owner, 2);
showBriefPage.call(owner, 1);
await nextTick();
assert.equal(
text('#cockpit-brief-source'),
'GOOGLE NEWS RSS · LOCATION QUERY · RECENT',
'GOOGLE NEWS RSS · CACHED 1H AGO',
);
showBriefPage.call(owner, 0);
renderRegionalBrief.call(owner, { newsSource: 'wire', articles: [] }, INFO);
await nextTick();
assert.equal(
text('#cockpit-brief-source'),
'SOURCE-BACKED EVENTS · NO SYNTHETIC NEWS',
// So does a brief whose news read failed while weather answered.
await refresh(() =>
Promise.resolve({
status: 'partial',
newsStatus: 'unavailable',
articles: [],
}),
);
assert.equal(text('#cockpit-news-status'), 'CACHED · REFRESH FAILED');
assert.equal(rows(), 2);
// A successful refresh clears the cached label; a true empty clears rows.
await refresh(() =>
Promise.resolve({
status: 'ready',
newsStatus: 'empty',
newsSource: 'Google News RSS',
articles: [],
}),
);
assert.equal(text('#cockpit-news-status'), 'NO NEWS IN THE LAST 24 H');
assert.equal(rows(), 0);
assert.equal(text('#cockpit-brief-source'), 'GOOGLE NEWS RSS · LAST 24 H');
// Another aircraft never inherits the last one's rows.
await refresh(() =>
Promise.resolve({ newsStatus: 'ready', articles: [story('c')] }),
);
assert.equal(rows(), 1);
await refresh(() => Promise.reject(new Error('503')), {
...INFO,
icao24: 'def456',
});
assert.equal(text('#cockpit-news-status'), 'REGIONAL NEWS UNAVAILABLE');
assert.equal(rows(), 0);
});
test('an unchanged position publishes nothing new', (t) => {
@@ -278,7 +550,10 @@ test('the card and its toggle render the collapse the controller presents', asyn
await nextTick();
assert.equal(card.dataset.collapsed, 'true');
assert.equal(toggle.getAttribute('aria-expanded'), 'false');
assert.equal(toggle.getAttribute('aria-label'), 'Expand cockpit briefing panel');
assert.equal(
toggle.getAttribute('aria-label'),
'Expand cockpit briefing panel',
);
assert.equal(toggle.title, 'Expand briefing panel');
assert.equal(toggle.textContent.trim(), 'right_panel_open');
assert.equal(owner.signalUserCollapsed, true);
@@ -287,3 +562,75 @@ test('the card and its toggle render the collapse the controller presents', asyn
assert.equal(card.dataset.collapsed, 'false');
assert.equal(toggle.textContent.trim(), 'right_panel_close');
});
test("a refresh that fails after a move never shows the last location's brief as current", async (t) => {
const { $, text, owner } = fixture(t);
const answers = [];
Object.assign(owner, {
active: true,
regionalBriefSubjectId: null,
regionalBriefAbort: null,
regionalBriefRequestToken: 0,
regionalBriefFetchedAt: 0,
regionalBrief: null,
renderRegionalBrief,
renderRegionalBriefStatus,
});
owner.services = {
...owner.services,
// One degree of latitude stands for a move past the refresh distance.
regionalDistanceM: (from, to) =>
from ? Math.abs(from.latitude - to.latitude) * 111_000 : Infinity,
fetchRegionalBrief: () => answers.shift()(),
};
const refresh = async (answer, latitude) => {
answers.push(answer);
owner.regionalBriefFetchedAt = 0;
maybeRefreshRegionalBrief.call(owner, {
...INFO,
icao24: 'abc123',
latitude,
});
await new Promise((resolve) => setTimeout(resolve, 0));
await nextTick();
};
const rows = () => document.querySelectorAll('#cockpit-news-list li').length;
const here = () =>
Promise.resolve({
status: 'ready',
newsStatus: 'ready',
newsSource: 'Google News RSS',
newsWindowHours: 24,
newsFetchedAt: hoursAgo(1),
articles: [story('a'), story('b')],
});
showBriefPage.call(owner, 1);
await refresh(here, 40);
assert.equal(rows(), 2);
// The same place: a failed refresh keeps the rows as cached.
await refresh(() => Promise.reject(new TypeError('Failed to fetch')), 40);
assert.equal(text('#cockpit-news-status'), 'CACHED · REFRESH FAILED');
assert.equal(rows(), 2);
// Elsewhere: the brief is unavailable, as it was before there was a cache.
await refresh(() => Promise.reject(new TypeError('Failed to fetch')), 45);
assert.equal($('#cockpit-news-status').dataset.state, 'unavailable');
assert.equal(rows(), 0);
// Nor is it held, for a language change to show again.
assert.equal(owner.regionalBrief, null);
// Nor does a brief there whose news read failed borrow the last place's rows.
await refresh(here, 40);
assert.equal(rows(), 2);
await refresh(
() =>
Promise.resolve({
status: 'partial',
newsStatus: 'unavailable',
articles: [],
}),
45,
);
assert.equal($('#cockpit-news-status').dataset.state, 'unavailable');
assert.equal(rows(), 0);
});
+297 -183
View File
@@ -1,8 +1,30 @@
/** Camera placement, ground acquisition and motion correction for the Cockpit controller. */
import * as Cesium from 'cesium';
import { cameraOf, findFrame, findQuery } from '../render/rendererOf.js';
import { heightsOf } from '../queries/heights.js';
import { followedPosition, isFollowing } from '../data/followed.js';
import { readEntityRecord } from '../data/entityRecords.js';
import { trackedEntityDrawn } from './cockpitTrackingController.js';
import {
add,
clone,
eastNorthUp,
frameVector,
fromDegrees,
fromRadians,
magnitude,
normalize,
scale,
sub,
toCartographicRadians,
toDegrees,
toRadians,
vec,
} from '../geo/index.js';
import {
cockpitAnchorCorrectionStep,
cockpitGroundSafeHeight,
easeCockpitLift,
cockpitSubjectStepSec,
cockpitSurfaceWaitExpired,
cockpitUiUpdateDue,
slewHeading,
@@ -16,6 +38,7 @@ import {
waterlineProbePoints,
} from '../cockpitSubjects.js';
import { easeLook } from '../cockpitLook.js';
import { cockpitSubjectFrame } from '../cockpitSubjectProviders.js';
import {
COCKPIT_HEADING_SLEW_DPS,
COCKPIT_FORWARD_OFFSET_M,
@@ -28,6 +51,17 @@ import {
COCKPIT_GROUND_WAIT_TIMEOUT_MS,
} from './cockpitPresentation.js';
/**
* Where the aircraft Cockpit flies is now: its follow target's position at
* scene time (what the drawn entity's position reads), or, for a target
* with none, where it is shown.
*/
export function trackedPositionNow(viewer, followed) {
if (typeof followed?.position === 'function')
return followed.position(findFrame(viewer)?.time() ?? Date.now());
return followedPosition(viewer, followed);
}
/** The aircraft eye: just ahead of and above the reported position. */
const AIRCRAFT_CAMERA_PROFILE = Object.freeze({
forwardM: COCKPIT_FORWARD_OFFSET_M,
@@ -53,6 +87,10 @@ export function update() {
}
const nowMs = performance.now();
if (this.subjectProvider) {
updateSubject.call(this, nowMs);
return;
}
if (this.subjectKind === 'vessel') {
updateVessel.call(this, nowMs);
return;
@@ -70,7 +108,7 @@ export function update() {
if (
!info ||
!this.trackedEntity ||
!this.viewer.entities.contains(this.trackedEntity)
!trackedEntityDrawn.call(this, this.trackedEntity)
) {
if (nowMs < this.contextNavigationDeadlineMs) return;
this.exit({ restoreTracking: false });
@@ -86,10 +124,7 @@ export function update() {
return;
this.lastCameraUpdateMs = nowMs;
const target = this.trackedEntity.position.getValue(
this.viewer.clock.currentTime,
this.scratchTarget,
);
const target = trackedPositionNow(this.viewer, this.trackedFollow);
if (!target) return;
const dtSec = Math.min(0.1, Math.max(0, (nowMs - this.lastFrameMs) / 1000));
this.lastFrameMs = nowMs;
@@ -126,20 +161,20 @@ function vesselSurfaceM(info, nowMs, at = info) {
const seaM = Number.isFinite(info.seaSurfaceHeightM)
? info.seaSurfaceHeightM
: 0;
const scene = this.viewer.scene;
const query = findQuery(this.viewer) ? heightsOf(this.viewer) : null;
let read =
this.vesselWaterline?.mmsi === info.mmsi ? this.vesselWaterline : null;
this.vesselWaterline?.vesselId === info.id ? this.vesselWaterline : null;
if (
typeof scene?.sampleHeightMostDetailed === 'function' &&
query &&
(!read || nowMs - read.sampledMs >= VESSEL_WATERLINE_REFRESH_MS)
) {
const probes = waterlineProbePoints(at.latitude, at.longitude).map(
({ lat, lon }) => Cesium.Cartographic.fromDegrees(lon, lat),
({ lat, lon }) => ({ lon, lat }),
);
if (!read) {
read = {
mmsi: info.mmsi,
heightM: loadedWaterlineM(scene, probes, seaM),
vesselId: info.id,
heightM: loadedWaterlineM(query, probes, seaM),
sampledMs: nowMs,
// Whether a full-detail read has answered for this ship.
landed: false,
@@ -149,7 +184,7 @@ function vesselSurfaceM(info, nowMs, at = info) {
} else {
read.sampledMs = nowMs;
if (read.inFlight && !read.landed) {
const loadedM = loadedWaterlineM(scene, probes, seaM);
const loadedM = loadedWaterlineM(query, probes, seaM);
// Taking a river back to the sea is the full-detail read's to say.
const lowers =
Number.isFinite(read.heightM) &&
@@ -158,7 +193,7 @@ function vesselSurfaceM(info, nowMs, at = info) {
if (Number.isFinite(loadedM) && !lowers) read.heightM = loadedM;
}
}
if (!read.inFlight) readWaterline.call(this, read, scene, probes, seaM);
if (!read.inFlight) readWaterline.call(this, read, query, probes, seaM);
}
return read && Number.isFinite(read.heightM)
? Math.max(seaM, read.heightM)
@@ -166,25 +201,26 @@ function vesselSurfaceM(info, nowMs, at = info) {
}
/** Start one full-detail water read for `read`; its answer lands on it. */
function readWaterline(read, scene, probes, seaM) {
function readWaterline(read, query, probes, seaM) {
read.inFlight = true;
Promise.resolve()
.then(() => scene.sampleHeightMostDetailed(probes))
.then(
(samples) => {
if (this.vesselWaterline !== read) return;
read.inFlight = false;
// However late it lands, it applies; one that sampled nothing (tiles
// not loaded yet) is no answer and keeps the height already read.
const heights = (samples || []).map((sample) => sample?.height);
if (!heights.some(Number.isFinite)) return;
read.landed = true;
read.heightM = vesselWaterlineM(seaM, heights);
},
() => {
if (this.vesselWaterline === read) read.inFlight = false;
},
);
// An async read: a failure arrives as a rejection, never a throw here.
// The drawn surface, globe included, as the scene's own sample read it:
// a lake on a globe map stands on its terrain.
query.batch(probes).then(
(samples) => {
if (this.vesselWaterline !== read) return;
read.inFlight = false;
// However late it lands, it applies; one that sampled nothing (tiles
// not loaded yet) is no answer and keeps the height already read.
const heights = samples || [];
if (!heights.some(Number.isFinite)) return;
read.landed = true;
read.heightM = vesselWaterlineM(seaM, heights);
},
() => {
if (this.vesselWaterline === read) read.inFlight = false;
},
);
}
/**
@@ -193,11 +229,9 @@ function readWaterline(read, scene, probes, seaM) {
* probe met loaded geometry: nothing sampled is no answer, not the sea, so it
* never undoes a river height a full read set.
*/
function loadedWaterlineM(scene, probes, seaM) {
if (typeof scene.sampleHeight !== 'function') return null;
if (scene.sampleHeightSupported === false) return null;
function loadedWaterlineM(query, probes, seaM) {
try {
const heights = probes.map((probe) => scene.sampleHeight(probe));
const heights = probes.map((probe) => query.now(probe));
if (!heights.some(Number.isFinite)) return null;
return vesselWaterlineM(seaM, heights);
} catch {
@@ -212,14 +246,15 @@ function loadedWaterlineM(scene, probes, seaM) {
* correction each new fix brings.
*/
function updateVessel(nowMs) {
// Tracking an aircraft from the bridge clears the vessel selection; end the
// bridge and leave Cesium tracking with that aircraft.
if (this.viewer.trackedEntity?.position) {
// Tracking anything from the bridge (an aircraft, a satellite, a site)
// takes the camera: entry stopped every follow, so any follow now is
// another's. End the bridge and leave the camera following it.
if (isFollowing(this.viewer)) {
this.exit({ restoreTracking: false });
return;
}
const info = this.readVesselInfo();
if (!info || info.mmsi !== this.subjectId) {
if (!info || info.id !== this.subjectId) {
this.exit({ restoreTracking: false });
return;
}
@@ -247,13 +282,11 @@ function updateVessel(nowMs) {
);
// The radar centres here too, so it agrees with the view out the window.
this.vesselFix = fix;
const target = Cesium.Cartesian3.fromDegrees(
const target = fromDegrees(
fix.longitude,
fix.latitude,
// Read the water where the ship is now, not at its last report.
vesselSurfaceM.call(this, info, nowMs, fix),
Cesium.Ellipsoid.WGS84,
this.scratchTarget,
);
// The target advances in wall-clock time, so the anchor must too: the
// aircraft path's 0.1 s step cap would leave a slow-frame or hitching bridge
@@ -297,10 +330,123 @@ function updateVessel(nowMs) {
);
}
/**
* Drive the camera from an application provider's subject: read its frame,
* stand the eye `eye.upM` above `heightM` (the shared floor where the frame
* gives none) and slew toward its heading. A frame that is null, malformed or
* for another subject ends the view, as an aircraft tracked meanwhile does.
* The update runs on the provider's `cameraIntervalMs` (0: every frame), and
* its rates advance by the time that interval spans (cockpitSubjectStepSec).
*/
function updateSubject(nowMs) {
const provider = this.subjectProvider;
if (isFollowing(this.viewer)) {
this.exit({ restoreTracking: false });
return;
}
const intervalMs = provider.cameraIntervalMs ?? COCKPIT_CAMERA_UPDATE_MS;
if (!cockpitUiUpdateDue(nowMs, this.lastCameraUpdateMs, intervalMs)) return;
this.lastCameraUpdateMs = nowMs;
const frame = cockpitSubjectFrame(
this.callSubject(provider, 'read', [nowMs, this.subjectContext()], null),
this.subjectId,
);
if (!frame) {
this.exit({ restoreTracking: false });
return;
}
this.lastSubjectFrame = frame;
let heightM = frame.heightM;
if (heightM === null) {
this.services.warmGroundFloor?.([
{ lat: frame.latitude, lon: frame.longitude },
]);
const floorM = this.services.cachedGroundFloor?.(
frame.latitude,
frame.longitude,
);
// A frame with no height stands on the shared floor; while that is cold
// it keeps the height it last stood at.
heightM = Number.isFinite(floorM) ? floorM : this.subjectHeightM;
}
if (!Number.isFinite(heightM)) {
// Nothing to stand on yet, from the first frame: the camera stays where
// it is while the floor is acquired, its HUD saying so, rather than
// standing on the ellipsoid (kilometres underground on a plateau). The
// wait is bounded as the built-in views' is. Unlike a parked aircraft,
// whose fallback is its own reported altitude, such a subject has no
// height at all to fall back to: any number would be a guess, so the
// view ends and the provider gets its subject back.
if (!this.surfaceWaitStartedMs) this.surfaceWaitStartedMs = nowMs;
if (
cockpitSurfaceWaitExpired(
nowMs,
this.surfaceWaitStartedMs,
COCKPIT_GROUND_WAIT_TIMEOUT_MS,
)
) {
this.exit({ restoreTracking: false });
return;
}
this.surfaceAcquiring = true;
if (
cockpitUiUpdateDue(nowMs, this.lastHudUpdateMs, COCKPIT_HUD_UPDATE_MS)
) {
this.lastHudUpdateMs = nowMs;
this.updateHud(this.subjectInfo(frame), nowMs);
}
return;
}
this.surfaceWaitStartedMs = 0;
this.surfaceAcquiring = false;
this.subjectHeightM = heightM;
const target = fromDegrees(frame.longitude, frame.latitude, heightM);
const dtSec = cockpitSubjectStepSec(nowMs - this.lastFrameMs, intervalMs);
this.lastFrameMs = nowMs;
if (frame.headingDeg !== null) {
const rate = provider.headingSlewDps ?? COCKPIT_HEADING_SLEW_DPS;
this.heading =
rate === Infinity
? frame.headingDeg
: slewHeading(
this.heading ?? frame.headingDeg,
frame.headingDeg,
rate * dtSec,
);
}
let look = null;
if (provider.look) {
this.lookView = easeLook(
this.lookView,
this.lookTarget,
nowMs - (this.lookLastMs || nowMs),
);
this.lookLastMs = nowMs;
look = this.lookView;
}
placeCamera.call(
this,
target,
this.subjectInfo(frame),
nowMs,
dtSec,
{
forwardM: frame.eye.forwardM,
upM: frame.eye.upM,
pitchDeg: frame.eye.pitchDeg,
minClearanceM: frame.eye.minClearanceM,
},
look,
);
}
/**
* 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.
* A subject with `anchor: 'exact'` keeps the anchor on its target (its layer
* already moves it smoothly), and one with `groundClamp: false` (inside a
* structure, say) is never pushed up to the floor: a lift it had eases out.
* @param {{x: number, y: number, z: number}} target Authoritative subject position.
* @param {object} info Subject info; `motionCourse` (when present) is the
* direction the subject moves, otherwise it moves where it faces.
* @param {number} nowMs Frame time.
@@ -314,8 +460,9 @@ function updateVessel(nowMs) {
*/
function placeCamera(target, info, nowMs, dtSec, profile, look = null) {
if (!this.cockpitAnchorValid) {
Cesium.Cartesian3.clone(target, this.cockpitAnchor);
this.cockpitAnchor = clone(target);
this.cockpitAnchorValid = true;
this.subjectLiftM = null;
}
// First-person motion cannot use the delayed feed correction as a raw
@@ -325,73 +472,49 @@ function placeCamera(target, info, nowMs, dtSec, profile, look = null) {
// display position at a bounded rate. This preserves the layer's required
// 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 headingRad = toRadians(this.heading ?? 0);
const courseRad = Number.isFinite(info.motionCourse)
? Cesium.Math.toRadians(info.motionCourse)
? toRadians(info.motionCourse)
: headingRad;
const pitchRad = Cesium.Math.toRadians(
look ? look.pitchDeg : profile.pitchDeg,
);
const pitchRad = toRadians(look ? look.pitchDeg : profile.pitchDeg);
const viewHeadingRad = look
? Cesium.Math.toRadians((this.heading ?? 0) + look.yawDeg)
? toRadians((this.heading ?? 0) + look.yawDeg)
: headingRad;
const speedMps = Number.isFinite(info.velocityMps)
? Math.max(0, info.velocityMps)
: 0;
if (info.stale) {
const groundClamp = info.groundClamp !== false;
if (info.stale || info.anchor === 'exact') {
// A feed backoff has no authoritative velocity epoch to advance from.
// Hold the cockpit on the exact layer-rendered position so the camera
// cannot coast away while the icon correctly remains fixed.
Cesium.Cartesian3.clone(target, this.cockpitAnchor);
this.cockpitAnchor = clone(target);
} else {
Cesium.Transforms.eastNorthUpToFixedFrame(
const horizontal = normalize(
frameVector(
eastNorthUp(this.cockpitAnchor),
vec(Math.sin(courseRad), Math.cos(courseRad), 0),
),
);
this.cockpitAnchor = add(
this.cockpitAnchor,
Cesium.Ellipsoid.WGS84,
this.scratchEnu,
);
this.scratchLocal.x = Math.sin(courseRad);
this.scratchLocal.y = Math.cos(courseRad);
this.scratchLocal.z = 0;
Cesium.Matrix4.multiplyByPointAsVector(
this.scratchEnu,
this.scratchLocal,
this.scratchHorizontal,
);
Cesium.Cartesian3.normalize(this.scratchHorizontal, this.scratchHorizontal);
Cesium.Cartesian3.multiplyByScalar(
this.scratchHorizontal,
speedMps * dtSec,
this.scratchAdvance,
);
Cesium.Cartesian3.add(
this.cockpitAnchor,
this.scratchAdvance,
this.cockpitAnchor,
);
Cesium.Cartesian3.subtract(
target,
this.cockpitAnchor,
this.scratchCorrection,
);
const correctionDistanceM = Cesium.Cartesian3.magnitude(
this.scratchCorrection,
scale(horizontal, speedMps * dtSec),
);
const correction = sub(target, this.cockpitAnchor);
const correctionDistanceM = magnitude(correction);
// An application subject's step is already bounded by its own update
// interval (cockpitSubjectStepSec); the built-in views keep the 0.1 s.
const correctionStepM = cockpitAnchorCorrectionStep(
correctionDistanceM,
speedMps,
dtSec,
info.generic === true ? dtSec : undefined,
);
if (correctionStepM > 0 && correctionDistanceM > 0) {
Cesium.Cartesian3.multiplyByScalar(
this.scratchCorrection,
correctionStepM / correctionDistanceM,
this.scratchCorrection,
);
Cesium.Cartesian3.add(
this.cockpitAnchor,
this.scratchCorrection,
this.cockpitAnchor = add(
this.cockpitAnchor,
scale(correction, correctionStepM / correctionDistanceM),
);
}
}
@@ -401,23 +524,15 @@ function placeCamera(target, info, nowMs, dtSec, profile, look = null) {
// between fixes. Clamp it against the same mesh-first shared floor used by
// aircraft rendering. For a slow contact whose floor cell is still cold,
// its already-clamped render position is a conservative temporary floor.
const anchorCartographic = Cesium.Cartographic.fromCartesian(
this.cockpitAnchor,
Cesium.Ellipsoid.WGS84,
this.scratchAnchorCartographic,
);
const targetCartographic = Cesium.Cartographic.fromCartesian(
target,
Cesium.Ellipsoid.WGS84,
this.scratchTargetCartographic,
);
const anchorCartographic = toCartographicRadians(this.cockpitAnchor);
const targetCartographic = toCartographicRadians(target);
// A bridge's target is its fix dead-reckoned up to minutes ahead: read
// the floor where the ship is now, as its water is.
const floorAt =
info.kind === 'vessel'
info.kind === 'vessel' && targetCartographic
? {
latitude: Cesium.Math.toDegrees(targetCartographic.latitude),
longitude: Cesium.Math.toDegrees(targetCartographic.longitude),
latitude: toDegrees(targetCartographic.lat),
longitude: toDegrees(targetCartographic.lon),
}
: info;
let cockpitFloorM = this.services.cachedGroundFloor(
@@ -440,11 +555,11 @@ function placeCamera(target, info, nowMs, dtSec, profile, look = null) {
)
) {
this.lastGroundProbeMs = nowMs;
const viewerCartographic = this.viewer.camera.positionCartographic;
this.services.sampleMeshFloorCells(this.viewer.scene, groundPoint, {
excludeObjects: [this.trackedEntity],
viewerLat: Cesium.Math.toDegrees(viewerCartographic.latitude),
viewerLon: Cesium.Math.toDegrees(viewerCartographic.longitude),
const eye = cameraOf(this.viewer).pose();
this.services.sampleMeshFloorCells(this.viewer, groundPoint, {
sets: readEntityRecord(this.trackedEntity)?.groundSets?.() ?? [],
viewerLat: eye.lat,
viewerLon: eye.lon,
});
}
cockpitFloorM = this.services.cachedMeshFloor(
@@ -498,90 +613,64 @@ function placeCamera(target, info, nowMs, dtSec, profile, look = null) {
cockpitFloorM =
targetCartographic.height - this.services.GROUND_FLOOR_LIFT_M;
}
if (anchorCartographic && Number.isFinite(cockpitFloorM)) {
// An application subject's anchor is where its provider puts it; only its
// eye is kept out of the floor, below.
if (
groundClamp &&
info.generic !== true &&
anchorCartographic &&
Number.isFinite(cockpitFloorM)
) {
const minimumAnchorHeightM = cockpitGroundSafeHeight(
anchorCartographic.height,
cockpitFloorM,
profile.minClearanceM - profile.upM,
);
if (minimumAnchorHeightM !== anchorCartographic.height) {
anchorCartographic.height = minimumAnchorHeightM;
Cesium.Ellipsoid.WGS84.cartographicToCartesian(
anchorCartographic,
this.cockpitAnchor,
this.cockpitAnchor = fromRadians(
anchorCartographic.lon,
anchorCartographic.lat,
minimumAnchorHeightM,
);
}
}
// Rebuild the local frame at the stabilized anchor after advancing it.
Cesium.Transforms.eastNorthUpToFixedFrame(
this.cockpitAnchor,
Cesium.Ellipsoid.WGS84,
this.scratchEnu,
const enu = eastNorthUp(this.cockpitAnchor);
const horizontal = normalize(
frameVector(enu, vec(Math.sin(headingRad), Math.cos(headingRad), 0)),
);
this.scratchLocal.x = Math.sin(headingRad);
this.scratchLocal.y = Math.cos(headingRad);
this.scratchLocal.z = 0;
Cesium.Matrix4.multiplyByPointAsVector(
this.scratchEnu,
this.scratchLocal,
this.scratchHorizontal,
const forward = normalize(
frameVector(
enu,
vec(
Math.sin(viewHeadingRad) * Math.cos(pitchRad),
Math.cos(viewHeadingRad) * Math.cos(pitchRad),
Math.sin(pitchRad),
),
),
);
Cesium.Cartesian3.normalize(this.scratchHorizontal, this.scratchHorizontal);
this.scratchLocal.x = Math.sin(viewHeadingRad) * Math.cos(pitchRad);
this.scratchLocal.y = Math.cos(viewHeadingRad) * Math.cos(pitchRad);
this.scratchLocal.z = Math.sin(pitchRad);
Cesium.Matrix4.multiplyByPointAsVector(
this.scratchEnu,
this.scratchLocal,
this.scratchForward,
const up = normalize(
frameVector(
enu,
vec(
-Math.sin(viewHeadingRad) * Math.sin(pitchRad),
-Math.cos(viewHeadingRad) * Math.sin(pitchRad),
Math.cos(pitchRad),
),
),
);
Cesium.Cartesian3.normalize(this.scratchForward, this.scratchForward);
this.scratchLocal.x = -Math.sin(viewHeadingRad) * Math.sin(pitchRad);
this.scratchLocal.y = -Math.cos(viewHeadingRad) * Math.sin(pitchRad);
this.scratchLocal.z = Math.cos(pitchRad);
Cesium.Matrix4.multiplyByPointAsVector(
this.scratchEnu,
this.scratchLocal,
this.scratchUp,
);
Cesium.Cartesian3.normalize(this.scratchUp, this.scratchUp);
Cesium.Cartesian3.multiplyByScalar(
this.scratchHorizontal,
profile.forwardM,
this.scratchCamera,
);
Cesium.Cartesian3.add(
this.cockpitAnchor,
this.scratchCamera,
this.scratchCamera,
);
Cesium.Matrix4.getTranslation(this.scratchEnu, this.scratchTarget);
Cesium.Cartesian3.normalize(this.scratchTarget, this.scratchTarget);
Cesium.Cartesian3.multiplyByScalar(
this.scratchTarget,
profile.upM,
this.scratchTarget,
);
Cesium.Cartesian3.add(
this.scratchCamera,
this.scratchTarget,
this.scratchCamera,
let eye = add(
add(this.cockpitAnchor, scale(horizontal, profile.forwardM)),
scale(normalize(enu.origin), profile.upM),
);
// Recheck at the final forward-offset camera coordinate because a taxiing
// aircraft can cross into an adjacent coarse floor cell between updates.
const cameraCartographic = Cesium.Cartographic.fromCartesian(
this.scratchCamera,
Cesium.Ellipsoid.WGS84,
this.scratchCameraCartographic,
);
if (cameraCartographic) {
const cameraLat = Cesium.Math.toDegrees(cameraCartographic.latitude);
const cameraLon = Cesium.Math.toDegrees(cameraCartographic.longitude);
const cameraCartographic = toCartographicRadians(eye);
if (groundClamp && cameraCartographic) {
const cameraLat = toDegrees(cameraCartographic.lat);
const cameraLon = toDegrees(cameraCartographic.lon);
const cameraFloorM = this.services.cachedGroundFloor(cameraLat, cameraLon);
if (Number.isFinite(cameraFloorM)) {
cockpitFloorM = Math.max(
@@ -589,23 +678,48 @@ function placeCamera(target, info, nowMs, dtSec, profile, look = null) {
cameraFloorM,
);
}
const safeHeightM = cockpitGroundSafeHeight(
let safeHeightM = cockpitGroundSafeHeight(
cameraCartographic.height,
cockpitFloorM,
profile.minClearanceM,
);
// An application subject's eye rides its provider's smoothed height:
// the clearance over the coarse, refining floor eases in and out
// rather than jumping at each cell (easeCockpitLift).
if (info.generic === true) {
const hardM =
cockpitGroundSafeHeight(cameraCartographic.height, cockpitFloorM, 0) -
cameraCartographic.height;
this.subjectLiftM = easeCockpitLift(
this.subjectLiftM,
safeHeightM - cameraCartographic.height,
hardM,
dtSec,
);
safeHeightM = cameraCartographic.height + this.subjectLiftM;
}
if (safeHeightM !== cameraCartographic.height) {
cameraCartographic.height = safeHeightM;
Cesium.Ellipsoid.WGS84.cartographicToCartesian(
cameraCartographic,
this.scratchCamera,
eye = fromRadians(
cameraCartographic.lon,
cameraCartographic.lat,
safeHeightM,
);
}
} else if (info.generic === true) {
// Inside a structure the floor holds the eye up no more: the lift it gave
// goes at the rate it came (easeCockpitLift), never at once.
this.subjectLiftM = easeCockpitLift(this.subjectLiftM, 0, 0, dtSec);
if (cameraCartographic && this.subjectLiftM > 0)
eye = fromRadians(
cameraCartographic.lon,
cameraCartographic.lat,
cameraCartographic.height + this.subjectLiftM,
);
}
this.viewer.camera.setView({
destination: this.scratchCamera,
orientation: { direction: this.scratchForward, up: this.scratchUp },
cameraOf(this.viewer).setView({
destination: eye,
orientation: { direction: forward, up },
});
if (cockpitUiUpdateDue(nowMs, this.lastHudUpdateMs, COCKPIT_HUD_UPDATE_MS)) {
this.lastHudUpdateMs = nowMs;
+4 -9
View File
@@ -1,5 +1,5 @@
/** Contact readouts and nearby-signal presentation for the Cockpit controller. */
import * as Cesium from 'cesium';
import { toLonLatH } from '../geo/index.js';
import { formatNumber, t, tn } from '../i18n/index.js';
import { sourceStatusLabel } from './layerNames.js';
import { unitLabel } from './unitLabels.js';
@@ -186,14 +186,9 @@ export function updateContext(info, heading) {
Number.isFinite(info.latitude) &&
Number.isFinite(info.longitude)
) {
const cartographic = Cesium.Cartographic.fromCartesian(closest.position);
const bearing = cartographic
? bearingBetweenCoordinates(
info.latitude,
info.longitude,
Cesium.Math.toDegrees(cartographic.latitude),
Cesium.Math.toDegrees(cartographic.longitude),
)
const at = toLonLatH(closest.position);
const bearing = at
? bearingBetweenCoordinates(info.latitude, info.longitude, at.lat, at.lon)
: null;
relative = relativeBearing(bearing, heading);
}
+35
View File
@@ -11,6 +11,7 @@ import {
showContextCard,
updateContext,
} from './cockpitContext.js';
import { fromDegrees } from '../geo/index.js';
import { createContextState } from './cockpitContextState.js';
import {
dropCockpitSignal,
@@ -173,6 +174,40 @@ test('a snapshot fills the card and keeps classes other code sets', async (t) =>
assert.equal(layouts.length, 1);
});
test('when the tracked aircraft is the subject, the bearing points at the nearest contact', async (t) => {
const tracked = { layerId: 'flights', id: 'abc123', label: 'ABC123' };
const contact = (lon, lat) =>
snapshot({
subject: tracked,
cohorts: [
{
id: 'flights',
label: 'Flights',
count: 1,
relationship: 'OBSERVED',
nearest: [
{ id: 'N1', distanceM: 96_000, position: fromDegrees(lon, lat) },
],
},
],
});
const { text, owner } = fixture(t, contact(-96, 30));
// Due east of a north-facing nose.
updateContext.call(owner, INFO, 0);
await nextTick();
assert.equal(text('#cockpit-context-bearing'), 'R 090°');
// Due north: inside the dead-ahead cone.
owner.snapshot = contact(-97, 31);
updateContext.call(owner, INFO, 0);
await nextTick();
assert.equal(text('#cockpit-context-bearing'), 'AHEAD');
// Due west of a nose turned to the north-east.
owner.snapshot = contact(-98, 30);
updateContext.call(owner, INFO, 45);
await nextTick();
assert.equal(text('#cockpit-context-bearing'), 'L 135°');
});
test('each count names the provider its snapshot reports, with its feed state', async (t) => {
const reported = snapshot();
reported.cohorts[0].source = 'adsb.lol';
+100 -24
View File
@@ -1,14 +1,22 @@
/** Coordinate Cockpit lifecycle through supplied aircraft, terrain, rendering and briefing operations. */
import { onFollowChanged } from '../data/followed.js';
import { canvasOf, frameOf } from '../render/rendererOf.js';
import {
readAircraftInfo,
readSatelliteInfo,
readVesselInfo,
readSubjectCandidate,
readSubjectLayerId,
subjectContext,
subjectInfo,
entryCandidates,
resolveEntry,
resolveEntryKind,
dispatchCockpitModeChanged,
toggleTrackedTr3b,
syncTr3bToggle,
syncEntry,
refreshSubjectWords,
publishPresenceView,
navigateContext,
_adoptTrackedEntity,
@@ -30,6 +38,7 @@ import {
import {
onOrbitalClick,
onOrbitalDoubleClick,
orbitalSiteUnder,
routeSceneClick,
toggleOrbitalFocus,
} from './cockpitOrbitalFocus.js';
@@ -100,7 +109,7 @@ import {
import { DEFAULT_RADAR_RANGE_NM, nextRadarRange } from '../cockpitRadar.js';
import { VESSEL_BRIDGE_PITCH_DEG } from '../cockpitSubjects.js';
import { stepLook } from '../cockpitLook.js';
import * as Cesium from 'cesium';
import { createCockpitSubjectCaller } from '../cockpitSubjectProviders.js';
/** Whether the user asked for reduced motion: look turns then jump. */
function prefersReducedMotion() {
@@ -120,6 +129,8 @@ export class CockpitViewController {
isEntryAllowed = null,
isBridgeEntryAllowed = null,
isOrbitEntryAllowed = null,
subjectProviders = [],
isSubjectEntryAllowed = null,
isUtilityDisclosureOpen = null,
onEntered = null,
onExited = null,
@@ -128,18 +139,39 @@ export class CockpitViewController {
publish = {},
} = {},
) {
// Before anything subscribes: a viewer with no frame port throws here.
const frame = frameOf(viewer);
this.viewer = viewer;
this.services = services;
this.destroyed = false;
this.disposed = false;
this.active = false;
/** Gives camera input back; held from enter to exit. */
this.releaseCameraInput = null;
/**
* 'aircraft', 'vessel' or 'satellite' while active; which subject the
* camera rides.
* 'aircraft', 'vessel', 'satellite' or a provider's kind while active;
* which subject the camera rides.
*/
this.subjectKind = null;
/**
* The vessel subject's MMSI or the satellite's NORAD id; aircraft are
* The application's subject providers (cockpitSubjectProviders.js),
* checked by the coordinator; the one ridden while active, else null.
*/
this.subjectProviders = Array.isArray(subjectProviders)
? subjectProviders
: [];
this.subjectProvider = null;
/** The ridden provider subject's last frame and normalized HUD view. */
this.lastSubjectFrame = null;
this.subjectHud = null;
/** The Live Signals rows the provider's HUD view pushed. */
this.subjectSignalKeys = new Set();
/** Provider methods run through one guard: a throw warns once. */
this.callSubject = createCockpitSubjectCaller();
/** The look's rest pitch for a provider's view; null on a bridge. */
this.lookRestPitchDeg = null;
/**
* The vessel subject's id or the satellite's NORAD id; aircraft are
* identified by trackedEntity.
*/
this.subjectId = null;
@@ -149,6 +181,8 @@ export class CockpitViewController {
*/
this.orbital = null;
this.trackedEntity = null;
/** What the camera followed before Cockpit took it, to follow again. */
this.trackedFollow = null;
this.trackedEntityWasShown = true;
this.heading = null;
this.lastFrameMs = 0;
@@ -160,6 +194,10 @@ export class CockpitViewController {
this.surfaceWaitStartedMs = 0;
this.surfaceAcquiring = false;
this.surfaceFallback = false;
/** The height an application subject's frame last stood at (m). */
this.subjectHeightM = null;
/** The ground clamp's eased lift under that subject's eye (m). */
this.subjectLiftM = null;
/**
* Where the bridge view is turned to (`lookTarget`) and where the camera
* looks on its way there (`lookView`): yaw off the bow, starboard
@@ -203,6 +241,11 @@ export class CockpitViewController {
typeof isOrbitEntryAllowed === 'function'
? isOrbitEntryAllowed
: () => false;
// Nor a provider's subject without a gate for it.
this.isSubjectEntryAllowed =
typeof isSubjectEntryAllowed === 'function'
? isSubjectEntryAllowed
: () => false;
this.isUtilityDisclosureOpen =
typeof isUtilityDisclosureOpen === 'function'
? isUtilityDisclosureOpen
@@ -246,7 +289,14 @@ export class CockpitViewController {
entryAvailable: false,
// Which subject the entry button would enter, and the active subject.
entryKind: null,
// A provider's entry face, `{icon, label}`; null for the built-ins.
entryFace: null,
subjectKind: null,
// While a provider's subject is ridden: its HUD and exit labels, and
// `{aheadLabel}` when it looks around.
subjectGeneric: false,
subjectLabels: null,
subjectLook: null,
tr3b: null,
context: false,
// The Contact and briefing cards' collapse, which their toggles show.
@@ -269,28 +319,17 @@ export class CockpitViewController {
this.regionalBriefSubjectId = null;
this.contextLayoutFrame = null;
this.contextLayoutStamp = null;
this.scratchTarget = new Cesium.Cartesian3();
this.cockpitAnchor = new Cesium.Cartesian3();
/** Where the Cockpit eye is carried from, as ECEF; see cockpitCamera.js. */
this.cockpitAnchor = null;
this.cockpitAnchorValid = false;
this.scratchCamera = new Cesium.Cartesian3();
this.scratchAdvance = new Cesium.Cartesian3();
this.scratchCorrection = new Cesium.Cartesian3();
this.scratchForward = new Cesium.Cartesian3();
this.scratchHorizontal = new Cesium.Cartesian3();
this.scratchUp = new Cesium.Cartesian3();
this.scratchLocal = new Cesium.Cartesian3();
this.scratchEnu = new Cesium.Matrix4();
this.scratchAnchorCartographic = new Cesium.Cartographic();
this.scratchCameraCartographic = new Cesium.Cartographic();
this.scratchTargetCartographic = new Cesium.Cartographic();
this._listenerRemovers = [onLocaleChange(() => this.relocalize())];
// Camera mutations belong before scene update/culling. Changing the camera
// from preRender makes 3D Tiles discover a new view after traversal and can
// create a self-sustaining refinement loop under a moving cockpit camera.
this._listenerRemovers.push(
viewer.scene.preUpdate.addEventListener(() => this.update()),
viewer.trackedEntityChanged.addEventListener(() => {
frame.on('preUpdate', () => this.update()),
onFollowChanged(viewer, () => {
if (this.active) this._adoptTrackedEntity(performance.now());
else this.syncEntry();
}),
@@ -298,7 +337,7 @@ export class CockpitViewController {
this._listen(this.entry, 'click', () => this.enter());
// Double-clicking the followed track is a third way in.
this._listen(
viewer.scene?.canvas,
canvasOf(viewer),
'pointerdown',
() => this.onScenePointerDown(),
true,
@@ -309,7 +348,7 @@ export class CockpitViewController {
// In orbit the wheel steps the optical zoom (Cesium's own wheel zoom is
// off while the Cockpit holds the camera).
this._listen(
viewer.scene?.canvas,
canvasOf(viewer),
'wheel',
(event) => this.onOrbitalWheel(event),
{ passive: false },
@@ -456,6 +495,9 @@ export class CockpitViewController {
onOrbitalDoubleClick(position) {
return onOrbitalDoubleClick.call(this, position);
}
orbitalSiteUnder(position) {
return orbitalSiteUnder.call(this, position);
}
/**
* A site's orbital Live Signals row: focus that site, switch to it, or end
* the focus held on it.
@@ -508,6 +550,21 @@ export class CockpitViewController {
if (reset && hadFocus) this.mapViewButton?.focus({ preventScroll: true });
return reset;
}
readSubjectCandidate(provider) {
return readSubjectCandidate.call(this, provider);
}
subjectContext() {
return subjectContext.call(this);
}
subjectInfo(frame) {
return subjectInfo.call(this, frame);
}
entryCandidates(nowMs) {
return entryCandidates.call(this, nowMs);
}
resolveEntry(nowMs) {
return resolveEntry.call(this, nowMs);
}
readSubjectLayerId() {
return readSubjectLayerId.call(this);
}
@@ -529,6 +586,9 @@ export class CockpitViewController {
syncEntry() {
return syncEntry.call(this);
}
refreshSubjectWords() {
return refreshSubjectWords.call(this);
}
navigateContext(direction, options) {
return navigateContext.call(this, direction, options);
}
@@ -568,6 +628,19 @@ export class CockpitViewController {
presentLook() {
return presentLook.call(this);
}
/** Whether the active view looks around: a bridge, or a provider's with `look`. */
get looksAround() {
return (
this.active &&
(this.subjectKind === 'vessel' || Boolean(this.subjectProvider?.look))
);
}
/** Where the look rests: the bridge's pitch, or the provider's. */
get lookRestPitch() {
return Number.isFinite(this.lookRestPitchDeg)
? this.lookRestPitchDeg
: VESSEL_BRIDGE_PITCH_DEG;
}
/**
* Turn the bridge view one arrow step (see `lookKeyStep`). The camera
* eases there unless the user prefers reduced motion.
@@ -575,7 +648,7 @@ export class CockpitViewController {
* @returns {boolean} True when a bridge view was turned.
*/
turnLook(step) {
if (!this.active || this.subjectKind !== 'vessel' || !step) return false;
if (!this.looksAround || !step) return false;
this.lookTarget = stepLook(this.lookTarget, step);
if (prefersReducedMotion()) this.lookView = { ...this.lookTarget };
this.presentLook();
@@ -588,7 +661,7 @@ export class CockpitViewController {
* as entry and exit do.
*/
resetLook({ immediate = false } = {}) {
this.lookTarget = { yawDeg: 0, pitchDeg: VESSEL_BRIDGE_PITCH_DEG };
this.lookTarget = { yawDeg: 0, pitchDeg: this.lookRestPitch };
if (immediate || prefersReducedMotion())
this.lookView = { ...this.lookTarget };
this.lookLastMs = performance.now();
@@ -601,7 +674,7 @@ export class CockpitViewController {
* @returns {boolean} True on a bridge.
*/
lookAhead() {
if (!this.active || this.subjectKind !== 'vessel') return false;
if (!this.looksAround) return false;
const button = document.getElementById('cockpit-look-ahead');
const hadFocus = !!button && button.contains(document.activeElement);
this.resetLook();
@@ -718,6 +791,9 @@ export class CockpitViewController {
this.relocalizeBrief();
this.publishVision(createVisionState(this.visionMode));
this.routeSignature = null;
// A provider's words, ridden or on the entry, follow the language.
this.refreshSubjectWords();
if (!this.active) this.syncEntry();
if (this.active && this.lastSubjectInfo) {
this.rewordingSignals = true;
try {
+330 -6
View File
@@ -1,6 +1,20 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { CockpitViewController } from './cockpitController.js';
import { withEntityRecord } from '../data/entityRecords.js';
import { fakeInput } from '../input/testDoubles.mjs';
import { bindRenderer } from '../render/rendererOf.js';
import { entityFollowTarget, followedOf } from '../data/followed.js';
import {
cockpitAnchorCorrectionStep,
cockpitGroundSafeHeight,
} from '../cockpitMath.js';
import {
COCKPIT_FORWARD_OFFSET_M,
COCKPIT_MIN_GROUND_CLEARANCE_M,
COCKPIT_UP_OFFSET_M,
COCKPIT_VIEW_PITCH_DEG,
} from './cockpitPresentation.js';
function environment() {
const original = { document: globalThis.document, window: globalThis.window };
@@ -22,13 +36,32 @@ function environment() {
const viewer = {
scene: {
preUpdate: event,
screenSpaceCameraController: { enableInputs: false },
screenSpaceCameraController: { enableInputs: true },
},
trackedEntityChanged: event,
entities: { contains: () => false },
};
// What the camera follows, as a layer's follow sets it.
const camera = {
followed: null,
follow(target) {
camera.followed = target;
},
on: (name, fn) =>
name === 'followChanged' ? event.addEventListener(fn) : () => {},
};
// The renderer's frame port: Cockpit moves the camera on its preUpdate.
bindRenderer(viewer, {
camera,
frame: {
on: (phase, fn) =>
phase === 'preUpdate' ? event.addEventListener(fn) : () => {},
},
});
/** Follow a holder of an entity record, as a layer's follow does. */
const follow = (holder) =>
camera.follow(holder ? entityFollowTarget(holder, {}) : null);
return {
viewer,
follow,
callbacks,
restore() {
Object.assign(globalThis, original);
@@ -61,7 +94,14 @@ test('disposing an active Cockpit releases the supplied render owner without ret
const owner = new CockpitViewController(env.viewer, {
services: { releaseContinuousRender: (reason) => released.push(reason) },
});
// Entered: the cockpit holds camera input, as enter() takes it.
const { input } = fakeInput(env.viewer);
owner.active = true;
owner.releaseCameraInput = input.suspendCamera('cockpit');
assert.equal(
env.viewer.scene.screenSpaceCameraController.enableInputs,
false,
);
owner.dispose();
owner.dispose();
assert.deepEqual(released, ['cockpit']);
@@ -69,7 +109,7 @@ test('disposing an active Cockpit releases the supplied render owner without ret
env.viewer.scene.screenSpaceCameraController.enableInputs,
true,
);
assert.equal(env.viewer.trackedEntity, undefined);
assert.equal(followedOf(env.viewer), null);
assert.equal(owner.active, false);
} finally {
env.restore();
@@ -95,9 +135,9 @@ test('aircraft identity is read from the supplied layer instances', () => {
militaryFlightsLayer: { getTrackedInfo: () => military },
},
});
env.viewer.trackedEntity = { gevTrackedId: 'military:def456' };
env.follow(withEntityRecord({}, { trackedId: 'military:def456' }));
assert.deepEqual(owner.readAircraftInfo(), military);
env.viewer.trackedEntity = { gevTrackedId: 'flights:abc123' };
env.follow(withEntityRecord({}, { trackedId: 'flights:abc123' }));
assert.deepEqual(owner.readAircraftInfo(), civilian);
owner.dispose();
} finally {
@@ -244,3 +284,287 @@ test('the weather toggle flips from its own state, however fast it is pressed',
env.restore();
}
});
/**
* The Cockpit eye as cockpitCamera.js computed it with Cesium's own maths,
* for one update: the anchor advanced along the heading and pulled toward
* the target (held on it when stale), lifted to the floor, then the eye
* set forward and up from it and lifted again.
*/
function cesiumCockpitEye(
Cesium,
{ target, anchor, info, heading, dtSec, floorM, liftM },
) {
const { Cartesian3, Matrix4, Transforms, Cartographic, Ellipsoid } = Cesium;
const h = Cesium.Math.toRadians(heading);
const p = Cesium.Math.toRadians(COCKPIT_VIEW_PITCH_DEG);
const speed = Math.max(0, info.velocityMps);
const along = (origin, x, y, z) =>
Cartesian3.normalize(
Matrix4.multiplyByPointAsVector(
Transforms.eastNorthUpToFixedFrame(origin, Ellipsoid.WGS84),
new Cartesian3(x, y, z),
new Cartesian3(),
),
new Cartesian3(),
);
let a = Cartesian3.clone(anchor ?? target);
if (info.stale) a = Cartesian3.clone(target);
else {
const horizontal = along(a, Math.sin(h), Math.cos(h), 0);
a = Cartesian3.add(
a,
Cartesian3.multiplyByScalar(horizontal, speed * dtSec, new Cartesian3()),
new Cartesian3(),
);
const correction = Cartesian3.subtract(target, a, new Cartesian3());
const distance = Cartesian3.magnitude(correction);
const step = cockpitAnchorCorrectionStep(distance, speed, dtSec);
if (step > 0 && distance > 0)
a = Cartesian3.add(
a,
Cartesian3.multiplyByScalar(
correction,
step / distance,
new Cartesian3(),
),
new Cartesian3(),
);
}
const anchorCarto = Cartographic.fromCartesian(a);
let floor = floorM;
const targetCarto = Cartographic.fromCartesian(target);
if (!Number.isFinite(floor) && speed < 90) floor = targetCarto.height - liftM;
if (Number.isFinite(floor)) {
const minimum = cockpitGroundSafeHeight(
anchorCarto.height,
floor,
COCKPIT_MIN_GROUND_CLEARANCE_M - COCKPIT_UP_OFFSET_M,
);
if (minimum !== anchorCarto.height) {
anchorCarto.height = minimum;
a = Ellipsoid.WGS84.cartographicToCartesian(anchorCarto);
}
}
const horizontal = along(a, Math.sin(h), Math.cos(h), 0);
const forward = along(
a,
Math.sin(h) * Math.cos(p),
Math.cos(h) * Math.cos(p),
Math.sin(p),
);
const up = along(
a,
-Math.sin(h) * Math.sin(p),
-Math.cos(h) * Math.sin(p),
Math.cos(p),
);
let eye = Cartesian3.add(
Cartesian3.add(
a,
Cartesian3.multiplyByScalar(
horizontal,
COCKPIT_FORWARD_OFFSET_M,
new Cartesian3(),
),
new Cartesian3(),
),
Cartesian3.multiplyByScalar(
Cartesian3.normalize(a, new Cartesian3()),
COCKPIT_UP_OFFSET_M,
new Cartesian3(),
),
new Cartesian3(),
);
const eyeCarto = Cartographic.fromCartesian(eye);
const safe = cockpitGroundSafeHeight(
eyeCarto.height,
floor,
COCKPIT_MIN_GROUND_CLEARANCE_M,
);
if (safe !== eyeCarto.height) {
eyeCarto.height = safe;
eye = Ellipsoid.WGS84.cartographicToCartesian(eyeCarto);
}
return { eye, forward, up, anchor: a };
}
/** A Cockpit flying `info` over `target`, its camera writes in `views`. */
function cockpitOver({ info, target, services = {} }) {
const views = [];
const viewer = {
trackedEntityChanged: { addEventListener: () => () => {} },
};
bindRenderer(viewer, {
frame: { on: () => () => {}, time: () => 0 },
camera: {
followed: null,
on: () => () => {},
pose: () => ({ lat: 30.2, lon: -97.7 }),
setView: (view) => views.push(view),
},
});
const owner = new CockpitViewController(viewer, {
services: {
flightsLayer: { getTrackedInfo: () => info },
militaryFlightsLayer: {},
cachedGroundFloor: () => null,
trackedEntityDrawn: () => true,
releaseContinuousRender() {},
...services,
},
});
owner.updateHud = () => {};
owner.active = true;
owner.heading = info.track;
owner.trackedEntity = {};
owner.trackedFollow = { key: 'flights:abc123', position: () => target };
return { owner, viewer, views };
}
const near = (a, b, eps, what) =>
assert.ok(
Math.abs(a.x - b.x) <= eps &&
Math.abs(a.y - b.y) <= eps &&
Math.abs(a.z - b.z) <= eps,
`${what}: ${JSON.stringify(a)} vs ${JSON.stringify(b)}`,
);
test('Cockpit places the eye at its aircraft as the Cesium maths did', async () => {
const Cesium = await import('cesium');
const env = environment();
const realNow = performance.now;
try {
const target = Cesium.Cartesian3.fromDegrees(-97.67, 30.19, 1200);
const info = {
icao24: 'abc123',
layerId: 'flights',
track: 72,
velocityMps: 200,
latitude: 30.19,
longitude: -97.67,
onGround: false,
stale: true,
};
const { owner, views } = cockpitOver({ info, target });
// Held on the target while the feed is stale.
owner.update();
let expected = cesiumCockpitEye(Cesium, {
target,
info,
heading: 72,
dtSec: 0,
liftM: 0,
});
near(views[0].destination, expected.eye, 1e-6, 'stale eye');
near(views[0].orientation.direction, expected.forward, 1e-12, 'direction');
near(views[0].orientation.up, expected.up, 1e-12, 'up');
// Live: the anchor coasts 80 ms along the heading and is pulled toward
// where the layer now shows the aircraft.
info.stale = false;
const anchor = Cesium.Cartesian3.clone(expected.anchor);
const moved = Cesium.Cartesian3.fromDegrees(-97.6698, 30.1901, 1210);
owner.trackedFollow.position = () => moved;
let now = owner.lastFrameMs + 80;
performance.now = () => now;
owner.update();
expected = cesiumCockpitEye(Cesium, {
target: moved,
anchor,
info,
heading: 72,
dtSec: 0.08,
liftM: 0,
});
assert.equal(views.length, 2);
near(views[1].destination, expected.eye, 1e-6, 'live eye');
near(views[1].orientation.direction, expected.forward, 1e-12, 'direction');
near(views[1].orientation.up, expected.up, 1e-12, 'up');
// An aircraft its layer no longer draws ends Cockpit.
owner.services.trackedEntityDrawn = () => false;
now += 80;
owner.update();
assert.equal(owner.active, false);
assert.equal(views.length, 2);
owner.dispose();
} finally {
performance.now = realNow;
env.restore();
}
});
test('a grounded Cockpit probes the mesh from the camera and keeps the eye above the floor', async () => {
const Cesium = await import('cesium');
const env = environment();
try {
// Reported below the apron: the floor lifts the anchor and the eye.
const target = Cesium.Cartesian3.fromDegrees(-97.67, 30.19, 120);
const info = {
icao24: 'abc123',
layerId: 'flights',
track: 300,
velocityMps: 0,
latitude: 30.19,
longitude: -97.67,
onGround: true,
stale: true,
};
const probes = [];
const { owner, viewer, views } = cockpitOver({
info,
target,
services: {
cachedGroundFloor: () => 140,
warmGroundFloor() {},
cachedMeshFloor: () => null,
meshFloorPreferred: () => true,
sampleMeshFloorCells: (...args) => probes.push(args),
GROUND_FLOOR_LIFT_M: 0,
},
});
// The tracked contact names the draw sets its probe sees through.
withEntityRecord(owner.trackedEntity, {
groundSets: () => ['flights-models:1', 'flights-tracked-icon:1'],
});
// The surface wait is over: Cockpit flies on the ground floor.
owner.surfaceWaitStartedMs = -1e9;
owner.update();
assert.equal(probes.length, 1);
const [host, points, options] = probes[0];
assert.equal(host, viewer);
assert.deepEqual(points, [{ lat: 30.19, lon: -97.67 }]);
assert.deepEqual(options, {
sets: ['flights-models:1', 'flights-tracked-icon:1'],
viewerLat: 30.2,
viewerLon: -97.7,
});
const expected = cesiumCockpitEye(Cesium, {
target,
info,
heading: 300,
dtSec: 0,
floorM: 140,
liftM: 0,
});
assert.equal(views.length, 1);
// The floor lifts round-trip through geodetic heights: the shared geo helpers' and
// Cesium's agree to well under a millimetre there.
near(views[0].destination, expected.eye, 1e-4, 'eye');
const height = Cesium.Cartographic.fromCartesian(
new Cesium.Cartesian3(
views[0].destination.x,
views[0].destination.y,
views[0].destination.z,
),
).height;
assert.ok(
height >= 140 + COCKPIT_MIN_GROUND_CLEARANCE_M - 1e-6,
`${height}`,
);
owner.dispose();
} finally {
env.restore();
}
});
+64 -24
View File
@@ -1,3 +1,4 @@
import { followedOf } from '../data/followed.js';
import { nextTick } from 'vue';
import { CockpitViewController, CockpitDisplayPortal } from './cockpit.js';
import {
@@ -5,10 +6,13 @@ import {
bridgeEntryAllowed,
cockpitEntryAllowed,
orbitEntryAllowed,
subjectEntryAllowed,
} from '../contextModePolicy.js';
import { cockpitSubjectProviders } from '../cockpitSubjectProviders.js';
import { formatAwarenessLabel } from '../data/militaryAwarenessEngine.js';
import { enterCockpitWithTracking } from '../cockpitTracking.js';
import { cockpitVisionModeForStyle } from '../cockpitVisionPolicy.js';
import { readEntityRecord } from '../data/entityRecords.js';
/** Own Cockpit entry/rollback, readouts and the single Display portal. */
export class CockpitCoordinator {
@@ -54,14 +58,18 @@ export class CockpitCoordinator {
meshFloorPreferred,
warmGroundFloor,
sampleMeshFloorCells,
trackedEntityDrawn,
holdContinuousRender,
releaseContinuousRender,
fetchRegionalBrief,
regionalDistanceM,
weatherCodeLabel,
acquireOrbitImagery,
cockpitSubjects,
} = services;
this._cockpitDisplayPortal = null;
// The application's own subjects (services.cockpitSubjects), checked once.
const subjectProviders = cockpitSubjectProviders(cockpitSubjects ?? []);
this.cockpitView = new CockpitViewController(viewer, {
services: {
flightsLayer,
@@ -79,6 +87,7 @@ export class CockpitCoordinator {
meshFloorPreferred,
warmGroundFloor,
sampleMeshFloorCells,
trackedEntityDrawn,
holdContinuousRender,
releaseContinuousRender,
fetchRegionalBrief,
@@ -108,6 +117,21 @@ export class CockpitCoordinator {
vesselsEnabled: !!this._dataManager?.isEnabled('ais-live-vessels'),
contextModeChanging: this._contextModeChanging,
}),
subjectProviders,
// A provider's subject needs its own layer on, no Context change in
// flight, and the provider's own say.
isSubjectEntryAllowed: (provider, candidate) =>
subjectEntryAllowed({
layerEnabled: this._isLayerEnabled(provider.layerId),
contextModeChanging: this._contextModeChanging,
providerAllows:
this.cockpitView?.callSubject(
provider,
'isEntryAllowed',
[candidate],
false,
) === true,
}),
isOrbitEntryAllowed: () =>
orbitEntryAllowed({
satellitesEnabled: !!this._dataManager?.isEnabled('satellites'),
@@ -122,9 +146,9 @@ export class CockpitCoordinator {
onExited: () => this.exitPanels(),
onRide: (layerId) => this._adoptRiddenLayer(layerId),
restoreTrackingFrame: (entity) => {
const [layerId, ...idParts] = String(entity?.gevTrackedId || '').split(
':',
);
const [layerId, ...idParts] = String(
readEntityRecord(entity)?.trackedId || '',
).split(':');
const trackedId = idParts.join(':');
if (!trackedId) return false;
if (layerId === 'flights')
@@ -197,6 +221,9 @@ export class CockpitCoordinator {
this.cockpitView.subjectKind === 'satellite'
)
return 'Cockpit is in an orbital view — exit it first, then track an aircraft to enter Cockpit';
// And in an application's own first-person view.
if (this.cockpitView?.active && this.cockpitView.subjectProvider)
return 'Cockpit is in another first-person view — exit it first, then track an aircraft to enter Cockpit';
if (!this._aircraftLayerEnabled)
return 'No aircraft layer is on — turn on Flights or Military Flights and track an aircraft to enter Cockpit';
return null;
@@ -216,15 +243,26 @@ export class CockpitCoordinator {
active && this.cockpitView?.subjectKind === 'satellite'
? this.cockpitView.readSatelliteInfo?.()
: null;
// And a provider's subject in use.
const provided =
active && this.cockpitView?.subjectProvider
? {
kind: this.cockpitView.subjectProvider.kind,
id: this.cockpitView.subjectId,
layerId: this.cockpitView.subjectProvider.layerId,
callsign: null,
name: this.cockpitView.lastSubjectFrame?.name ?? null,
}
: null;
const gateOpen = Boolean(this.cockpitView?.isEntryAllowed?.());
// "Could Cockpit be ENTERED right now" — so it is false while already
// inside, unconditionally. Cockpit takes the entity off
// `viewer.trackedEntity` on entry and NEXT puts one back, which made this
// the camera's follow on entry and NEXT puts one back, which made this
// flip true/false between calls while `active` stayed true; readers
// (including the voice model) read that as a broken half-entered state.
const entryAllowed =
!active &&
Boolean(gateOpen && info && this.viewer?.trackedEntity?.position);
Boolean(gateOpen && info && followedOf(this.viewer)?.entity?.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
@@ -244,30 +282,32 @@ export class CockpitCoordinator {
? 'subject-layer-off'
: 'no-tracked-aircraft',
visionMode: this.cockpitView?.visionMode || null,
subject: satellite
? {
kind: 'satellite',
id: satellite.id,
layerId: satellite.layerId,
callsign: null,
name: satellite.name,
}
: vessel
subject: provided
? provided
: satellite
? {
kind: 'vessel',
id: vessel.mmsi,
layerId: vessel.layerId,
kind: 'satellite',
id: satellite.id,
layerId: satellite.layerId,
callsign: null,
name: vessel.name,
name: satellite.name,
}
: info
: vessel
? {
kind: 'aircraft',
id: info.icao24 || info.id || null,
layerId: info.layerId || null,
callsign: info.callsign || null,
kind: 'vessel',
id: vessel.id,
layerId: vessel.layerId,
callsign: null,
name: vessel.name,
}
: null,
: info
? {
kind: 'aircraft',
id: info.icao24 || info.id || null,
layerId: info.layerId || null,
callsign: info.callsign || null,
}
: null,
navigation: snapshot
? {
canPrevious: Boolean(snapshot.navigation?.canPrevious),
+251
View File
@@ -0,0 +1,251 @@
// A double-click on the followed track enters first person, and the
// renderer's own double-click follow is held off for that press, so it
// cannot let go of the track first.
//
// Run with: npm test
import test from 'node:test';
import assert from 'node:assert/strict';
import {
fakeInput,
FakeScreenSpaceEventHandler,
FAKE_EVENT_TYPES,
} from '../input/testDoubles.mjs';
import { bindRenderer } from '../render/rendererOf.js';
import { entityFollowTarget } from '../data/followed.js';
import { createCesiumInput } from '../render/cesium/input.js';
import { routeSceneDoubleClick, onSceneDoubleClick } from './cockpitInput.js';
import { inputFor } from '../input/dispatcher.js';
function harness(t, { stock = null } = {}) {
t.mock.timers.enable({ apis: ['setTimeout', 'Date'] });
const viewer = {
scene: {
pick: () => null,
},
clock: { currentTime: 0 },
};
// The followed aircraft is drawn at (100, 100).
const project = () => ({ x: 100, y: 100 });
// With `stock`, the renderer's own input port takes the viewer's stock
// double-click follow and runs it as the app's does; else the fake input.
// The camera port follows the aircraft, as the flights layer's follow does.
const camera = { followed: null, on: () => () => {} };
const input = stock
? cesiumInput(viewer, stock, project, camera)
: fakeInput(viewer);
if (!stock) bindRenderer(viewer, { query: { project }, camera });
const entity = {
id: 'flights:abc',
position: { getValue: () => ({ x: 1, y: 2, z: 3 }) },
};
camera.followed = entityFollowTarget(entity, {
position: () => entity.position.getValue(),
frame: 'enu',
viewFrom: { x: 0, y: -1000, z: 500 },
});
const controller = {
viewer,
active: false,
destroyed: false,
entered: 0,
holds: 0,
// Counted here, unless the test watches the renderer's own hold.
...(stock
? {}
: {
holdStockFollow() {
this.holds += 1;
return () => {
this.holds -= 1;
};
},
}),
resolveEntryKind: () => 'aircraft',
enter() {
this.entered += 1;
},
onSceneDoubleClick(position) {
return onSceneDoubleClick.call(this, position);
},
};
const stop = routeSceneDoubleClick.call(controller);
t.after(() => {
stop();
input.destroy();
});
return { input, controller, stop };
}
/** The Cesium renderer's input port over a fake handler, with `follow` as
* the viewer's stock double-click follow. */
function cesiumInput(viewer, follow, project, camera) {
const stock = new FakeScreenSpaceEventHandler();
stock.setInputAction(follow, FAKE_EVENT_TYPES.LEFT_DOUBLE_CLICK);
viewer.screenSpaceEventHandler = stock;
viewer.scene.canvas = {
addEventListener() {},
removeEventListener() {},
};
const handler = new FakeScreenSpaceEventHandler();
const query = { project, pick: () => null, drillPick: () => [] };
const made = createCesiumInput(viewer, {
query,
createHandler: () => handler,
report: (error) => {
throw error;
},
document: null,
});
bindRenderer(viewer, { input: made.port, query, camera });
const T = FAKE_EVENT_TYPES;
const fire = (type) => (position) => handler.fire(type, { position });
return {
down: fire(T.LEFT_DOWN),
up: fire(T.LEFT_UP),
click: fire(T.LEFT_CLICK),
tap(position) {
handler.fire(T.LEFT_DOWN, { position });
handler.fire(T.LEFT_UP, { position });
handler.fire(T.LEFT_CLICK, { position });
},
dblclick: fire(T.LEFT_DOUBLE_CLICK),
stockEnabled: (name) => made.port.behaviours[name].enabled,
destroy: () => made.dispose(),
};
}
const doubleClick = (input, position) => {
input.tap(position);
input.down(position);
input.up(position);
input.dblclick(position);
};
test('a double-click on the followed track enters, with the stock follow held off for the press', async (t) => {
const { input, controller } = harness(t);
const on = { x: 110, y: 95 };
input.down(on);
assert.equal(
input.stockEnabled('dblclickFollow'),
false,
'held at the press',
);
input.up(on);
input.click(on);
input.down(on);
input.up(on);
input.dblclick(on);
assert.equal(controller.entered, 1);
// Given back once the double-click's dispatch is over.
await Promise.resolve();
assert.equal(controller.holds, 0, 'given back');
});
test("a double-click elsewhere is the renderer's own", (t) => {
const { input, controller } = harness(t);
const off = { x: 400, y: 300 };
input.down(off);
assert.equal(controller.holds, 0);
doubleClick(input, off);
assert.equal(controller.entered, 0);
assert.equal(controller.holds, 0);
});
test('a single press on the track gives the stock follow back at its release, or by itself', (t) => {
const { input, controller } = harness(t);
input.tap({ x: 100, y: 100 });
assert.equal(controller.holds, 0, 'given back at the release');
t.mock.timers.tick(700);
input.down({ x: 100, y: 100 });
assert.equal(controller.holds, 1);
t.mock.timers.tick(700);
assert.equal(controller.holds, 0, 'a press never released lets go');
assert.equal(controller.entered, 0);
});
test("a double-click that starts on the track and ends off it is the renderer's own", (t) => {
const follows = [];
const { input, controller } = harness(t, {
stock: (event) => follows.push(event.position),
});
const on = { x: 120, y: 100 };
const off = { x: 140, y: 100 };
// As Cesium raises them: each press clicks, then the double-click.
input.tap(on);
input.tap(off);
input.dblclick(off);
assert.equal(controller.entered, 0);
assert.equal(follows.length, 1, 'the stock follow ran');
assert.equal(input.stockEnabled('dblclickFollow'), true);
});
test('a press elsewhere just before cannot make a press on the track keep its hold', (t) => {
const follows = [];
const { input, controller } = harness(t, {
stock: (event) => follows.push(event.position),
});
input.tap({ x: 500, y: 500 });
input.tap({ x: 120, y: 100 });
input.tap({ x: 140, y: 100 });
input.dblclick({ x: 140, y: 100 });
assert.equal(controller.entered, 0);
assert.equal(follows.length, 1, 'the stock follow ran');
});
test('a press on the track long after the last keeps no hold past its release', (t) => {
const { input, controller } = harness(t);
const on = { x: 100, y: 100 };
input.tap(on);
t.mock.timers.tick(701);
input.down(on);
input.up(on);
assert.equal(controller.holds, 0, 'it cannot end a double-click');
input.down(on);
input.up(on);
assert.equal(controller.holds, 1, 'a quick second press keeps it');
});
test('a double-click that ends on the track holds the stock follow off', async (t) => {
const follows = [];
const { input, controller } = harness(t, {
stock: (event) => follows.push(event.position),
});
const on = { x: 110, y: 95 };
input.tap({ x: 140, y: 100 });
input.tap(on);
input.dblclick(on);
assert.equal(controller.entered, 1);
assert.deepEqual(follows, [], 'the stock follow did not run');
await Promise.resolve();
assert.equal(input.stockEnabled('dblclickFollow'), true, 'given back');
});
test('subscribers after the Cockpit find the stock follow held through the double-click', async (t) => {
const { input, controller } = harness(t, { stock: () => {} });
// A layer's own follow on a double-click, subscribed after the Cockpit
// (Mapped Installations follows a site only while the stock follow runs).
const seen = [];
const off = inputFor(controller.viewer).onPointer('dblclick', () =>
seen.push(input.stockEnabled('dblclickFollow')),
);
t.after(off);
const on = { x: 110, y: 95 };
input.tap(on);
input.tap(on);
input.dblclick(on);
assert.deepEqual(seen, [false], 'held for the whole dispatch');
await Promise.resolve();
assert.equal(input.stockEnabled('dblclickFollow'), true, 'given back after');
});
test('an active Cockpit leaves presses alone, and stopping lets a hold go', (t) => {
const { input, controller, stop } = harness(t);
controller.active = true;
input.down({ x: 100, y: 100 });
assert.equal(controller.holds, 0);
controller.active = false;
input.down({ x: 100, y: 100 });
assert.equal(controller.holds, 1);
stop();
assert.equal(controller.holds, 0);
});
+232 -11
View File
@@ -9,6 +9,13 @@ import assert from 'node:assert/strict';
import { createPinia } from 'pinia';
import { createApp, defineComponent, h, nextTick } from 'vue';
import { DataLayerManager } from '../data/manager.js';
import { withEntityRecord } from '../data/entityRecords.js';
import {
bindFakeCesiumCamera,
followEntity,
} from '../testSupport/fakeCameraPort.mjs';
import { followedOf } from '../data/followed.js';
import { fakeScenePorts } from '../testSupport/fakeCesiumScene.mjs';
import { createDependencies } from '../layers/awareness/dependencies.js';
import { CockpitCoordinator } from './cockpitCoordinator.js';
import { ContextControls } from './contextControls.js';
@@ -55,8 +62,11 @@ function fixture(
changing = false,
dataManager: suppliedManager = null,
readContext = null,
subjects = [],
vessel = null,
} = {},
) {
let selectedVessel = vessel;
document.body.replaceChildren();
const host = document.body.appendChild(document.createElement('div'));
const pinia = createPinia();
@@ -75,17 +85,18 @@ function fixture(
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 entityFor = (subject) =>
withEntityRecord(
{ position: { getValue: () => null }, show: true },
{
trackedId: 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) },
@@ -95,13 +106,22 @@ function fixture(
},
trackedEntityChanged: listeners(),
};
// The Cockpit reads frames, the camera and what it follows through ports.
bindFakeCesiumCamera(viewer, fakeScenePorts(viewer));
if (tracked) followEntity(viewer, entity);
const context = { mode: contextMode, changing };
const coordinator = new CockpitCoordinator({
viewer,
services: {
flightsLayer: { getTrackedInfo: trackedFrom('flights') },
militaryFlightsLayer: { getTrackedInfo: trackedFrom('military') },
aisLiveVesselsLayer: { getCockpitSubject: () => null },
// Like the layer, no subject while Live AIS Vessels is off.
aisLiveVesselsLayer: {
getCockpitSubject: () =>
selectedVessel && layers.has('ais-live-vessels')
? { ...selectedVessel }
: null,
},
// Like the layer, no subject while Satellites is off.
satellitesLayer: {
getCockpitSubject: () =>
@@ -113,6 +133,7 @@ function fixture(
isTr3b: () => false,
holdContinuousRender() {},
releaseContinuousRender() {},
cockpitSubjects: subjects,
},
elements: {},
operations: {
@@ -147,6 +168,7 @@ function fixture(
'cockpit-mode',
'cockpit-bridge',
'cockpit-orbit',
'cockpit-subject',
);
});
/** Turn a layer off and tell the Context owner, as the data manager does. */
@@ -168,13 +190,39 @@ function fixture(
/** Track another aircraft, as Contacts navigation does mid-session. */
const retrack = (subject) => {
tracked = subject;
viewer.trackedEntity = entityFor(subject);
entities.add(viewer.trackedEntity);
const next = entityFor(subject);
entities.add(next);
followEntity(viewer, next);
};
/** Select a vessel on the map, or none. */
const selectVessel = (info) => {
selectedVessel = info;
};
const $ = (selector) => document.querySelector(selector);
return { $, coordinator, cockpit, store, layers, disable, retrack, pinia };
return {
$,
coordinator,
cockpit,
store,
layers,
disable,
retrack,
selectVessel,
pinia,
};
}
/** A selected vessel as the AIS layer gives it to the bridge view. */
const VESSEL = Object.freeze({
id: '211000001',
name: 'EXAMPLE',
latitude: 54,
longitude: 10,
headingDeg: 90,
courseDeg: 90,
speedMps: 5,
});
test('a civilian aircraft enters with Live Flights alone: no Contacts, no Military', (t) => {
const { coordinator, cockpit } = fixture(t, {
enabled: ['flights'],
@@ -498,8 +546,10 @@ test('a ride handed to an aircraft on a layer Contacts turned on keeps that laye
await settle();
assert.equal(cockpit.enter(), true);
// NEXT hands the view to a military aircraft; Contacts turned its layer on.
// The follow's change adopts it as the ridden aircraft: the Cockpit
// takes the camera from the follow.
retrack({ layerId: 'military', info: MILITARY });
assert.equal(cockpit._adoptTrackedEntity(performance.now()), true);
assert.equal(followedOf(cockpit.viewer), null, 'adopted');
assert.equal(cockpit.readSubjectLayerId(), 'military');
await manager.setEnabled('ais-live-vessels', false, { origin: 'user' });
await settle();
@@ -567,6 +617,32 @@ test('the readout entry reads BRIDGE for a selected vessel', async (t) => {
assert.match(readoutEntry.textContent, /BRIDGE/);
});
test('without providers the built-in order decides: a vessel selected after an aircraft still reads COCKPIT', async (t) => {
const { $, cockpit, store, selectVessel } = fixture(t, {
enabled: ['flights', 'ais-live-vessels'],
tracked: { layerId: 'flights', info: CIVIL },
});
cockpit.syncEntry();
assert.equal(store.presence.entryKind, 'aircraft');
await new Promise((resolve) => setTimeout(resolve, 2));
selectVessel(VESSEL);
cockpit.syncEntry();
await nextTick();
assert.equal(store.presence.entryKind, 'aircraft');
assert.match($('#cockpit-entry-readout').textContent, /COCKPIT/);
// And the other way round: an aircraft tracked after the vessel.
const later = fixture(t, {
enabled: ['flights', 'ais-live-vessels'],
vessel: VESSEL,
});
later.cockpit.syncEntry();
assert.equal(later.store.presence.entryKind, 'vessel');
await new Promise((resolve) => setTimeout(resolve, 2));
later.retrack({ layerId: 'flights', info: CIVIL });
later.cockpit.syncEntry();
assert.equal(later.store.presence.entryKind, 'aircraft');
});
test('a tracked satellite needs Satellites on for the ORBIT entry', async (t) => {
const { $, cockpit } = fixture(t, { satellite: SATELLITE });
cockpit.syncEntry();
@@ -648,3 +724,148 @@ test('turning Satellites off ends the orbital view', (t) => {
disable('satellites');
assert.equal(cockpit.active, false);
});
/** An application provider whose subject sits on `example-layer`. */
function exampleSubject() {
const released = [];
return {
released,
provider: {
kind: 'example-kind',
layerId: 'example-layer',
entryFace: { icon: 'commute', label: 'RIDE' },
labels: { view: 'Example view', exit: 'Exit example', exitText: 'EXIT' },
candidate: () => ({ id: 'a1', name: 'Example 12' }),
hold: () => true,
read: () => ({
id: 'a1',
name: 'Example 12',
latitude: 30,
longitude: -97,
heightM: 200,
headingDeg: 90,
eye: { upM: 2 },
}),
hud: () => ({ title: 'Example 12' }),
release: (id, { restore }) => released.push([id, restore]),
},
};
}
test("a provider's subject needs only its own layer, and never a Context change in flight", async (t) => {
const { provider } = exampleSubject();
let changing = false;
const off = fixture(t, { subjects: [provider] });
off.cockpit.syncEntry();
await nextTick();
assert.equal(off.$('#cockpit-entry').hidden, true, 'its layer is off');
assert.equal(off.cockpit.enter(), false);
const on = fixture(t, {
enabled: ['example-layer'],
subjects: [provider],
readContext: () => ({ mode: null, changing }),
});
changing = true;
on.cockpit.syncEntry();
await nextTick();
assert.equal(on.$('#cockpit-entry').hidden, true, 'Context is changing');
changing = false;
on.cockpit.syncEntry();
await nextTick();
assert.equal(on.$('#cockpit-entry').hidden, false);
assert.match(on.$('#cockpit-entry').textContent, /RIDE/);
assert.match(on.$('#cockpit-entry-readout').textContent, /commute/);
});
test("a provider's view reports its subject, refuses voice entry and ends with its layer", async (t) => {
const { provider, released } = exampleSubject();
const { cockpit, coordinator, disable } = fixture(t, {
enabled: ['example-layer', 'flights'],
subjects: [provider],
});
cockpit.syncEntry();
assert.equal(cockpit.enter(), true);
const state = coordinator.getCockpitState();
assert.equal(state.active, true);
assert.deepEqual(state.subject, {
kind: 'example-kind',
id: 'a1',
layerId: 'example-layer',
callsign: null,
name: 'Example 12',
});
assert.equal(coordinator.controlCockpit('enter').ok, false);
assert.match(coordinator._cockpitEntryRefusal(), /another first-person view/);
disable('flights');
assert.equal(cockpit.active, true, 'another layer is free to go off');
disable('example-layer');
assert.equal(cockpit.active, false, 'its own layer going off ends it');
assert.deepEqual(released, [['a1', false]]);
});
test("a provider's guards: a throwing candidate, gate or release, and a gate that is not true", async (t) => {
const warned = [];
t.mock.method(console, 'warn', (message) => warned.push(String(message)));
const entered = (provider) => {
const { cockpit } = fixture(t, {
enabled: ['example-layer'],
subjects: [provider],
});
cockpit.syncEntry();
return { cockpit, entered: cockpit.enter() };
};
const { provider: base } = exampleSubject();
// A candidate() that throws offers nothing.
const noCandidate = entered({
...base,
candidate: () => {
throw new Error('candidate failed');
},
});
assert.equal(noCandidate.entered, false);
assert.equal(noCandidate.cockpit.resolveEntry(), null);
// An isEntryAllowed() that throws, or answers anything but true, shuts
// the gate.
for (const isEntryAllowed of [
() => {
throw new Error('gate failed');
},
() => 1,
() => 'yes',
() => ({}),
]) {
const gated = entered({ ...base, isEntryAllowed });
assert.equal(gated.entered, false, String(isEntryAllowed));
assert.equal(gated.cockpit.active, false);
}
// A release() that throws still ends the view.
const { provider } = exampleSubject();
const releasing = entered({
...provider,
release: () => {
throw new Error('release failed');
},
});
assert.equal(releasing.entered, true);
assert.equal(releasing.cockpit.exit(), true);
assert.equal(releasing.cockpit.active, false);
assert.equal(document.body.classList.contains('cockpit-subject'), false);
for (const method of ['candidate', 'isEntryAllowed', 'release'])
assert.ok(
warned.some((line) => line.includes(`${method}() failed`)),
method,
);
});
test('a malformed provider is left out and the built-in kinds are unchanged', async (t) => {
t.mock.method(console, 'warn', () => {});
const { cockpit } = fixture(t, {
enabled: ['flights'],
tracked: { layerId: 'flights', info: CIVIL },
subjects: [{ kind: 'aircraft', layerId: 'flights' }],
});
assert.deepEqual(cockpit.subjectProviders, []);
cockpit.syncEntry();
assert.equal(cockpit.enter(), true);
assert.equal(cockpit.subjectKind, 'aircraft');
});
+111 -41
View File
@@ -1,7 +1,11 @@
/** Route Cockpit keys while preserving the active disclosure and form-control owner. */
import * as Cesium from 'cesium';
import { followedOf } from '../data/followed.js';
import { fromDegrees } from '../geo/ellipsoid.js';
import { lookKeyStep } from '../cockpitLook.js';
import { isPointerFree } from '../data/inputOwnership.js';
import { inputFor } from '../input/dispatcher.js';
import { findInput, findQuery } from '../render/rendererOf.js';
import { trackedPositionNow } from './cockpitCamera.js';
/** How far from the followed track a double-click may land, CSS pixels. */
export const SUBJECT_DOUBLE_CLICK_RADIUS_PX = 32;
@@ -32,15 +36,13 @@ export const DOUBLE_CLICK_MEMORY_MS = 700;
/** Where the track `kind` would ride is drawn now, as a world position. */
function subjectWorldPosition(kind) {
if (kind === 'aircraft') {
return (
this.viewer.trackedEntity?.position?.getValue?.(
this.viewer.clock?.currentTime,
) ?? null
);
}
if (kind === 'aircraft')
return trackedPositionNow(this.viewer, followedOf(this.viewer));
if (kind === 'satellite')
return this.services.satellitesLayer?.getCockpitPosition?.() ?? null;
// An application's subject has no position before its view is entered:
// the selected vessel's sprite must not stand in for it.
if (kind !== 'vessel') return null;
const info = this.readVesselInfo();
if (!Number.isFinite(info?.latitude) || !Number.isFinite(info?.longitude))
return null;
@@ -51,19 +53,15 @@ function subjectWorldPosition(kind) {
: Number.isFinite(info.seaSurfaceHeightM)
? info.seaSurfaceHeightM
: 0;
return Cesium.Cartesian3.fromDegrees(info.longitude, info.latitude, heightM);
return fromDegrees(info.longitude, info.latitude, heightM);
}
/** 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
);
if (!world) return null;
return findQuery(this.viewer)?.project(world) ?? null;
}
/**
@@ -83,8 +81,10 @@ export function onScenePointerDown(nowMs = performance.now()) {
return;
}
const at = subjectCanvasPosition.call(this);
const mmsi = this.readVesselInfo()?.mmsi ?? null;
this.doubleClickStart = at ? { x: at.x, y: at.y, atMs: nowMs, mmsi } : null;
const vesselId = this.readVesselInfo()?.id ?? null;
this.doubleClickStart = at
? { x: at.x, y: at.y, atMs: nowMs, vesselId }
: null;
}
/**
@@ -111,41 +111,108 @@ export function onSceneDoubleClick(position, nowMs = performance.now()) {
// The memory is the ship's it was taken for: one followed since (an
// aircraft, another ship) is hit only where it is drawn.
this.resolveEntryKind() === 'vessel' &&
start.mmsi === (this.readVesselInfo()?.mmsi ?? null) &&
start.vesselId === (this.readVesselInfo()?.id ?? null) &&
doubleClickHitsSubject(position, start));
if (!hit) return false;
this.enter();
return true;
}
/** Hold the renderer's own double-click follow off; returns the release. */
const holdStockFollow = (viewer) =>
findInput(viewer)?.behaviours?.dblclickFollow?.suppress?.() ?? null;
/**
* 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, as is one on a mapped ground point in
* orbit (a focus); 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.
* How long a press on the followed track keeps the stock follow off, and
* how soon after a press the next one may end a double-click with it.
*/
const SUBJECT_PRESS_HOLD_MS = 700;
/** How far apart, CSS pixels, two presses of one double-click may land. */
const DOUBLE_CLICK_SLOP_PX = 8;
/**
* Take the scene's double-click on the followed track for the Cockpit. The
* renderer's own double-click follow lets go of whatever is followed when
* the double-click does not land on something it can follow itself: on a
* followed aircraft's model it would drop the very track the double-click
* means to ride. It runs before any subscriber and cannot be refused from
* one, so a press on the followed track holds it off for that press
* (`behaviours.dblclickFollow`, a hold a `down` subscriber takes covers its
* press), and the double-click it ends in enters. A double-click anywhere
* else is the renderer's, as before. The renderer decides a double-click's
* stock follow from its second press, as the hold stood when that press
* went down, so a press that cannot end a double-click on the track (no
* press on the track came just before it, at about the same spot) gives
* its hold back at its release: a second press off the track then finds
* the follow free. In orbit a press on a mapped ground point holds it
* off the same way, and the double-click it ends in is a focus. `this.holdStockFollow`, when set, takes
* the hold in place of the renderer's input port (tests).
* @returns {() => void} Stops listening and lets any hold go.
*/
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;
let input;
try {
input = inputFor(this.viewer);
} catch {
// A viewer with no input to take (headless tools, partial stubs) has no
// double-click to route.
return () => {};
}
let release = null;
let timer = null;
// The last left press (when, where, and whether it was on the track),
// and whether the held press could end a double-click on the track.
let last = null;
let endsDouble = false;
const drop = () => {
globalThis.clearTimeout(timer);
timer = null;
release?.();
release = null;
};
// Ambient `down`/`up` are the unmodified left button's, while the
// pointer is free.
const offDown = input.onPointer('down', ({ position }) => {
drop();
const at = Date.now();
const onSubject =
!this.destroyed &&
isPointerFree() &&
(this.active
? Boolean(this.orbitalSiteUnder?.(position))
: doubleClickHitsSubject(position, subjectCanvasPosition.call(this)));
endsDouble =
!!last?.onSubject &&
at - last.at <= SUBJECT_PRESS_HOLD_MS &&
Math.hypot(position?.x - last.x, position?.y - last.y) <=
DOUBLE_CLICK_SLOP_PX;
last = { at, x: position?.x, y: position?.y, onSubject };
if (!onSubject) return;
release = this.holdStockFollow
? this.holdStockFollow()
: holdStockFollow(this.viewer);
// A press that ends in no double-click gives the follow back by itself.
timer = globalThis.setTimeout(drop, SUBJECT_PRESS_HOLD_MS);
});
const offUp = input.onPointer('up', () => {
if (!endsDouble) drop();
});
const offDouble = input.onPointer('dblclick', ({ position }) => {
// In orbit, a double-click on a mapped ground point is a focus, never a
// retarget that would end the view.
if (this.onOrbitalDoubleClick?.(event?.position)) return;
stock?.(event);
};
handler.setInputAction(routed, type);
if (!this.onSceneDoubleClick(position))
this.onOrbitalDoubleClick?.(position);
// The hold covers the whole double-click: it is given back once the
// dispatch is over.
queueMicrotask(drop);
});
return () => {
if (handler.isDestroyed?.() || handler.getInputAction?.(type) !== routed)
return;
if (stock) handler.setInputAction(stock, type);
else handler.removeInputAction(type);
offDown();
offUp();
offDouble();
drop();
};
}
@@ -187,7 +254,7 @@ const LOOK_KEY_OWNERS = [
* @returns {boolean} True when the key was taken.
*/
function handleLookKey(event) {
if (!this.active || this.subjectKind !== 'vessel') return false;
if (!this.looksAround) return false;
if (event.metaKey || event.ctrlKey || event.altKey) return false;
const step = lookKeyStep(event.key, event.shiftKey);
const reset = !event.repeat && (event.key === 'Home' || event.key === '0');
@@ -243,6 +310,9 @@ export function onKeyDown(event) {
if (event.target?.closest?.('.cesium-credit-lightbox')) return;
// An open Display or Radio popover takes Escape itself.
if (this.isUtilityDisclosureOpen?.()) return;
// So do the Data Layers search field and filter menu.
if (event.target?.closest?.('.layer-finder__field, .layer-finder__menu'))
return;
if (this.context?.contains(event.target) && !this.contextCollapsed) {
event.preventDefault();
event.stopImmediatePropagation();
+17 -2
View File
@@ -52,7 +52,7 @@ function createRimState(value) {
*/
export function createInstrumentState() {
return {
// 'aircraft' or 'vessel': which readouts the HUD labels and shows.
// 'aircraft', 'vessel' or 'subject': which readouts the HUD shows.
kind: 'aircraft',
layer: null,
callsign: t('AIRCRAFT'),
@@ -76,6 +76,19 @@ export function createInstrumentState() {
look: { offset: false, yawDeg: 0, readout: '' },
clock: '--:--:--Z',
position: '--° · --°',
// A provider subject's HUD (kind 'subject', cockpitSubjectProviders.js):
// its kicker, speed unit and tag, readouts, sources, banner, veil and
// progress line, all worded by the provider.
kicker: '',
speedUnit: '',
speedTag: '',
speedTone: 'normal',
readouts: [],
sources: [],
banner: null,
veil: null,
progress: null,
lookEnabled: false,
};
}
@@ -86,8 +99,10 @@ export function createInstrumentState() {
*/
export function createRouteState() {
return {
// A vessel's card shows only the free-text AIS destination.
// A vessel's card shows only the free-text AIS destination; a provider's
// subject's (kind 'subject') carries its own title.
kind: 'aircraft',
title: '',
visible: false,
from: t('UNKNOWN'),
to: t('UNKNOWN'),
+155 -6
View File
@@ -1,5 +1,5 @@
/** Instrument values, routes and vision controls for the Cockpit controller. */
import { formatNumber, t } from '../i18n/index.js';
import { formatNumber, t, tn } from '../i18n/index.js';
import {
COCKPIT_VISION_MODES,
normalizeCockpitVisionMode,
@@ -35,6 +35,7 @@ import {
vesselCameraProfile,
} from '../cockpitSubjects.js';
import { lookIsOffset, lookReadoutParts, wrapLookYaw } from '../cockpitLook.js';
import { cockpitSubjectHudView } from '../cockpitSubjectProviders.js';
import {
RADAR_MAX_CONTACTS,
radarPicture,
@@ -90,6 +91,13 @@ export function publishInstrumentsView() {
compass: view.compass.map((division) => ({ ...division })),
compassMarkers: { ...view.compassMarkers },
look: { ...view.look },
// A provider's view model is rebuilt on each HUD update, never edited
// in place, so it is published as it stands.
readouts: view.readouts,
sources: view.sources,
banner: view.banner,
veil: view.veil,
progress: view.progress,
});
}
@@ -118,24 +126,162 @@ function wordLook({ side, bearingDeg, elevation, angleDeg }) {
*/
export function presentLook() {
const target = this.lookTarget;
// A provider's view words its own readout (its HUD view's `lookReadout`).
const provider = Boolean(this.subjectProvider);
const rest = provider ? this.lookRestPitch : VESSEL_BRIDGE_PITCH_DEG;
const offset =
this.active &&
this.subjectKind === 'vessel' &&
lookIsOffset(target, VESSEL_BRIDGE_PITCH_DEG);
(this.active && this.subjectKind === 'vessel') ||
(provider && this.looksAround)
? lookIsOffset(target, rest)
: false;
this.instruments.look = offset
? {
offset: true,
yawDeg: wrapLookYaw(target.yawDeg),
readout: wordLook(lookReadoutParts(target, VESSEL_BRIDGE_PITCH_DEG)),
readout: provider
? (this.subjectHud?.lookReadout ?? '')
: wordLook(lookReadoutParts(target, VESSEL_BRIDGE_PITCH_DEG)),
}
: { offset: false, yawDeg: 0, readout: '' };
}
/** Live Signals' tone for a provider's signal row. */
const SUBJECT_SIGNAL_TONES = Object.freeze({
warning: 'warning',
alert: 'warning',
});
/**
* Present a provider subject's HUD: its view model (cockpitSubjectHudView)
* in the generic readouts, the compass at the camera's heading, the route
* card, and its signals in Live Signals. A HUD view that is null, a `hud()`
* that throws, or a view whose reading throws keeps the last one. Contact
* navigation stays with aircraft, so the Contact card is withdrawn.
*/
function updateSubjectHud(info, nowMs, forceContext) {
const provider = this.subjectProvider;
this.lastSubjectInfo = info;
const frame = this.lastSubjectFrame;
const look = {
yawDeg: this.lookTarget?.yawDeg ?? 0,
pitchDeg: this.lookTarget?.pitchDeg ?? 0,
offset:
this.looksAround && lookIsOffset(this.lookTarget, this.lookRestPitch),
};
const raw = frame
? this.callSubject(
provider,
'hud',
[frame, Object.freeze({ ...this.subjectContext(), look })],
null,
)
: null;
if (raw != null)
this.subjectHud = cockpitSubjectHudView(raw) ?? this.subjectHud;
const hud = this.subjectHud ?? cockpitSubjectHudView(null);
const view = this.instruments;
view.kind = 'subject';
view.trackSource = null;
view.kicker = hud.kicker || provider.labels.kicker;
view.callsign = hud.title || info.name || '';
// While the floor under a subject with no height is acquired
// (cockpitCamera.js), the meta line says so in place of the provider's.
const acquiring = this.surfaceAcquiring === true;
view.meta.text = acquiring ? t('ACQUIRING SURFACE') : hud.meta.text;
view.meta.tone = acquiring ? 'warning' : hud.meta.tone;
view.meta.emergency = !acquiring && hud.meta.tone === 'alert';
const speed = hud.speed?.value ?? null;
view.speed = hud.speed
? {
text: speed === null ? '---' : formatNumber(Math.round(speed)),
value: speed === null ? null : Math.round(speed),
immediate: forceContext,
}
: null;
view.speedUnit = hud.speed?.unit ?? '';
view.speedTag = hud.speed?.tag ?? '';
view.speedTone = hud.speed?.tone ?? 'normal';
view.speedRim.unavailable = true;
view.altitude = null;
view.altitudeRim.unavailable = true;
view.course = null;
const heading = normalizeHeading(this.heading ?? info.track ?? 0);
view.heading = {
text: formatHeadingReadout(heading),
value: heading,
immediate: forceContext,
};
const viewHeading = normalizeHeading(
heading + (provider.look ? (this.lookView?.yawDeg ?? 0) : 0),
);
view.compass = scrollingCompassDivisions(viewHeading).map((division) => ({
slot: division.slot,
heading: division.heading,
active: division.nearest,
label: compassPointLabel(formatCompassDivision(division.heading)),
}));
view.compassMarkers = {
prograde: compassMarkerSlot(heading, viewHeading),
retrograde: compassMarkerSlot(heading + 180, viewHeading),
};
view.clock = new Date().toISOString().slice(11, 19) + 'Z';
view.position = `${formatCockpitCoordinate(info.latitude, 'N', 'S')} · ${formatCockpitCoordinate(info.longitude, 'E', 'W')}`;
view.readouts = hud.readouts;
view.sources = hud.sources;
view.banner = hud.banner;
view.veil = hud.veil;
view.progress = hud.progress;
view.lookEnabled = Boolean(provider.look);
view.layer = provider.layerId;
this.presentLook();
this.publishInstrumentsView();
const route = this.routeView;
route.kind = 'subject';
route.title = hud.route?.title ?? '';
route.from = hud.route?.from ?? '';
route.to = hud.route?.to ?? '';
route.status = hud.route?.status ?? '';
route.visible = Boolean(hud.route);
// No destination arrow; clearing also publishes the card.
this.clearPredictiveRoute();
if (
forceContext ||
cockpitUiUpdateDue(
nowMs,
this.lastContextUpdateMs,
COCKPIT_CONTEXT_UPDATE_MS,
)
) {
this.lastContextUpdateMs = nowMs;
this.updateLocalPosition(info);
this.maybeRefreshRegionalBrief(info);
this.showContextCard(false);
const keys = new Set();
for (const signal of hud.signals) {
const key = `subject:${signal.id}`;
keys.add(key);
this.pushCockpitSignal(
key,
SUBJECT_SIGNAL_TONES[signal.tone] ?? 'info',
signal.title,
signal.detail || signal.title,
);
}
for (const key of this.subjectSignalKeys ?? [])
if (!keys.has(key)) this.dropCockpitSignal(key);
this.subjectSignalKeys = keys;
}
}
export function updateHud(
info,
nowMs = performance.now(),
forceContext = false,
) {
if (this.subjectProvider && info?.generic === true) {
updateSubjectHud.call(this, info, nowMs, forceContext);
return;
}
if (info?.kind === 'vessel') {
updateVesselHud.call(this, info, nowMs, forceContext);
return;
@@ -379,7 +525,10 @@ export function updateRadar(info) {
);
this.publishRadar({
...picture,
rangeLabel: t('{range} NM', { range: formatNumber(rangeNm) }),
// A plural, as the ring spacing is: ru «3 МОР. МИЛИ», «12 МОР. МИЛЬ».
rangeLabel: tn(rangeNm, '{range} NM', '{range} NM', {
range: formatNumber(rangeNm),
}),
});
}
+1
View File
@@ -99,6 +99,7 @@ export function syncContextLayout() {
let safeBottom = window.innerHeight - 24;
for (const selector of [
'#cesium-credits',
'#gev-credits',
'#command-dock',
'#view-switcher',
]) {
+8 -8
View File
@@ -45,7 +45,7 @@ function fixture(t) {
test('the orbital HUD is hidden until a satellite view is published', async (t) => {
const f = fixture(t);
assert.equal(f.section().hidden, true);
assert.equal(f.section().querySelector('#cockpit-orbital-zoom-in'), null);
assert.equal(f.section().querySelector('#cockpit-orbital-zoom-in') === null, true);
});
test('a published orbital view renders its readouts and zoom controls', async (t) => {
@@ -97,7 +97,7 @@ test('an unknown velocity leaves its row out', async (t) => {
const f = fixture(t);
f.store.publishOrbital({ ...VIEW, velocityMps: null });
await nextTick();
assert.equal(f.section().querySelector('.cockpit-orbital-velocity'), null);
assert.equal(f.section().querySelector('.cockpit-orbital-velocity') === null, true);
assert.equal(f.text('.cockpit-orbital-altitude'), '418 KM');
});
@@ -145,7 +145,7 @@ test('publishing null hides the orbital HUD again', async (t) => {
f.store.publishOrbital(null);
await nextTick();
assert.equal(f.section().hidden, true);
assert.equal(f.section().querySelector('.cockpit-orbital-name'), null);
assert.equal(f.section().querySelector('.cockpit-orbital-name') === null, true);
});
const ISS_TLE = Object.freeze({
@@ -160,7 +160,7 @@ test('the place below shows at the top once known', async (t) => {
const f = fixture(t);
f.store.publishOrbital({ ...VIEW, place: undefined });
await nextTick();
assert.equal(f.section().querySelector('#cockpit-orbital-over'), null);
assert.equal(f.section().querySelector('#cockpit-orbital-over') === null, true);
const over = () =>
f.section().querySelector('#cockpit-orbital-over strong')?.textContent;
f.store.publishOrbital({
@@ -195,7 +195,7 @@ test('the place below shows at the top once known', async (t) => {
// says nothing rather than call land open ocean.
f.store.publishOrbital({ ...VIEW, place: null });
await nextTick();
assert.equal(document.querySelector('#cockpit-orbital-over'), null);
assert.equal(document.querySelector('#cockpit-orbital-over') === null, true);
});
test('an owner country shows its flag from the sheet, or its code if the sheet will not load', async (t) => {
@@ -216,7 +216,7 @@ test('an owner country shows its flag from the sheet, or its code if the sheet w
owner: { countryCode: 'US', label: 'USA' },
});
await nextTick();
assert.equal(f.section().querySelector('.cockpit-orbital-flag'), null);
assert.equal(f.section().querySelector('.cockpit-orbital-flag') === null, true);
assert.equal(images.length, 1, 'the sheet is asked for');
images[0].onerror();
await settle();
@@ -244,7 +244,7 @@ test('an owner country shows its flag from the sheet, or its code if the sheet w
flag.style.backgroundPosition,
ownerFlagStyle('FR').backgroundPosition,
);
assert.equal(f.section().querySelector('.cockpit-orbital-owner-badge'), null);
assert.equal(f.section().querySelector('.cockpit-orbital-owner-badge') === null, true);
});
test('the readout names the owner, operator and element set', async (t) => {
@@ -327,7 +327,7 @@ test('unknown identity fields leave their rows out', async (t) => {
'.cockpit-orbital-ident',
'#cockpit-orbital-tle',
])
assert.equal(f.section().querySelector(selector), null, selector);
assert.equal(f.section().querySelector(selector) === null, true, selector);
// An element set with no NORAD id still dates itself.
f.store.publishOrbital({ ...VIEW, tle: ISS_TLE });
await nextTick();
+34 -25
View File
@@ -8,7 +8,9 @@
* (src/ui/cockpitOrbitalView.js); its state lives on the orbital session, so
* it ends with the session.
*/
import * as Cesium from 'cesium';
import { fromDegrees } from '../geo/ellipsoid.js';
import { inputFor } from '../input/dispatcher.js';
import { findQuery } from '../render/rendererOf.js';
import { clampOrbitalLook, easeLook } from '../cockpitLook.js';
import { ORBITAL_EARTH_RADIUS_M } from '../cockpitOrbital.js';
import {
@@ -113,11 +115,11 @@ function sitePosition(site) {
: null;
}
/** The mapped site a canvas position shows, through the layer's pick ids. */
/** The mapped site a canvas position shows, through the layer's picks. */
function siteAt(controller, position) {
let picked = null;
try {
picked = controller.viewer.scene?.pick?.(position) ?? null;
picked = findQuery(controller.viewer)?.pick(position.x, position.y) ?? null;
} catch {
picked = null;
}
@@ -215,10 +217,25 @@ export function toggleOrbitalFocus(key) {
return site ? startFocus.call(this, site) : false;
}
/**
* Whether a press at `position` lands on a mapped ground point in orbit:
* the double-click it may begin is a focus, so the renderer's own
* double-click follow is held off for it.
* @param {{x: number, y: number}|null|undefined} position Canvas position.
* @returns {boolean}
*/
export function orbitalSiteUnder(position) {
if (!inOrbit(this) || !isPointerFree()) return false;
if (!Number.isFinite(position?.x) || !Number.isFinite(position?.y))
return false;
return Boolean(siteAt(this, position));
}
/**
* A double-click on the orbital picture. On a mapped ground point it keeps
* or starts the focus on it (as a single click does) and is taken: Cesium's
* own double-click would track that point, which ends the view. Any other
* or starts the focus on it (as a single click does) and is taken: the
* renderer's own double-click would follow that point, which ends the view
* (its press held that follow off, `orbitalSiteUnder`). Any other
* double-click, one a tool owns, and every one outside orbit go on.
* @param {{x: number, y: number}|null|undefined} position Canvas position.
* @returns {boolean} True when it landed on a ground point and was taken.
@@ -257,27 +274,19 @@ export function onOrbitalClick(position) {
}
/**
* Take the scene's single click through the orbital focus first, then hand
* it on to Cesium's own (it picks into `selectedEntity`), as before.
* @returns {() => void} Puts Cesium's handler back, unless another owner
* (the draw tool borrows it) has replaced ours since.
* Take the scene's single click through the orbital focus, alongside the
* other click subscribers and the renderer's own select, as before.
* @returns {() => void} Stops listening.
*/
export function routeSceneClick() {
const handler = this.viewer.screenSpaceEventHandler;
if (typeof handler?.setInputAction !== 'function') return () => {};
const type = Cesium.ScreenSpaceEventType.LEFT_CLICK;
const stock = handler.getInputAction?.(type) ?? null;
const routed = (event) => {
this.onOrbitalClick(event?.position);
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);
};
let input;
try {
input = inputFor(this.viewer);
} catch {
// A viewer with no input (headless tools, partial stubs) has no clicks.
return () => {};
}
return input.onClick((event) => this.onOrbitalClick(event?.position));
}
/**
@@ -408,7 +417,7 @@ export function orbitalSitesInReach(info) {
let sites = [];
try {
sites = layer.getNearby(
Cesium.Cartesian3.fromDegrees(info.longitude, info.latitude, 0),
fromDegrees(info.longitude, info.latitude, 0),
rangeM,
SITE_QUERY_MAX,
);
+94 -43
View File
@@ -12,7 +12,19 @@ import assert from 'node:assert/strict';
import { createPinia } from 'pinia';
import { createApp, defineComponent, h, nextTick } from 'vue';
import * as Cesium from 'cesium';
import {
bindFakeCesiumCamera,
followEntity,
} from '../testSupport/fakeCameraPort.mjs';
import { followedOf } from '../data/followed.js';
import { fakeScenePorts } from '../testSupport/fakeCesiumScene.mjs';
import {
FAKE_EVENT_TYPES,
FakeScreenSpaceEventHandler,
fakeInput,
} from '../input/testDoubles.mjs';
import { CockpitViewController } from './cockpitController.js';
import { setLocale, t as translate } from '../i18n/index.js';
import { useCockpitStore } from './stores/cockpit.js';
import { useHudStore } from './stores/hud.js';
import CockpitView from './views/CockpitView.vue';
@@ -117,10 +129,9 @@ function installationsLayer() {
const record = layer.records.find((r) => r.id === String(id));
return record ? layer.withPosition(record) : null;
},
findByPick(picked) {
const id =
picked?.id?.installationId ||
(typeof picked?.id?.id === 'string' ? picked.id.id : null);
// A query hit on a named marker carries its installation id.
findByPick(hit) {
const id = hit?.meta?.installationId ?? null;
return id ? layer.getById(id) : null;
},
};
@@ -204,7 +215,7 @@ function satellitesLayer(viewer) {
if (!positions.has(id)) return false;
layer.calls.push(['track', id]);
layer.tracked = id;
viewer.trackedEntity = { position: { getValue: () => layer.position(id) } };
followEntity(viewer, { position: { getValue: () => layer.position(id) } });
return true;
},
setCockpitSubject(noradId) {
@@ -237,7 +248,6 @@ function fixture(t, { reducedMotion = false } = {}) {
const shots = [];
const picks = new Map();
const viewer = {
trackedEntity: undefined,
clock: { currentTime: null },
camera: {
frustum: { fov: 1, aspectRatio: ASPECT },
@@ -254,41 +264,46 @@ function fixture(t, { reducedMotion = false } = {}) {
scene: {
preUpdate: listeners(),
screenSpaceCameraController: { enableInputs: true },
pick: (position) => picks.get(`${position.x},${position.y}`),
},
trackedEntityChanged: listeners(),
};
// The Viewer's own input handler: its single click picks into
// selectedEntity; its double-click tracks what it picks, which would end
// the orbital view.
const actions = new Map();
// The renderer's own click and double-click: its click picks into its
// selection; its double-click follows what it picks, which would end the
// orbital view. Counted when the scene's input lets them run.
const handler = {
stockClicks: 0,
stockDoubleClicks: 0,
getInputAction: (type) => actions.get(type),
setInputAction: (action, type) => actions.set(type, action),
removeInputAction: (type) => actions.delete(type),
isDestroyed: () => false,
};
handler.stock = () => {
handler.stockClicks += 1;
};
handler.stockDouble = ({ position }) => {
handler.stockDoubleClicks += 1;
const picked = viewer.scene.pick(position);
viewer.trackedEntity = picked
? { position: { getValue: () => null } }
: undefined;
const picked = picks.get(`${position.x},${position.y}`);
followEntity(viewer, picked ? { position: { getValue: () => null } } : null);
};
actions.set(Cesium.ScreenSpaceEventType.LEFT_CLICK, handler.stock);
actions.set(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK, handler.stockDouble);
viewer.screenSpaceEventHandler = handler;
// The viewer's stock handler holds them, so the scene's input has them to
// hold off.
const stock = new FakeScreenSpaceEventHandler();
stock.setInputAction(() => {}, FAKE_EVENT_TYPES.LEFT_CLICK);
stock.setInputAction(handler.stockDouble, FAKE_EVENT_TYPES.LEFT_DOUBLE_CLICK);
viewer.screenSpaceEventHandler = stock;
const sites = installationsLayer();
const satellites = satellitesLayer(viewer);
const modeEvents = [];
const onMode = (event) => modeEvents.push(event.detail);
window.addEventListener('gev:cockpit-mode-changed', onMode);
// The Cockpit drives the camera, reads frames and picks through ports: the
// Cesium camera port over the fake camera, and a pick that answers from
// the named markers the test draws.
const ports = fakeScenePorts(viewer);
bindFakeCesiumCamera(viewer, {
...ports,
query: {
...ports.query,
pick: (x, y) =>
picks.get(`${x},${y}`) ?? { set: '', id: '', surface: true },
},
});
const input = fakeInput(viewer);
const cockpit = new CockpitViewController(viewer, {
services: {
flightsLayer: { getTrackedInfo: () => null },
@@ -317,6 +332,15 @@ function fixture(t, { reducedMotion = false } = {}) {
signals: (rows) => store.publishSignals(rows),
},
});
let stockHolds = 0;
cockpit.holdStockFollow = () => {
stockHolds += 1;
let held = true;
return () => {
if (held) stockHolds -= 1;
held = false;
};
};
Object.assign(cockpit, {
setVisionMode() {},
showBriefPage() {},
@@ -328,11 +352,13 @@ function fixture(t, { reducedMotion = false } = {}) {
updateContext() {},
updateRoute() {},
});
// Named markers pick as `{ installationId }`, as the layer draws them.
// Named markers pick as items carrying `{ installationId }`, as the layer
// draws them.
for (const site of Object.values(SITES))
picks.set(`${site.at.x},${site.at.y}`, {
id: { installationId: site.id },
primitive: {},
set: 'installations:named',
id: site.id,
meta: { installationId: site.id },
});
const originalNow = performance.now;
@@ -344,6 +370,7 @@ function fixture(t, { reducedMotion = false } = {}) {
t.after(() => {
window.removeEventListener('gev:cockpit-mode-changed', onMode);
cockpit.stop();
input.destroy();
app.unmount();
globalThis.matchMedia = previousMatchMedia;
performance.now = originalNow;
@@ -356,7 +383,11 @@ function fixture(t, { reducedMotion = false } = {}) {
cockpit.update();
return shots.at(-1);
};
const fire = (type, position) => actions.get(type)?.({ position });
/** A click, with the renderer's own click when the input lets it run. */
const click = (position) => {
if (input.stockEnabled('select')) handler.stockClicks += 1;
input.tap(position);
};
return {
$: (selector) => document.querySelector(selector),
cockpit,
@@ -368,12 +399,20 @@ function fixture(t, { reducedMotion = false } = {}) {
satellites,
modeEvents,
frame,
click: (position) => fire(Cesium.ScreenSpaceEventType.LEFT_CLICK, position),
/** A double-click as Cesium fires it: two clicks, then the double. */
input,
click,
/**
* A double-click as the scene's input sees it: a click, a second press
* and the double. The renderer's own follow runs unless the second
* press held it off.
*/
doubleClick(position) {
fire(Cesium.ScreenSpaceEventType.LEFT_CLICK, position);
fire(Cesium.ScreenSpaceEventType.LEFT_CLICK, position);
fire(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK, position);
click(position);
input.down(position);
input.up(position);
if (stockHolds === 0 && input.stockEnabled('dblclickFollow'))
handler.stockDouble({ position });
input.dblclick(position);
},
/** Rebuild the Context card on the next frame, past its clock. */
refreshCard() {
@@ -534,6 +573,18 @@ test('a site row turns the camera onto it, holds it, and reads its off-nadir ang
assert.match(held.className, /^track actionable$/);
assert.match(held.detail, /^FOCUS · BASE · OFF-NADIR/);
assert.equal(siteRow(scene, 'alpha').getAttribute('aria-label'), 'Release the camera from Camp Alpha');
// The held site's FOCUS is a status, worded apart from the FOCUS command.
t.after(() => setLocale('en'));
setLocale('es');
await refreshRows(scene);
const heldEs = rows(scene).find((row) => row.target?.id === SITES.alpha.id);
assert.match(heldEs.detail, /^ENFOQUE · /);
assert.match(
$('#cockpit-orbital-focus').textContent,
/^ENFOQUE · /,
'the card names the held site with the same word',
);
assert.equal(translate('FOCUS'), 'ENFOCAR', 'the command keeps its verb');
});
test('another site row switches the focus; the held site row ends it', async (t) => {
@@ -602,7 +653,7 @@ test('a double-click on a site focuses it and keeps the orbital view', async (t)
const { cockpit, viewer, handler } = scene;
scene.doubleClick(SITES.alpha.at);
assert.equal(handler.stockDoubleClicks, 0, 'Cesium does not track the site');
assert.equal(viewer.trackedEntity, undefined);
assert.equal(followedOf(viewer), null);
scene.frame();
assert.equal(cockpit.active, true, 'still in orbit');
assert.equal(cockpit.orbital.focus.key, SITES.alpha.id);
@@ -688,7 +739,7 @@ test('a satellite row rides it, staying in orbit; RETURN goes back', async (t) =
assert.equal(newTrack.length, 1);
assert.ok(newTrack[0].timestamp > firstTrack.timestamp, 'the new ride’s own time');
assert.deepEqual(satellites.calls.slice(-2), [['track', 49260], ['subject', 49260]]);
assert.equal(viewer.trackedEntity, undefined, 'the Cockpit keeps the camera');
assert.equal(followedOf(viewer), null, 'the Cockpit keeps the camera');
assert.equal(cockpit.subjectId, 49260);
assert.equal(cockpit.orbital.focus, null, 'the focus is reset');
assert.equal(modeEvents.at(-1)?.active, true);
@@ -878,14 +929,14 @@ test('reduced motion cuts onto the site, back, and between satellites', async (t
assert.ok(Cesium.Cartesian3.distance(shot.destination, scene.satellites.position(49260)) < 1);
});
test('stopping the Cockpit hands both clicks back to Cesium', async (t) => {
const scene = fixture(t);
const click = Cesium.ScreenSpaceEventType.LEFT_CLICK;
const double = Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK;
assert.notEqual(scene.handler.getInputAction(click), scene.handler.stock);
test('stopping the Cockpit leaves both clicks to the renderer', async (t) => {
const scene = await inOrbit(t);
scene.cockpit.stop();
assert.equal(scene.handler.getInputAction(click), scene.handler.stock);
assert.equal(scene.handler.getInputAction(double), scene.handler.stockDouble);
scene.doubleClick(SITES.alpha.at);
assert.equal(scene.handler.stockClicks, 1, 'its own click runs');
assert.equal(scene.handler.stockDoubleClicks, 1, 'and its own follow');
assert.equal(scene.input.stockEnabled('select'), true);
assert.equal(scene.input.stockEnabled('dblclickFollow'), true);
});
test('the focused site keeps its row after nearer sites push it down', async (t) => {
+7 -7
View File
@@ -7,7 +7,7 @@
* focus ends, and the camera hops along the great circle to the new
* satellite. Bound to the Cockpit controller like the orbital view itself.
*/
import * as Cesium from 'cesium';
import { stopFollowing } from '../data/followed.js';
import { t } from '../i18n/index.js';
import { zoomTransitionProgress } from '../cockpitOrbital.js';
import {
@@ -122,8 +122,8 @@ export function switchOrbitalSatellite(noradId) {
} catch {
tracked = false;
}
// Tracking hands the camera to Cesium's follow; the orbital view keeps it.
this.viewer.trackedEntity = undefined;
// Tracking hands the camera to the follow; the orbital view keeps it.
stopFollowing(this.viewer);
const info = tracked ? this.readSatelliteInfo() : null;
if (!info || String(info.noradId) !== String(noradId)) {
// Nothing changed hands, or the layer could not take it: the view ends
@@ -149,7 +149,6 @@ export function switchOrbitalSatellite(noradId) {
state.verticalFov = null;
state.place = undefined;
state.placeTracker?.reset?.();
state.prefetched?.clear?.();
this.lastHudUpdateMs = 0;
this.lastContextUpdateMs = 0;
this.dispatchCockpitModeChanged(true, info);
@@ -171,9 +170,10 @@ export function switchOrbitalSatellite(noradId) {
* Where the camera is this frame: on the satellite, or part-way along a hop
* to it, eased like a zoom step. The hop ends when it lands.
* @param {object} state The orbital session.
* @param {Cesium.Cartesian3} position The ridden satellite this frame.
* @param {{x: number, y: number, z: number}} position The ridden
* satellite this frame (ECEF).
* @param {number} nowMs
* @returns {Cesium.Cartesian3}
* @returns {{x: number, y: number, z: number}}
*/
export function orbitalEyePosition(state, position, nowMs) {
const hop = state.hop;
@@ -190,5 +190,5 @@ export function orbitalEyePosition(state, position, nowMs) {
state.hop = null;
return position;
}
return new Cesium.Cartesian3(eye.x, eye.y, eye.z);
return { x: eye.x, y: eye.y, z: eye.z };
}
+2 -1
View File
@@ -132,7 +132,8 @@ function siteRows(info, { settled = true } = {}) {
}),
});
const words = [installationClassLabel(site.class), angle];
if (focused) words.unshift(t('FOCUS'));
// A status, as on the focus card, not the command: es «ENFOQUE», not «ENFOCAR».
if (focused) words.unshift(t('FOCUS', { context: 'site status' }));
return {
key: `site:${site.id}`,
// The held site reads as the subject does.
+25 -222
View File
@@ -1,20 +1,14 @@
/** The orbital (satellite) view of the Cockpit controller: camera, zoom, look and HUD. */
import * as Cesium from 'cesium';
import { isFollowing } from '../data/followed.js';
import { cameraOf, canvasOf, findGlobe } from '../render/rendererOf.js';
import { formatNumber, msg, t } from '../i18n/index.js';
import {
ORBITAL_DEFAULT_ZOOM,
ORBITAL_PREFETCH_INTERVAL_MS,
centreLinesFirst,
ORBITAL_PREFETCH_MAX_TILES,
ORBITAL_PREFETCH_MIN_ZOOM,
ORBITAL_SETTLE_BLUR_PX,
ORBITAL_ZOOM_LADDER,
ORBITAL_ZOOM_TRANSITION_MS,
cesiumFrustumFovRad,
footprintWidthKm,
fovForZoom,
groundTrackAhead,
imageryLevelForView,
interpolateZoomFov,
nadirOrientation,
nextOrbitalZoom,
@@ -27,7 +21,6 @@ import {
previousOrbitalZoom,
sensorStripFraction,
sensorSwathZoom,
tilesForPoints,
wheelZoomStep,
zoomSettleHolding,
zoomTransitionState,
@@ -79,27 +72,18 @@ const IDLE_TRANSITION = Object.freeze({
const NADIR_LOOK = Object.freeze({ yawDeg: 0, pitchDeg: 0 });
/**
* Start an orbital session's state. Keeps the camera's own field of view so
* the exit can put it back exactly.
* Start an orbital session's state. The exit gives the field of view back
* to the renderer, as it was before the session.
*/
export function beginOrbital() {
const frustum = this.viewer.camera?.frustum;
const state = {
imagery: acquireOrbitImagery(this.services),
zoom: ORBITAL_DEFAULT_ZOOM,
// Wheel scrolling summed toward the next zoom step (wheelZoomStep).
wheel: null,
// Imagery pre-loaded ahead of the ground track from 16x: when it last
// looked ahead, and the tiles already asked for (oldest first).
prefetchMs: -Infinity,
prefetched: new Set(),
// The provider those tiles came from, and the requests still in flight.
prefetchProvider: null,
prefetchRequests: new Set(),
// A zoom step in flight: the magnification it started from and when.
transition: null,
previousUp: null,
savedFov: Number.isFinite(frustum?.fov) ? frustum.fov : null,
altitudeM: null,
verticalFov: null,
lastBriefMs: 0,
@@ -129,11 +113,8 @@ export function endOrbital() {
if (!state) return;
this.orbital = null;
state.placeTracker?.reset();
// Pre-loads still queued or in flight are for a view no longer shown.
for (const request of state.prefetchRequests) request.cancel?.();
state.prefetchRequests.clear();
const frustum = this.viewer.camera?.frustum;
if (frustum && state.savedFov !== null) frustum.fov = state.savedFov;
// The renderer's own field of view again, following the view's shape.
cameraOf(this.viewer).setFov(null);
// Back to the map the operator had, unless they picked another meanwhile.
state.imagery?.release?.()?.catch?.(() => {});
this.publishOrbital(null);
@@ -150,10 +131,7 @@ function trackPlace(info, nowMs) {
if (!state?.placeTracker) return;
let nearKm = null;
if (Number.isFinite(info.altitudeM)) {
const frustum = this.viewer.camera?.frustum;
const aspect = Number.isFinite(frustum?.aspectRatio)
? frustum.aspectRatio
: canvasAspect(this.viewer);
const aspect = viewAspect(this.viewer);
const fov = fovForZoom(orbitalBaseFovRad(info.altitudeM), state.zoom);
// The field of view is vertical: aspect 1 gives the ground height.
nearKm = nearPlaceRadiusKm(
@@ -246,13 +224,7 @@ function applyFov(state, altitudeM, nowMs) {
reading.transition = IDLE_TRANSITION;
}
state.verticalFov = reading.fov;
const frustum = this.viewer.camera?.frustum;
if (frustum && 'fov' in frustum) {
const aspect = Number.isFinite(frustum.aspectRatio)
? frustum.aspectRatio
: canvasAspect(this.viewer);
frustum.fov = cesiumFrustumFovRad(reading.fov, aspect);
}
cameraOf(this.viewer).setFov({ vertical: reading.fov });
return reading;
}
@@ -261,25 +233,18 @@ function applyFov(state, altitudeM, nowMs) {
* globe; with the globe hidden (Google 3D kept) there is nothing to wait for.
*/
function tilesLoaded(viewer) {
const globe = viewer.scene?.globe;
return !globe?.show || globe.tilesLoaded !== false;
const globe = findGlobe(viewer);
if (!globe || globe.isGlobeVisible?.() === false) return true;
return globe.isSettled('imagery') !== false;
}
function canvasAspect(viewer) {
const canvas = viewer.scene?.canvas;
const canvas = canvasOf(viewer);
const width = canvas?.clientWidth;
const height = canvas?.clientHeight;
return width > 0 && height > 0 ? width / height : 1;
}
/** Copy a plain vector into a Cesium scratch. */
function intoCartesian(vector, result) {
result.x = vector.x;
result.y = vector.y;
result.z = vector.z;
return result;
}
/**
* Drive the orbital camera for one rendered frame: at the satellite's own
* per-frame position, looking at the Earth's centre with the ground track at
@@ -290,8 +255,8 @@ function intoCartesian(vector, result) {
*/
export function updateOrbital(nowMs) {
// Tracking anything from orbit (an aircraft, another satellite) ends the
// view and leaves Cesium tracking with that target.
if (this.viewer.trackedEntity?.position) {
// view and leaves the camera following that target.
if (isFollowing(this.viewer)) {
this.exit({ restoreTracking: false });
return;
}
@@ -340,11 +305,15 @@ export function updateOrbital(nowMs) {
});
const zoomStepping = Boolean(state.transition);
const reading = applyFov.call(this, state, info.altitudeM, nowMs);
this.viewer.camera.setView({
destination: eye,
cameraOf(this.viewer).setView({
destination: { x: eye.x, y: eye.y, z: eye.z },
orientation: {
direction: intoCartesian(view.direction, this.scratchForward),
up: intoCartesian(view.up, this.scratchUp),
direction: {
x: view.direction.x,
y: view.direction.y,
z: view.direction.z,
},
up: { x: view.up.x, y: view.up.y, z: view.up.z },
},
});
this.lastSubjectInfo = info;
@@ -366,169 +335,6 @@ export function updateOrbital(nowMs) {
this.lastContextUpdateMs = nowMs;
updateOrbitalContext.call(this, info, nowMs);
}
prefetchImageryAhead.call(this, info, nowMs);
}
/** Tiles remembered as asked for in one orbital session. */
const PREFETCH_MEMORY = 512;
/** How far the shown time may be from now for the look-ahead to run, ms. */
const PREFETCH_LIVE_TOLERANCE_MS = 60_000;
/**
* From 16x the view is 10 to 40 km wide while the ground track moves about
* 7 km/s, so the imagery under it arrives late. Every
* ORBITAL_PREFETCH_INTERVAL_MS ask the globe's base imagery for the tiles
* the view will need 5 to 20 s ahead (`groundTrackAhead`), at the level
* Cesium will draw there (`imageryLevelForView`), so the browser has them
* cached when the view gets there. The requests are throttled at the
* lowest priority: Cesium's request scheduler declines one while the
* imagery server's slots are taken by the tiles on screen or the scheduler
* is full, and a declined tile is asked again on a later look-ahead. At most
* ORBITAL_PREFETCH_MAX_TILES a time; the last PREFETCH_MEMORY tiles asked
* for are not asked again unless their request failed, and a new base map
* starts the memory over. Exit cancels the requests still pending. Nothing
* below 16x, while the view is tilted off nadir (it no longer looks at the
* track), with the world clock away from now (paused, played back), after
* the exit, or with the globe hidden (Google 3D tiles drawn instead).
* @returns {number} The tiles asked for.
*/
export function prefetchImageryAhead(info, nowMs) {
const state = this.orbital;
if (!state || !(state.zoom >= ORBITAL_PREFETCH_MIN_ZOOM)) return 0;
// Tilted, the view looks off the track the pre-load follows.
if (lookIsOffset(state.lookTarget, 0) || lookIsOffset(state.lookView, 0))
return 0;
if (nowMs - state.prefetchMs < ORBITAL_PREFETCH_INTERVAL_MS) return 0;
// The look-ahead runs at live speed: with the world clock paused, played
// back or moved, the view will not pass where it points.
if (
Number.isFinite(info.atMs) &&
Math.abs(info.atMs - Date.now()) > PREFETCH_LIVE_TOLERANCE_MS
)
return 0;
state.prefetchMs = nowMs;
try {
const globe = this.viewer.scene?.globe;
if (!globe || globe.show === false) return 0;
const provider = baseImageryProvider(this.viewer);
if (!provider) return 0;
// Another base map: its tiles have not been asked for.
// A fresh set, so a late failure from the old map's requests cannot
// drop a tile the new one has fetched.
if (provider !== state.prefetchProvider) {
for (const request of state.prefetchRequests) request.cancel?.();
state.prefetchRequests = new Set();
state.prefetched = new Set();
state.prefetchProvider = provider;
}
const fov = fovForZoom(orbitalBaseFovRad(info.altitudeM), state.zoom);
const viewKm = footprintWidthKm(
info.altitudeM,
fov,
viewAspect(this.viewer),
);
// The ground one CSS pixel covers at the nadir point, as Cesium's
// screen-space error measures it: the vertical field of view over the
// canvas height, at the satellite's altitude.
const canvas = this.viewer.scene?.canvas;
const heightPx = canvas?.clientHeight || canvas?.height;
const terrain =
this.viewer.terrainProvider ?? this.viewer.scene?.globe?.terrainProvider;
const level = imageryLevelForView(provider.tilingScheme, {
metresPerPixel: (info.altitudeM * 2 * Math.tan(fov / 2)) / heightPx,
latitudeDeg: info.latitude,
geographic:
provider.tilingScheme.projection instanceof Cesium.GeographicProjection,
tileWidthPx: provider.tileWidth,
minimumLevel: provider.minimumLevel,
maximumLevel: provider.maximumLevel,
maximumScreenSpaceError: globe.maximumScreenSpaceError,
terrainLevelErrorM:
typeof terrain?.getLevelMaximumGeometricError === 'function'
? (terrainLevel) =>
terrain.getLevelMaximumGeometricError(terrainLevel)
: undefined,
});
if (level === null) return 0;
const memory = state.prefetched;
const tiles = tilesForPoints(
provider.tilingScheme,
centreLinesFirst(groundTrackAhead(info, viewKm)),
level,
{
maxTiles: ORBITAL_PREFETCH_MAX_TILES,
skip: (key) => memory.has(key),
},
);
let asked = 0;
for (const tile of tiles) {
let pending;
let request;
try {
// The tiles on screen keep their slots: Cesium's scheduler declines
// this request while the imagery server's slots are taken (shared
// with the globe's own tile requests, throttleByServer) or the
// scheduler is full, and at the lowest priority it is the first
// dropped from the priority heap, never one the screen asked for.
pending = provider.requestImage(
tile.x,
tile.y,
tile.level,
(request = new Cesium.Request({
throttle: true,
throttleByServer: true,
priority: Number.MAX_VALUE,
type: Cesium.RequestType.IMAGERY,
})),
);
} catch {
continue;
}
// A provider that declines now (throttled) is asked again later.
if (!pending) continue;
const requests = state.prefetchRequests;
requests.add(request);
Promise.resolve(pending).then(
() => requests.delete(request),
(error) => {
requests.delete(request);
// Dropped by the scheduler (rejected with no error): asked again
// later. A tile that failed to load stays remembered, so one
// missing from the map is not asked for every look-ahead.
if (error === undefined) memory.delete(tile.key);
},
);
memory.add(tile.key);
if (memory.size > PREFETCH_MEMORY)
memory.delete(memory.values().next().value);
asked += 1;
}
return asked;
} catch {
return 0;
}
}
/**
* The provider of the lowest shown imagery layer, the base map the globe
* drapes, when it can be asked for a tile; else null.
*/
function baseImageryProvider(viewer) {
const layers = viewer.imageryLayers ?? viewer.scene?.imageryLayers;
const count = Number.isInteger(layers?.length) ? layers.length : 0;
for (let i = 0; i < count; i += 1) {
const layer = layers.get(i);
if (!layer || layer.show === false || layer.alpha === 0) continue;
const provider = layer.imageryProvider;
if (
typeof provider?.requestImage === 'function' &&
typeof provider.tilingScheme?.positionToTileXY === 'function'
)
return provider;
return null;
}
return null;
}
/**
@@ -626,9 +432,7 @@ export function publishOrbitalView(info, transition = IDLE_TRANSITION) {
if (!state || !info) return;
const focus = orbitalFocusReadout.call(this);
const offset = Boolean(focus) || lookIsOffset(state.lookTarget, 0);
const aspect = Number.isFinite(this.viewer.camera?.frustum?.aspectRatio)
? this.viewer.camera.frustum.aspectRatio
: canvasAspect(this.viewer);
const aspect = viewAspect(this.viewer);
const settledFov = fovForZoom(orbitalBaseFovRad(info.altitudeM), state.zoom);
const footprintKm = footprintWidthKm(info.altitudeM, settledFov, aspect);
// The strip is drawn over the picture, so it follows the view as a step
@@ -848,9 +652,8 @@ function orbitalMaxZoomFor(info) {
}
function viewAspect(viewer) {
return Number.isFinite(viewer.camera?.frustum?.aspectRatio)
? viewer.camera.frustum.aspectRatio
: canvasAspect(viewer);
const aspect = cameraOf(viewer).pose().aspectRatio;
return Number.isFinite(aspect) && aspect > 0 ? aspect : canvasAspect(viewer);
}
/**
+86 -241
View File
@@ -15,8 +15,6 @@ import CockpitView from './views/CockpitView.vue';
import ContextView from './views/ContextView.vue';
import IntelHudView from './views/IntelHudView.vue';
import {
ORBITAL_PREFETCH_INTERVAL_MS,
ORBITAL_PREFETCH_MAX_TILES,
ORBITAL_SETTLE_BLUR_PX,
ORBITAL_SETTLE_MAX_MS,
ORBITAL_ZOOM_TRANSITION_MS,
@@ -25,8 +23,15 @@ import {
orbitalBaseFovRad,
} from '../cockpitOrbital.js';
import { vesselCockpitInfo } from '../layers/vessels/cockpitSubject.js';
import { prefetchImageryAhead } from './cockpitOrbitalView.js';
import { claimPointer, releasePointer } from '../data/inputOwnership.js';
import {
bindFakeCesiumCamera,
followEntity,
followedEntity,
} from '../testSupport/fakeCameraPort.mjs';
import { followedOf } from '../data/followed.js';
import { fakeScenePorts } from '../testSupport/fakeCesiumScene.mjs';
import { fakeInput } from '../input/testDoubles.mjs';
const ISS = Object.freeze({
kind: 'satellite',
@@ -97,7 +102,7 @@ function stockEventHandler(viewer) {
};
actions.set(DOUBLE_CLICK, () => {
handler.stockCalls += 1;
viewer.trackedEntity = undefined;
followEntity(viewer, null);
});
return handler;
}
@@ -141,10 +146,18 @@ function fixture(
gevTrackedId: aircraftInfo ? `flights:${aircraftInfo.icao24}` : '',
};
const viewer = {
trackedEntity: undefined,
clock: { currentTime: null },
camera: {
frustum: { fov: SAVED_FOV, aspectRatio: ASPECT },
// Cesium's frustum: `fov` the wider angle, `fovy` the vertical one.
frustum: {
fov: SAVED_FOV,
aspectRatio: ASPECT,
get fovy() {
return this.aspectRatio > 1
? 2 * Math.atan(Math.tan(this.fov / 2) / this.aspectRatio)
: this.fov;
},
},
cancelFlight() {},
setView({ destination, orientation }) {
shots.push({
@@ -164,6 +177,26 @@ function fixture(
// Cesium's Viewer installs a double-click that untracks on any pick that
// is not an Entity; the Cockpit routes it.
viewer.screenSpaceEventHandler = stockEventHandler(viewer);
// The Cockpit drives the camera, reads frames and the globe through ports:
// the Cesium camera port over the fake camera, and a globe whose imagery
// has loaded unless the test's `scene.globe` says otherwise.
const ports = fakeScenePorts(viewer);
bindFakeCesiumCamera(viewer, {
...ports,
// Where the test's scene says a position is drawn.
query: {
...ports.query,
project: (position) =>
viewer.scene.cartesianToCanvasCoordinates?.(position, {}) ?? null,
},
globe: {
isGlobeVisible: () => viewer.scene.globe?.show !== false,
isSettled: () => viewer.scene.globe?.tilesLoaded !== false,
},
});
// The scene's input; the renderer's own double-click follow runs unless
// something holds it off, as `stockEventHandler` counts it.
const input = fakeInput(viewer);
const satellites = satelliteLayer(satellite);
const cockpit = new CockpitViewController(viewer, {
services: {
@@ -213,12 +246,22 @@ function fixture(
updateContext() {},
updateRoute() {},
});
let stockHolds = 0;
cockpit.holdStockFollow = () => {
stockHolds += 1;
let held = true;
return () => {
if (held) stockHolds -= 1;
held = false;
};
};
const events = [];
const onMode = (event) => events.push(event.detail);
window.addEventListener('gev:cockpit-mode-changed', onMode);
t.after(() => {
window.removeEventListener('gev:cockpit-mode-changed', onMode);
cockpit.stop();
input.destroy();
app.unmount();
globalThis.matchMedia = previousMatchMedia;
document.body.classList.remove(
@@ -232,6 +275,8 @@ function fixture(
$,
cockpit,
viewer,
input,
stockHeld: () => stockHolds > 0,
satellites,
store,
shots,
@@ -368,7 +413,7 @@ test('entering takes the camera and shows only the orbital HUD', async (t) => {
assert.equal(cockpit.subjectKind, 'satellite');
assert.equal(cockpit.subjectId, ISS.noradId);
assert.deepEqual(satellites.calls, [['subject', ISS.noradId]]);
assert.equal(viewer.trackedEntity, undefined);
assert.equal(followedOf(viewer), null);
assert.equal(viewer.scene.screenSpaceCameraController.enableInputs, false);
assert.ok(document.body.classList.contains('cockpit-mode'));
assert.ok(document.body.classList.contains('cockpit-orbit'));
@@ -718,11 +763,11 @@ test('losing the satellite ends the view without refocusing it', async (t) => {
test('tracking an aircraft from orbit ends the view and keeps that tracking', async (t) => {
const { cockpit, viewer, satellites, aircraft, clock } = await orbitAt(t);
viewer.trackedEntity = aircraft;
followEntity(viewer, aircraft);
clock.advance(16);
cockpit.update();
assert.equal(cockpit.active, false);
assert.equal(viewer.trackedEntity, aircraft);
assert.equal(followedEntity(viewer), aircraft);
assert.ok(!satellites.calls.some(([call]) => call === 'refocus'));
});
@@ -744,7 +789,7 @@ test('+ and − mean nothing new in an aircraft cockpit or on a bridge', async (
onGround: false,
};
const air = fixture(t, { satellite: null, aircraftInfo });
air.viewer.trackedEntity = air.aircraft;
followEntity(air.viewer, air.aircraft);
assert.equal(air.cockpit.enter({ kind: 'aircraft' }), true);
for (const key of ['+', '=', '-', '_'])
assert.equal(press(air.cockpit, key).defaultPrevented, false, key);
@@ -829,44 +874,53 @@ test('a map already leased elsewhere does not keep orbit out', async (t) => {
* A double-click `offsetPx` from where the followed satellite is drawn, at
* (400, 300) on the canvas, through Cesium's double-click handler.
*/
function doubleClickNearSatellite(viewer, offsetPx) {
function doubleClickNearSatellite(scene, offsetPx) {
const { viewer, input, stockHeld } = scene;
viewer.scene.cartesianToCanvasCoordinates = (position, result) =>
position ? Object.assign(result, { x: 400, y: 300 }) : undefined;
const handler = viewer.screenSpaceEventHandler;
const before = handler.stockCalls;
handler.doubleClick({ x: 400 + offsetPx, y: 300 });
const position = { x: 400 + offsetPx, y: 300 };
input.tap(position);
input.down(position);
input.up(position);
// The renderer's own follow runs unless the second press held it off.
if (!stockHeld()) handler.doubleClick(position);
input.dblclick(position);
return { stock: handler.stockCalls > before };
}
test('double-clicking the followed satellite enters the orbital view', async (t) => {
const { viewer, store } = fixture(t);
const miss = doubleClickNearSatellite(viewer, 60);
const scene = fixture(t);
const { store } = scene;
const miss = doubleClickNearSatellite(scene, 60);
assert.equal(miss.stock, true, 'a double-click elsewhere goes to Cesium');
assert.equal(store.orbital, null);
const hit = doubleClickNearSatellite(viewer, 20);
const hit = doubleClickNearSatellite(scene, 20);
assert.equal(hit.stock, false, 'Cesium never sees it');
await settle();
assert.ok(store.orbital, 'the orbital HUD is up');
assert.equal(
doubleClickNearSatellite(viewer, 0).stock,
doubleClickNearSatellite(scene, 0).stock,
true,
'inside, a double-click is not the entry',
);
});
test('a double-click a tool owns, or one the gate refuses, does not enter', async (t) => {
const { cockpit, viewer, store } = fixture(t, { orbitAllowed: false });
const scene = fixture(t, { orbitAllowed: false });
const { cockpit, store } = scene;
// On the track but refused: no entry, and no untracking either.
assert.equal(doubleClickNearSatellite(viewer, 0).stock, false);
assert.equal(doubleClickNearSatellite(scene, 0).stock, false);
assert.equal(store.orbital, null);
cockpit.isOrbitEntryAllowed = () => true;
// Drawing ends a shape with a double-click.
const lease = claimPointer('draw');
t.after(() => releasePointer(lease));
doubleClickNearSatellite(viewer, 0);
doubleClickNearSatellite(scene, 0);
assert.equal(store.orbital, null);
releasePointer(lease);
doubleClickNearSatellite(viewer, 0);
doubleClickNearSatellite(scene, 0);
await settle();
assert.ok(store.orbital);
});
@@ -882,20 +936,22 @@ test('a double-click on the followed aircraft model enters instead of untracking
track: 45,
onGround: false,
};
const { viewer, aircraft, store } = fixture(t, { aircraftInfo });
viewer.trackedEntity = aircraft;
const scene = fixture(t, { aircraftInfo });
const { viewer, aircraft, store } = scene;
followEntity(viewer, aircraft);
// The model is a primitive, not an Entity: Cesium's own double-click
// would untrack it.
doubleClickNearSatellite(viewer, 0);
doubleClickNearSatellite(scene, 0);
await settle();
assert.equal(viewer.screenSpaceEventHandler.stockCalls, 0);
assert.equal(store.presence.active, true, 'the cockpit is entered');
});
test('the Cockpit hands the double-click back to Cesium when it stops', async (t) => {
const { cockpit, viewer } = fixture(t);
const scene = fixture(t);
const { cockpit, viewer } = scene;
cockpit.stop();
doubleClickNearSatellite(viewer, 0);
doubleClickNearSatellite(scene, 0);
assert.equal(viewer.screenSpaceEventHandler.stockCalls, 1);
});
@@ -994,7 +1050,7 @@ test('a place that lands after the exit is dropped', async (t) => {
assert.equal(store.orbital, null, 'no HUD comes back for a stale answer');
});
test('a tracked aircraft takes entry before a tracked satellite', async (t) => {
test('an aircraft and a satellite first seen in one sync: the aircraft takes entry, by the fixed order', async (t) => {
const aircraftInfo = {
icao24: 'abc123',
callsign: 'TEST1',
@@ -1006,7 +1062,10 @@ test('a tracked aircraft takes entry before a tracked satellite', async (t) => {
onGround: false,
};
const { cockpit, viewer, aircraft, store } = fixture(t, { aircraftInfo });
viewer.trackedEntity = aircraft;
followEntity(viewer, aircraft);
// The satellite and the aircraft are both new to this sync; the fixed order
// decides between subjects first seen together. Selected one after the
// other, the later one takes entry (cockpitEntryGate.test.mjs).
cockpit.syncEntry();
assert.equal(store.presence.entryKind, 'aircraft');
});
@@ -1133,33 +1192,6 @@ test('S does nothing in an orbital view, even with a SENSOR step', async (t) =>
);
});
/** A globe draping one Web Mercator imagery layer that records requests. */
function imageryGlobe(viewer, { requestImage } = {}) {
const requests = [];
const requestObjects = [];
const provider = {
tilingScheme: new Cesium.WebMercatorTilingScheme(),
tileWidth: 256,
maximumLevel: 19,
requestImage:
requestImage ??
((x, y, level, request) => {
requests.push(`${level}/${x}/${y}`);
requestObjects.push(request);
return Promise.resolve({});
}),
};
viewer.scene.globe = { show: true, tilesLoaded: true };
viewer.scene.canvas = { clientWidth: 1600, clientHeight: 900 };
viewer.imageryLayers = {
length: 1,
get: () => ({ show: true, alpha: 1, imageryProvider: provider }),
};
return { requests, requestObjects, provider };
}
const WORLDVIEW_ON_TRACK = Object.freeze({ ...WORLDVIEW, groundTrackDeg: 52 });
test('the sensor strip follows the view through a zoom step, not ahead of it', async (t) => {
const { cockpit, store, clock } = await orbitAt(t, {
satellite: WORLDVIEW,
@@ -1181,84 +1213,6 @@ test('the sensor strip follows the view through a zoom step, not ahead of it', a
assert.ok(midway > atOne && midway < atTwo, 'part-way through the step');
});
test('from 16x the imagery ahead of the ground track is pre-loaded', async (t) => {
const { cockpit, viewer, store, clock } = await orbitAt(t, {
satellite: WORLDVIEW_ON_TRACK,
});
const { requests } = imageryGlobe(viewer);
for (const zoom of [2, 4, 8]) {
press(cockpit, '+');
assert.equal(store.orbital.zoom, zoom);
clock.advance(ORBITAL_PREFETCH_INTERVAL_MS);
cockpit.update();
}
assert.deepEqual(requests, [], 'nothing below 16x');
press(cockpit, '+');
assert.equal(store.orbital.zoom, 16);
clock.advance(16);
cockpit.update();
assert.ok(requests.length > 0, 'tiles ahead are asked for');
assert.ok(requests.length <= ORBITAL_PREFETCH_MAX_TILES, 'bounded');
assert.equal(new Set(requests.map((key) => key.split('/')[0])).size, 1);
const first = requests.length;
// Not again until the interval has passed, and never the same tile twice.
clock.advance(16);
cockpit.update();
assert.equal(requests.length, first);
clock.advance(ORBITAL_PREFETCH_INTERVAL_MS);
cockpit.update();
assert.equal(new Set(requests).size, requests.length, 'no repeats');
// A tighter zoom needs a finer level.
press(cockpit, '+');
assert.equal(store.orbital.zoom, 32);
clock.advance(ORBITAL_PREFETCH_INTERVAL_MS);
cockpit.update();
const levels = requests.map((key) => Number(key.split('/')[0]));
assert.equal(levels.at(-1), levels[0] + 1);
// Back below 16x, and after the exit: no more work.
const before = requests.length;
press(cockpit, '-');
press(cockpit, '-');
assert.equal(store.orbital.zoom, 8);
clock.advance(ORBITAL_PREFETCH_INTERVAL_MS);
cockpit.update();
assert.equal(requests.length, before, 'stops below 16x');
press(cockpit, '+');
cockpit.exit();
clock.advance(ORBITAL_PREFETCH_INTERVAL_MS);
cockpit.update();
assert.equal(
prefetchImageryAhead.call(cockpit, WORLDVIEW_ON_TRACK, Infinity),
0,
);
assert.equal(requests.length, before, 'stops after the exit');
});
test('the pre-load skips a hidden globe and a provider that cannot fetch', async (t) => {
const { cockpit, viewer, store, clock } = await orbitAt(t, {
satellite: WORLDVIEW_ON_TRACK,
});
const { requests, provider } = imageryGlobe(viewer);
for (let i = 0; i < 4; i += 1) press(cockpit, '+');
assert.equal(store.orbital.zoom, 16);
// Google 3D tiles drawn, the globe hidden: nothing to pre-load.
viewer.scene.globe.show = false;
clock.advance(ORBITAL_PREFETCH_INTERVAL_MS);
cockpit.update();
assert.deepEqual(requests, []);
viewer.scene.globe.show = true;
// No requestImage, or one that throws: no error, nothing remembered.
delete provider.requestImage;
clock.advance(ORBITAL_PREFETCH_INTERVAL_MS);
assert.doesNotThrow(() => cockpit.update());
provider.requestImage = () => {
throw new Error('offline');
};
clock.advance(ORBITAL_PREFETCH_INTERVAL_MS);
assert.doesNotThrow(() => cockpit.update());
assert.equal(store.orbital.zoom, 16, 'the view carries on');
});
test('an unconfirmed sensor swath is drawn but adds no zoom steps', async (t) => {
const { store } = await orbitAt(t, {
satellite: {
@@ -1434,45 +1388,6 @@ test('the readout says OFF-NADIR while the view is tilted', async (t) => {
);
});
test('the pre-load is throttled, at the level Cesium draws, and waits out a tilt', async (t) => {
const { cockpit, viewer, store, clock } = await orbitAt(t, {
satellite: WORLDVIEW_ON_TRACK,
});
const { requests, requestObjects } = imageryGlobe(viewer);
for (let i = 0; i < 4; i += 1) press(cockpit, '+');
assert.equal(store.orbital.zoom, 16);
// Tilted off nadir the view looks away from the track: nothing asked.
press(cockpit, 'ArrowRight');
clock.advance(ORBITAL_PREFETCH_INTERVAL_MS);
cockpit.update();
assert.deepEqual(requests, [], 'nothing while tilted');
press(cockpit, 'Home');
for (let frame = 0; frame < 30; frame += 1) {
clock.advance(16);
cockpit.update();
}
assert.ok(requests.length > 0, 'back at nadir it pre-loads');
// Every request may be declined while Cesium is busy with the screen.
for (const request of requestObjects) {
assert.ok(request instanceof Cesium.Request);
assert.equal(request.throttle, true);
assert.equal(request.throttleByServer, true);
assert.equal(
request.priority,
Number.MAX_VALUE,
'never ahead of the screen',
);
assert.equal(request.type, Cesium.RequestType.IMAGERY);
}
// The level Cesium's own selection takes for this view, worked by hand:
// at 16x from 617 km the 900 px canvas is ~49.5 m a pixel. The ellipsoid
// terrain's level-zero error is 6378137 · 2π / 4 / 128 ≈ 78,272 m; it first
// meets Cesium's screen-space error of 2 px (≤ 99 m) at level 10, 76.4 m.
// A Web Mercator level-zero texel at 30° is 6378137 · 2π · cos 30° / 256
// ≈ 135,570 m, so the imagery level is round(log2(135,570 / 76.4)) = 11.
assert.equal(Number(requests[0].split('/')[0]), 11);
});
test('the TLE age is measured from the time the satellite is shown at', async (t) => {
const DAY = 86_400_000;
const { store } = await orbitAt(t, {
@@ -1527,76 +1442,6 @@ test('a SAR swath reads but draws no strip under nadir', async (t) => {
assert.equal(store.orbital.sensor.stripFraction, null);
});
test('exit cancels pending pre-loads, and a dropped one is asked again', async (t) => {
const { cockpit, viewer, store, clock } = await orbitAt(t, {
satellite: WORLDVIEW_ON_TRACK,
});
const asked = [];
let fail = true;
const pending = [];
imageryGlobe(viewer, {
requestImage: (x, y, level, request) => {
asked.push(`${level}/${x}/${y}`);
// Cesium's scheduler drops a request by rejecting with no error.
if (fail) return Promise.reject(undefined);
pending.push(request);
return new Promise(() => {});
},
});
for (let i = 0; i < 4; i += 1) press(cockpit, '+');
assert.equal(store.orbital.zoom, 16);
clock.advance(ORBITAL_PREFETCH_INTERVAL_MS);
cockpit.update();
await settle();
const firstAsk = asked.slice();
assert.ok(firstAsk.length > 0);
fail = false;
clock.advance(ORBITAL_PREFETCH_INTERVAL_MS);
cockpit.update();
assert.deepEqual(asked.slice(firstAsk.length), firstAsk, 'asked again');
assert.ok(pending.length > 0);
cockpit.exit();
assert.ok(
pending.every((request) => request.cancelled === true),
'cancelled on exit',
);
});
test('the pre-load waits while the world clock is away from now', async (t) => {
const { cockpit, viewer, store, clock } = await orbitAt(t, {
satellite: { ...WORLDVIEW_ON_TRACK, atMs: START_MS - 3_600_000 },
});
const { requests } = imageryGlobe(viewer);
for (let i = 0; i < 4; i += 1) press(cockpit, '+');
assert.equal(store.orbital.zoom, 16);
clock.advance(ORBITAL_PREFETCH_INTERVAL_MS);
cockpit.update();
assert.deepEqual(requests, []);
});
test('a tile that fails to load is not asked again', async (t) => {
const { cockpit, viewer, store, clock } = await orbitAt(t, {
satellite: WORLDVIEW_ON_TRACK,
});
const asked = [];
imageryGlobe(viewer, {
requestImage: (x, y, level) => {
asked.push(`${level}/${x}/${y}`);
return Promise.reject(new Error('404'));
},
});
for (let i = 0; i < 4; i += 1) press(cockpit, '+');
assert.equal(store.orbital.zoom, 16);
clock.advance(ORBITAL_PREFETCH_INTERVAL_MS);
cockpit.update();
await settle();
const first = asked.length;
assert.ok(first > 0);
clock.advance(ORBITAL_PREFETCH_INTERVAL_MS);
cockpit.update();
assert.equal(new Set(asked).size, asked.length, 'none asked twice');
});
test('back to nadir from past the limb, the sensor waits for the view', async (t) => {
const { cockpit, store, clock } = await orbitAt(t, {
satellite: GEO_IMAGER,
+20 -1
View File
@@ -7,9 +7,14 @@ import assert from 'node:assert/strict';
import { createPinia } from 'pinia';
import { createApp, defineComponent, h, nextTick } from 'vue';
import { CockpitViewController } from './cockpitController.js';
import { setLocale } from '../i18n/index.js';
import { useCockpitStore } from './stores/cockpit.js';
import CockpitView from './views/CockpitView.vue';
import ContextView from './views/ContextView.vue';
import {
bindFakeCesiumCamera,
followEntity,
} from '../testSupport/fakeCameraPort.mjs';
const INFO = Object.freeze({
icao24: 'abc123',
@@ -42,7 +47,6 @@ function fixture(t) {
const listeners = () => ({ addEventListener: () => () => {} });
const entity = { position: {}, show: true };
const viewer = {
trackedEntity: entity,
camera: { cancelFlight() {} },
entities: { contains: (candidate) => candidate === entity },
scene: {
@@ -51,6 +55,8 @@ function fixture(t) {
},
trackedEntityChanged: listeners(),
};
bindFakeCesiumCamera(viewer, { frame: { on: () => () => {} } });
followEntity(viewer, entity);
const cockpit = new CockpitViewController(viewer, {
services: {
flightsLayer: { getTrackedInfo: () => INFO, refreshTr3b() {} },
@@ -255,3 +261,16 @@ test('entering asks for a panel layout before Vue shows the cards', async (t) =>
await new Promise((resolve) => setTimeout(resolve, 50));
assert.deepEqual(laid, ['context', 'signals']);
});
test('an aircraft is acquired on its CURSO in Portuguese; a ship keeps RUMO', async (t) => {
const { cockpit } = fixture(t);
t.after(() => setLocale('en'));
setLocale('pt');
const signals = [];
cockpit.pushCockpitSignal = (...args) => signals.push(args);
cockpit.enter();
await nextTick();
const acquired = signals.find(([key]) => key === 'track');
assert.ok(acquired, JSON.stringify(signals));
assert.equal(acquired[3], 'UAL123 · CURSO 092°');
});
+13 -7
View File
@@ -27,9 +27,11 @@ export const COCKPIT_UTILITY_REC_GAP_PX = 12;
export const COCKPIT_UTILITY_SIGNAL_GAP_PX = 8;
export const COCKPIT_UTILITY_MIN_TOP_PX = 96;
// Display and Radio start where the left rail does (max(206px, 22vh) in
// cockpit-panels.css), so the two rails' tops line up.
export const COCKPIT_UTILITY_MIN_TOP_PX = 206;
export const COCKPIT_UTILITY_MIN_TOP_RATIO = 0.12;
export const COCKPIT_UTILITY_MIN_TOP_RATIO = 0.22;
export const COCKPIT_UTILITY_LAUNCHER_MIN_HEIGHT_PX = 50;
@@ -184,11 +186,15 @@ const COCKPIT_ENTRY_FACES = Object.freeze({
});
/**
* The entry's glyph and localized label for the subject it would ride.
* @param {'aircraft'|'vessel'|'satellite'|null|undefined} kind
* The entry's glyph and localized label for the subject it would ride. An
* application provider's subject brings its own face, already in the page's
* language (`presence.entryFace`).
* @param {string|null|undefined} kind
* @param {{icon: string, label: string}|null} [face]
* @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) };
export function cockpitEntryFace(kind, face = null) {
if (face?.icon && face?.label) return { icon: face.icon, label: face.label };
const known = COCKPIT_ENTRY_FACES[kind] ?? COCKPIT_ENTRY_FACES.aircraft;
return { icon: known.icon, label: t(known.label) };
}
File diff suppressed because it is too large. Load diff
+450 -64
View File
@@ -1,25 +1,45 @@
/** Tracking identity, entry, exit and contact navigation for the Cockpit controller. */
import { t } from '../i18n/index.js';
import { cameraOf } from '../render/rendererOf.js';
import {
formatHeadingReadout,
normalizeHeading,
resolveTrackedAircraftInfo,
} from '../cockpitMath.js';
import {
followedOf,
resumeFollowing,
stopFollowing,
} from '../data/followed.js';
import { inputFor } from '../input/dispatcher.js';
import {
cockpitSubjectCandidate,
cockpitSubjectFrame,
} from '../cockpitSubjectProviders.js';
/** The camera's own heading in degrees, or 0 when it has none. */
function cameraHeadingDeg(camera) {
const heading = camera?.heading;
/**
* Whether the aircraft entity Cockpit holds still draws, as its services
* say; true when they cannot say.
*/
export function trackedEntityDrawn(entity) {
const drawn = this.services.trackedEntityDrawn;
return typeof drawn === 'function' ? drawn(entity) !== false : true;
}
/** A camera pose's heading in degrees, or 0 when it has none. */
function cameraHeadingDeg(pose) {
const heading = pose?.heading;
return Number.isFinite(heading) ? (heading * 180) / Math.PI : 0;
}
export function readAircraftInfo() {
// In cockpit mode the controller takes the entity off `viewer.trackedEntity`
// (see update()), so the cockpit's own handle is the tracked identity there.
const trackedEntity = this.viewer?.trackedEntity || this.trackedEntity;
// In cockpit mode the controller stops the camera following (see enter()),
// so the cockpit's own handle is the tracked identity there.
const followed = followedOf(this.viewer) || this.trackedFollow;
return resolveTrackedAircraftInfo({
civilian: this.services.flightsLayer.getTrackedInfo?.() || null,
military: this.services.militaryFlightsLayer.getTrackedInfo?.() || null,
trackedId: trackedEntity?.gevTrackedId || '',
trackedId: followed?.key || '',
});
}
@@ -33,47 +53,221 @@ export function readSatelliteInfo() {
return this.services.satellitesLayer?.getCockpitSubject?.() || null;
}
/**
* What an application subject provider would have entry ride now, or null.
* @param {object} provider A provider from cockpitSubjectProviders.
* @returns {{id: string, name: string, face: object|null}|null}
*/
export function readSubjectCandidate(provider) {
return cockpitSubjectCandidate(
this.callSubject(provider, 'candidate', [], null),
);
}
/**
* What a provider's `read` and `hud` receive besides the frame: the shared
* ground floor at a point (metres, or null), a way to warm its cells, and the
* floor service's lift.
*/
export function subjectContext() {
this._subjectContext ??= Object.freeze({
groundHeightAt: (latitude, longitude) => {
const height = this.services.cachedGroundFloor?.(latitude, longitude);
return Number.isFinite(height) ? height : null;
},
warmGround: (points) => {
this.services.warmGroundFloor?.(points);
},
liftM: Number.isFinite(this.services.GROUND_FLOOR_LIFT_M)
? this.services.GROUND_FLOOR_LIFT_M
: 0,
});
return this._subjectContext;
}
/**
* The ridden provider subject as the camera and HUD read it: the frame's
* place and motion, named like the built-in kinds' info.
* @param {object} frame From cockpitSubjectFrame.
*/
export function subjectInfo(frame) {
return {
kind: this.subjectProvider?.kind ?? null,
generic: true,
layerId: this.subjectProvider?.layerId ?? null,
id: frame.id,
name: frame.name,
latitude: frame.latitude,
longitude: frame.longitude,
track: frame.headingDeg,
motionCourse: frame.courseDeg,
velocityMps: frame.speedMps ?? 0,
stale: frame.stale,
groundClamp: frame.groundClamp,
anchor: frame.anchor,
onGround: false,
};
}
/** The built-in kinds' fixed entry order. */
const BUILT_IN_ENTRY_ORDER = Object.freeze({
aircraft: 0,
satellite: 1,
vessel: 2,
});
/**
* Every subject entry could ride now, in entry order: a tracked aircraft,
* the tracked satellite, the selected vessel and each provider's candidate.
* The built-in kinds keep their fixed order (aircraft, satellite, vessel),
* whenever each was selected. A provider's candidate goes ahead of them only
* when it was selected after every built-in one present: a train picked
* after an aircraft was tracked takes entry, an aircraft tracked after it
* takes it back. Providers' candidates are ordered most recently selected
* first, then by priority. A candidate's time is when this controller first
* saw it (it looks on its entry cadence and on tracking changes), or saw it
* selected again: another subject of a built-in kind, a provider candidate
* whose `selectedAt` changes, or one without a `selectedAt` whose id changes.
* A new id under the same `selectedAt` is the same selection, as when a
* train's selection moves to another feed's copy of it. One
* first seen together with a built-in candidate comes after it. With no
* provider, entry is the built-in order alone. Each carries `allowed()`, its
* kind's entry gate.
* @param {number} [nowMs]
* @returns {Array<{kind: string, id: string, seenAtMs: number, order: number,
* allowed: () => boolean, provider?: object, candidate?: object}>}
*/
export function entryCandidates(nowMs = performance.now()) {
const seen = (this._entrySeen ??= new Map());
const list = [];
const note = (kind, id, entry, selectedAt = null) => {
const last = seen.get(kind);
// A provider's token says when its subject was selected: a new id under
// the same token (a train handed to another feed's copy of it) is not a
// new selection. Without a token, a new id is.
if (
!last ||
last.selectedAt !== selectedAt ||
(selectedAt === null && last.id !== id)
)
seen.set(kind, { id, selectedAt, atMs: nowMs });
else if (last.id !== id) seen.set(kind, { ...last, id });
list.push({ kind, id, seenAtMs: seen.get(kind).atMs, ...entry });
};
const aircraft = this.readAircraftInfo();
const followed = aircraft ? followedOf(this.viewer) : null;
if (aircraft && followed?.entity?.position)
note(
'aircraft',
String(followed.key || aircraft.icao24 || aircraft.id || 'aircraft'),
{
order: BUILT_IN_ENTRY_ORDER.aircraft,
allowed: () => this.isEntryAllowed(),
},
);
const satellite = this.readSatelliteInfo();
if (satellite)
note('satellite', String(satellite.noradId ?? satellite.id ?? ''), {
order: BUILT_IN_ENTRY_ORDER.satellite,
allowed: () => this.isOrbitEntryAllowed(),
});
const vessel = this.readVesselInfo();
if (vessel)
note('vessel', String(vessel.id ?? ''), {
order: BUILT_IN_ENTRY_ORDER.vessel,
allowed: () => this.isBridgeEntryAllowed(),
});
this.subjectProviders.forEach((provider, index) => {
const candidate = this.readSubjectCandidate(provider);
if (candidate)
note(
provider.kind,
candidate.id,
{
order: 3 + index,
provider,
candidate,
allowed: () => this.isSubjectEntryAllowed(provider, candidate),
},
candidate.selectedAt,
);
});
// A subject gone and back counts as selected again.
for (const kind of [...seen.keys()])
if (!list.some((entry) => entry.kind === kind)) seen.delete(kind);
const builtIns = list
.filter((entry) => !entry.provider)
.sort((a, b) => a.order - b.order);
const provided = list
.filter((entry) => entry.provider)
.sort((a, b) => b.seenAtMs - a.seenAtMs || a.order - b.order);
const builtInSeenAtMs = Math.max(
-Infinity,
...builtIns.map((entry) => entry.seenAtMs),
);
const later = provided.filter((entry) => entry.seenAtMs > builtInSeenAtMs);
const earlier = provided.filter((entry) => entry.seenAtMs <= builtInSeenAtMs);
return [...later, ...builtIns, ...earlier];
}
/**
* The subject entry would ride: the first in entry order (entryCandidates).
* It decides alone, so when its own gate is shut entry is unavailable rather
* than taken by the next one.
* @returns {object|null} An entry of entryCandidates, or null.
*/
export function resolveEntry(nowMs = performance.now()) {
return this.entryCandidates(nowMs)[0] ?? null;
}
/**
* The layer the active view rides: Live AIS Vessels on a bridge, Satellites
* in orbit, else 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'|'ais-live-vessels'|'satellites'|null}
* in orbit, a provider's own layer, else the aircraft's own layer. It is read
* from the followed aircraft's key once the layer has dropped its tracking,
* so a layer turned off still names itself.
* @returns {string|null}
*/
export function readSubjectLayerId() {
if (!this.active) return null;
if (this.subjectProvider) return this.subjectProvider.layerId;
if (this.subjectKind === 'vessel') return 'ais-live-vessels';
if (this.subjectKind === 'satellite') return 'satellites';
const layerId = this.readAircraftInfo()?.layerId;
if (layerId) return layerId;
const [prefix] = String(this.trackedEntity?.gevTrackedId || '').split(':');
const [prefix] = String(this.trackedFollow?.key || '').split(':');
return ['flights', 'military'].includes(prefix) ? prefix : null;
}
/**
* The subject entry would take: a Cesium-tracked aircraft first, then the
* tracked satellite, else the selected vessel. Vessels never take Cesium
* tracking, so an aircraft and a vessel cannot be live through the same owner.
* @returns {'aircraft'|'satellite'|'vessel'|null}
* The kind entry would take, the first in entry order's (resolveEntry): a
* followed aircraft, the tracked satellite, the selected vessel or a
* provider's candidate.
* @returns {string|null}
*/
export function resolveEntryKind() {
if (this.readAircraftInfo() && this.viewer.trackedEntity?.position)
return 'aircraft';
if (this.readSatelliteInfo()) return 'satellite';
return this.readVesselInfo() ? 'vessel' : null;
return this.resolveEntry()?.kind ?? null;
}
export function dispatchCockpitModeChanged(active, info = null) {
const subjectId = active
? String(info?.icao24 || info?.mmsi || info?.noradId || '')
? String(
info?.icao24 ||
(info?.kind === 'vessel' || info?.generic === true ? info.id : '') ||
info?.noradId ||
'',
)
.trim()
.toLowerCase() || null
: null;
const layerId =
active &&
['flights', 'military', 'ais-live-vessels', 'satellites'].includes(
(['flights', 'military', 'ais-live-vessels', 'satellites'].includes(
info?.layerId,
)
) ||
(info?.generic === true &&
this.subjectProviders.some(
(provider) => provider.layerId === info.layerId,
)))
? info.layerId
: null;
window.dispatchEvent(
@@ -122,40 +316,60 @@ export function syncTr3bToggle(info) {
this.publishPresenceView();
}
/**
* Word the ridden provider subject's labels and Look ahead button again,
* after a change of the page's language: a provider may give them as
* functions (cockpitSubjectProviders).
*/
export function refreshSubjectWords() {
const provider = this.subjectProvider;
if (!this.active || !provider) return;
this.presence.subjectLabels = { ...provider.labels };
const look = provider.look;
this.presence.subjectLook = look ? { aheadLabel: look.aheadLabel } : null;
this.publishPresenceView();
}
export function syncEntry() {
if (this.destroyed) return false;
if (this.active) return;
const info = this.readAircraftInfo();
const trackedContact = !!(info && this.viewer.trackedEntity?.position);
this.syncTr3bToggle(trackedContact ? info : null);
const orbitContact = !trackedContact && !!this.readSatelliteInfo();
const bridgeContact =
!trackedContact && !orbitContact && !!this.readVesselInfo();
let entryKind = null;
if (trackedContact) entryKind = this.isEntryAllowed() ? 'aircraft' : null;
else if (orbitContact)
entryKind = this.isOrbitEntryAllowed() ? 'satellite' : null;
else if (bridgeContact)
entryKind = this.isBridgeEntryAllowed() ? 'vessel' : null;
const candidates = this.entryCandidates(performance.now());
const tracked = candidates.some(({ kind }) => kind === 'aircraft');
this.syncTr3bToggle(tracked ? this.readAircraftInfo() : null);
// The first in entry order decides alone (resolveEntry).
const chosen = candidates[0] ?? null;
const entryKind = chosen?.allowed() ? chosen.kind : null;
const face =
entryKind && chosen.provider
? (chosen.candidate.face ?? chosen.provider.entryFace)
: null;
const available = entryKind !== null;
// Change-only publishes: this runs on a preUpdate cadence, and a fresh
// presence every frame would re-render the views even when nothing
// changed. (perf item 9)
if (
this.presence.entryAvailable === available &&
this.presence.entryKind === entryKind
this.presence.entryKind === entryKind &&
this.presence.entryFace?.icon === face?.icon &&
this.presence.entryFace?.label === face?.label
)
return;
this.presence.entryAvailable = available;
this.presence.entryKind = entryKind;
this.presence.entryFace = face && { icon: face.icon, label: face.label };
this.publishPresenceView();
}
export function navigateContext(direction, options = {}) {
if (this.destroyed) return false;
// Contact navigation moves between aircraft; a bridge does not jump ship
// and an orbital view stays with its satellite.
if (this.subjectKind === 'vessel' || this.subjectKind === 'satellite')
// Contact navigation moves between aircraft; a bridge does not jump ship,
// an orbital view stays with its satellite and a provider's view with its
// subject.
if (
this.subjectKind === 'vessel' ||
this.subjectKind === 'satellite' ||
this.subjectProvider
)
return false;
const method = direction < 0 ? 'navigatePrevious' : 'navigateNext';
const wasActive = this.active;
@@ -175,11 +389,17 @@ export function navigateContext(direction, options = {}) {
}
export function _adoptTrackedEntity(nowMs, suppliedInfo = null) {
// An aircraft tracked from the bridge or from orbit ends that view (see the
// vessel and orbital camera updates); it is never adopted as its subject.
if (this.subjectKind === 'vessel' || this.subjectKind === 'satellite')
// An aircraft followed from the bridge, from orbit or from a provider's
// view ends that view (see the camera updates); it is never adopted as its
// subject.
if (
this.subjectKind === 'vessel' ||
this.subjectKind === 'satellite' ||
this.subjectProvider
)
return false;
const nextEntity = this.viewer.trackedEntity;
const nextFollowed = followedOf(this.viewer);
const nextEntity = nextFollowed?.entity;
if (
!this.active ||
!nextEntity?.position ||
@@ -188,13 +408,14 @@ export function _adoptTrackedEntity(nowMs, suppliedInfo = null) {
return false;
const info = suppliedInfo || this.readAircraftInfo();
if (!info) return false;
if (this.trackedEntity && this.viewer.entities.contains(this.trackedEntity)) {
if (this.trackedEntity && trackedEntityDrawn.call(this, this.trackedEntity)) {
this.trackedEntity.show = this.trackedEntityWasShown;
}
this.trackedEntity = nextEntity;
this.trackedFollow = nextFollowed;
this.trackedEntityWasShown = nextEntity.show;
nextEntity.show = false;
this.viewer.trackedEntity = undefined;
stopFollowing(this.viewer);
this.cockpitAnchorValid = false;
this.heading = normalizeHeading(info.track ?? 0);
this.lastFrameMs = nowMs;
@@ -208,16 +429,154 @@ export function _adoptTrackedEntity(nowMs, suppliedInfo = null) {
}
/**
* Enter first person on a tracked aircraft or, with none tracked, the
* tracked satellite's orbital view or the selected vessel's bridge.
* @param {{kind?: 'aircraft'|'satellite'|'vessel'|null}} [options] Restrict
* entry to one subject kind; voice entry is aircraft-only.
* Enter a provider's view on its candidate: hold it, read a first frame, then
* take the camera as the built-in views do. Entry fails when the gate is shut,
* the hold answers anything but `true` or no frame comes; past the gate, a
* failed entry releases the subject, since the hold may have taken it.
* @param {object} provider From cockpitSubjectProviders.
* @returns {boolean}
*/
function enterSubject(provider) {
const candidate = this.readSubjectCandidate(provider);
if (!candidate || !this.isSubjectEntryAllowed(provider, candidate))
return false;
const failed = {};
const release = () =>
this.callSubject(provider, 'release', [candidate.id, { restore: false }]);
// An asynchronous hold may land after it was refused: it is released
// again once it settles, unless this subject is being ridden by then.
const releaseLate = () => {
if (
this.active &&
this.subjectProvider === provider &&
this.subjectId === candidate.id
)
return;
release();
};
const held = this.callSubject(
provider,
'hold',
[candidate.id],
failed,
releaseLate,
);
if (held !== true) {
// `false` refuses entry; a hold that threw, returned a promise or
// answered anything else (warned of once) may still have taken the
// subject. Each is released.
if (held !== false && held !== failed)
this.callSubject.warnOnce(
provider,
'hold',
'must return true or false; entry refused',
held,
);
release();
return false;
}
const frame = cockpitSubjectFrame(
this.callSubject(
provider,
'read',
[performance.now(), this.subjectContext()],
null,
),
candidate.id,
);
if (!frame) {
this.callSubject(provider, 'release', [candidate.id, { restore: false }]);
return false;
}
this.entryFocusOrigin =
document.activeElement instanceof HTMLElement
? document.activeElement
: null;
this.onCameraTakeover?.();
cameraOf(this.viewer).cancelFlight();
this.subjectKind = provider.kind;
this.subjectProvider = provider;
this.subjectId = candidate.id;
this.lastSubjectFrame = frame;
this.subjectHud = null;
this.subjectSignalKeys = new Set();
this.vesselWaterline = null;
this.vesselFix = null;
this.trackedEntity = null;
this.heading = normalizeHeading(
frame.headingDeg ?? cameraHeadingDeg(cameraOf(this.viewer).pose()),
);
this.lastFrameMs = performance.now();
this.lastCameraUpdateMs = 0;
this.lastHudUpdateMs = 0;
this.lastContextUpdateMs = 0;
this.contextNavigationDeadlineMs = 0;
this.lastGroundProbeMs = 0;
this.surfaceWaitStartedMs = 0;
this.surfaceAcquiring = false;
this.surfaceFallback = false;
this.cockpitAnchorValid = false;
this.subjectHeightM = null;
this.lookRestPitchDeg = provider.look?.restPitchDeg ?? null;
this.resetLook({ immediate: true });
this.active = true;
this.services.holdContinuousRender('cockpit');
stopFollowing(this.viewer);
this.releaseCameraInput?.();
this.releaseCameraInput = inputFor(this.viewer).suspendCamera('cockpit');
document.body.classList.add('cockpit-mode', 'cockpit-subject');
this._tr3bSignature = null;
Object.assign(this.presence, {
active: true,
entryAvailable: false,
entryKind: null,
entryFace: null,
subjectKind: provider.kind,
subjectGeneric: true,
subjectLabels: { ...provider.labels },
subjectLook: provider.look
? { aheadLabel: provider.look.aheadLabel }
: null,
tr3b: null,
});
this.publishPresenceView();
this.publishRadar(null);
this.signalItems = [];
this.signalSignatures.clear();
this.showBriefPage(0);
this.startBriefRotation();
this.pushCockpitSignal('track', 'track', t('TRACK ACQUIRED'), frame.name);
const info = this.subjectInfo(frame);
this.updateHud(info, performance.now(), true);
this.setVisionMode(this.getInitialVisionMode());
this.scheduleContextLayout();
Promise.resolve().then(() => {
if (this.active && !this.destroyed)
this.mapViewButton?.focus({ preventScroll: true });
});
this.onEntered?.();
this.onRide?.(provider.layerId);
this.dispatchCockpitModeChanged(true, info);
return true;
}
/**
* Enter first person on the first subject in entry order (resolveEntry): a
* tracked aircraft, the tracked satellite's orbital view, the selected
* vessel's bridge or an application provider's subject.
* @param {{kind?: string|null}} [options] Restrict entry to one subject kind;
* voice entry is aircraft-only.
* @returns {boolean} True when the view was entered.
*/
export function enter({ kind = null } = {}) {
if (this.destroyed) return false;
if (this.active) return false;
const subjectKind = kind ?? this.resolveEntryKind() ?? 'aircraft';
const provider = this.subjectProviders.find(
(entry) => entry.kind === subjectKind,
);
if (provider) return enterSubject.call(this, provider);
if (!['aircraft', 'satellite', 'vessel'].includes(subjectKind)) return false;
const vessel = subjectKind === 'vessel';
const satellite = subjectKind === 'satellite';
const allowed = vessel
@@ -231,8 +590,9 @@ export function enter({ kind = null } = {}) {
: satellite
? this.readSatelliteInfo()
: this.readAircraftInfo();
// Only an aircraft is ridden through its Cesium entity.
const entity = vessel || satellite ? null : this.viewer.trackedEntity;
// Only an aircraft is ridden through the followed entity.
const followed = vessel || satellite ? null : followedOf(this.viewer);
const entity = followed?.entity ?? null;
if (!info || (!vessel && !satellite && !entity?.position)) return false;
this.entryFocusOrigin =
document.activeElement instanceof HTMLElement
@@ -240,13 +600,14 @@ export function enter({ kind = null } = {}) {
: null;
// Retire deferred navigation before cancelFlight can run its callbacks.
this.onCameraTakeover?.();
this.viewer.camera.cancelFlight();
cameraOf(this.viewer).cancelFlight();
this.subjectKind = subjectKind;
// Each session reads its own water: never a height left from the last.
this.vesselWaterline = null;
this.vesselFix = null;
this.subjectId = vessel ? info.mmsi : satellite ? info.noradId : null;
this.subjectId = vessel ? info.id : satellite ? info.noradId : null;
this.trackedEntity = entity;
this.trackedFollow = followed;
if (entity) {
this.trackedEntityWasShown = entity.show;
entity.show = false;
@@ -255,7 +616,7 @@ export function enter({ kind = null } = {}) {
this.services.satellitesLayer?.setCockpitSubject?.(info.noradId);
this.beginOrbital();
} else {
this.services.aisLiveVesselsLayer?.setCockpitSubject?.(info.mmsi);
this.services.aisLiveVesselsLayer?.setCockpitSubject?.(info.id);
}
// A ship reporting neither heading nor course keeps the camera's own
// heading: no direction is made up for it.
@@ -263,7 +624,7 @@ export function enter({ kind = null } = {}) {
Number.isFinite(info.track)
? info.track
: vessel
? cameraHeadingDeg(this.viewer.camera)
? cameraHeadingDeg(cameraOf(this.viewer).pose())
: 0,
);
this.lastFrameMs = performance.now();
@@ -284,8 +645,9 @@ export function enter({ kind = null } = {}) {
// runs on rendered frames, so idle mode would freeze the cockpit solid.
// (perf wave 2)
this.services.holdContinuousRender('cockpit');
this.viewer.trackedEntity = undefined;
this.viewer.scene.screenSpaceCameraController.enableInputs = false;
stopFollowing(this.viewer);
this.releaseCameraInput?.();
this.releaseCameraInput = inputFor(this.viewer).suspendCamera('cockpit');
document.body.classList.add('cockpit-mode');
// Bridge styling reaches surfaces outside the HUD (exit row, side panels).
if (vessel) document.body.classList.add('cockpit-bridge');
@@ -321,9 +683,11 @@ export function enter({ kind = null } = {}) {
'track',
t('TRACK ACQUIRED'),
// A ship with no true heading is held on its course over ground; one
// with neither is named without a direction.
// with neither is named without a direction. A ship's course has a
// word of its own: pt «RUMO», where an aircraft's is «CURSO».
info.trackSource === 'course'
? t('{label} · COURSE {heading}°', {
context: 'vessel',
label: info.name,
heading: trackHeading,
})
@@ -366,16 +730,24 @@ export function enter({ kind = null } = {}) {
export function exit({ restoreTracking = true } = {}) {
if (!this.active) return false;
const entity = this.trackedEntity;
const followed = this.trackedFollow;
const provider = this.subjectProvider;
const providerSubject = provider ? this.subjectId : null;
const vesselSubject = this.subjectKind === 'vessel' ? this.subjectId : null;
const satelliteSubject =
this.subjectKind === 'satellite' ? this.subjectId : null;
this.active = false;
this.subjectKind = null;
this.subjectProvider = null;
this.lastSubjectFrame = null;
this.subjectHud = null;
this.lookRestPitchDeg = null;
this.vesselWaterline = null;
this.vesselFix = null;
this.subjectId = null;
this.services.releaseContinuousRender('cockpit');
this.trackedEntity = null;
this.trackedFollow = null;
this.heading = null;
this.resetLook({ immediate: true });
this.cockpitAnchorValid = false;
@@ -394,6 +766,7 @@ export function exit({ restoreTracking = true } = {}) {
'cockpit-mode',
'cockpit-bridge',
'cockpit-orbit',
'cockpit-subject',
);
// The camera's own field of view returns before any follow resumes.
this.endOrbital();
@@ -401,22 +774,34 @@ export function exit({ restoreTracking = true } = {}) {
this.publishUtilityLayout(null);
this.presence.active = false;
this.presence.subjectKind = null;
this.presence.subjectGeneric = false;
this.presence.subjectLabels = null;
this.presence.subjectLook = null;
this.publishPresenceView();
this.routeView.visible = false;
this.clearPredictiveRoute();
this.publishRadar(null);
this.setVisionMode('optical');
this.viewer.scene.screenSpaceCameraController.enableInputs = true;
if (entity && this.viewer.entities.contains(entity))
entity.show = this.trackedEntityWasShown;
this.releaseCameraInput?.();
this.releaseCameraInput = null;
const present = () =>
Boolean(entity) && trackedEntityDrawn.call(this, entity);
if (present()) entity.show = this.trackedEntityWasShown;
this.trackedEntityWasShown = true;
if (vesselSubject)
this.services.aisLiveVesselsLayer?.setCockpitSubject?.(null);
if (satelliteSubject !== null)
this.services.satellitesLayer?.setCockpitSubject?.(null);
// The provider gives its subject back; `restore` asks it to bring the map
// back to it, as the built-in kinds' refocus does.
if (provider)
this.callSubject(provider, 'release', [
providerSubject,
{ restore: restoreTracking === true },
]);
this.dispatchCockpitModeChanged(false);
if (restoreTracking && entity && this.viewer.entities.contains(entity)) {
this.viewer.trackedEntity = entity;
if (restoreTracking && present()) {
resumeFollowing(this.viewer, followed);
this.restoreTrackingFrame(entity);
} else if (restoreTracking && vesselSubject) {
// Back to the selected vessel's map view, through the layer's own focus.
@@ -426,10 +811,11 @@ export function exit({ restoreTracking = true } = {}) {
this.services.satellitesLayer?.refocusTrackedById?.(satelliteSubject);
}
this.syncEntry();
// Back to whichever entry was used: the Contacts button or the readout's.
// Return to the card or readout control that opened Cockpit.
const readoutEntry = document.getElementById('cockpit-entry-readout');
const restoreTarget =
this.entryFocusOrigin === this.entry ||
this.entryFocusOrigin?.hasAttribute('data-entity-cockpit-entry') ||
(readoutEntry && this.entryFocusOrigin === readoutEntry)
? this.entryFocusOrigin
: this.entry || this.entryFocusOrigin;
+39
View File
@@ -450,3 +450,42 @@ test('the real layout pass drives the mounted controls: compact hides the collap
assert.equal(cockpit.utilityLayout.top, '120.00px');
assert.equal(strip.classList.contains('layout-primary-only'), false);
});
test('the rail opens one panel at a time and reads as a disclosure', async (t) => {
const { $, controls } = fixture(t);
const item = (kind) =>
document.querySelector(`[data-cockpit-rail-item="${kind}"]`);
item('display').click();
await nextTick();
assert.equal($('cockpit-display-panel').hidden, false);
assert.equal(item('display').getAttribute('aria-expanded'), 'true');
assert.equal(
item('display').getAttribute('aria-controls'),
'cockpit-display-panel',
);
item('radio').click();
await nextTick();
assert.equal($('cockpit-display-panel').hidden, true);
assert.equal($('cockpit-radio-panel').hidden, false);
assert.equal(item('display').getAttribute('aria-expanded'), 'false');
assert.equal(item('radio').getAttribute('aria-expanded'), 'true');
item('radio').click();
await nextTick();
assert.equal(controls._cockpitDisclosureOpen('radio'), false);
assert.equal(controls._cockpitDisclosureOpen('display'), false);
});
test('collapsing an open panel hands focus to the rail when its toggle is hidden', async (t) => {
const { $, controls } = fixture(t);
const railItem = document.querySelector('[data-cockpit-rail-item="radio"]');
// happy-dom lays nothing out: show the rail and hide the launcher's toggle
// as the desktop look does.
railItem.getClientRects = () => [{ width: 32, height: 32 }];
$('cockpit-radio-toggle-btn').getClientRects = () => [];
controls._setCockpitDisclosure('radio', true);
await nextTick();
document.querySelector('.cockpit-utility-collapse').click();
await nextTick();
assert.equal($('cockpit-radio-panel').hidden, true);
assert.equal(document.activeElement, railItem);
});
+1 -1
View File
@@ -142,7 +142,7 @@ test('the map source row renders the published chips and selects through the con
assert.equal(osm.classList.contains('active'), true);
assert.equal(osm.getAttribute('aria-pressed'), 'true');
assert.equal(osm.hasAttribute('aria-label'), false);
assert.equal(esri.querySelector('.map-stack-chip-req'), null);
assert.equal(esri.querySelector('.map-stack-chip-req') === null, true);
bing.click();
esri.click();
assert.deepEqual(selected, ['esri-imagery']);
+6
View File
@@ -29,6 +29,7 @@ import {
import {
activateWorldOverlayAction,
destroyWorldOverlay,
hitTestWorldOverlay,
initWorldOverlay,
subscribeWorldOverlayActions,
} from '../overlays/worldOverlay.js';
@@ -56,6 +57,8 @@ import {
isScopeMaskEnabled,
setScopeMaskFeather,
getScopeMaskFeather,
setScopeMaskOpacity,
getScopeMaskOpacity,
setScopeTerminusOverride,
getScopeTerminusOverride,
clampScopeTerminusPct,
@@ -71,6 +74,7 @@ export class StyleManager extends ApplicationShell {
super(viewer, {
...options,
services: {
hitTestWorldOverlay,
CITY_POIS,
GLOBE_VIEW,
flyToGlobeView,
@@ -112,6 +116,8 @@ export class StyleManager extends ApplicationShell {
isScopeMaskEnabled,
setScopeMaskFeather,
getScopeMaskFeather,
setScopeMaskOpacity,
getScopeMaskOpacity,
setScopeTerminusOverride,
getScopeTerminusOverride,
clampScopeTerminusPct,
+12
View File
@@ -51,6 +51,8 @@ export class ContextControls {
this._contextRestoreState = null;
this._contextLayerReactionPromises = new Set();
this._preservePanelStateDuringLayerClear = false;
/** Layers Context isolation is switching off right now. */
this._isolatingLayerIds = new Set();
this._userFacingContextNotificationTokens = new Set();
this._clearSelectedLayersPromise = null;
this._clearSelectedLayersManagerPromise = null;
@@ -59,6 +61,16 @@ export class ContextControls {
showToast(...args) {
if (!this.destroyed) this.actions.showToast(...args);
}
/**
* Whether Context isolation is switching this layer off right now: it is
* suspended, and leaving the mode restores it. A switch-off by the user,
* inside the mode or out of it, is not.
* @param {string} layerId Layer id.
* @returns {boolean}
*/
suspendsLayer(layerId) {
return this._isolatingLayerIds.has(layerId);
}
setClearBusy(...args) {
if (!this.destroyed) this.actions.setClearBusy(...args);
}
+53
View File
@@ -153,3 +153,56 @@ test('a rejected tracked reaction settles without an unhandled rejection', async
await controls._waitForContextLayerSettlement();
assert.equal(controls._contextLayerReactionPromises.size, 0);
});
test('only a layer Context isolation is switching off is suspended', async (t) => {
const { controls } = fixture(t);
const enabled = new Set(['cctv']);
// What the CCTV panel is told at each visibility change of its layer.
const seen = [];
controls._dataManager = {
layers: new Map([['cctv', {}]]),
getEnabledLayerIds: () => [...enabled],
getLayerParams: () => null,
setLayerParams() {},
isEnabled: (layerId) => enabled.has(layerId),
isEffectivelyEnabled: (layerId) => enabled.has(layerId),
async setEnabled(layerId, next) {
// The layer tells its panel it is off while it is being disabled.
if (next) enabled.add(layerId);
else enabled.delete(layerId);
seen.push([layerId, next, controls.suspendsLayer(layerId)]);
return true;
},
async restoreEnabledLayerIds(layerIds) {
for (const layerId of layerIds) await this.setEnabled(layerId, true);
},
};
assert.equal(controls.suspendsLayer('cctv'), false);
controls._captureContextSessionSnapshot();
await controls._clearLayersOutsideContextMode('flights');
assert.deepEqual(seen, [['cctv', false, true]]);
assert.equal(controls.suspendsLayer('cctv'), false, 'only while isolating');
// Inside the mode the user turns CCTV back on, then off: their own.
await controls._dataManager.setEnabled('cctv', true);
await controls._dataManager.setEnabled('cctv', false);
assert.deepEqual(seen.at(-1), ['cctv', false, false]);
await controls._restoreContextSession();
assert.equal(enabled.has('cctv'), true);
// A switch-off after the mode is left is the user's own too.
await controls._dataManager.setEnabled('cctv', false);
assert.deepEqual(seen.at(-1), ['cctv', false, false]);
});
test('a failed isolation leaves no layer suspended', async (t) => {
const { controls } = fixture(t);
controls._dataManager = {
layers: new Map([['cctv', {}]]),
isEffectivelyEnabled: () => true,
isEnabled: () => true,
setEnabled: async () => {
throw new Error('disable failed');
},
};
await assert.rejects(controls._clearLayersOutsideContextMode('flights'));
assert.equal(controls.suspendsLayer('cctv'), false);
});
+15
View File
@@ -249,6 +249,21 @@ export function _handleContextLayerChange(change) {
);
}
}
if (
change.type === 'visibility' &&
change.enabled &&
change.origin === 'user' &&
!this.cockpitView?.active &&
(change.layerId === 'radio' || change.layerId === 'rocket-launches')
) {
// Context's panel shows its main tab for them (ContextView listens).
globalThis.dispatchEvent?.(new Event('gev:context-show-view'));
this.actions.setPanelCollapsed('global-context-panel', false, {
explicit: true,
});
if (change.layerId === 'radio')
this.actions.setPanelCollapsed('radio-panel', false, { explicit: true });
}
// 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
+95
View File
@@ -0,0 +1,95 @@
import { computed, ref } from 'vue';
import { msg } from '../i18n/index.js';
// Context's layer tabs: when a layer that has its own settings is on, those
// settings move out of the panel they normally live in (Visual) into a tab
// in the Context panel, so they sit beside what they affect.
// Each tab's content is teleported into `#context-tab-<id>`; when the layer
// goes off the content returns to its usual panel.
const AIRCRAFT = ['flights', 'military', 'local-adsb'];
// Layers that draw labels and cards through the world overlay, which the
// Dense settings (density, allocation, fade, outside) govern.
export const LABEL_LAYERS = new Set([
'satellites',
'ais-live-vessels',
'rocket-launches',
'cctv',
'transit',
'bikeshare',
'radio',
'local-adsb',
'earthquakes',
'local-firms',
'fire-perimeters',
'weather-cyclones',
'air-quality',
'alpr-cameras',
'drone-airspace',
'military-installations',
'telegeography-submarine-cables',
'osm-places',
's2-ghostmaps',
'directions',
]);
// Which of the layers that are on each tab acts on.
export const TAB_AFFECTS = {
labels: (on) => [...on].filter((id) => LABEL_LAYERS.has(id)),
aircraft: (on) => [...on].filter((id) => AIRCRAFT.includes(id)),
};
export const LAYER_TABS = [
// Labels and cards the world overlay draws for the label layers.
{
id: 'labels',
label: msg('Labels'),
icon: 'label',
when: (on) => TAB_AFFECTS.labels(on).length > 0,
},
{
id: 'aircraft',
label: msg('3D aircraft'),
icon: 'flight',
when: (on) => TAB_AFFECTS.aircraft(on).length > 0,
},
];
/** Ids of the layers that are on; Context refreshes it. */
export const enabledLayerIds = ref(new Set());
export function setEnabledLayers(ids) {
const next = new Set(ids);
const prev = enabledLayerIds.value;
if (next.size === prev.size && [...next].every((id) => prev.has(id))) return;
enabledLayerIds.value = next;
}
/** Whether Context is mounted and can host tab content. */
export const contextReady = ref(false);
/** The tabs available now. */
export const availableTabs = computed(() =>
contextReady.value
? LAYER_TABS.filter((tab) => tab.when(enabledLayerIds.value))
: [],
);
export const hasTab = (id) => availableTabs.value.some((tab) => tab.id === id);
/** The tab Context shows: 'view' (the card) or a layer tab's id. */
export const activeTab = ref('view');
// Each tab's content lands in an element made here, before any panel mounts,
// so a panel that mounts ahead of Context still has a real target; Context
// places these elements in its tab panes when it mounts.
const targets = new Map();
export function tabTarget(id) {
if (!targets.has(id) && globalThis.document) {
const el = document.createElement('div');
el.className = 'context-tab-body';
el.dataset.tab = id;
targets.set(id, el);
}
return targets.get(id) ?? 'body';
}
+45
View File
@@ -0,0 +1,45 @@
import { ref } from 'vue';
// How far out Context looks for what is "nearby": one distance for every
// nearby block (flights, vessels, hazards, alerts, other loaded items). The
// control in the Context panel steps through a few distances; the choice is
// kept for the next visit.
const KEY = 'gev.contextRadiusKm';
/** The distances the control steps through, in km. */
export const CONTEXT_RADIUS_STEPS = Object.freeze([
25, 50, 100, 250, 500, 1000, 2500,
]);
export const DEFAULT_CONTEXT_RADIUS_KM = 250;
/** The step closest to a distance; the default for anything unusable. */
export function nearestRadiusStep(km) {
const value = Number(km);
if (!Number.isFinite(value) || value <= 0) return DEFAULT_CONTEXT_RADIUS_KM;
return CONTEXT_RADIUS_STEPS.reduce((best, step) =>
Math.abs(step - value) < Math.abs(best - value) ? step : best,
);
}
function read() {
try {
const saved = globalThis.localStorage?.getItem(KEY);
return saved === null || saved === undefined
? DEFAULT_CONTEXT_RADIUS_KM
: nearestRadiusStep(saved);
} catch {
return DEFAULT_CONTEXT_RADIUS_KM;
}
}
/** The radius every nearby block uses, in km. */
export const contextRadiusKm = ref(read());
export function setContextRadiusKm(km) {
contextRadiusKm.value = nearestRadiusStep(km);
try {
globalThis.localStorage?.setItem(KEY, String(contextRadiusKm.value));
} catch {
// Without storage the choice lasts for this visit.
}
}
+31
View File
@@ -0,0 +1,31 @@
import { computed, ref } from 'vue';
// The Context panel's own search: one field in its header that narrows what
// the panel is showing (the selected item's details, and every list of what
// is nearby or in view) to what holds the typed text.
/** Whether the search field is showing. */
export const contextSearchOpen = ref(false);
/** The text as typed. */
export const contextSearchText = ref('');
/** The text to match against: trimmed, lower case, '' when not searching. */
export const contextNeedle = computed(() =>
contextSearchOpen.value ? contextSearchText.value.trim().toLowerCase() : '',
);
/** Whether any of the given strings holds the searched text (true when not searching). */
export function matchesContextSearch(...parts) {
const needle = contextNeedle.value;
if (!needle) return true;
return parts.some(
(part) =>
part !== null &&
part !== undefined &&
String(part).toLowerCase().includes(needle),
);
}
export function closeContextSearch() {
contextSearchOpen.value = false;
contextSearchText.value = '';
}
+27 -17
View File
@@ -240,25 +240,35 @@ export async function _clearLayersOutsideContextMode(
) {
const allowed = contextAllowedLayerIds(mode);
const pending = [];
for (const [layerId] of this._dataManager.layers || []) {
// Effective visibility: a disallowed layer still mid-ENABLING must be
// isolated too, or it settles ON inside the exclusive mode.
if (
!allowed.has(layerId) &&
this._dataManager.isEffectivelyEnabled(layerId)
) {
pending.push({
layerId,
transition: this._dataManager.setEnabled(layerId, false, {
notificationToken,
...(signal ? { signal } : {}),
}),
});
// Panels read this while their layer goes off (suspendsLayer): a layer
// isolation switches off is suspended, not switched off by the user.
const isolating = [];
let results;
try {
for (const [layerId] of this._dataManager.layers || []) {
// Effective visibility: a disallowed layer still mid-ENABLING must be
// isolated too, or it settles ON inside the exclusive mode.
if (
!allowed.has(layerId) &&
this._dataManager.isEffectivelyEnabled(layerId)
) {
if (!this._isolatingLayerIds.has(layerId)) {
this._isolatingLayerIds.add(layerId);
isolating.push(layerId);
}
pending.push({
layerId,
transition: this._dataManager.setEnabled(layerId, false, {
notificationToken,
...(signal ? { signal } : {}),
}),
});
}
}
results = await Promise.all(pending.map(({ transition }) => transition));
} finally {
for (const layerId of isolating) this._isolatingLayerIds.delete(layerId);
}
const results = await Promise.all(
pending.map(({ transition }) => transition),
);
const failed = pending
.filter(
({ layerId }, index) =>
+181
View File
@@ -0,0 +1,181 @@
/**
* @module ui/creditsView
* @description The attribution line, in the application's own DOM, for a
* renderer that does not draw its own credit display: what the renderer's
* credits port lists (its own credits, each base layer's, the layers' data
* credits). Inline credits are shown on the line at the bottom left; the
* rest are in the "Data attribution" list it opens. A credit is plain data
* (`src/render/contract/credits.d.ts`): its text is set as text, and a link
* or logo is kept only for a safe scheme.
*/
import { findCredits } from '../render/rendererOf.js';
import {
LINK_SCHEMES,
LOGO_SCHEMES,
safeUrl,
splitLink,
} from '../render/creditMarkup.js';
import { onLocaleChange, t } from '../i18n/index.js';
const PANEL_ID = 'gev-credits-panel';
/** The credits once each, in order: the same text and link are one. */
function distinct(list) {
const seen = new Set();
return list.filter((credit) => {
const key = `${credit?.text ?? ''}\u0000${credit?.href ?? ''}`;
if (!credit?.text || seen.has(key)) return false;
seen.add(key);
return true;
});
}
/** One credit as DOM: its logo or its text, linked when it has a link. */
function creditElement(doc, credit) {
const href = credit.href ? safeUrl(credit.href, LINK_SCHEMES) : null;
const logoUrl = credit.logoUrl ? safeUrl(credit.logoUrl, LOGO_SCHEMES) : null;
// Only the credit's linked words are the link, as the source wrote it.
if (href && !logoUrl && credit.linkText) {
const [before, words, after] = splitLink(credit);
const element = doc.createElement('span');
element.className = 'gev-credit';
const link = doc.createElement('a');
link.href = href;
link.target = '_blank';
link.rel = 'noopener noreferrer';
link.textContent = words;
element.append(before, link, after);
return element;
}
const element = doc.createElement(href ? 'a' : 'span');
element.className = 'gev-credit';
if (href) {
element.href = href;
element.target = '_blank';
element.rel = 'noopener noreferrer';
}
// A logo is drawn in place of the text, which names it (its alt text).
const logo = credit.logoUrl ? safeUrl(credit.logoUrl, LOGO_SCHEMES) : null;
if (logo) {
const image = doc.createElement('img');
image.className = 'gev-credit-logo';
image.src = logo;
image.alt = credit.text;
element.append(image);
} else element.textContent = credit.text;
return element;
}
/**
* Show `viewer`'s renderer credits at the bottom left of `root`'s page.
* @param {object} viewer The scene object, bound to its renderer.
* @param {{root?: HTMLElement}} [options] Where the line goes (the body).
* @returns {() => void} Removes it.
*/
export function mountCreditsView(viewer, { root = document.body } = {}) {
const credits = findCredits(viewer);
if (!credits || !root) return () => {};
const doc = root.ownerDocument;
const bar = doc.createElement('div');
bar.id = 'gev-credits';
bar.className = 'gev-credits';
// Takes focus back from an emptied list when the line has no link.
bar.tabIndex = -1;
const line = doc.createElement('span');
line.className = 'gev-credits-line';
const expand = doc.createElement('button');
expand.type = 'button';
expand.className = 'gev-credits-expand';
expand.setAttribute('aria-haspopup', 'dialog');
expand.setAttribute('aria-controls', PANEL_ID);
expand.setAttribute('aria-expanded', 'false');
const panel = doc.createElement('div');
panel.id = PANEL_ID;
panel.className = 'gev-credits-panel';
panel.setAttribute('role', 'dialog');
panel.hidden = true;
const header = doc.createElement('div');
header.className = 'gev-credits-header';
const title = doc.createElement('span');
title.className = 'gev-credits-title';
title.id = `${PANEL_ID}-title`;
panel.setAttribute('aria-labelledby', title.id);
const close = doc.createElement('button');
close.type = 'button';
close.className = 'gev-credits-close';
close.textContent = '×';
header.append(title, close);
const list = doc.createElement('ul');
list.className = 'gev-credits-list';
panel.append(header, list);
bar.append(line, expand);
root.append(bar, panel);
const label = () => {
expand.textContent = t('Data attribution');
title.textContent = t('Data provided by:');
close.setAttribute('aria-label', t('Close data attribution'));
};
const setOpen = (open, { focus = false } = {}) => {
panel.hidden = !open;
expand.setAttribute('aria-expanded', String(open));
if (open) close.focus();
else if (focus) expand.focus();
};
const render = (all) => {
const focused = panel.contains(doc.activeElement);
const shown = distinct(Array.isArray(all) ? all : []);
const inline = shown.filter((credit) => credit.inline);
const listed = shown.filter((credit) => !credit.inline);
line.replaceChildren();
inline.forEach((credit, i) => {
if (i) line.append(doc.createTextNode(' · '));
line.append(creditElement(doc, credit));
});
if (inline.length && listed.length) line.append(doc.createTextNode(' · '));
list.replaceChildren(
...listed.map((credit) => {
const item = doc.createElement('li');
item.append(creditElement(doc, credit));
return item;
}),
);
expand.hidden = listed.length === 0;
if (expand.hidden && !panel.hidden) {
// Focus in the list goes back to the line, not to the page.
setOpen(false);
if (focused) (line.querySelector('a') ?? bar).focus();
} else if (focused && !panel.contains(doc.activeElement)) {
// A link that focus was on was redrawn: focus stays in the list.
close.focus();
}
};
const onExpand = () => setOpen(panel.hidden);
const onClose = () => setOpen(false, { focus: true });
// Escape in the open list closes it (it takes focus as it opens).
const onKey = (event) => {
if (event.key !== 'Escape' || panel.hidden) return;
event.preventDefault();
setOpen(false, { focus: true });
};
expand.addEventListener('click', onExpand);
close.addEventListener('click', onClose);
panel.addEventListener('keydown', onKey);
label();
render(credits.list());
const offChange = credits.on('change', render);
const offLocale = onLocaleChange(label);
return () => {
offChange();
offLocale();
expand.removeEventListener('click', onExpand);
close.removeEventListener('click', onClose);
panel.removeEventListener('keydown', onKey);
bar.remove();
panel.remove();
};
}
+154
View File
@@ -0,0 +1,154 @@
import '../testSupport/registerDom.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import { mountCreditsView } from './creditsView.js';
import { bindRenderer } from '../render/rendererOf.js';
import { createStubRenderer } from '../render/stub/index.js';
function scene() {
document.body.replaceChildren();
const renderer = createStubRenderer();
const viewer = {};
bindRenderer(viewer, renderer);
return { viewer, renderer };
}
test("the renderer's credits show on the line, and the rest in the list it opens", () => {
const { viewer, renderer } = scene();
renderer.credits.addStatic({
text: 'Google',
href: 'https://maps.google.com',
inline: true,
});
const off = mountCreditsView(viewer);
const line = document.querySelector('#gev-credits .gev-credits-line');
assert.equal(line.textContent, 'Google');
assert.equal(line.querySelector('a').href, 'https://maps.google.com/');
const expand = document.querySelector('.gev-credits-expand');
assert.equal(expand.hidden, true, 'nothing to list yet');
const remove = renderer.credits.addStatic({ text: 'Wildlife: iNaturalist' });
renderer.credits.addStatic({ text: 'Wildlife: iNaturalist' });
renderer.credits.addStatic({ text: 'OSM', href: 'javascript:alert(1)' });
assert.equal(expand.hidden, false);
assert.equal(expand.textContent, 'Data attribution');
const panel = document.getElementById('gev-credits-panel');
assert.equal(panel.hidden, true);
expand.click();
assert.equal(panel.hidden, false);
assert.equal(expand.getAttribute('aria-expanded'), 'true');
const items = [...panel.querySelectorAll('li')].map((li) => li.textContent);
assert.deepEqual(items, ['Wildlife: iNaturalist', 'OSM'], 'once each');
assert.equal(panel.querySelector('li:last-child a'), null, 'unsafe link');
panel.dispatchEvent(
new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }),
);
assert.equal(panel.hidden, true);
assert.equal(document.activeElement, expand, 'focus goes back');
remove();
assert.equal(
[...panel.querySelectorAll('li')].length,
2,
'a duplicate still credits it',
);
off();
assert.equal(document.getElementById('gev-credits'), null);
assert.equal(document.getElementById('gev-credits-panel'), null);
});
test('a credit with a logo is drawn as the logo, named by its text', () => {
const { viewer, renderer } = scene();
renderer.credits.addStatic({
text: 'Google',
logoUrl: 'https://example.com/logo.png',
inline: true,
});
const off = mountCreditsView(viewer);
const credit = document.querySelector('#gev-credits .gev-credit');
const logo = credit.querySelector('img');
assert.equal(logo.src, 'https://example.com/logo.png');
assert.equal(logo.alt, 'Google', 'screen readers and copies keep the name');
assert.equal(credit.textContent, '', 'the logo stands in place of the text');
off();
});
test('a viewer with no renderer shows no credits line', () => {
document.body.replaceChildren();
const off = mountCreditsView({});
assert.equal(document.getElementById('gev-credits'), null);
off();
});
test('the credits line is placed wherever the renderer’s own display is', async () => {
const { readFileSync, readdirSync } = await import('node:fs');
const dir = new URL('./styles/', import.meta.url);
const missing = [];
for (const name of readdirSync(dir).filter((f) => f.endsWith('.css'))) {
const css = readFileSync(new URL(name, dir), 'utf8').replace(
/\/\*[\s\S]*?\*\//g,
'',
);
const parts = [...css.matchAll(/([^{};]+)\{/g)]
.map((match) => match[1].replace(/\s+/g, ' ').trim())
.filter((selector) => !selector.startsWith('@'))
.flatMap((selector) =>
selector.split(/,(?![^(]*\))/).map((part) => part.trim()),
);
// The display's own selectors, without its inner parts, each with the
// line's counterpart in the same stylesheet.
for (const part of parts)
if (
/#cesium-credits$/.test(part) &&
!parts.includes(part.replace('#cesium-credits', '#gev-credits'))
)
missing.push(`${name}: ${part}`);
}
assert.deepEqual(missing, []);
});
test('focus in the list stays in it as it redraws, and goes to the line as it empties', () => {
const { viewer, renderer } = scene();
renderer.credits.addStatic({ text: 'Esri', inline: true });
const remove = renderer.credits.addStatic({
text: 'OSM',
href: 'https://www.openstreetmap.org/copyright',
});
const off = mountCreditsView(viewer);
const panel = document.getElementById('gev-credits-panel');
document.querySelector('.gev-credits-expand').click();
panel.querySelector('li a').focus();
const removeOther = renderer.credits.addStatic({ text: 'NOAA' });
assert.equal(panel.hidden, false);
assert.ok(panel.contains(document.activeElement), 'still in the list');
remove();
removeOther();
assert.equal(panel.hidden, true);
assert.equal(
document.activeElement,
document.getElementById('gev-credits'),
'a line with no link takes it',
);
off();
});
test('a credit with linked words links only those words', () => {
const { viewer, renderer } = scene();
renderer.credits.addStatic({
text: 'Street Level: imagery © Mapillary contributors, CC BY-SA 4.0',
href: 'https://www.mapillary.com/',
linkText: 'Mapillary',
inline: true,
});
const off = mountCreditsView(viewer);
const credit = document.querySelector('#gev-credits .gev-credit');
const link = credit.querySelector('a');
assert.equal(link.textContent, 'Mapillary');
assert.equal(link.href, 'https://www.mapillary.com/');
assert.equal(
credit.textContent,
'Street Level: imagery © Mapillary contributors, CC BY-SA 4.0',
);
off();
});
+3
View File
@@ -57,6 +57,9 @@ test('real runner and facade use visual settings, preserve visibility and return
camera: { moveEnd: { addEventListener() {} } },
clock: { onTick: { addEventListener: () => () => {} } },
scene: { canvas: new EventTarget() },
get canvas() {
return this.scene.canvas;
},
};
try {
const runner = createGevActionRunner({ styleManager: owner, viewer, dataManager: {} });
+49 -12
View File
@@ -1,4 +1,11 @@
import { getScopeMaskFeather, isScopeMaskEnabled, setScopeMaskEnabled, setScopeMaskFeather } from '../scopeMask.js';
import {
getScopeMaskFeather,
getScopeMaskOpacity,
isScopeMaskEnabled,
setScopeMaskEnabled,
setScopeMaskFeather,
setScopeMaskOpacity,
} from '../scopeMask.js';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import test from 'node:test';
@@ -254,6 +261,7 @@ test('Display and voice HUD routes preserve explicit Cyber entry and exit author
const viewer = {
camera: { moveEnd: { addEventListener() {} } },
clock: { onTick: { addEventListener: () => () => {} } },
canvas: eventSource,
scene: { canvas: eventSource },
};
const runVoiceAction = createGevActionRunner({
@@ -282,7 +290,7 @@ test('scope choice and expanded feather survive every HUD layout and both restor
let shown = null;
owner.store = { publish: (view) => (shown = view.scope) };
await owner.restoreShareState({ scopeEnabled: false, scopeFeatherPct: 200 });
assert.deepEqual(shown, { enabled: false, featherPct: 200 });
assert.deepEqual(shown, { enabled: false, featherPct: 200, opacityPct: 100 });
for (const layout of ['minimal', 'cyber', 'tactical']) {
owner._setHudVariant(layout, { applyVisualDefaults: true });
assert.equal(isScopeMaskEnabled(), false, layout);
@@ -292,10 +300,44 @@ test('scope choice and expanded feather survive every HUD layout and both restor
await owner.applyVisualState({ scope: { enabled: true, featherPct: 175 } });
assert.equal(isScopeMaskEnabled(), true);
assert.equal(getScopeMaskFeather(), 1.75);
assert.deepEqual(shown, { enabled: true, featherPct: 175 });
assert.deepEqual(shown, { enabled: true, featherPct: 175, opacityPct: 100 });
await owner.applyVisualState({ scope: { featherPct: 500 } });
assert.equal(getScopeMaskFeather(), 2);
assert.deepEqual(shown, { enabled: true, featherPct: 200 });
assert.deepEqual(shown, { enabled: true, featherPct: 200, opacityPct: 100 });
});
test('a shared scope opacity is restored and rides in the next share state', async (t) => {
const { owner } = styleOwner(t, 'tactical');
const previous = getScopeMaskOpacity();
t.after(() => setScopeMaskOpacity(previous));
Object.assign(owner.services, {
setScopeMaskEnabled() {},
setScopeMaskFeather() {},
setScopeMaskOpacity,
});
let shown = null;
owner.store = { publish: (view) => (shown = view.scope) };
await owner.restoreShareState({ scopeOpacityPct: 60 });
assert.equal(getScopeMaskOpacity(), 0.6);
assert.equal(shown.opacityPct, 60);
// A state without it leaves the opacity alone.
await owner.restoreShareState({ scopeFeatherPct: 80 });
assert.equal(getScopeMaskOpacity(), 0.6);
assert.equal(shown.opacityPct, 60);
Object.assign(owner.services, {
getDetectionTuning: () => ({ allocationStrategy: 'ELASTIC' }),
getDetectionMode: () => 'OFF',
isScopeMaskEnabled: () => true,
getScopeMaskFeather: () => 0.8,
getScopeMaskOpacity,
getScopeTerminusOverride: () => null,
});
owner.readCelestialRing = () => null;
assert.equal(owner._readShareState().options.scopeOpacityPct, 60);
// A link asking for less than the floor opens at the floor, and says so.
await owner.restoreShareState({ scopeOpacityPct: 20 });
assert.equal(getScopeMaskOpacity(), 0.5);
assert.equal(owner._readShareState().options.scopeOpacityPct, 50);
});
test('a scene shot saved with the retired Snow style plays on Normal', async (t) => {
@@ -650,8 +692,7 @@ test('the Display selector, voice schema and final stylesheet expose Cyber', ()
const hud = read('../hud.js');
const hudView = read('./views/IntelHudView.vue');
const detection = read('../data/detection.js');
const civilRendering = read('../layers/flights/rendering.js');
const militaryRendering = read('../layers/military/rendering.js');
const aircraftModels = read('../data/aircraftModelLayer.js');
const setHud = GEV_ACTION_SCHEMAS.find((schema) => schema.name === 'set_hud');
assert.match(display, /<option value="cyber">\{\{ t\('Cyber'\) \}\}<\/option>/);
@@ -701,12 +742,8 @@ test('the Display selector, voice schema and final stylesheet expose Cyber', ()
);
assert.doesNotMatch(detection, /sonarActive \? 1 : 0/);
assert.match(
civilRendering,
/alpha: flightState\._irBoost \? 1 : treatment\.alpha/,
);
assert.match(
militaryRendering,
/baseAlpha:[\s\S]*?alpha: flightState\._irBoost \? 1 : treatment\.alpha/,
aircraftModels,
/alpha: state\._irBoost\s*\?\s*1\s*:\s*aircraftTreatmentAlpha\(/,
);
assert.match(
cyberStyles,
+27
View File
@@ -105,6 +105,11 @@ export class DisplayBindings {
this._setScope({ featherPct: value });
this._syncShareState();
},
setScopeOpacity: (value) => {
this.shareLinkManager?.claimRestoreLane?.('visual');
this._setScope({ opacityPct: Number(value) });
this._syncShareState();
},
setSharpenIntensity: (pct) => {
this.shareLinkManager?.claimRestoreLane?.('visual');
this._setSharpenIntensity(pct);
@@ -168,6 +173,28 @@ export class DisplayBindings {
this._syncModels3dModeRow();
},
setModelsMode: (mode) => this._setModels3dMode(mode),
// Back to the out-of-the-box look: Normal style, the global post
// defaults (bloom, sharpen, HUD, labels, celestial), scope on at full
// feather and opacity, 3D aircraft on in Proximity.
resetVisual: () => {
this.shareLinkManager?.claimRestoreLane?.('visual');
this.setStyle('normal', { userInitiated: true });
// The HUD layout follows the Normal style, as choosing it does: the
// Cyber HUD stays Cyber.
this._applyGlobalPostDefaults({ keepHudVariant: true });
this._setDetectionAllocation('ELASTIC');
this._setScope({ enabled: true, featherPct: 100, opacityPct: 100 });
this._setModels3dEnabled(true);
this._setModels3dMode('proximity');
this._syncModels3dModeRow?.();
// Inside Contacts the detection shown is lent for the session, and
// leaving puts back the state from before. A reset there is the user's
// choice, so the defaults become what leaving puts back and what a
// share link carries.
this.claimDetection();
this._adoptDetectionAsRestore?.();
this._syncShareState();
},
});
this._detachDisplayControls = () => store.detach(token);
}
+31
View File
@@ -0,0 +1,31 @@
/** A row of a group added to the Display panel. */
export type DisplayGroupRow =
| {
kind: 'toggle';
id: string;
label: string;
icon?: string;
title?: string;
checked: boolean;
onChange(checked: boolean): void;
}
| {
kind: 'slider';
id: string;
label: string;
min: number;
max: number;
/** Shown in percent. */
value: number;
onChange(value: number): void;
}
| { kind: 'note'; id: string; text: string };
/**
* Show the group `id` on the page's Display panel, under Effects, in place
* where it is shown already; null takes it away.
*/
export function publishDisplayGroup(
id: string,
group: { rows: DisplayGroupRow[] } | null,
): void;
+20
View File
@@ -0,0 +1,20 @@
/**
* Groups of controls added to the Display panel, under
* Effects: toggles, sliders and notes, each answered by whoever added it.
*/
import { applicationPinia } from './vueRuntime.js';
import { useDisplayStore } from './stores/display.js';
/**
* Show the group `id` on the page's Display panel as `group` describes it,
* in place where it is shown already; null takes it away. A row is a
* `toggle` (`{kind, id, label, icon?, title?, checked, onChange(checked)}`),
* a `slider` (`{kind, id, label, min, max, value, onChange(value)}`, its
* value shown in percent) or a `note` (`{kind, id, text}`). Publish it again
* whenever what it shows changes.
* @param {string} id
* @param {?{rows: object[]}} group
*/
export function publishDisplayGroup(id, group) {
useDisplayStore(applicationPinia()).publishGroup(id, group);
}
+20
View File
@@ -0,0 +1,20 @@
// src/ui/displayGroups.test.mjs — added groups reach the Display
// panel's store on the page's Pinia.
import test from 'node:test';
import assert from 'node:assert/strict';
import { publishDisplayGroup } from './displayGroups.js';
import { useDisplayStore } from './stores/display.js';
import { applicationPinia } from './vueRuntime.js';
test('publishDisplayGroup shows a group on the page’s Display panel, and takes it away', () => {
const store = useDisplayStore(applicationPinia());
publishDisplayGroup('conditions', {
rows: [{ kind: 'note', id: 'status', text: 'Nothing here' }],
});
assert.deepEqual(
store.groups.map((g) => [g.id, g.rows.length]),
[['conditions', 1]],
);
publishDisplayGroup('conditions', null);
assert.deepEqual(store.groups, []);
});
+147 -11
View File
@@ -108,7 +108,11 @@ test('bloom and sharpen render their state, slider and readout', async (t) => {
await nextTick();
assert.equal($('bloom-toggle').classList.contains('active'), false);
assert.equal($('bloom-slider-row').classList.contains('visible'), false);
assert.equal($('bloom-intensity-value').textContent, '140%', 'the amount stays');
assert.equal(
$('bloom-intensity-value').textContent,
'140%',
'the amount stays',
);
});
test('a publish never rewrites a slider the user is dragging', async (t) => {
@@ -314,6 +318,73 @@ test('Scope and Celestial render what VisualSettings shows', async (t) => {
assert.equal(celestial.title, 'Celestial ring — reveal the full globe');
});
test('scope opacity renders what VisualSettings shows and sets the mask', async (t) => {
const { store, $ } = fixture(t);
const { owner } = settings(store);
const mask = { opacity: 1 };
owner.services = {
...owner.services,
setScopeMaskEnabled() {},
setScopeMaskOpacity: (value) => (mask.opacity = value),
};
assert.equal($('scope-opacity-slider').value, '100');
assert.equal($('scope-opacity-value').textContent, '100%');
owner._setScope({ opacityPct: 62.4 });
await nextTick();
assert.equal(mask.opacity, 0.62);
assert.equal($('scope-opacity-slider').value, '62');
assert.equal($('scope-opacity-value').textContent, '62%');
assert.equal(store.view.scope.opacityPct, 62);
// No fainter than the floor, where the view would read as Scope off.
owner._setScope({ opacityPct: 10 });
await nextTick();
assert.equal(mask.opacity, 0.5, 'floored');
assert.equal($('scope-opacity-value').textContent, '50%');
assert.equal($('scope-opacity-slider').min, '50');
// A value that is not a number changes nothing.
owner._setScope({ opacityPct: Number.NaN });
await nextTick();
assert.equal($('scope-opacity-value').textContent, '50%');
owner._setScope({ opacityPct: 180 });
await nextTick();
assert.equal(mask.opacity, 1, 'clamped');
assert.equal($('scope-opacity-value').textContent, '100%');
owner._setScope({ opacityPct: 70 }, { apply: false });
await nextTick();
assert.equal(mask.opacity, 1, 'only shown');
assert.equal($('scope-opacity-value').textContent, '70%');
owner._setScope({ enabled: false });
await nextTick();
assert.equal($('scope-opacity-slider').disabled, true, 'off with the scope');
assert.equal(store.view.scope.opacityPct, 70, 'kept while off');
});
test('the Visual panel groups its controls and words its on/off pills', (t) => {
const { $ } = fixture(t);
const panel = $('pp-toggles');
assert.deepEqual(
[
...panel.querySelectorAll(
'.pp-section-heading, .visual-presets__heading',
),
].map((el) => el.textContent.trim()),
['Look', 'MAP SOURCE 3D', 'Overlay', 'Effects'],
);
assert.equal(panel.querySelector('.pp-header-label').textContent, 'VISUAL');
const body = panel.querySelector('.pp-panel-body');
assert.equal(body.style.getPropertyValue('--pp-pill-on'), '"ON"');
assert.equal(body.style.getPropertyValue('--pp-pill-off'), '"OFF"');
const reset = panel.querySelector('.pp-reset-btn');
assert.equal(reset, body.lastElementChild, 'the reset closes the panel');
assert.equal(reset.textContent.trim(), 'restart_altReset to default');
});
test('the 3D aircraft group renders what AircraftDisplay shows', async (t) => {
const { store, $ } = fixture(t);
const params = [];
@@ -331,7 +402,10 @@ test('the 3D aircraft group renders what AircraftDisplay shows', async (t) => {
assert.equal(coreClasses(button), 'pp-toggle-btn active');
assert.equal(button.getAttribute('aria-pressed'), 'true');
assert.equal(row.classList.contains('visible'), true);
assert.equal($('models3d-mode-proximity').getAttribute('aria-checked'), 'true');
assert.equal(
$('models3d-mode-proximity').getAttribute('aria-checked'),
'true',
);
// The button leaves the row to its own sync.
owner._setModels3dEnabled(false);
@@ -347,7 +421,10 @@ test('the 3D aircraft group renders what AircraftDisplay shows', async (t) => {
await nextTick();
assert.equal(all.classList.contains('active'), true);
assert.equal(all.getAttribute('aria-checked'), 'true');
assert.equal($('models3d-mode-proximity').classList.contains('active'), false);
assert.equal(
$('models3d-mode-proximity').classList.contains('active'),
false,
);
assert.deepEqual(params.at(-1), ['military', { models3dMode: 'all' }]);
owner._syncModels3dFromLayerState({
@@ -376,12 +453,18 @@ test('the Draw controls render what the draw tool publishes', async (t) => {
assert.equal(segment('area').getAttribute('aria-label'), 'Area');
assert.equal(segment('area').title, 'Area');
assert.equal(segment('area').textContent, 'pentagon');
const swatch = (color) => document.querySelector(`#draw-colors [data-color="${color}"]`);
const swatch = (color) =>
document.querySelector(`#draw-colors [data-color="${color}"]`);
assert.equal(swatch('primary').getAttribute('aria-checked'), 'true');
assert.equal(swatch('amber').getAttribute('aria-label'), 'Amber');
assert.equal($('draw-hint').textContent, '');
store.publishDraw({ active: true, shape: 'line', color: 'amber', hint: 'Click to add points.' });
store.publishDraw({
active: true,
shape: 'line',
color: 'amber',
hint: 'Click to add points.',
});
await nextTick();
assert.equal(swatch('amber').getAttribute('aria-checked'), 'true');
assert.equal(swatch('primary').classList.contains('active'), false);
@@ -411,12 +494,11 @@ test('the imported files render what the file import publishes and keep focus',
const viewer = {
container: document.createElement('div'),
scene: { requestRender() {} },
dataSources: { add: async (ds) => ds, remove: () => true },
};
const tool = initGeoFileImport({
viewer,
load: async (file) => ({
dataSource: { show: true },
drawing: { show: true, destroy() {} },
name: file.name,
format: file.name.endsWith('.kml') ? 'kml' : 'geojson',
entityCount: 2,
@@ -477,7 +559,10 @@ test('the imported files render what the file import publishes and keep focus',
assert.equal(document.activeElement === button(first, 'toggle'), true);
assert.equal(button(first, 'toggle').getAttribute('aria-pressed'), 'true');
assert.equal(button(first, 'fly').title, 'Fly to <b>a</b>.geojson');
assert.equal(button(first, 'remove').getAttribute('aria-label'), 'Remove <b>a</b>.geojson');
assert.equal(
button(first, 'remove').getAttribute('aria-label'),
'Remove <b>a</b>.geojson',
);
await press(button(first, 'remove'));
assert.equal(rowsNow().length, 1);
@@ -593,7 +678,11 @@ test('VisualSettings publishes a style’s parameters and writes a moved slider
assert.equal(store.parameters, null, 'the sliders go with their owner');
assert.equal($('param-slider-panel').classList.contains('active'), false);
assert.equal(store.act('setStyleParameter', 'grainAmt', 0.2), undefined);
assert.equal(owner.stages.noir.uniforms.grainAmt, 0.3, 'a stopped owner no longer answers');
assert.equal(
owner.stages.noir.uniforms.grainAmt,
0.3,
'a stopped owner no longer answers',
);
// An older owner's stop leaves a newer owner's rows.
const newer = { style: 'noir', rows: [] };
owner._parameters = { style: 'noir', rows: [] };
@@ -605,10 +694,16 @@ test('VisualSettings publishes a style’s parameters and writes a moved slider
test('the four Cockpit groups teleport to the published slots and back to their places', async (t) => {
const { store, $ } = fixture(t);
const groupOf = (id) => $(id).closest('.pp-toggle-group') ?? $(id);
const ids = ['hud-toggle', 'detection-toggle', 'param-slider-panel', 'models3d-toggle'];
const ids = [
'hud-toggle',
'detection-toggle',
'param-slider-panel',
'models3d-toggle',
];
const body = $('pp-toggles').querySelector('.pp-panel-body');
const order = () =>
[...body.children].filter((el) => el.matches('.pp-toggle-group, #param-slider-panel'))
[...body.children]
.filter((el) => el.matches('.pp-toggle-group, #param-slider-panel'))
.map((el) => el.id || el.querySelector('[id]')?.id);
const home = order();
const popover = document.body.appendChild(document.createElement('div'));
@@ -707,3 +802,44 @@ test('the real portal lays out once the groups have moved and puts back the focu
await nextTick();
assert.deepEqual(layouts, [true]);
});
test('a group added to Effects shows its toggles, notes and sliders, and goes', async (t) => {
const { store, $ } = fixture(t);
const changes = [];
store.publishGroup('conditions', {
rows: [
{
kind: 'toggle',
id: 'live',
icon: 'partly_cloudy_day',
label: 'Live',
title: 'Live conditions',
checked: true,
onChange: (on) => changes.push(['live', on]),
},
{ kind: 'note', id: 'status', text: 'Nothing here' },
{
kind: 'slider',
id: 'level',
label: 'Level',
min: 0,
max: 100,
value: 40,
onChange: (value) => changes.push(['level', value]),
},
],
});
await nextTick();
const toggle = $('conditions-live-toggle');
assert.ok(toggle, 'its toggle is drawn');
assert.equal(toggle.checked, true);
assert.equal(toggle.closest('label').title, 'Live conditions');
assert.equal($('conditions-status').textContent.trim(), 'Nothing here');
assert.equal($('conditions-level-value').textContent.trim(), '40%');
toggle.checked = false;
toggle.dispatchEvent(new Event('change'));
assert.deepEqual(changes, [['live', false]]);
store.publishGroup('conditions', null);
await nextTick();
assert.equal($('conditions-group'), null, 'gone once removed');
});
+123
View File
@@ -8,6 +8,7 @@ import { createApp, h, nextTick } from 'vue';
import { createPinia } from 'pinia';
import { useDisplayStore } from './stores/display.js';
import { DisplayBindings } from './displayBindings.js';
import { VisualSettings } from './visualSettings.js';
import CommandDockView from './views/CommandDockView.vue';
import DisplayControlsView from './views/DisplayControlsView.vue';
import DrawControls from './views/panels/DrawControls.vue';
@@ -231,3 +232,125 @@ test('several owners answer their own actions, the newest first', (t) => {
['display', 'toggleBloom'],
]);
});
test('the Visual panel’s scope opacity, reset and presets call their actions', async (t) => {
const store = mount(t);
const { calls } = recorder(store);
const selected = [];
store.connectMapSource({ select: async (id) => selected.push(id) });
store.publishMapSource({
status: { text: 'OSM', warn: false },
chips: [
{ id: 'photoreal', label: 'Google 3D', available: false },
{ id: 'osm', label: 'OSM', available: true, active: true },
],
});
await nextTick();
input($('scope-opacity-slider'), 60);
document.querySelector('#pp-toggles .pp-reset-btn').click();
const presets = document.querySelector('#pp-toggles .visual-presets');
presets.querySelector('[data-style="noir"]').click();
const chips = presets.querySelectorAll('.visual-presets__chip');
chips[0].click();
chips[1].click();
assert.deepEqual(calls, [
['setScopeOpacity', 60],
['resetVisual'],
['setStyle', 'noir'],
]);
assert.deepEqual(selected, ['osm'], 'an unavailable source is not selected');
// The presets follow the published style, as the dock's do.
assert.equal(
presets.querySelector('[data-style="normal"]').getAttribute('aria-pressed'),
'true',
);
store.publishStyle({ name: 'noir', label: 'NOIR' });
await nextTick();
assert.equal(
presets.querySelector('[data-style="noir"]').getAttribute('aria-pressed'),
'true',
);
assert.equal(
presets.querySelector('[data-style="normal"]').getAttribute('aria-pressed'),
'false',
);
// The dock keeps its own presets and map source beside them.
assert.ok(
document.querySelector('#control-panel .style-btn[data-style="noir"]'),
);
assert.ok($('map-stack-chips'));
});
test('DisplayBindings sets the scope opacity and resets Visual to its defaults', (t) => {
const store = mount(t);
const calls = [];
const bindings = new DisplayBindings({
viewer: null,
services: { isScopeMaskEnabled: () => true, cycleDetectionMode: () => {} },
elements: { _locationSearch: document.createElement('input') },
operations: {
setStyle: (style, options) => calls.push(['style', style, options]),
_applyGlobalPostDefaults: (options) =>
calls.push(['postDefaults', options]),
_setDetectionAllocation: (value) => calls.push(['allocation', value]),
_setScope: (scope) => calls.push(['scope', scope]),
_setModels3dEnabled: (on) => calls.push(['models3d', on]),
_setModels3dMode: (mode) => calls.push(['models3dMode', mode]),
_syncModels3dModeRow: () => calls.push(['models3dRow']),
_syncShareState: () => calls.push(['share']),
_adoptDetectionAsRestore: () => calls.push(['adoptDetection']),
},
readState: () => ({
shareLinkManager: {
claimRestoreLane: (lane) => calls.push(['claim', lane]),
},
}),
claimDetection: () => calls.push(['claimDetection']),
displayStore: store,
});
bindings._initUI();
t.after(() => bindings.destroy());
calls.length = 0;
input($('scope-opacity-slider'), 65);
assert.deepEqual(calls, [
['claim', 'visual'],
['scope', { opacityPct: 65 }],
['share'],
]);
calls.length = 0;
document.querySelector('#pp-toggles .pp-reset-btn').click();
assert.deepEqual(calls, [
['claim', 'visual'],
['style', 'normal', { userInitiated: true }],
['postDefaults', { keepHudVariant: true }],
['allocation', 'ELASTIC'],
['scope', { enabled: true, featherPct: 100, opacityPct: 100 }],
['models3d', true],
['models3dMode', 'proximity'],
['models3dRow'],
['claimDetection'],
['adoptDetection'],
['share'],
]);
});
test('a reset inside Contacts makes the shown detection what leaving puts back', () => {
const adopt = VisualSettings.prototype.adoptDetectionAsRestore;
const live = { detectionMode: 'DENSE', densityPct: 75 };
const inContacts = {
_contactsDetectionRestore: { mode: 'OFF', densityPct: 50 },
getDetectionState: () => live,
};
adopt.call(inContacts);
assert.deepEqual(inContacts._contactsDetectionRestore, {
mode: 'DENSE',
densityPct: 75,
});
// Outside Contacts there is no saved state to change.
const outside = {
_contactsDetectionRestore: null,
getDetectionState: () => live,
};
adopt.call(outside);
assert.equal(outside._contactsDetectionRestore, null);
});
+363
View File
@@ -0,0 +1,363 @@
import { resolvePickedContext } from '../data/pickedContext.js';
import { followedOf, onFollowChanged } from '../data/followed.js';
import { fromDegreesInto } from '../geo/ellipsoid.js';
import { inputFor } from '../input/dispatcher.js';
import {
isTrackingClickGesture,
isTrackingSelectionGesture,
} from '../data/trackingClickGesture.js';
import { applicationHooksOf } from '../render/applicationHooks.js';
import { findCamera, rendererOf } from '../render/rendererOf.js';
import { useCockpitStore } from './stores/cockpit.js';
import { useEntityCardStore } from './stores/entityCard.js';
import { useOmnibarStore } from './stores/omnibar.js';
import { usePanelChromeStore } from './stores/panelChrome.js';
import { useVoiceStore } from './stores/voice.js';
/** Camera distance (m) that frames an item of each kind. */
const FRAME_RANGE = Object.freeze({
aircraft: 30_000,
vessel: 9_000,
satellite: 2_500_000,
earthquake: 120_000,
storm: 1_500_000,
fire: 20_000,
'fire perimeter': 40_000,
});
const DEFAULT_RANGE = 8_000;
/**
* Items the camera can follow: their layers follow through the camera port
* with a key naming the item (src/data/followed.js). A vessel is flown to.
*/
const FOLLOWABLE = new Set(['flights', 'military', 'satellites']);
/**
* Connects the Context panel's entity card to the globe: a click on anything a
* layer can identify opens its card, and the card's actions fly to it, follow
* it or ask GEV about it. Layers keep their own click behaviour; this listens
* alongside them.
* @param {object} options
* @param {object} options.viewer Cesium viewer.
* @param {() => object} options.getDataManager Layer lifecycle.
* @param {object} options.pinia
* @param {(viewer: object, x: number, y: number) => ({lat: number, lon: number}|null)} [options.pickWorld]
* The ground under a normalized screen point; the view's centre falls back
* to the point under the camera without it.
* @param {(lat: number, lon: number) => Promise<object>} [options.regionalBrief]
* The app's regional brief service, for the weather and news Context shows.
* @param {(x: number, y: number) => object|null} [options.overlayHit]
* The overlay card under a screen point, if any (a vessel's, a fire's).
* @returns {() => void} disconnects
*/
export function installEntityContext({
viewer,
getDataManager,
pinia,
pickWorld,
regionalBrief,
overlayHit,
}) {
const store = useEntityCardStore(pinia);
const omnibar = useOmnibarStore(pinia);
const voice = useVoiceStore(pinia);
const cockpitStore = useCockpitStore(pinia);
const chrome = usePanelChromeStore(pinia);
/** Whether Context is open; a closed panel reads nothing. */
const isOpen = () =>
chrome.panels['global-context-panel']?.collapsed === false;
const doc = globalThis.document;
let disposed = false;
// The renderer's camera; looked up on use, as a renderer can be bound
// after Context is installed.
const camera = () => findCamera(viewer);
/** Whether the camera follows this card's item (the follow's key). */
const followsCard = (card, followed = followedOf(viewer)) => {
const key = followed?.key;
if (!key || !card) return false;
return key === card.key || key === `${card.layerId}:${card.identity?.id}`;
};
const inCockpit = () =>
Boolean(doc?.body?.classList.contains('cockpit-mode'));
function openPanel() {
const button = doc?.querySelector(
'.ui-rail--right .ui-rail__item[data-rail-item="global-context-panel"]',
);
if (button && button.getAttribute('aria-pressed') !== 'true')
button.click();
}
function flyTo(card) {
const port = camera();
if (!port || !Number.isFinite(card?.lat) || !Number.isFinite(card?.lon))
return;
const height = Number.isFinite(card.altitudeM) ? card.altitudeM : 0;
const range = FRAME_RANGE[card.kind] ?? DEFAULT_RANGE;
port.flyToBounds(
{
center: fromDegreesInto(card.lon, card.lat, Math.max(0, height), {
x: 0,
y: 0,
z: 0,
}),
radius: 1,
},
{
offset: {
heading: port.pose().heading,
pitch: ((card.kind === 'satellite' ? -90 : -45) * Math.PI) / 180,
range,
},
durationS: 2,
},
);
}
function follow(card) {
const run = omnibar.runner;
if (!run || !FOLLOWABLE.has(card.layerId)) return flyTo(card);
Promise.resolve(
run('track_entity', {
query: card.identity.id || card.title,
layerId: card.layerId,
}),
).catch(() => {});
}
// Closing the card lets go of the camera, when the camera follows the
// card's own item and nothing else took it over since.
function letGo(card) {
if (!followsCard(card)) return;
// Only the card's own layer lets go, as the person's own action; other
// layers' selections stay as they are.
const layer = getDataManager()?.layers?.get?.(card.layerId);
try {
layer?.module?.stopTracking?.({ origin: 'user' });
} catch {
// A layer going away meanwhile has nothing left to let go of.
}
}
// Aircraft can be flown from, and a satellite ridden in the orbital view:
// track the craft, then enter Cockpit on it. Only layers the tracking
// action can follow are offered (local ADS-B cannot be tracked).
const COCKPIT_LAYERS = new Set(['flights', 'military', 'satellites']);
async function cockpit(card) {
try {
await enterCockpit(card);
} catch {
// The craft left the feed or tracking failed; the card stays as it is.
}
}
async function enterCockpit(card) {
const run = omnibar.runner;
if (!run || !COCKPIT_LAYERS.has(card.layerId)) return;
await run('track_entity', {
query: card.identity.id || card.title,
layerId: card.layerId,
});
if (disposed) return;
if (card.layerId !== 'satellites') {
await run('control_cockpit', { action: 'enter' });
return;
}
// A satellite is ridden through the app's own Cockpit entry, which offers
// the orbital view once the satellite is tracked. Wait for it to say so;
// if it never does (a class that cannot be ridden), nothing is entered.
for (let tries = 0; tries < 40; tries++) {
// Another pick or a closed card in the meantime calls the ride off.
if (disposed || store.card?.key !== card.key) return;
const presence = cockpitStore.presence;
if (presence?.entryAvailable && presence.entryKind === 'satellite') {
doc?.getElementById('cockpit-entry')?.click();
return;
}
await new Promise((resolve) => setTimeout(resolve, 100));
}
}
function askText(prompt) {
voice.controls?.emit('chat-restore');
voice.controls?.emit('chat-prompt', prompt);
voice.controls?.emit('chat-submit');
}
function ask(card) {
const where =
Number.isFinite(card.lat) && Number.isFinite(card.lon)
? ` at ${card.lat.toFixed(3)}, ${card.lon.toFixed(3)}`
: '';
const prompt = `Tell me about the ${card.kind} ${card.title} (${card.layerName})${where}, and what is around it.`;
voice.controls?.emit('chat-restore');
voice.controls?.emit('chat-prompt', prompt);
voice.controls?.emit('chat-submit');
}
store.connect({
dataManager: getDataManager,
openPanel,
flyTo,
follow,
letGo,
isOpen,
regionalBrief,
// The renderer's card previews, when it has them.
previews: () => applicationHooksOf(rendererOf(viewer)).cardPreviews ?? null,
ask,
askText,
cockpit,
canCockpit: (card) =>
Boolean(omnibar.runner) && COCKPIT_LAYERS.has(card?.layerId),
canFollow: (card) => FOLLOWABLE.has(card?.layerId),
// Where the camera is, so a search prefers what is close by.
here: () => {
const pose = camera()?.pose();
return pose && Number.isFinite(pose.lat) && Number.isFinite(pose.lon)
? { lat: pose.lat, lon: pose.lon }
: null;
},
});
// What the camera shows, for the Context panel to describe when nothing is
// picked: the ground under the middle of the screen, the view's bounds and
// the height. Read when the camera settles, not every frame.
const readView = () => {
const port = camera();
if (!port || !isOpen()) return;
const pose = port.pose();
if (![pose.lat, pose.lon, pose.height].every(Number.isFinite)) return;
const middle = pickWorld?.(viewer, 0.5, 0.5);
const center = middle
? { lat: middle.lat, lon: middle.lon }
: { lat: pose.lat, lon: pose.lon };
const rect = port.viewRectangle() ?? {
west: -180,
south: -90,
east: 180,
north: 90,
};
store.setView({ center, rect, heightM: pose.height });
};
// Read when the camera settles. A camera that keeps moving (following an
// aircraft, a long fly-to) never settles, and a jump (a share link, a
// restored view) raises no moveEnd, so also read it on large changes: at
// most once a second, and once more after the last change, so the view it
// stops at is the one described.
let lastRead = 0;
let trailing = null;
const onChanged = () => {
clearTimeout(trailing);
const now = performance.now();
if (now - lastRead >= 1000) {
lastRead = now;
readView();
return;
}
trailing = setTimeout(
() => {
lastRead = performance.now();
readView();
},
1000 - (now - lastRead),
);
};
let cameraOff = [];
const listen = () => {
const port = camera();
if (!port || cameraOff.length) return;
cameraOff = [port.on('moveEnd', readView), port.on('changed', onChanged)];
};
listen();
const firstRead = setTimeout(() => {
listen();
readView();
}, 0);
// Opening the panel describes the view as it is now.
let wasOpen = isOpen();
const offChrome = chrome.$subscribe(() => {
const open = isOpen();
if (open && !wasOpen) readView();
wasOpen = open;
});
/** Layers whose own map click already follows what was clicked. */
const CLICK_FOLLOWS = new Set(['flights', 'military', 'satellites']);
// Keep the card's "following" in step with the camera: it says Following
// while the camera follows the card's own item (the follow's key names
// it) and not otherwise, whoever started or ended the follow. A layer
// switching what it follows lets go for a moment and takes hold again in
// the same turn, so this is checked once that settles.
let followCheck = 0;
const offFollow = onFollowChanged(viewer, () => {
clearTimeout(followCheck);
const card = store.card;
// Taking hold of the card's item shows at once; letting go waits a
// moment, in case the layer is only switching follows.
if (followsCard(card)) {
store.following = card.key;
return;
}
followCheck = setTimeout(() => {
const now = store.card;
store.following = followsCard(now) ? now.key : null;
}, 250);
});
// A click on anything a layer can identify opens its card. The input
// dispatcher hands every subscriber the same click, picked once before
// any layer acts on it, and only while no tool holds the pointer.
const offClick = inputFor(viewer).onClick((event) => {
// Cockpit has its own picks, and Context is hidden while it runs. A
// camera drag never selects, even if it ends over something.
if (inCockpit() || !isTrackingSelectionGesture(event.gesture)) return;
const identity = resolvePickedContext(event.hit, {
dataManager: getDataManager(),
});
if (identity) {
// These layers start following on their own click; following again
// from here would fight them (the flights layer reads a second track
// of the same plane as a click on empty map and lets go).
store.select(identity, { follow: !CLICK_FOLLOWS.has(identity.layerId) });
return;
}
// A click on open ground, sea or sky lets go of what was selected. A
// click on something else Context cannot describe (a label, a trail)
// leaves the card as it is.
// Only a clean click lets go, as the layers' own clicks do; a card
// painted on the overlay (a vessel's, a fire's) is not open map.
if (
event.surface &&
isTrackingClickGesture(event.gesture) &&
!overlayHit?.(event.screenPosition?.x, event.screenPosition?.y)
)
store.clear();
});
// Layers that select through the context store (GeoJSON sites, fires,
// installations) announce it; their selection opens the card too.
const onSelected = ({ detail: record }) => {
if (!record?.layerId || inCockpit()) return;
store.select({
layerId: record.layerId,
id: record.id,
label: record.label || record.properties?.name,
lat: record.latitude,
lon: record.longitude,
});
};
globalThis.addEventListener?.('gev:entity-selected', onSelected);
return () => {
disposed = true;
clearTimeout(firstRead);
offClick();
for (const off of cameraOff) off?.();
clearTimeout(trailing);
offFollow();
offChrome();
clearTimeout(followCheck);
globalThis.removeEventListener?.('gev:entity-selected', onSelected);
store.connect(null);
};
}
+38 -97
View File
@@ -1,93 +1,39 @@
/** Frame the complete finite footprint of a session-local file. */
import * as Cesium from 'cesium';
import { guardCameraAboveGround } from '../cameraGroundGuard.js';
import { rangeForBoundingSphere } from '../data/cameraFraming.js';
import { cancelCameraArrival } from '../data/cameraArrival.js';
import { distance, fromDegrees, toLonLatH } from '../geo/index.js';
import { sphereFromPoints } from '../geo/sphere.js';
import { heightsOf } from '../queries/heights.js';
import { findCamera } from '../render/rendererOf.js';
/** All visible positions, path vertices, polygon rings, walls and overlay bounds. */
export function dataSourcePoints(dataSource, time = Cesium.JulianDate.now()) {
const points = [];
const add = (position, grounded = false) => {
if (
!position ||
![position.x, position.y, position.z].every(Number.isFinite)
)
return;
const c = Cesium.Cartographic.fromCartesian(position);
if (c && Number.isFinite(c.longitude) && Number.isFinite(c.latitude))
points.push([
Cesium.Math.toDegrees(c.longitude),
Cesium.Math.toDegrees(c.latitude),
grounded ? 0 : c.height,
]);
};
if (dataSource?.show === false) return points;
for (const entity of dataSource?.importedEntities ??
dataSource?.entities?.values ??
[]) {
if (entity.isShowing === false) continue;
add(
entity.position?.getValue?.(time),
entity.billboard?.heightReference?.getValue?.(time) ===
Cesium.HeightReference.CLAMP_TO_GROUND,
);
for (const graphic of [entity.polyline, entity.wall])
for (const position of graphic?.positions?.getValue?.(time) || [])
add(position, graphic.clampToGround?.getValue?.(time) === true);
const rings = [entity.polygon?.hierarchy?.getValue?.(time)];
while (rings.length) {
const ring = rings.pop();
for (const position of ring?.positions || [])
add(
position,
entity.polygon?.perPositionHeight?.getValue?.(time) !== true,
);
for (const hole of ring?.holes || []) rings.push(hole);
}
const rectangle = entity.rectangle?.coordinates?.getValue?.(time);
if (rectangle) {
const bounds = Cesium.RectangleGeometry.computeRectangle({
rectangle,
rotation: entity.rectangle.rotation?.getValue?.(time) || 0,
});
for (const corner of [
'southwest',
'southeast',
'northwest',
'northeast',
]) {
const c = Cesium.Rectangle[corner](bounds);
if (Number.isFinite(c.longitude) && Number.isFinite(c.latitude))
points.push([
Cesium.Math.toDegrees(c.longitude),
Cesium.Math.toDegrees(c.latitude),
entity.rectangle.height?.getValue?.(time) || 0,
]);
}
}
}
return points;
}
/** Fly synchronously to the footprint; later navigation always owns its camera. */
export function flyToDataSource(
/**
* Fly synchronously to a footprint, `[lon, lat, height]` points (degrees,
* metres) such as a file's (`importedDrawingPoints`); later navigation always
* owns its camera. False when there is nothing to frame or no camera.
*/
export function flyToFootprint(
viewer,
dataSource,
points,
{ duration = 1.5, ground = null } = {},
) {
const points = dataSourcePoints(dataSource);
if (!points.length) return false;
if (!points?.length) return false;
const camera = findCamera(viewer);
if (!camera) return false;
cancelCameraArrival(viewer);
const positions = points.map(([lon, lat, height]) =>
Cesium.Cartesian3.fromDegrees(lon, lat, height),
fromDegrees(lon, lat, height),
);
const sphere = Cesium.BoundingSphere.fromPoints(positions);
const center =
Cesium.Cartographic.fromCartesian(sphere.center) ||
Cesium.Cartographic.fromDegrees(points[0][0], points[0][1]);
const lat = Cesium.Math.toDegrees(center.latitude),
lon = Cesium.Math.toDegrees(center.longitude);
const terrain = viewer.scene?.globe?.getHeight?.(center);
const sphere = sphereFromPoints(positions);
const center = toLonLatH(sphere.center) || {
lon: points[0][0],
lat: points[0][1],
height: 0,
};
const { lat, lon } = center;
const terrain = viewer
? heightsOf(viewer).now({ lon, lat }, { against: 'terrain' })
: null;
const cached = ground?.cachedGroundFloor?.(lat, lon);
const height =
Number.isFinite(terrain) && terrain > 0
@@ -98,25 +44,20 @@ export function flyToDataSource(
? terrain
: 0;
ground?.warmGroundFloor?.([{ lat, lon }]);
sphere.center = Cesium.Cartesian3.fromRadians(
center.longitude,
center.latitude,
Math.max(0, height, center.height),
);
sphere.radius = 0;
const framed = {
center: fromDegrees(lon, lat, Math.max(0, height, center.height)),
radius: 0,
};
for (const position of positions)
sphere.radius = Math.max(
sphere.radius,
Cesium.Cartesian3.distance(sphere.center, position),
);
viewer.camera?.flyToBoundingSphere?.(sphere, {
offset: new Cesium.HeadingPitchRange(
viewer.camera.heading || 0,
-Math.PI / 2,
Math.max(800, rangeForBoundingSphere(viewer, sphere.radius)),
),
duration,
complete: () => guardCameraAboveGround(viewer, { lat, lon }),
framed.radius = Math.max(framed.radius, distance(framed.center, position));
camera.flyToBounds(framed, {
offset: {
heading: camera.pose().heading || 0,
pitch: -Math.PI / 2,
range: Math.max(800, rangeForBoundingSphere(viewer, framed.radius)),
},
durationS: duration,
onComplete: () => guardCameraAboveGround(viewer, { lat, lon }),
});
return true;
}
+110 -88
View File
@@ -1,34 +1,70 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { cancelCameraArrival } from '../data/cameraArrival.js';
import { dataSourcePoints, flyToDataSource } from './flyToDataSource.js';
import {
cancelCameraArrival,
ownCameraArrival,
} from '../data/cameraArrival.js';
import {
createImportedDrawing,
importedDrawingPoints,
} from '../data/geoImportPins.js';
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
import { fakeSceneQuery } from '../testSupport/fakeCesiumScene.mjs';
import { flyToFootprint } from './flyToDataSource.js';
/** As the file import flies to one of its files. */
const flyToDataSource = (viewer, drawing) =>
flyToFootprint(viewer, importedDrawingPoints(drawing));
/** An imported file's drawing of `features`, not drawn. */
const drawingOf = (features) => createImportedDrawing({}, features);
const pin = (lon, lat, height = 0, mode = 'absolute') => ({
kind: 'pin',
lon,
lat,
height,
mode,
image: 'pin.png',
size: [32, 32],
});
const line = (coords, mode = 'draped') => ({
kind: 'line',
coords,
mode,
color: [1, 1, 1, 1],
width: 1,
});
/** A Cesium-shaped viewer double, bound to the camera and query ports. */
const bound = (viewer) =>
bindFakeCesiumCamera(viewer, { query: fakeSceneQuery(viewer) });
function source() {
const ds = new Cesium.CustomDataSource('t');
ds.entities.add({
position: Cesium.Cartesian3.fromDegrees(-122.4862, 37.7694, -2667),
billboard: { heightReference: Cesium.HeightReference.CLAMP_TO_GROUND },
});
ds.entities.add({
polyline: {
positions: Cesium.Cartesian3.fromDegreesArray([
-122.49, 37.77, -122.48, 37.771,
]),
return drawingOf([
pin(-122.4862, 37.7694, 0, 'clamp'),
line([
[-122.49, 37.77, 0],
[-122.48, 37.771, 0],
]),
{
kind: 'polygon',
rings: [
[
[-122.5, 37.76, 0],
[-122.49, 37.76, 0],
[-122.49, 37.765, 0],
],
],
clamp: true,
fill: [1, 1, 1, 0.25],
outline: null,
},
});
ds.entities.add({
polygon: {
hierarchy: Cesium.Cartesian3.fromDegreesArray([
-122.5, 37.76, -122.49, 37.76, -122.49, 37.765,
]),
},
});
return ds;
]);
}
test('points come from positions, lines and polygons, as lon/lat only', () => {
const points = dataSourcePoints(source());
const points = importedDrawingPoints(source());
assert.equal(points.length, 6);
assert.ok(Math.abs(points[0][0] + 122.4862) < 1e-6);
assert.ok(Math.abs(points[0][1] - 37.7694) < 1e-6);
@@ -36,26 +72,28 @@ test('points come from positions, lines and polygons, as lon/lat only', () => {
test('the camera frames the footprint at the surface, never a buried center', () => {
const calls = [];
const viewer = {
const viewer = bound({
scene: {},
camera: {
heading: 0,
positionWC: Cesium.Cartesian3.fromDegrees(-122.49, 37.77, 900),
directionWC: new Cesium.Cartesian3(0, 0, -1),
upWC: new Cesium.Cartesian3(0, 1, 0),
flyToBoundingSphere: (sphere, options) => calls.push({ sphere, options }),
},
flyTo: () => calls.push('viewer.flyTo'),
};
});
assert.equal(flyToDataSource(viewer, source()), true);
const center = Cesium.Cartographic.fromCartesian(calls[0].sphere.center);
assert.ok(Math.abs(center.height) < 50, `center height ${center.height}`);
assert.ok(calls[0].options.offset.range >= 800);
assert.equal(
typeof calls[0].options.complete,
'function',
'the ground guard runs on landing',
);
assert.equal(
flyToDataSource(viewer, new Cesium.CustomDataSource('empty')),
false,
);
// Landing starts the ground guard, which takes over the arrival.
let handedOver = false;
ownCameraArrival(viewer, () => (handedOver = true));
calls[0].options.complete();
assert.equal(handedOver, true, 'the ground guard runs on landing');
cancelCameraArrival(viewer);
assert.equal(flyToDataSource(viewer, drawingOf([])), false);
assert.equal(
calls.length,
1,
@@ -67,13 +105,11 @@ test('a very long track is framed without spreading it into a call', () => {
// 400k vertices: `push(...line)` throws RangeError (too many arguments)
// well below this; the walk keeps a bounded sample and both ends.
const n = 400_000;
const line = new Array(n);
for (let i = 0; i < n; i++)
line[i] = Cesium.Cartesian3.fromDegrees(-120 + (i / n) * 2, 40);
const ds = new Cesium.CustomDataSource('long');
ds.entities.add({ polyline: { positions: line } });
ds.entities.add({ position: Cesium.Cartesian3.fromDegrees(-110, 41) });
const points = dataSourcePoints(ds);
const coords = new Array(n);
for (let i = 0; i < n; i++) coords[i] = [-120 + (i / n) * 2, 40, 0];
const points = importedDrawingPoints(
drawingOf([line(coords), pin(-110, 41)]),
);
assert.equal(points.length, n + 1, 'every vertex contributes to framing');
const lons = points.map(([lon]) => lon);
assert.ok(
@@ -84,42 +120,45 @@ test('a very long track is framed without spreading it into a call', () => {
});
test('framing includes a sparse interior outlier, walls and rotated overlays', () => {
const ds = new Cesium.CustomDataSource('bounds');
const line = Array.from({ length: 200031 }, () =>
Cesium.Cartesian3.fromDegrees(0, 0),
const coords = Array.from({ length: 200031 }, () => [0, 0, 0]);
coords[12345] = [20, 10, 0];
const points = importedDrawingPoints(
drawingOf([
line(coords),
{
kind: 'wall',
coords: [
[30, 10, 0],
[31, 11, 0],
],
},
{
kind: 'overlay',
rect: { west: 40, south: 0, east: 41, north: 1 },
rotation: Math.PI / 4,
},
]),
);
line[12345] = Cesium.Cartesian3.fromDegrees(20, 10);
ds.entities.add({ polyline: { positions: line } });
ds.entities.add({
wall: { positions: Cesium.Cartesian3.fromDegreesArray([30, 10, 31, 11]) },
});
ds.entities.add({
rectangle: {
coordinates: Cesium.Rectangle.fromDegrees(40, 0, 41, 1),
rotation: Math.PI / 4,
},
});
const points = dataSourcePoints(ds);
assert.ok(points.some(([lon]) => Math.abs(lon - 20) < 1e-6));
assert.ok(points.some(([lon]) => Math.abs(lon - 31) < 1e-6));
assert.ok(points.some(([lon]) => lon > 41));
});
test('portrait framing accounts for FOV, high ground and symmetric extents', () => {
const ds = new Cesium.CustomDataSource('view');
ds.entities.add({
polyline: {
positions: Cesium.Cartesian3.fromDegreesArray([-105, 39, -104.9, 39]),
},
});
const ds = drawingOf([
line([
[-105, 39, 0],
[-104.9, 39, 0],
]),
]);
const calls = [];
const viewer = {
const viewer = bound({
scene: { globe: { getHeight: () => 2600 } },
camera: {
frustum: { fov: Math.PI / 3, aspectRatio: 390 / 844 },
frustum: { fovy: Math.PI / 3, aspectRatio: 390 / 844 },
flyToBoundingSphere: (sphere, options) => calls.push({ sphere, options }),
},
};
});
flyToDataSource(viewer, ds);
assert.ok(
Math.abs(
@@ -130,34 +169,17 @@ test('portrait framing accounts for FOV, high ground and symmetric extents', ()
viewer.camera.frustum.aspectRatio = 16 / 9;
flyToDataSource(viewer, ds);
assert.ok(calls[0].options.offset.range > calls[1].options.offset.range);
const symmetric = {
entities: {
values: [
{ position: { getValue: () => new Cesium.Cartesian3(6378137, 0, 0) } },
{ position: { getValue: () => new Cesium.Cartesian3(-6378137, 0, 0) } },
],
},
};
const symmetric = drawingOf([pin(0, 0), pin(180, 0)]);
assert.doesNotThrow(() => flyToDataSource(viewer, symmetric));
assert.ok(Number.isFinite(calls.at(-1).options.offset.range));
assert.doesNotThrow(() => calls.at(-1).options.complete());
cancelCameraArrival(viewer);
});
test('non-finite positions and hidden features never enter the camera footprint', () => {
const position = (p) => ({ position: { getValue: () => p } });
const points = dataSourcePoints({
entities: {
values: [
position(new Cesium.Cartesian3(NaN, 1, 2)),
{
...position(Cesium.Cartesian3.fromDegrees(10, 10)),
isShowing: false,
},
position(Cesium.Cartesian3.fromDegrees(20, 20)),
],
},
});
assert.equal(points.length, 1);
assert.ok(Math.abs(points[0][0] - 20) < 1e-6);
test('non-finite positions are refused and a hidden file has no footprint', () => {
assert.throws(() => drawingOf([pin(Number.NaN, 1)]), /invalid point/);
const drawing = drawingOf([pin(20, 20)]);
assert.equal(importedDrawingPoints(drawing).length, 1);
drawing.show = false;
assert.deepEqual(importedDrawingPoints(drawing), []);
});
+6 -3
View File
@@ -1,5 +1,6 @@
import { useStatusStore } from './stores/status.js';
import { applicationPinia } from './vueRuntime.js';
import { findFrame } from '../render/rendererOf.js';
/**
* Count rendered globe frames while the optional readout is visible. The
@@ -10,9 +11,9 @@ export function createFrameRateMonitor({
documentRef = document,
store = useStatusStore(applicationPinia()),
}) {
const frameEvent = viewer?.scene?.postRender;
const frameOfViewer = () => findFrame(viewer);
// A page without the scene chrome has no title bar to show it in.
if (!documentRef.getElementById('title-bar') || !frameEvent)
if (!documentRef.getElementById('title-bar') || !frameOfViewer())
return { destroy() {} };
// i18n-ignore: FPS is a unit code, the same in every language
@@ -43,7 +44,9 @@ export function createFrameRateMonitor({
startedAt = performance.now();
// i18n-ignore: FPS is a unit code, the same in every language
present({ visible: true, text: 'FPS —' });
removeFrameListener = frameEvent.addEventListener(() => {
// Looked up when shown, so a renderer bound since creation is the one
// counted.
removeFrameListener = frameOfViewer()?.on('postRender', () => {
frames++;
});
timer = setInterval(() => {
+4
View File
@@ -1,6 +1,8 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createFrameRateMonitor } from './frameRateMonitor.js';
import { bindRenderer } from '../render/rendererOf.js';
import { fakeSceneFrame } from '../testSupport/fakeCesiumScene.mjs';
function fixture(t) {
const keys = new Set();
@@ -27,6 +29,7 @@ function fixture(t) {
},
},
};
bindRenderer(viewer, { frame: fakeSceneFrame(viewer) });
const monitor = createFrameRateMonitor({ viewer, documentRef, store });
t.after(() => monitor.destroy());
return {
@@ -133,6 +136,7 @@ test("destroying an earlier monitor leaves a newer one's readout", () => {
const viewer = {
scene: { postRender: { addEventListener: () => () => {} } },
};
bindRenderer(viewer, { frame: fakeSceneFrame(viewer) });
const first = createFrameRateMonitor({ viewer, documentRef, store });
const second = createFrameRateMonitor({ viewer, documentRef, store });
const shown = store.fps;
+39 -1
View File
@@ -8,6 +8,8 @@ import { createPinia } from 'pinia';
import { useStatusStore } from './stores/status.js';
import { createFrameRateMonitor } from './frameRateMonitor.js';
import SceneChromeView from './views/SceneChromeView.vue';
import { bindRenderer } from '../render/rendererOf.js';
import { fakeSceneFrame } from '../testSupport/fakeCesiumScene.mjs';
test('the FPS readout sits in the title bar, hidden until the backquote key', async (t) => {
document.body.replaceChildren();
@@ -18,8 +20,12 @@ test('the FPS readout sits in the title bar, hidden until the backquote key', as
const readout = () =>
document.querySelector('#title-bar .frame-rate-readout');
assert.equal(readout(), null, 'no readout without a monitor');
const viewer = {
scene: { postRender: { addEventListener: () => () => {} } },
};
bindRenderer(viewer, { frame: fakeSceneFrame(viewer) });
const monitor = createFrameRateMonitor({
viewer: { scene: { postRender: { addEventListener: () => () => {} } } },
viewer,
store: useStatusStore(pinia),
});
t.after(() => monitor.destroy());
@@ -42,3 +48,35 @@ test('the FPS readout sits in the title bar, hidden until the backquote key', as
await nextTick();
assert.equal(readout(), null);
});
test('the title logo is a button that asks for the way back to live at the start view', async (t) => {
document.body.replaceChildren();
const pinia = createPinia();
const app = createApp(SceneChromeView).use(pinia);
app.mount(document.body.appendChild(document.createElement('div')));
t.after(() => app.unmount());
const { useGlobeActionsStore } = await import('./stores/globeActions.js');
const calls = [];
useGlobeActionsStore(pinia).connect({ home: () => calls.push('home') });
const logo = document.querySelector('#title-bar h1 > button.title-logo');
assert.ok(logo, 'the logo is the title heading’s button');
assert.equal(
logo.getAttribute('aria-label'),
'Back to live at the starting view',
);
assert.ok(logo.hasAttribute('data-logo-gaze'));
logo.click();
assert.deepEqual(calls, ['home']);
});
test('the title heading keeps its own name beside the logo button', async (t) => {
document.body.replaceChildren();
const app = createApp(SceneChromeView).use(createPinia());
app.mount(document.body.appendChild(document.createElement('div')));
t.after(() => app.unmount());
const heading = document.querySelector('#title-bar h1');
const named = document.getElementById(
heading.getAttribute('aria-labelledby'),
);
assert.equal(named.textContent.replace(/\s+/g, ' ').trim(), "GOD'S EYE VIEW");
});
+62 -26
View File
@@ -4,8 +4,23 @@ import {
MAX_IMPORTED_FILES,
loadGeoFile,
} from '../data/geoFileImport.js';
import {
importedDrawingPoints,
removeImportedDrawing,
showImportedDrawing,
} from '../data/geoImportPins.js';
import { formatNumber, t, tn, translateKnown } from '../i18n/index.js';
import { flyToDataSource } from './flyToDataSource.js';
import { flyToFootprint } from './flyToDataSource.js';
import {
canvasOf,
findCamera,
findFrame,
findGlobe,
} from '../render/rendererOf.js';
/** Fly to the whole footprint of one imported file's drawing. */
const flyToDrawing = (viewer, drawing, options) =>
flyToFootprint(viewer, importedDrawingPoints(drawing), options);
// One color per file, in import order, from the whiteboard palette.
const COLORS = ['#39d0ff', '#ffb547', '#5dff9f', '#ff6b6b', '#8be9ff'];
@@ -29,14 +44,14 @@ function localizedValues(values) {
* renders them. `connect(actions)` answers the view's pick and row buttons
* and returns their disconnect.
* @returns {{destroy: Function, importFiles: Function, list: Function,
* setVisible: Function, flyTo: Function, remove: Function,
* setVisible: Function, flyTo: Function, remove: Function, drawn: Function,
* diagnostics: Function}|null}
*/
export function initGeoFileImport({
viewer,
load = loadGeoFile,
document: doc = globalThis.document,
flyToSource = flyToDataSource,
flyToSource = flyToDrawing,
navigation = null,
ground = null,
subscribeMapSource = null,
@@ -68,7 +83,7 @@ export function initGeoFileImport({
hint = text || '';
present();
};
const render = () => viewer.scene?.requestRender?.();
const render = () => findFrame(viewer)?.requestRender('geo-import');
let groundTimer,
groundQueued = false,
groundAgain = false;
@@ -109,14 +124,20 @@ export function initGeoFileImport({
}, 200);
};
removeMapSource = subscribeMapSource?.(scheduleGround);
const ownEvent = (event, listener) => {
const remove = event?.addEventListener?.(listener);
if (remove) groundRemovers.push(remove);
};
ownEvent(viewer.camera?.moveEnd, scheduleGround);
ownEvent(viewer.scene?.globe?.tileLoadProgressEvent, (pending) => {
if (!pending) scheduleGround();
});
const camera = findCamera(viewer);
if (camera) groundRemovers.push(camera.on('moveEnd', scheduleGround));
// Terrain tiles finishing loading: the queue running dry, once each time.
let terrainPending = null;
const globe = findGlobe(viewer);
if (globe)
groundRemovers.push(
globe.on('progress', (progress) => {
const pending = progress.terrainPending;
if (pending === terrainPending) return;
terrainPending = pending;
if (!pending) scheduleGround();
}),
);
/** Publish the file list and hint; the view renders them. */
function present() {
@@ -166,7 +187,7 @@ export function initGeoFileImport({
const item = find(id);
if (!item) return false;
item.visible = Boolean(visible);
item.dataSource.show = item.visible;
showImportedDrawing(item.drawing, item.visible);
if (item.visible) scheduleGround();
present();
render();
@@ -177,7 +198,7 @@ export function initGeoFileImport({
// destination's terrain has loaded (see ./flyToDataSource.js).
const fly = (item) => {
if (!item.visible) setVisible(item.id, true);
flyToSource(viewer, item.dataSource, { ground });
flyToSource(viewer, item.drawing, { ground });
return true;
};
@@ -214,7 +235,7 @@ export function initGeoFileImport({
const at = imports.findIndex((item) => item.id === id);
if (at < 0) return false;
const [item] = imports.splice(at, 1);
viewer.dataSources?.remove?.(item.dataSource, true);
removeImportedDrawing(item.drawing);
item.revoke?.();
present();
render();
@@ -278,6 +299,18 @@ export function initGeoFileImport({
loaded.revoke?.();
break;
}
try {
loaded.mount?.();
} catch {
// Something in it the renderer would not draw: refused whole.
loaded.revoke?.();
outcomes.push({
name: fileName,
ok: false,
error: t('That file could not be read.'),
});
continue;
}
colorAt += 1;
seq += 1;
const item = {
@@ -289,17 +322,10 @@ export function initGeoFileImport({
removed: loaded.removed || 0,
color,
visible: true,
dataSource: loaded.dataSource,
drawing: loaded.drawing,
revoke: loaded.revoke,
refreshGround: loaded.refreshGround,
};
await viewer.dataSources.add(item.dataSource);
if (destroyed) {
viewer.dataSources.remove?.(item.dataSource, true);
item.revoke?.();
break;
}
loaded.mount?.();
imports.push(item);
present();
render();
@@ -336,10 +362,10 @@ export function initGeoFileImport({
const gesture = () => {
cameraIntent += 1;
};
listen(viewer.scene?.canvas || container, 'pointerdown', gesture, {
listen(canvasOf(viewer) || container, 'pointerdown', gesture, {
passive: true,
});
listen(viewer.scene?.canvas || container, 'wheel', gesture, {
listen(canvasOf(viewer) || container, 'wheel', gesture, {
passive: true,
});
const hasFiles = (event) =>
@@ -387,6 +413,16 @@ export function initGeoFileImport({
setVisible,
flyTo,
remove,
/** What a file drew: its sets' ids, whether shown, and their items. */
drawn: (id) => {
const item = imports.find((entry) => entry.id === id);
if (!item?.drawing) return null;
return {
sets: { ...item.drawing.ids },
show: item.drawing.show,
...item.drawing.items?.(),
};
},
diagnostics: () => ({
files: imports.length,
entities: imports.reduce((n, item) => n + item.entityCount, 0),
@@ -402,7 +438,7 @@ export function initGeoFileImport({
clearTimeout(groundTimer);
for (const remove of groundRemovers) remove();
for (const item of imports.splice(0)) {
viewer.dataSources?.remove?.(item.dataSource, true);
removeImportedDrawing(item.drawing);
item.revoke?.();
}
for (const [target, type, listener, options] of listeners.splice(0))
+126 -21
View File
@@ -1,6 +1,6 @@
// Behavioral tests for DISPLAY ▸ Import: the controller is driven against
// fake DOM and viewer doubles with an injected loader, and its observable
// effects are asserted — data sources added and removed, the rows and hint it
// effects are asserted — drawings mounted and removed, the rows and hint it
// publishes, drop handling, the file limit, and what destroy() gives back.
// The Display panel renders the published list (`displayPanel.test.mjs`);
// real parsing and rendering run in `scripts/qa-geo-import.mjs`.
@@ -9,6 +9,7 @@ import assert from 'node:assert/strict';
import fs from 'node:fs';
import { initGeoFileImport, summarize } from './geoFileImport.js';
import { GeoImportError, MAX_IMPORTED_FILES } from '../data/geoFileImport.js';
import { bindRenderer } from '../render/rendererOf.js';
class FakeClassList {
constructor() {
@@ -59,7 +60,13 @@ class FakeElement {
}
}
function setup({ load, navigation, flyToSource, subscribeMapSource } = {}) {
function setup({
load,
navigation,
flyToSource,
subscribeMapSource,
ports,
} = {}) {
const els = {
'geo-import-button': new FakeElement('button', 'geo-import-button'),
};
@@ -78,18 +85,11 @@ function setup({ load, navigation, flyToSource, subscribeMapSource } = {}) {
const viewer = {
container: new FakeElement('div', 'cesiumContainer'),
scene: { requestRender: () => (renders += 1) },
dataSources: {
add: async (ds) => {
added.push(ds);
return ds;
},
remove: (ds, destroy) => {
removed.push({ ds, destroy });
return true;
},
},
flyTo: (target) => flights.push(target),
};
// The renderer's ports, when the test gives them, bound before the import
// starts as the application binds its renderer.
if (ports) bindRenderer(viewer, ports);
const revoked = [];
const loads = [];
const defaultLoad = async (file, opts) => {
@@ -97,7 +97,7 @@ function setup({ load, navigation, flyToSource, subscribeMapSource } = {}) {
if (file.fail) throw new GeoImportError(file.fail);
if (file.crash) throw new Error('boom');
return {
dataSource: { show: true },
drawing: { show: true },
name: file.name,
format: 'geojson',
entityCount: 3,
@@ -105,9 +105,24 @@ function setup({ load, navigation, flyToSource, subscribeMapSource } = {}) {
revoke: () => revoked.push(file.name),
};
};
// Each loaded file's drawing, recorded when the import mounts it and when
// it takes it off the globe.
const recorded = async (file, opts) => {
const loaded = await (load || defaultLoad)(file, opts);
const drawing = loaded.drawing ?? {};
drawing.destroy = () => removed.push({ ds: drawing, destroy: true });
return {
...loaded,
drawing,
mount() {
loaded.mount?.();
added.push(drawing);
},
};
};
const tool = initGeoFileImport({
viewer,
load: load || defaultLoad,
load: recorded,
document,
...(navigation ? { navigation } : {}),
...(subscribeMapSource ? { subscribeMapSource } : {}),
@@ -191,10 +206,19 @@ test('row buttons hide, show, fly to and remove a file', async () => {
await t.tool.importFiles([file('a.gpx')]);
const [{ id }] = t.tool.list();
const ds = t.added[0];
ds.ids = { icons: 'i', lines: 'l', shapes: 's' };
ds.items = () => ({ icons: [{ id: 'p0' }], lines: [], shapes: [] });
const glyphClick = (name) => press(t, rows(t)[0], name);
assert.equal(ds.show, true);
glyphClick('toggle');
assert.equal(ds.show, false);
assert.deepEqual(t.tool.drawn(id), {
sets: { icons: 'i', lines: 'l', shapes: 's' },
show: false,
icons: [{ id: 'p0' }],
lines: [],
shapes: [],
});
assert.equal(t.tool.list()[0].visible, false);
assert.equal(action(rows(t)[0], 'toggle').pressed, 'false');
assert.equal(action(rows(t)[0], 'toggle').icon, 'visibility_off');
@@ -207,6 +231,7 @@ test('row buttons hide, show, fly to and remove a file', async () => {
assert.deepEqual(t.revoked, ['a.gpx']);
assert.equal(t.tool.list().length, 0);
assert.deepEqual(rows(t), []);
assert.equal(t.tool.drawn(id), null);
assert.equal(t.tool.remove(id), false);
});
@@ -230,6 +255,32 @@ test('a refused file says why and does not stop the rest of the batch', async ()
assert.equal(t.tool.list().length, 1);
});
test('a file the renderer will not draw is refused and released, and the batch goes on', async () => {
const t = setup({
load: async (file) => ({
drawing: { show: true },
name: file.name,
format: 'kml',
entityCount: 1,
revoke: () => t.revoked.push(file.name),
mount() {
if (file.name === 'odd.kml') throw new Error('refused');
},
}),
});
const out = await t.tool.importFiles([file('odd.kml'), file('good.kml')]);
assert.deepEqual(
out.map((o) => o.ok),
[false, true],
);
assert.match(out[0].error, /could not be read\./);
assert.deepEqual(t.revoked, ['odd.kml']);
assert.deepEqual(
t.tool.list().map((f) => f.name),
['good.kml'],
);
});
test('the number of files on the globe is bounded', async () => {
const t = setup();
const many = Array.from({ length: MAX_IMPORTED_FILES + 2 }, (_, i) =>
@@ -304,7 +355,7 @@ test('a file that finishes loading after destroy is released, not added', async
load: async () => {
await gate;
return {
dataSource: {},
drawing: {},
name: 'late',
format: 'kml',
entityCount: 1,
@@ -408,7 +459,7 @@ test('a direct camera gesture cancels the fly-to of a file still being read', as
name: 'slow.geojson',
format: 'geojson',
entityCount: 1,
dataSource: {},
drawing: {},
};
},
});
@@ -454,7 +505,7 @@ test('ground refresh coalesces map changes and releases its subscription on tear
name: 'point.geojson',
format: 'geojson',
entityCount: 1,
dataSource: {},
drawing: {},
refreshGround: async () => refreshed++,
}),
});
@@ -471,6 +522,60 @@ test('ground refresh coalesces map changes and releases its subscription on tear
assert.equal(unsubscribed, 1);
});
test('the camera settling and the terrain queue running dry refresh the ground, through the ports', async () => {
const listeners = { moveEnd: new Set(), progress: new Set() };
const on = (name) => (event, cb) => {
assert.equal(event, name);
listeners[name].add(cb);
return () => listeners[name].delete(cb);
};
const reasons = [];
let refreshed = 0;
const t = setup({
ports: {
camera: { on: on('moveEnd') },
globe: { on: on('progress') },
frame: { requestRender: (reason) => reasons.push(reason) },
},
load: async () => ({
name: 'point.geojson',
format: 'geojson',
entityCount: 1,
drawing: {},
refreshGround: async () => refreshed++,
}),
});
const settle = () => new Promise((resolve) => setTimeout(resolve, 300));
const progress = (terrainPending) => {
for (const cb of [...listeners.progress])
cb({ tilesPending: 0, imageryPending: 0, terrainPending });
};
await t.tool.importFiles([file('point.geojson')]);
assert.ok(reasons.length > 0 && reasons.every((r) => r === 'geo-import'));
for (const cb of [...listeners.moveEnd]) cb();
await settle();
assert.equal(refreshed, 1, 'the camera settling refreshes once');
// The first report of an empty terrain queue counts, then only the queue
// running dry again, once each time it does; progress that leaves the
// terrain count where it was (imagery only) does not.
progress(0);
await settle();
assert.equal(refreshed, 2);
progress(0);
await settle();
assert.equal(refreshed, 2);
progress(3);
progress(1);
await settle();
assert.equal(refreshed, 2);
progress(0);
await settle();
assert.equal(refreshed, 3);
t.tool.destroy();
assert.equal(listeners.moveEnd.size, 0);
assert.equal(listeners.progress.size, 0);
});
test('Fly to is an immediate navigation that Cockpit can refuse', async () => {
const flown = [];
const nav = navigationDouble({ immediate: false });
@@ -505,7 +610,7 @@ test('a slow import does not fly once something newer took the camera', async ()
load: async (f) => {
await gate;
return {
dataSource: {},
drawing: {},
name: f.name,
format: 'geojson',
entityCount: 1,
@@ -539,7 +644,7 @@ test('a queued import cannot fly over navigation that happened while it waited',
load: async (f) => {
if (f.name === 'first.geojson') await gate;
return {
dataSource: {},
drawing: {},
name: f.name,
format: 'geojson',
entityCount: 1,
@@ -574,7 +679,7 @@ test('a refused deferred stamp (Cockpit) imports without flying', async () => {
test('KML and KMZ rows say they keep their own styles instead of showing a color', async () => {
const t = setup({
load: async (f) => ({
dataSource: {},
drawing: {},
name: f.name,
format: f.name.endsWith('.kml') ? 'kml' : 'gpx',
entityCount: 2,
@@ -593,7 +698,7 @@ test('KML and KMZ rows say they keep their own styles instead of showing a color
test('the map-object count in a row title keeps digit grouping', async () => {
const t = setup({
load: async (f) => ({
dataSource: {},
drawing: {},
name: f.name,
format: 'geojson',
entityCount: 12345,
+48 -139
View File
@@ -1,28 +1,29 @@
/**
* Box selection for the Recent Imagery layer: press on the world, drag, and
* release to hand the layer a degrees box. Follows the draw tool's ownership
* rules — the pointer is claimed for the session, the viewer's own click
* actions are borrowed and given back, and `destroy()` returns everything —
* and freezes the camera only while a drag is in progress.
* rules — the pointer is claimed for the session (a newer claim cancels it),
* the viewer's own click actions are suppressed and given back, and
* `destroy()` returns everything — and holds the camera only while a drag is
* in progress.
*/
import * as Cesium from 'cesium';
import { pickWorldFromScreen } from '../annotations/annotationResolver.js';
import {
claimPointer,
pointerOwner,
releasePointer,
} from '../data/inputOwnership.js';
import { claimPointer, releasePointer } from '../data/inputOwnership.js';
import { inputFor as defaultInputFor } from '../input/dispatcher.js';
import { validateBox } from '../layers/recentImagery/model.js';
import { createImageryBoxPreview } from '../layers/recentImagery/rendering.js';
import { msg } from '../i18n/index.js';
import { canvasOf } from '../render/rendererOf.js';
/** The id this tool claims the pointer under. */
export const IMAGERY_BOX_POINTER_OWNER = 'recent-imagery-box';
/**
* Wire the box tool.
* @param {{ viewer: object, onBox: (box: object) => void, onCancel?: (reason: string, message?: string, box?: object) => void, onActive?: (active: boolean) => void, onEscape?: () => boolean, cesium?: object, pickWorld?: Function, documentRef?: object }} deps
* @param {{ viewer: object, onBox: (box: object) => void, onCancel?: (reason: string, message?: string, box?: object) => void, onActive?: (active: boolean) => void, onEscape?: () => boolean, createPreview?: Function, inputFor?: Function, pickWorld?: Function, documentRef?: object }} deps
* `onEscape` runs before the tool cancels on Escape; returning `true` claims
* the key (it is still consumed) and leaves the tool armed.
* `createPreview(viewer, dragBox)` draws the box being dragged
* (`createImageryBoxPreview`).
* @returns {{ start: () => boolean, cancel: (reason?: string) => void, isActive: () => boolean, destroy: () => Promise<void> } | null}
*/
export function initImageryBoxTool({
@@ -31,22 +32,21 @@ export function initImageryBoxTool({
onCancel,
onActive,
onEscape,
cesium = Cesium,
createPreview = createImageryBoxPreview,
inputFor = defaultInputFor,
pickWorld = pickWorldFromScreen,
documentRef = globalThis.document,
} = {}) {
if (!viewer?.scene || typeof onBox !== 'function') return null;
if (!viewer || typeof onBox !== 'function') return null;
let active = false;
let destroyed = false;
/** Drag corners in degrees; `anchor` is null while no drag is live. */
let anchor = null;
let corner = null;
let handler = null;
let unbindScene = null;
let lease = null;
let savedSingleClick = null;
let savedDoubleClick = null;
let savedCameraInputs = null;
let releaseCamera = null;
const dragBox = () =>
anchor && {
@@ -56,68 +56,11 @@ export function initImageryBoxTool({
north: Math.max(anchor.lat, corner.lat),
};
const dataSource = new cesium.CustomDataSource(
'gev-recent-imagery-box-preview',
);
let attaching = Promise.resolve(viewer.dataSources.add(dataSource)).catch(
() => null,
);
const stroke = cesium.Color.fromCssColorString('#8be9ff');
const previewRectangle = () => {
const box = dragBox();
return box
? cesium.Rectangle.fromDegrees(box.west, box.south, box.east, box.north)
: undefined;
};
const previewOutline = () => {
const box = dragBox();
if (!box) return [];
return cesium.Cartesian3.fromDegreesArray([
box.west,
box.south,
box.east,
box.south,
box.east,
box.north,
box.west,
box.north,
box.west,
box.south,
]);
};
const fill = dataSource.entities.add({
show: false,
rectangle: {
coordinates: new cesium.CallbackProperty(previewRectangle, false),
material: stroke.withAlpha(0.12),
classificationType: cesium.ClassificationType.BOTH,
},
});
// A rectangle graphic cannot draw a dashed edge on the ground, so the
// outline is its own draped polyline traced round the same corners.
const outline = dataSource.entities.add({
show: false,
polyline: {
positions: new cesium.CallbackProperty(previewOutline, false),
width: 2,
clampToGround: true,
classificationType: cesium.ClassificationType.BOTH,
material: new cesium.PolylineDashMaterialProperty({
color: stroke.withAlpha(0.95),
dashLength: 12,
}),
},
});
const requestRender = () => viewer.scene.requestRender?.();
const setPreview = (visible) => {
fill.show = visible;
outline.show = visible;
requestRender();
};
const preview = createPreview(viewer, dragBox);
const setPreview = (visible) => preview.setVisible(visible);
const worldAt = (position) => {
if (!position) return null;
const canvas = viewer.scene.canvas;
const canvas = canvasOf(viewer);
const w = canvas?.clientWidth || canvas?.width || 1;
const h = canvas?.clientHeight || canvas?.height || 1;
const point = pickWorld(viewer, position.x / w, position.y / h);
@@ -125,19 +68,13 @@ export function initImageryBoxTool({
const lat = Number(point?.lat);
return Number.isFinite(lon) && Number.isFinite(lat) ? { lon, lat } : null;
};
const cameraController = () => viewer.scene.screenSpaceCameraController;
function freezeCamera() {
const controller = cameraController();
if (!controller || savedCameraInputs !== null) return;
savedCameraInputs = controller.enableInputs;
controller.enableInputs = false;
releaseCamera ??= inputFor(viewer).suspendCamera('recent-imagery-box');
}
function thawCamera() {
const controller = cameraController();
if (controller && savedCameraInputs !== null)
controller.enableInputs = savedCameraInputs;
savedCameraInputs = null;
releaseCamera?.();
releaseCamera = null;
}
function endDrag() {
@@ -163,7 +100,7 @@ export function initImageryBoxTool({
const point = anchor && !destroyed && worldAt(event.endPosition);
if (!point) return;
corner = point;
requestRender();
preview.changed();
};
const onUp = (event) => {
if (!anchor || destroyed) return;
@@ -190,45 +127,23 @@ export function initImageryBoxTool({
};
function bindScene() {
if (handler) return;
handler = new cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
handler.setInputAction(onDown, cesium.ScreenSpaceEventType.LEFT_DOWN);
handler.setInputAction(onMove, cesium.ScreenSpaceEventType.MOUSE_MOVE);
handler.setInputAction(onUp, cesium.ScreenSpaceEventType.LEFT_UP);
const stock = viewer.screenSpaceEventHandler;
if (stock) {
savedSingleClick =
stock.getInputAction(cesium.ScreenSpaceEventType.LEFT_CLICK) || null;
savedDoubleClick =
stock.getInputAction(cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK) ||
null;
stock.removeInputAction(cesium.ScreenSpaceEventType.LEFT_CLICK);
stock.removeInputAction(cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
}
if (unbindScene) return;
const input = inputFor(viewer);
const held = { lease: () => lease };
const offs = [
input.onPointer('down', onDown, held),
input.onPointer('move', onMove, held),
input.onPointer('up', onUp, held),
input.suppressStockClicks(),
];
unbindScene = () => offs.forEach((off) => off());
documentRef?.addEventListener?.('keydown', onKey, true);
documentRef?.body?.classList?.add?.('gev-imagery-box');
}
function releaseScene() {
if (handler) {
handler.destroy();
handler = null;
}
const stock = viewer.screenSpaceEventHandler;
if (stock && savedSingleClick) {
stock.setInputAction(
savedSingleClick,
cesium.ScreenSpaceEventType.LEFT_CLICK,
);
}
if (stock && savedDoubleClick) {
stock.setInputAction(
savedDoubleClick,
cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK,
);
}
savedSingleClick = null;
savedDoubleClick = null;
unbindScene?.();
unbindScene = null;
documentRef?.removeEventListener?.('keydown', onKey, true);
documentRef?.body?.classList?.remove?.('gev-imagery-box');
}
@@ -236,14 +151,16 @@ export function initImageryBoxTool({
function setActive(next) {
if (next === active) return active;
if (next) {
lease = claimPointer(IMAGERY_BOX_POINTER_OWNER);
if (!lease) {
onCancel?.(
'pointer-busy',
`${pointerOwner()} is using the pointer — close it first`,
);
return active;
}
// The newest claim takes over: a tool holding the pointer is told and
// turns itself off, and a newer one cancels this session as if the
// person had.
const claimed = claimPointer(IMAGERY_BOX_POINTER_OWNER, {
onLost: () => {
if (lease === claimed) cancel();
},
});
if (!claimed) return active;
lease = claimed;
active = true;
bindScene();
} else {
@@ -264,7 +181,7 @@ export function initImageryBoxTool({
}
return {
/** Begin a box session. False when the pointer is held elsewhere. */
/** Begin a box session, taking the pointer from any tool holding it. */
start() {
return !destroyed && setActive(true);
},
@@ -274,22 +191,14 @@ export function initImageryBoxTool({
},
/** Returns everything; resolves once the preview is detached. */
destroy() {
if (destroyed) return attaching;
if (destroyed) return preview.destroy();
if (active) setActive(false);
destroyed = true;
releaseScene();
releasePointer(lease);
lease = null;
thawCamera();
dataSource.entities.removeAll();
attaching = attaching.then(() => {
try {
viewer.dataSources.remove(dataSource, true);
} catch {
/* viewer already disposed */
}
});
return attaching;
return preview.destroy();
},
};
}
+74 -17
View File
@@ -11,16 +11,20 @@ import {
initImageryBoxTool,
} from './imageryBoxTool.js';
import { boxToolFakes } from '../layers/recentImagery/testDoubles.mjs';
import { createImageryBoxPreview } from '../layers/recentImagery/rendering.js';
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
function fixture(options = {}) {
resetPointerOwnership();
const fakes = boxToolFakes();
const draw = fakeDrawPort();
const boxes = [];
const cancels = [];
const actives = [];
const tool = initImageryBoxTool({
viewer: fakes.viewer,
cesium: fakes.cesium,
createPreview: (viewer, dragBox) =>
createImageryBoxPreview(viewer, dragBox, { draw }),
pickWorld: fakes.pickWorld,
documentRef: fakes.documentRef,
onBox: (box) => boxes.push(box),
@@ -29,12 +33,35 @@ function fixture(options = {}) {
...options,
});
const camera = fakes.viewer.scene.screenSpaceCameraController;
// The stock action as it runs now: the input port holds them, so it is
// the original while not suppressed, and none while it is.
const stockAction = (type) =>
fakes.viewer.screenSpaceEventHandler.getInputAction(fakes.types[type]);
fakes.stockEnabled(type === 'LEFT_CLICK' ? 'select' : 'dblclickFollow')
? type === 'LEFT_CLICK'
? fakes.originalClick
: fakes.originalDouble
: undefined;
// The preview's fill or outline set, while it is live.
const previewSet = (part) =>
[...draw.sets.values()].find(
(r) =>
!r.disposed &&
r.spec.id.startsWith('recent-imagery-box:') &&
r.spec.id.endsWith(`:${part}`),
);
// Whether the box shows: its fill and its outline, drawn and shown.
const preview = () =>
fakes.viewer.dataSources.sources[0]?.entities.values.every((e) => e.show);
['fill', 'outline'].every((part) => {
const set = previewSet(part);
return (
Boolean(set?.items.size) &&
[...set.items.values()].every((item) => item.show !== false)
);
});
return {
...fakes,
draw,
previewSet,
tool,
boxes,
cancels,
@@ -55,8 +82,16 @@ test('a session claims the pointer, borrows the stock clicks, freezes the camera
assert.equal(f.camera.enableInputs, true, 'not frozen before the press');
f.fire('LEFT_DOWN', { position: { x: 250, y: 125 } });
assert.equal(f.camera.enableInputs, false);
assert.equal(f.preview(), true);
assert.equal(f.preview(), false, 'a press alone has no box to draw');
f.fire('MOUSE_MOVE', { endPosition: { x: 500, y: 250 } });
assert.equal(f.preview(), true, 'the box shows as it is dragged');
const rect = () => f.previewSet('fill').items.get('box').geometry.rect;
assert.deepEqual(
Object.values(rect()).map((v) => Math.round(v * 1e6) / 1e6),
[-97.85, 30.3, -97.8, 30.35],
);
assert.equal(f.previewSet('outline').items.get('edge').style.kind, 'dash');
assert.equal(f.previewSet('outline').items.get('edge').mode, 'draped');
f.fire('MOUSE_MOVE', { endPosition: { x: 500, y: 10 } }); // sky: ignored
f.fire('LEFT_UP', { position: { x: 500, y: 250 } });
assert.equal(f.boxes.length, 1);
@@ -74,7 +109,7 @@ test('a session claims the pointer, borrows the stock clicks, freezes the camera
assert.equal(f.preview(), false);
assert.equal(f.documentRef.classes.has('gev-imagery-box'), false);
assert.equal(f.documentRef.listeners.length, 0);
assert.equal(f.handler(), null);
assert.equal(f.bound(), false);
assert.deepEqual(f.actives, [true, false]);
await f.tool.destroy();
});
@@ -125,17 +160,36 @@ test('an Escape interceptor that claims the key leaves the tool armed; the next
await f.tool.destroy();
});
test('a held pointer refuses the session and nothing is borrowed', async () => {
test('a session takes the pointer from another tool, which is told', async () => {
const f = fixture();
const lease = claimPointer('draw');
assert.equal(f.tool.start(), false);
assert.deepEqual(f.cancels, [
['pointer-busy', 'draw is using the pointer — close it first'],
]);
assert.equal(f.stockAction('LEFT_CLICK'), f.originalClick);
assert.equal(f.handler(), null);
releasePointer(lease);
let lost = 0;
claimPointer('draw', { onLost: () => (lost += 1) });
assert.equal(f.tool.start(), true);
assert.equal(pointerOwner(), IMAGERY_BOX_POINTER_OWNER);
assert.equal(lost, 1);
assert.deepEqual(f.cancels, []);
await f.tool.destroy();
});
test('a newer tool taking the pointer mid-drag cancels the session and returns everything', async () => {
const f = fixture();
f.tool.start();
f.fire('LEFT_DOWN', { position: { x: 250, y: 125 } });
f.fire('MOUSE_MOVE', { endPosition: { x: 500, y: 250 } });
assert.equal(f.camera.enableInputs, false);
const lease = claimPointer('draw');
assert.equal(f.tool.isActive(), false);
assert.deepEqual(f.cancels, [['cancel', undefined]], 'as if cancelled');
assert.deepEqual(f.actives, [true, false]);
assert.equal(f.camera.enableInputs, true, 'the camera is back');
assert.equal(f.preview(), false, 'no box is left on the globe');
assert.equal(f.stockAction('LEFT_CLICK'), f.originalClick);
assert.equal(f.bound(), false);
assert.equal(f.documentRef.classes.has('gev-imagery-box'), false);
assert.equal(pointerOwner(), 'draw', 'the newer tool keeps it');
f.fire('LEFT_UP', { position: { x: 500, y: 250 } });
assert.deepEqual(f.boxes, [], 'the drag it ended hands over no box');
releasePointer(lease);
await f.tool.destroy();
});
@@ -143,11 +197,14 @@ test('destroy mid-drag restores the camera, releases the claim and detaches the
const f = fixture();
f.tool.start();
f.fire('LEFT_DOWN', { position: { x: 250, y: 125 } });
assert.equal(f.viewer.dataSources.sources.length, 1);
await f.tool.destroy();
assert.ok(f.previewSet('fill') && f.previewSet('outline'));
const destroying = f.tool.destroy();
assert.equal(f.tool.destroy(), destroying);
await destroying;
assert.equal(f.camera.enableInputs, true);
assert.equal(pointerOwner(), null);
assert.equal(f.viewer.dataSources.sources.length, 0);
assert.equal(f.previewSet('fill'), undefined, 'the preview is gone');
assert.equal(f.previewSet('outline'), undefined);
assert.equal(f.stockAction('LEFT_CLICK'), f.originalClick);
assert.equal(f.tool.start(), false);
assert.equal(initImageryBoxTool({ viewer: null, onBox() {} }), null);
+20
View File
@@ -24,6 +24,26 @@ function defaultValueText(beforePercent, afterPercent) {
return `A ${beforePercent} percent, B ${afterPercent} percent`;
}
/**
* A globe port's split as `createImagerySplit` writes it (its `scene`): the
* divider moves the globe's split through the port. Null when the globe
* has no split.
* @param {import('../render/contract/globe').GlobePort|null|undefined} globe
* @returns {{splitPosition: number}|null}
*/
export function globeSplitTarget(globe) {
const imagery = globe?.imagery;
if (!imagery?.setSplit) return null;
return {
get splitPosition() {
return imagery.getSplit();
},
set splitPosition(value) {
imagery.setSplit(value);
},
};
}
/**
* Split divider for before/after imagery comparison.
*
+2
View File
@@ -1,5 +1,6 @@
<script setup>
import { vClassToggle } from '../rail/classToggle.js';
import UiPanelEdge from './UiPanelEdge.vue';
import UiPanelToggle from './UiPanelToggle.vue';
// Core's panel, with a name, title, slots and v-model:collapsed. It draws Core's panel markup
@@ -57,6 +58,7 @@ const emit = defineEmits(['update:collapsed']);
<slot name="badge" />
<span class="panel-divider"></span>
<slot name="actions" />
<UiPanelEdge v-if="props.collapsible" />
<UiPanelToggle
v-if="props.collapsible"
:target="props.id"
+48
View File
@@ -0,0 +1,48 @@
<script setup>
import { computed, onMounted, ref } from 'vue';
import { t } from '../../i18n/index.js';
import { panelEdge, panelSide, togglePanelEdge } from '../panelEdge.js';
// A panel header's edge switch: it slides this side's panels over their rail
// to the screen edge, and back. The side comes from the column the panel is in.
const button = ref(null);
const side = ref('left');
const on = computed(() => panelEdge.value[side.value]);
function toggle() {
side.value = panelSide(button.value);
togglePanelEdge(side.value);
}
function sync() {
side.value = panelSide(button.value);
}
// The layout moves some panels to the right column after they mount, so the
// side is read again once that has happened.
onMounted(() => {
sync();
globalThis.requestAnimationFrame?.(sync);
});
const icon = computed(() =>
side.value === 'right' ? 'align_horizontal_right' : 'align_horizontal_left',
);
const label = computed(() =>
on.value
? t('Move panels back beside the rail')
: t('Move panels over the rail, to the edge'),
);
</script>
<template>
<button
ref="button"
type="button"
class="ui-panel-edge panel-edge-btn"
:aria-pressed="String(on)"
:aria-label="label"
:title="label"
@pointerenter="sync"
@focus="sync"
@click="toggle"
>
<span class="material-symbols-outlined" aria-hidden="true">{{ icon }}</span>
</button>
</template>
+25 -5
View File
@@ -1,3 +1,4 @@
import { onFollowChanged } from '../data/followed.js';
import { isExplicitLayerStateOrigin } from '../data/layerState.js';
import {
registerCctvFocusRequestListener,
@@ -80,11 +81,13 @@ export class LayerBindings {
window,
this._worldRequestFocusHandler,
);
this._navigationOwnerChangedRemover =
this.viewer.trackedEntityChanged.addEventListener((entity) => {
if (entity && !this._disposed)
this._navigationOwnerChangedRemover = onFollowChanged(
this.viewer,
(followed) => {
if (followed && !this._disposed)
this._stampNavigation({ cancelPendingSelection: false });
});
},
);
// Vessel/installation focus flies without ever assigning a tracked entity,
// so it cannot reach the listener above. It announces instead.
this._removeNavigationAuthorityListener =
@@ -116,7 +119,6 @@ export class LayerBindings {
this.runImmediateNavigation('route', navigate),
floorFn: (lat, lon) => this.services.cachedGroundFloor(lat, lon),
warmFn: (cells) => this.services.warmGroundFloor(cells),
showToast: (message) => this._showToast(message),
});
}
@@ -147,6 +149,24 @@ export class LayerBindings {
fires.attachShellServices({ imageryHost: this.services.imageryHost });
this._weatherShellModules.push(fires);
}
// News flies to a chosen report or hotspot through the same release.
const news = this._dataManager?.layers?.get('news')?.module;
if (typeof news?.attachShellServices === 'function') {
news.attachShellServices({
runNavigation: (navigate) =>
this.runImmediateNavigation('news', navigate),
});
this._weatherShellModules.push(news);
}
// Bike share flies into a covered city from its marker the same way.
const bikeshare = this._dataManager?.layers?.get('bikeshare')?.module;
if (typeof bikeshare?.attachShellServices === 'function') {
bikeshare.attachShellServices({
runNavigation: (navigate) =>
this.runImmediateNavigation('bike share', navigate),
});
this._weatherShellModules.push(bikeshare);
}
}
_persistAwarenessSelection(event, cleared = false) {
+200
View File
@@ -0,0 +1,200 @@
// src/ui/layerFinder.test.mjs — the Data Layers finder and section index work
// on the rows LayerRows renders: search, the On/Off and category filter,
// Escape, the clear request voice sends, and the group ticks.
import '../testSupport/registerDom.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import { createApp, h, nextTick } from 'vue';
import LayerFinder, {
LAYER_FINDER_CLEAR_EVENT,
} from './views/panels/LayerFinder.vue';
import LayerSectionIndex from './views/panels/LayerSectionIndex.vue';
const ROWS = [
{ group: 'movement', heading: 'Movement' },
{ id: 'flights', name: 'Live Flights', english: 'Live Flights', on: true },
{ id: 'ships', name: 'Ships', english: 'Ships', on: false },
{ group: 'weather', heading: 'Weather' },
{ id: 'radar', name: 'Radar météo', english: 'Weather Radar', on: false },
];
const flush = async () => {
await nextTick();
await new Promise((resolve) => setTimeout(resolve, 0));
await nextTick();
};
function fixture(t) {
document.body.replaceChildren();
// Frames run at once, so the observers' batching does not hold a test up.
globalThis.requestAnimationFrame = (fn) => setTimeout(fn, 0);
globalThis.cancelAnimationFrame = (id) => clearTimeout(id);
const panel = document.body.appendChild(document.createElement('section'));
panel.id = 'data-panel';
const header = panel.appendChild(document.createElement('div'));
const bar = panel.appendChild(document.createElement('div'));
const list = panel.appendChild(document.createElement('div'));
list.id = 'data-toggles';
for (const row of ROWS) {
if (row.heading) {
const heading = list.appendChild(document.createElement('h3'));
heading.className = 'data-layer-group-heading';
heading.dataset.group = row.group;
heading.textContent = row.heading;
continue;
}
const el = list.appendChild(document.createElement('div'));
el.className = 'data-toggle-row';
el.dataset.layerId = row.id;
el.dataset.layerName = row.english;
el.innerHTML = `<span class="data-name">${row.name}</span><button class="data-toggle-btn${row.on ? ' active' : ''}"></button>`;
}
const index = panel.appendChild(document.createElement('div'));
const apps = [
createApp(() => h(LayerFinder, { part: 'buttons' })),
createApp(() => h(LayerFinder, { part: 'bar' })),
createApp(LayerSectionIndex),
];
apps[0].mount(header);
apps[1].mount(bar);
apps[2].mount(index);
t.after(async () => {
document.dispatchEvent(new CustomEvent(LAYER_FINDER_CLEAR_EVENT));
for (const app of apps) app.unmount();
});
const shown = () =>
[...list.querySelectorAll('.data-toggle-row:not(.is-filtered)')].map(
(row) => row.dataset.layerId,
);
const search = async (text) => {
if (!document.getElementById('layer-finder-input')) {
document.getElementById('layer-finder-search-btn').click();
await flush();
}
const input = document.getElementById('layer-finder-input');
input.value = text;
input.dispatchEvent(new Event('input', { bubbles: true }));
await flush();
};
const openFilter = async () => {
document.querySelector('[aria-controls="layer-finder-menu"]').click();
await flush();
return document.getElementById('layer-finder-menu');
};
return { list, panel, shown, search, openFilter };
}
test('search finds a layer by the name on screen or its English name', async (t) => {
const { shown, search, list } = fixture(t);
await search('météo');
assert.deepEqual(shown(), ['radar']);
await search('weather radar');
assert.deepEqual(shown(), ['radar']);
// The Movement heading has no rows left, so it is hidden too.
assert.equal(
list
.querySelector('[data-group="movement"]')
.classList.contains('is-filtered'),
true,
);
await search('nothing like it');
assert.deepEqual(shown(), []);
assert.match(
document.querySelector('.layer-finder__empty')?.textContent || '',
/No layers match/,
);
});
test('On and Off follow whether the layer is enabled', async (t) => {
const { shown, openFilter } = fixture(t);
const menu = await openFilter();
const on = [...menu.querySelectorAll('button')].find((b) =>
b.textContent.trim().endsWith('On'),
);
on.click();
await flush();
assert.deepEqual(shown(), ['flights']);
assert.equal(on.getAttribute('aria-pressed'), 'true');
});
test('a chosen category survives its heading being translated', async (t) => {
const { shown, openFilter, list } = fixture(t);
const menu = await openFilter();
[...menu.querySelectorAll('button')]
.find((b) => b.textContent.trim().endsWith('Weather'))
.click();
await flush();
assert.deepEqual(shown(), ['radar']);
list.querySelector('[data-group="weather"]').textContent = 'Météo';
await flush();
assert.deepEqual(shown(), ['radar']);
assert.match(
document.querySelector('.layer-finder__chip').textContent,
/Météo/,
);
});
test('Escape in the search field closes it without reaching the panel', async (t) => {
const { search, panel } = fixture(t);
let reached = false;
panel.addEventListener('keydown', () => (reached = true));
await search('ships');
document
.getElementById('layer-finder-input')
.dispatchEvent(
new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }),
);
await flush();
assert.equal(reached, false);
assert.equal(document.getElementById('layer-finder-input') === null, true);
assert.equal(document.activeElement?.id, 'layer-finder-search-btn');
});
test('the filter menu takes focus, moves with the arrows and closes on Escape', async (t) => {
const { openFilter } = fixture(t);
const menu = await openFilter();
const buttons = [...menu.querySelectorAll('button')];
assert.equal(document.activeElement, buttons[0]);
menu.dispatchEvent(
new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true }),
);
assert.equal(document.activeElement, buttons[1]);
menu.dispatchEvent(
new KeyboardEvent('keydown', { key: 'End', bubbles: true }),
);
assert.equal(document.activeElement, buttons.at(-1));
menu.dispatchEvent(
new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }),
);
await flush();
assert.equal(document.getElementById('layer-finder-menu') === null, true);
assert.equal(
document.activeElement,
document.querySelector('[aria-controls="layer-finder-menu"]'),
);
});
test('a clear request shows every row again', async (t) => {
const { shown, search } = fixture(t);
await search('ships');
assert.deepEqual(shown(), ['ships']);
document.dispatchEvent(new CustomEvent(LAYER_FINDER_CLEAR_EVENT));
await flush();
assert.deepEqual(shown(), ['flights', 'ships', 'radar']);
});
test('the section index has a tick per group and drops filtered groups', async (t) => {
const { search } = fixture(t);
await flush();
assert.equal(
document.querySelectorAll('.layer-section-index__tick').length,
2,
);
await search('ships');
await flush();
// One group left: no index.
assert.equal(
document.querySelectorAll('.layer-section-index__tick').length,
0,
);
});
+3
View File
@@ -32,12 +32,15 @@ export const LAYER_NAME_KEYS = Object.freeze({
'local-adsb': msg('Local ADS-B'),
'osm-places': msg('OSM Places'),
transit: msg('Transit'),
rail: msg('Rail'),
'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'),
news: msg('News'),
shipwrecks: msg('Shipwrecks'),
wind: msg('Wind'),
'weather-radar': msg('Rain radar'),
'weather-satellite': msg('Satellite clouds'),
+78 -16
View File
@@ -11,6 +11,7 @@ import {
} from './layerNames.js';
export { localizeLayerName } from './layerNames.js';
import { createWeatherPanel } from './weatherPanel.js';
import { createNewsPanel } from './newsPanel.js';
import {
translateFeedError,
translateStatusLine,
@@ -52,6 +53,7 @@ const PANEL_GROUPS = [
'ais-live-vessels',
'traffic',
'transit',
'rail',
'bikeshare',
],
},
@@ -81,6 +83,8 @@ const PANEL_GROUPS = [
'fire-perimeters',
'gnss-integrity',
's2-ghostmaps',
'shipwrecks',
'news',
],
},
{
@@ -116,6 +120,17 @@ const PANEL_ORDER = PANEL_GROUPS.flatMap(({ label, ids, containerId }) =>
const PANEL_POSITIONS = new Map(
PANEL_ORDER.map(({ id }, index) => [id, index]),
);
// Data Library layers follow every core group, in the order they were added.
const LIBRARY_GROUP = msg('Library');
const panelPosition = (layer) =>
layer.libraryEntryId
? PANEL_ORDER.length + 1
: (PANEL_POSITIONS.get(layer.id) ?? PANEL_ORDER.length);
const panelGroup = (layer) =>
layer.libraryEntryId
? LIBRARY_GROUP
: (PANEL_ORDER[PANEL_POSITIONS.get(layer.id)]?.label ??
msg('Other layers'));
function englishPanelLabel(layer) {
return PANEL_LABELS[layer.id] || LAYER_NAME_KEYS[layer.id] || layer.name;
@@ -317,6 +332,11 @@ export class LayerPanel {
container?.ownerDocument?.getElementById?.('weather-panel-body'),
setLayerParams: this.setLayerParams,
});
this._newsPanel?.destroy();
this._newsPanel = createNewsPanel({
container: container?.ownerDocument?.getElementById?.('news-panel-body'),
setLayerParams: this.setLayerParams,
});
this._mountRecentImagery();
this._renderToggles();
}
@@ -352,6 +372,8 @@ export class LayerPanel {
this._releaseBindings();
this._weatherPanel?.destroy();
this._weatherPanel = null;
this._newsPanel?.destroy();
this._newsPanel = null;
this._recentImageryPanel?.destroy();
this._recentImageryPanel = null;
this._recentImageryFactory = null;
@@ -361,6 +383,10 @@ export class LayerPanel {
this._groupContainers = new Map();
this._toggleContainer = null;
}
/** Rebuild the rows after the layer set changed (a Data Library add/remove). */
rerender() {
this._renderToggles();
}
_renderToggles() {
if (this._destroyed || !this._toggleContainer) return;
this._releaseBindings();
@@ -369,19 +395,13 @@ export class LayerPanel {
// its toggle and metadata.
const layers = this.getAll()
.slice()
.sort(
(a, b) =>
(PANEL_POSITIONS.get(a.id) ?? PANEL_ORDER.length) -
(PANEL_POSITIONS.get(b.id) ?? PANEL_ORDER.length),
);
.sort((a, b) => panelPosition(a) - panelPosition(b));
this._rows = [];
this._rowViews = new Map();
let previousGroup = '';
for (const layer of layers) {
if (!layer.showInTogglePanel) continue;
const group =
PANEL_ORDER[PANEL_POSITIONS.get(layer.id)]?.label ??
msg('Other layers');
const group = panelGroup(layer);
const containerId =
PANEL_ORDER[PANEL_POSITIONS.get(layer.id)]?.containerId;
const container = this._groupContainers.has(containerId)
@@ -416,10 +436,12 @@ export class LayerPanel {
onLocaleChange(() => {
this._paint();
this._refreshWeatherPanel();
this._refreshNewsPanel();
}),
);
this._paint();
this._refreshWeatherPanel();
this._refreshNewsPanel();
}
/** Present every row from the layers' current state and render them. */
@@ -451,6 +473,8 @@ export class LayerPanel {
this._selectListItem(layerId, itemId, generation),
onSlider: (layerId, sliderId, value) =>
this._moveSlider(layerId, sliderId, value, generation),
onRange: (layerId, rangeId, end, value) =>
this._pickRangeEnd(layerId, rangeId, end, value, generation),
}),
id === null ? this._toggleContainer : this._groupContainers.get(id),
);
@@ -470,6 +494,7 @@ export class LayerPanel {
id: layer.id,
// English name for voice tools, which must not receive translated text.
englishName: englishPanelLabel(layer),
libraryEntry: layer.libraryEntryId || null,
icon: layer.icon,
name: panelLabel(layer),
count: row.count ? presentLayerCount(layer.stats) : null,
@@ -480,7 +505,7 @@ export class LayerPanel {
}
/**
* A layer's row chips, one-of-many switch, slider, color legend, info line
* A layer's row chips, one-of-many switch, slider, start/end pickers, color legend, info line
* and ordered list. The block
* is hidden while the layer is off (or while a dependency owner has
* surrendered it), so a quiet row stays quiet. Chips and list items are
@@ -489,7 +514,12 @@ export class LayerPanel {
* controls for good, and a shown info line stays.
*/
_presentControls(row, layer) {
const controls = layer.enabled ? this._rowControlsFor(layer.id) : null;
// A quiet row stays quiet while off, except Data Library rows, whose
// actions (zoom, remove) work on a layer that is off.
const controls =
layer.enabled || layer.libraryEntryId
? this._rowControlsFor(layer.id)
: null;
if (controls?.readout) {
// The row became a rail readout: its controls go for good.
row.controls = false;
@@ -507,6 +537,7 @@ export class LayerPanel {
const infoText = controls?.info ? String(controls.info) : '';
const segmented = controls?.segmented || null;
const slider = controls?.slider || null;
const range = controls?.range || null;
// The info line, once shown, stays in place and hides when empty.
if (infoText) row.info = true;
return {
@@ -515,10 +546,12 @@ export class LayerPanel {
legend.length === 0 &&
!infoText &&
!segmented &&
!slider,
!slider &&
!range,
chips,
segmented,
slider,
range,
legend,
info: row.info
? { text: infoText, title: controls?.infoTitle || '' }
@@ -562,7 +595,8 @@ export class LayerPanel {
...(live?.chips || []),
...(live?.segmented?.options || []),
].find((entry) => entry.id === chipId);
if (!chip || chip.disabled || !this.isEnabled(id)) return;
if (!chip || chip.disabled || (!this.isEnabled(id) && !chip.whileOff))
return;
if (typeof chip.onClick === 'function') chip.onClick();
else if (chip.params)
this.setLayerParams(id, chip.params, { origin: 'user' });
@@ -583,6 +617,20 @@ export class LayerPanel {
this.setLayerParams(id, slider.params(value), { origin: 'user' });
}
_pickRangeEnd(id, rangeId, end, value, generation = this._generation) {
if (this._destroyed || this._generation !== generation) return;
const range = this._rowControlsFor(id)?.range;
if (
!range ||
range.id !== rangeId ||
(end !== 'from' && end !== 'to') ||
typeof range.params !== 'function' ||
!this.isEnabled(id)
)
return;
this.setLayerParams(id, range.params(end, value), { origin: 'user' });
}
_selectListItem(id, itemId, generation = this._generation) {
if (this._destroyed || this._generation !== generation) return;
const item = this._rowControlsFor(id)?.list?.items?.find(
@@ -648,6 +696,15 @@ export class LayerPanel {
}
this._paint();
this._refreshWeatherPanel();
this._refreshNewsPanel();
}
/** Feed the News rail panel the view the news layer publishes while on. */
_refreshNewsPanel() {
const layer = this.getAll().find(({ id }) => id === 'news');
this._newsPanel?.update(
layer?.enabled ? this._rowControlsFor(layer.id)?.feed || null : null,
);
}
_buildMetaText(layer) {
@@ -700,7 +757,9 @@ export class LayerPanel {
) {
return `${source} · ${translateStatusMessage(stats.statusMessage.trim())}`;
}
const ago = stats.lastUpdate ? this._timeAgo(stats.lastUpdate) : t('never');
const ago = stats.lastUpdate
? this._timeAgo(stats.lastUpdate, stats.atMs)
: t('never');
if (stats.loading) {
const loadingLabel =
typeof stats.loadingLabel === 'string' && stats.loadingLabel.trim()
@@ -743,7 +802,7 @@ export class LayerPanel {
// row by the oldest of it, not by the load that re-served it.
const dataAgo =
Number(stats.oldestTileAt) > 0
? this._timeAgo(stats.oldestTileAt)
? this._timeAgo(stats.oldestTileAt, stats.atMs)
: ago;
if (typeof stats.retryInSec === 'number' && stats.retryInSec > 0) {
return t('{state} · {source} · {ago} · retrying in {seconds}s', {
@@ -768,8 +827,11 @@ export class LayerPanel {
return t('{source} · {ago}', { source, ago });
}
_timeAgo(timestamp) {
const diff = Math.floor((Date.now() - timestamp) / 1000);
/** How long before `nowMs` (the layer's world time, else the wall clock). */
_timeAgo(timestamp, nowMs) {
const diff = Math.floor(
((Number.isFinite(nowMs) ? nowMs : Date.now()) - timestamp) / 1000,
);
if (diff < 5) return t('just now');
if (diff < 60) return t('{count}s ago', { count: diff });
if (diff < 3600) return t('{count}m ago', { count: Math.floor(diff / 60) });
+5 -2
View File
@@ -4,7 +4,7 @@ import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { runInNewContext } from 'node:vm';
test('panel presentation places Transit between Street Traffic and Bike Share in Movement', () => {
test('panel presentation places Transit and Rail between Street Traffic and Bike Share in Movement', () => {
const source = readFileSync(
new URL('./layerPanel.js', import.meta.url),
'utf8',
@@ -28,10 +28,12 @@ test('panel presentation places Transit between Street Traffic and Bike Share in
'ais-live-vessels',
'traffic',
'transit',
'rail',
'bikeshare',
],
);
assert.equal(order.filter(({ id }) => id === 'transit').length, 1);
assert.equal(order.filter(({ id }) => id === 'rail').length, 1);
});
test('Wildlife follows Events and precedes Weather', () => {
@@ -50,7 +52,8 @@ test('Wildlife follows Events and precedes Weather', () => {
);
const wildlife = order.findIndex(({ id }) => id === 'wildlife-sightings');
assert.equal(order[wildlife].label, 'Wildlife');
assert.equal(order[wildlife - 1].id, 's2-ghostmaps');
// News is the last of Events.
assert.equal(order[wildlife - 1].id, 'news');
assert.equal(order[wildlife + 1].id, 'air-quality');
assert.equal(order.filter(({ id }) => id === 'wildlife-sightings').length, 1);
});
+15 -3
View File
@@ -1,6 +1,7 @@
<script setup>
import RailChips from '../rail/RailChips.vue';
import RailRowList from '../rail/RailRowList.vue';
import RowRange from './RowRange.vue';
import RowSlider from './RowSlider.vue';
import RowSwitch from './RowSwitch.vue';
import RowText from './RowText.vue';
@@ -15,14 +16,17 @@ defineProps({
onChip: { type: Function, default: () => {} },
onListItem: { type: Function, default: () => {} },
onSlider: { type: Function, default: () => {} },
onRange: { type: Function, default: () => {} },
});
</script>
<template>
<template v-for="item in items" :key="item.key"
><h3 v-if="item.heading" class="data-layer-group-heading">{{
item.heading
}}</h3
><h3
v-if="item.heading"
class="data-layer-group-heading"
:data-group="item.key"
>{{ item.heading }}</h3
><div
v-else
class="data-toggle-row"
@@ -31,6 +35,7 @@ defineProps({
}"
:data-layer-id="item.id"
:data-layer-name="item.englishName"
:data-library-entry="item.libraryEntry || undefined"
><div class="data-toggle-top"
><div class="data-toggle-left"
><span class="data-icon" aria-hidden="true">{{ item.icon }}</span
@@ -68,6 +73,13 @@ defineProps({
:on-input="
(value) => onSlider(item.id, item.controls.slider.id, value)
"
/><RowRange
v-if="item.controls.range"
:range="item.controls.range"
:on-select="
(end, value) =>
onRange(item.id, item.controls.range.id, end, value)
"
/><span
v-for="(entry, index) in item.controls.legend"
:key="index"
+40
View File
@@ -0,0 +1,40 @@
<script setup>
// A row's start and end pickers on one line (e.g. the Shipwrecks period).
// Both ends share one option list; `onSelect` reports which end moved
// ('from' or 'to') and the chosen option value.
defineProps({
range: { type: Object, required: true },
onSelect: { type: Function, default: () => {} },
});
</script>
<template>
<div class="data-toggle-range" :data-range-id="range.id"
><div class="data-toggle-slider-head"
><span class="data-toggle-slider-label">{{ range.label }}</span
><span class="data-toggle-slider-value gev-slider-value">{{
range.valueText
}}</span></div
><div class="data-toggle-range-ends"
><label
v-for="end in ['from', 'to']"
:key="end"
class="data-toggle-range-end"
><span class="data-toggle-range-caption">{{ range[end].label }}</span
><select
class="data-toggle-range-select"
:data-range-end="end"
:aria-label="range[end].ariaLabel || undefined"
:value="String(range[end].value)"
@change="onSelect(end, $event.target.value)"
><option
v-for="option in range.options"
:key="option.value"
:value="String(option.value)"
>{{ option.label }}</option
></select
></label
></div
></div
>
</template>
+113
View File
@@ -159,3 +159,116 @@ test('a row switch and slider render their markup and report choices', () => {
assert.equal(segments[1].classList.contains('active'), true);
render(null, container);
});
test('a row range renders start and end pickers and reports which end moved', () => {
document.body.replaceChildren();
const container = document.body.appendChild(document.createElement('div'));
const picks = [];
const item = {
...row(false),
key: 'shipwrecks',
id: 'shipwrecks',
controls: {
hidden: false,
chips: [],
segmented: null,
slider: null,
range: {
id: 'period',
label: 'Period',
valueText: '2010–2024',
from: { label: 'From', ariaLabel: 'First year', value: 2010 },
to: { label: 'To', ariaLabel: 'Last year', value: 2024 },
options: [2024, 2010, 2007].map((year) => ({
value: year,
label: String(year),
})),
},
legend: [],
info: null,
list: null,
},
};
render(
h(LayerRows, {
items: [item],
onRange: (id, rangeId, end, value) =>
picks.push([id, rangeId, end, value]),
}),
container,
);
const block = container.querySelector('.data-toggle-range');
assert.equal(block.dataset.rangeId, 'period');
assert.equal(
block.querySelector('.data-toggle-slider-value').textContent,
'2010–2024',
);
const [from, to] = block.querySelectorAll('select.data-toggle-range-select');
assert.equal(from.getAttribute('aria-label'), 'First year');
assert.equal(from.value, '2010');
assert.equal(to.value, '2024');
assert.deepEqual(
[...block.querySelectorAll('.data-toggle-range-caption')].map(
(caption) => caption.textContent,
),
['From', 'To'],
);
to.value = '2007';
to.dispatchEvent(new Event('change', { bubbles: true }));
assert.deepEqual(picks, [['shipwrecks', 'period', 'to', '2007']]);
render(null, container);
});
const libraryRow = (chips) => ({
...row(false),
key: 'lib-night-lights',
id: 'lib-night-lights',
libraryEntry: 'nasa-black-marble',
controls: { hidden: false, chips, legend: [], list: null },
});
test('a Data Library row names its entry and draws icon action chips', () => {
document.body.replaceChildren();
const container = document.body.appendChild(document.createElement('div'));
const zoom = {
id: 'zoom',
icon: 'zoom_in_map',
action: true,
label: 'Zoom to layer',
};
render(h(LayerRows, { items: [libraryRow([zoom])] }), container);
const element = container.querySelector('[data-layer-id="lib-night-lights"]');
assert.equal(element.dataset.libraryEntry, 'nasa-black-marble');
const button = element.querySelector('[data-chip-id="zoom"]');
const glyph = button.children[0];
assert.equal(glyph.className, 'material-symbols-outlined');
assert.equal(glyph.textContent, 'zoom_in_map');
assert.equal(glyph.getAttribute('aria-hidden'), 'true');
assert.equal(button.getAttribute('aria-label'), 'Zoom to layer');
assert.equal(button.title, 'Zoom to layer');
assert.equal(button.getAttribute('aria-pressed'), null);
assert.ok(button.classList.contains('chip-icon'));
// The same id as a text toggle drops the icon semantics.
render(
h(LayerRows, {
items: [libraryRow([{ id: 'zoom', label: 'ZOOM', active: true }])],
}),
container,
);
const toggle = element.querySelector('[data-chip-id="zoom"]');
assert.equal(toggle.textContent, 'ZOOM');
assert.equal(toggle.getAttribute('aria-label'), null);
assert.equal(toggle.getAttribute('aria-pressed'), 'true');
assert.equal(toggle.classList.contains('chip-icon'), false);
render(null, container);
});
test('a core row carries no library entry attribute', () => {
document.body.replaceChildren();
const container = document.body.appendChild(document.createElement('div'));
render(h(LayerRows, { items: [row(false)] }), container);
const element = container.querySelector('[data-layer-id="flights"]');
assert.equal(element.hasAttribute('data-library-entry'), false);
render(null, container);
});
+11 -1
View File
@@ -60,6 +60,7 @@ export function layoutLeftPanelRail({
stack.style.removeProperty('--left-stack-safe-bottom');
stack.style.removeProperty('--left-stack-centered-height');
stack.style.removeProperty('--panel-rail-offset');
stack.style.removeProperty('--panel-rail-lift');
stack.classList.remove('layout-exclusive');
stack.dataset.layoutMode = 'mobile';
settleSideAccordion({ panels, enabled: false, onCollapse });
@@ -282,10 +283,19 @@ export function layoutLeftPanelRail({
getComputedStyle(stack)
.getPropertyValue?.('--panel-stack-top-pinned')
?.trim() === '1';
const railOffset = `${(topPinned ? 0 : safeTop - layoutTop).toFixed(1)}px`;
// The stack itself rises by the lift below, by a different amount for a
// tall panel than at rest; the rail takes up the difference.
const lift = (top) => Math.min(0, obstacleSafeTop - top);
const railOffset = `${(topPinned ? 0 : safeTop + lift(safeTop) - layoutTop - lift(layoutTop)).toFixed(1)}px`;
if (stack.style.getPropertyValue('--panel-rail-offset') !== railOffset) {
stack.style.setProperty('--panel-rail-offset', railOffset);
}
// How far the column can rise before it meets the HUD readout, so the rail
// and any open panel sit just under it, whether or not a panel is open.
const railLift = `${(topPinned ? 0 : lift(layoutTop)).toFixed(1)}px`;
if (stack.style.getPropertyValue('--panel-rail-lift') !== railLift) {
stack.style.setProperty('--panel-rail-lift', railLift);
}
stack.style.removeProperty('--left-stack-centered-height');
for (const panel of panels)
panel.style.removeProperty('--left-panel-allocated-height');
+402
View File
@@ -0,0 +1,402 @@
/**
* DATA LAYERS ▸ Browse data library: the owner of the dialog that lists every
* Data Library entry this build knows, with its licence, coverage and what
* this instance needs to serve it, and adds or removes it from the panel.
*
* Framework-free: `createLibraryBrowser` presents the dialog's state (open,
* filters, the rows they show, the stat summary, Remove all) through
* `publish`, and its `controls` answer the view
* (src/ui/views/panels/DataLibraryDialog.vue, placed by LayerPanelsView). The
* text helpers below are what the view renders; they call `t()`, so text
* rendered through them follows the locale.
*
* A `dialog[data-panel-surface]` per docs/panel-surfaces.md: the view owns
* width, height, labels and focus; this owner closes the dialog when clean
* view, recording or Cockpit hides the panels.
*/
import { formatNumber, msg, t, tn } from '../i18n/index.js';
const PANEL_HIDING_MODES = ['ui-clean-view', 'recording-mode', 'cockpit-mode'];
/** How long Remove all stays armed after its first press. */
const RESET_CONFIRM_MS = 4000;
/** How often the open dialog rereads its stat tiles (the panel's own pace). */
const STATS_REFRESH_MS = 1000;
const FAMILY_LABELS = Object.freeze({
movement: msg('Movement'),
cameras: msg('Cameras'),
infrastructure: msg('Infrastructure'),
events: msg('Events'),
weather: msg('Weather'),
environment: msg('Environment'),
imagery: msg('Imagery'),
demographics: msg('Demographics'),
});
const KIND_LABELS = Object.freeze({
dataset: msg('DATASET'),
tiles: msg('TILES'),
pack: msg('PACK'),
});
const STATUS_LABELS = Object.freeze({
incubating: msg('INCUBATING'),
community: msg('COMMUNITY'),
verified: msg('VERIFIED'),
stale: msg('STALE'),
archived: msg('ARCHIVED'),
});
/** The Theme filter's choices, translated: all themes first. */
export function libraryThemeOptions() {
return [
{ value: '', label: t('All themes') },
...Object.entries(FAMILY_LABELS).map(([value, label]) => ({
value,
label: t(label),
})),
];
}
/**
* An entry card's badges: kind, status, then how it is served (operator
* opt-in, a provider key, or keyless). `tone` is '', 'good' or 'warn'.
* @param {object} entry
* @returns {Array<{ label: string, tone: string }>}
*/
export function libraryBadges(entry) {
const badges = [
{ label: t(KIND_LABELS[entry.kind]), tone: '' },
{
label: t(STATUS_LABELS[entry.status]),
tone:
entry.status === 'verified'
? 'good'
: entry.status === 'stale'
? 'warn'
: '',
},
];
if (entry.licence.operatorOptIn)
badges.push({ label: t('OPT-IN'), tone: 'warn' });
else if (entry.kind !== 'pack' && entry.source.key)
badges.push({ label: t('KEY'), tone: 'warn' });
else if (entry.kind !== 'pack')
badges.push({ label: t('KEYLESS'), tone: '' });
return badges;
}
const compact = (value) =>
formatNumber(value, { notation: 'compact', maximumFractionDigits: 1 });
/**
* The four stat tiles at the top of Browse: label, value and one line of
* breakdown each. Text only; nothing here is a data colour.
* @param {ReturnType<ReturnType<typeof import('../library/controller.js').createDataLibrary>['summary']>} summary
* @returns {Array<{ id: string, label: string, value: string, detail: string }>}
*/
export function libraryStatTiles(summary) {
const { kinds } = summary;
return [
{
id: 'entries',
label: t('Datasets'),
value: compact(summary.entries),
detail: t('{datasets} · {tiles} · {packs}', {
datasets: tn(kinds.dataset, '{count} dataset', '{count} datasets'),
tiles: tn(kinds.tiles, '{count} tile layer', '{count} tile layers'),
packs: tn(kinds.pack, '{count} pack', '{count} packs'),
}),
},
{
id: 'themes',
label: t('Themes'),
value: compact(summary.themes.length),
// The count alone: the theme names are the Theme filter below.
detail: '',
},
{
id: 'added',
label: t('Added'),
value: compact(summary.added),
detail: summary.added
? tn(summary.on, '{count} on the map', '{count} on the map')
: t('none yet'),
},
{
id: 'features',
label: t('Map features'),
value: summary.featureLayers ? compact(summary.features) : '—',
detail: summary.featureLayers
? tn(
summary.featureLayers,
'from {count} dataset',
'from {count} datasets',
)
: t('switch on a dataset to load features'),
},
];
}
/** The sentence explaining what this instance needs to serve an entry. */
export function libraryReasonText({ entry, available, reason }) {
if (entry.kind === 'pack')
return available
? t('Switched on by this instance · part of the CCTV layer')
: t('Operator opt-in: set {env}=1 on the server', {
env: entry.pack.env,
});
if (available) return '';
if (reason === 'operator-opt-in')
return t('Operator opt-in: add {id} to GEV_LIBRARY_ENABLE on the server', {
id: entry.id,
});
if (reason === 'operator-disabled')
return t("Turned off by this instance's operator");
if (reason === 'key-missing') return t('Needs a provider key on the server');
if (reason === 'server-unavailable')
return t("Needs this app's server · not available in a static build");
return t('Checking what this instance serves…');
}
/** Where an entry covers, for its card line. */
export function coverageText(entry) {
const { coverage } = entry;
if (coverage.global) return t('Global');
if (coverage.countries?.length) return coverage.countries.join(' · ');
return t('Regional');
}
const IMAGERY_TYPE_LABELS = Object.freeze({
ortho: msg('Orthophoto'),
'satellite-mosaic': msg('Satellite mosaic'),
oblique: msg('Oblique'),
historic: msg('Historic imagery'),
});
/**
* An imagery entry's specs as label/value pairs for its card: what it is,
* how sharp, when it was flown and how often it is refreshed.
* @param {object} entry
* @returns {Array<{ label: string, value: string }>}
*/
export function imagerySpecs(entry) {
const imagery = entry?.imagery;
if (!imagery) return [];
const type =
imagery.type === 'ortho' && imagery.trueOrtho
? t('True orthophoto')
: t(IMAGERY_TYPE_LABELS[imagery.type]);
return [
{ label: t('Type'), value: type },
{ label: t('Resolution'), value: imagery.resolution },
imagery.vintage && { label: t('Flown'), value: imagery.vintage },
imagery.updateCycle && { label: t('Updates'), value: imagery.updateCycle },
imagery.orthoQuality && {
label: t('Ortho quality'),
value: imagery.orthoQuality,
},
].filter(Boolean);
}
/**
* Whether a row matches the current filters.
* @param {{ entry: object, available: boolean, added: boolean }} row
* @param {{ query: string, family: string, availableOnly: boolean }} filter
*/
export function libraryRowMatches(row, { query, family, availableOnly }) {
const { entry } = row;
if (entry.status === 'archived' && !row.added) return false;
if (family && entry.family !== family) return false;
if (availableOnly && !row.available) return false;
const needle = String(query || '')
.trim()
.toLocaleLowerCase();
if (!needle) return true;
return [
entry.title,
entry.provider,
entry.description,
entry.id,
entry.imagery?.resolution,
...(entry.coverage.countries || []),
]
.join(' ')
.toLocaleLowerCase()
.includes(needle);
}
/**
* Browse order: what a viewer can add first, then what this instance would
* need to switch on, then packs (which a host layer owns), each by title.
* @param {Array<{ entry: object, available: boolean }>} rows
*/
export function sortLibraryRows(rows) {
const rank = ({ entry, available }) =>
entry.kind === 'pack' ? 2 : available ? 0 : 1;
return [...rows].sort(
(a, b) =>
rank(a) - rank(b) || a.entry.title.localeCompare(b.entry.title, 'en'),
);
}
/**
* The Browse dialog's owner. Presents its state through `publish` and answers
* the view through `controls`; never touches the dialog's markup.
* @param {{ library: ReturnType<import('../library/controller.js').createDataLibrary>, publish?: (view: object|null) => void, body?: HTMLElement|null }} options
* @returns {{ controls: object, open: () => void, close: () => void, destroy: () => void }}
*/
export function createLibraryBrowser({
library,
publish = () => {},
body = globalThis.document?.body ?? null,
}) {
const filter = { query: '', family: '', availableOnly: false };
let open = false;
let destroyed = false;
let rows = [];
let statsTimer = null;
// Remove all asks twice: the first press arms it for a few seconds.
let resetArmed = false;
let resetTimer = null;
let resetting = false;
// Bumped when focus should go back to the search field (after Remove all).
let focusSearch = 0;
function disarmReset() {
clearTimeout(resetTimer);
resetTimer = null;
resetArmed = false;
}
/**
* Publish the dialog. Rows are reread from the library unless only the
* stat tiles changed, so an unchanged row list keeps its identity and its
* cards do not re-render.
*/
function present({ rowsChanged = true } = {}) {
if (destroyed) return;
if (rowsChanged || !rows.length) rows = library.list();
const added = rows.filter((row) => row.added).length;
if (!added && !resetting && resetArmed) disarmReset();
publish({
open,
ready: library.ready,
filter: { ...filter },
shown: open
? sortLibraryRows(rows.filter((row) => libraryRowMatches(row, filter)))
: [],
total: rows.length,
added,
summary: library.summary(),
reset: {
visible: added > 0 || resetting,
armed: resetArmed,
busy: resetting,
},
focusSearch,
});
}
function close() {
disarmReset();
clearInterval(statsTimer);
statsTimer = null;
if (!open) return;
open = false;
present();
}
const controls = {
open() {
if (destroyed || open) return;
open = true;
present();
// Feature counts arrive as datasets finish loading, outside the
// library's own notifications; refresh the tiles while open.
clearInterval(statsTimer);
statsTimer = setInterval(
() => present({ rowsChanged: false }),
STATS_REFRESH_MS,
);
},
close,
setQuery(value) {
filter.query = String(value ?? '');
present({ rowsChanged: false });
},
setFamily(value) {
filter.family = String(value ?? '');
present({ rowsChanged: false });
},
setAvailableOnly(value) {
filter.availableOnly = Boolean(value);
present({ rowsChanged: false });
},
add(id) {
Promise.resolve(library.add(id)).catch((error) =>
console.warn(`[Library] ${id} failed:`, error),
);
},
remove(id) {
Promise.resolve(library.remove(id)).catch((error) =>
console.warn(`[Library] ${id} failed:`, error),
);
},
zoom(id) {
// Close first so the flight is visible; focus returns to Browse. An
// entry that is off is switched on first.
close();
Promise.resolve(library.zoom(id)).catch((error) =>
console.warn(`[Library] ${id} zoom failed:`, error),
);
},
reset() {
if (resetting) return;
if (!resetArmed) {
resetArmed = true;
resetTimer = setTimeout(() => {
disarmReset();
present({ rowsChanged: false });
}, RESET_CONFIRM_MS);
present({ rowsChanged: false });
return;
}
disarmReset();
resetting = true;
present({ rowsChanged: false });
Promise.resolve(library.reset())
.catch((error) => console.warn('[Library] reset failed:', error))
.finally(() => {
resetting = false;
focusSearch += 1;
present();
});
},
};
const unsubscribe = library.subscribe(() => present());
const observer =
typeof MutationObserver === 'function' && body
? new MutationObserver(() => {
if (PANEL_HIDING_MODES.some((mode) => body.classList.contains(mode)))
close();
})
: null;
observer?.observe(body, { attributes: true, attributeFilter: ['class'] });
present();
return {
controls,
open: controls.open,
close,
destroy() {
if (destroyed) return;
close();
destroyed = true;
unsubscribe();
observer?.disconnect();
publish(null);
},
};
}
+158
View File
@@ -0,0 +1,158 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
libraryReasonText,
libraryRowMatches,
libraryStatTiles,
sortLibraryRows,
} from './libraryBrowser.js';
import { libraryEntry } from '../library/catalog.js';
import { localInfrastructureOverlayCopy } from '../data/localGeojsonCore.js';
const row = (id, extra = {}) => ({
entry: libraryEntry(id),
available: true,
added: false,
...extra,
});
const all = { query: '', family: '', availableOnly: false };
test('Browse filters by text, theme and what this instance serves', () => {
assert.ok(
libraryRowMatches(row('eia-power-plants'), { ...all, query: 'eia' }),
);
assert.ok(
libraryRowMatches(row('eia-power-plants'), { ...all, query: 'us' }),
);
assert.equal(
libraryRowMatches(row('eia-power-plants'), { ...all, query: 'volcano' }),
false,
);
assert.equal(
libraryRowMatches(row('eia-power-plants'), { ...all, family: 'events' }),
false,
);
assert.equal(
libraryRowMatches(row('cctv-nyc-dot', { available: false }), {
...all,
availableOnly: true,
}),
false,
);
});
test('the guidance names the exact operator switch', () => {
assert.match(
libraryReasonText({ ...row('cctv-nyc-dot'), available: false }),
/CCTV_NYC_ENABLED=1/,
);
assert.match(
libraryReasonText({ ...row('cctv-nyc-dot'), available: true }),
/part of the CCTV layer/,
);
assert.match(
libraryReasonText({
...row('gvp-holocene-volcanoes'),
available: false,
reason: 'server-unavailable',
}),
/static build/,
);
assert.equal(libraryReasonText(row('nasa-eonet-events')), '');
});
test('library features show their manifest card lines on the map', () => {
const copy = localInfrastructureOverlayCopy(
{
name: 'Grand Coulee',
__gevDetails: ['PrimSource: hydroelectric', 'Total_MW: 6809', 'extra'],
},
'lib-eia-power-plants',
);
assert.deepEqual(copy, {
title: 'Grand Coulee',
details: ['PrimSource: hydroelectric', 'Total_MW: 6809'],
});
});
test('Browse lists what a viewer can add first and packs last', () => {
const order = sortLibraryRows([
row('cctv-nyc-dot', { available: false }),
row('nasa-eonet-events'),
row('gvp-holocene-volcanoes', { available: false }),
row('eia-power-plants'),
]).map(({ entry }) => entry.id);
assert.deepEqual(order, [
'nasa-eonet-events',
'eia-power-plants',
'gvp-holocene-volcanoes',
'cctv-nyc-dot',
]);
});
test('the stat tiles summarise the library in words and compact numbers', () => {
const tiles = libraryStatTiles({
entries: 8,
kinds: { dataset: 3, tiles: 2, pack: 3 },
themes: ['cameras', 'environment', 'events', 'imagery', 'infrastructure'],
available: 5,
unavailable: 3,
added: 2,
on: 1,
features: 3712,
featureLayers: 2,
});
assert.deepEqual(
tiles.map(({ id, value, detail }) => [id, value, detail]),
[
['entries', '8', '3 datasets · 2 tile layers · 3 packs'],
['themes', '5', ''],
['added', '2', '1 on the map'],
['features', '3.7K', 'from 2 datasets'],
],
);
const empty = libraryStatTiles({
entries: 1,
kinds: { dataset: 1, tiles: 0, pack: 0 },
themes: ['events'],
available: 1,
unavailable: 0,
added: 0,
on: 0,
features: 0,
featureLayers: 0,
});
assert.deepEqual(
empty.map(({ value, detail }) => [value, detail]),
[
['1', '1 dataset · 0 tile layers · 0 packs'],
['1', ''],
['0', 'none yet'],
['—', 'switch on a dataset to load features'],
],
);
});
test('an imagery card lists type, resolution, years flown and refresh', async () => {
const { imagerySpecs } = await import('./libraryBrowser.js');
const specs = imagerySpecs({
imagery: {
type: 'ortho',
trueOrtho: true,
resolution: '5 cm',
vintage: '2024',
updateCycle: 'Annual',
},
});
assert.deepEqual(
specs.map(({ label }) => label),
['Type', 'Resolution', 'Flown', 'Updates'],
);
assert.equal(specs[0].value, 'True orthophoto');
assert.equal(specs[1].value, '5 cm');
assert.equal(
imagerySpecs(libraryEntry('ign-orthophotos-france'))[0].value,
'Orthophoto',
);
assert.deepEqual(imagerySpecs(libraryEntry('eia-power-plants')), []);
});
+8
View File
@@ -52,6 +52,8 @@ test('the current language comes first, the rest by their own names', () => {
'fr',
'it',
'pt',
'sv',
'he',
'ar',
'zh-CN',
'zh-Hant',
@@ -73,8 +75,10 @@ test('the current language comes first, the rest by their own names', () => {
'fr',
'it',
'pt',
'sv',
'ru',
'uk',
'he',
'ar',
'zh-CN',
'zh-Hant',
@@ -96,8 +100,10 @@ test('the current language comes first, the rest by their own names', () => {
'fr',
'it',
'pt',
'sv',
'ru',
'uk',
'he',
'ar',
'zh-CN',
'zh-Hant',
@@ -120,8 +126,10 @@ test('the current language comes first, the rest by their own names', () => {
'fr',
'it',
'pt',
'sv',
'ru',
'uk',
'he',
'zh-CN',
'zh-Hant',
'ja',
+2 -2
View File
@@ -340,12 +340,12 @@ test('the provider settings corner shows the picker only while the shell publish
app.mount(host);
t.after(() => app.unmount());
const store = useLocaleStore(pinia);
assert.equal(document.getElementById('locale-picker'), null);
assert.equal(document.getElementById('locale-picker') === null, true);
store.publishPicker({ current: 'de', onSelect() {} });
await nextTick();
const code = document.querySelector('#corner-actions .locale-picker-code');
assert.equal(code?.textContent, 'DE');
store.publishPicker(null);
await nextTick();
assert.equal(document.getElementById('locale-picker'), null);
assert.equal(document.getElementById('locale-picker') === null, true);
});
+3
View File
@@ -88,6 +88,9 @@ export class LocationControls {
event.target === elements.search
)
return;
// As for the application shortcuts: Cmd+R, Ctrl+W, Alt+E and the like
// belong to the browser and the system. Shift is not a chord.
if (event.metaKey || event.ctrlKey || event.altKey) return;
const index = POI_KEYS.indexOf(event.key.toUpperCase());
if (index !== -1 && index < (cities[cityId]?.pois.length || 0))
onPoi(cityId, index);
+10
View File
@@ -191,6 +191,16 @@ test('location and POI keys route once while form controls retain typing', () =>
f.controls.reset();
assert.deepEqual(f.calls, [['poi', 'a', 1], ['reset']]);
});
test('POI keys held with Cmd, Ctrl or Alt run no POI; Shift still does', () => {
const f = fixture();
const target = { matches: () => false };
for (const modifier of ['metaKey', 'ctrlKey', 'altKey'])
for (const key of ['q', 'w', 'r', 'R'])
f.doc.fire('keydown', { key, target, [modifier]: true });
assert.deepEqual(f.calls, []);
f.doc.fire('keydown', { key: 'W', target, shiftKey: true });
assert.deepEqual(f.calls, [['poi', 'a', 1]]);
});
test('typing clears a failed search error and closing the emptied field drops it too', () => {
const f = fixture();
f.elements.search.value = 'Pariss';
+39 -15
View File
@@ -1,7 +1,9 @@
import * as Cesium from 'cesium';
import { findCamera } from '../render/rendererOf.js';
import { stopFollowing } from '../data/followed.js';
import { t } from '../i18n/index.js';
import { createStateChannel } from '../app/stateChannel.js';
import { LocationControls } from './location.js';
import { worldClock } from '../time/worldClock.js';
/** Own destination selection, lookup, orbit and world-jump lifetime. */
export class LocationNavigation {
@@ -13,10 +15,11 @@ export class LocationNavigation {
navigation,
readCockpit,
operations,
homeView = null,
}) {
Object.assign(
this,
{ viewer, placeSearch, services, navigation, readCockpit },
{ viewer, placeSearch, services, navigation, readCockpit, homeView },
elements,
operations,
);
@@ -314,7 +317,24 @@ export class LocationNavigation {
}
}
resetToGlobeView() {
/**
* Back to live, at the view the app started from (the logo): the world
* clock goes live and the camera flies to the start view as the globe reset
* does, letting go of whatever it follows.
*/
returnToStart() {
if (!this._disposed) worldClock.goLive();
if (!this.homeView) return this.resetToGlobeView();
// A globe reset under way flies elsewhere: this one replaces it.
this._cancelGlobeReset?.();
return this.resetToGlobeView({ view: this.homeView });
}
/**
* Fly out to the full globe over the current spot, or to `view` (the start
* view's shape: `{ lon, lat, height, heading?, pitch? }`, degrees).
*/
resetToGlobeView({ view = null } = {}) {
const {
GLOBE_VIEW,
flyToGlobeView,
@@ -367,11 +387,13 @@ export class LocationNavigation {
} catch {
/* best-effort release */
}
this.viewer.trackedEntity = undefined;
this.viewer.camera.cancelFlight();
this.viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
stopFollowing(this.viewer);
const camera = findCamera(this.viewer);
camera?.cancelFlight();
camera?.release();
this._beginWorldJumpTransition();
const heightM = view?.height ?? GLOBE_VIEW.heightM;
let resolveReset;
const resetPromise = new Promise((resolve) => {
resolveReset = resolve;
@@ -384,15 +406,19 @@ export class LocationNavigation {
settled = true;
clearTimeout(timer);
this._endWorldJumpTransition();
const carto = this.viewer.camera.positionCartographic;
const pose = findCamera(this.viewer)?.pose();
const result = {
ok: !cancelled,
action: 'zoom_to_globe',
cancelled,
heightKm: Math.round(GLOBE_VIEW.heightM / 1000),
heightKm: Math.round(heightM / 1000),
centeredOn: {
latitude: Number(Cesium.Math.toDegrees(carto.latitude).toFixed(2)),
longitude: Number(Cesium.Math.toDegrees(carto.longitude).toFixed(2)),
latitude: Number.isFinite(pose?.lat)
? Number(pose.lat.toFixed(2))
: null,
longitude: Number.isFinite(pose?.lon)
? Number(pose.lon.toFixed(2))
: null,
},
};
this._publishGlobeResetting?.(false);
@@ -402,16 +428,14 @@ export class LocationNavigation {
};
this._cancelGlobeReset = () => finish(true);
timer = window.setTimeout(() => {
const height = this.viewer.camera.positionCartographic?.height;
finish(
!Number.isFinite(height) ||
Math.abs(height - GLOBE_VIEW.heightM) > 1000,
);
const height = findCamera(this.viewer)?.pose().height;
finish(!Number.isFinite(height) || Math.abs(height - heightM) > 1000);
}, 4200);
this._publishGlobeResetting?.(true);
const target = flyToGlobeView(this.viewer, {
onComplete: () => finish(false),
onCancel: () => finish(true),
...(view ? { view } : {}),
});
if (!target) finish(true);
return resetPromise;
+2 -1
View File
@@ -368,7 +368,8 @@ export function initMobileShell({
: sheet === 'search'
? [dock]
: sheet === 'more'
? [element('right-context-rail'), dock]
? // Visual lives in the left stack; the dock holds the presets.
[element('left-panel-stack'), dock]
: [element('right-context-rail')];
return roots.find((root) => root?.contains(target));
};
+20 -2
View File
@@ -10,6 +10,7 @@ import {
nextSheet,
sheetForPanelId,
} from './mobileShell.js';
import { withEntityRecord } from '../data/entityRecords.js';
function element(tag, document) {
const node = new EventTarget();
@@ -623,7 +624,7 @@ test('the phone shell keeps the required attribution visible', () => {
);
const openDock = rule('body.mobile-shell[data-mobile-sheet] #command-dock');
const railSheet = rule(
"body.mobile-shell[data-mobile-sheet='more'] #right-context-rail",
"body.mobile-shell[data-mobile-sheet='more'] #left-panel-stack",
);
assert.ok(z(sheetCredit) > z(openDock));
assert.ok(z(sheetCredit) > z(railSheet));
@@ -824,7 +825,7 @@ test('the tab-open callback reports only a successful manual opening', () => {
test('manual Context opens the existing transaction without disabling the tracked aircraft', async () => {
const calls = [];
const tracked = { layerId: 'flights', icao24: 'abc123', callsign: 'EJA225' };
const viewer = { trackedEntity: { gevTrackedId: 'flights:abc123' } };
const viewer = { trackedEntity: withEntityRecord({}, { trackedId: 'flights:abc123' }) };
const entity = viewer.trackedEntity;
const enabled = new Set(['flights', 'weather']);
const controls = new ContextControls({
@@ -977,3 +978,20 @@ test('a slow downward pull is claimed before Android native scroll takes ownersh
assert.equal(shell.getSheet(), null);
shell.destroy();
});
test('on phones the News panel shows in the Context sheet only, like Weather', () => {
const css = readFileSync(
new URL('./styles/mobile-shell.css', import.meta.url),
'utf8',
);
// Hidden by id: the rail's own `#news-panel:not(.collapsed)` rule outranks
// the generic `#right-context-rail > *` hiding rule.
assert.match(
css,
/body\.mobile-shell #right-context-rail > #news-panel,\n[^{}]*\{\s*display: none;/,
);
assert.match(
css,
/body\.mobile-shell\[data-mobile-sheet='context'\]\s+#right-context-rail\s+> #news-panel:not\(\[hidden\]\),/,
);
});
+7 -5
View File
@@ -1,6 +1,7 @@
import { findCamera } from '../render/rendererOf.js';
import { stopFollowing } from '../data/followed.js';
import { cancelCameraArrival } from '../data/cameraArrival.js';
import { createStateChannel } from '../app/stateChannel.js';
import * as Cesium from 'cesium';
import {
beginDeferredNavigation,
reassertNavigationHandoff,
@@ -176,12 +177,13 @@ export class NavigationController {
} catch {
/* best-effort release */
}
this.viewer.trackedEntity = undefined;
stopFollowing(this.viewer);
this.interruptCameraMotion('explicit-navigation');
this.stopOrbit();
if (!preserveCameraFlight) this.viewer.camera.cancelFlight();
const camera = findCamera(this.viewer);
if (!preserveCameraFlight) camera?.cancelFlight();
try {
this.viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
camera?.release();
} catch {
/* teardown race */
}
@@ -215,7 +217,7 @@ export class NavigationController {
release: () => {
this.interruptCameraMotion('camera-orientation');
this.stopOrbit();
this.viewer.camera.cancelFlight();
findCamera(this.viewer)?.cancelFlight();
},
navigate,
});
+159
View File
@@ -0,0 +1,159 @@
<script setup>
import { ref, watch } from 'vue';
import { t } from '../../i18n/index.js';
import UiButton from '../kit/UiButton.vue';
// One event in the News panel: the publisher's
// picture when the event has one, the headline, a mono meta line (severity
// marker, category, place, sources, age), who reported it, its attestation
// and media chips, and the service it came through ("via …"), which some ask
// to be credited wherever their reports show. A click chooses it (the layer
// flies there and opens its card on the globe); open, it plays the post's
// clip when it has one (on request, with sound and controls), and shows the
// summary, the other sides' reports and the link to the original article.
// The layer computes every value shown (feedCardView in
// src/layers/news/model.js).
const props = defineProps({
item: { type: Object, required: true },
open: { type: Boolean, default: false },
onChoose: { type: Function, default: () => {} },
onClear: { type: Function, default: () => {} },
});
// A picture the publisher no longer serves leaves the card without one.
const pictureFailed = ref(false);
const dropPicture = () => {
pictureFailed.value = true;
};
// So does a clip whose signed link has expired.
const clipFailed = ref(false);
const dropClip = () => {
clipFailed.value = true;
};
watch(
() => props.item.picture?.url,
() => {
pictureFailed.value = false;
clipFailed.value = false;
},
);
const meta = () =>
[
props.item.category,
props.item.place &&
(props.item.placedByModel
? t('{place} (placed by model)', { place: props.item.place })
: props.item.place),
props.item.sources,
props.item.age,
]
.filter(Boolean)
.join(' · ');
</script>
<template>
<article
class="news-card"
:class="{ 'is-open': open, 'is-unmapped': !item.mappable }"
:data-report-id="item.id"
:style="{ '--news-color': item.color }"
>
<button
type="button"
class="news-card__main ui-focus"
:aria-expanded="open ? 'true' : 'false'"
@click="onChoose(item)"
>
<span v-if="item.picture && !pictureFailed" class="news-card__thumb"
><img
:src="item.picture.url"
alt=""
loading="lazy"
decoding="async"
referrerpolicy="no-referrer"
v-on="{ error: dropPicture }"
/><span
v-if="item.picture.video && !clipFailed"
class="news-card__play"
role="img"
:aria-label="t('Video')"
>▶</span
><span v-if="item.picture.credit" class="news-card__credit">{{
item.picture.credit
}}</span></span
>
<span class="news-card__title">{{ item.title }}</span>
<span v-if="item.original" class="news-card__note">{{
t('English headline by the model')
}}</span>
<span class="news-card__meta ui-mono"
><span
class="news-card__marker"
:class="{ solid: item.solid }"
role="img"
:aria-label="item.severityLabel"
:title="item.severityLabel"
><svg viewBox="0 0 16 16" aria-hidden="true">
<path :d="item.icon" /></svg></span
><span v-if="item.severity >= 2" class="news-card__severity">{{
item.severityLabel
}}</span
>{{ item.severity >= 2 ? ` · ${meta()}` : meta() }}</span
>
<span v-if="item.sides" class="news-card__sides">{{ item.sides }}</span>
<span v-if="item.chips.length" class="news-card__chips"
><span
v-for="chip in item.chips"
:key="`${chip.kind}:${chip.label}`"
class="news-chip"
:class="`news-chip--${chip.kind}`"
>{{ chip.label }}</span
></span
>
<span v-if="item.via" class="news-card__via ui-mono">{{ item.via }}</span>
</button>
<div v-if="open" class="news-card__open">
<video
v-if="item.picture?.video && !clipFailed"
class="news-card__clip"
:src="item.picture.video"
:poster="pictureFailed ? undefined : item.picture.url"
controls
playsinline
preload="none"
referrerpolicy="no-referrer"
v-on="{ error: dropClip }"
></video>
<p v-if="item.original" class="news-card__original">{{
item.original
}}</p>
<p v-if="item.snippet" class="news-card__snippet">{{ item.snippet }}</p>
<p v-if="!item.mappable" class="news-card__note">
{{ t('Not placed on the map') }}
</p>
<ul v-if="item.others.length" class="news-card__others">
<li v-for="other in item.others" :key="other.url">
<span class="news-card__side ui-mono">{{ other.side }}</span
><a :href="other.url" target="_blank" rel="noopener noreferrer"
>{{ other.publisher }}: {{ other.title }}</a
>
</li>
</ul>
<div class="news-card__actions">
<a
class="news-card__link"
:href="item.url"
target="_blank"
rel="noopener noreferrer"
>{{ item.sourceLink }}</a
>
<UiButton
class="data-toggle-chip news-card__clear"
type="button"
@click="onClear()"
>{{ t('Close') }}</UiButton
>
</div>
</div>
</article>
</template>
+317
View File
@@ -0,0 +1,317 @@
<script setup>
import { computed } from 'vue';
import { formatNumber, t, tn } from '../../i18n/index.js';
import UiButton from '../kit/UiButton.vue';
import UiEmpty from '../kit/UiEmpty.vue';
import UiSelect from '../kit/UiSelect.js';
import RailChips from '../rail/RailChips.vue';
import NewsCard from './NewsCard.vue';
// The News panel: the window the server serves only (the last 24 hours, or
// fewer where the host serves less), or a shorter one chosen at the
// top (24/12/6/3/1 h), and two sections. Conflicts: hotspot chips, the
// severity floor, the chosen event and a continuous feed, newest first.
// Local: every report in the area at the view centre (its country, a large
// country's state; within a radius at sea) while the camera is low, named at
// the top, which the map then shows, outlined, instead of the hotspots' news.
// A section read from a key the server lacks (or whose allowance for the day
// is spent) says which key instead. It
// renders the `feed` view the news layer publishes and acts only through
// `onParams`.
const props = defineProps({
view: { type: Object, default: null },
onParams: { type: Function, default: () => {} },
});
const filters = computed(() => props.view?.filters ?? {});
const local = computed(() => filters.value.section === 'local');
const sections = computed(() =>
[
{ id: 'conflicts', label: t('Conflicts') },
{ id: 'local', label: t('Local') },
].map((chip) => ({
...chip,
active: (filters.value.section ?? 'conflicts') === chip.id,
})),
);
const chips = computed(() =>
(props.view?.hotspots ?? []).map((chip) => ({
id: chip.id,
label: `${chip.label} ${chip.count}`,
active: chip.active,
title: chip.label,
})),
);
const severityOptions = computed(() => {
const levels = props.view?.severities ?? [];
return [
{ value: '0', label: t('Any severity') },
...levels.slice(1, 3).map((level) => ({
value: String(level.value),
label: t('{severity} and above', { severity: level.label }),
})),
...levels.slice(3).map((level) => ({
value: String(level.value),
label: t('{severity} only', { severity: level.label }),
})),
];
});
const categoryOptions = computed(() => [
{ value: 'all', label: t('All categories') },
...(props.view?.categories ?? []),
]);
const windowOptions = computed(() =>
(props.view?.windowChoices ?? []).map((hours) => ({
value: String(hours),
label: lastHours(hours),
})),
);
// The window offers 1 h, so every hour count is a plural: es «Última 1 h».
function lastHours(hours) {
return tn(hours, 'Last {hours} h', 'Last {hours} h', {
hours: formatNumber(hours),
});
}
// The longest choice is the server's whole window, kept as no choice.
const chooseWindow = (hours) =>
setFilter('hours', hours === props.view?.windowChoices?.[0] ? null : hours);
const selectedId = computed(() => props.view?.selected?.id ?? null);
// The chosen event leads the panel unless the feed already shows it open.
const selectedApart = computed(() => {
const chosen = props.view?.selected;
if (!chosen) return null;
const listed = local.value
? props.view.inView.items.some((item) => item.id === chosen.id)
: props.view.items.some((item) => item.id === chosen.id);
return listed ? null : chosen;
});
// What Local reads: the area named, else the radius; neither while the
// first area is being named, so the radius does not flash before it.
const areaHead = computed(() => {
const inView = props.view?.inView;
if (!inView?.active) return '';
if (inView.area) return t('News from {area}', { area: inView.area });
if (inView.areaLoading) return '';
return t('Within {km} km of the view centre', { km: inView.radiusKm });
});
const status = computed(() => {
const view = props.view;
if (!view) return '';
if (view.error) return view.error;
if (view.loading && !view.items.length) return t('Reading the news…');
return '';
});
const setFilter = (name, value) =>
props.onParams({ filters: { [name]: value } });
function choose(item) {
if (item.id === selectedId.value) props.onParams({ clear: true });
else props.onParams({ reportId: item.id, focus: true });
}
const clear = () => props.onParams({ clear: true });
</script>
<template>
<section
v-if="view"
class="news-readout"
:aria-label="
tn(
view.windowHours,
'News, last {hours} hour',
'News, last {hours} hours',
{
hours: formatNumber(view.windowHours),
},
)
"
>
<UiSelect
v-if="windowOptions.length > 1"
class="gev-field news-filter news-readout__window-choice"
:aria-label="t('Time window')"
:model-value="String(view.windowHours)"
:options="windowOptions"
@update:model-value="chooseWindow(Number($event))"
/>
<p v-else class="news-readout__window ui-mono">{{
lastHours(view.windowHours)
}}</p>
<div
class="news-readout__sections"
role="group"
:aria-label="t('News sections')"
>
<RailChips
:chips="sections"
:on-select="(chip) => setFilter('section', chip.id)"
/>
</div>
<div
v-if="!local"
class="news-readout__chips"
role="group"
:aria-label="t('Hotspots')"
>
<RailChips
:chips="chips"
:on-select="(chip) => setFilter('hotspot', chip.id)"
/>
</div>
<div class="news-readout__filters">
<UiSelect
v-if="!local"
class="gev-field news-filter"
:aria-label="t('Severity')"
:model-value="String(filters.minSeverity ?? 2)"
:options="severityOptions"
@update:model-value="setFilter('minSeverity', Number($event))"
/>
<UiSelect
class="gev-field news-filter"
:aria-label="t('Category')"
:model-value="filters.category ?? 'all'"
:options="categoryOptions"
@update:model-value="setFilter('category', $event)"
/>
</div>
<NewsCard
v-if="selectedApart"
class="news-readout__selected"
:item="selectedApart"
open
:on-choose="choose"
:on-clear="clear"
/>
<section
v-if="local"
class="news-readout__section"
:aria-label="t('Local')"
>
<p v-if="areaHead" class="news-readout__head news-readout__area ui-mono">
{{ areaHead }}
</p>
<UiEmpty
v-if="!view.inView.active"
class="news-readout__empty"
:title="t('Zoom in to see local news')"
/>
<UiEmpty
v-else-if="view.inView.key"
class="news-readout__empty"
:title="view.inView.key.title"
:hint="view.inView.key.hint"
/>
<p v-else-if="view.inView.error" class="news-readout__status">
{{ view.inView.error }}
</p>
<UiEmpty
v-else-if="!view.inView.items.length && !view.inView.loading"
class="news-readout__empty"
:title="
tn(
view.windowHours,
'Nothing reported near here in the last {hours} h',
'Nothing reported near here in the last {hours} h',
{ hours: formatNumber(view.windowHours) },
)
"
/>
<ol
v-else
class="news-readout__list"
:class="{ 'is-stale': view.inView.loading }"
:aria-busy="view.inView.loading ? 'true' : 'false'"
>
<li v-for="item in view.inView.items" :key="item.id">
<NewsCard
:item="item"
:open="item.id === selectedId"
:on-choose="choose"
:on-clear="clear"
/>
</li>
</ol>
</section>
<section
v-else
class="news-readout__section"
:aria-label="t('Latest news')"
>
<h3 class="news-readout__head ui-mono">{{
t('Latest', { context: 'news list' })
}}</h3>
<UiEmpty
v-if="view.key"
class="news-readout__empty"
:title="view.key.title"
:hint="view.key.hint"
/>
<ol
v-else-if="view.items.length"
class="news-readout__list news-readout__feed"
>
<li v-for="item in view.items" :key="item.id">
<NewsCard
:item="item"
:open="item.id === selectedId"
:on-choose="choose"
:on-clear="clear"
/>
</li>
</ol>
<UiEmpty
v-else-if="!view.loading && !view.error"
class="news-readout__empty"
:title="
tn(
view.windowHours,
'No news matches these filters in the last {hours} h',
'No news matches these filters in the last {hours} h',
{ hours: formatNumber(view.windowHours) },
)
"
/>
<div class="news-readout__footer">
<span class="news-readout__status" role="status">{{ status }}</span>
<UiButton
v-if="view.hasMore && !view.loading"
class="data-toggle-chip"
type="button"
@click="onParams({ loadMore: true })"
>{{ t('Load older news') }}</UiButton
>
</div>
</section>
<details class="news-legend">
<summary>{{ t('How to read the map') }}</summary>
<p>{{ t('Colour: severity · icon: type of event') }}</p>
<ul class="news-legend__severity">
<li
v-for="level in view.severities"
:key="level.value"
:style="{ '--news-color': level.color }"
>
{{ level.label }}
</li>
</ul>
<p>{{
t(
'Solid rim: reported by both sides or independently. Dashed rim: a claim. Thin rim: one source, or one side’s own press.',
)
}}</p>
<p>{{
t(
'Larger: more sources · fainter: older. Picture card: a major or fast-growing event with two or more sources.',
)
}}</p>
<p>{{
t('Side labels describe the source, not whether a report is true.')
}}</p>
</details>
</section>
</template>
+89
View File
@@ -0,0 +1,89 @@
import { h, render as renderVue } from 'vue';
import NewsFeed from './news/NewsFeed.vue';
const LAYER_ID = 'news';
const LOAD_MORE_MARGIN_PX = 160;
// Remounting must not reopen a panel the reader already collapsed.
const appearedPanels = new WeakSet();
const set = (node, key, value) => {
if (node[key] !== value) node[key] = value;
};
/**
* The News rail panel (`#news-panel`): it renders the `feed` view the news
* layer publishes through its row controls, shows itself only while the
* layer is on, and acts only through setLayerParams. Near the bottom of its
* scroller it asks for the next older page, once per page; other filters or a
* failed read let it ask again.
*/
export function createNewsPanel({ container, setLayerParams = () => {} } = {}) {
const document = container?.ownerDocument;
if (!document?.createElement) return null;
const panel = container.closest?.('#news-panel');
const count = panel?.querySelector('#news-panel-count');
const onParams = (params) =>
setLayerParams(LAYER_ID, params, { origin: 'user' });
let view = null;
let destroyed = false;
let requestedAt = -1;
let shownFilters = '';
function render() {
if (destroyed) return;
renderVue(h(NewsFeed, { view, onParams }), container);
const hidden = !view;
if (panel) set(panel, 'hidden', hidden);
// The count is the shown section's: Local's list, else the feed.
const shown =
view?.filters?.section === 'local' ? view.inView?.items : view?.items;
if (count) set(count, 'textContent', String(shown?.length ?? 0));
if (!hidden && panel && !appearedPanels.has(panel)) {
appearedPanels.add(panel);
// First appearance opens the panel unless a stored or shared collapse
// choice exists (marked by the panel chrome when it restored the state).
const preference = panel.dataset?.collapsedPreference;
if (
panel.classList?.contains('collapsed') &&
(preference === undefined || preference === 'default')
)
panel.querySelector('[data-collapse-target="news-panel"]')?.click();
}
}
const onScroll = () => {
if (!view?.hasMore || view.loading) return;
const remaining =
container.scrollHeight - container.scrollTop - container.clientHeight;
if (remaining > LOAD_MORE_MARGIN_PX) return;
if (requestedAt === view.items.length) return;
requestedAt = view.items.length;
onParams({ loadMore: true });
};
container.addEventListener?.('scroll', onScroll, { passive: true });
return {
/** Show the layer's feed view, or hide the panel with null. */
update(next) {
const filters = JSON.stringify(next?.filters ?? null);
// A new list (other filters or hotspot), or a read that failed, may stop
// at the same length as the last request: let the next scroll ask.
// A list started over is shorter than the one the last request saw.
if (
filters !== shownFilters ||
(next?.error && !view?.error) ||
(next?.items?.length ?? 0) < requestedAt
)
requestedAt = -1;
shownFilters = filters;
view = next || null;
render();
},
destroy() {
destroyed = true;
container.removeEventListener?.('scroll', onScroll);
renderVue(null, container);
if (panel) set(panel, 'hidden', true);
if (count) set(count, 'textContent', '0');
},
};
}
+490
View File
@@ -0,0 +1,490 @@
import '../testSupport/registerDom.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import { setLocale } from '../i18n/index.js';
import { createNewsPanel } from './newsPanel.js';
import {
NEWS_CATEGORIES,
NEWS_SEVERITY,
categoryLabel,
feedCardView,
normalizeFilters,
} from '../layers/news/model.js';
const NOW = Date.parse('2026-10-28T10:00:00Z');
const report = (id, extra = {}) => ({
id,
title: `Report ${id}`,
url: `https://www.example.com/${id}`,
publishedAt: '2026-10-28T09:00:00.000Z',
publisher: 'Example',
side: 'UA',
category: 'strike',
severity: 2,
geo: { lat: 50, lon: 36, place: 'Kharkiv', mappable: true },
pins: [{ lat: 50, lon: 36, place: 'Kharkiv', mappable: true }],
event: null,
media: [],
...extra,
});
const big = report('big', {
severity: 3,
titleEn: 'Strike on Kharkiv',
title: 'Удар по Харкову',
media: ['video'],
event: {
size: 4,
severity: 3,
status: 'both-sides',
lastAt: '2026-10-28T09:50:00.000Z',
sides: [
{
side: 'UA',
title: 'a',
url: 'https://a.test/',
publisher: 'A',
publishedAt: '2026-10-28T09:00:00.000Z',
},
{
side: 'RU',
title: 'b',
url: 'https://b.test/',
publisher: 'B',
publishedAt: '2026-10-28T09:40:00.000Z',
},
],
image: { url: 'https://a.test/p.jpg', publisher: 'A' },
},
});
function view(extra = {}) {
return {
filters: normalizeFilters(),
hotspots: [
{ id: 'all', label: 'All', count: 7, active: true },
{ id: 'ua-ru-war', label: 'Ukraine–Russia', count: 7, active: false },
],
categories: Object.keys(NEWS_CATEGORIES).map((id) => ({
value: id,
label: categoryLabel(id),
})),
severities: NEWS_SEVERITY.map((level, index) => ({
value: index,
label: level.label,
color: level.color,
})),
items: [feedCardView(big, NOW), feedCardView(report('lone'), NOW)],
inView: { active: false, loading: false, error: null, items: [] },
selected: null,
hasMore: true,
windowHours: 24,
loading: false,
error: null,
...extra,
};
}
function fixture() {
document.body.innerHTML = `
<div id="news-panel" class="collapsed" hidden>
<span id="news-panel-count">0</span>
<button data-collapse-target="news-panel"></button>
<div id="news-panel-body"></div>
</div>`;
const panel = document.getElementById('news-panel');
let opened = 0;
panel
.querySelector('[data-collapse-target]')
.addEventListener('click', () => {
opened++;
panel.classList.remove('collapsed');
});
const calls = [];
const news = createNewsPanel({
container: document.getElementById('news-panel-body'),
setLayerParams: (id, params, options) => calls.push([id, params, options]),
});
return { news, panel, calls, opened: () => opened };
}
test('the panel shows the last 24 h as event cards and opens once', () => {
const { news, panel, opened } = fixture();
news.update(null);
assert.equal(panel.hidden, true);
news.update(view());
assert.equal(panel.hidden, false);
assert.equal(opened(), 1);
assert.equal(document.getElementById('news-panel-count').textContent, '2');
assert.equal(
panel.querySelector('.news-readout__window').textContent,
'Last 24 h',
);
assert.deepEqual(
[...panel.querySelectorAll('.news-readout__chips [data-chip-id]')].map(
(chip) => chip.textContent,
),
['All 7', 'Ukraine–Russia 7'],
);
const [first, second] = panel.querySelectorAll(
'.news-readout__feed .news-card',
);
assert.equal(
first.querySelector('.news-card__title').textContent,
'Strike on Kharkiv',
);
assert.equal(
first.querySelector('.news-card__note').textContent,
'English headline by the model',
);
assert.equal(
first.querySelector('.news-card__meta').textContent,
'Major · Strike · Kharkiv · 4 sources · 10 min',
);
assert.equal(
first.querySelector('.news-card__marker').getAttribute('aria-label'),
'Major',
);
assert.equal(
first.querySelector('.news-card__sides').textContent,
'Reported by UA sources · RU sources',
);
assert.deepEqual(
[...first.querySelectorAll('.news-chip')].map((c) => c.textContent),
['Reported by both sides', 'Video'],
);
const img = first.querySelector('.news-card__thumb img');
assert.equal(img.getAttribute('src'), 'https://a.test/p.jpg');
assert.equal(img.getAttribute('referrerpolicy'), 'no-referrer');
assert.equal(first.querySelector('.news-card__credit').textContent, 'A');
// A lone report has no picture.
assert.equal(second.querySelector('.news-card__thumb') === null, true);
// A later update does not reopen a panel the reader collapsed.
panel.classList.add('collapsed');
news.update(view());
assert.equal(opened(), 1);
news.destroy();
assert.equal(panel.hidden, true);
});
test('a card click flies there; open, it links the source and closes', () => {
const { news, panel, calls } = fixture();
news.update(view());
panel.querySelector('.news-card__main').click();
assert.deepEqual(calls.at(-1), [
'news',
{ reportId: 'big', focus: true },
{ origin: 'user' },
]);
news.update(view({ selected: feedCardView(big, NOW) }));
const open = panel.querySelector('.news-card.is-open');
const link = open.querySelector('.news-card__link');
assert.equal(link.textContent, 'Source: example.com ↗');
assert.equal(link.getAttribute('href'), 'https://www.example.com/big');
assert.equal(link.getAttribute('rel'), 'noopener noreferrer');
assert.equal(
open.querySelector('.news-card__original').textContent,
'Удар по Харкову',
);
open.querySelector('.news-card__main').click();
assert.deepEqual(calls.at(-1)[1], { clear: true });
news.destroy();
});
test('filters, the Local section and empty or failed reads', () => {
const { news, panel, calls } = fixture();
news.update(view());
assert.equal(panel.querySelector('[aria-label="Local"]') === null, true);
assert.equal(panel.querySelector('.news-toggle') === null, true);
const severity = panel.querySelector('select[aria-label="Severity"]');
assert.equal(severity.value, '2');
severity.value = '3';
severity.dispatchEvent(new Event('change'));
assert.deepEqual(calls.at(-1)[1], { filters: { minSeverity: 3 } });
panel.querySelector('[data-chip-id="ua-ru-war"]').click();
assert.deepEqual(calls.at(-1)[1], { filters: { hotspot: 'ua-ru-war' } });
panel.querySelector('[data-chip-id="local"]').click();
assert.deepEqual(calls.at(-1)[1], { filters: { section: 'local' } });
news.update(
view({
items: [],
hasMore: false,
}),
);
assert.match(
panel.textContent,
/No news matches these filters in the last 24 h/,
);
assert.equal(panel.querySelector('.news-readout__footer button') === null, true);
// Local: no hotspot chips or severity floor, and its own empty states.
const localView = (inView) =>
view({
filters: normalizeFilters({ section: 'local' }),
inView: { loading: false, error: null, items: [], ...inView },
});
news.update(localView({ active: false }));
const section = panel.querySelector('[aria-label="Local"]');
assert.match(section.textContent, /Zoom in to see local news/);
assert.equal(panel.querySelector('[data-chip-id="ua-ru-war"]') === null, true);
assert.equal(panel.querySelector('select[aria-label="Severity"]') === null, true);
assert.equal(panel.querySelector('[aria-label="Latest news"]') === null, true);
assert.equal(document.getElementById('news-panel-count').textContent, '0');
news.update(
localView({ active: true, items: [feedCardView(report('near'), NOW)] }),
);
assert.equal(document.getElementById('news-panel-count').textContent, '1');
news.update(localView({ active: true }));
assert.match(
panel.querySelector('[aria-label="Local"]').textContent,
/Nothing reported near here in the last 24 h/,
);
news.update(view());
news.update(
view({ items: [], error: 'News feed unavailable', hasMore: false }),
);
assert.equal(
panel.querySelector('.news-readout__status').textContent,
'News feed unavailable',
);
news.destroy();
});
test('each section says which key it lacks; Local names the area it reads', () => {
const { news, panel } = fixture();
const key = {
title: 'Liveuamap key required',
hint: 'Needs LIVEUAMAP_API_KEY — add it in Provider Settings',
};
news.update(view({ key, items: [], hasMore: false }));
const latest = panel.querySelector('[aria-label="Latest news"]');
assert.match(latest.textContent, /Liveuamap key required/);
assert.match(latest.textContent, /Needs LIVEUAMAP_API_KEY/);
assert.doesNotMatch(latest.textContent, /No news matches/);
const localView = (inView) =>
view({
filters: normalizeFilters({ section: 'local' }),
inView: {
active: true,
loading: false,
error: null,
items: [],
radiusKm: 500,
...inView,
},
});
const section = () => panel.querySelector('[aria-label="Local"]');
const heading = () => section().querySelector('.news-readout__area');
news.update(
localView({
key: {
title: 'World News API limit reached for today',
hint: 'News resumes tomorrow, or with a paid plan',
},
}),
);
assert.match(section().textContent, /World News API limit reached for today/);
assert.match(section().textContent, /News resumes tomorrow/);
assert.doesNotMatch(section().textContent, /Nothing reported near here/);
// The area named, else the radius at sea.
news.update(localView({ area: 'Ukraine' }));
assert.equal(heading().textContent.trim(), 'News from Ukraine');
news.update(localView({ area: null }));
assert.equal(
heading().textContent.trim(),
'Within 500 km of the view centre',
);
// While the first area is named, neither: the radius does not flash.
news.update(localView({ area: null, areaLoading: true, loading: true }));
assert.equal(heading(), null);
// A new area on the way keeps the one shown.
news.update(localView({ area: 'Ukraine', areaLoading: true, loading: true }));
assert.equal(heading().textContent.trim(), 'News from Ukraine');
news.destroy();
});
test('a card credits the service its report came through', () => {
const { news, panel } = fixture();
news.update(
view({
items: [
feedCardView(report('gdelt', { attribution: 'GDELT Project' }), NOW),
feedCardView(report('own'), NOW),
],
}),
);
const [credited, own] = panel.querySelectorAll('.news-card');
assert.equal(
credited.querySelector('.news-card__via').textContent,
'via GDELT Project',
);
assert.equal(own.querySelector('.news-card__via') === null, true);
news.destroy();
});
test('scrolling to the end asks once per page, again after a filter change or a failed read', () => {
const { news, calls } = fixture();
const body = document.getElementById('news-panel-body');
// A scroller at its bottom.
Object.defineProperty(body, 'scrollHeight', {
value: 1000,
configurable: true,
});
Object.defineProperty(body, 'clientHeight', {
value: 400,
configurable: true,
});
body.scrollTop = 600;
const loadMores = () => calls.filter(([, p]) => p.loadMore === true).length;
const scroll = () => body.dispatchEvent(new Event('scroll'));
news.update(view());
scroll();
scroll();
assert.equal(loadMores(), 1);
// The page came back with nothing new (as many items): no second request.
news.update(view());
scroll();
assert.equal(loadMores(), 1);
// Another hotspot, the same number of rows: the new list can be read on.
const hotspot = normalizeFilters({ hotspot: 'ua-ru-war' }, [
{ id: 'ua-ru-war' },
]);
news.update(view({ filters: hotspot }));
scroll();
assert.equal(loadMores(), 2);
// The read fails: the next scroll tries again.
news.update(view({ filters: hotspot, error: 'News feed unavailable' }));
scroll();
assert.equal(loadMores(), 3);
// While loading, or with no older page, nothing is asked.
news.update(view({ filters: hotspot, loading: true }));
scroll();
news.update(view({ filters: hotspot, hasMore: false }));
scroll();
assert.equal(loadMores(), 3);
news.destroy();
});
test('the window choice offers shorter windows; the longest is the server window', () => {
const { news, panel, calls } = fixture();
news.update(view({ windowHours: 12, windowChoices: [12, 6, 3, 1] }));
assert.equal(panel.querySelector('.news-readout__window') === null, true);
const choice = panel.querySelector('select[aria-label="Time window"]');
assert.deepEqual(
[...choice.options].map((option) => option.textContent),
['Last 12 h', 'Last 6 h', 'Last 3 h', 'Last 1 h'],
);
assert.equal(choice.value, '12');
choice.value = '3';
choice.dispatchEvent(new Event('change'));
assert.deepEqual(calls.at(-1)[1], { filters: { hours: 3 } });
choice.value = '12';
choice.dispatchEvent(new Event('change'));
assert.deepEqual(calls.at(-1)[1], { filters: { hours: null } });
});
test('the time window agrees with its number of hours', (t) => {
t.after(() => setLocale('en'));
setLocale('es');
const { news, panel } = fixture();
news.update(view({ windowHours: 24, windowChoices: [24, 12, 6, 3, 1] }));
const choice = panel.querySelector(
'select.news-readout__window-choice, .news-readout__window-choice select',
);
assert.deepEqual(
[...choice.options].map((option) => option.textContent),
['Últimas 24 h', 'Últimas 12 h', 'Últimas 6 h', 'Últimas 3 h', 'Última 1 h'],
);
news.update(view({ windowHours: 1, items: [], hasMore: false }));
assert.equal(
panel.querySelector('.news-readout__window').textContent,
'Última 1 h',
);
assert.equal(
panel.querySelector('.news-readout').getAttribute('aria-label'),
'Noticias de la última 1 hora',
);
assert.match(
panel.textContent,
/En la última 1 h no hay noticias que coincidan con estos filtros/,
);
setLocale('ru');
news.update(view({ windowHours: 1, items: [], hasMore: false }));
assert.equal(
panel.querySelector('.news-readout').getAttribute('aria-label'),
'Новости за последний 1 час',
);
news.update(view({ windowHours: 12, items: [], hasMore: false }));
assert.equal(
panel.querySelector('.news-readout').getAttribute('aria-label'),
'Новости за последние 12 часов',
);
news.destroy();
});
test('the Latest news heading agrees with the news it heads (fr)', (t) => {
t.after(() => setLocale('en'));
setLocale('fr');
const { news, panel } = fixture();
news.update(view());
assert.equal(panel.querySelector('.news-readout__head').textContent, 'Dernières');
news.destroy();
});
test('the panel names the window the server serves', () => {
const { news, panel } = fixture();
news.update(view({ windowHours: 12 }));
assert.equal(
panel.querySelector('.news-readout__window').textContent,
'Last 12 h',
);
});
test('a clip waits behind its picture and plays, on request, in the open card', () => {
const { news, panel } = fixture();
const clipped = report('clip', {
event: {
size: 1,
sides: [],
image: {
url: 'https://cdn4.telesco.pe/file/v.jpg',
publisher: 'Channel',
video: 'https://cdn4.telesco.pe/file/v.mp4?token=x',
},
},
});
news.update(view({ items: [feedCardView(clipped, NOW)] }));
const card = panel.querySelector('.news-card');
assert.equal(card.querySelector('.news-card__play').textContent, '▶');
assert.equal(card.querySelector('video') === null, true);
news.update(
view({
items: [feedCardView(clipped, NOW)],
selected: feedCardView(clipped, NOW),
}),
);
const video = panel.querySelector('.news-card.is-open video');
assert.equal(
video.getAttribute('src'),
'https://cdn4.telesco.pe/file/v.mp4?token=x',
);
assert.equal(
video.getAttribute('poster'),
'https://cdn4.telesco.pe/file/v.jpg',
);
assert.equal(video.getAttribute('preload'), 'none');
assert.ok(video.hasAttribute('controls'));
// An expired link leaves the card without the clip.
video.dispatchEvent(new Event('error'));
news.update(
view({
items: [feedCardView(clipped, NOW)],
selected: feedCardView(clipped, NOW),
}),
);
assert.equal(panel.querySelector('.news-card.is-open video') === null, true);
news.destroy();
});
+2
View File
@@ -17,6 +17,7 @@ const SHARE_PANEL_STATE_SPECS = Object.freeze([
{ id: 'data-panel' },
{ id: 'cctv-panel' },
{ id: 'weather-panel' },
{ id: 'news-panel' },
{ id: 'recent-imagery-panel' },
{ id: 'street-level-panel' },
{ id: 'radio-panel' },
@@ -41,6 +42,7 @@ const COCKPIT_ENTRY_COLLAPSE_PANEL_IDS = Object.freeze([
'data-panel',
'cctv-panel',
'weather-panel',
'news-panel',
'recent-imagery-panel',
'street-level-panel',
'scene-panel',
+3 -2
View File
@@ -141,6 +141,7 @@ test("UiPanel draws Core's panel markup and asks for the other state", async (t)
'demo-badge',
'panel-divider',
'demo-action',
'panel-edge-btn',
'panel-collapse-btn',
],
);
@@ -165,8 +166,8 @@ test('UiPanel without collapsible has no button, and glow is optional', (t) => {
});
const panel = document.getElementById('plain-panel');
assert.equal(panel.tagName, 'SECTION');
assert.equal(panel.querySelector('.panel-glow'), null);
assert.equal(panel.querySelector('.panel-collapse-btn'), null);
assert.equal(panel.querySelector('.panel-glow') === null, true);
assert.equal(panel.querySelector('.panel-collapse-btn') === null, true);
});
test('RailPanel follows the store, forwards clicks, and never restores a class its owner removed', async (t) => {
+42
View File
@@ -0,0 +1,42 @@
import { ref } from 'vue';
// Panels can slide over their rail to the screen edge, one setting per side:
// the left column moves onto the left rail, the right column onto the right
// rail. Each panel header has the switch (UiPanelEdge); the choice is kept
// for the next visit and shows as a body class the stylesheet reads.
const KEY = 'gev.panelEdge';
function read() {
try {
const saved = JSON.parse(globalThis.localStorage?.getItem(KEY) || '{}');
return { left: saved.left === true, right: saved.right === true };
} catch {
return { left: false, right: false };
}
}
export const panelEdge = ref(read());
function apply() {
const body = globalThis.document?.body;
if (!body) return;
body.classList.toggle('panels-edge-left', panelEdge.value.left);
body.classList.toggle('panels-edge-right', panelEdge.value.right);
}
apply();
/** Which side a panel element sits on, from the column it is in. */
export function panelSide(element) {
return element?.closest?.('#right-context-rail, #cockpit-utility-controls')
? 'right'
: 'left';
}
export function togglePanelEdge(side) {
panelEdge.value = { ...panelEdge.value, [side]: !panelEdge.value[side] };
try {
globalThis.localStorage?.setItem(KEY, JSON.stringify(panelEdge.value));
} catch {
// Without storage the choice lasts for this visit.
}
apply();
}
+20 -7
View File
@@ -27,6 +27,7 @@ const LEFT_STACK_OBSTACLE_SELECTOR = [
'#cockpit-context',
'#cesium-credits .cesium-credit-logoContainer',
'#cesium-credits .cesium-credit-textContainer',
'#gev-credits',
'#location-bar',
'#control-panel',
'#gev-voice-control',
@@ -58,6 +59,7 @@ const RIGHT_STACK_OBSTACLE_SELECTOR = [
'#cockpit-signal-stream',
'#cesium-credits .cesium-credit-logoContainer',
'#cesium-credits .cesium-credit-textContainer',
'#gev-credits',
'#command-dock',
'#gev-voice-control',
'#world-timeline',
@@ -97,6 +99,7 @@ export class PanelLayoutController {
this._ppToggles = document.getElementById('pp-toggles');
this._cctvPanel = document.getElementById('cctv-panel');
this._weatherPanel = document.getElementById('weather-panel');
this._newsPanel = document.getElementById('news-panel');
this._recentImageryPanel = document.getElementById('recent-imagery-panel');
this._streetLevelPanel = document.getElementById('street-level-panel');
}
@@ -188,17 +191,25 @@ export class PanelLayoutController {
const stack = this._rightPanelStack;
if (!stack || !this._ppToggles) return;
stack.prepend(this._ppToggles);
// Visual (presets and display settings) is the last panel of the left
// column, after the other tools, and opens from the left rail like them.
if (typeof this._leftPanelStack?.append === 'function')
this._leftPanelStack.append(this._ppToggles);
else stack.prepend(this._ppToggles);
const globalContextPanel = document.getElementById('global-context-panel');
for (const panel of [
this._cctvPanel,
this._weatherPanel,
this._newsPanel,
this._recentImageryPanel,
this._streetLevelPanel,
]) {
if (!panel) continue;
stack.insertBefore(panel, globalContextPanel);
}
// Context leads the right column: it is the panel for whatever is picked,
// and the camera panels follow it.
if (globalContextPanel) stack.prepend(globalContextPanel);
if (typeof ResizeObserver !== 'undefined') {
this._rightStackResizeObserver = new ResizeObserver(() => {
this._scheduleRightPanelLayout();
@@ -208,6 +219,7 @@ export class PanelLayoutController {
this._ppToggles,
this._cctvPanel,
this._weatherPanel,
this._newsPanel,
this._recentImageryPanel,
this._streetLevelPanel,
globalContextPanel,
@@ -342,12 +354,13 @@ export class PanelLayoutController {
attributeFilter: ['class', 'data-variant'],
});
}
const credits = document.getElementById('cesium-credits');
if (credits) {
this._leftStackMutationObserver.observe(credits, {
subtree: true,
childList: true,
});
for (const id of ['cesium-credits', 'gev-credits']) {
const credits = document.getElementById(id);
if (credits)
this._leftStackMutationObserver.observe(credits, {
subtree: true,
childList: true,
});
}
}
+12 -1
View File
@@ -6,9 +6,20 @@
* @returns {number} Natural height in CSS pixels.
*/
export function measurePanelNaturalHeight(panel, getComputedStyle) {
const inner = [...panel.children].find(
const content = [...panel.children].filter(
(child) => !child.classList.contains('panel-glow'),
);
// A panel built as a header row and a body (Visual) scrolls as a whole, so
// its full scroll height is its natural height.
if (content.length > 1) {
const panelStyle = getComputedStyle(panel);
return Math.ceil(
panel.scrollHeight +
(parseFloat(panelStyle.borderTopWidth) || 0) +
(parseFloat(panelStyle.borderBottomWidth) || 0),
);
}
const inner = content[0];
if (!inner)
return Math.ceil(
panel.scrollHeight || panel.getBoundingClientRect().height,
+5 -2
View File
@@ -9,7 +9,7 @@ export const PANEL_RAIL_FALLBACK_ICON = 'more_horiz';
/**
* How each side panel appears on its rail. Labels are the panels' own titles.
* `shownBy` names a class the panel needs to be shown at all (`f` toggles
* Data Layers' `active`).
* Data Layers' `active`). `context` is the label's translation context.
*/
export const PANEL_RAIL_ITEMS = Object.freeze({
'data-panel': {
@@ -19,9 +19,12 @@ export const PANEL_RAIL_ITEMS = Object.freeze({
},
'utilities-panel': { icon: 'handyman', label: msg('UTILITIES') },
'scene-panel': { icon: 'movie', label: msg('AUTHORING') },
'pp-toggles': { icon: 'tune', label: msg('DISPLAY') },
// `context` keeps the panel's name apart from the satellite class of the
// same English word.
'pp-toggles': { icon: 'palette', label: msg('VISUAL'), context: 'panel' },
'cctv-panel': { icon: 'videocam', label: msg('CCTV') },
'weather-panel': { icon: 'partly_cloudy_day', label: msg('WEATHER') },
'news-panel': { icon: 'public', label: msg('NEWS') },
'recent-imagery-panel': {
icon: 'satellite_alt',
label: msg('RECENT IMAGERY'),
Loaded 100 of 2063 files, more files were not shown because too many files have changed in this diff. Show more