Merge main into byrdit/recent-imagery-dateline

Resolve the Recent Imagery conflicts on main's renderer ports: dateline slots drape up to two globe-port layers, the drag preview draws a box across ±180°.
This commit is contained in:
German Khokhlov committed 2026-11-19 19:14:59 +04:00
commit 5555aba82c
2619 files changed
+259411 -57489

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,
};
}),
);
+136 -54
View File
@@ -1,3 +1,5 @@
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';
@@ -28,13 +30,16 @@ import { LocationNavigation } from './locationNavigation.js';
import { bindCameraOrientationControls } from './cameraOrientationControls.js';
import { createMapSourceControls } from './mapSource.js';
import { STYLES } from './effects.js';
import { isHudLayout } from '../hudLayouts.js';
import { isHudLayout, isLegacySonarHudLayout } from '../hudLayouts.js';
import {
getCyberSonarControlState,
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';
@@ -57,18 +62,30 @@ import { applyLocaleChoice } from './localePicker.js';
import { PanelNavigation } from './panelNavigation.js';
import { applicationPinia, createUiRuntime } from './vueRuntime.js';
import { useContextStore } from './stores/context.js';
import { useSpaceMissionsStore } from './stores/spaceMissions.js';
import { SpaceMissionsControls } from './spaceMissionsControls.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';
import { onPlacePacksLoadingChange } from '../data/placeBelow.js';
import {
hideOsmCredit,
registerDynamicCredit,
showOsmCredit,
WIKIDATA_PLACES_CREDIT,
} from '../data/dataCredits.js';
import { withPlacePacks } from './placePacksLoading.js';
import { preloadOwnerFlags } from './ownerFlag.js';
@@ -93,10 +110,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 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,
@@ -107,6 +127,7 @@ export class StyleManager extends ShellFacade {
requestServices,
initialShareCode = null,
localePicker = true,
homeView = null,
} = {},
) {
super();
@@ -164,6 +185,22 @@ 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' }),
// The Omnibar shows names from the bundled Wikidata packs.
creditPlaces: () =>
registerDynamicCredit(this.viewer, WIKIDATA_PLACES_CREDIT),
// Photon's suggestions are OpenStreetMap data: credited while shown.
creditSuggestions: (shown) =>
shown
? showOsmCredit(this.viewer, 'omnibar')
: hideOsmCredit(this.viewer, 'omnibar'),
});
// Scrolling at a screen edge steps through that side's rail panels.
this._removeRailEdgeScroll = installRailEdgeScroll();
this._feedback = new ShellFeedback({
readLayers: () => withPlacePacks(this._dataManager?.getAll?.() || []),
});
@@ -175,6 +212,14 @@ 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,
});
this.mapStackController = mapStackController;
this.placeSearch = placeSearch;
@@ -209,8 +254,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({
@@ -223,6 +268,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,
@@ -236,6 +282,7 @@ export class StyleManager extends ShellFacade {
setKeyholeFadeTuning: services.setKeyholeFadeTuning,
setScopeMaskEnabled: services.setScopeMaskEnabled,
setScopeMaskFeather: services.setScopeMaskFeather,
setScopeMaskOpacity: services.setScopeMaskOpacity,
},
elements: {
_ppToggles: this._ppToggles,
@@ -280,6 +327,7 @@ export class StyleManager extends ShellFacade {
readControls: () => ({
hud: this.hud,
_contextControls: this._contextControls,
_spaceMissionsControls: this._spaceMissionsControls,
_cctvControls: this._cctvControls,
_radioControls: this._radioControls,
_streetLevelControls: this._streetLevelControls,
@@ -313,6 +361,7 @@ export class StyleManager extends ShellFacade {
this._locationNavigation = new LocationNavigation({
viewer,
placeSearch,
homeView,
navigation: this._navigation,
readCockpit: () => this.cockpitView,
services: {
@@ -388,6 +437,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,
@@ -400,6 +456,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,
@@ -457,6 +516,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,
@@ -471,7 +532,7 @@ 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,
});
@@ -576,6 +637,7 @@ export class StyleManager extends ShellFacade {
_toggleOrbit: (...args) => this._toggleOrbit(...args),
toggleCleanView: (...args) => this.toggleCleanView(...args),
_toggleCctvEnabled: (...args) => this._toggleCctvEnabled(...args),
_togglePanel: (panelId) => this._panelChrome._togglePanel(panelId),
_setBloomEnabled: (...args) => this._setBloomEnabled(...args),
_setBloomIntensity: (...args) => this._setBloomIntensity(...args),
_setSharpenEnabled: (...args) => this._setSharpenEnabled(...args),
@@ -588,6 +650,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),
@@ -626,6 +692,7 @@ export class StyleManager extends ShellFacade {
this._initStreetLevelPanel();
this._initWildlifeSightingCard();
this._initGlobalContextPanel();
this._initSpaceMissionsPanel();
this._initLocationBar();
this._initMobileShell();
this._initShareButton();
@@ -962,17 +1029,12 @@ export class StyleManager extends ShellFacade {
}
_initGlobalContextPanel() {
const {
radioLayer,
militaryInstallationsLayer,
militaryAwarenessLayer,
rocketLaunchesLayer,
} = this.services;
const { radioLayer, militaryInstallationsLayer, militaryAwarenessLayer } =
this.services;
const contextStore = useContextStore(applicationPinia());
this._contextControls = new ContextControls({
elements: {
_globalContextFlightsBtn: this._globalContextFlightsBtn,
_globalContextMissionsBtn: this._globalContextMissionsBtn,
_installationsSearchBtn: this._installationsSearchBtn,
},
installations: militaryInstallationsLayer,
@@ -1008,13 +1070,24 @@ export class StyleManager extends ShellFacade {
militaryAwarenessLayer?.subscribeDirectionOverlay?.((view) =>
awarenessDirectionStore.publish(view),
);
}
_initSpaceMissionsPanel() {
const { rocketLaunchesLayer } = this.services;
// The Space Missions layer publishes its roster and selected mission.
contextStore.connectMissions(rocketLaunchesLayer);
this._missionsPanelUnsubscribe?.();
contextStore.publishMissions(null);
this._missionsPanelUnsubscribe = rocketLaunchesLayer?.subscribePanel?.(
(view) => contextStore.publishMissions(view),
);
this._spaceMissionsControls?.destroy();
this._spaceMissionsControls = new SpaceMissionsControls({
layer: rocketLaunchesLayer,
store: useSpaceMissionsStore(applicationPinia()),
actions: {
setPanelCollapsed: (...args) => this.setPanelCollapsed(...args),
isCockpitActive: () => Boolean(this.cockpitView?.active),
// After the panel has rendered as shown: the phone shell will not
// open the Missions sheet over a hidden panel.
revealPanel: () =>
nextTick(() => this.revealPanel('space-missions-panel')),
},
});
// And its replay vehicle overlay, which the scene chrome renders.
const missionReplayStore = useMissionReplayStore(applicationPinia());
this._missionReplayUnsubscribe?.();
@@ -1048,7 +1121,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'),
@@ -1197,6 +1270,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(),
},
@@ -1224,7 +1302,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: () =>
@@ -1322,17 +1400,18 @@ export class StyleManager extends ShellFacade {
}
/**
* Switches the HUD layout variant.
* Switches the HUD layout variant. The removed Cyber layout is accepted
* as an alias: it opens Tactical with the Sonar style on.
* @param {'tactical'|'minimal'|'cyber'} variantName - Layout variant.
* @returns {{ok: boolean, layout?: string, visible?: boolean, error?: string}}
*/
setHudLayout(variantName) {
const variant = String(variantName ?? '').toLowerCase();
if (!isHudLayout(variant)) {
if (!isHudLayout(variant) && !isLegacySonarHudLayout(variant)) {
return { ok: false, error: `Unknown HUD layout: ${variantName}` };
}
this.shareLinkManager?.claimRestoreLane?.('visual');
this._setHudVariant(variant, { applyVisualDefaults: true });
this._setHudVariant(variant);
return {
ok: true,
layout: this.hud.getVariant(),
@@ -1451,7 +1530,7 @@ export class StyleManager extends ShellFacade {
};
}
/** Apply Cyber-only sonar settings through the shared visual controls. */
/** Apply sonar visual-style settings through the shared visual controls. */
setCyberSonar(settings) {
return setCyberSonarControls(this, settings);
}
@@ -1500,15 +1579,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),
};
}
@@ -1520,20 +1600,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,
});
);
}
/**
@@ -1588,8 +1666,6 @@ export class StyleManager extends ShellFacade {
* @param {string} styleName - Target style ('normal'|'retro'|'surveillance'|'thermal'|'anime'|'noir').
* @param {object} [options]
* @param {boolean} [options.applyPreset=true] - Whether to apply STYLE_PRESET_DEFAULTS for the new style.
* @param {boolean} [options.userInitiated=false] - Whether a direct user preset choice owns the Cyber exit style.
* @param {boolean} [options.preserveCyberRestore=false] - Whether an automatic style update keeps the Cyber entry snapshot.
* @returns {void}
*/
setStyle(
@@ -1669,7 +1745,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)
@@ -1785,7 +1866,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}
*/
@@ -1848,6 +1929,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;
@@ -1881,16 +1965,14 @@ export class StyleManager extends ShellFacade {
this._awarenessDirectionUnsubscribe?.();
this._awarenessDirectionUnsubscribe = null;
useAwarenessDirectionStore(applicationPinia()).publish(null);
this._missionsPanelUnsubscribe?.();
this._missionsPanelUnsubscribe = null;
this._spaceMissionsControls?.destroy();
this._spaceMissionsControls = null;
this._missionReplayUnsubscribe?.();
this._missionReplayUnsubscribe = null;
useMissionReplayStore(applicationPinia()).publish(null);
const contextStore = useContextStore(applicationPinia());
contextStore.connectAwareness(null);
contextStore.publishAwareness(null);
contextStore.connectMissions(null);
contextStore.publishMissions(null);
this._cockpitCoordinator.stop();
this._visualSettings.stop();
this.shareLinkManager?.destroy();
+3 -3
View File
@@ -280,7 +280,7 @@ test('a tracked flight’s photo shows under its name, credited and linked to it
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);
assert.equal(panel().querySelector('.military-awareness-photo') === null, true);
});
test('a photo whose image fails to load is hidden until another arrives', async (t) => {
@@ -290,10 +290,10 @@ test('a photo whose image fails to load is hidden until another arrives', async
.querySelector('.military-awareness-photo img')
.dispatchEvent(new Event('error'));
await nextTick();
assert.equal(panel().querySelector('.military-awareness-photo'), null);
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);
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 });
+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.
+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);
+126 -11
View File
@@ -7,10 +7,17 @@ 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';
@@ -89,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 } = {},
@@ -115,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() {},
@@ -142,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: {
@@ -355,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();
@@ -369,10 +455,10 @@ 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.id],
@@ -380,6 +466,18 @@ test('tracking an aircraft from the bridge ends it without refocusing the vessel
]);
});
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();
@@ -415,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();
@@ -818,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');
@@ -839,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,
@@ -849,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/,
@@ -868,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');
@@ -906,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.
@@ -929,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();
@@ -1201,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 () => {
@@ -1248,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/,
@@ -1504,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.
@@ -1530,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);
+1 -1
View File
@@ -164,7 +164,7 @@ export function maybeRefreshRegionalBrief(info) {
!Number.isFinite(info.longitude)
)
return;
const subjectId = `${info.layerId || 'aircraft'}:${info.icao24 || (info.kind === 'vessel' ? info.id : '') || 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;
+317 -181
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?.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 = {
vesselId: info.id,
heightM: loadedWaterlineM(scene, probes, seaM),
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,9 +246,10 @@ 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;
}
@@ -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,143 @@ 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 since the last update (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;
let held = false;
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
// the eye keeps the last height it stood at (a frame's or the floor's),
// at first the entry frame's.
held = !Number.isFinite(floorM);
heightM = held ? this.subjectHeightM : floorM;
}
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;
if (!held) {
// The first height to replace the entry frame's is the anchor's at once
// (an inertial anchor would close on it only at the horizontal
// correction's rate); where the anchor stands, it stays.
if (
this.subjectHeightFromEntry &&
this.cockpitAnchorValid &&
heightM !== this.subjectHeightM
) {
const anchor = toCartographicRadians(this.cockpitAnchor);
if (anchor)
this.cockpitAnchor = fromRadians(anchor.lon, anchor.lat, heightM);
}
this.subjectHeightFromEntry = 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,
// At most half a turn, which reaches any heading: a huge rate times
// the step must not overflow to Infinity and stop the turn.
Math.min(rate * dtSec, 180),
);
}
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.
@@ -313,9 +479,12 @@ function updateVessel(nowMs) {
* Aircraft pass none and look along the heading at the profile pitch.
*/
function placeCamera(target, info, nowMs, dtSec, profile, look = null) {
if (!this.cockpitAnchorValid) {
Cesium.Cartesian3.clone(target, this.cockpitAnchor);
// The update that first sets the anchor stands it on the target: the time
// before it (an entry, a floor wait) moved nothing, so it has no step.
const anchoring = !this.cockpitAnchorValid;
if (anchoring) {
this.cockpitAnchorValid = true;
this.subjectLiftM = null;
}
// First-person motion cannot use the delayed feed correction as a raw
@@ -325,73 +494,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 (anchoring || 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 (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 +546,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 +577,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 +635,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 +700,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';
+111 -25
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,16 +139,37 @@ 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 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.
@@ -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,12 @@ export class CockpitViewController {
this.surfaceWaitStartedMs = 0;
this.surfaceAcquiring = false;
this.surfaceFallback = false;
/** The height an application subject's eye last stood at (m). */
this.subjectHeightM = null;
/** Whether `subjectHeightM` is still the one its entry frame gave. */
this.subjectHeightFromEntry = false;
/** 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 +243,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 +291,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 +321,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 +339,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 +350,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 +497,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 +552,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 +588,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 +630,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 +650,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 +663,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 +676,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();
@@ -662,8 +737,16 @@ export class CockpitViewController {
publishCockpitSignals() {
return publishCockpitSignals.call(this);
}
pushCockpitSignal(key, tone, title, detail, target) {
return pushCockpitSignal.call(this, key, tone, title, detail, target);
pushCockpitSignal(key, tone, title, detail, target, options) {
return pushCockpitSignal.call(
this,
key,
tone,
title,
detail,
target,
options,
);
}
dropCockpitSignal(key) {
return dropCockpitSignal.call(this, key);
@@ -718,6 +801,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 {
+329 -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,286 @@ 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: false,
};
const { owner, views } = cockpitOver({ info, target });
// The first update stands the anchor on the target.
owner.update();
let expected = cesiumCockpitEye(Cesium, {
target,
info,
heading: 72,
dtSec: 0,
liftM: 0,
});
near(views[0].destination, expected.eye, 1e-6, 'first 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.
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.id,
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),
+4 -11
View File
@@ -1,5 +1,3 @@
import { displayPanelScroller } from './displayPanelScroll.js';
/**
* Show the existing Display groups in Cockpit's Display popover while Cockpit
* is on. The portal publishes the popover's slots; the Display panel
@@ -37,16 +35,13 @@ export class CockpitDisplayPortal {
this.slots = Object.freeze(
Object.fromEntries(this.records.map(({ name, slot }) => [name, slot])),
);
this.standardScrollTop =
displayPanelScroller(standardPanel)?.scrollTop || 0;
this.standardScrollTop = standardPanel?.scrollTop || 0;
this.cockpitScrollTop = cockpitPanel?.scrollTop || 0;
const options = { passive: true, signal: this.listeners.signal };
standardPanel?.addEventListener(
'scroll',
() => {
if (!this.active)
this.standardScrollTop =
displayPanelScroller(standardPanel).scrollTop;
if (!this.active) this.standardScrollTop = standardPanel.scrollTop;
},
{ ...options, capture: true },
);
@@ -98,8 +93,7 @@ export class CockpitDisplayPortal {
if (nextActive && this.cockpitPanel)
this.cockpitPanel.scrollTop = this.cockpitScrollTop;
if (!nextActive && this.standardPanel)
displayPanelScroller(this.standardPanel).scrollTop =
this.standardScrollTop;
this.standardPanel.scrollTop = this.standardScrollTop;
};
if (!settle) {
this.afterRender(() => {
@@ -146,8 +140,7 @@ export class CockpitDisplayPortal {
this.publish(null);
const { standardPanel, standardScrollTop } = this;
this.afterRender(() => {
if (standardPanel)
displayPanelScroller(standardPanel).scrollTop = standardScrollTop;
if (standardPanel) standardPanel.scrollTop = standardScrollTop;
});
this.records = [];
this.restoreOwner = null;
+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');
});
+106 -38
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;
}
/**
@@ -120,34 +118,101 @@ export function onSceneDoubleClick(position, nowMs = performance.now()) {
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();
};
}
@@ -189,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');
@@ -245,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'),
+156 -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,163 @@ 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(hud.signals.map(({ id }) => `subject:${id}`));
// Rows the view no longer lists leave first, so new ones take their
// places rather than push a listed one (or TRACK ACQUIRED) off.
for (const key of this.subjectSignalKeys ?? [])
if (!keys.has(key)) this.dropCockpitSignal(key);
this.subjectSignalKeys = keys;
for (const signal of hud.signals)
this.pushCockpitSignal(
`subject:${signal.id}`,
SUBJECT_SIGNAL_TONES[signal.tone] ?? 'info',
signal.title,
signal.detail || signal.title,
null,
{ inPlace: true },
);
}
}
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 +526,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),
}),
});
}
+3 -134
View File
@@ -2,7 +2,6 @@
import {
resolveCockpitUtilityAnchor,
resolveCockpitUtilityLayout,
resolveCyberCockpitPanelLane,
} from '../cockpitUtilityLayout.js';
import {
COCKPIT_UTILITY_REC_GAP_PX,
@@ -67,8 +66,6 @@ export function syncContextLayout() {
if (window.matchMedia('(max-width: 760px)').matches) {
this.context.dataset.layoutMode = 'compact-bottom';
this.context.style.removeProperty('--cockpit-context-left');
this.context.style.removeProperty('--cockpit-context-top');
this.context.style.removeProperty('--cockpit-context-max-height');
return;
}
@@ -78,55 +75,6 @@ export function syncContextLayout() {
'--cockpit-context-left',
`${desktopInset.toFixed(1)}px`,
);
if (document.documentElement.dataset.uiTheme !== 'cyber') {
this.context.style.removeProperty('--cockpit-context-top');
this.context.style.removeProperty('--cockpit-context-max-height');
return;
}
const defaultTop = Math.max(255, Math.min(300, window.innerHeight * 0.28));
// An open left panel Cockpit keeps (Data Layers or Utilities).
const dataPanel = document.querySelector(
'#left-panel-stack > :is(#data-panel, #utilities-panel):not(.collapsed)',
);
let desiredTop = defaultTop;
if (this.contextCollapsed && dataPanel) {
desiredTop = Math.max(
desiredTop,
dataPanel.getBoundingClientRect().bottom + 8,
);
}
const contextBounds = this.context.getBoundingClientRect();
let safeBottom = window.innerHeight - 24;
for (const selector of [
'#cesium-credits',
'#command-dock',
'#view-switcher',
]) {
const obstacle = document.querySelector(selector);
if (!obstacle) continue;
const style = window.getComputedStyle(obstacle);
if (
style.display === 'none' ||
style.visibility === 'hidden' ||
Number(style.opacity) === 0
)
continue;
const bounds = obstacle.getBoundingClientRect();
const overlapsHorizontally =
bounds.right > contextBounds.left && bounds.left < contextBounds.right;
if (overlapsHorizontally && bounds.top > desiredTop) {
safeBottom = Math.min(safeBottom, bounds.top - 8);
}
}
const boundedTop = Math.max(
defaultTop,
Math.min(desiredTop, safeBottom - contextBounds.height),
);
this.context.style.setProperty(
'--cockpit-context-top',
`${boundedTop.toFixed(1)}px`,
);
this.context.style.removeProperty('--cockpit-context-max-height');
}
export function syncSignalLayout() {
@@ -137,8 +85,6 @@ export function syncSignalLayout() {
// The compact strip shows only an expanded control.
this.publishUtilityLayout(utilityLayoutView({ hideCollapsed: true }));
this.signalStream.style.removeProperty('--cockpit-signal-right');
this.signalStream.style.removeProperty('--cockpit-signal-top');
this.signalStream.style.removeProperty('--cockpit-signal-max-height');
return;
}
@@ -148,36 +94,6 @@ export function syncSignalLayout() {
'--cockpit-signal-right',
`${desktopInset.toFixed(1)}px`,
);
this.signalStream.style.removeProperty('--cockpit-signal-top');
this.signalStream.style.removeProperty('--cockpit-signal-max-height');
const cyber = document.documentElement.dataset.uiTheme === 'cyber';
const leftPanel = cyber
? document.querySelector('#left-panel-stack > #data-panel')
: null;
const alignedTop = isRenderedOnScreen(leftPanel)
? leftPanel.getBoundingClientRect().top
: null;
// Cyber's two rails share a top edge. Move the briefing below the collapsed
// strip rather than pulling the right rail upward to avoid it.
if (alignedTop !== null && utilityControls) {
const expanded = utilityControls.querySelector(
'.cockpit-utility-control.is-expanded',
);
if (!expanded) {
const signalTop = Math.max(
Math.max(255, Math.min(300, window.innerHeight * 0.28)),
alignedTop + utilityControls.getBoundingClientRect().height + 28,
);
this.signalStream.style.setProperty(
'--cockpit-signal-top',
`${signalTop.toFixed(1)}px`,
);
this.signalStream.style.setProperty(
'--cockpit-signal-max-height',
`${Math.max(44, window.innerHeight - signalTop - 80).toFixed(1)}px`,
);
}
}
const signalBounds = this.signalStream.getBoundingClientRect();
const utilityBounds = utilityControls?.getBoundingClientRect();
if (utilityBounds) {
@@ -202,42 +118,7 @@ export function syncSignalLayout() {
collapsedLauncher.scrollHeight,
)
: 0;
if (alignedTop !== null) {
const lane = resolveCyberCockpitPanelLane({
viewportHeight: window.innerHeight,
top: alignedTop,
launcherHeight: Math.max(
collapsedHeight,
collapsedLauncher?.getBoundingClientRect().height || 60,
),
signalHeight: this.signalCollapsed ? signalBounds.height : 44,
contactHeight:
this.contextCollapsed && this.context
? this.context.getBoundingClientRect().height
: 64,
});
document.body.style.setProperty(
'--cyber-cockpit-panel-height',
`${lane.panelHeight.toFixed(2)}px`,
);
this.publishUtilityLayout(
utilityLayoutView({
top: `${alignedTop.toFixed(2)}px`,
maxHeight: `${lane.utilityHeight.toFixed(2)}px`,
expandedMaxHeight: `${lane.panelHeight.toFixed(2)}px`,
}),
);
if (expandedControl) {
this.signalStream.style.setProperty(
'--cockpit-signal-top',
`${lane.signalTop.toFixed(2)}px`,
);
}
this.syncContextLayout();
return;
}
// Non-Cyber themes retain their independent REC/briefing corridor. Cyber
// uses the rendered Data Layers top after reserving briefing space above.
// The REC readout and the briefing card bound the utility corridor.
// The readout only anchors the strip while it is genuinely on screen:
// the Minimal variant drops it with `display:none`, but HUD Off hides the
// whole Intel HUD with `visibility`/`opacity`, which keeps its rect.
@@ -253,20 +134,8 @@ export function syncSignalLayout() {
collapsedHeight,
recGap: COCKPIT_UTILITY_REC_GAP_PX,
signalGap: COCKPIT_UTILITY_SIGNAL_GAP_PX,
minTopFloor: alignedTop ?? COCKPIT_UTILITY_MIN_TOP_PX,
minTopRatio: alignedTop !== null ? 0 : COCKPIT_UTILITY_MIN_TOP_RATIO,
signalCollapsed: this.signalCollapsed,
utilityExpanded: Boolean(expandedControl),
// Only Cyber relocates its collapsed briefing below the utility lane.
// Other themes keep the measured visible card as the lower boundary.
reserveViewportLane: document.documentElement.dataset.uiTheme === 'cyber',
// Cyber keeps the collapsed briefing reachable below the utility instead
// of hiding it. Reserve its actual height, including wrapped headings.
signalHeight:
document.documentElement.dataset.uiTheme === 'cyber' &&
this.signalCollapsed
? signalBounds.height
: 0,
minTopFloor: COCKPIT_UTILITY_MIN_TOP_PX,
minTopRatio: COCKPIT_UTILITY_MIN_TOP_RATIO,
});
const availableHeight = utilityAnchor.maxHeight;
const utilityLayout =
+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();
+39 -24
View File
@@ -8,7 +8,10 @@
* (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 { isUnderOtherCard } from '../data/pickRegistry.js';
import { findQuery } from '../render/rendererOf.js';
import { clampOrbitalLook, easeLook } from '../cockpitLook.js';
import { ORBITAL_EARTH_RADIUS_M } from '../cockpitOrbital.js';
import {
@@ -113,11 +116,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 +218,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 +275,24 @@ 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) => {
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) => {
// Another layer's card or label painted on top takes the click: the site
// under it does not focus, and the click does not end a held focus.
if (isUnderOtherCard(event)) return;
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);
};
});
}
/**
@@ -408,7 +423,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,
);
+112 -43
View File
@@ -12,13 +12,26 @@ 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';
import ContextView from './views/ContextView.vue';
import IntelHudView from './views/IntelHudView.vue';
import { claimPointer, releasePointer } from '../data/inputOwnership.js';
import { setClickCardHitTest } from '../data/pickRegistry.js';
import { ORBITAL_FOCUS_EASE_TAU_MS } from '../cockpitOrbitalFocus.js';
import { ORBITAL_HOP_MS } from '../cockpitOrbitalSatellites.js';
@@ -117,10 +130,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 +216,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 +249,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 +265,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 +333,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 +353,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 +371,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 +384,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 +400,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 +574,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) => {
@@ -597,12 +649,29 @@ test('a click a tool owns is left alone', async (t) => {
assert.equal(scene.cockpit.orbital.focus.key, SITES.alpha.id, 'kept while drawing');
});
// The card or label painted on top takes the click: a site under another
// layer's card does not focus, and a click there does not end a held focus.
test('another layer\'s card over the orbital view keeps the click', async (t) => {
const scene = await inOrbit(t);
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
setClickCardHitTest(() => top);
t.after(() => setClickCardHitTest(null));
scene.click(SITES.alpha.at);
assert.equal(scene.cockpit.orbital.focus ?? null, null, 'covered: no focus');
top = null;
scene.click(SITES.alpha.at);
assert.equal(scene.cockpit.orbital.focus.key, SITES.alpha.id);
top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
scene.click(EMPTY_GROUND);
assert.equal(scene.cockpit.orbital.focus.key, SITES.alpha.id, 'covered: kept');
});
test('a double-click on a site focuses it and keeps the orbital view', async (t) => {
const scene = await inOrbit(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 +757,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 +947,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) };
}
+33 -8
View File
@@ -39,17 +39,42 @@ export function publishCockpitSignals() {
this.scheduleContextLayout();
}
export function pushCockpitSignal(key, tone, title, detail, target = null) {
/**
* Log a signal as the newest row, unless its key last said the same.
* @param {{inPlace?: boolean}} [options] `inPlace`: a status row, such as a
* provider's, that changes where it stands rather than log a new row, so a
* changing ETA never pushes a steady warning off the list; it keeps its
* time while it stays listed, and one pushed off comes back as the newest
* row.
*/
export function pushCockpitSignal(
key,
tone,
title,
detail,
target = null,
{ inPlace = false } = {},
) {
if (!title || !detail) return;
const signature = `${title}|${detail}|${target?.layerId || ''}|${target?.id || ''}`;
if (this.signalSignatures.get(key) === signature) return;
this.signalSignatures.set(key, signature);
// JSON, not a joined string, so a separator inside a title or detail cannot
// make two rows match. An in-place row also changes with its tone alone.
const signature = JSON.stringify([
title,
detail,
target?.layerId || '',
target?.id || '',
inPlace ? tone : '',
]);
// A locale change words the signal again where it stands.
const shown = this.rewordingSignals
? this.signalItems.find((item) => item.key === key)
: null;
const shown =
this.rewordingSignals || inPlace
? this.signalItems.find((item) => item.key === key)
: null;
if (this.signalSignatures.get(key) === signature && (!inPlace || shown))
return;
this.signalSignatures.set(key, signature);
if (shown) {
Object.assign(shown, { title, detail });
Object.assign(shown, { tone, title, detail });
this.publishCockpitSignals();
return;
}
File diff suppressed because it is too large. Load diff
+446 -62
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,41 +53,206 @@ 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?.kind === 'vessel' ? info.id : '') ||
(info?.kind === 'vessel' || info?.generic === true ? info.id : '') ||
info?.noradId ||
'',
)
@@ -76,9 +261,13 @@ export function dispatchCockpitModeChanged(active, info = 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(
@@ -127,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;
@@ -180,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 ||
@@ -193,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;
@@ -213,16 +429,157 @@ 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;
// The entry frame's height, if any, stands in for a cold floor
// (updateSubject).
this.subjectHeightM = frame.heightM;
this.subjectHeightFromEntry = true;
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
@@ -236,8 +593,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
@@ -245,13 +603,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.id : satellite ? info.noradId : null;
this.trackedEntity = entity;
this.trackedFollow = followed;
if (entity) {
this.trackedEntityWasShown = entity.show;
entity.show = false;
@@ -268,7 +627,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();
@@ -289,8 +648,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');
@@ -326,9 +686,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,
})
@@ -371,16 +733,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;
@@ -399,6 +769,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();
@@ -406,22 +777,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.
@@ -431,10 +814,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;
+42 -27
View File
@@ -379,7 +379,7 @@ test('the layout pass’s measured fit hides the collapsed control and marks the
app.unmount();
});
test('the real layout pass drives the mounted controls: compact hides the collapsed sibling, Cyber shows both', async (t) => {
test('the real layout pass drives the mounted controls: compact hides the collapsed sibling, desktop shows both', async (t) => {
document.body.replaceChildren();
const host = document.body.appendChild(document.createElement('div'));
const pinia = createPinia();
@@ -403,9 +403,6 @@ test('the real layout pass drives the mounted controls: compact hides the collap
window.matchMedia = (query) => ({ matches: compact, media: query });
t.after(() => {
window.matchMedia = originalMatchMedia;
delete document.documentElement.dataset.uiTheme;
document.body.style.removeProperty('opacity');
document.documentElement.style.removeProperty('opacity');
app.unmount();
});
const strip = document.getElementById('cockpit-utility-controls');
@@ -421,32 +418,50 @@ test('the real layout pass drives the mounted controls: compact hides the collap
assert.equal(cockpit.utilityLayout.top, null);
// Compact hides the sibling without marking the strip primary-only.
assert.equal(strip.classList.contains('layout-primary-only'), false);
// Cyber aligns the strip with the Data panel and keeps both controls.
// The desktop pass anchors the strip in its own corridor and keeps both.
compact = false;
document.documentElement.dataset.uiTheme = 'cyber';
const stack = document.body.appendChild(document.createElement('div'));
stack.id = 'left-panel-stack';
const dataPanel = stack.appendChild(document.createElement('section'));
dataPanel.id = 'data-panel';
for (const node of [
dataPanel,
stack,
document.body,
document.documentElement,
])
node.style.opacity = '1';
dataPanel.getBoundingClientRect = () => ({
top: 120,
bottom: 400,
left: 0,
right: 200,
width: 200,
height: 280,
});
syncSignalLayout.call(owner);
await nextTick();
assert.equal(display.getAttribute('aria-hidden'), 'false');
assert.equal(radioControl.getAttribute('aria-hidden'), 'false');
assert.equal(cockpit.utilityLayout.top, '120.00px');
assert.equal(strip.classList.contains('layout-primary-only'), false);
assert.match(cockpit.utilityLayout.top, /^\d+(\.\d+)?px$/);
});
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);
});
File diff suppressed because it is too large. Load diff
+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,
+1 -17
View File
@@ -4,19 +4,6 @@ import {
contextModeWord,
} from '../contextModePolicy.js';
/** Why a Space Missions entry failed: its mission index never loaded, and
* the error is no older than `since` (an earlier attempt's is not the cause). */
export function spaceMissionsIndexFailure(dataManager, since = 0) {
const stats = dataManager?.layers
?.get('rocket-launches')
?.module?.getStats?.();
return stats?.error && stats.lastUpdate == null && stats.errorAt >= since
? t(
'Space Missions unavailable: the mission index could not load. Try again later.',
)
: null;
}
export async function _runUserFacingContextAction(
operation,
message = t('Context could not restore every layer; try again'),
@@ -71,7 +58,6 @@ export function getContextModeState() {
changing: Boolean(this._contextModeChanging),
entering: this._contextModeEntering || null,
canContact: !this._contextMode || this._contextMode === 'flights',
canMission: !this._contextMode || this._contextMode === 'space-missions',
snapshotCaptured: Boolean(this._contextSessionSnapshot),
};
}
@@ -127,7 +113,7 @@ export async function setContextMode(
};
}
const canonical = mode === 'contacts' ? 'flights' : mode;
if (!['flights', 'space-missions'].includes(canonical)) {
if (canonical !== 'flights') {
return {
ok: false,
action: 'set_context_mode',
@@ -222,8 +208,6 @@ export function clearSelectedLayers() {
this._contextModeChanging = true;
this._contextMode = null;
this._contextModeEntering = null;
this._contextModeEntryIntent = null;
this._contextModeReplacementIntent = null;
this._contextSessionSnapshot = null;
this._contextRestoreState = null;
this._preservePanelStateDuringLayerClear = true;
+2 -55
View File
@@ -1,27 +1,8 @@
import { t } from '../i18n/index.js';
import { spaceMissionsIndexFailure } from './contextActions.js';
import { translateStatusMessage } from './statusText.js';
import { shouldExpandGlobalContextPanel } from '../rightRailPolicy.js';
export function _initGlobalContextPanel() {
const contextTabs = [
this._globalContextFlightsBtn,
this._globalContextMissionsBtn,
].filter(Boolean);
contextTabs.forEach((tab, index) =>
this.listen(tab, 'keydown', (event) => {
let nextIndex = null;
if (event.key === 'ArrowRight')
nextIndex = (index + 1) % contextTabs.length;
else if (event.key === 'ArrowLeft')
nextIndex = (index - 1 + contextTabs.length) % contextTabs.length;
else if (event.key === 'Home') nextIndex = 0;
else if (event.key === 'End') nextIndex = contextTabs.length - 1;
if (nextIndex === null) return;
event.preventDefault();
contextTabs[nextIndex].focus({ preventScroll: true });
contextTabs[nextIndex].click();
}),
);
this.listen(this._globalContextFlightsBtn, 'click', () => {
if (
this.destroyed ||
@@ -50,40 +31,6 @@ export function _initGlobalContextPanel() {
});
});
});
this.listen(this._globalContextMissionsBtn, 'click', () => {
if (
this.destroyed ||
this._contextModeChanging ||
this._clearSelectedLayersPromise
)
return;
const nextMode =
this._contextMode === 'space-missions' ? null : 'space-missions';
this._claimContextVisualAuthority();
const startedAt = Date.now();
void this._runUserFacingContextAction(
(notificationToken) =>
this._selectContextMode(nextMode, { notificationToken }),
() =>
(nextMode && spaceMissionsIndexFailure(this._dataManager, startedAt)) ||
t(
'Space Missions could not complete the requested transition; try again',
),
).then((succeeded) => {
if (
!this.destroyed &&
nextMode &&
shouldExpandGlobalContextPanel({
action: 'space-missions',
explicitUserAction: true,
succeeded: succeeded === true,
})
)
this.actions.setPanelCollapsed('global-context-panel', false, {
explicit: true,
});
});
});
this.listen(this._installationsSearchBtn, 'click', () => {
if (
this.destroyed ||
@@ -112,7 +59,7 @@ export function _initGlobalContextPanel() {
if (this.destroyed || searched === false) return false;
const stats = this.installations.getStats?.();
this.showToast(
stats?.statusMessage ||
(stats?.statusMessage && translateStatusMessage(stats.statusMessage)) ||
(stats?.status === 'zoom-in'
? t('Zoom in to search mapped installations')
: t('Nearby installations refreshed')),
+12 -3
View File
@@ -44,13 +44,12 @@ export class ContextControls {
this._contextModeChanging = false;
this._contextModeGeneration = 0;
this._contextModeEntering = null;
this._contextModeEntryIntent = null;
this._contextModeReplacementIntent = null;
this._contextModeDeferredEntryIntent = null;
this._contextSessionSnapshot = null;
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 +58,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 -1
View File
@@ -48,7 +48,6 @@ test('Context starts with an explicit idle snapshot', (t) => {
changing: false,
entering: null,
canContact: true,
canMission: true,
snapshotCaptured: false,
});
});
@@ -153,3 +152,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);
});
+4 -51
View File
@@ -2,10 +2,6 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { setLocale } from '../i18n/index.js';
import {
contextLayerEnableBlockReason,
parseContextLayerBlockReason,
} from '../contextModePolicy.js';
import {
_handleContextLayerChange,
localizeVisibilityBlockReason,
@@ -18,7 +14,7 @@ function fakeShell() {
_userFacingContextNotificationTokens: new Set(),
_contextSessionSnapshot: null,
_contextModeChanging: false,
_contextMode: 'space-missions',
_contextMode: null,
_contextModeEntering: null,
_syncContextModeButtons() {},
showToast(message) {
@@ -28,41 +24,19 @@ function fakeShell() {
};
}
const ENGLISH_GUARD =
'Space Missions isolates replay data. Exit the mode to enable Live Flights.';
test.afterEach(() => setLocale('en'));
test('the guard reason is English data and parses back to its layer name', () => {
const reason = contextLayerEnableBlockReason({
contextMode: 'space-missions',
change: { layerId: 'flights', enabled: true, origin: 'user' },
layerName: 'Live Flights',
});
assert.equal(reason, ENGLISH_GUARD);
assert.deepEqual(parseContextLayerBlockReason(reason), {
layer: 'Live Flights',
});
assert.equal(parseContextLayerBlockReason('Data source unavailable'), null);
assert.equal(
parseContextLayerBlockReason(
'Space Missions isolates replay data. Exit the mode to enable .',
),
null,
);
});
test('en: the toast shows the reason unchanged', () => {
setLocale('en');
const shell = fakeShell();
_handleContextLayerChange.call(shell, {
type: 'visibility-blocked',
layerId: 'flights',
layerId: 'street-level',
enabled: true,
origin: 'user',
reason: ENGLISH_GUARD,
reason: 'Data source unavailable',
});
assert.deepEqual(shell.toasts, [ENGLISH_GUARD]);
assert.deepEqual(shell.toasts, ['Data source unavailable']);
assert.equal(
localizeVisibilityBlockReason('Overpass returned HTTP 503'),
'Overpass returned HTTP 503',
@@ -70,27 +44,6 @@ test('en: the toast shows the reason unchanged', () => {
});
for (const locale of ['es', 'ru']) {
test(`${locale}: the Space Missions block toast is localized with the layer name`, () => {
setLocale(locale);
const reason = contextLayerEnableBlockReason({
contextMode: 'space-missions',
change: { layerId: 'flights', enabled: true, origin: 'user' },
layerName: 'Live Flights',
});
const shell = fakeShell();
_handleContextLayerChange.call(shell, {
type: 'visibility-blocked',
layerId: 'flights',
enabled: true,
origin: 'user',
reason,
});
assert.equal(shell.toasts.length, 1);
assert.notEqual(shell.toasts[0], ENGLISH_GUARD, 'toast must be localized');
assert.doesNotMatch(shell.toasts[0], /Space Missions isolates/);
assert.doesNotMatch(shell.toasts[0], /Live Flights/);
});
test(`${locale}: a known lifecycle reason is looked up in the catalog`, () => {
setLocale(locale);
const shell = fakeShell();
+32 -105
View File
@@ -1,28 +1,16 @@
import { t, translateKnown } from '../i18n/index.js';
import {
SPACE_MISSIONS_LAYER_BLOCK_REASON,
isExplicitUserIntentOrigin,
parseContextLayerBlockReason,
recordContextRestoreExplicitChange,
recordContextSessionUserChange,
shouldExitContextForLayerChange,
spaceMissionEntryCancellationDisposition,
} from '../contextModePolicy.js';
import { localizeLayerName } from './layerNames.js';
import { spaceMissionsIndexFailure } from './contextActions.js';
/**
* A blocked-visibility reason in the UI language. Reasons stay English (voice
* and tools read them): the Space Missions refusal is rebuilt with the layer
* name localized, a known sentence is looked up, anything else passes.
* and tools read them): a known sentence is looked up, anything else passes.
*/
export function localizeVisibilityBlockReason(reason) {
if (typeof reason !== 'string' || !reason) return reason;
const blocked = parseContextLayerBlockReason(reason);
if (blocked)
return t(SPACE_MISSIONS_LAYER_BLOCK_REASON, {
layer: localizeLayerName(blocked.layer),
});
return translateKnown(reason);
}
@@ -40,74 +28,12 @@ export function _handleContextLayerChange(change) {
this.actions.refreshRadio();
}
if (change?.type === 'visibility-transition') return;
// The effective mode must be read BEFORE the entering flag is cleared:
// the entry layer's own enable event is the one that clears it, and the
// session bookkeeping below needs to know a mode was being entered.
// A mode still being entered counts for the session bookkeeping below.
const effectiveContextMode = this._contextModeEntering || this._contextMode;
if (change?.type === 'visibility-cancelled') {
const cancellationDisposition = spaceMissionEntryCancellationDisposition({
change,
});
if (
this._contextModeDeferredEntryIntent?.layerId === change.layerId &&
this._contextModeDeferredEntryIntent.intentEpoch === change.intentEpoch
) {
if (cancellationDisposition !== 'replacement') {
this._contextModeDeferredEntryIntent = null;
}
}
if (cancellationDisposition === 'replacement') {
this._contextModeEntering = 'space-missions';
const entryIntent = this._contextModeEntryIntent;
if (
entryIntent?.generation === this._contextModeGeneration &&
entryIntent.layerId === change.layerId &&
entryIntent.intentEpoch === change.intentEpoch
) {
this._contextModeReplacementIntent = {
generation: entryIntent.generation,
layerId: change.layerId,
intentEpoch: change.successorIntentEpoch,
};
}
} else if (cancellationDisposition === 'restore') {
this._contextModeEntering = null;
this._contextModeEntryIntent = null;
this._contextModeReplacementIntent = null;
if (this._contextSessionSnapshot && !this._contextModeChanging) {
this._contextMode = null;
void this._trackContextLayerReaction(
this._runUserFacingContextAction(
async (notificationToken) => {
await this._restoreContextSessionAfterLayerSettles(
change.layerId,
{
notificationToken,
},
);
return true;
},
'Space Missions cancellation could not restore the previous layer state', // i18n-ignore: English message; the toast shows localizedMessage
{
localizedMessage: t(
'Space Missions cancellation could not restore the previous layer state',
),
},
),
);
}
}
this._syncContextModeButtons();
return;
}
if (
change?.layerId === 'rocket-launches' &&
['visibility', 'visibility-blocked', 'visibility-failed'].includes(
change.type,
)
) {
this._contextModeEntering = null;
}
if (change?.type === 'visibility-blocked') {
if (
!this._userFacingContextNotificationTokens.has(change.notificationToken)
@@ -121,10 +47,13 @@ export function _handleContextLayerChange(change) {
return;
}
if (change?.type === 'visibility-failed') {
// A layer may name why its own start failed (Space Missions: the
// mission index never loaded).
const failureMessage =
(change.layerId === 'rocket-launches' &&
change.enabled &&
spaceMissionsIndexFailure(this._dataManager)) ||
(change.enabled &&
this._dataManager?.layers
?.get(change.layerId)
?.module?.enableFailureMessage?.()) ||
t('{layerId} could not {action} cleanly', {
layerId: change.layerId,
action: change.enabled ? t('start') : t('stop'),
@@ -134,7 +63,7 @@ export function _handleContextLayerChange(change) {
// notification for this queue to settle, then reconcile the complete
// snapshot, including an uncertain failed shell.
const needsDeferredShellRestore =
['military-awareness', 'rocket-launches'].includes(change.layerId) &&
change.layerId === 'military-awareness' &&
change.enabled &&
this._contextSessionSnapshot &&
!this._contextModeChanging;
@@ -212,26 +141,6 @@ export function _handleContextLayerChange(change) {
),
);
}
} else if (change.layerId === 'rocket-launches') {
const ownsContextEntry =
isExplicitUserIntentOrigin(change.origin, change.layerId) ||
this._contextMode === 'space-missions' ||
effectiveContextMode === 'space-missions';
if (!ownsContextEntry) return;
this._contextMode = change.enabled
? 'space-missions'
: this._contextMode === 'space-missions'
? null
: this._contextMode;
if (change.enabled) {
this._syncContextModeButtons();
} else if (this._contextSessionSnapshot) {
void this._trackContextLayerReaction(
this._runUserFacingContextAction((notificationToken) =>
this._deactivateContextForLayerChange({ notificationToken }),
),
);
}
} else if (
this._contextMode === 'flights' &&
[
@@ -249,13 +158,31 @@ export function _handleContextLayerChange(change) {
);
}
}
if (
change.type === 'visibility' &&
change.enabled &&
change.origin === 'user' &&
!this.cockpitView?.active &&
change.layerId === 'radio'
) {
globalThis.dispatchEvent?.(new Event('gev:context-show-view'));
this.actions.setPanelCollapsed('global-context-panel', false, {
explicit: true,
});
this.actions.setPanelCollapsed('radio-panel', false, { explicit: true });
}
finishContextLayerChange(this);
}
/** The checks every settled layer change ends with. */
function finishContextLayerChange(controls) {
// Turning off the layer the view rides ends it; every other layer may be
// turned on or off freely during a session.
const riddenLayerId = this.cockpitView?.active
? this.cockpitView.readSubjectLayerId?.()
const riddenLayerId = controls.cockpitView?.active
? controls.cockpitView.readSubjectLayerId?.()
: null;
if (riddenLayerId && !this._dataManager?.isEnabled(riddenLayerId)) {
this.cockpitView.exit({ restoreTracking: false });
if (riddenLayerId && !controls._dataManager?.isEnabled(riddenLayerId)) {
controls.cockpitView.exit({ restoreTracking: false });
}
this._syncContextModeButtons();
controls._syncContextModeButtons();
}
+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';
}
+22 -43
View File
@@ -22,7 +22,6 @@ function fixture(t) {
const controls = new ContextControls({
elements: {
_globalContextFlightsBtn: $('global-context-flights-btn'),
_globalContextMissionsBtn: $('global-context-missions-btn'),
_installationsSearchBtn: $('installations-search-btn'),
},
installations: {},
@@ -58,61 +57,41 @@ test('before ContextControls renders, the switch shows its initial markup', (t)
'ui-panel panel-collapsible collapsed ui-panel--collapsed',
);
assert.equal(panel.hasAttribute('data-context-mode'), false);
for (const id of [
'global-context-flights-btn',
'global-context-missions-btn',
]) {
const tab = $(id);
assert.equal(tab.className, 'context-mode-button');
assert.equal(tab.getAttribute('aria-selected'), 'false');
assert.equal(tab.getAttribute('tabindex'), '0');
assert.equal(tab.hasAttribute('aria-busy'), false);
}
const tab = $('global-context-flights-btn');
assert.equal(tab.className, 'context-mode-button');
assert.equal(tab.getAttribute('aria-selected'), 'false');
assert.equal(tab.getAttribute('tabindex'), '0');
assert.equal(tab.hasAttribute('aria-busy'), false);
assert.equal($('context-mode-standby').hidden, false);
assert.equal($('context-flights-view').hidden, true);
assert.equal($('context-missions-view').hidden, true);
assert.equal($('global-context-missions-btn'), null);
assert.equal($('context-missions-view'), null);
assert.equal($('installations-search-btn').hasAttribute('aria-busy'), false);
});
test('a transition keeps focus and Tab on both tabs until it settles', async (t) => {
test('a Contacts transition keeps the tab focusable until it settles', async (t) => {
const { $, controls, sync } = fixture(t);
const contacts = $('global-context-flights-btn');
const missions = $('global-context-missions-btn');
missions.focus();
contacts.focus();
controls._contextModeChanging = true;
await sync();
assert.equal(
document.activeElement === missions,
true,
'busy render keeps focus',
);
for (const tab of [contacts, missions]) {
assert.equal(tab.disabled, false);
assert.equal(tab.getAttribute('tabindex'), '0');
assert.equal(tab.getAttribute('aria-disabled'), 'true');
assert.equal(tab.getAttribute('aria-busy'), 'true');
}
assert.equal(document.activeElement, contacts);
assert.equal(contacts.disabled, false);
assert.equal(contacts.getAttribute('tabindex'), '0');
assert.equal(contacts.getAttribute('aria-disabled'), 'true');
assert.equal(contacts.getAttribute('aria-busy'), 'true');
controls._contextModeChanging = false;
controls._contextMode = 'space-missions';
controls._contextMode = 'flights';
await sync();
assert.equal(
document.activeElement === missions,
true,
'settled render keeps focus',
);
for (const tab of [contacts, missions]) {
assert.equal(tab.disabled, false);
assert.equal(tab.getAttribute('aria-disabled'), 'false');
assert.equal(tab.getAttribute('aria-busy'), 'false');
}
assert.equal(missions.classList.contains('active'), true);
assert.equal(missions.getAttribute('aria-selected'), 'true');
assert.equal(contacts.classList.contains('active'), false);
assert.equal(contacts.getAttribute('aria-selected'), 'false');
assert.equal(document.activeElement, contacts);
assert.equal(contacts.disabled, false);
assert.equal(contacts.getAttribute('aria-disabled'), 'false');
assert.equal(contacts.getAttribute('aria-busy'), 'false');
assert.equal(contacts.classList.contains('active'), true);
assert.equal(contacts.getAttribute('aria-selected'), 'true');
assert.equal($('context-mode-standby').hidden, true);
assert.equal($('context-flights-view').hidden, true);
assert.equal($('context-missions-view').hidden, false);
assert.equal($('context-flights-view').hidden, false);
});
test('the panel carries the mode beside the classes its chrome writes', async (t) => {
+1 -8
View File
@@ -12,17 +12,10 @@ export function _syncContextModeButtons() {
export function _presentContext() {
if (this.destroyed) return;
const flightsActive = this._contextMode === 'flights';
const missionsActive = this._contextMode === 'space-missions';
// Both Context choices stay in the ordinary Tab sequence and are never
// native-disabled. Arrow keys still provide tablist navigation, but must
// not be the only way to reach Space Missions from the keyboard. Semantic
// busy state keeps them perceivable while synchronous click guards prevent
// a second transition.
this.publish({
mode: this._contextMode || 'none',
enabled: flightsActive || missionsActive,
enabled: flightsActive,
flightsActive,
missionsActive,
busy: Boolean(this._contextModeChanging),
installationsBusy: this._installationsSearchBusy,
});
+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 = '';
}
+8 -4
View File
@@ -1,4 +1,5 @@
import {
CONTEXT_INDEPENDENT_LAYER_IDS,
contextRestoreLayerIds,
contextSnapshotLayerIds,
mergeContextTransitionErrors,
@@ -24,7 +25,8 @@ export async function _waitForContextLayerSettlement() {
export function _captureContextSessionSnapshot({ excludeLayerIds = [] } = {}) {
if (!this._dataManager || this._contextSessionSnapshot) return;
const params = {};
for (const layerId of ['military-awareness', 'satellites']) {
// Satellites is not Context's: the mission controller owns its parameters.
for (const layerId of ['military-awareness']) {
const value = this._dataManager.getLayerParams(layerId);
if (value) params[layerId] = value;
}
@@ -93,9 +95,11 @@ export async function _restoreContextSession({
restoreState.enabledLayerIds,
{
origin: 'context-restore',
excludeLayerIds: settleContactsCoordinator
? [...excludeLayerIds, contactsCoordinatorId]
: excludeLayerIds,
excludeLayerIds: [
...excludeLayerIds,
...CONTEXT_INDEPENDENT_LAYER_IDS,
...(settleContactsCoordinator ? [contactsCoordinatorId] : []),
],
notificationToken,
...(restoreSignal ? { signal: restoreSignal } : {}),
},
+38 -104
View File
@@ -1,11 +1,8 @@
import { t } from '../i18n/index.js';
import {
contextLayerEnableBlockReason,
isExplicitUserIntentOrigin,
runWithContextModeChanging,
settleContextModeChange,
shouldCaptureContextSession,
shouldDeferContextEntryDuringClear,
} from '../contextModePolicy.js';
export function connectContextManager(manager) {
@@ -28,31 +25,6 @@ export function connectContextManager(manager) {
this._captureContextSessionSnapshot({
excludeLayerIds: [change.layerId],
});
if (
shouldDeferContextEntryDuringClear({
change,
clearInFlight: Boolean(this._clearSelectedLayersPromise),
})
) {
this._contextModeDeferredEntryIntent = {
layerId: change.layerId,
intentEpoch: change.intentEpoch,
origin: change.origin,
};
this._contextModeEntering = 'space-missions';
this._syncContextModeButtons();
}
} else if (
change?.layerId === 'rocket-launches' &&
change.enabled === false &&
isExplicitUserIntentOrigin(change.origin, change.layerId)
) {
this._contextModeDeferredEntryIntent = null;
if (this._clearSelectedLayersPromise) {
this._contextSessionSnapshot = null;
this._contextModeEntering = null;
this._syncContextModeButtons();
}
}
});
}
@@ -60,88 +32,50 @@ export function connectContextManager(manager) {
this._dataManagerVisibilityGuardUnsubscribe =
this._dataManager.addVisibilityGuard(async (change) => {
if (this.destroyed) return null;
const layerName =
this._dataManager?.layers?.get(change.layerId)?.module?.name ||
change.layerId;
const reason = contextLayerEnableBlockReason({
contextMode: this._contextModeEntering || this._contextMode,
change,
layerName,
});
if (reason) return reason;
// A direct Contacts start (the coordinator layer itself, not the
// Context chooser) isolates its dependencies like the chooser does.
if (
change.enabled &&
['military-awareness', 'rocket-launches'].includes(change.layerId) &&
shouldCaptureContextSession(change) &&
(!this._contextModeChanging ||
(change.layerId === 'rocket-launches' &&
this._contextModeDeferredEntryIntent?.intentEpoch ===
change.intentEpoch))
) {
const entryMode =
change.layerId === 'rocket-launches' ? 'space-missions' : null;
const deferredClearEntry =
this._contextModeDeferredEntryIntent?.intentEpoch ===
change.intentEpoch;
// A deferred entry owns the state after Clear settles. Restoring
// Clear's transient busy flag here would leave Context stuck.
const priorChanging = deferredClearEntry
? false
: this._contextModeChanging;
const notificationToken =
change.notificationToken || Symbol('direct-context-shell-entry');
const ownsNotificationToken = !change.notificationToken;
if (ownsNotificationToken) {
this._userFacingContextNotificationTokens.add(notificationToken);
}
this._contextModeEntering = entryMode;
this._contextModeChanging = true;
!change.enabled ||
change.layerId !== 'military-awareness' ||
!shouldCaptureContextSession(change) ||
this._contextModeChanging
)
return null;
const notificationToken =
change.notificationToken || Symbol('direct-context-shell-entry');
const ownsNotificationToken = !change.notificationToken;
if (ownsNotificationToken) {
this._userFacingContextNotificationTokens.add(notificationToken);
}
this._contextModeEntering = null;
this._contextModeChanging = true;
try {
await this._clearLayersOutsideContextMode(null, {
notificationToken,
});
if (this.destroyed) return false;
} catch (error) {
console.warn(`[Context] ${change.layerId} isolation failed`, error);
try {
if (deferredClearEntry) {
await this._clearSelectedLayersManagerPromise;
if (this.destroyed) return false;
if (
this._contextModeDeferredEntryIntent?.intentEpoch !==
change.intentEpoch
)
return false;
this._contextModeDeferredEntryIntent = null;
}
await this._clearLayersOutsideContextMode(entryMode, {
await this._restoreContextSession({
excludeLayerIds: [change.layerId],
notificationToken,
});
if (this.destroyed) return false;
} catch (error) {
this._contextModeEntering = null;
console.warn(`[Context] ${change.layerId} isolation failed`, error);
try {
await this._restoreContextSession({
excludeLayerIds: [change.layerId],
notificationToken,
});
} catch (restoreError) {
console.warn(
`[Context] ${change.layerId} rollback failed`,
restoreError,
);
}
return t(
'{mode} could not start because another layer did not stop cleanly',
{
mode:
entryMode === 'space-missions'
? t('Space Missions')
: t('Context'),
},
} catch (restoreError) {
console.warn(
`[Context] ${change.layerId} rollback failed`,
restoreError,
);
} finally {
if (ownsNotificationToken) {
this._userFacingContextNotificationTokens.delete(
notificationToken,
);
}
if (!this.destroyed) settleContextModeChange(this, priorChanging);
}
return t(
'{mode} could not start because another layer did not stop cleanly',
{ mode: t('Context') },
);
} finally {
if (ownsNotificationToken) {
this._userFacingContextNotificationTokens.delete(notificationToken);
}
if (!this.destroyed) settleContextModeChange(this, false);
}
return null;
});
+29 -79
View File
@@ -13,8 +13,6 @@ export async function _selectContextMode(
const generation = ++this._contextModeGeneration;
const isCurrent = () =>
!this.destroyed && generation === this._contextModeGeneration;
this._contextModeEntryIntent = null;
this._contextModeReplacementIntent = null;
this._contextModeChanging = true;
this._syncContextModeButtons();
try {
@@ -47,9 +45,6 @@ export async function _selectContextMode(
this._captureContextSessionSnapshot();
this._contextMode = mode;
this._syncContextModeButtons();
// Replay isolation must settle before Space Missions starts. Contacts
// keeps its non-dependency teardown in the background so slow source
// shutdown does not delay cockpit entry.
try {
await this._clearLayersOutsideContextMode(mode, {
notificationToken,
@@ -82,13 +77,8 @@ export async function _selectContextMode(
// Entry is one transaction: isolation succeeded above, so a failed mode
// activation must roll the cleared layers back instead of stranding the
// user in a half-entered mode with an orphaned snapshot.
const entryLayerId =
mode === 'flights' ? 'military-awareness' : 'rocket-launches';
if (mode === 'flights') {
this._dataManager.setLayerParams('military-awareness', {
passive: false,
});
}
const entryLayerId = 'military-awareness';
this._dataManager.setLayerParams(entryLayerId, { passive: false });
let activated = false;
let activationError = null;
let activationIntent = null;
@@ -99,11 +89,6 @@ export async function _selectContextMode(
true,
{ notificationToken, ...(signal ? { signal } : {}) },
);
this._contextModeEntryIntent = {
generation,
layerId: entryLayerId,
intentEpoch: activationIntent.intentEpoch,
};
activated = await activationIntent.promise;
terminalIntentOutcome =
await this._dataManager._waitForVisibilityIntent?.(
@@ -114,46 +99,6 @@ export async function _selectContextMode(
activationError = error;
}
if (!isCurrent()) return false;
let replacementIntent =
mode === 'space-missions' &&
this._contextModeReplacementIntent?.generation === generation &&
this._contextModeReplacementIntent.layerId === entryLayerId
? this._contextModeReplacementIntent
: null;
while (replacementIntent) {
const outcome = await this._dataManager._waitForVisibilityIntent?.(
entryLayerId,
replacementIntent.intentEpoch,
);
terminalIntentOutcome = outcome;
if (!isCurrent()) return false;
const replacementOwnsMode =
outcome?.intentEpoch === replacementIntent.intentEpoch &&
outcome.enabled === true &&
outcome.succeeded === true;
if (replacementOwnsMode) {
this._contextModeEntering = null;
this._contextModeEntryIntent = null;
this._contextModeReplacementIntent = null;
this._syncContextModeButtons();
return true;
}
const successorEpoch =
outcome?.cancellationReason === 'superseded' &&
outcome.successorEnabled === true &&
Number.isInteger(outcome.successorIntentEpoch) &&
outcome.successorIntentEpoch > replacementIntent.intentEpoch
? outcome.successorIntentEpoch
: null;
replacementIntent =
successorEpoch === null
? null
: {
generation,
layerId: entryLayerId,
intentEpoch: successorEpoch,
};
}
if (
activationError ||
activated === false ||
@@ -182,8 +127,6 @@ export async function _selectContextMode(
);
}
this._contextMode = null;
this._contextModeEntryIntent = null;
this._contextModeReplacementIntent = null;
this._syncContextModeButtons();
try {
await this._restoreContextSession({
@@ -205,7 +148,6 @@ export async function _selectContextMode(
// while callers still require literal `true` before expanding Context.
return cancelledAndSettled ? null : false;
}
this._contextModeEntryIntent = null;
return true;
} finally {
if (isCurrent()) {
@@ -221,8 +163,6 @@ export async function _deactivateContextForLayerChange({
this._contextModeGeneration += 1;
this._contextModeChanging = true;
this._contextMode = null;
this._contextModeEntryIntent = null;
this._contextModeReplacementIntent = null;
// A layer turned off ends Contacts but not the Cockpit: the view ends only
// when the layer it rides goes off (see _handleContextLayerChange).
this._syncContextModeButtons();
@@ -240,25 +180,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) =>
+41
View File
@@ -0,0 +1,41 @@
/**
* @module ui/creditLineHeight
* @description Keeps `--credit-line-height` on the page's root at the
* height of the attribution line at the bottom of the screen, so what sits
* above it (the HUD's bottom corners) clears it when it wraps onto more
* lines. The line is the application's own (`#gev-credits`) or the one a
* renderer draws inside `#cesium-credits`.
*/
const LINES = ['#gev-credits', '#cesium-credits .cesium-widget-credits'];
/**
* Follow the attribution line's height in `--credit-line-height`.
* @param {Document} [doc]
* @returns {() => void} Stops following it and clears the property.
*/
export function trackCreditLineHeight(doc = globalThis.document) {
const Observer = doc?.defaultView?.ResizeObserver;
if (!doc?.documentElement || typeof Observer !== 'function') return () => {};
const root = doc.documentElement;
const lines = LINES.map((selector) => doc.querySelector(selector)).filter(
Boolean,
);
if (!lines.length) return () => {};
const update = () => {
const height = Math.max(
0,
...lines.map((line) => line.getBoundingClientRect().height),
);
if (height > 0)
root.style.setProperty('--credit-line-height', `${Math.ceil(height)}px`);
else root.style.removeProperty('--credit-line-height');
};
const observer = new Observer(update);
for (const line of lines) observer.observe(line);
update();
return () => {
observer.disconnect();
root.style.removeProperty('--credit-line-height');
};
}
+79
View File
@@ -0,0 +1,79 @@
import '../testSupport/registerDom.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import { trackCreditLineHeight } from './creditLineHeight.js';
/** A ResizeObserver the test drives, with each line's height set by hand. */
function fakeResizing() {
const observers = [];
const window = document.defaultView;
const original = window.ResizeObserver;
window.ResizeObserver = class {
constructor(callback) {
this.callback = callback;
this.targets = new Set();
observers.push(this);
}
observe(target) {
this.targets.add(target);
}
disconnect() {
this.targets.clear();
}
};
return {
resize(element, height) {
element.getBoundingClientRect = () => ({ height });
for (const observer of observers)
if (observer.targets.has(element)) observer.callback([]);
},
restore() {
window.ResizeObserver = original;
},
};
}
test("the credit line's height follows it as it wraps, for either renderer's line", () => {
const resizing = fakeResizing();
try {
for (const markup of [
'<div id="gev-credits"></div>',
'<div id="cesium-credits"><div class="cesium-widget-credits"></div></div>',
]) {
document.body.innerHTML = markup;
const line = document.querySelector(
'#gev-credits, #cesium-credits .cesium-widget-credits',
);
line.getBoundingClientRect = () => ({ height: 28 });
const stop = trackCreditLineHeight(document);
const root = document.documentElement.style;
assert.equal(root.getPropertyValue('--credit-line-height'), '28px');
resizing.resize(line, 66.4);
assert.equal(root.getPropertyValue('--credit-line-height'), '67px');
// Hidden, it holds no room.
resizing.resize(line, 0);
assert.equal(root.getPropertyValue('--credit-line-height'), '');
resizing.resize(line, 28);
stop();
assert.equal(root.getPropertyValue('--credit-line-height'), '');
}
} finally {
resizing.restore();
document.body.replaceChildren();
}
});
test('without a credit line nothing is followed', () => {
const resizing = fakeResizing();
try {
document.body.replaceChildren();
const stop = trackCreditLineHeight(document);
assert.equal(
document.documentElement.style.getPropertyValue('--credit-line-height'),
'',
);
stop();
} finally {
resizing.restore();
}
});
+53
View File
@@ -0,0 +1,53 @@
<script setup>
import { computed } from 'vue';
import {
LINK_SCHEMES,
LOGO_SCHEMES,
safeUrl,
splitLink,
} from '../../render/creditMarkup.js';
// One credit: its logo or its text, linked when it has a link. 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.
const props = defineProps({
credit: { type: Object, required: true },
});
const href = computed(() =>
props.credit.href ? safeUrl(props.credit.href, LINK_SCHEMES) : null,
);
// A logo is drawn in place of the text, which names it (its alt text).
const logo = computed(() =>
props.credit.logoUrl ? safeUrl(props.credit.logoUrl, LOGO_SCHEMES) : null,
);
// Only the credit's linked words are the link, as the source wrote it.
const parts = computed(() =>
href.value && !logo.value && props.credit.linkText
? splitLink(props.credit)
: null,
);
</script>
<template>
<span v-if="parts" class="gev-credit"
>{{ parts[0]
}}<a :href="href" target="_blank" rel="noopener noreferrer">{{
parts[1]
}}</a
>{{ parts[2] }}</span
><component
:is="href ? 'a' : 'span'"
v-else
class="gev-credit"
:href="href || undefined"
:target="href ? '_blank' : undefined"
:rel="href ? 'noopener noreferrer' : undefined"
><img
v-if="logo"
class="gev-credit-logo"
:src="logo"
:alt="credit.text"
/><template v-else>{{ credit.text }}</template></component
>
</template>
+82
View File
@@ -0,0 +1,82 @@
<script setup>
import { t } from '../../i18n/index.js';
import UiCloseButton from '../kit/UiCloseButton.vue';
import CreditItem from './CreditItem.vue';
// The attribution line at the bottom left and the "Data attribution" list it
// opens, both at the end of `to` (the page's body), where the page's rules
// place them. The owner (src/ui/creditsView.js) computes the credits shown,
// keeps the list's open state and its focus, and takes the clicks and keys;
// `elements` receives the line's, the button's and the list's elements for
// it.
const props = defineProps({
to: { type: Object, required: true },
panelId: { type: String, required: true },
/** The credits on the line, once each. */
inline: { type: Array, required: true },
/** The credits in the list, once each. */
listed: { type: Array, required: true },
open: { type: Boolean, default: false },
/**
* The locale its words are in: a change words them again. The template
* never reads it; `t()` is not reactive, so a new value is what makes the
* view render again in the new language.
*/
locale: { type: String, default: '' },
elements: { type: Object, required: true },
onExpand: { type: Function, default: () => {} },
onClose: { type: Function, default: () => {} },
onKeydown: { type: Function, default: () => {} },
});
/** Between the line's credits, and before the list's button. */
const SEPARATOR = ' · ';
/** A credit's key: the same text and link are one credit. */
const key = (credit) => `${credit.text}\u0000${credit.href ?? ''}`;
/** Keep `name`'s element for the owner. */
const keep = (name) => (element) => {
props.elements[name] = element?.$el ?? element;
};
</script>
<template>
<Teleport :to="props.to"
><div id="gev-credits" :ref="keep('bar')" class="gev-credits" tabindex="-1"
><span :ref="keep('line')" class="gev-credits-line"
><template v-for="(credit, i) in props.inline" :key="key(credit)"
>{{ i ? SEPARATOR : '' }}<CreditItem :credit="credit" /></template
>{{ props.inline.length && props.listed.length ? SEPARATOR : '' }}</span
><button
:ref="keep('expand')"
type="button"
class="gev-credits-expand"
aria-haspopup="dialog"
:aria-controls="props.panelId"
:aria-expanded="String(props.open)"
:hidden="props.listed.length === 0"
@click="props.onExpand()"
>{{ t('Data attribution') }}</button
></div
><div
:id="props.panelId"
:ref="keep('panel')"
class="gev-credits-panel"
role="dialog"
:aria-labelledby="`${props.panelId}-title`"
:hidden="!props.open"
@keydown="props.onKeydown($event)"
><div class="gev-credits-header"
><span class="gev-credits-title" :id="`${props.panelId}-title`">{{
t('Data provided by:')
}}</span
><UiCloseButton
:ref="keep('close')"
class="gev-credits-close"
bare
:label="t('Close data attribution')"
@click="props.onClose()" /></div
><ul class="gev-credits-list"
><li v-for="credit in props.listed" :key="key(credit)"
><CreditItem :credit="credit" /></li></ul></div
></Teleport>
</template>
+114
View File
@@ -0,0 +1,114 @@
/**
* @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. `CreditsView` renders the line and
* the list; this owner keeps the credits shown, the list's open state and
* its focus.
*/
import { h, render as renderVue } from 'vue';
import { findCredits } from '../render/rendererOf.js';
import { getLocale, onLocaleChange } from '../i18n/index.js';
import CreditsView from './credits/CreditsView.vue';
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;
});
}
/**
* 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;
// The view teleports the line and the list to the end of `root`; this
// host, never in the page, holds only its place.
const host = doc.createElement('div');
const elements = {};
let inline = [];
let listed = [];
let open = false;
// The view patches synchronously, so focus can move once it returns.
const paint = () =>
renderVue(
h(CreditsView, {
to: root,
panelId: PANEL_ID,
inline,
listed,
open,
locale: getLocale(),
elements,
onExpand,
onClose,
onKeydown,
}),
host,
);
const setOpen = (next, { focus = false } = {}) => {
open = next;
paint();
if (open) elements.close.focus();
else if (focus) elements.expand.focus();
};
const render = (all) => {
const { bar, line, panel } = elements;
const focused = panel.contains(doc.activeElement);
const shown = distinct(Array.isArray(all) ? all : []);
inline = shown.filter((credit) => credit.inline);
listed = shown.filter((credit) => !credit.inline);
paint();
if (listed.length === 0 && open) {
// 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.
elements.close.focus();
}
};
function onExpand() {
setOpen(!open);
}
function onClose() {
setOpen(false, { focus: true });
}
// Escape in the open list closes it (it takes focus as it opens).
function onKeydown(event) {
if (event.key !== 'Escape' || !open) return;
event.preventDefault();
setOpen(false, { focus: true });
}
paint();
render(credits.list());
const offChange = credits.on('change', render);
// The view words its text again in the new locale, as it renders.
const offLocale = onLocaleChange(paint);
return () => {
offChange();
offLocale();
renderVue(null, host);
};
}
+209
View File
@@ -0,0 +1,209 @@
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';
import { setLocale } from '../i18n/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();
const link = panel.querySelector('li a');
link.focus();
const removeOther = renderer.credits.addStatic({ text: 'NOAA' });
assert.equal(panel.hidden, false);
assert.ok(panel.contains(document.activeElement), 'still in the list');
assert.equal(document.activeElement, link, 'the focused link keeps it');
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();
});
test('the line and its list follow the locale', () => {
const { viewer, renderer } = scene();
renderer.credits.addStatic({ text: 'NOAA' });
const off = mountCreditsView(viewer);
const expand = document.querySelector('.gev-credits-expand');
const close = document.querySelector('.gev-credits-close');
try {
setLocale('fr');
assert.equal(expand.textContent, 'Attribution des données');
assert.equal(
document.getElementById('gev-credits-panel-title').textContent,
'Données fournies par\u202f:',
);
assert.equal(
close.getAttribute('aria-label'),
"Fermer l'attribution des données",
);
} finally {
setLocale('en');
}
assert.equal(expand.textContent, 'Data attribution');
off();
});
test('the line and its list are the last of the body, and its close button is the kit’s', () => {
const { viewer, renderer } = scene();
document.body.append(document.createElement('main'));
renderer.credits.addStatic({ text: 'NOAA' });
const off = mountCreditsView(viewer);
const children = [...document.body.children];
assert.deepEqual(
children.slice(-2).map((element) => element.id),
['gev-credits', 'gev-credits-panel'],
'the page’s rules select them as children of the body',
);
const close = document.querySelector('.gev-credits-close');
assert.ok(close.classList.contains('ui-button'), 'a UiCloseButton');
assert.equal(close.type, 'button');
assert.equal(close.textContent, '×');
assert.equal(close.hasAttribute('title'), false, 'no tip');
assert.equal(
close.classList.contains('ui-close-button'),
false,
'bare: it keeps the browser’s padding',
);
off();
assert.deepEqual(
[...document.body.children].map((element) => element.tagName),
['MAIN'],
);
});
+2 -3
View File
@@ -9,9 +9,8 @@ import { fileURLToPath } from 'node:url';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const STYLES = path.join(HERE, 'styles');
const LOCALES = path.join(HERE, '..', 'i18n', 'locales');
// cyber.css carries decorative theme strings (LOC / GRID, SYS 06 // ...);
// street-level.css ' · ESC' is a key cap. Neither is UI copy.
const DECORATIVE = new Set(['cyber.css', 'street-level.css']);
// street-level.css ' · ESC' is a key cap, not UI copy.
const DECORATIVE = new Set(['street-level.css']);
test('no user-visible text in CSS content: outside decorative themes', () => {
const hits = [];
+4 -10
View File
@@ -38,7 +38,6 @@ export function getCyberSonarControlState(
intensityPct: settings.intensity,
opacityPct: settings.opacity,
sectorDeg: settings.sector,
cyberSelected: root?.dataset?.uiTheme === 'cyber',
mapSweepActive: isCyberSonarActive(options),
contactSweepActive:
root?.dataset?.cyberSonarGpu === 'supported' &&
@@ -59,10 +58,10 @@ export function setCyberSonarControls(
sonar: getCyberSonarControlState(doc, { hudActive: owner?.hud?.visible }),
});
if (!request || typeof request !== 'object' || Array.isArray(request)) {
return fail('Provide Cyber sonar settings as an object.');
return fail('Provide sonar settings as an object.');
}
const fields = Object.keys(request);
if (!fields.length) return fail('Provide at least one Cyber sonar setting.');
if (!fields.length) return fail('Provide at least one sonar setting.');
for (const field of fields) {
const value = request[field];
if (field === 'enabled') {
@@ -70,19 +69,14 @@ export function setCyberSonarControls(
continue;
}
if (!Object.hasOwn(SETTING_FIELDS, field)) {
return fail('Unknown Cyber sonar setting.');
return fail('Unknown sonar setting.');
}
const [, min, max] = SETTING_FIELDS[field];
if (!Number.isInteger(value) || value < min || value > max) {
return fail(`${field} must be an integer from ${min} to ${max}.`);
}
}
if (
owner.hud?.getVariant?.() !== 'cyber' ||
doc?.documentElement?.dataset?.uiTheme !== 'cyber'
) {
return fail('Cyber sonar controls require the Cyber HUD layout.');
}
owner.shareLinkManager?.claimRestoreLane?.('visual');
for (const [field, [setting]] of Object.entries(SETTING_FIELDS)) {
if (Object.hasOwn(request, field)) {
owner._setCyberSonarSetting(setting, request[field]);
+23 -9
View File
@@ -11,9 +11,9 @@ import { StyleManager } from './applicationShell.js';
import { VisualSettings } from './visualSettings.js';
import { readFileSync } from 'node:fs';
function fixture(theme = 'cyber') {
function fixture(layout = 'tactical') {
const root = {
dataset: { uiTheme: theme, cyberSonarGpu: 'supported' },
dataset: { cyberSonarGpu: 'supported' },
style: { setProperty() {} },
};
const flags = new Set();
@@ -27,7 +27,7 @@ function fixture(theme = 'cyber') {
};
const calls = [];
const owner = {
hud: { getVariant: () => theme },
hud: { getVariant: () => layout },
_setCyberSonarSetting(name, value) {
calls.push([name, value]);
const suffix = name[0].toUpperCase() + name.slice(1);
@@ -50,31 +50,45 @@ test('real runner and facade use visual settings, preserve visibility and return
visual.services = { governorRequestRender: (reason) => renders.push(reason) };
// No Display panel here: the controls' render is not under test.
visual._publishDisplay = () => {};
// The shell's share sync; a sonar change keeps the link current.
const shares = [];
visual._syncShareState = () => shares.push(true);
const owner = Object.create(StyleManager.prototype);
owner._visualSettings = visual;
const claims = [];
Object.defineProperty(owner, 'shareLinkManager', { value: {
claimRestoreLane: (lane) => claims.push({ lane, renders: renders.length }),
} });
Object.defineProperty(owner, 'hud', { value: f.owner.hud });
const viewer = {
camera: { moveEnd: { addEventListener() {} } },
clock: { onTick: { addEventListener: () => () => {} } },
scene: { canvas: new EventTarget() },
get canvas() {
return this.scene.canvas;
},
};
try {
const runner = createGevActionRunner({ styleManager: owner, viewer, dataManager: {} });
const result = await runner('set_cyber_sonar', { enabled: false, intensityPct: 73, sectorDeg: 9 });
assert.equal(result.ok, true);
assert.deepEqual(claims, [{ lane: 'visual', renders: 0 }]);
assert.equal(result.sonar.intensityPct, 73);
assert.equal(result.sonar.sectorDeg, 9);
assert.equal(result.sonar.enabled, false);
assert.equal(f.root.dataset.uiTheme, 'cyber');
assert.equal(f.owner.hud.getVariant(), 'tactical');
assert.equal(f.hudFlags.has('active'), true);
assert.equal(renders.length, 3);
assert.equal(shares.length, 1);
const before = getCyberSonarControlState();
const invalid = await runner('set_cyber_sonar', { rings: 6, opacityPct: 0 });
assert.equal(invalid.ok, false);
assert.deepEqual(claims, [{ lane: 'visual', renders: 0 }], 'invalid requests claim no authority');
assert.deepEqual(getCyberSonarControlState(), before);
assert.equal(renders.length, 3);
const zero = await runner('set_cyber_sonar', { intensityPct: 0 });
assert.equal(zero.sonar.intensityPct, 0);
assert.deepEqual(claims.map(({ lane }) => lane), ['visual', 'visual']);
assert.equal(zero.sonar.enabled, false);
const unavailable = createGevActionRunner({ styleManager: {}, viewer, dataManager: {} });
assert.equal((await unavailable('set_cyber_sonar', { enabled: true })).ok, false);
@@ -133,11 +147,11 @@ test('rejects the whole invalid request before any mutation', () => {
}
});
test('requires Cyber and preserves off state and every omitted setting', () => {
for (const theme of ['tactical', 'minimal']) {
const f = fixture(theme);
assert.equal(setCyberSonarControls(f.owner, { enabled: true }, f.doc).ok, false);
assert.deepEqual(f.calls, []);
test('works under every HUD layout and preserves off state and every omitted setting', () => {
for (const layout of ['tactical', 'minimal']) {
const f = fixture(layout);
assert.equal(setCyberSonarControls(f.owner, { enabled: true }, f.doc).ok, true);
assert.deepEqual(f.calls, [['enabled', true]]);
}
const f = fixture();
f.root.dataset.cyberSonar = 'off';
-913
View File
@@ -1,913 +0,0 @@
import { getScopeMaskFeather, isScopeMaskEnabled, setScopeMaskEnabled, setScopeMaskFeather } from '../scopeMask.js';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import test from 'node:test';
import {
applyHudUiTheme,
CYBER_VISUAL_DEFAULTS,
cyberVisualDefaultsForHudTransition,
HUD_LAYOUTS,
normalizeHudLayout,
} from '../hudLayouts.js';
import { GEV_ACTION_SCHEMAS } from '../voice/actionSchemas.js';
import { createGevActionRunner } from '../voice/gevActions.js';
import { StyleManager } from './applicationShell.js';
import { createPinia } from 'pinia';
import { useDisplayStore } from './stores/display.js';
import { VisualSettings } from './visualSettings.js';
import { STYLES } from './visualPresets.js';
test('CCTV and Context keep their headers outside Cyber-only scroll bodies', () => {
for (const file of ['panels/CctvPanel.vue', 'ContextView.vue']) {
const markup = readFileSync(
new URL(`./views/${file}`, import.meta.url),
'utf8',
);
// The body wears the shared scrollbar skin where Cyber makes it scroll.
assert.match(
markup,
/class="cyber-panel-body ui-scroll" data-rail-scroller/,
);
assert.ok(
// The header is RailPanel's; the body is its first content.
markup.indexOf('<RailPanel ') > -1 &&
markup.indexOf('<RailPanel ') <
markup.indexOf('class="cyber-panel-body ui-scroll"'),
);
}
const shared = readFileSync(
new URL('./styles/controls.css', import.meta.url),
'utf8',
);
const cyber = readFileSync(
new URL('./styles/cyber.css', import.meta.url),
'utf8',
);
assert.match(shared, /\.cyber-panel-body\s*\{\s*display: contents;/);
assert.match(
cyber,
/:root\[data-ui-theme='cyber'\] \.cyber-panel-body\s*\{[^}]*overflow-y: auto;[^}]*overscroll-behavior: contain;/,
);
});
function styleOwner(t, initialVariant = 'cyber') {
const previous = { document: globalThis.document, window: globalThis.window };
const root = { dataset: {} };
globalThis.document = { documentElement: root, querySelectorAll: () => [] };
globalThis.window = { dispatchEvent() {} };
t.after(() => Object.assign(globalThis, previous));
let variant = initialVariant;
const calls = [];
const hud = {
getVariant: () => variant,
setVariant: (value) => {
// Normalize like the real HUD so retired layouts fall back.
variant = normalizeHudLayout(value);
applyHudUiTheme(root, variant);
},
setMode: (value) => calls.push(['mode', value]),
onStyleChange: (value) => calls.push(['style', value]),
};
hud.setVariant(initialVariant);
const owner = Object.create(VisualSettings.prototype);
Object.assign(owner, {
activeStyle: 'normal',
store: { publish() {} },
readHud: () => hud,
readShareLinks: () => ({ onStyleChange() {} }),
_visualEffects: {
stages: Object.fromEntries(
Object.entries(STYLES).map(([name, config]) => [
name,
{ uniforms: { ...config.uniforms, intensity: 0 } },
]),
),
},
services: { governorRequestRender() {}, setDetectionStyle() {} },
_setBloomEnabled: (value) => calls.push(['bloom', value]),
_setSharpenEnabled: (value) => calls.push(['sharpen', value]),
_applyDetectionPreset: (value) => calls.push(['detection', value]),
_syncShareState: () => calls.push(['share', variant]),
});
for (const name of [
'setCelestialRingEnabled',
'_startTransition',
'_publishActiveStyle',
'_updateSliderPanel',
'_updateHudButtonState',
'_syncIrBoost',
'_syncCockpitInheritedStyle',
'_syncCyberSonarControl',
'_scheduleAdaptivePanelLayout',
'_setDetectionFade',
// Intensities: the fixture has no post-process stages to drive.
'_setBloomIntensity',
'_setSharpenIntensity',
])
owner[name] = () => {};
return { owner, hud, root, calls };
}
test('visual styles retain Cyber through real preset application without dropping other defaults', (t) => {
const { owner, hud, root, calls } = styleOwner(t);
for (const style of [
'surveillance',
'normal',
'noir',
'anime',
'thermal',
'retro',
]) {
owner.setStyle(style);
assert.equal(owner.activeStyle, style);
assert.equal(hud.getVariant(), 'cyber');
assert.equal(root.dataset.uiTheme, 'cyber');
assert.deepEqual(calls.at(-1), ['share', 'cyber']);
}
assert.equal(owner.stages.thermal.uniforms.sensitivity, 0.85);
assert.equal(calls.filter(([name]) => name === 'detection').length, 3);
assert.equal(
calls.filter(([name, value]) => name === 'bloom' && value === false).length,
3,
);
assert.equal(
calls.filter(([name, value]) => name === 'sharpen' && value === true)
.length,
3,
);
});
test('non-Cyber style presets and explicit HUD choices remain authoritative', (t) => {
const { owner, hud, root } = styleOwner(t);
for (const variant of ['tactical', 'minimal']) {
owner._setHudVariant(variant);
assert.equal(hud.getVariant(), variant);
assert.equal(root.dataset.uiTheme, undefined);
owner.setStyle('normal');
owner.setStyle('surveillance');
assert.equal(hud.getVariant(), 'tactical');
}
});
test('leaving Cyber without a preset choice restores the prior visual preset', (t) => {
const { owner, hud } = styleOwner(t, 'tactical');
owner.setStyle('noir');
owner._setHudVariant('cyber', { applyVisualDefaults: true });
assert.equal(owner.activeStyle, 'thermal');
assert.equal(owner._preCyberStyle, 'noir');
assert.equal(owner._cyberStyleUserSelected, false);
owner._setHudVariant('minimal', { applyVisualDefaults: true });
assert.equal(hud.getVariant(), 'minimal');
assert.equal(owner.activeStyle, 'noir');
assert.equal(owner._preCyberStyle, null);
assert.equal(owner._cyberStyleUserSelected, false);
});
test('a preset explicitly selected in Cyber survives exit and resets for re-entry', (t) => {
const { owner, hud } = styleOwner(t, 'tactical');
owner.setStyle('noir');
owner._setHudVariant('cyber', { applyVisualDefaults: true });
owner.setStyle('anime', { userInitiated: true });
assert.equal(owner.activeStyle, 'anime');
assert.equal(owner._preCyberStyle, 'noir');
assert.equal(owner._cyberStyleUserSelected, true);
// Reselecting the active mode must not erase the user's preset intent.
owner._setHudVariant('cyber', { applyVisualDefaults: true });
assert.equal(owner._preCyberStyle, 'noir');
owner._setHudVariant('minimal', { applyVisualDefaults: true });
assert.equal(hud.getVariant(), 'minimal');
assert.equal(owner.activeStyle, 'anime');
assert.equal(owner._preCyberStyle, null);
assert.equal(owner._cyberStyleUserSelected, false);
// A later untouched Cyber round trip restores the new pre-Cyber preset.
owner._setHudVariant('cyber', { applyVisualDefaults: true });
assert.equal(owner.activeStyle, 'thermal');
assert.equal(owner._preCyberStyle, 'anime');
owner._setHudVariant('minimal', { applyVisualDefaults: true });
assert.equal(owner.activeStyle, 'anime');
});
test('an explicit same-value FLIR choice is preserved on Cyber exit', (t) => {
const { owner } = styleOwner(t, 'tactical');
owner.setStyle('noir');
owner._setHudVariant('cyber', { applyVisualDefaults: true });
owner.setStyle('thermal', { userInitiated: true });
assert.equal(owner.activeStyle, 'thermal');
assert.equal(owner._cyberStyleUserSelected, true);
owner._setHudVariant('minimal', { applyVisualDefaults: true });
assert.equal(owner.activeStyle, 'thermal');
});
test('an authoritative same-Cyber reset clears local preset ownership', (t) => {
const { owner } = styleOwner(t, 'tactical');
owner.setStyle('noir');
owner._setHudVariant('cyber', { applyVisualDefaults: true });
owner.setStyle('anime', { userInitiated: true });
assert.equal(owner._cyberStyleUserSelected, true);
owner._setHudVariant('cyber');
assert.equal(owner.activeStyle, 'anime');
assert.equal(owner._preCyberStyle, null);
assert.equal(owner._cyberStyleUserSelected, false);
owner._setHudVariant('minimal', { applyVisualDefaults: true });
assert.equal(owner.activeStyle, 'anime');
});
test('Display and voice HUD routes preserve explicit Cyber entry and exit authority', async (t) => {
const makeOwner = () => {
const { owner, hud } = styleOwner(t, 'tactical');
owner.setStyle('noir');
owner.setHudLayout = (...args) =>
StyleManager.prototype.setHudLayout.call(owner, ...args);
owner.getControlState = () => ({
hud: { layout: hud.getVariant(), visible: true },
});
return { owner, hud };
};
const display = makeOwner();
// The Display panel's layout select and the dock's style buttons call
// these actions through the display store.
const store = useDisplayStore(createPinia());
const token = store.connect({
setHudLayout: (value) => display.owner.setHudLayout(value),
setStyle: (value) => display.owner.setStyle(value, { userInitiated: true }),
});
store.act('setHudLayout', 'cyber');
assert.equal(display.hud.getVariant(), 'cyber');
assert.equal(display.owner.activeStyle, 'thermal');
store.act('setStyle', 'anime');
assert.equal(display.owner.activeStyle, 'anime');
store.act('setHudLayout', 'minimal');
assert.equal(display.hud.getVariant(), 'minimal');
assert.equal(display.owner.activeStyle, 'anime');
store.detach(token);
const voice = makeOwner();
const eventSource = { addEventListener() {}, removeEventListener() {} };
const viewer = {
camera: { moveEnd: { addEventListener() {} } },
clock: { onTick: { addEventListener: () => () => {} } },
scene: { canvas: eventSource },
};
const runVoiceAction = createGevActionRunner({
viewer,
styleManager: voice.owner,
dataManager: {},
});
const entered = await runVoiceAction('set_hud', { layout: 'cyber' });
assert.equal(entered.ok, true);
assert.equal(voice.hud.getVariant(), 'cyber');
assert.equal(voice.owner.activeStyle, 'thermal');
const selected = await runVoiceAction('set_visual_style', { style: 'anime' });
assert.equal(selected.ok, true);
assert.equal(voice.owner.activeStyle, 'anime');
const exited = await runVoiceAction('set_hud', { layout: 'minimal' });
assert.equal(exited.ok, true);
assert.equal(voice.hud.getVariant(), 'minimal');
assert.equal(voice.owner.activeStyle, 'anime');
});
test('scope choice and expanded feather survive every HUD layout and both restore paths', async (t) => {
const { owner } = styleOwner(t, 'tactical');
const previous = { enabled: isScopeMaskEnabled(), feather: getScopeMaskFeather() };
t.after(() => { setScopeMaskEnabled(previous.enabled); setScopeMaskFeather(previous.feather); });
Object.assign(owner.services, { setScopeMaskEnabled, setScopeMaskFeather });
let shown = null;
owner.store = { publish: (view) => (shown = view.scope) };
await owner.restoreShareState({ scopeEnabled: false, scopeFeatherPct: 200 });
assert.deepEqual(shown, { enabled: false, featherPct: 200 });
for (const layout of ['minimal', 'cyber', 'tactical']) {
owner._setHudVariant(layout, { applyVisualDefaults: true });
assert.equal(isScopeMaskEnabled(), false, layout);
assert.equal(getScopeMaskFeather(), 2, layout);
assert.equal(shown.enabled, false, layout);
}
await owner.applyVisualState({ scope: { enabled: true, featherPct: 175 } });
assert.equal(isScopeMaskEnabled(), true);
assert.equal(getScopeMaskFeather(), 1.75);
assert.deepEqual(shown, { enabled: true, featherPct: 175 });
await owner.applyVisualState({ scope: { featherPct: 500 } });
assert.equal(getScopeMaskFeather(), 2);
assert.deepEqual(shown, { enabled: true, featherPct: 200 });
});
test('a scene shot saved with the retired Snow style plays on Normal', async (t) => {
const { owner } = styleOwner(t, 'tactical');
owner.setStyle('noir');
await owner.applyVisualState({ style: 'snow' });
assert.equal(owner.activeStyle, 'normal');
});
test('scene and share HUD transitions do not restore a local pre-Cyber preset', async (t) => {
const { owner, hud } = styleOwner(t, 'tactical');
owner.setStyle('noir');
owner._setHudVariant('cyber', { applyVisualDefaults: true });
owner.setStyle('anime', { userInitiated: true });
assert.equal(owner._cyberStyleUserSelected, true);
await owner.applyVisualState({ style: 'retro', hud: { variant: 'cyber' } });
assert.equal(hud.getVariant(), 'cyber');
assert.equal(owner.activeStyle, 'retro');
assert.equal(owner._preCyberStyle, null);
assert.equal(owner._cyberStyleUserSelected, false);
owner._setHudVariant('minimal', { applyVisualDefaults: true });
assert.equal(owner.activeStyle, 'retro');
owner.setStyle('surveillance');
owner._setHudVariant('cyber', { applyVisualDefaults: true });
assert.equal(owner._preCyberStyle, 'surveillance');
owner.setStyle('anime', { userInitiated: true });
await owner.restoreShareState({
style: 'thermal',
hudVariant: 'cyber',
});
assert.equal(hud.getVariant(), 'cyber');
assert.equal(owner.activeStyle, 'thermal');
assert.equal(owner._preCyberStyle, null);
assert.equal(owner._cyberStyleUserSelected, false);
owner._setHudVariant('tactical', { applyVisualDefaults: true });
assert.equal(owner.activeStyle, 'thermal');
assert.equal(owner._preCyberStyle, null);
});
test('scene and share restoration override Cyber and preserve restored Cyber parameters', async (t) => {
const { owner, hud } = styleOwner(t);
await owner.applyVisualState({ style: 'retro', hud: { variant: 'minimal' } });
assert.equal(hud.getVariant(), 'minimal');
owner._setHudVariant('cyber');
await owner.restoreShareState({
style: 'surveillance',
hudVariant: 'operator',
});
// A link saved with the retired Operator layout restores as Tactical.
assert.equal(hud.getVariant(), 'tactical');
await owner.restoreShareState({
style: 'thermal',
hudVariant: 'cyber',
styleParams: { palette: 0.73 },
});
assert.equal(hud.getVariant(), 'cyber');
assert.equal(owner.activeStyle, 'thermal');
assert.equal(owner.stages.thermal.uniforms.palette, 0.73);
owner._setHudVariant('cyber', { applyVisualDefaults: true });
assert.equal(owner.stages.thermal.uniforms.palette, 0.73);
owner._setHudVariant('tactical');
owner._setHudVariant('cyber', { applyVisualDefaults: true });
assert.equal(owner.stages.thermal.uniforms.palette, 0.42);
});
const read = (relative) =>
readFileSync(new URL(relative, import.meta.url), 'utf8');
test('Cyber setup uses a compact toolbar icon and highlights the north-up letter', () => {
const css = read('./styles/cyber.css');
assert.match(
css,
/#top-center-actions #key-setup-chip\s*\{[^}]*inset: auto;[^}]*width: 36px;/,
);
assert.match(css, /#key-setup-chip\[hidden\]\s*\{\s*display: none;/);
assert.match(
css,
/#north-up-view\[data-north-up='true'\]\s+\.camera-compass-n\s*\{[^}]*color: var\(--cyber-red-bright\)/,
);
});
const cyberStyles = read('./styles/cyber.css');
// Source guards supplement rendered popup/hit-target checks. Inspect one rule
// at a time so a safe declaration on a child cannot excuse a clipped ancestor.
function cssRuleBody(styles, selector) {
const match = styles.match(new RegExp(`${selector.source}\\s*\\{([^}]+)\\}`));
assert.ok(match, `Missing CSS rule: ${selector.source}`);
return match[1];
}
test('Cyber Voice clips its decoration without clipping descendant help and errors', () => {
const owner = cssRuleBody(
cyberStyles,
/:root\[data-ui-theme='cyber'\] #command-dock > #gev-voice-control/,
);
assert.match(owner, /isolation:\s*isolate;/);
assert.match(owner, /overflow:\s*visible;/);
assert.match(owner, /clip-path:\s*none;/);
const decoration = cssRuleBody(
cyberStyles,
/:root\[data-ui-theme='cyber'\] #command-dock > #gev-voice-control::before/,
);
assert.match(decoration, /clip-path:\s*polygon\(/);
assert.match(decoration, /pointer-events:\s*none;/);
assert.match(decoration, /inset:\s*0;/);
assert.match(decoration, /z-index:\s*-1;/);
});
test('Cyber dock pins escape the tray mask and its decoration overrides the legacy arrow geometry', () => {
const owner = cssRuleBody(
cyberStyles,
/:root\[data-ui-theme='cyber'\] #command-dock \.dock-popover-content/,
);
assert.match(owner, /clip-path:\s*none;/);
assert.match(owner, /isolation:\s*isolate;/);
// Including the tray owners beats #control-panel's more specific old
// ::after arrow positioning. Otherwise left:auto can collapse the frame.
const decoration = cssRuleBody(
cyberStyles,
/:root\[data-ui-theme='cyber'\]\s+#command-dock\s+:is\(#location-bar, #control-panel\)\s+\.dock-popover-content::after/,
);
assert.match(decoration, /inset:\s*0;/);
assert.match(decoration, /width:\s*auto;/);
assert.match(decoration, /height:\s*auto;/);
assert.match(decoration, /transform:\s*none;/);
assert.match(decoration, /clip-path:\s*var\(--cyber-panel-frame\);/);
assert.match(decoration, /pointer-events:\s*none;/);
});
test('Cyber lower-left telemetry tracks the credit anchor with clearance for its logo row', () => {
const telemetry = cssRuleBody(
cyberStyles,
/#intel-hud\[data-variant='cyber'\] \.hud-bottom-left/,
);
const offset = telemetry.match(/bottom:\s*calc\(2vh \+ ([\d.]+)rem \+ var\(--world-timeline-lift, 0px\)\);/);
assert.ok(offset, 'telemetry must retain the attribution viewport anchor');
const credits = read('./styles/command-dock-trays.css');
const creditOffsets = [
...credits.matchAll(
/#cesium-credits\s*\{[^}]*bottom:\s*calc\(2vh \+ ([\d.]+)rem \+ var\(--world-timeline-lift, 0px\)\);/g,
),
];
assert.ok(creditOffsets.length > 0);
for (const credit of creditOffsets) {
assert.ok(
Number(offset[1]) - Number(credit[1]) >= 2.75,
'reserve the 28px logo row, baseline descent and 12px clearance at the 16px root size',
);
}
assert.doesNotMatch(cyberStyles, /\.hud-bottom-left\s*\{\s*bottom:\s*60px;/);
});
test('shared panel hooks affect only opted-in rail surfaces without overriding disclosure and concealment', () => {
const styles = read('./styles/panel-surfaces.css');
const rail = cssRuleBody(
styles,
/:is\(#left-panel-stack, #right-context-rail\)\s+> \[data-panel-id\]:has\(> \[data-panel-surface\]\)/,
);
assert.match(rail, /pointer-events:\s*auto;/);
assert.doesNotMatch(rail, /(?:display|visibility):/);
assert.doesNotMatch(
styles,
/:is\(#left-panel-stack, #right-context-rail\)\s*> \[data-panel-id\]\s*\{/,
);
assert.match(
styles,
/\[data-panel-surface\]:not\(\[hidden\]\):not\(dialog:not\(\[open\]\)\)\s*\{\s*display: flex;/,
);
assert.match(
styles,
/dialog\[data-panel-surface\]:not\(\[open\]\)\s*\{\s*display: none !important;/,
);
assert.match(
styles,
/body:is\(\.ui-clean-view, \.recording-mode\)[^{]+\{[^}]*visibility: hidden !important;[^}]*pointer-events: none !important;/,
);
});
test('Cyber clipped expand controls retain an inset keyboard-focus outline in map and cockpit', () => {
assert.match(
cyberStyles,
/:root\[data-ui-theme='cyber'\]\s+:is\(\s*\.panel-collapse-btn,\s*body\.cockpit-mode \.cockpit-utility-glyph\s*\):focus-visible\s*\{[^}]*outline: 2px solid var\(--cyber-red-bright\) !important;[^}]*outline-offset: -3px;[^}]*box-shadow: none;/,
);
assert.match(
cyberStyles,
/:root\[data-ui-theme='cyber'\]\s+:is\(\.panel-collapse-btn, body\.cockpit-mode \.cockpit-utility-glyph\):is\(\s*:hover,\s*:focus-visible\s*\)\s*\{[^}]*border-color: var\(--cyber-red-bright\);/,
);
});
test('Cyber Radio retains upstream nested Context ownership', () => {
assert.doesNotMatch(cyberStyles, /#right-context-rail\s*>\s*#radio-panel/);
});
test('Cyber cockpit launchers share Data Layers frame and expand-control treatment', () => {
assert.match(
cyberStyles,
/:is\(\.panel-collapse-btn, body\.cockpit-mode \.cockpit-utility-glyph\)/,
);
assert.match(
cyberStyles,
/body\.cockpit-mode \.cockpit-utility-launcher \{[^}]*width: var\(--cyber-panel-width\);[^}]*min-height: 60px;[^}]*clip-path: var\(--cyber-panel-frame\);/,
);
assert.match(
cyberStyles,
/\.cockpit-utility-glyph::after \{\s*content: '\+';/,
);
assert.match(
cyberStyles,
/\.cockpit-utility-glyph\[aria-expanded='true'\]::after \{\s*content: '−';/,
);
assert.match(
cyberStyles,
/\.cockpit-utility-control\.is-expanded\s+\.cockpit-utility-launcher \{[^}]*width: 100%;[^}]*clip-path: none;/,
);
});
test('Cyber side panels share one width and one framed surface material', () => {
assert.match(cyberStyles, /--cyber-panel-width: 272px;/);
assert.match(cyberStyles, /--cyber-right-panel-width: 312px;/);
assert.match(cyberStyles, /--cyber-panel-collapsed-width: 200px;/);
assert.match(cyberStyles, /--cyber-panel-control-size: 30px;/);
assert.match(
cyberStyles,
/--cyber-panel-surface: rgba\(18, 24, 27, 0\.92\);/,
);
assert.match(
cyberStyles,
/\.cockpit-utility-control\.is-expanded \{[\s\S]*?width: var\(--cyber-right-panel-width\);[\s\S]*?background-color: var\(--cyber-panel-surface\);[\s\S]*?background-image: var\(--cyber-panel-surface-detail\);[\s\S]*?clip-path: var\(--cyber-panel-frame\);/,
);
assert.match(
cyberStyles,
/\.cockpit-utility-control\.is-expanded::after \{[\s\S]*?width: 36px;[\s\S]*?border-top: 1px solid rgba\(225, 102, 102, 0\.84\);/,
);
assert.match(
cyberStyles,
/#global-context-panel #radio-panel\.collapsed \{\s*width: 100%;/,
);
assert.match(
cyberStyles,
/#left-panel-stack\s*> :is\(#data-panel, #utilities-panel, #scene-panel\)\.collapsed \{\s*width: var\(--cyber-panel-collapsed-width\);/,
);
assert.match(
cyberStyles,
/:is\(#data-panel, #utilities-panel, #scene-panel\)\.collapsed\s+:is\(\.data-panel-inner, \.utilities-panel-inner, \.scene-panel-inner\) \{[\s\S]*?height: 50px;[\s\S]*?min-height: 50px;/,
);
assert.match(
cyberStyles,
/\.cockpit-utility-control:not\(\.is-expanded\)\s+\.cockpit-utility-launcher \{\s*width: var\(--cyber-panel-collapsed-width\);/,
);
assert.match(
cyberStyles,
/#pp-toggles\s*> \.pp-header-row\s+\.pp-collapse-btn \{[\s\S]*?width: var\(--cyber-panel-control-size\);[\s\S]*?height: var\(--cyber-panel-control-size\);/,
);
assert.match(
cyberStyles,
/#right-context-rail\s+:is\(\s*\.cctv-panel-inner,\s*\.weather-panel-inner,\s*\.recent-imagery-panel-inner,\s*\.street-level-panel-inner,\s*\.global-context-panel-inner\s*\) \{\s*padding-inline-end: 8px;/,
);
assert.match(
cyberStyles,
/#right-context-rail[\s\S]*?:is\(\s*#cctv-panel,\s*#weather-panel,\s*#recent-imagery-panel,\s*#street-level-panel,\s*#global-context-panel\s*\)\.collapsed[\s\S]*?> \.panel-header \{[\s\S]*?height: 48px;[\s\S]*?padding: 0 10px 0 14px;/,
);
assert.doesNotMatch(
cyberStyles,
/\.cockpit-utility-control\.is-expanded\s*\{[^}]*order:/,
'expanded Cockpit utilities must retain Display-then-Radio DOM order',
);
});
test('Cyber is a canonical HUD layout with a safe Tactical fallback', () => {
assert.deepEqual(HUD_LAYOUTS, ['tactical', 'minimal', 'cyber']);
assert.equal(normalizeHudLayout('CYBER'), 'cyber');
assert.equal(normalizeHudLayout('operator'), 'tactical');
assert.equal(normalizeHudLayout('unknown'), 'tactical');
});
test('the Cyber HUD owns the global shell skin and leaving it restores defaults', () => {
const root = { dataset: { unrelated: 'preserved' } };
assert.equal(applyHudUiTheme(root, 'cyber'), 'cyber');
assert.equal(root.dataset.uiTheme, 'cyber');
assert.equal(applyHudUiTheme(root, 'minimal'), null);
assert.equal(root.dataset.uiTheme, undefined);
assert.equal(root.dataset.unrelated, 'preserved');
});
test('an explicit transition into Cyber selects FLIR with Ironbow 0.42 once', () => {
assert.deepEqual(CYBER_VISUAL_DEFAULTS, {
style: 'thermal',
ironbow: 0.42,
});
assert.equal(
cyberVisualDefaultsForHudTransition('tactical', 'cyber', {
explicit: true,
}),
CYBER_VISUAL_DEFAULTS,
);
assert.equal(
cyberVisualDefaultsForHudTransition('cyber', 'cyber', {
explicit: true,
}),
null,
);
assert.equal(cyberVisualDefaultsForHudTransition('tactical', 'cyber'), null);
assert.equal(
cyberVisualDefaultsForHudTransition('cyber', 'minimal', {
explicit: true,
}),
null,
);
});
test('Cyber visual defaults update the style, thermal palette and render state', () => {
const calls = [];
const owner = {
stages: { thermal: { uniforms: { palette: 0 } } },
services: {
governorRequestRender: (reason) => calls.push(['render', reason]),
},
setStyle: (style, options) => calls.push(['style', style, options]),
_updateSliderPanel: (style, options) =>
calls.push(['sliders', style, options]),
};
VisualSettings.prototype._applyCyberVisualDefaults.call(
owner,
CYBER_VISUAL_DEFAULTS,
);
assert.equal(owner.stages.thermal.uniforms.palette, 0.42);
assert.deepEqual(calls, [
[
'style',
'thermal',
{
applyPreset: false,
revealParameters: false,
preserveCyberRestore: true,
},
],
['sliders', 'thermal', { reveal: false }],
['render', 'cyber-visual-defaults'],
]);
});
test('the Display selector, voice schema and final stylesheet expose Cyber', () => {
const display = read('./views/panels/DisplayPanel.vue');
const stylesheet = read('../../style.css');
const rightRail = read('./rightPanelRail.js');
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 setHud = GEV_ACTION_SCHEMAS.find((schema) => schema.name === 'set_hud');
assert.match(display, /<option value="cyber">\{\{ t\('Cyber'\) \}\}<\/option>/);
assert.match(display, /id="cyber-sonar-toggle"/);
assert.match(
display,
/id="cyber-sonar-opacity"[^>]*:model-value="sonar\?\.opacity \?\? 84" :aria-label="t\('Cyber contact and label opacity'\)"/,
);
assert.match(display, /id="cyber-sonar-sector"/);
assert.deepEqual(setHud.parameters.properties.layout.enum, HUD_LAYOUTS);
assert.match(stylesheet, /@import '\.\/src\/ui\/styles\/cyber\.css';\s*$/);
assert.match(cyberStyles, /:root\[data-ui-theme='cyber'\]/);
assert.match(cyberStyles, /\.material-symbols-outlined/);
assert.match(cyberStyles, /\.pp-label/);
assert.match(cyberStyles, /#intel-hud\[data-variant='cyber'\]/);
assert.match(cyberStyles, /#left-panel-stack/);
assert.match(cyberStyles, /#right-context-rail/);
assert.match(cyberStyles, /#command-dock/);
assert.match(cyberStyles, /--cyber-panel-frame: polygon/);
assert.match(cyberStyles, /\.data-panel-inner,/);
assert.match(cyberStyles, /#pp-toggles\.collapsed > \.pp-header-row/);
assert.match(
cyberStyles,
/\.panel-collapsible:not\(#location-bar\):not\(#control-panel\)::after/,
);
assert.match(cyberStyles, /clip-path: var\(--cyber-panel-frame\);/);
assert.match(hudView, /class="hud-sonar" aria-hidden="true"/);
assert.match(cyberStyles, /\.hud-sonar::before/);
assert.match(cyberStyles, /\.hud-sonar::after/);
assert.match(cyberStyles, /@keyframes cyber-sonar-sweep/);
assert.match(
cyberStyles,
/animation-delay:\s*var\(--cyber-sonar-phase-delay, 0ms\)/,
);
assert.doesNotMatch(cyberStyles, /--cyber-sonar-angle/);
assert.match(cyberStyles, /prefers-reduced-motion: reduce/);
assert.match(detection, /candidate\.sonarFactor \?\? 1/);
assert.match(detection, /sonarActive && !obj\.skipLabel/);
assert.match(detection, /const bracketAlpha = admissionAlpha \* sonarFactor/);
assert.match(detection, /sonarSampler\.label\(sonarFactor\)/);
assert.match(detection, /createCyberSonarSampler\(width, height, now\)/);
assert.match(cyberStyles, /data-cyber-sonar='off'/);
assert.match(detection, /governorRequestRender\('cyber-sonar-cadence'\)/);
assert.match(
detection,
/const animatingCount = countAnimatingRenderEntries\(renderEntries\);/,
);
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/,
);
assert.match(
cyberStyles,
/#title-bar \.title-logo #globe \{[\s\S]*?fill: var\(--cyber-red\);[\s\S]*?stroke: var\(--cyber-red-bright\);/,
);
assert.match(cyberStyles, /#title-bar \.title-logo #globe_cage/);
assert.match(
cyberStyles,
/#top-center-actions button\s*\{[\s\S]*?border-radius:\s*0;[\s\S]*?clip-path:\s*polygon\(\s*29% 0,\s*71% 0,[\s\S]*?0 29%\s*\);/,
);
assert.match(cyberStyles, /#top-center-actions button::before/);
assert.match(cyberStyles, /\.hud-top-left/);
assert.match(cyberStyles, /transparent 0 min\(40vw, 52vh\)/);
assert.match(cyberStyles, /\.hud-bottom-bar \{\s*display: none;/);
assert.doesNotMatch(cyberStyles, /\.hud-top-bar/);
// Cyber shares the measured rail/credit keep-out rather than overriding it.
assert.doesNotMatch(
cyberStyles,
/#right-context-rail\s*\{[^}]*\b(?:top|bottom|height|max-height):/,
);
assert.match(cyberStyles, /--cyber-hud-card-top: max\(100px, 10\.25vh\);/);
assert.match(
cyberStyles,
/--cyber-left-rail-top: max\([\s\S]*?220px,[\s\S]*?calc\(var\(--cyber-hud-card-top\) \+ 120px\)/,
);
assert.match(
cyberStyles,
/\.hud-top-left \{[\s\S]*?top: var\(--cyber-hud-card-top\);/,
);
assert.match(
cyberStyles,
/#left-panel-stack \{[\s\S]*?top: var\(--cyber-left-rail-top\) !important;[\s\S]*?bottom: calc\(2vh \+ 13rem \+ var\(--world-timeline-lift, 0px\)\);/,
);
assert.match(
cyberStyles,
/\.hud-left-edge \{\s*top: calc\(var\(--cyber-left-rail-top\) - 18px\);\s*left: 14px;/,
);
assert.match(
rightRail,
/const leftStackTop = settledLeftRailTop\([\s\S]*?const alignedTop = Number\.isFinite\(leftStackTop\)[\s\S]*?baseTop: alignedTop,/,
);
assert.match(
cyberStyles,
/--right-display-collapsed-width: var\(--cyber-panel-collapsed-width\);/,
);
assert.match(
cyberStyles,
/clip-path: polygon\([\s\S]*?12px 0,[\s\S]*?0 12px/,
);
assert.match(cyberStyles, /\.hud-corner::before/);
assert.match(
cyberStyles,
/--cyber-telemetry-fill: rgba\(13, 20, 23, 0\.985\);/,
);
assert.match(cyberStyles, /var\(--cyber-telemetry-fill\)/);
assert.match(cyberStyles, />\s*\.panel-header\s+\.panel-title::before/);
assert.match(cyberStyles, /\.panel-collapsible\.collapsed::after/);
assert.match(cyberStyles, /\.panel-collapsible:not\(\.collapsed\)::after/);
assert.match(cyberStyles, /\.context-mode-standby:not\(\[hidden\]\)/);
// The base standby is borderless plain text, so the focus card must name its
// own frame width and centring rather than inherit them.
assert.match(
cyberStyles,
/\.context-mode-standby:not\(\[hidden\]\) \{[^}]*place-content: center;[^}]*border: 1px solid[^}]*text-align: center;/,
);
assert.match(
cyberStyles,
/:root\[data-ui-theme='cyber'\] \.global-context-modes \{[^}]*border: 0;/,
);
assert.match(cyberStyles, /mask-image: linear-gradient\(/);
assert.match(cyberStyles, /flex: 1 1 auto;/);
assert.match(cyberStyles, /#left-panel-stack:has/);
assert.match(
cyberStyles,
/inset-inline-start: calc\(54px \+ var\(--panel-rail-clearance\)\);/,
);
assert.match(cyberStyles, /right: calc\(51px \+ var\(--panel-rail-clearance\)\);/);
// Each side's edge line shows only beside an open panel.
assert.match(
cyberStyles,
/#left-panel-stack:has\(> \[data-panel-id\]:not\(\.collapsed, \[hidden\]\)\) \{\s*border-inline-start-color:/,
);
assert.match(
cyberStyles,
/#right-context-rail:has\(> \[data-panel-id\]:not\(\.collapsed, \[hidden\]\)\) \{\s*border-inline-end-color:/,
);
assert.match(cyberStyles, /bottom: calc\(2vh \+ 13rem \+ var\(--world-timeline-lift, 0px\)\);/);
assert.doesNotMatch(cyberStyles, /NAV 01 \/\/ COMMAND BUS \/\/ VIS 03/);
assert.match(cyberStyles, /data-layer-id='satellites'/);
assert.match(cyberStyles, /#search-toggle::before/);
assert.match(cyberStyles, /VISUAL MATRIX \/\/ 03/);
assert.match(cyberStyles, /body\.cockpit-mode #cockpit-hud/);
assert.match(cyberStyles, /TARGET SCANNING \/\/ LIVE VECTOR/);
assert.match(
cyberStyles,
/body\.cockpit-mode #global-loading-status \{[\s\S]*?top: 60px;[\s\S]*?z-index: 146;/,
);
assert.match(
cyberStyles,
/body\.cockpit-mode #global-loading-detail \{[\s\S]*?color: var\(--cockpit-accent\);/,
);
assert.match(cyberStyles, /body\.cockpit-mode \.cockpit-visor-shell::before/);
assert.match(cyberStyles, /body\.cockpit-mode \.cockpit-scan-array/);
assert.match(cyberStyles, /body\.cockpit-mode \.cockpit-target-side-arcs/);
assert.match(cyberStyles, /body\.cockpit-mode \.cockpit-target-ticks/);
assert.match(cyberStyles, /body\.cockpit-mode \.cockpit-target-core/);
assert.match(cyberStyles, /width: min\(48vw, 60vh\);/);
assert.match(cyberStyles, /body\.cockpit-mode \.cockpit-context-window/);
assert.match(cyberStyles, /body\.cockpit-mode \.cockpit-signal-window/);
assert.match(cyberStyles, /body\.cockpit-mode #intel-hud\.active/);
});
test('Cyber voice telemetry renders a live scan scope without replacing audio ownership', () => {
assert.match(
cyberStyles,
/#gev-voice-control\s*\{[\s\S]*?--cyber-voice-wave:/,
);
assert.match(cyberStyles, /\.gev-voice-visualizer::before/);
assert.match(cyberStyles, /\.gev-voice-visualizer::after/);
assert.match(cyberStyles, /@keyframes gev-cyber-voice-scan/);
assert.match(cyberStyles, /@keyframes gev-cyber-voice-lock/);
assert.match(cyberStyles, /\[data-speaker='user'\]/);
assert.match(cyberStyles, /\[data-speaker='ai'\]/);
assert.match(
cyberStyles,
/prefers-reduced-motion: reduce[\s\S]*?gev-voice-visualizer::after[\s\S]*?animation: none/,
);
});
test('Cyber Cockpit Display uses the released briefing lane instead of the legacy viewport cap', () => {
assert.match(
cyberStyles,
/body\.cockpit-mode\s+#cockpit-display-panel\s*\{[\s\S]*?max-height:\s*calc\(var\(--cockpit-utility-expanded-max-height, 72vh\) - 62px\)/,
);
assert.match(
cyberStyles,
/#cockpit-hud:has\(\.cockpit-utility-control\.is-expanded\)[\s\S]*?\.cockpit-signal-window\[data-collapsed='true'\][\s\S]*?bottom: 80px;[\s\S]*?visibility:\s*visible/,
);
});
test('Cyber Cockpit keeps Data Layers inside its bounded rail', () => {
assert.match(
cyberStyles,
/body:not\(\.cockpit-mode\)\s+#left-panel-stack:has\([\s\S]*?max-height:\s*none;/,
);
assert.match(
cyberStyles,
/body\.cockpit-mode\s+#left-panel-stack\s+> :is\(#data-panel, #utilities-panel\) \{[\s\S]*?max-height: min\(64vh, 610px\);/,
);
});
test('Cyber desktop cockpit collapsed utility frames match the 50px Data Layers frame', () => {
const desktop = cyberStyles.slice(
cyberStyles.indexOf('@media (min-width: 961px) and (min-height: 650px)'),
cyberStyles.indexOf('@media (max-width: 720px)'),
);
assert.match(
desktop,
/:root\[data-ui-theme='cyber'\]\s+body\.cockpit-mode\s+\.cockpit-utility-control:not\(\.is-expanded\)\s+\.cockpit-utility-launcher\s*\{\s*height: 50px;\s*min-height: 50px;\s*padding: 9px 18px 9px 24px;/,
);
assert.match(
desktop,
/\.cockpit-utility-control:not\(\.is-expanded\)\s+\.cockpit-utility-launcher::after\s*\{\s*bottom: 6px;/,
);
});
test('Cyber right panels preserve intrinsic sizing and the shared rail allocation', () => {
assert.doesNotMatch(
cyberStyles.slice(cyberStyles.indexOf(":root[data-ui-theme='cyber'] {")),
/#right-context-rail\s*>[^{}]+\{[^{}]*\b(?:flex|height|max-height):/,
);
});
test('Cyber panels retain clean edges without the added footer band', () => {
assert.doesNotMatch(cyberStyles, /--cyber-panel-foot-/);
assert.doesNotMatch(cyberStyles, /border-bottom: 24px solid transparent/);
});
test('Cyber keeps Sonar on/off without the removed CSS effect switch or dimmer', () => {
const template = readFileSync(
new URL('./views/panels/DisplayPanel.vue', import.meta.url),
'utf8',
);
assert.match(template, /id="cyber-sonar-toggle"/);
assert.doesNotMatch(template, /data-sonar-mode|cyber-sonar-mode-row/);
assert.doesNotMatch(cyberStyles, /cyber-scene-dimmer|data-cyber-sonar-mode/);
});
test('Cyber Display uses a red title without a panel-specific center tab', () => {
assert.match(
cyberStyles,
/#pp-toggles \.pp-header-label\s*\{\s*color: var\(--cyber-red-bright\);/,
);
assert.doesNotMatch(cyberStyles, /#pp-toggles[^,{]*::after\s*\{/);
assert.match(cyberStyles, /isolation: isolate;\s*clip-path: none;/);
assert.match(cyberStyles, /#pp-toggles:not\(\.collapsed\)::before/);
});
test('Cyber omits only the fictional classification and system header lines', () => {
assert.match(
cyberStyles,
/#intel-hud\[data-variant='cyber'\] \.hud-top-left \.hud-classification,\s*#intel-hud\[data-variant='cyber'\] \.hud-top-left \.hud-system\s*\{\s*display: none;\s*\}/,
);
});
+35 -6
View File
@@ -54,7 +54,7 @@ export class DisplayBindings {
documentRef: document,
searchInput: this._locationSearch,
actions: {
setStyle: (style) => this.setStyle(style, { userInitiated: true }),
setStyle: (style) => this.setStyle(style),
dismissSearch: () => this._closeLocationSearch?.({ ifOpen: true }),
toggleHud: () => {
this.shareLinkManager?.claimRestoreLane?.('visual');
@@ -64,8 +64,8 @@ export class DisplayBindings {
},
toggleOrbit: () => this._toggleOrbit(),
toggleCleanView: () => this.toggleCleanView(),
toggleLayers: () =>
document.getElementById('data-panel').classList.toggle('active'),
// Same collapse as the panel's own button, so its rail entry stays.
toggleLayers: () => this._togglePanel('data-panel'),
cycleDetection: () => {
this.shareLinkManager?.claimRestoreLane?.('visual');
this.claimDetection();
@@ -82,7 +82,7 @@ export class DisplayBindings {
this._detachDisplayControls?.();
const store = this.displayStore ?? useDisplayStore(applicationPinia());
const token = store.connect({
setStyle: (style) => this.setStyle(style, { userInitiated: true }),
setStyle: (style) => this.setStyle(style),
toggleBloom: () => {
this.shareLinkManager?.claimRestoreLane?.('visual');
this._setBloomEnabled(!this.bloomEnabled);
@@ -105,13 +105,18 @@ 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);
},
setHudLayout: (value) => {
this.shareLinkManager?.claimRestoreLane?.('visual');
this._setHudVariant(value, { applyVisualDefaults: true });
this._setHudVariant(value);
},
toggleCleanView: () => this.toggleCleanView(),
exitCleanView: () => this.toggleCleanView(false),
@@ -150,7 +155,10 @@ export class DisplayBindings {
this._updateHudButtonState();
this._syncShareState();
},
toggleSonar: () => this._setCyberSonarEnabled(),
toggleSonar: () => {
this.shareLinkManager?.claimRestoreLane?.('visual');
this._setCyberSonarEnabled();
},
setSonarRings: (value) => this._setCyberSonarSetting('rings', value),
setSonarRange: (value) => this._setCyberSonarSetting('range', value),
setSonarIntensity: (value) =>
@@ -168,6 +176,27 @@ 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');
// The HUD layout and the Sonar style stay as the viewer set them.
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, []);
});
+176 -14
View File
@@ -72,7 +72,11 @@ function settings(store) {
test('before VisualSettings renders, the panel shows its initial markup', (t) => {
const { $ } = fixture(t);
assert.equal($('bloom-toggle').className, 'pp-toggle-btn');
// Beside the kit's ui-* classes, the toggle carries only its own.
assert.deepEqual(
[...$('bloom-toggle').classList].filter((name) => !name.startsWith('ui-')),
['pp-toggle-btn'],
);
assert.equal($('bloom-slider-row').className, 'pp-slider-row');
assert.equal($('bloom-intensity-slider').value, '0');
assert.equal($('bloom-intensity-value').textContent, '0%');
@@ -108,7 +112,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) => {
@@ -234,20 +242,29 @@ test('the HUD and Sonar controls render what VisualSettings shows', async (t) =>
getVariant: () => variant,
});
owner._scheduleAdaptivePanelLayout = () => {};
assert.equal($('cyber-sonar-toggle').textContent, 'ON');
assert.equal($('cyber-sonar-toggle').getAttribute('aria-pressed'), 'true');
// Sonar is opt-in: OFF until the viewer turns it on.
assert.equal($('cyber-sonar-toggle').textContent, 'OFF');
assert.equal($('cyber-sonar-toggle').getAttribute('aria-pressed'), 'false');
assert.equal(
[...$('hud-layout-select').options].map((option) => option.value).join(),
'tactical,minimal',
);
owner._syncHudControls();
await nextTick();
assert.equal($('hud-toggle').classList.contains('active'), true);
assert.equal($('hud-layout-row').classList.contains('visible'), true);
assert.equal($('hud-layout-select').value, 'minimal');
// The toggle shows with the HUD; its sliders wait for Sonar ON.
assert.equal($('cyber-sonar-row').classList.contains('visible'), true);
assert.equal($('cyber-sonar-rings-row').classList.contains('visible'), false);
visible = false;
owner._updateHudButtonState();
await nextTick();
assert.equal($('hud-toggle').classList.contains('active'), false);
assert.equal($('hud-layout-row').classList.contains('visible'), false);
assert.equal($('cyber-sonar-row').classList.contains('visible'), false);
owner._sonarShown = {
enabled: false,
@@ -268,6 +285,19 @@ test('the HUD and Sonar controls render what VisualSettings shows', async (t) =>
assert.equal($('cyber-sonar-range-value').textContent, '90%');
assert.equal($('cyber-sonar-sector').value, '30');
assert.equal($('cyber-sonar-sector-value').textContent, '30°');
visible = true;
owner._updateHudButtonState();
owner._sonarShown = { ...owner._sonarShown, enabled: true };
owner._publishDisplay();
await nextTick();
assert.equal(toggle.textContent, 'ON');
for (const name of ['rings', 'range', 'intensity', 'opacity', 'sector'])
assert.equal(
$(`cyber-sonar-${name}-row`).classList.contains('visible'),
true,
name,
);
});
test('Scope and Celestial render what VisualSettings shows', async (t) => {
@@ -314,6 +344,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 +428,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 +447,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 +479,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 +520,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 +585,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 +704,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 +720,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 +828,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', undefined],
['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);
});
-6
View File
@@ -1,6 +0,0 @@
/** Cyber keeps the frame fixed; other layouts retain their existing scroller. */
export function displayPanelScroller(panel) {
return panel?.ownerDocument?.documentElement?.dataset.uiTheme === 'cyber'
? panel.querySelector('.pp-panel-body') || panel
: panel;
}
+367
View File
@@ -0,0 +1,367 @@
import { resolvePickedContext } from '../data/pickedContext.js';
import { clickCard } from '../data/pickRegistry.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.
* @returns {() => void} disconnects
*/
export function installEntityContext({
viewer,
getDataManager,
pinia,
pickWorld,
regionalBrief,
}) {
const store = useEntityCardStore(pinia);
const omnibar = useOmnibarStore(pinia);
const voice = useVoiceStore(pinia);
const cockpitStore = useCockpitStore(pinia);
const chrome = usePanelChromeStore(pinia);
/** Whether Context is open. (readView also reads while the Omnibar is focused.) */
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() && doc?.activeElement?.id !== 'gev-omnibar-input'))
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);
// The Omnibar's nearby suggestions also need a fresh center even with
// Context closed. Its focus event requests one camera read.
const onSearchFocus = (event) => {
if (event.target?.id === 'gev-omnibar-input') readView();
};
doc?.addEventListener('focusin', onSearchFocus);
// 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;
// A card or label painted on top is its layer's click, read once per
// click so every layer agrees: Context names nothing under it and keeps
// its own card as it is.
if (clickCard(event)) 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.
if (event.surface && isTrackingClickGesture(event.gesture)) 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();
doc?.removeEventListener('focusin', onSearchFocus);
clearTimeout(followCheck);
globalThis.removeEventListener?.('gev:entity-selected', onSelected);
store.connect(null);
};
}
+85
View File
@@ -0,0 +1,85 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createPinia } from 'pinia';
import { installEntityContext } from './entityContextBridge.js';
import { useEntityCardStore } from './stores/entityCard.js';
import { fakeInput } from '../input/testDoubles.mjs';
import {
registerPickOwner,
setClickCardHitTest,
unregisterPickOwner,
} from '../data/pickRegistry.js';
// The card or label painted on top takes the click: Context names nothing
// under it, exact or nearby, an acting owner's item or a passive one, and
// keeps its own card. On open map it names what the click found.
test('Context names nothing under a card painted on top, and keeps its card', (t) => {
const previous = globalThis.matchMedia;
globalThis.matchMedia = () => ({ matches: true });
t.after(() => {
if (previous) globalThis.matchMedia = previous;
else delete globalThis.matchMedia;
});
const fire = { set: 'test-fires:1', id: 'fire:1' };
const plane = { set: 'test-planes:1', id: 'plane:1' };
const route = { set: 'test-route:1', id: 'route:line' };
registerPickOwner('test-fires', (id) => id === fire.id);
registerPickOwner('test-planes', (id) => id === plane.id);
registerPickOwner('test-route', (id) => id.startsWith('route:'));
let cardOnTop = false;
// The card on top at a click, as the host answers the pick registry.
setClickCardHitTest(() =>
cardOnTop ? { sourceId: 'earthquake-card', entryId: 'q' } : null,
);
t.after(() => {
setClickCardHitTest(null);
unregisterPickOwner('test-fires');
unregisterPickOwner('test-planes');
unregisterPickOwner('test-route');
});
let exact = null;
let near = null;
const viewer = {
scene: {
pick: () => (exact ? { id: exact } : null),
drillPick: () => (near ? [{ id: near }] : []),
},
};
const input = fakeInput(viewer);
const pinia = createPinia();
const disconnect = installEntityContext({
viewer,
getDataManager: () => ({
isEnabled: () => true,
layers: new Map(),
getAll: () => [],
}),
pinia,
});
t.after(() => {
disconnect();
input.destroy();
});
const store = useEntityCardStore(pinia);
const named = [];
let clears = 0;
store.select = (identity) => named.push(identity.id);
store.clear = () => clears++;
const tap = (hitExact, hitNear) => {
exact = hitExact;
near = hitNear;
named.length = 0;
input.click();
return [...named];
};
assert.deepEqual(tap(null, fire), ['fire:1'], 'open map: a near fire');
assert.deepEqual(tap(route, null), ['route:line'], 'open map: a route');
cardOnTop = true;
assert.deepEqual(tap(null, fire), [], 'under a card: a near fire');
assert.deepEqual(tap(fire, fire), [], 'under a card: an exact fire');
assert.deepEqual(tap(plane, plane), [], 'under a card: an aircraft');
assert.deepEqual(tap(route, null), [], 'under a card: a route');
const cleared = clears;
tap(null, null);
assert.equal(clears, cleared, 'a card over open map is not open map');
});
+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,
+787
View File
@@ -0,0 +1,787 @@
import {
getScopeMaskFeather,
getScopeMaskOpacity,
isScopeMaskEnabled,
setScopeMaskEnabled,
setScopeMaskFeather,
setScopeMaskOpacity,
} from '../scopeMask.js';
import assert from 'node:assert/strict';
import { readdirSync, readFileSync } from 'node:fs';
import test from 'node:test';
import {
HUD_LAYOUTS,
isLegacySonarHudLayout,
LEGACY_SONAR_HUD_LAYOUTS,
normalizeHudLayout,
} from '../hudLayouts.js';
import {
isCyberMapThemeActive,
isCyberSonarActive,
isCyberSonarEnabled,
setCyberSonarEnabled,
} from '../cyberSonar.js';
import { GEV_ACTION_SCHEMAS } from '../voice/actionSchemas.js';
import { createGevActionRunner } from '../voice/gevActions.js';
import { StyleManager } from './applicationShell.js';
import { setCyberSonarControls } from './cyberSonarControls.js';
import { createPinia } from 'pinia';
import { useDisplayStore } from './stores/display.js';
import { VisualSettings } from './visualSettings.js';
import { normalizeShot } from '../scenes/project.js';
import {
SCENE_DOCUMENT_VERSION,
validateSceneDocument,
} from '../director/document.js';
import { decodeShareView, encodeShareView } from '../share/viewCodec.js';
import { toLegacyShareState } from '../share/legacyShareState.js';
import { STYLES } from './visualPresets.js';
const read = (relative) =>
readFileSync(new URL(relative, import.meta.url), 'utf8');
function cssRuleBody(styles, selector) {
const match = styles.match(new RegExp(`${selector.source}\\s*\\{([^}]+)\\}`));
assert.ok(match, `Missing CSS rule: ${selector.source}`);
return match[1];
}
function styleOwner(t, initialVariant = 'tactical') {
const previous = { document: globalThis.document, window: globalThis.window };
const root = { dataset: {} };
globalThis.document = { documentElement: root, querySelectorAll: () => [] };
globalThis.window = { dispatchEvent() {} };
t.after(() => Object.assign(globalThis, previous));
let variant = initialVariant;
const calls = [];
const hud = {
getVariant: () => variant,
// Normalize like the real HUD so removed layouts fall back.
setVariant: (value) => (variant = normalizeHudLayout(value)),
setMode: (value) => calls.push(['mode', value]),
onStyleChange: (value) => calls.push(['style', value]),
visible: true,
};
hud.setVariant(initialVariant);
const owner = Object.create(VisualSettings.prototype);
Object.assign(owner, {
activeStyle: 'normal',
store: { publish() {} },
readHud: () => hud,
readShareLinks: () => ({ onStyleChange() {} }),
_visualEffects: {
stages: Object.fromEntries(
Object.entries(STYLES).map(([name, config]) => [
name,
{ uniforms: { ...config.uniforms, intensity: 0 } },
]),
),
},
services: {
governorRequestRender: (reason) => calls.push(['render', reason]),
setDetectionStyle() {},
},
_setBloomEnabled: (value) => calls.push(['bloom', value]),
_setSharpenEnabled: (value) => calls.push(['sharpen', value]),
_applyDetectionPreset: (value) => calls.push(['detection', value]),
_syncShareState: () => calls.push(['share', variant]),
});
for (const name of [
'setCelestialRingEnabled',
'_startTransition',
'_publishActiveStyle',
'_updateSliderPanel',
'_updateHudButtonState',
'_syncIrBoost',
'_syncCockpitInheritedStyle',
'_syncCyberSonarControl',
'_scheduleAdaptivePanelLayout',
'_setDetectionFade',
// Intensities: the fixture has no post-process stages to drive.
'_setBloomIntensity',
'_setSharpenIntensity',
])
owner[name] = () => {};
return { owner, hud, root, calls };
}
test('Tactical and Minimal are the HUD layouts; Cyber is only a Sonar alias', () => {
assert.deepEqual(HUD_LAYOUTS, ['tactical', 'minimal']);
assert.deepEqual(LEGACY_SONAR_HUD_LAYOUTS, ['cyber']);
assert.equal(normalizeHudLayout('cyber'), 'tactical');
assert.equal(normalizeHudLayout('CYBER'), 'tactical');
assert.equal(normalizeHudLayout('operator'), 'tactical');
assert.equal(normalizeHudLayout('Minimal'), 'minimal');
assert.equal(isLegacySonarHudLayout('Cyber'), true);
assert.equal(isLegacySonarHudLayout('operator'), false);
assert.equal(isLegacySonarHudLayout('tactical'), false);
});
test('a share link, scene or saved view naming Cyber opens Tactical with Sonar on', async (t) => {
const { owner, hud, root, calls } = styleOwner(t, 'minimal');
assert.equal(isCyberSonarEnabled(root), false);
await owner.restoreShareState({ hudVariant: 'cyber' });
assert.equal(hud.getVariant(), 'tactical');
assert.equal(root.dataset.cyberSonar, 'on');
assert.equal(root.dataset.uiTheme, undefined);
// Turning it on asks for a frame, so a parked map starts the sweep.
assert.ok(
calls.some(
([name, reason]) => name === 'render' && reason === 'cyber-sonar-toggle',
),
);
// The viewer's own layout choice afterwards leaves the Sonar style alone.
owner._setHudVariant('minimal');
assert.equal(hud.getVariant(), 'minimal');
assert.equal(isCyberSonarEnabled(root), true);
// A restored state is authoritative: one that does not name Cyber turns
// Sonar off, whether from a link or a scene shot.
await owner.restoreShareState({ hudVariant: 'tactical' });
assert.equal(isCyberSonarEnabled(root), false);
setCyberSonarEnabled(true, root);
await owner.applyVisualState({ hud: { variant: 'minimal' } });
assert.equal(hud.getVariant(), 'minimal');
assert.equal(isCyberSonarEnabled(root), false);
await owner.applyVisualState({ hud: { variant: 'cyber' } });
assert.equal(hud.getVariant(), 'tactical');
assert.equal(isCyberSonarEnabled(root), true);
});
/** A styleOwner that can also read its share state and scene shot. */
function sharingOwner(t, initialVariant) {
const fixture = styleOwner(t, initialVariant);
Object.assign(fixture.owner.services, {
getDetectionTuning: () => ({ allocationStrategy: 'ELASTIC' }),
getDetectionMode: () => 'OFF',
isScopeMaskEnabled: () => true,
getScopeMaskFeather: () => 1,
getScopeMaskOpacity: () => 1,
getScopeTerminusOverride: () => null,
});
fixture.owner.readCelestialRing = () => null;
return fixture;
}
test('links and scene shots record Tactical with Sonar as the Cyber code, and only that', (t) => {
const { owner, root } = sharingOwner(t, 'tactical');
const shared = () => {
const { hudVariant, hudSonar } = owner._readShareState().options;
return [hudVariant, hudSonar];
};
const shot = () => owner.getVisualState().hud;
assert.deepEqual(shared(), ['tactical', false]);
assert.deepEqual(shot(), { visible: true, variant: 'tactical' });
owner._setCyberSonarEnabled(true);
// Tactical with Sonar is the Cyber code alone, as older readers expect.
assert.deepEqual(shared(), ['cyber', false]);
assert.deepEqual(shot(), { visible: true, variant: 'cyber' });
// Minimal has no such code, so Sonar is carried beside it.
owner._setHudVariant('minimal');
assert.deepEqual(shared(), ['minimal', true]);
assert.deepEqual(shot(), { visible: true, variant: 'minimal', sonar: true });
owner._setCyberSonarEnabled(false);
assert.deepEqual(shared(), ['minimal', false]);
assert.deepEqual(shot(), { visible: true, variant: 'minimal' });
owner._setHudVariant('tactical');
assert.deepEqual(shared(), ['tactical', false]);
assert.equal(isCyberSonarEnabled(root), false);
});
test('Minimal with Sonar round-trips through a compact link and a scene shot', async (t) => {
const { owner, hud, root } = sharingOwner(t, 'minimal');
owner._setCyberSonarEnabled(true);
const options = owner._readShareState().options;
const shot = normalizeShot(
JSON.parse(JSON.stringify({ visual: owner.getVisualState() })),
);
validateSceneDocument({
version: SCENE_DOCUMENT_VERSION,
scenes: [{ id: 'scene', title: 'Scene', shots: [shot] }],
});
const code = encodeShareView({
hudVariant: options.hudVariant,
hudSonar: options.hudSonar,
});
const link = decodeShareView(code, { nowMs: Date.now() }).state;
// The viewer is elsewhere: Tactical, Sonar off.
owner._setHudVariant('tactical');
owner._setCyberSonarEnabled(false);
// The HUD fields of the parsed link (the fixture drives no detection).
const { hudVariant, hudSonar } = toLegacyShareState(link);
assert.deepEqual([hudVariant, hudSonar], ['minimal', true]);
await owner.restoreShareState({ hudVariant, hudSonar });
assert.equal(hud.getVariant(), 'minimal');
assert.equal(isCyberSonarEnabled(root), true);
owner._setHudVariant('tactical');
owner._setCyberSonarEnabled(false);
// The saved shot's HUD, as the editor normalized and validated it.
assert.deepEqual(shot.visual.hud, {
visible: true,
variant: 'minimal',
sonar: true,
});
await owner.applyVisualState({ hud: shot.visual.hud });
assert.equal(hud.getVariant(), 'minimal');
assert.equal(isCyberSonarEnabled(root), true);
});
test('a link or scene shot that does not mention Sonar restores as before', async (t) => {
const { owner, hud, root } = sharingOwner(t, 'minimal');
// Made before Sonar was carried: Minimal turns the viewer's Sonar off...
setCyberSonarEnabled(true, root);
await owner.restoreShareState({ hudVariant: 'minimal' });
assert.equal(isCyberSonarEnabled(root), false);
setCyberSonarEnabled(true, root);
await owner.applyVisualState({ hud: { variant: 'minimal' } });
assert.equal(isCyberSonarEnabled(root), false);
// ...and Cyber still opens Tactical with Sonar on.
await owner.restoreShareState({ hudVariant: 'cyber', hudSonar: false });
assert.equal(hud.getVariant(), 'tactical');
assert.equal(isCyberSonarEnabled(root), true);
owner._setCyberSonarEnabled(false);
await owner.applyVisualState({ hud: { variant: 'cyber' } });
assert.equal(isCyberSonarEnabled(root), true);
// Sonar beside a layout counts only in a restore, not a layout choice.
owner._setCyberSonarEnabled(false);
owner._setHudVariant('minimal', { sonar: true });
assert.equal(isCyberSonarEnabled(root), false);
});
test('Sonar is opt-in and gated on its toggle, the HUD, Cockpit and motion, not a theme', () => {
const classes = new Set();
const root = { dataset: {} };
const body = { classList: { contains: (name) => classes.has(name) } };
const gate = (extra = {}) => ({
root,
body,
hudActive: true,
reducedMotion: false,
...extra,
});
assert.equal(isCyberSonarEnabled(root), false);
assert.equal(isCyberSonarActive(gate()), false);
assert.equal(isCyberMapThemeActive(gate()), false);
// The removed Cyber theme attribute no longer enables anything.
root.dataset.uiTheme = 'cyber';
assert.equal(isCyberSonarActive(gate()), false);
delete root.dataset.uiTheme;
assert.equal(setCyberSonarEnabled(true, root), true);
assert.equal(root.dataset.cyberSonar, 'on');
assert.equal(isCyberSonarActive(gate()), true);
assert.equal(isCyberMapThemeActive(gate()), true);
assert.equal(isCyberSonarActive(gate({ hudActive: false })), false);
assert.equal(isCyberMapThemeActive(gate({ hudActive: false })), false);
// Reduced motion keeps the static treatment and stops the sweep.
assert.equal(isCyberSonarActive(gate({ reducedMotion: true })), false);
assert.equal(isCyberMapThemeActive(gate({ reducedMotion: true })), true);
classes.add('cockpit-mode');
assert.equal(isCyberSonarActive(gate()), false);
assert.equal(isCyberMapThemeActive(gate()), false);
classes.delete('cockpit-mode');
assert.equal(setCyberSonarEnabled(false, root), false);
assert.equal(root.dataset.cyberSonar, 'off');
assert.equal(isCyberSonarActive(gate()), false);
assert.equal(isCyberMapThemeActive(gate()), false);
});
test('Sonar controls apply under Tactical and Minimal and still validate input', () => {
for (const layout of ['tactical', 'minimal']) {
const root = { dataset: {} };
const doc = {
documentElement: root,
body: { classList: { contains: () => false } },
getElementById: () => null,
};
const calls = [];
const owner = {
hud: { getVariant: () => layout, visible: true },
_setCyberSonarSetting: (name, value) => calls.push([name, value]),
_setCyberSonarEnabled: (value) => {
calls.push(['enabled', value]);
setCyberSonarEnabled(value, root);
},
};
const applied = setCyberSonarControls(
owner,
{ enabled: true, rings: 6, sectorDeg: 30 },
doc,
);
assert.equal(applied.ok, true, layout);
assert.equal(applied.sonar.enabled, true);
assert.equal('cyberSelected' in applied.sonar, false);
assert.deepEqual(calls, [
['rings', 6],
['sector', 30],
['enabled', true],
]);
assert.equal(
setCyberSonarControls(owner, { enabled: 'yes' }, doc).error,
'enabled must be a boolean.',
);
assert.equal(
setCyberSonarControls(owner, { pulse: 3 }, doc).error,
'Unknown sonar setting.',
);
assert.equal(
setCyberSonarControls(owner, { rings: 13 }, doc).error,
'rings must be an integer from 3 to 12.',
);
}
});
test('Display and voice HUD routes offer Tactical and Minimal, and Cyber turns Sonar on', async (t) => {
const makeOwner = () => {
const { owner, hud, root } = styleOwner(t, 'tactical');
owner.setStyle('noir');
owner.setHudLayout = (...args) =>
StyleManager.prototype.setHudLayout.call(owner, ...args);
owner.getControlState = () => ({
hud: { layout: hud.getVariant(), visible: true },
});
return { owner, hud, root };
};
const display = makeOwner();
const store = useDisplayStore(createPinia());
const token = store.connect({
setHudLayout: (value) => display.owner.setHudLayout(value),
setStyle: (value) => display.owner.setStyle(value),
});
store.act('setHudLayout', 'minimal');
assert.equal(display.hud.getVariant(), 'minimal');
// Switching layouts never changes the visual preset.
assert.equal(display.owner.activeStyle, 'noir');
store.act('setStyle', 'anime');
assert.equal(display.owner.activeStyle, 'anime');
store.detach(token);
const setHud = GEV_ACTION_SCHEMAS.find((tool) => tool.name === 'set_hud');
assert.deepEqual(setHud.parameters.properties.layout.enum, HUD_LAYOUTS);
const voice = makeOwner();
const eventSource = { addEventListener() {}, removeEventListener() {} };
const viewer = {
camera: { moveEnd: { addEventListener() {} } },
clock: { onTick: { addEventListener: () => () => {} } },
canvas: eventSource,
scene: { canvas: eventSource },
};
const runVoiceAction = createGevActionRunner({
viewer,
styleManager: voice.owner,
dataManager: {},
});
const minimal = await runVoiceAction('set_hud', { layout: 'minimal' });
assert.equal(minimal.ok, true);
assert.equal(voice.hud.getVariant(), 'minimal');
assert.equal(isCyberSonarEnabled(voice.root), false);
const legacy = await runVoiceAction('set_hud', { layout: 'cyber' });
assert.equal(legacy.ok, true);
assert.equal(legacy.layout, 'tactical');
assert.equal(voice.hud.getVariant(), 'tactical');
assert.equal(isCyberSonarEnabled(voice.root), true);
assert.equal(voice.owner.activeStyle, 'noir');
const unknown = await runVoiceAction('set_hud', { layout: 'operator' });
assert.equal(unknown.ok, false);
});
test('style presets keep their own HUD layout and never touch Sonar', (t) => {
const { owner, hud, root } = styleOwner(t);
setCyberSonarEnabled(true, root);
for (const variant of ['tactical', 'minimal']) {
owner._setHudVariant(variant);
assert.equal(hud.getVariant(), variant);
owner.setStyle('normal');
owner.setStyle('surveillance');
assert.equal(hud.getVariant(), 'tactical');
assert.equal(isCyberSonarEnabled(root), true);
}
});
test('the Display panel offers Sonar as an opt-in toggle under the HUD layout', () => {
const view = read('./views/panels/DisplayPanel.vue');
assert.doesNotMatch(view, /value="cyber"/);
assert.match(view, /<option value="tactical">/);
assert.match(view, /<option value="minimal">/);
assert.match(
view,
/const sonarOn = computed\(\(\) => sonar\.value\?\.enabled \?\? false\);/,
);
// The toggle shows with the HUD; its sliders only once Sonar is on.
assert.match(
view,
/cyber-sonar-toggle-row" :class="\{ visible: hud\?\.visible \}" id="cyber-sonar-row"/,
);
assert.equal(
view.match(
/cyber-sonar-setting" :class="\{ visible: hud\?\.visible && sonarOn \}"/g,
)?.length,
5,
);
assert.match(view, /:aria-label="t\('Sonar contact scanner'\)"/);
// Its renderer status speaks only for a Sonar the viewer turned on.
assert.match(
view,
/<output id="cyber-sonar-status"[^>]*:hidden="!\(hud\?\.visible && sonarOn\)"/,
);
assert.doesNotMatch(view, /t\('Cyber/);
});
test('stylesheets carry no Cyber theme and show the sweep only while Sonar is on', () => {
const entry = readFileSync(
new URL('../../style.css', import.meta.url),
'utf8',
);
assert.match(entry, /@import '\.\/src\/ui\/styles\/sonar\.css';/);
assert.doesNotMatch(entry, /cyber\.css/);
const dir = new URL('./styles/', import.meta.url);
for (const name of readdirSync(dir).filter((file) => file.endsWith('.css')))
assert.doesNotMatch(
readFileSync(new URL(name, dir), 'utf8'),
/data-ui-theme/,
name,
);
const sonar = read('./styles/sonar.css');
assert.match(cssRuleBody(sonar, /\n\.hud-sonar/), /display: none;/);
assert.match(
cssRuleBody(
sonar,
/\n:root\[data-cyber-sonar='on'\] #intel-hud \.hud-sonar/,
),
/display: block;/,
);
// Cockpit and a hidden HUD keep no sweep, not even an invisible one.
assert.match(
cssRuleBody(
sonar,
/:root\[data-cyber-sonar='on'\] body\.cockpit-mode #intel-hud \.hud-sonar,\s*:root\[data-cyber-sonar='on'\] #intel-hud:not\(\.active\) \.hud-sonar/,
),
/display: none;/,
);
assert.match(
sonar,
/@media \(prefers-reduced-motion: reduce\)\s*\{\s*:root\[data-cyber-sonar='on'\] #intel-hud \.hud-sonar::after\s*\{\s*display: none;\s*animation: none;/,
);
// The Vue bindings own the Sonar rows' visibility now.
const controls = read('./styles/controls.css');
assert.doesNotMatch(controls, /\.cyber-sonar-control\s*\{\s*display: none/);
assert.doesNotMatch(controls, /data-cyber-sonar='off'/);
});
test('the desktop bottom row: credits on the Power Up baseline, the dock lifted, the corners level', () => {
const rem = 16;
const lift = 'var\\(--world-timeline-lift, 0px\\)';
const value = (text, pattern) => {
const match = text.match(pattern);
assert.ok(match, pattern.source);
return Number(match[1]);
};
const block = (text, header) => {
const start = text.indexOf(header);
assert.ok(start >= 0, header);
let depth = 0;
for (let i = text.indexOf('{', start); i < text.length; i += 1) {
if (text[i] === '{') depth += 1;
else if (text[i] === '}' && --depth === 0)
return text.slice(start, i + 1);
}
assert.fail(`unclosed ${header}`);
};
// Measured constants: the Power Up / language row is 32px tall, 14px up
// and about 20rem wide in English; the attribution logo line is 28px; the
// single-row dock is 62px; the bottom-right readout is one 26px line
// taller than the coordinates.
const POWER_UP = { bottom: 14, height: 32 };
const CREDIT_HEIGHT = 28;
const DOCK_HEIGHT = 62;
const timeline = read('./styles/world-timeline.css');
const timelineLift = value(
timeline,
/body:has\(#world-timeline\) \{\s*--world-timeline-lift: (\d+)px;/,
);
// From 1200px the dock and the World Timeline leave the bottom 74px; below
// it they return to the bottom edge, where the dock spans the corners.
const dock = read('./styles/command-dock.css');
const dockFloor = value(
dock,
new RegExp(
`\\n#command-dock \\{[^}]*bottom: calc\\((\\d+)px \\+ ${lift}\\)`,
),
);
assert.match(
block(dock, '@media (max-width: 1199px)'),
new RegExp(`#command-dock \\{\\s*bottom: calc\\(2vh \\+ ${lift}\\);`),
);
assert.equal(
value(timeline, /\n#world-timeline \{[^}]*bottom: (\d+)px;/),
dockFloor,
);
assert.match(
block(timeline, '@media (max-width: 1199px)'),
/#world-timeline \{\s*bottom: 2vh;/,
);
assert.ok(dockFloor >= POWER_UP.bottom + POWER_UP.height + 8);
// Both credit renderers share Power Up's row, centred on it, below the
// dock, and stop short of the corner row instead of running under it:
// GEV's own line on its anchor, Cesium's on the absolutely placed box it
// draws inside its empty anchor.
const trays = read('./styles/command-dock-trays.css');
const trayWide = block(trays, '@media (min-width: 1200px)');
const caps = {
'gev-credits': trays.match(
/#gev-credits \{\s*right: auto;\s*bottom: ([\d.]+)rem;\s*left: 1\.5rem;\s*width: max-content !important;\s*max-width: calc\(100vw - 1\.5rem - ([\d.]+)rem\);\s*white-space: normal;/,
),
'cesium-credits': (() => {
const anchor = trays.match(
/#cesium-credits \{\s*right: auto;\s*bottom: ([\d.]+)rem;\s*left: 1\.5rem;/,
);
// From 1200px, and in the Omnibar layout at every width: a long line
// wraps rather than running under the corner row.
const box = trayWide.match(
/\n\s*#cesium-credits \.cesium-widget-credits \{\s*width: max-content;\s*max-width: calc\(100vw - 1\.5rem - ([\d.]+)rem\);\s*white-space: normal;/,
);
assert.match(
trays,
/:has\(#command-dock > #gev-voice-control\)\s*\)\s*#cesium-credits\s*\.cesium-widget-credits \{\s*width: max-content;\s*max-width: calc\(100vw - 1\.5rem - 26rem\);/,
);
return anchor && box && [null, anchor[1], box[1]];
})(),
};
for (const [id, match] of Object.entries(caps)) {
assert.ok(match, id);
const creditsBottom = Number(match[1]) * rem;
assert.equal(
creditsBottom + CREDIT_HEIGHT / 2,
POWER_UP.bottom + POWER_UP.height / 2,
);
assert.ok(creditsBottom + CREDIT_HEIGHT + 8 <= dockFloor);
assert.ok(Number(match[2]) >= 20 + 1.5, `${id} leaves the corner row room`);
}
// Below 1200px the row returns above the bottom-edge dock, on one line.
const narrow = block(trays, '@media (max-width: 1199px)');
for (const id of ['cesium-credits', 'gev-credits'])
assert.match(narrow, new RegExp(`#${id}[,\\s]`));
assert.match(
narrow,
new RegExp(
`\\{\\s*bottom: calc\\(2vh \\+ 5rem \\+ ${lift}\\);\\s*width: auto !important;\\s*max-width: calc\\(100vw - 3rem\\);\\s*white-space: nowrap;`,
),
);
// Right to left the corner row is at the bottom left, so the row moves
// right, with the Minimal HUD too (its placement names #intel-hud).
assert.match(
trayWide,
/html\[dir='rtl'\]\s*body:not\(\.context-docked\):not\(\.ui-clean-view\):not\(\.recording-mode\)\s*:is\(#cesium-credits, #gev-credits\),\s*html\[dir='rtl'\]\s*body:not\(\.context-docked\):not\(\.ui-clean-view\):not\(\.recording-mode\):has\(\s*#intel-hud\[data-variant='minimal'\]\.active\s*\)\s*:is\(#cesium-credits, #gev-credits\) \{\s*right: 1\.5rem;\s*left: auto;/,
);
// Its box hangs from the anchor's right edge there, and in the Omnibar
// layout at every width; never in clean view or recording, where the
// anchor stays on the left.
assert.match(
trayWide,
/body:not\(\.context-docked\):not\(\.ui-clean-view\):not\(\.recording-mode\)\s*#cesium-credits\s*\.cesium-widget-credits \{\s*right: 0;\s*left: auto;/,
);
assert.match(
trays,
/html\[dir='rtl'\]\s*body:not\(\.mobile-shell\)[^{]*:not\(\.recording-mode\):not\(\.context-docked\)[^{]*#cesium-credits\s*\.cesium-widget-credits \{\s*right: 0;\s*left: auto;/,
);
// There the readout clears the row under it, however many lines it wraps
// onto (--credit-line-height).
assert.match(
read('./styles/omnibar-dock.css'),
/html\[dir='rtl'\] \*\):not\(\.context-docked\)\s*#intel-hud\[data-variant='tactical'\]\s*\.hud-bottom-right \{\s*bottom: max\(3\.375rem, var\(--omnibar-credits-clear\)\);/,
);
const locale = read('./styles/locale-picker.css');
assert.match(locale, /#corner-actions \{[^}]*inset-inline-end: 0\.9rem;/);
// From 1200px the readout keeps 8px above Power Up and the coordinates
// start level with it. The World Timeline sits between the corners, so they
// do not move while it shows.
const split = read('./styles/rail-split.css');
const wide = block(split, '@media (min-width: 1200px)');
const readoutWide =
value(
wide,
/\n #intel-hud\[data-variant='tactical'\] \.hud-bottom-right \{\s*bottom: ([\d.]+)rem;/,
) * rem;
assert.equal(readoutWide, POWER_UP.bottom + POWER_UP.height + 8);
assert.equal(
value(wide, /\.hud-bottom-left \{\s*bottom: calc\(([\d.]+)rem \+ 26px\);/) *
rem,
readoutWide,
);
assert.doesNotMatch(
wide,
/hud-bottom-(left|right) \{[^}]*world-timeline-lift/,
);
// Corners: coordinates ~302px from 36px, readout ~292px to 36px from the
// right edge; the bar keeps 12px from each at every width from 1200px.
const gutter =
value(
wide,
/#world-timeline \{\s*width: min\(820px, calc\(100vw - ([\d.]+)rem\)\);/,
) * rem;
assert.ok(gutter / 2 >= 36 + 302 + 12);
assert.ok(timelineLift > 0);
// Toasts keep 12px above the raised dock.
assert.equal(
value(
wide,
new RegExp(`#toast \\{\\s*bottom: calc\\((\\d+)px \\+ ${lift}\\);`),
),
dockFloor + DOCK_HEIGHT + 12,
);
// The dock's panels lose the dock's rise from their height budgets.
assert.match(
wide,
/\.gev-voice-panel \{[^}]*calc\(100dvh - 12rem - 74px \+ 2vh - var\(--gev-provider-lift, 0px\)\)/,
);
assert.match(
block(read('./styles/ai-chat.css'), '@media (min-width: 1200px)'),
/#gev-chat-panel \{\s*max-height: min\(34rem, calc\(100dvh - 10rem - 74px \+ 2vh\)\);/,
);
// Below 1200px the corners keep the committed layout: the coordinates clear
// the raised credit row's logo line by 6px.
assert.ok(
value(
trays.slice(
trays.indexOf(
'/* The coordinate readout shares the bottom-left corner',
),
),
new RegExp(
`\\.hud-bottom-left \\{\\s*bottom: calc\\(2vh \\+ ([\\d.]+)rem \\+ ${lift}\\);`,
),
) *
rem >=
5 * rem + CREDIT_HEIGHT + 6,
);
// The desktop Omnibar layout outranks these rules; its readout keeps the
// same 8px above Power Up.
const omnibarReadout = value(
read('./styles/omnibar-dock.css'),
/#intel-hud\[data-variant='tactical'\] \.hud-bottom-right \{\s*bottom: ([\d.]+)rem;/,
);
assert.equal(omnibarReadout * rem, POWER_UP.bottom + POWER_UP.height + 8);
});
test('scope choice and expanded feather survive every HUD layout and both restore paths', async (t) => {
const { owner } = styleOwner(t, 'tactical');
const previous = {
enabled: isScopeMaskEnabled(),
feather: getScopeMaskFeather(),
};
t.after(() => {
setScopeMaskEnabled(previous.enabled);
setScopeMaskFeather(previous.feather);
});
Object.assign(owner.services, { setScopeMaskEnabled, setScopeMaskFeather });
let shown = null;
owner.store = { publish: (view) => (shown = view.scope) };
await owner.restoreShareState({ scopeEnabled: false, scopeFeatherPct: 200 });
assert.deepEqual(shown, { enabled: false, featherPct: 200, opacityPct: 100 });
for (const layout of ['minimal', 'cyber', 'tactical']) {
owner._setHudVariant(layout);
assert.equal(isScopeMaskEnabled(), false, layout);
assert.equal(getScopeMaskFeather(), 2, layout);
assert.equal(shown.enabled, false, layout);
}
await owner.applyVisualState({ scope: { enabled: true, featherPct: 175 } });
assert.equal(isScopeMaskEnabled(), true);
assert.equal(getScopeMaskFeather(), 1.75);
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, 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) => {
const { owner } = styleOwner(t, 'tactical');
owner.setStyle('noir');
await owner.applyVisualState({ style: 'snow' });
assert.equal(owner.activeStyle, 'normal');
});
test('shared panel hooks affect only opted-in rail surfaces without overriding disclosure and concealment', () => {
const styles = read('./styles/panel-surfaces.css');
const rail = cssRuleBody(
styles,
/:is\(#left-panel-stack, #right-context-rail\)\s+> \[data-panel-id\]:has\(> \[data-panel-surface\]\)/,
);
assert.match(rail, /pointer-events:\s*auto;/);
assert.doesNotMatch(rail, /(?:display|visibility):/);
assert.doesNotMatch(
styles,
/:is\(#left-panel-stack, #right-context-rail\)\s*> \[data-panel-id\]\s*\{/,
);
assert.match(
styles,
/\[data-panel-surface\]:not\(\[hidden\]\):not\(dialog:not\(\[open\]\)\)\s*\{\s*display: flex;/,
);
assert.match(
styles,
/dialog\[data-panel-surface\]:not\(\[open\]\)\s*\{\s*display: none !important;/,
);
assert.match(
styles,
/body:is\(\.ui-clean-view, \.recording-mode\)[^{]+\{[^}]*visibility: hidden !important;[^}]*pointer-events: none !important;/,
);
});
test('narrow Omnibar corners clear the World Timeline over the dock', () => {
const css = read('./styles/omnibar-dock.css');
const timeline = css.match(
/#world-timeline \{\s*bottom: calc\(var\(--omnibar-dock-bottom\) \+ (\d+)px\);/,
);
const height = read('./styles/world-timeline.css').match(
/#world-timeline \{[^}]*\n {2}height: (\d+)px;/,
);
const corners = css.match(
/&:has\(#world-timeline\) \{\s*--omnibar-coordinates-bottom: max\(\s*calc\(var\(--omnibar-dock-bottom\) \+ (\d+)px \+ (\d+)px \+ (\d+)px\)/,
);
assert.ok(timeline && height && corners);
assert.equal(Number(corners[1]), Number(timeline[1]));
assert.equal(Number(corners[2]), Number(height[1]));
assert.ok(Number(corners[3]) >= 6);
});
+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 = () => {
if (!anchor) return null;
@@ -63,68 +63,11 @@ export function initImageryBoxTool({
};
};
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);
@@ -132,19 +75,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() {
@@ -170,7 +107,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;
@@ -197,45 +134,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');
}
@@ -243,14 +158,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 {
@@ -271,7 +188,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);
},
@@ -281,22 +198,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.
*
+6 -4
View File
@@ -1,8 +1,10 @@
<script setup>
// Core's read-only badge, with a `tone` and the kit's classes. It carries Core's `gev-status-badge` class, and
// callers add its density variants (`gev-status-badge--box`, `--plain`) and
// the feature classes that colour it; the kit classes carry no Core styles
// yet. Not mirrored yet: pulse, busy, the tone glyphs and the clipped title.
// Core's read-only badge, with a `tone` and the kit's classes. `ui-badge`
// wears Core's badge (status-badge.css) beside Core's `gev-status-badge`
// class; callers add its density variants (`gev-status-badge--box`,
// `--plain`) and the feature classes that colour it. The tone classes carry
// no style yet. Not mirrored yet: pulse, busy, the tone glyphs and the
// clipped title.
defineProps({
tone: { type: String, default: 'neutral' },
});
+47
View File
@@ -100,3 +100,50 @@ test('server-rendered markup carries the pressed classes', async () => {
assert.match(html, /<button[^>]*class="[^"]*\bactive\b[^"]*"/);
assert.match(html, /aria-pressed="true"/);
});
const LOOKS = [
'ui-button--action',
'ui-button--primary',
'ui-button--icon',
'ui-button--compact',
];
test('a ghost button, the default, carries no look of the kit’s', () => {
const wrapper = mountButton({}, { class: 'pp-toggle-btn' });
const classes = wrapper.get('button').classes();
assert.ok(classes.includes('ui-button--ghost'));
for (const look of LOOKS) assert.equal(classes.includes(look), false, look);
wrapper.unmount();
});
test('the variant, tone and size render their kit classes', async () => {
const wrapper = mountButton({ variant: 'action', tone: 'danger' });
const button = wrapper.get('button');
assert.ok(button.classes().includes('ui-button--action'));
assert.ok(button.classes().includes('ui-button--danger'));
assert.equal(button.classes().includes('ui-button--compact'), false);
await wrapper.setProps({ size: 'compact' });
assert.ok(button.classes().includes('ui-button--compact'));
for (const variant of ['primary', 'icon']) {
await wrapper.setProps({ variant });
assert.ok(button.classes().includes(`ui-button--${variant}`));
assert.equal(button.classes().includes('ui-button--action'), false);
}
wrapper.unmount();
});
test('a styled variant still presses', async () => {
const wrapper = mountButton({
variant: 'action',
pressed: false,
pressedClass: 'active',
});
const button = wrapper.get('button');
assert.equal(button.attributes('aria-pressed'), 'false');
await wrapper.setProps({ pressed: true });
assert.equal(button.attributes('aria-pressed'), 'true');
assert.ok(button.classes().includes('ui-button--pressed'));
assert.ok(button.classes().includes('ui-button--action'));
assert.ok(button.classes().includes('active'));
wrapper.unmount();
});
+39 -6
View File
@@ -4,9 +4,22 @@ import { vClassToggle } from '../rail/classToggle.js';
// Core's button and its attribute contract: the button is always the root,
// attributes passed in win over its own (a `title` replaces the label's), and
// `pressed` renders aria-pressed only when it is passed. Core styles the
// button through the classes its callers pass; the kit classes carry no Core
// styles yet. Core adds `pressedClass`, its class on a pressed button (most
// `pressed` renders aria-pressed only when it is passed. The variant picks
// the look:
// - `ghost` (the default) carries no style; the caller's classes style it.
// - `action` wears Core's action surface (action-button.css), with
// `tone="danger"` for a red hover and `size="compact"` for the smaller
// shot-row footprint.
// - `primary` is that surface with the accent emphasis of a group's one main
// action (action-button.css).
// - `icon` is the 22px square glyph button of a panel's collapse toggle
// (controls.css).
// A pressed action, primary or icon button looks as a hovered regular one
// does (a compact action's quieter hover is for an unpressed button); a
// disabled one dims and ignores hover and press. `size` styles the action
// variant only. Each
// resting rule selects one kit class, so a feature class loaded later still
// wins. Core adds `pressedClass`, its class on a pressed button (most
// toggles use `active`). The pressed classes toggle through `classList`, so
// classes other code adds to the button (a voice highlight) survive a press.
// Not mirrored yet: icon, loading, disabledReason and the missing-label
@@ -14,8 +27,24 @@ import { vClassToggle } from '../rail/classToggle.js';
defineOptions({ inheritAttrs: false });
const props = defineProps({
variant: { type: String, default: 'ghost' },
tone: { type: String, default: 'accent' },
variant: {
type: String,
default: 'ghost',
validator: (value) =>
['ghost', 'action', 'primary', 'icon'].includes(value),
},
/** `accent`, or `danger` for an action that destroys or stops. */
tone: {
type: String,
default: 'accent',
validator: (value) => ['accent', 'danger'].includes(value),
},
/** `compact` for an action's smaller footprint. */
size: {
type: String,
default: 'regular',
validator: (value) => ['regular', 'compact'].includes(value),
},
/** The accessible name (aria-label) and, with nativeTitle, the tip. */
label: { type: String, default: undefined },
pressed: { type: Boolean, default: undefined },
@@ -53,7 +82,11 @@ const vPressedClasses = {
:type="props.type"
:form="props.form"
class="ui-button ui-focus"
:class="[`ui-button--${props.variant}`, `ui-button--${props.tone}`]"
:class="[
`ui-button--${props.variant}`,
`ui-button--${props.tone}`,
{ 'ui-button--compact': props.size === 'compact' },
]"
:aria-label="props.label"
:title="props.nativeTitle ? props.label : undefined"
:aria-pressed="
+162
View File
@@ -0,0 +1,162 @@
import { after, before, test } from 'node:test';
import assert from 'node:assert/strict';
import { installVueDom } from '../../testSupport/vueDom.mjs';
let mount;
let nextTick;
let UiCheckbox;
let uninstall;
before(async () => {
uninstall = installVueDom();
({ mount } = await import('@vue/test-utils'));
({ nextTick } = await import('vue'));
UiCheckbox = (await import('./UiCheckbox.vue')).default;
});
after(() => uninstall());
/** A checkbox whose v-model writes back into its props, as a parent's would. */
function bound(props = {}, attrs = {}) {
const wrapper = mount(UiCheckbox, {
attachTo: document.body,
props: {
modelValue: false,
...props,
'onUpdate:modelValue': (value) => wrapper.setProps({ modelValue: value }),
},
attrs,
slots: { default: '<span class="words">Scope</span>' },
});
return wrapper;
}
/** Tick the box as a person does: flip it, then the change event. */
async function tick(input) {
input.element.checked = !input.element.checked;
await input.trigger('change');
}
test('a checkbox is a label wrapping a native box, then its words', () => {
const wrapper = bound();
const root = wrapper.get('label');
assert.ok(root.classes().includes('ui-checkbox'));
const input = wrapper.get('input');
assert.equal(input.attributes('type'), 'checkbox');
assert.ok(input.classes().includes('ui-checkbox__input'));
assert.equal(input.attributes('id'), undefined);
const elements = [...root.element.children];
assert.deepEqual(
elements.map((el) => el.tagName),
['INPUT', 'SPAN'],
);
wrapper.unmount();
});
test('trailing puts the box after its words', () => {
const wrapper = bound({ trailing: true });
assert.deepEqual(
[...wrapper.get('label').element.children].map((el) => el.tagName),
['SPAN', 'INPUT'],
);
wrapper.unmount();
});
test('attributes and classes go to the label; inputId and inputAttrs to the box', () => {
const wrapper = bound(
{
inputId: 'scope-toggle',
inputAttrs: { 'aria-describedby': 'note', 'data-hook': '' },
},
{ class: 'pp-scope-toggle', title: 'Scope', id: 'scope-row' },
);
const root = wrapper.get('label');
assert.ok(root.classes().includes('pp-scope-toggle'));
assert.equal(root.attributes('title'), 'Scope');
assert.equal(root.attributes('id'), 'scope-row');
const input = wrapper.get('input');
assert.equal(input.attributes('id'), 'scope-toggle');
assert.equal(input.attributes('aria-describedby'), 'note');
assert.equal(input.attributes('data-hook'), '');
assert.equal(input.attributes('title'), undefined);
assert.ok(!input.classes().includes('pp-scope-toggle'));
wrapper.unmount();
});
test('v-model shows the value and reports each change', async () => {
const wrapper = bound({ modelValue: true });
const input = wrapper.get('input');
assert.equal(input.element.checked, true);
await tick(input);
assert.deepEqual(wrapper.emitted('update:modelValue').at(-1), [false]);
assert.equal(wrapper.emitted('change').at(-1)[0].target, input.element);
assert.equal(input.element.checked, false);
await tick(input);
assert.deepEqual(wrapper.emitted('update:modelValue').at(-1), [true]);
// A parent that resets its value resets the box.
await wrapper.setProps({ modelValue: false });
assert.equal(input.element.checked, false);
wrapper.unmount();
});
test('without restore a change the owner ignores stays ticked, as :checked did', async () => {
const wrapper = mount(UiCheckbox, { props: { modelValue: false } });
const input = wrapper.get('input');
await tick(input);
await nextTick();
assert.deepEqual(wrapper.emitted('update:modelValue'), [[true]]);
assert.equal(input.element.checked, true);
wrapper.unmount();
});
test('restore puts a refused change back and keeps an accepted one', async () => {
// Refused: the owner keeps its value.
const refused = mount(UiCheckbox, {
props: { modelValue: true, restore: true },
});
const box = refused.get('input');
await tick(box);
assert.deepEqual(refused.emitted('update:modelValue'), [[false]]);
await nextTick();
assert.equal(box.element.checked, true);
refused.unmount();
// Accepted: the owner takes the change before the box is checked again.
const accepted = bound({ modelValue: true, restore: true });
const input = accepted.get('input');
await tick(input);
await nextTick();
assert.equal(input.element.checked, false);
assert.equal(accepted.props('modelValue'), false);
accepted.unmount();
});
test('without a modelValue the box is the browser’s own', async () => {
const wrapper = mount(UiCheckbox, {
props: { inputAttrs: { 'data-first-run-suppress': '' } },
});
const input = wrapper.get('input');
assert.equal(input.element.checked, false);
await tick(input);
assert.equal(input.element.checked, true);
assert.equal(wrapper.emitted('change').length, 1);
// Rendering again leaves what was ticked alone.
await wrapper.setProps({ inputId: 'suppress' });
assert.equal(input.attributes('id'), 'suppress');
assert.equal(input.element.checked, true);
wrapper.unmount();
});
test('a change listener sees the box as the event’s current target', async () => {
let seen = null;
const wrapper = mount(UiCheckbox, {
attrs: {
onChange: (event) => {
seen = event.currentTarget;
},
},
});
const input = wrapper.get('input');
await tick(input);
assert.equal(seen, input.element);
// The label itself does not hear the box's change a second time.
assert.equal(wrapper.emitted('change').length, 1);
wrapper.unmount();
});
+57
View File
@@ -0,0 +1,57 @@
<script setup>
import { nextTick, ref } from 'vue';
// Core's checkbox: a `<label>` wrapping a native `<input type="checkbox">`
// and the default slot, which names it. The box comes first, or after the
// slot with `trailing`. Attributes and classes pass through to the label, so
// each site keeps its feature class and tip; the input takes `inputId` and
// `inputAttrs` (other attributes it needs, such as aria-describedby or a
// data hook). With v-model the box shows `modelValue` and a change emits the
// checked state; `change` is emitted with the event too. Without a
// modelValue the box is the browser's own and keeps whatever is ticked.
// `restore` puts the box back to `modelValue` after a change its owner did
// not take, so a refused preference shows the applied value again. The kit
// classes `ui-checkbox` and `ui-checkbox__input` (checkbox.css) are the
// label's centred flex row and the box, which keeps each skin's look.
const props = defineProps({
modelValue: { type: Boolean, default: undefined },
inputId: { type: String, default: undefined },
inputAttrs: { type: Object, default: undefined },
trailing: { type: Boolean, default: false },
restore: { type: Boolean, default: false },
});
const emit = defineEmits(['update:modelValue', 'change']);
const input = ref(null);
function onChange(event) {
emit('update:modelValue', event.target.checked);
emit('change', event);
if (!props.restore) return;
// The owner has answered once the update it caused has rendered.
nextTick(() => {
const box = input.value;
if (
box &&
props.modelValue !== undefined &&
box.checked !== props.modelValue
)
box.checked = props.modelValue;
});
}
</script>
<template>
<label class="ui-checkbox">
<slot v-if="props.trailing" />
<input
ref="input"
type="checkbox"
:id="props.inputId"
class="ui-checkbox__input"
v-bind="props.inputAttrs"
:checked="props.modelValue"
@change="onChange"
/>
<slot v-if="!props.trailing" />
</label>
</template>
+4 -3
View File
@@ -1,7 +1,8 @@
<script setup>
// Core's chip: a label that says what something is, never a control.
// Core styles it through the classes its callers pass; the kit classes carry
// no Core styles yet. A chip that presses is a UiButton with pressedClass.
// Core's chip: a label that says what something is, never a control. It
// wears Core's read-only chip (chip.css: a pill of small uppercase mono
// text), and `selected` its accent; feature classes the caller passes
// restyle it. A chip that presses is a UiButton with pressedClass.
defineProps({
selected: { type: Boolean, default: false },
mono: { type: Boolean, default: false },
+98
View File
@@ -0,0 +1,98 @@
import { after, before, test } from 'node:test';
import assert from 'node:assert/strict';
import { installVueDom } from '../../testSupport/vueDom.mjs';
let mount;
let UiCloseButton;
let uninstall;
before(async () => {
uninstall = installVueDom();
({ mount } = await import('@vue/test-utils'));
UiCloseButton = (await import('./UiCloseButton.vue')).default;
});
after(() => uninstall());
function mountClose(props = {}, attrs = {}) {
return mount(UiCloseButton, {
attachTo: document.body,
props: { label: 'Close card', ...props },
attrs,
});
}
test('a close button is a button named by its label, with no tip of its own', () => {
const wrapper = mountClose();
const button = wrapper.get('button');
assert.equal(button.attributes('type'), 'button');
assert.equal(button.attributes('aria-label'), 'Close card');
assert.equal(button.attributes('title'), undefined);
assert.ok(button.classes().includes('ui-close-button'));
wrapper.unmount();
});
test('glyph="times" draws the × character', () => {
const wrapper = mountClose();
const button = wrapper.get('button');
assert.equal(button.element.innerHTML, '×');
wrapper.unmount();
});
test('glyph="icon" draws the Material close symbol, sized by the stylesheet', () => {
const wrapper = mountClose({ glyph: 'icon' });
const icon = wrapper.get('button > span');
assert.equal(wrapper.get('button').element.children.length, 1);
assert.equal(icon.text(), 'close');
assert.ok(icon.classes().includes('material-symbols-outlined'));
assert.equal(icon.attributes('aria-hidden'), 'true');
assert.equal(icon.attributes('style'), undefined);
wrapper.unmount();
});
test('attributes and classes pass through to the button', () => {
const wrapper = mountClose(
{},
{
id: 'gev-chat-close',
class: 'data-toggle-chip',
title: 'Clear reading',
'data-action-id': 'clear',
'aria-hidden': 'true',
disabled: true,
hidden: true,
},
);
const button = wrapper.get('button');
assert.equal(button.attributes('id'), 'gev-chat-close');
assert.ok(button.classes().includes('data-toggle-chip'));
assert.ok(button.classes().includes('ui-close-button'));
assert.equal(button.attributes('title'), 'Clear reading');
assert.equal(button.attributes('data-action-id'), 'clear');
assert.equal(button.attributes('aria-hidden'), 'true');
assert.equal(button.element.disabled, true);
assert.equal(button.element.hidden, true);
wrapper.unmount();
});
test('bare leaves the kit look off', () => {
const wrapper = mountClose({ bare: true }, { class: 'sl-viewer-x' });
const classes = wrapper.get('button').classes();
assert.ok(classes.includes('sl-viewer-x'));
assert.equal(classes.includes('ui-close-button'), false);
wrapper.unmount();
});
test('a click is emitted with its event', async () => {
const wrapper = mountClose();
await wrapper.get('button').trigger('click');
const clicks = wrapper.emitted('click');
assert.equal(clicks.length, 1);
assert.ok(clicks[0][0] instanceof Event);
wrapper.unmount();
});
test('a disabled close button emits no click', async () => {
const wrapper = mountClose({}, { disabled: true });
await wrapper.get('button').trigger('click');
assert.equal(wrapper.emitted('click'), undefined);
wrapper.unmount();
});
+40
View File
@@ -0,0 +1,40 @@
<script setup>
import UiButton from './UiButton.vue';
import UiIcon from './UiIcon.vue';
// Core's close, dismiss and clear button: a UiButton with a fixed glyph and
// a required accessible name. `glyph` is `times` (the × character) or `icon`
// (the Material `close` symbol, sized by the caller's stylesheet). Attributes
// and classes pass through to the button, so each site keeps its id, its
// feature class and its look; a `title` passed in is its tip, and without
// one it has none. The kit class `ui-close-button` (close-button.css) is
// Core's common look, a bare glyph: no padding, border or background of its
// own, and a pointer. Its rule selects one class and loads before the
// feature stylesheets, so a feature rule still sets the size, colour, hover
// and any surface. `bare` leaves the kit look off, for a button whose own
// skin sets its padding and border.
const props = defineProps({
/** The accessible name (aria-label). */
label: { type: String, required: true },
glyph: {
type: String,
default: 'times',
validator: (value) => ['times', 'icon'].includes(value),
},
bare: { type: Boolean, default: false },
});
const emit = defineEmits(['click']);
</script>
<template>
<UiButton
:class="{ 'ui-close-button': !props.bare }"
:label="props.label"
:native-title="false"
@click="emit('click', $event)"
><UiIcon v-if="props.glyph === 'icon'" name="close" :size="null" /><template
v-else
>×</template
></UiButton
>
</template>
+200
View File
@@ -0,0 +1,200 @@
import { after, before, test } from 'node:test';
import assert from 'node:assert/strict';
import { installVueDom } from '../../testSupport/vueDom.mjs';
let mount;
let nextTick;
let UiDialog;
let uninstall;
before(async () => {
uninstall = installVueDom();
({ mount } = await import('@vue/test-utils'));
({ nextTick } = await import('vue'));
UiDialog = (await import('./UiDialog.vue')).default;
});
after(() => uninstall());
/**
* A dialog that records what it emits, each with whether the dialog was open
* then; its content is a paragraph. One is mounted at a time.
*/
function dialog(props = {}, attrs = {}) {
const events = [];
const record = (name) => () =>
events.push(
name,
document.querySelector('dialog').open ? 'shown' : 'hidden',
);
const wrapper = mount(UiDialog, {
attachTo: document.body,
props: {
...props,
onDismiss: record('dismiss'),
onBrowserClose: record('browserClose'),
onOpened: record('opened'),
onClosed: record('closed'),
},
attrs,
slots: { default: '<p class="content">Words</p>' },
});
return { wrapper, events };
}
test('a dialog mounted closed stays closed until open', async () => {
const { wrapper, events } = dialog();
const element = wrapper.element;
assert.equal(element.tagName, 'DIALOG');
assert.equal(element.open, false);
assert.equal(wrapper.vm.element, element, 'element is exposed');
await wrapper.setProps({ open: true });
assert.equal(element.open, true);
assert.deepEqual(events, ['opened', 'shown']);
await wrapper.setProps({ open: false });
assert.equal(element.open, false);
assert.deepEqual(events, ['opened', 'shown', 'closed', 'hidden']);
wrapper.unmount();
});
test('a dialog mounted open opens modal on mount; unmounting closes it', async () => {
const modal = [];
const showModal = HTMLDialogElement.prototype.showModal;
HTMLDialogElement.prototype.showModal = function () {
modal.push(this);
return showModal.call(this);
};
try {
const { wrapper, events } = dialog({ open: true });
const element = wrapper.element;
assert.deepEqual(modal, [element]);
assert.equal(element.open, true);
assert.deepEqual(events, ['opened', 'shown']);
wrapper.unmount();
assert.equal(element.open, false);
assert.deepEqual(events, ['opened', 'shown'], 'no dismiss on unmount');
} finally {
HTMLDialogElement.prototype.showModal = showModal;
}
});
test('the open state follows the content: opened comes after it renders', async () => {
// The content changes in the same update that opens the dialog, so an
// opened emitted before that update renders would see the old words.
const { h } = await import('vue');
let seen;
const Host = {
props: { open: Boolean, words: String },
setup(props) {
return () =>
h(
UiDialog,
{
open: props.open,
onOpened: () => {
seen = document.querySelector('dialog .content')?.textContent;
},
},
() => h('p', { class: 'content' }, props.words),
);
},
};
const wrapper = mount(Host, {
attachTo: document.body,
props: { open: false, words: 'Before' },
});
await wrapper.setProps({ open: true, words: 'After' });
assert.equal(seen, 'After');
wrapper.unmount();
});
test('Escape is prevented and emitted as dismiss; the owner decides', async () => {
const { wrapper, events } = dialog({ open: true });
events.length = 0;
const cancel = new Event('cancel', { cancelable: true });
wrapper.element.dispatchEvent(cancel);
assert.equal(cancel.defaultPrevented, true);
assert.equal(wrapper.element.open, true);
assert.deepEqual(events, ['dismiss', 'shown']);
wrapper.unmount();
});
test('a close the browser made while open is reported once; the owner’s is not', async () => {
const { wrapper, events } = dialog({ open: true });
events.length = 0;
wrapper.element.close();
assert.deepEqual(events, ['browserClose', 'hidden']);
events.length = 0;
// The owner then closes it too: nothing to close, closed is still emitted.
await wrapper.setProps({ open: false });
assert.deepEqual(events, ['closed', 'hidden']);
await wrapper.setProps({ open: true });
events.length = 0;
await wrapper.setProps({ open: false });
assert.deepEqual(events, ['closed', 'hidden'], 'no browserClose');
wrapper.unmount();
});
test('a late close event from an earlier close is not reported once open again', async () => {
const { wrapper, events } = dialog({ open: true });
await wrapper.setProps({ open: false });
await wrapper.setProps({ open: true });
events.length = 0;
// The browser's queued close event from the first close lands now.
wrapper.element.dispatchEvent(new Event('close'));
assert.deepEqual(events, [], 'no browserClose');
wrapper.unmount();
});
test('a backdrop click dismisses only when asked, and only on the dialog', async () => {
const plain = dialog({ open: true });
plain.events.length = 0;
plain.wrapper.element.click();
assert.deepEqual(plain.events, []);
plain.wrapper.unmount();
const backdrop = dialog({ open: true, backdropDismiss: true });
backdrop.events.length = 0;
backdrop.wrapper.get('.content').element.click();
assert.deepEqual(backdrop.events, [], 'a click inside is content');
backdrop.wrapper.element.click();
assert.deepEqual(backdrop.events, ['dismiss', 'shown']);
backdrop.wrapper.unmount();
});
test('attributes, classes, styles and listeners pass through to the dialog', async () => {
const clicks = [];
const { wrapper } = dialog(
{},
{
id: 'library',
class: 'library-dialog',
style: { width: '40px' },
'aria-label': 'Library',
'data-panel-surface': '',
onClick: () => clicks.push('click'),
},
);
const element = wrapper.element;
assert.equal(element.id, 'library');
assert.ok(element.classList.contains('library-dialog'));
assert.equal(element.style.width, '40px');
assert.equal(element.getAttribute('aria-label'), 'Library');
assert.equal(element.getAttribute('data-panel-surface'), '');
element.click();
assert.deepEqual(clicks, ['click']);
wrapper.unmount();
});
test('a DOM without showModal leaves the dialog closed rather than failing', async () => {
const showModal = HTMLDialogElement.prototype.showModal;
HTMLDialogElement.prototype.showModal = undefined;
try {
const { wrapper, events } = dialog({ open: true });
assert.equal(wrapper.element.open, false);
assert.deepEqual(events, ['opened', 'hidden']);
await wrapper.setProps({ open: false });
await nextTick();
wrapper.unmount();
} finally {
HTMLDialogElement.prototype.showModal = showModal;
}
});
+74
View File
@@ -0,0 +1,74 @@
<script setup>
import { onBeforeUnmount, onMounted, useTemplateRef, watch } from 'vue';
// Core's modal dialog: a native `<dialog>` the owner opens and closes with
// `open`. True opens it with showModal() (once mounted, so a dialog mounted
// open opens straight away), false closes it, and unmounting closes it.
// Each change is applied after the content has rendered and is then emitted
// (`opened`, `closed`), so the owner can move focus into the content it
// shows or back to the control that opened it. Escape's `cancel` is
// prevented and emitted as `dismiss`, so the owner decides; with
// `backdropDismiss`, a click on the backdrop (the dialog element itself,
// outside its content) is a `dismiss` too. When the browser closes the
// dialog on its own while `open` is still true (an Escape it does not let
// the page cancel), `browserClose` tells the owner. A DOM without
// showModal() (a test's) leaves the dialog closed rather than failing.
// Attributes, classes, styles and listeners pass through to the dialog; the
// content is the default slot. `element` is the dialog element.
const props = defineProps({
open: { type: Boolean, default: false },
backdropDismiss: { type: Boolean, default: false },
});
const emit = defineEmits(['dismiss', 'browserClose', 'opened', 'closed']);
const element = useTemplateRef('element');
let unmounting = false;
function show() {
const dialog = element.value;
if (!dialog) return;
if (!dialog.open) dialog.showModal?.();
emit('opened');
}
onMounted(() => {
if (props.open) show();
});
watch(
() => props.open,
(open) => {
if (open) return show();
const dialog = element.value;
if (!dialog) return;
// The browser may already have closed it.
if (dialog.open) dialog.close();
emit('closed');
},
{ flush: 'post' },
);
onBeforeUnmount(() => {
unmounting = true;
if (element.value?.open) element.value.close();
});
function onCancel(event) {
event.preventDefault();
emit('dismiss');
}
// The browser queues its close event, so one from an earlier close can land
// after the dialog has been opened again; only a dialog still shut reports it.
function onClose() {
if (!unmounting && props.open && !element.value?.open) emit('browserClose');
}
function onClick(event) {
if (props.backdropDismiss && event.target === event.currentTarget)
emit('dismiss');
}
defineExpose({ element });
</script>
<template>
<dialog ref="element" @cancel="onCancel" @close="onClose" @click="onClick">
<slot />
</dialog>
</template>
+3 -2
View File
@@ -1,8 +1,9 @@
<script setup>
// Core's empty state, with a `title` and `hint`. Core's empty states are one
// line, so the title is the text itself rather than a bold heading; a hint
// follows it. Core
// styles it through the classes its callers pass. Not mirrored yet: icon.
// follows it on a line of its own. It wears Core's empty line
// (empty-state.css: dim 10px mono text); feature classes the caller passes
// restyle it. Not mirrored yet: icon.
defineProps({
title: { type: String, required: true },
hint: { type: String, default: undefined },
+5 -2
View File
@@ -1,5 +1,8 @@
<script setup>
/** A Material Symbols glyph; the name must be in index.html's `icon_names`. */
/**
* A Material Symbols glyph; the name must be in index.html's `icon_names`.
* `size` is its font size in pixels; null leaves the size to the stylesheet.
*/
defineProps({
name: { type: String, required: true },
size: { type: Number, default: 18 },
@@ -9,7 +12,7 @@ defineProps({
<template>
<span
class="ui-icon material-symbols-outlined"
:style="{ fontSize: `${size}px` }"
:style="size == null ? undefined : { fontSize: `${size}px` }"
aria-hidden="true"
>{{ name }}</span
>
+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>
+136
View File
@@ -0,0 +1,136 @@
import { after, before, test } from 'node:test';
import assert from 'node:assert/strict';
import { installVueDom } from '../../testSupport/vueDom.mjs';
let mount;
let UiSearchField;
let uninstall;
before(async () => {
uninstall = installVueDom();
({ mount } = await import('@vue/test-utils'));
UiSearchField = (await import('./UiSearchField.vue')).default;
});
after(() => uninstall());
/** A field whose v-model writes back into its props, as a parent's would. */
function bound(props = {}, attrs = {}) {
const wrapper = mount(UiSearchField, {
attachTo: document.body,
props: {
label: 'Search layers',
modelValue: '',
...props,
'onUpdate:modelValue': (value) => wrapper.setProps({ modelValue: value }),
},
attrs,
});
return wrapper;
}
test('a search field is the search glyph and a search input named by its label', () => {
const wrapper = bound({ placeholder: 'Search layers…' });
const root = wrapper.get('div');
assert.ok(root.classes().includes('ui-search-field'));
const icon = wrapper.get('span');
assert.equal(icon.text(), 'search');
assert.ok(icon.classes().includes('material-symbols-outlined'));
assert.equal(icon.attributes('aria-hidden'), 'true');
const input = wrapper.get('input');
assert.equal(input.attributes('type'), 'search');
assert.ok(input.classes().includes('ui-search-field__input'));
assert.equal(input.attributes('aria-label'), 'Search layers');
assert.equal(input.attributes('placeholder'), 'Search layers…');
for (const name of ['id', 'autocomplete', 'spellcheck'])
assert.equal(input.attributes(name), undefined, name);
assert.equal(wrapper.find('button').exists(), false);
wrapper.unmount();
});
test('v-model shows the text and updates it as typed', async () => {
const wrapper = bound({ modelValue: 'radar' });
const input = wrapper.get('input');
assert.equal(input.element.value, 'radar');
await input.setValue('rain');
assert.deepEqual(wrapper.emitted('update:modelValue').at(-1), ['rain']);
assert.equal(wrapper.props('modelValue'), 'rain');
// A parent that empties its value, as closing a search does, empties the input.
await wrapper.setProps({ modelValue: '' });
assert.equal(input.element.value, '');
wrapper.unmount();
});
test('the clear button shows only while text is typed, clears and refocuses', async () => {
const wrapper = bound({
clearLabel: 'Clear search',
clearClass: 'context-search__clear',
});
assert.equal(wrapper.find('button').exists(), false);
await wrapper.setProps({ modelValue: 'rain' });
const clear = wrapper.get('button');
assert.equal(clear.attributes('aria-label'), 'Clear search');
assert.equal(clear.attributes('title'), 'Clear search');
assert.ok(clear.classes().includes('context-search__clear'));
assert.ok(clear.classes().includes('ui-close-button'));
assert.equal(clear.get('span').text(), 'close');
await clear.trigger('click');
assert.deepEqual(wrapper.emitted('update:modelValue').at(-1), ['']);
assert.equal(document.activeElement, wrapper.get('input').element);
assert.equal(wrapper.find('button').exists(), false);
wrapper.unmount();
});
test('Escape is emitted with its event and stops at the input', async () => {
const wrapper = bound();
let bubbled = 0;
const onKey = () => bubbled++;
wrapper.element.addEventListener('keydown', onKey);
await wrapper.get('input').trigger('keydown', { key: 'Escape' });
const escapes = wrapper.emitted('escape');
assert.equal(escapes.length, 1);
assert.ok(escapes[0][0] instanceof Event);
assert.equal(escapes[0][0].defaultPrevented, false);
assert.equal(bubbled, 0);
await wrapper.get('input').trigger('keydown', { key: 'a' });
assert.equal(wrapper.emitted('escape').length, 1);
assert.equal(bubbled, 1);
wrapper.unmount();
});
test('tag="label" frames the input in a label', () => {
const wrapper = bound({ tag: 'label' });
assert.equal(wrapper.element.tagName, 'LABEL');
assert.ok(wrapper.element.contains(wrapper.get('input').element));
wrapper.unmount();
});
test('attributes and classes pass through to the frame; the input takes its own', () => {
const wrapper = bound(
{
inputId: 'layer-finder-input',
inputClass: 'context-search__input',
autocomplete: 'off',
spellcheck: 'false',
},
{ class: 'context-search', role: 'search', 'data-x': '1' },
);
const root = wrapper.get('div');
assert.ok(root.classes().includes('context-search'));
assert.ok(root.classes().includes('ui-search-field'));
assert.equal(root.attributes('role'), 'search');
assert.equal(root.attributes('data-x'), '1');
const input = wrapper.get('input');
assert.equal(input.attributes('id'), 'layer-finder-input');
assert.ok(input.classes().includes('context-search__input'));
assert.ok(input.classes().includes('ui-search-field__input'));
assert.equal(input.attributes('autocomplete'), 'off');
assert.equal(input.attributes('spellcheck'), 'false');
assert.equal(input.attributes('role'), undefined);
wrapper.unmount();
});
test('focus() focuses the input', () => {
const wrapper = bound();
wrapper.vm.focus();
assert.equal(document.activeElement, wrapper.get('input').element);
wrapper.unmount();
});
+81
View File
@@ -0,0 +1,81 @@
<script setup>
import { computed, ref } from 'vue';
import UiCloseButton from './UiCloseButton.vue';
// Core's search field: the Material `search` glyph, then an
// `<input type="search">` bound with v-model, and, when `clearLabel` is set,
// a UiCloseButton (the `close` symbol, its label as its tip) shown while
// text is typed, which empties the field and focuses the input again. `tag`
// is the frame: a `div` (give it role="search") or a `label`, which names
// the input by wrapping it. Attributes and classes pass through to the frame,
// so each site keeps its feature class; the input takes `inputId`,
// `inputClass`, `autocomplete` and `spellcheck`, and the clear button
// `clearClass`. Escape, pressed in the input, stops there and is emitted
// with its event, so a caller that also prevents the browser's own Escape
// does so. `focus()` focuses the input. The kit classes `ui-search-field`
// and `ui-search-field__input` (search-field.css) are the frame's flex row
// and the bare input; the browser's own cancel button is left as it is.
const props = defineProps({
modelValue: { type: String, default: '' },
/** The input's accessible name (aria-label). */
label: { type: String, required: true },
placeholder: { type: String, default: undefined },
tag: {
type: String,
default: 'div',
validator: (value) => ['div', 'label'].includes(value),
},
inputId: { type: String, default: undefined },
inputClass: { type: String, default: undefined },
autocomplete: { type: String, default: undefined },
spellcheck: { type: String, default: undefined },
/** The clear button's accessible name and tip; none without it. */
clearLabel: { type: String, default: undefined },
clearClass: { type: String, default: undefined },
});
const emit = defineEmits(['update:modelValue', 'escape']);
const input = ref(null);
// The input keeps Vue's native v-model, as both fields had.
const text = computed({
get: () => props.modelValue,
set: (value) => emit('update:modelValue', value),
});
function focus() {
input.value?.focus();
}
function clear() {
emit('update:modelValue', '');
focus();
}
defineExpose({ focus });
</script>
<template>
<component :is="props.tag" class="ui-search-field">
<span class="material-symbols-outlined" aria-hidden="true">search</span>
<input
:id="props.inputId"
ref="input"
v-model="text"
type="search"
class="ui-search-field__input"
:class="props.inputClass"
:placeholder="props.placeholder"
:aria-label="props.label"
:autocomplete="props.autocomplete"
:spellcheck="props.spellcheck"
@keydown.esc.stop="emit('escape', $event)"
/>
<UiCloseButton
v-if="props.clearLabel && props.modelValue"
:class="props.clearClass"
glyph="icon"
:label="props.clearLabel"
:title="props.clearLabel"
@click="clear"
/>
</component>
</template>
+3 -1
View File
@@ -7,7 +7,9 @@ import { computed } from 'vue';
// stop that arrows move) or `radio` (arrows plus Home and
// End). Each option may carry `attrs` (an id, data attributes, a tip), and
// Core's classes sit beside the kit's: `gev-segmented`, `gev-segment` and the
// selected option's `activeClass`. An option with an `icon` shows the glyph,
// selected option's `activeClass`. The kit's classes wear Core's segmented
// skin (segmented-control.css) as Core's do; `stacked` carries no style yet.
// An option with an `icon` shows the glyph,
// and its label becomes the button's accessible name and tooltip, unless its
// `attrs` carry a tip of their own.
const props = defineProps({
+67
View File
@@ -0,0 +1,67 @@
// Every checkbox in a Vue view is a UiCheckbox: no SFC template hand-writes
// `<input type="checkbox">`.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync, readdirSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const SRC_ROOT = fileURLToPath(new URL('../../', import.meta.url));
const REPO_ROOT = path.resolve(SRC_ROOT, '..');
const NOT_YET = new Set(['src/ui/kit/UiCheckbox.vue']);
/** Every SFC under src. */
function sfcFiles(directory = SRC_ROOT) {
const files = [];
for (const entry of readdirSync(directory, { withFileTypes: true })) {
const absolute = path.join(directory, entry.name);
if (entry.isDirectory()) files.push(...sfcFiles(absolute));
else if (entry.isFile() && entry.name.endsWith('.vue'))
files.push(absolute);
}
return files.sort();
}
/** The template block: everything outside script and style. */
function template(source) {
return source.replace(/<(script|style)\b[\s\S]*?<\/\1\s*>/g, '');
}
// An opening tag's attributes, quoted values may hold `>` (`() => x`).
const ATTRS = String.raw`(?:[^>"']|"[^"]*"|'[^']*')*`;
const HAND_WRITTEN_CHECKBOX = new RegExp(
String.raw`<input\b${ATTRS}\btype="checkbox"${ATTRS}>`,
'gi',
);
/** Hand-written checkboxes in an SFC's template. */
function handWrittenCheckboxes(source) {
return [...template(source).matchAll(HAND_WRITTEN_CHECKBOX)].map((m) =>
m[0].replace(/\s+/g, ' '),
);
}
test('the scan finds each hand-written checkbox', () => {
for (const markup of [
'<template><input type="checkbox" id="x" @change="on" /></template>',
'<template><input\n :checked="a > b"\n type="checkbox"\n/></template>',
])
assert.equal(handWrittenCheckboxes(markup).length, 1, markup);
for (const markup of [
'<template><UiCheckbox input-id="x" v-model="on">On</UiCheckbox></template>',
'<template><input type="search" /></template>',
'<script>const html = \'<input type="checkbox">\';</script><template><p /></template>',
])
assert.equal(handWrittenCheckboxes(markup).length, 0, markup);
});
test('no SFC hand-writes a checkbox; each is a UiCheckbox', () => {
const found = [];
for (const file of sfcFiles()) {
const relative = path.relative(REPO_ROOT, file).split(path.sep).join('/');
if (NOT_YET.has(relative)) continue;
for (const markup of handWrittenCheckboxes(readFileSync(file, 'utf8')))
found.push(`${relative}: ${markup}`);
}
assert.deepEqual(found, []);
});
Loaded 100 of 2619 files, more files were not shown because too many files have changed in this diff. Show more