mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-23 11:42:21 +00:00
Merge remote-tracking branch 'origin/main' into fix/cockpit-utility-phone-row
# Conflicts: # src/ui/styles/cyber.css
This commit is contained in:
commit
0c828095ad
3290 files changed
+460721
-51931
No files matched your search
@@ -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,
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
+213
-61
@@ -1,10 +1,16 @@
|
||||
import { followedOf } from '../data/followed.js';
|
||||
import { readEntityRecord } from '../data/entityRecords.js';
|
||||
import { nextTick } from 'vue';
|
||||
import { resolveImageryHost } from '../layers/weather/imageryHost.js';
|
||||
import { ShellFacade } from './shellFacade.js';
|
||||
import { AircraftDisplay } from './aircraftDisplay.js';
|
||||
import { LayerBindings } from './layerBindings.js';
|
||||
import { PanelChrome } from './panelChrome.js';
|
||||
import { initMobileShell } from './mobileShell.js';
|
||||
import {
|
||||
initMobileShell,
|
||||
MOBILE_SHELL_MEDIA_QUERY,
|
||||
sheetForPanelId,
|
||||
} from './mobileShell.js';
|
||||
import { VisualSettings } from './visualSettings.js';
|
||||
import { NavigationController } from './navigationController.js';
|
||||
import { ShareRestoration } from './shareRestoration.js';
|
||||
@@ -17,19 +23,23 @@ import { CockpitCoordinator } from './cockpitCoordinator.js';
|
||||
import { ContextControls } from './context.js';
|
||||
import { CctvControls } from './cctv.js';
|
||||
import { StreetLevelControls } from './streetLevelControls.js';
|
||||
import { createWildlifeSightingCard } from './wildlifeSightingCard.js';
|
||||
import { RadioControls } from './radio.js';
|
||||
import { LocalSdrControls } from './localSdrControls.js';
|
||||
import { LocationNavigation } from './locationNavigation.js';
|
||||
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';
|
||||
|
||||
@@ -52,17 +62,32 @@ 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';
|
||||
|
||||
/**
|
||||
* Central UI orchestrator for the God's Eye View application.
|
||||
@@ -85,10 +110,13 @@ import { useRecordingStore } from './stores/recording.js';
|
||||
|
||||
export class StyleManager extends ShellFacade {
|
||||
/**
|
||||
* @param {Cesium.Viewer} viewer - The CesiumJS viewer instance.
|
||||
* @param {object} viewer - The scene object the renderer draws.
|
||||
* @param {object} [options]
|
||||
* @param {boolean} [options.localePicker=true] - false removes the language
|
||||
* picker, for a host that does not initialize Core's locale.
|
||||
* picker, for a host that offers its own language choice.
|
||||
* @param {{lon: number, lat: number, height: number, heading?: number,
|
||||
* pitch?: number}|null} [options.homeView] - where the title's logo goes
|
||||
* back to (degrees): the view the app started from.
|
||||
*/
|
||||
constructor(
|
||||
viewer,
|
||||
@@ -99,6 +127,7 @@ export class StyleManager extends ShellFacade {
|
||||
requestServices,
|
||||
initialShareCode = null,
|
||||
localePicker = true,
|
||||
homeView = null,
|
||||
} = {},
|
||||
) {
|
||||
super();
|
||||
@@ -156,10 +185,41 @@ export class StyleManager extends ShellFacade {
|
||||
});
|
||||
// Vue views share this runtime and its stores; dispose unmounts them.
|
||||
this._ui = createUiRuntime({ pinia: applicationPinia() });
|
||||
this._feedback = new ShellFeedback({
|
||||
readLayers: () => this._dataManager?.getAll?.() || [],
|
||||
// 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?.() || []),
|
||||
});
|
||||
// The satellite owner flags load with the app, not on the first ride.
|
||||
preloadOwnerFlags();
|
||||
// The place names under a Cockpit load on its first lookup: the loading
|
||||
// status names them meanwhile.
|
||||
this._offPlacePacks = onPlacePacksLoadingChange(() =>
|
||||
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;
|
||||
|
||||
@@ -194,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({
|
||||
@@ -208,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,
|
||||
@@ -221,6 +282,7 @@ export class StyleManager extends ShellFacade {
|
||||
setKeyholeFadeTuning: services.setKeyholeFadeTuning,
|
||||
setScopeMaskEnabled: services.setScopeMaskEnabled,
|
||||
setScopeMaskFeather: services.setScopeMaskFeather,
|
||||
setScopeMaskOpacity: services.setScopeMaskOpacity,
|
||||
},
|
||||
elements: {
|
||||
_ppToggles: this._ppToggles,
|
||||
@@ -265,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,
|
||||
@@ -298,6 +361,7 @@ export class StyleManager extends ShellFacade {
|
||||
this._locationNavigation = new LocationNavigation({
|
||||
viewer,
|
||||
placeSearch,
|
||||
homeView,
|
||||
navigation: this._navigation,
|
||||
readCockpit: () => this.cockpitView,
|
||||
services: {
|
||||
@@ -360,6 +424,10 @@ export class StyleManager extends ShellFacade {
|
||||
services: {
|
||||
flightsLayer: services.flightsLayer,
|
||||
militaryFlightsLayer: services.militaryFlightsLayer,
|
||||
aisLiveVesselsLayer: services.aisLiveVesselsLayer,
|
||||
satellitesLayer: services.satellitesLayer,
|
||||
// Orbit's Live Signals rows list and focus its mapped sites.
|
||||
militaryInstallationsLayer: services.militaryInstallationsLayer,
|
||||
isTr3b: services.isTr3b,
|
||||
toggleTr3b: services.toggleTr3b,
|
||||
militaryAwarenessLayer: services.militaryAwarenessLayer,
|
||||
@@ -369,11 +437,28 @@ 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,
|
||||
regionalDistanceM: services.regionalDistanceM,
|
||||
weatherCodeLabel: services.weatherCodeLabel,
|
||||
// Orbit reads flat Esri imagery: Google 3D tiles stay coarse from
|
||||
// hundreds of kilometres up. The lease puts the map back on exit.
|
||||
acquireOrbitImagery: () =>
|
||||
this.mapStackController?.acquireImageryComparison?.({
|
||||
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,
|
||||
@@ -399,6 +484,10 @@ export class StyleManager extends ShellFacade {
|
||||
useCockpitStore(applicationPinia()).publishVision(view),
|
||||
signals: (rows) =>
|
||||
useCockpitStore(applicationPinia()).publishSignals(rows),
|
||||
radar: (view) =>
|
||||
useCockpitStore(applicationPinia()).publishRadar(view),
|
||||
orbital: (view) =>
|
||||
useCockpitStore(applicationPinia()).publishOrbital(view),
|
||||
utilityLayout: (layout) =>
|
||||
useCockpitStore(applicationPinia()).publishUtilityLayout(layout),
|
||||
},
|
||||
@@ -427,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,
|
||||
@@ -441,12 +532,17 @@ export class StyleManager extends ShellFacade {
|
||||
},
|
||||
isNavigationCurrent: (generation) =>
|
||||
generation === this._navigationGeneration,
|
||||
cancelOwnedNavigation: () => this.viewer.camera.cancelFlight(),
|
||||
cancelOwnedNavigation: () => cameraOf(this.viewer).cancelFlight(),
|
||||
// A host may open a share code without a `/share/<code>` address.
|
||||
initialShareCode,
|
||||
});
|
||||
this.shareLinkManager.setFollowSubjectProvider(({ nowMs }) =>
|
||||
readShareFollowSubject({ viewer: this.viewer, nowMs }),
|
||||
readShareFollowSubject({
|
||||
viewer: this.viewer,
|
||||
nowMs,
|
||||
readSelectedVessel: () =>
|
||||
this.services.aisLiveVesselsLayer?.getSelectedFix?.() ?? null,
|
||||
}),
|
||||
);
|
||||
this.shareLinkManager.setPanelStateProvider(() =>
|
||||
this._buildSharePanelState(),
|
||||
@@ -541,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),
|
||||
@@ -553,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),
|
||||
@@ -589,7 +690,9 @@ export class StyleManager extends ShellFacade {
|
||||
this._initRadioPanel();
|
||||
this._initCctvPanel();
|
||||
this._initStreetLevelPanel();
|
||||
this._initWildlifeSightingCard();
|
||||
this._initGlobalContextPanel();
|
||||
this._initSpaceMissionsPanel();
|
||||
this._initLocationBar();
|
||||
this._initMobileShell();
|
||||
this._initShareButton();
|
||||
@@ -728,7 +831,7 @@ export class StyleManager extends ShellFacade {
|
||||
this._lifetime.own(
|
||||
onLocaleChange(() => nextTick(() => this._sizeDisplayLabelColumn())),
|
||||
);
|
||||
// A host that does not initialize Core's locale shows no picker.
|
||||
// A host that offers its own language choice shows no picker.
|
||||
if (this._localePickerEnabled === false) return;
|
||||
this._publishLocalePicker();
|
||||
}
|
||||
@@ -926,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,
|
||||
@@ -972,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?.();
|
||||
@@ -1012,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'),
|
||||
@@ -1073,6 +1182,19 @@ export class StyleManager extends ShellFacade {
|
||||
return this._runExplicitNavigation('camera', () => focus(cameraId));
|
||||
}
|
||||
|
||||
/** Keep one compact card anchored to the selected wildlife sighting. */
|
||||
_initWildlifeSightingCard() {
|
||||
this._wildlifeSightingCard?.destroy();
|
||||
this._wildlifeSightingCard = null;
|
||||
const layer = this.services.wildlifeSightingsLayer;
|
||||
if (!layer) return;
|
||||
this._wildlifeSightingCard = createWildlifeSightingCard({
|
||||
layer,
|
||||
ui: this._ui,
|
||||
viewer: this.viewer,
|
||||
});
|
||||
}
|
||||
|
||||
/** Compose the Street Level panel controls from its layer and application actions. */
|
||||
_initStreetLevelPanel() {
|
||||
const { streetLevelLayer } = this.services;
|
||||
@@ -1098,6 +1220,7 @@ export class StyleManager extends ShellFacade {
|
||||
this._dataManager?.setLayerParams('street-level', params, options),
|
||||
setPanelCollapsed: (collapsed, options) =>
|
||||
this.setPanelCollapsed('street-level-panel', collapsed, options),
|
||||
revealPanel: () => this.revealPanel('street-level-panel'),
|
||||
showToast: (message) => this._showToast(message),
|
||||
// Lets the panel open for a user, voice or tool switch-on, not a restore.
|
||||
subscribeEnableRequests: (listener) =>
|
||||
@@ -1139,6 +1262,7 @@ export class StyleManager extends ShellFacade {
|
||||
_cctvSummary: this._cctvSummary,
|
||||
},
|
||||
cctv: cctvLayer,
|
||||
viewer: this.viewer,
|
||||
actions: {
|
||||
isEnabled: () => this._dataManager?.isEnabled('cctv'),
|
||||
setParams: (params, options) =>
|
||||
@@ -1146,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(),
|
||||
},
|
||||
@@ -1173,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: () =>
|
||||
@@ -1212,6 +1341,20 @@ export class StyleManager extends ShellFacade {
|
||||
return this._panelChrome.setPanelCollapsed(...arguments);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bring a panel into view on a phone, where the rails show only as tab
|
||||
* sheets: opens the sheet that holds it. Does nothing above 720px.
|
||||
* @param {string} panelId - DOM id of the panel.
|
||||
* @returns {void}
|
||||
*/
|
||||
revealPanel(panelId) {
|
||||
const sheet = sheetForPanelId(panelId);
|
||||
if (!globalThis.matchMedia?.(MOBILE_SHELL_MEDIA_QUERY)?.matches) return;
|
||||
if (sheet) this._mobileShell?.setSheet(sheet);
|
||||
// The sheet opens at its top; a panel lower in the rail is scrolled to.
|
||||
document.getElementById(panelId)?.scrollIntoView?.({ block: 'nearest' });
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggles "clean view" mode which hides all UI panels via a CSS body class.
|
||||
* @param {boolean} [forceEnabled] - Explicit on/off. Omit to toggle.
|
||||
@@ -1257,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(),
|
||||
@@ -1318,9 +1462,12 @@ export class StyleManager extends ShellFacade {
|
||||
};
|
||||
}
|
||||
if (!target.available) {
|
||||
// The controller knows why (Google 3D: no Maps key; others: no ion token).
|
||||
return {
|
||||
ok: false,
|
||||
error: `${target.label} requires a Cesium ion token`,
|
||||
error:
|
||||
target.unavailableReason ||
|
||||
`${target.label} requires a Cesium ion token`,
|
||||
activeStack: this.mapStackController.getActiveId(),
|
||||
};
|
||||
}
|
||||
@@ -1383,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);
|
||||
}
|
||||
@@ -1432,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),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1452,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,
|
||||
});
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1520,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(
|
||||
@@ -1601,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)
|
||||
@@ -1717,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}
|
||||
*/
|
||||
|
||||
@@ -1780,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;
|
||||
@@ -1791,8 +1943,10 @@ export class StyleManager extends ShellFacade {
|
||||
this._recording.destroy();
|
||||
this._mobileShell?.destroy();
|
||||
this._panelNavigation?.destroy();
|
||||
this._wildlifeSightingCard?.destroy();
|
||||
this._ui.destroy();
|
||||
this._panelChrome.destroy();
|
||||
this._offPlacePacks();
|
||||
this._feedback.destroy();
|
||||
|
||||
this._displayBindings.destroy();
|
||||
@@ -1811,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();
|
||||
|
||||
@@ -10,7 +10,8 @@ const STYLE_KEYS = Object.freeze({
|
||||
/**
|
||||
* Bind the application's existing bubbling keyboard shortcuts.
|
||||
* Capture-phase surfaces keep first refusal. The caller owns each action and
|
||||
* persistence; form controls keep native typing except for Escape.
|
||||
* persistence; form controls keep native typing except for Escape, and a key
|
||||
* held with Cmd, Ctrl or Alt is left to the browser.
|
||||
* @param {object} options
|
||||
* @param {Document} options.documentRef Keyboard event target.
|
||||
* @param {HTMLElement} options.searchInput Additional editing target.
|
||||
@@ -27,6 +28,13 @@ export function bindApplicationShortcuts({
|
||||
event.target?.matches?.('select, input, textarea') ||
|
||||
event.target === searchInput;
|
||||
if (isFormControl && event.key !== 'Escape') return;
|
||||
// Cmd+C, Ctrl+F, Cmd+1 and the like belong to the browser and the system.
|
||||
// Shift is not a chord here: Shift+C is still C.
|
||||
if (
|
||||
(event.metaKey || event.ctrlKey || event.altKey) &&
|
||||
event.key !== 'Escape'
|
||||
)
|
||||
return;
|
||||
|
||||
if (STYLE_KEYS[event.key]) actions.setStyle(STYLE_KEYS[event.key]);
|
||||
if (event.key === 'Escape') actions.dismissSearch();
|
||||
|
||||
@@ -245,3 +245,73 @@ test('a repaint that leaves focus outside the panel does not pull it back', asyn
|
||||
'an empty cohort renders no list',
|
||||
);
|
||||
});
|
||||
|
||||
const photo = (extra = {}) => ({
|
||||
src: 'https://t.plnspttrs.net/1/abc123_280.jpg',
|
||||
width: 280,
|
||||
height: 186,
|
||||
link: 'https://www.planespotters.net/photo/1/n123ab',
|
||||
credit: 'Photo © Jane Doe',
|
||||
...extra,
|
||||
});
|
||||
|
||||
test('a tracked flight’s photo shows under its name, credited and linked to its page', async (t) => {
|
||||
const { panel, publish } = fixture(t);
|
||||
await publish({ ...results(), photo: photo() });
|
||||
const root = panel();
|
||||
const link = root.querySelector('a.military-awareness-photo');
|
||||
assert.ok(link, 'the photo renders');
|
||||
assert.equal(
|
||||
root.querySelector('.military-awareness-subject').nextElementSibling,
|
||||
link,
|
||||
'directly under the subject line',
|
||||
);
|
||||
assert.equal(link.getAttribute('href'), photo().link);
|
||||
assert.equal(link.getAttribute('target'), '_blank');
|
||||
assert.equal(link.getAttribute('rel'), 'noopener');
|
||||
const img = link.querySelector('img');
|
||||
assert.equal(img.getAttribute('src'), photo().src);
|
||||
assert.equal(img.getAttribute('alt'), '');
|
||||
assert.equal(img.getAttribute('width'), '280');
|
||||
assert.equal(img.getAttribute('height'), '186');
|
||||
assert.equal(link.querySelector('small').textContent, 'Photo © Jane Doe');
|
||||
});
|
||||
|
||||
test('no photo renders without one', async (t) => {
|
||||
const { panel, publish } = fixture(t);
|
||||
await publish({ ...results(), photo: null });
|
||||
assert.equal(panel().querySelector('.military-awareness-photo') === null, true);
|
||||
});
|
||||
|
||||
test('a photo whose image fails to load is hidden until another arrives', async (t) => {
|
||||
const { panel, publish } = fixture(t);
|
||||
await publish({ ...results(), photo: photo() });
|
||||
panel()
|
||||
.querySelector('.military-awareness-photo img')
|
||||
.dispatchEvent(new Event('error'));
|
||||
await nextTick();
|
||||
assert.equal(panel().querySelector('.military-awareness-photo') === null, true);
|
||||
// A repaint with the same photo keeps it hidden.
|
||||
await publish({ ...results({ previousDisabled: false }), photo: photo() });
|
||||
assert.equal(panel().querySelector('.military-awareness-photo') === null, true);
|
||||
// Another plane's photo shows.
|
||||
const next = photo({ src: 'https://t.plnspttrs.net/2/def456_280.jpg' });
|
||||
await publish({ ...results(), photo: next });
|
||||
assert.equal(
|
||||
panel().querySelector('.military-awareness-photo img').getAttribute('src'),
|
||||
next.src,
|
||||
);
|
||||
});
|
||||
|
||||
test('a late error from a previous photo’s image does not hide the current one', async (t) => {
|
||||
const { panel, publish } = fixture(t);
|
||||
const previous = photo();
|
||||
const current = photo({ src: 'https://t.plnspttrs.net/2/def456_280.jpg' });
|
||||
await publish({ ...results(), photo: current });
|
||||
// The error belongs to the image that failed: here, one still on the old src.
|
||||
const img = panel().querySelector('.military-awareness-photo img');
|
||||
img.setAttribute('src', previous.src);
|
||||
img.dispatchEvent(new Event('error'));
|
||||
await nextTick();
|
||||
assert.ok(panel().querySelector('.military-awareness-photo'));
|
||||
});
|
||||
+121
-126
@@ -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));
|
||||
}
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -23,6 +23,7 @@ import { useCctvStore } from './stores/cctv.js';
|
||||
import { useStatusStore } from './stores/status.js';
|
||||
import { applicationPinia } from './vueRuntime.js';
|
||||
import { onLocaleChange } from '../i18n/index.js';
|
||||
import { createQuebecCctvOverlay } from './quebecCctvOverlay.js';
|
||||
|
||||
/**
|
||||
* Own camera-panel interaction and presentation; receive the camera port and
|
||||
@@ -34,6 +35,7 @@ export class CctvControls {
|
||||
constructor({
|
||||
elements,
|
||||
cctv,
|
||||
viewer = null,
|
||||
actions,
|
||||
store = useCctvStore(applicationPinia()),
|
||||
statusStore = useStatusStore(applicationPinia()),
|
||||
@@ -42,14 +44,17 @@ export class CctvControls {
|
||||
this.store = store;
|
||||
this.statusStore = statusStore;
|
||||
this.cctv = cctv;
|
||||
this._quebecCctvOverlay = createQuebecCctvOverlay(viewer);
|
||||
this.actions = actions;
|
||||
this.destroyed = false;
|
||||
this.listeners = new AbortController();
|
||||
this._cctvUnsubscribe = null;
|
||||
this._cctvState = null;
|
||||
this._lastQuebecSelectionRevision = null;
|
||||
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.
|
||||
@@ -146,6 +151,7 @@ export class CctvControls {
|
||||
if (this.destroyed) return;
|
||||
this.destroyed = true;
|
||||
this._offLocale();
|
||||
this._quebecCctvOverlay?.dispose();
|
||||
this._cctvVideoSurface?.stop();
|
||||
this._videoVisibilityObserver?.disconnect();
|
||||
this._actionGeneration++;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { test } from 'node:test';
|
||||
import { CctvControls } from './cctvControls.js';
|
||||
import { CCTV_FRAME_DECODE_WAIT_MS } from './cctvFrames.js';
|
||||
|
||||
function element() {
|
||||
const classes = new Set();
|
||||
@@ -59,6 +60,50 @@ test('a late image completion cannot replace a newer camera preview', (t) => {
|
||||
assert.equal(controls._frame.cameraId, 'b');
|
||||
});
|
||||
|
||||
test('a camera frame settles once decoded, and a stale decode cannot land', async (t) => {
|
||||
const { controls, requests } = fixture(t);
|
||||
const decodes = [];
|
||||
const queue = (src, id) => {
|
||||
controls._queueCctvFrame(src, id, true);
|
||||
const request = requests.at(-1);
|
||||
request.decode = () =>
|
||||
new Promise((resolve) => decodes.push({ src, resolve }));
|
||||
return request;
|
||||
};
|
||||
const first = queue('first.jpg', 'a');
|
||||
first.onload();
|
||||
assert.equal(controls._frame.hasFrame, false);
|
||||
const second = queue('second.jpg', 'b');
|
||||
second.onload();
|
||||
decodes[1].resolve();
|
||||
await Promise.resolve();
|
||||
decodes[0].resolve();
|
||||
await Promise.resolve();
|
||||
assert.equal(controls._frame.src, 'second.jpg');
|
||||
assert.equal(controls._frame.cameraId, 'b');
|
||||
assert.equal(controls._frame.hasFrame, true);
|
||||
});
|
||||
|
||||
test('a loaded frame shows when its decode rejects or never settles', async (t) => {
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
const { controls, requests } = fixture(t);
|
||||
controls._queueCctvFrame('broken.jpg', 'a', true);
|
||||
requests[0].decode = () => Promise.reject(new Error('EncodingError'));
|
||||
requests[0].onload();
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
assert.equal(controls._frame.src, 'broken.jpg');
|
||||
assert.equal(controls._frame.hasFrame, true);
|
||||
|
||||
controls._queueCctvFrame('hidden.jpg', 'b', true);
|
||||
requests[1].decode = () => new Promise(() => {});
|
||||
requests[1].onload();
|
||||
assert.equal(controls._frame.hasFrame, false);
|
||||
t.mock.timers.tick(CCTV_FRAME_DECODE_WAIT_MS);
|
||||
assert.equal(controls._frame.src, 'hidden.jpg');
|
||||
assert.equal(controls._frame.hasFrame, true);
|
||||
});
|
||||
|
||||
test('failed refresh preserves settled pixels, but changing cameras clears them', (t) => {
|
||||
const { controls, requests } = fixture(t);
|
||||
controls._queueCctvFrame('first.jpg', 'a', true);
|
||||
|
||||
+25
-1
@@ -77,6 +77,9 @@ export function cctvSourceLabelText(label) {
|
||||
return SOURCE_LABELS[text] ? t(SOURCE_LABELS[text]) : text;
|
||||
}
|
||||
|
||||
/** Longest wait for a loaded frame's decode before it is shown anyway. */
|
||||
export const CCTV_FRAME_DECODE_WAIT_MS = 1000;
|
||||
|
||||
/** The preview before any frame: nothing requested, nothing shown. */
|
||||
export const EMPTY_CCTV_FRAME = Object.freeze({
|
||||
cameraId: '',
|
||||
@@ -127,7 +130,28 @@ export function _queueCctvFrame(src, cameraId, cameraChanged) {
|
||||
|
||||
const preloader = new Image();
|
||||
this._cctvFramePreloader = preloader;
|
||||
preloader.onload = () => this._settleCctvFrame(token, src, true);
|
||||
// Settle once the image is decoded, not merely loaded: the panel's <img>
|
||||
// then paints the frame the moment it takes the src, instead of showing
|
||||
// its empty box for the decode.
|
||||
// A decode that rejects after a load still has drawable data, as it was
|
||||
// before decoding was awaited. A decode that never settles (a hidden tab may
|
||||
// hold it until the page draws) shows the loaded frame after
|
||||
// CCTV_FRAME_DECODE_WAIT_MS rather than leaving the preview loading.
|
||||
preloader.onload = () => {
|
||||
if (typeof preloader.decode !== 'function') {
|
||||
this._settleCctvFrame(token, src, true);
|
||||
return;
|
||||
}
|
||||
let settled = false;
|
||||
const settle = () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
this._settleCctvFrame(token, src, true);
|
||||
};
|
||||
const timer = setTimeout(settle, CCTV_FRAME_DECODE_WAIT_MS);
|
||||
preloader.decode().then(settle, settle);
|
||||
};
|
||||
preloader.onerror = () => this._settleCctvFrame(token, src, false);
|
||||
preloader.src = src;
|
||||
}
|
||||
|
||||
@@ -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 /);
|
||||
});
|
||||
@@ -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',
|
||||
);
|
||||
@@ -154,6 +156,20 @@ export function _renderCctvState(state) {
|
||||
const enabled = !!state?.enabled && !!this.actions.isEnabled();
|
||||
const activeId = state?.activeCameraId || '';
|
||||
const activeCamera = state?.activeCamera || null;
|
||||
const selectionRevision = Number(state?.activeCameraReselection);
|
||||
const reselected =
|
||||
this._lastQuebecSelectionRevision !== null &&
|
||||
Number.isFinite(selectionRevision) &&
|
||||
selectionRevision !== this._lastQuebecSelectionRevision;
|
||||
this._lastQuebecSelectionRevision = Number.isFinite(selectionRevision)
|
||||
? selectionRevision
|
||||
: null;
|
||||
const isQuebecCamera =
|
||||
enabled && activeCamera?.sourceKind?.startsWith('quebec-');
|
||||
this._quebecCctvOverlay?.setCamera(isQuebecCamera ? activeCamera : null, {
|
||||
reselected,
|
||||
});
|
||||
if (this._cctvFrameWrap) this._cctvFrameWrap.hidden = Boolean(isQuebecCamera);
|
||||
|
||||
// Auto-expand the panel when the active camera CHANGES to a new non-null
|
||||
// id while the layer is enabled. Covers click-on-globe, panel controls,
|
||||
@@ -174,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);
|
||||
|
||||
@@ -241,7 +271,8 @@ export function _renderCctvState(state) {
|
||||
|
||||
this.store.publish(presentCctvPanel(state, enabled));
|
||||
|
||||
const liveIntent = enabled && !!activeCamera?.isVideo;
|
||||
const liveIntent =
|
||||
enabled && !!activeCamera?.isVideo && !activeCamera?.browserMediaUrl;
|
||||
this.store.setLive(liveIntent);
|
||||
if (this._cctvVideo) {
|
||||
const visible =
|
||||
@@ -261,8 +292,9 @@ export function _renderCctvState(state) {
|
||||
}
|
||||
|
||||
if (this._cctvFrame && !liveIntent) {
|
||||
const nextSrc = enabled ? activeCamera?.frameUrl : null;
|
||||
const nextCameraId = enabled ? activeCamera?.id || '' : '';
|
||||
const nextSrc = enabled && !isQuebecCamera ? activeCamera?.frameUrl : null;
|
||||
const nextCameraId =
|
||||
enabled && !isQuebecCamera ? activeCamera?.id || '' : '';
|
||||
const cameraChanged = this._frame.cameraId !== nextCameraId;
|
||||
const frameLoading = this._frame.loading;
|
||||
// A same-camera refresh waits for the current image to settle. Replacing
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
// src/ui/cockpitBodyClasses.test.mjs — the classes the Cockpit puts on
|
||||
// <body> must not also name an element's rule. A bare `.name { … }` written
|
||||
// for a panel matches <body> the moment <body> carries `name`, and its
|
||||
// pointer-events, position and overflow then apply to the whole page (a
|
||||
// shared `cockpit-orbital` once made every click in orbit fall through).
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync, readdirSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const UI_ROOT = fileURLToPath(new URL('.', import.meta.url));
|
||||
const SRC_ROOT = path.resolve(UI_ROOT, '..');
|
||||
const CONTROLLER = path.join(UI_ROOT, 'cockpitTrackingController.js');
|
||||
|
||||
/** Every stylesheet the app ships. */
|
||||
function stylesheets(directory = SRC_ROOT) {
|
||||
const files = [];
|
||||
for (const entry of readdirSync(directory, { withFileTypes: true })) {
|
||||
const absolute = path.join(directory, entry.name);
|
||||
if (entry.isDirectory()) files.push(...stylesheets(absolute));
|
||||
else if (entry.isFile() && entry.name.endsWith('.css'))
|
||||
files.push(absolute);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
/** A selector list split on its top-level commas, not those in `:not(a, b)`. */
|
||||
function splitSelectorList(list) {
|
||||
const parts = [];
|
||||
let depth = 0;
|
||||
let start = 0;
|
||||
for (let i = 0; i < list.length; i += 1) {
|
||||
if (list[i] === '(') depth += 1;
|
||||
else if (list[i] === ')') depth -= 1;
|
||||
else if (list[i] === ',' && depth === 0) {
|
||||
parts.push(list.slice(start, i));
|
||||
start = i + 1;
|
||||
}
|
||||
}
|
||||
parts.push(list.slice(start));
|
||||
return parts;
|
||||
}
|
||||
|
||||
/** The classes the tracking controller adds to <body>. */
|
||||
function cockpitBodyClasses() {
|
||||
const source = readFileSync(CONTROLLER, 'utf8');
|
||||
const names = [
|
||||
...source.matchAll(/body\.classList\.add\(\s*'([a-z0-9-]+)'/g),
|
||||
].map((match) => match[1]);
|
||||
return [...new Set(names)];
|
||||
}
|
||||
|
||||
test('the Cockpit adds its subject classes to <body>', () => {
|
||||
const classes = cockpitBodyClasses();
|
||||
for (const name of ['cockpit-mode', 'cockpit-bridge', 'cockpit-orbit']) {
|
||||
assert.ok(classes.includes(name), `${name} is not added to <body>`);
|
||||
}
|
||||
});
|
||||
|
||||
test('no stylesheet rule matches a Cockpit body class on another element', () => {
|
||||
const offenders = [];
|
||||
for (const name of cockpitBodyClasses()) {
|
||||
// `.name` as a whole class token, not as `.name-suffix`.
|
||||
const token = new RegExp(`\\.${name}(?![\\w-])`);
|
||||
for (const file of stylesheets()) {
|
||||
const css = readFileSync(file, 'utf8').replace(/\/\*[\s\S]*?\*\//g, '');
|
||||
for (const [, selectors] of css.matchAll(/([^{}]+)\{/g)) {
|
||||
for (const selector of splitSelectorList(selectors)) {
|
||||
// Prettier wraps long `:not(\n .name\n)` arguments; unwrap them.
|
||||
const compound = selector
|
||||
.trim()
|
||||
.replace(/\(\s+/g, '(')
|
||||
.replace(/\s+\)/g, ')');
|
||||
if (!token.test(compound)) continue;
|
||||
// Allowed only on <body> itself: `body.name` or `body:not(.name)`.
|
||||
const onBody = new RegExp(
|
||||
`(^|[\\s>+~])body[^\\s>+~]*\\.${name}(?![\\w-])`,
|
||||
);
|
||||
if (onBody.test(compound)) continue;
|
||||
offenders.push(`${path.relative(SRC_ROOT, file)}: ${compound}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert.deepEqual(
|
||||
offenders,
|
||||
[],
|
||||
'Selectors that match a Cockpit body class without `body.`: ' +
|
||||
offenders.join('; '),
|
||||
);
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,9 +1,29 @@
|
||||
/**
|
||||
* The Cockpit briefing's pages and the state it starts in. It needs only the
|
||||
* i18n module, so the controller and the view can both read it.
|
||||
* i18n module and the regional-news window, so the controller and the view
|
||||
* can both read it.
|
||||
*/
|
||||
import { REGIONAL_NEWS_WINDOW_HOURS } from '../data/regionalNewsWindow.js';
|
||||
import { msg, t } from '../i18n/index.js';
|
||||
|
||||
// i18n-ignore: provider name
|
||||
/** The news feed named before any briefing has answered. */
|
||||
export const DEFAULT_NEWS_SOURCE = 'GOOGLE NEWS RSS';
|
||||
|
||||
/**
|
||||
* The Regional News footer for a fresh, empty or unavailable list: the feed
|
||||
* and the window its articles are held to.
|
||||
* @param {string} [source]
|
||||
* @param {number} [hours]
|
||||
* @returns {string}
|
||||
*/
|
||||
export function newsWindowFooter(
|
||||
source = DEFAULT_NEWS_SOURCE,
|
||||
hours = REGIONAL_NEWS_WINDOW_HOURS,
|
||||
) {
|
||||
return t('{source} · LAST {hours} H', { source, hours });
|
||||
}
|
||||
|
||||
export const COCKPIT_BRIEF_PAGES = [
|
||||
{
|
||||
id: 'signals',
|
||||
@@ -15,8 +35,7 @@ export const COCKPIT_BRIEF_PAGES = [
|
||||
id: 'news',
|
||||
kickerKey: msg('REGIONAL NEWS'),
|
||||
subtitleKey: msg('LATEST LOCATION-MATCHED REPORTING'),
|
||||
sourceKey: msg('{source} · LOCATION QUERY · RECENT'),
|
||||
sourceName: 'GOOGLE NEWS RSS', // i18n-ignore: provider name
|
||||
// The news footer comes from the news state (`news.footer`), not here.
|
||||
},
|
||||
{
|
||||
id: 'local',
|
||||
@@ -60,6 +79,7 @@ export function createBriefState() {
|
||||
statusHidden: false,
|
||||
state: null,
|
||||
status: t('ACQUIRING REGIONAL NEWS'),
|
||||
footer: newsWindowFooter(),
|
||||
articles: [],
|
||||
},
|
||||
local: {
|
||||
|
||||
+115
-26
@@ -12,7 +12,14 @@ import {
|
||||
COCKPIT_BRIEF_PAGES,
|
||||
CYCLE_HELP_KEYS,
|
||||
createBriefState,
|
||||
newsWindowFooter,
|
||||
} from './cockpitBriefPages.js';
|
||||
import {
|
||||
recentRegionalArticles,
|
||||
regionalNewsWindowHours,
|
||||
} from '../data/regionalNewsWindow.js';
|
||||
|
||||
const NEWS_ROWS = 4;
|
||||
|
||||
// regionalModel.weatherCodeLabel is shared with node code and returns
|
||||
// English; translate it here.
|
||||
@@ -52,9 +59,13 @@ export function showBriefPage(index, { manual = false } = {}) {
|
||||
kicker: t(page.kickerKey),
|
||||
subtitle: t(page.subtitleKey),
|
||||
position: `${this.briefPageIndex + 1} / ${count}`,
|
||||
source: page.sourceKey
|
||||
? t(page.sourceKey, { source: page.sourceName })
|
||||
: page.source,
|
||||
// The news footer follows the news state, so it survives page changes.
|
||||
source:
|
||||
page.id === 'news'
|
||||
? this.brief.news.footer
|
||||
: page.sourceKey
|
||||
? t(page.sourceKey)
|
||||
: page.source,
|
||||
});
|
||||
this.publishBriefView();
|
||||
if (manual && this.briefAutoRotateEnabled)
|
||||
@@ -85,12 +96,9 @@ export function relocalizeBrief() {
|
||||
Object.assign(this.brief, cycleWords(this.briefAutoRotateEnabled));
|
||||
this.showBriefPage(this.briefPageIndex);
|
||||
if (this.regionalBrief)
|
||||
this.renderRegionalBrief(this.regionalBrief, this.lastAircraftInfo);
|
||||
this.renderRegionalBrief(this.regionalBrief, this.lastSubjectInfo);
|
||||
else if (this.brief.news.state)
|
||||
this.renderRegionalBriefStatus(
|
||||
this.brief.news.state,
|
||||
this.lastAircraftInfo,
|
||||
);
|
||||
this.renderRegionalBriefStatus(this.brief.news.state, this.lastSubjectInfo);
|
||||
}
|
||||
|
||||
export function setBriefAutoRotate(enabled) {
|
||||
@@ -156,7 +164,7 @@ export function maybeRefreshRegionalBrief(info) {
|
||||
!Number.isFinite(info.longitude)
|
||||
)
|
||||
return;
|
||||
const subjectId = `${info.layerId || 'aircraft'}:${info.icao24 || 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;
|
||||
@@ -179,6 +187,13 @@ export function maybeRefreshRegionalBrief(info) {
|
||||
)
|
||||
return;
|
||||
|
||||
// The brief held stands in after a failed refresh only near where its news
|
||||
// was read; past the refresh distance it is another place's.
|
||||
const previous =
|
||||
this.services.regionalDistanceM(this.regionalBriefPoint, point) <
|
||||
COCKPIT_REGIONAL_REFRESH_DISTANCE_M
|
||||
? this.regionalBrief
|
||||
: null;
|
||||
this.regionalBriefAnchor = point;
|
||||
this.regionalBriefFetchedAt = Date.now();
|
||||
const controller = new AbortController();
|
||||
@@ -196,8 +211,9 @@ export function maybeRefreshRegionalBrief(info) {
|
||||
subjectId !== this.regionalBriefSubjectId
|
||||
)
|
||||
return;
|
||||
this.regionalBrief = payload;
|
||||
this.renderRegionalBrief(payload, info);
|
||||
this.regionalBrief = withCachedNews(payload, previous);
|
||||
if (this.regionalBrief === payload) this.regionalBriefPoint = point;
|
||||
this.renderRegionalBrief(this.regionalBrief, info);
|
||||
})
|
||||
.catch((error) => {
|
||||
if (
|
||||
@@ -206,7 +222,14 @@ export function maybeRefreshRegionalBrief(info) {
|
||||
requestToken === this.regionalBriefRequestToken &&
|
||||
subjectId === this.regionalBriefSubjectId
|
||||
) {
|
||||
this.renderRegionalBriefStatus('unavailable', info);
|
||||
if (previous) {
|
||||
this.regionalBrief = cachedNews(previous, previous);
|
||||
this.renderRegionalBrief(this.regionalBrief, info);
|
||||
} else {
|
||||
// Another place's brief: not to come back with a language change.
|
||||
this.regionalBrief = null;
|
||||
this.renderRegionalBriefStatus('unavailable', info);
|
||||
}
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
@@ -215,6 +238,75 @@ export function maybeRefreshRegionalBrief(info) {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A brief whose news comes from `previous` after a refresh that brought none:
|
||||
* the earlier articles stay, marked `cached` so they are labelled as such.
|
||||
* @param {object} payload The brief to keep everything else from.
|
||||
* @param {object} previous The last brief rendered for this subject.
|
||||
*/
|
||||
function cachedNews(payload, previous) {
|
||||
return {
|
||||
...payload,
|
||||
newsStatus: 'cached',
|
||||
newsSource: previous.newsSource,
|
||||
newsWindowHours: previous.newsWindowHours,
|
||||
newsFetchedAt: previous.newsFetchedAt ?? previous.retrievedAt ?? null,
|
||||
articles: previous.articles,
|
||||
};
|
||||
}
|
||||
|
||||
// A refresh whose news read failed keeps the articles from before it.
|
||||
function withCachedNews(payload, previous) {
|
||||
return previous && payload?.newsStatus === 'unavailable'
|
||||
? cachedNews(payload, previous)
|
||||
: payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Regional News state a brief presents. `ready` and `cached` have rows
|
||||
* inside the window; `cached` is a refresh that failed (a client-side failure,
|
||||
* or the local proxy's `stale` answer). `empty` is a source that answered with
|
||||
* nothing in the window; anything else is `unavailable`.
|
||||
* @returns {{state: string, status: string, footer: string, articles: object[]}}
|
||||
*/
|
||||
function regionalNewsView(payload) {
|
||||
const hours = regionalNewsWindowHours(payload?.newsWindowHours);
|
||||
// Old caches and the local path are held to the window here too.
|
||||
const articles = recentRegionalArticles(payload?.articles, {
|
||||
windowHours: hours,
|
||||
limit: NEWS_ROWS,
|
||||
});
|
||||
const source = String(
|
||||
payload?.newsSource || t('REGIONAL NEWS'),
|
||||
).toUpperCase();
|
||||
const refreshFailed =
|
||||
payload?.newsStatus === 'cached' || payload?.status === 'stale';
|
||||
if (articles.length && refreshFailed)
|
||||
return {
|
||||
state: 'cached',
|
||||
status: t('CACHED · REFRESH FAILED'),
|
||||
footer: t('{source} · CACHED {age}', {
|
||||
source,
|
||||
age: formatCockpitBriefAge(
|
||||
payload?.newsFetchedAt ?? payload?.retrievedAt,
|
||||
),
|
||||
}),
|
||||
articles,
|
||||
};
|
||||
const answered =
|
||||
!refreshFailed && ['ready', 'empty'].includes(payload?.newsStatus);
|
||||
return {
|
||||
state: articles.length ? 'ready' : answered ? 'empty' : 'unavailable',
|
||||
status: articles.length
|
||||
? ''
|
||||
: answered
|
||||
? t('NO NEWS IN THE LAST {hours} H', { hours })
|
||||
: t('REGIONAL NEWS UNAVAILABLE'),
|
||||
footer: newsWindowFooter(source, hours),
|
||||
articles,
|
||||
};
|
||||
}
|
||||
|
||||
export function renderRegionalBriefStatus(status, info) {
|
||||
const { news, local } = this.brief;
|
||||
news.statusHidden = false;
|
||||
@@ -223,7 +315,10 @@ export function renderRegionalBriefStatus(status, info) {
|
||||
status === 'loading'
|
||||
? t('ACQUIRING REGIONAL NEWS')
|
||||
: t('REGIONAL NEWS UNAVAILABLE');
|
||||
if (status === 'unavailable') news.articles = [];
|
||||
news.footer = newsWindowFooter();
|
||||
// Only called with no brief for this subject: any rows are another's.
|
||||
news.articles = [];
|
||||
if (this.briefPageIndex === 1) this.brief.source = news.footer;
|
||||
if (status === 'loading') local.place = t('RESOLVING REGION');
|
||||
if (status === 'unavailable') local.place = t('REGION UNAVAILABLE');
|
||||
local.coordinates = localCoordinates(info);
|
||||
@@ -231,7 +326,7 @@ export function renderRegionalBriefStatus(status, info) {
|
||||
}
|
||||
|
||||
export function renderRegionalBrief(payload, info) {
|
||||
const articles = Array.isArray(payload?.articles) ? payload.articles : [];
|
||||
const { state, status, footer, articles } = regionalNewsView(payload);
|
||||
const seen = new Map();
|
||||
const storyKey = (url) => {
|
||||
const count = seen.get(url) ?? 0;
|
||||
@@ -244,13 +339,11 @@ export function renderRegionalBrief(payload, info) {
|
||||
const placeLabel =
|
||||
payload?.place?.label || payload?.place?.country || t('REGION UNAVAILABLE');
|
||||
this.brief.news = {
|
||||
statusHidden: articles.length > 0,
|
||||
state: payload?.newsStatus || 'unavailable',
|
||||
status:
|
||||
payload?.newsStatus === 'empty'
|
||||
? t('NO RECENT LOCATION MATCHES')
|
||||
: t('REGIONAL NEWS UNAVAILABLE'),
|
||||
articles: articles.slice(0, 4).map((article) => ({
|
||||
statusHidden: state === 'ready',
|
||||
state,
|
||||
status,
|
||||
footer,
|
||||
articles: articles.map((article) => ({
|
||||
// A row keeps its node, and so its focus, only for the same story.
|
||||
key: storyKey(article.url),
|
||||
url: article.url,
|
||||
@@ -284,11 +377,7 @@ export function renderRegionalBrief(payload, info) {
|
||||
: '—',
|
||||
};
|
||||
this.brief.regionalStatus = payload?.status || 'partial';
|
||||
if (this.briefPageIndex === 1) {
|
||||
this.brief.source = t('{source} · LOCATION QUERY', {
|
||||
source: String(payload?.newsSource || t('REGIONAL NEWS')).toUpperCase(),
|
||||
});
|
||||
}
|
||||
if (this.briefPageIndex === 1) this.brief.source = footer;
|
||||
this.publishBriefView();
|
||||
this.scheduleContextLayout();
|
||||
}
|
||||
+365
-18
@@ -3,11 +3,14 @@
|
||||
import '../testSupport/registerDom.mjs';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { createPinia } from 'pinia';
|
||||
import { createApp, nextTick } from 'vue';
|
||||
import { setLocale } from '../i18n/index.js';
|
||||
import { createBriefState } from './cockpitBriefPages.js';
|
||||
import {
|
||||
maybeRefreshRegionalBrief,
|
||||
publishBriefView,
|
||||
renderRegionalBrief,
|
||||
renderRegionalBriefStatus,
|
||||
@@ -88,10 +91,7 @@ test('pages, the cycle toggle and the source follow the controller', async (t) =
|
||||
await nextTick();
|
||||
assert.equal(text('#cockpit-brief-kicker'), 'REGIONAL NEWS');
|
||||
assert.equal(text('#cockpit-brief-position'), '2 / 3');
|
||||
assert.equal(
|
||||
text('#cockpit-brief-source'),
|
||||
'GOOGLE NEWS RSS · LOCATION QUERY · RECENT',
|
||||
);
|
||||
assert.equal(text('#cockpit-brief-source'), 'GOOGLE NEWS RSS · LAST 24 H');
|
||||
assert.deepEqual(visiblePages(), ['news']);
|
||||
assert.deepEqual(current(), ['false', 'true', 'false']);
|
||||
assert.equal($('#cockpit-signal-stream').dataset.briefPage, 'news');
|
||||
@@ -129,7 +129,8 @@ test('regional news and local conditions render what the region returned', async
|
||||
url: `https://example.com/${index}`,
|
||||
title: `Story ${index}`,
|
||||
domain: 'example.com',
|
||||
publishedAt: new Date().toISOString(),
|
||||
// Newest first is the shown order, so Story 0 is the newest.
|
||||
publishedAt: new Date(Date.now() - index * 60_000).toISOString(),
|
||||
})),
|
||||
weather: {
|
||||
temperatureC: 21.6,
|
||||
@@ -159,7 +160,7 @@ test('regional news and local conditions render what the region returned', async
|
||||
assert.equal(text('#cockpit-local-condition'), 'RAIN');
|
||||
assert.equal(text('#cockpit-local-cloud'), 'CLOUD 40%');
|
||||
assert.equal(text('#cockpit-local-precipitation'), '1.3');
|
||||
assert.equal(text('#cockpit-brief-source'), 'WIRE · LOCATION QUERY');
|
||||
assert.equal(text('#cockpit-brief-source'), 'WIRE · LAST 24 H');
|
||||
assert.equal($('#cockpit-signal-stream').dataset.regionalStatus, 'ok');
|
||||
renderRegionalBriefStatus.call(owner, 'unavailable', {});
|
||||
await nextTick();
|
||||
@@ -170,11 +171,15 @@ test('regional news and local conditions render what the region returned', async
|
||||
assert.equal(text('#cockpit-local-coordinates'), 'POSITION UNAVAILABLE');
|
||||
});
|
||||
|
||||
// One time for every story: newest-first order then keeps the order a test
|
||||
// lists them in. A clock read per story could tick between two of them and
|
||||
// swap them.
|
||||
const STORY_PUBLISHED_AT = new Date().toISOString();
|
||||
const story = (id, url = `https://example.com/${id}`) => ({
|
||||
url,
|
||||
title: `Story ${id}`,
|
||||
domain: 'example.com',
|
||||
publishedAt: new Date().toISOString(),
|
||||
publishedAt: STORY_PUBLISHED_AT,
|
||||
});
|
||||
|
||||
test('a refreshed news list keeps a focused story on its own link', async (t) => {
|
||||
@@ -210,26 +215,293 @@ test('a refreshed news list keeps a focused story on its own link', async (t) =>
|
||||
assert.equal($('#cockpit-news-list').textContent.includes('Story y'), true);
|
||||
});
|
||||
|
||||
test('the news source names the feed only while it is current on page 2', async (t) => {
|
||||
// This contract changed on purpose: the footer used to fall back to a
|
||||
// static "· RECENT" on every page change, which promised nothing. It now
|
||||
// follows the news state and names the window it holds articles to.
|
||||
test('the news footer follows the news state across page changes, not a static RECENT', async (t) => {
|
||||
const { text, owner } = fixture(t);
|
||||
showBriefPage.call(owner, 1);
|
||||
renderRegionalBrief.call(owner, { newsSource: 'wire', articles: [] }, INFO);
|
||||
renderRegionalBrief.call(
|
||||
owner,
|
||||
{
|
||||
newsStatus: 'ready',
|
||||
newsSource: 'wire',
|
||||
newsWindowHours: 24,
|
||||
articles: [story('a')],
|
||||
},
|
||||
INFO,
|
||||
);
|
||||
await nextTick();
|
||||
assert.equal(text('#cockpit-brief-source'), 'WIRE · LOCATION QUERY');
|
||||
assert.equal(text('#cockpit-brief-source'), 'WIRE · LAST 24 H');
|
||||
showBriefPage.call(owner, 2);
|
||||
showBriefPage.call(owner, 1);
|
||||
await nextTick();
|
||||
assert.equal(text('#cockpit-brief-source'), 'WIRE · LAST 24 H');
|
||||
showBriefPage.call(owner, 0);
|
||||
renderRegionalBrief.call(
|
||||
owner,
|
||||
{
|
||||
newsStatus: 'ready',
|
||||
newsSource: 'wire',
|
||||
newsWindowHours: 12,
|
||||
articles: [story('a')],
|
||||
},
|
||||
INFO,
|
||||
);
|
||||
await nextTick();
|
||||
// Off page 2 the footer is the current page's.
|
||||
assert.equal(
|
||||
text('#cockpit-brief-source'),
|
||||
'SOURCE-BACKED EVENTS · NO SYNTHETIC NEWS',
|
||||
);
|
||||
showBriefPage.call(owner, 1);
|
||||
await nextTick();
|
||||
assert.equal(text('#cockpit-brief-source'), 'WIRE · LAST 12 H');
|
||||
});
|
||||
|
||||
test('the news banner is hidden by the stylesheet, not only by the attribute', async (t) => {
|
||||
// happy-dom applies no author CSS by itself, so `hidden` alone proves
|
||||
// nothing: `.cockpit-brief-status { display: grid }` used to beat it.
|
||||
const css = readFileSync(
|
||||
fileURLToPath(new URL('./styles/cockpit.css', import.meta.url)),
|
||||
'utf8',
|
||||
);
|
||||
assert.match(
|
||||
css,
|
||||
/\.cockpit-brief-status\[hidden\]\s*\{\s*display:\s*none;?\s*\}/,
|
||||
);
|
||||
const { $, owner } = fixture(t);
|
||||
const style = document.head.appendChild(document.createElement('style'));
|
||||
t.after(() => style.remove());
|
||||
style.textContent = css;
|
||||
showBriefPage.call(owner, 1);
|
||||
renderRegionalBrief.call(
|
||||
owner,
|
||||
{ newsStatus: 'ready', articles: [story('a')] },
|
||||
INFO,
|
||||
);
|
||||
await nextTick();
|
||||
const banner = $('#cockpit-news-status');
|
||||
assert.equal(banner.hidden, true);
|
||||
assert.equal(getComputedStyle(banner).display, 'none');
|
||||
renderRegionalBrief.call(owner, { newsStatus: 'empty', articles: [] }, INFO);
|
||||
await nextTick();
|
||||
assert.equal(getComputedStyle(banner).display, 'grid');
|
||||
});
|
||||
|
||||
const hoursAgo = (hours) =>
|
||||
new Date(Date.now() - hours * 3_600_000).toISOString();
|
||||
|
||||
test('ready, cached, empty and unavailable each label the news differently', async (t) => {
|
||||
const { $, text, owner } = fixture(t);
|
||||
showBriefPage.call(owner, 1);
|
||||
const rows = () =>
|
||||
[...document.querySelectorAll('#cockpit-news-list strong')].map(
|
||||
(row) => row.textContent,
|
||||
);
|
||||
const banner = () => ({
|
||||
hidden: $('#cockpit-news-status').hidden,
|
||||
state: $('#cockpit-news-status').dataset.state,
|
||||
text: text('#cockpit-news-status'),
|
||||
});
|
||||
const ready = {
|
||||
status: 'ready',
|
||||
newsStatus: 'ready',
|
||||
newsSource: 'Google News RSS',
|
||||
newsWindowHours: 24,
|
||||
newsFetchedAt: hoursAgo(0.5),
|
||||
articles: [story('a'), story('b')],
|
||||
};
|
||||
renderRegionalBrief.call(owner, ready, INFO);
|
||||
await nextTick();
|
||||
assert.equal(banner().hidden, true);
|
||||
assert.equal(banner().state, 'ready');
|
||||
assert.deepEqual(rows(), ['Story a', 'Story b']);
|
||||
assert.equal(text('#cockpit-brief-source'), 'GOOGLE NEWS RSS · LAST 24 H');
|
||||
|
||||
// The local proxy's stale answer is a refresh that failed.
|
||||
renderRegionalBrief.call(owner, { ...ready, status: 'stale' }, INFO);
|
||||
await nextTick();
|
||||
assert.deepEqual(banner(), {
|
||||
hidden: false,
|
||||
state: 'cached',
|
||||
text: 'CACHED · REFRESH FAILED',
|
||||
});
|
||||
assert.deepEqual(rows(), ['Story a', 'Story b']);
|
||||
assert.equal(
|
||||
text('#cockpit-brief-source'),
|
||||
'GOOGLE NEWS RSS · CACHED 30M AGO',
|
||||
);
|
||||
|
||||
renderRegionalBrief.call(
|
||||
owner,
|
||||
{
|
||||
...ready,
|
||||
newsStatus: 'empty',
|
||||
newsSource: 'Google News RSS',
|
||||
articles: [],
|
||||
},
|
||||
INFO,
|
||||
);
|
||||
await nextTick();
|
||||
assert.deepEqual(banner(), {
|
||||
hidden: false,
|
||||
state: 'empty',
|
||||
text: 'NO NEWS IN THE LAST 24 H',
|
||||
});
|
||||
assert.deepEqual(rows(), []);
|
||||
|
||||
renderRegionalBrief.call(
|
||||
owner,
|
||||
{ ...ready, newsStatus: 'unavailable', newsSource: null, articles: [] },
|
||||
INFO,
|
||||
);
|
||||
await nextTick();
|
||||
assert.deepEqual(banner(), {
|
||||
hidden: false,
|
||||
state: 'unavailable',
|
||||
text: 'REGIONAL NEWS UNAVAILABLE',
|
||||
});
|
||||
assert.deepEqual(rows(), []);
|
||||
});
|
||||
|
||||
test('articles outside the window are dropped even when a server sends them', async (t) => {
|
||||
const { $, text, owner } = fixture(t);
|
||||
showBriefPage.call(owner, 1);
|
||||
const dated = (id, publishedAt) => ({ ...story(id), publishedAt });
|
||||
// The reported case: 4, 104, 215 and 165 days old under "RECENT".
|
||||
renderRegionalBrief.call(
|
||||
owner,
|
||||
{
|
||||
newsStatus: 'ready',
|
||||
articles: [
|
||||
dated('old', hoursAgo(4 * 24)),
|
||||
dated('older', hoursAgo(104 * 24)),
|
||||
dated('undated', null),
|
||||
dated('one', hoursAgo(20)),
|
||||
dated('two', hoursAgo(2)),
|
||||
],
|
||||
},
|
||||
INFO,
|
||||
);
|
||||
await nextTick();
|
||||
assert.deepEqual(
|
||||
[...document.querySelectorAll('#cockpit-news-list strong')].map(
|
||||
(row) => row.textContent,
|
||||
),
|
||||
['Story two', 'Story one'],
|
||||
);
|
||||
assert.equal($('#cockpit-news-status').hidden, true);
|
||||
renderRegionalBrief.call(
|
||||
owner,
|
||||
{ newsStatus: 'ready', articles: [dated('old', hoursAgo(25))] },
|
||||
INFO,
|
||||
);
|
||||
await nextTick();
|
||||
assert.equal(document.querySelectorAll('#cockpit-news-list li').length, 0);
|
||||
assert.equal(text('#cockpit-news-status'), 'NO NEWS IN THE LAST 24 H');
|
||||
});
|
||||
|
||||
test('a failed refresh keeps the earlier articles as cached, and clears only when there are none', async (t) => {
|
||||
const { $, text, owner } = fixture(t);
|
||||
const answers = [];
|
||||
Object.assign(owner, {
|
||||
active: true,
|
||||
regionalBriefSubjectId: null,
|
||||
regionalBriefAbort: null,
|
||||
regionalBriefRequestToken: 0,
|
||||
regionalBriefFetchedAt: 0,
|
||||
regionalBrief: null,
|
||||
renderRegionalBrief,
|
||||
renderRegionalBriefStatus,
|
||||
});
|
||||
owner.services = {
|
||||
...owner.services,
|
||||
regionalDistanceM: () => 0,
|
||||
fetchRegionalBrief: () => answers.shift()(),
|
||||
};
|
||||
const refresh = async (answer, info = { ...INFO, icao24: 'abc123' }) => {
|
||||
answers.push(answer);
|
||||
owner.regionalBriefFetchedAt = 0;
|
||||
maybeRefreshRegionalBrief.call(owner, info);
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
await nextTick();
|
||||
};
|
||||
const rows = () => document.querySelectorAll('#cockpit-news-list li').length;
|
||||
showBriefPage.call(owner, 1);
|
||||
|
||||
// No earlier brief: an error clears and says unavailable.
|
||||
await refresh(() => Promise.reject(new Error('503')));
|
||||
assert.equal($('#cockpit-news-status').dataset.state, 'unavailable');
|
||||
assert.equal(text('#cockpit-news-status'), 'REGIONAL NEWS UNAVAILABLE');
|
||||
assert.equal(rows(), 0);
|
||||
|
||||
const fetchedAt = hoursAgo(1);
|
||||
await refresh(() =>
|
||||
Promise.resolve({
|
||||
status: 'ready',
|
||||
newsStatus: 'ready',
|
||||
newsSource: 'Google News RSS',
|
||||
newsWindowHours: 24,
|
||||
newsFetchedAt: fetchedAt,
|
||||
articles: [story('a'), story('b')],
|
||||
}),
|
||||
);
|
||||
assert.equal($('#cockpit-news-status').hidden, true);
|
||||
assert.equal(rows(), 2);
|
||||
|
||||
// A network failure keeps the rows and says so, with their age.
|
||||
await refresh(() => Promise.reject(new TypeError('Failed to fetch')));
|
||||
assert.equal($('#cockpit-news-status').hidden, false);
|
||||
assert.equal(text('#cockpit-news-status'), 'CACHED · REFRESH FAILED');
|
||||
assert.equal(rows(), 2);
|
||||
assert.equal(
|
||||
text('#cockpit-brief-source'),
|
||||
'GOOGLE NEWS RSS · CACHED 1H AGO',
|
||||
);
|
||||
showBriefPage.call(owner, 2);
|
||||
showBriefPage.call(owner, 1);
|
||||
await nextTick();
|
||||
assert.equal(
|
||||
text('#cockpit-brief-source'),
|
||||
'GOOGLE NEWS RSS · LOCATION QUERY · RECENT',
|
||||
'GOOGLE NEWS RSS · CACHED 1H AGO',
|
||||
);
|
||||
showBriefPage.call(owner, 0);
|
||||
renderRegionalBrief.call(owner, { newsSource: 'wire', articles: [] }, INFO);
|
||||
await nextTick();
|
||||
assert.equal(
|
||||
text('#cockpit-brief-source'),
|
||||
'SOURCE-BACKED EVENTS · NO SYNTHETIC NEWS',
|
||||
|
||||
// So does a brief whose news read failed while weather answered.
|
||||
await refresh(() =>
|
||||
Promise.resolve({
|
||||
status: 'partial',
|
||||
newsStatus: 'unavailable',
|
||||
articles: [],
|
||||
}),
|
||||
);
|
||||
assert.equal(text('#cockpit-news-status'), 'CACHED · REFRESH FAILED');
|
||||
assert.equal(rows(), 2);
|
||||
|
||||
// A successful refresh clears the cached label; a true empty clears rows.
|
||||
await refresh(() =>
|
||||
Promise.resolve({
|
||||
status: 'ready',
|
||||
newsStatus: 'empty',
|
||||
newsSource: 'Google News RSS',
|
||||
articles: [],
|
||||
}),
|
||||
);
|
||||
assert.equal(text('#cockpit-news-status'), 'NO NEWS IN THE LAST 24 H');
|
||||
assert.equal(rows(), 0);
|
||||
assert.equal(text('#cockpit-brief-source'), 'GOOGLE NEWS RSS · LAST 24 H');
|
||||
|
||||
// Another aircraft never inherits the last one's rows.
|
||||
await refresh(() =>
|
||||
Promise.resolve({ newsStatus: 'ready', articles: [story('c')] }),
|
||||
);
|
||||
assert.equal(rows(), 1);
|
||||
await refresh(() => Promise.reject(new Error('503')), {
|
||||
...INFO,
|
||||
icao24: 'def456',
|
||||
});
|
||||
assert.equal(text('#cockpit-news-status'), 'REGIONAL NEWS UNAVAILABLE');
|
||||
assert.equal(rows(), 0);
|
||||
});
|
||||
|
||||
test('an unchanged position publishes nothing new', (t) => {
|
||||
@@ -278,7 +550,10 @@ test('the card and its toggle render the collapse the controller presents', asyn
|
||||
await nextTick();
|
||||
assert.equal(card.dataset.collapsed, 'true');
|
||||
assert.equal(toggle.getAttribute('aria-expanded'), 'false');
|
||||
assert.equal(toggle.getAttribute('aria-label'), 'Expand cockpit briefing panel');
|
||||
assert.equal(
|
||||
toggle.getAttribute('aria-label'),
|
||||
'Expand cockpit briefing panel',
|
||||
);
|
||||
assert.equal(toggle.title, 'Expand briefing panel');
|
||||
assert.equal(toggle.textContent.trim(), 'right_panel_open');
|
||||
assert.equal(owner.signalUserCollapsed, true);
|
||||
@@ -287,3 +562,75 @@ test('the card and its toggle render the collapse the controller presents', asyn
|
||||
assert.equal(card.dataset.collapsed, 'false');
|
||||
assert.equal(toggle.textContent.trim(), 'right_panel_close');
|
||||
});
|
||||
|
||||
test("a refresh that fails after a move never shows the last location's brief as current", async (t) => {
|
||||
const { $, text, owner } = fixture(t);
|
||||
const answers = [];
|
||||
Object.assign(owner, {
|
||||
active: true,
|
||||
regionalBriefSubjectId: null,
|
||||
regionalBriefAbort: null,
|
||||
regionalBriefRequestToken: 0,
|
||||
regionalBriefFetchedAt: 0,
|
||||
regionalBrief: null,
|
||||
renderRegionalBrief,
|
||||
renderRegionalBriefStatus,
|
||||
});
|
||||
owner.services = {
|
||||
...owner.services,
|
||||
// One degree of latitude stands for a move past the refresh distance.
|
||||
regionalDistanceM: (from, to) =>
|
||||
from ? Math.abs(from.latitude - to.latitude) * 111_000 : Infinity,
|
||||
fetchRegionalBrief: () => answers.shift()(),
|
||||
};
|
||||
const refresh = async (answer, latitude) => {
|
||||
answers.push(answer);
|
||||
owner.regionalBriefFetchedAt = 0;
|
||||
maybeRefreshRegionalBrief.call(owner, {
|
||||
...INFO,
|
||||
icao24: 'abc123',
|
||||
latitude,
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
await nextTick();
|
||||
};
|
||||
const rows = () => document.querySelectorAll('#cockpit-news-list li').length;
|
||||
const here = () =>
|
||||
Promise.resolve({
|
||||
status: 'ready',
|
||||
newsStatus: 'ready',
|
||||
newsSource: 'Google News RSS',
|
||||
newsWindowHours: 24,
|
||||
newsFetchedAt: hoursAgo(1),
|
||||
articles: [story('a'), story('b')],
|
||||
});
|
||||
showBriefPage.call(owner, 1);
|
||||
|
||||
await refresh(here, 40);
|
||||
assert.equal(rows(), 2);
|
||||
// The same place: a failed refresh keeps the rows as cached.
|
||||
await refresh(() => Promise.reject(new TypeError('Failed to fetch')), 40);
|
||||
assert.equal(text('#cockpit-news-status'), 'CACHED · REFRESH FAILED');
|
||||
assert.equal(rows(), 2);
|
||||
// Elsewhere: the brief is unavailable, as it was before there was a cache.
|
||||
await refresh(() => Promise.reject(new TypeError('Failed to fetch')), 45);
|
||||
assert.equal($('#cockpit-news-status').dataset.state, 'unavailable');
|
||||
assert.equal(rows(), 0);
|
||||
// Nor is it held, for a language change to show again.
|
||||
assert.equal(owner.regionalBrief, null);
|
||||
|
||||
// Nor does a brief there whose news read failed borrow the last place's rows.
|
||||
await refresh(here, 40);
|
||||
assert.equal(rows(), 2);
|
||||
await refresh(
|
||||
() =>
|
||||
Promise.resolve({
|
||||
status: 'partial',
|
||||
newsStatus: 'unavailable',
|
||||
articles: [],
|
||||
}),
|
||||
45,
|
||||
);
|
||||
assert.equal($('#cockpit-news-status').dataset.state, 'unavailable');
|
||||
assert.equal(rows(), 0);
|
||||
});
|
||||
+533
-143
@@ -1,12 +1,44 @@
|
||||
/** 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,
|
||||
} from '../cockpitMath.js';
|
||||
import {
|
||||
VESSEL_DEAD_RECKON_MAX_S,
|
||||
VESSEL_WATERLINE_REFRESH_MS,
|
||||
deadReckonVesselFix,
|
||||
vesselCameraProfile,
|
||||
vesselWaterlineM,
|
||||
waterlineProbePoints,
|
||||
} from '../cockpitSubjects.js';
|
||||
import { easeLook } from '../cockpitLook.js';
|
||||
import { cockpitSubjectFrame } from '../cockpitSubjectProviders.js';
|
||||
import {
|
||||
COCKPIT_HEADING_SLEW_DPS,
|
||||
COCKPIT_FORWARD_OFFSET_M,
|
||||
@@ -19,6 +51,25 @@ 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,
|
||||
upM: COCKPIT_UP_OFFSET_M,
|
||||
pitchDeg: COCKPIT_VIEW_PITCH_DEG,
|
||||
minClearanceM: COCKPIT_MIN_GROUND_CLEARANCE_M,
|
||||
});
|
||||
|
||||
export function update() {
|
||||
if (this.destroyed) return false;
|
||||
if (!this.active) {
|
||||
@@ -36,6 +87,18 @@ export function update() {
|
||||
}
|
||||
|
||||
const nowMs = performance.now();
|
||||
if (this.subjectProvider) {
|
||||
updateSubject.call(this, nowMs);
|
||||
return;
|
||||
}
|
||||
if (this.subjectKind === 'vessel') {
|
||||
updateVessel.call(this, nowMs);
|
||||
return;
|
||||
}
|
||||
if (this.subjectKind === 'satellite') {
|
||||
this.updateOrbital(nowMs);
|
||||
return;
|
||||
}
|
||||
const info = this.readAircraftInfo();
|
||||
|
||||
// Adopt a newly selected track before the camera cadence gate. A context
|
||||
@@ -45,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 });
|
||||
@@ -61,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;
|
||||
@@ -75,10 +135,356 @@ export function update() {
|
||||
COCKPIT_HEADING_SLEW_DPS * dtSec,
|
||||
);
|
||||
}
|
||||
placeCamera.call(this, target, info, nowMs, dtSec, AIRCRAFT_CAMERA_PROFILE);
|
||||
}
|
||||
|
||||
if (!this.cockpitAnchorValid) {
|
||||
Cesium.Cartesian3.clone(target, this.cockpitAnchor);
|
||||
/**
|
||||
* The surface the ridden ship floats on: the layer's geoid sea surface, or
|
||||
* the water read off the rendered scene when that sits higher (a river or
|
||||
* lake above sea level). The read runs in the background every
|
||||
* VESSEL_WATERLINE_REFRESH_MS. The full-detail read can take many seconds
|
||||
* from cold tiles, so a new ship's first read starts from the tiles already
|
||||
* on screen; until any read lands the sea surface stands. Only one
|
||||
* full-detail read runs at a time (each is nine picks Cesium traverses
|
||||
* every frame until it settles): while one is still running, a refresh
|
||||
* reads the loaded tiles instead, and the slow read applies whenever it
|
||||
* lands. Once a full-detail read has answered, only full-detail reads
|
||||
* change the height; before then a loaded-tile read may find raised water
|
||||
* but never takes a raised height back to the sea. One coarse probe cannot
|
||||
* drop a river bridge to the sea, and a read that sampled nothing keeps
|
||||
* the height it had.
|
||||
* @param {{latitude: number, longitude: number}} [at] Where to read the
|
||||
* water: the dead-reckoned position the camera rides.
|
||||
* @returns {number} Ellipsoidal metres.
|
||||
*/
|
||||
function vesselSurfaceM(info, nowMs, at = info) {
|
||||
const seaM = Number.isFinite(info.seaSurfaceHeightM)
|
||||
? info.seaSurfaceHeightM
|
||||
: 0;
|
||||
const query = findQuery(this.viewer) ? heightsOf(this.viewer) : null;
|
||||
let read =
|
||||
this.vesselWaterline?.vesselId === info.id ? this.vesselWaterline : null;
|
||||
if (
|
||||
query &&
|
||||
(!read || nowMs - read.sampledMs >= VESSEL_WATERLINE_REFRESH_MS)
|
||||
) {
|
||||
const probes = waterlineProbePoints(at.latitude, at.longitude).map(
|
||||
({ lat, lon }) => ({ lon, lat }),
|
||||
);
|
||||
if (!read) {
|
||||
read = {
|
||||
vesselId: info.id,
|
||||
heightM: loadedWaterlineM(query, probes, seaM),
|
||||
sampledMs: nowMs,
|
||||
// Whether a full-detail read has answered for this ship.
|
||||
landed: false,
|
||||
inFlight: false,
|
||||
};
|
||||
this.vesselWaterline = read;
|
||||
} else {
|
||||
read.sampledMs = nowMs;
|
||||
if (read.inFlight && !read.landed) {
|
||||
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) &&
|
||||
read.heightM > seaM &&
|
||||
!(loadedM > seaM);
|
||||
if (Number.isFinite(loadedM) && !lowers) read.heightM = loadedM;
|
||||
}
|
||||
}
|
||||
if (!read.inFlight) readWaterline.call(this, read, query, probes, seaM);
|
||||
}
|
||||
return read && Number.isFinite(read.heightM)
|
||||
? Math.max(seaM, read.heightM)
|
||||
: seaM;
|
||||
}
|
||||
|
||||
/** Start one full-detail water read for `read`; its answer lands on it. */
|
||||
function readWaterline(read, query, probes, seaM) {
|
||||
read.inFlight = true;
|
||||
// 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;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The waterline from the tiles already loaded, read at once: a first answer
|
||||
* while the full-detail read loads. Null when the scene cannot sample or no
|
||||
* 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(query, probes, seaM) {
|
||||
try {
|
||||
const heights = probes.map((probe) => query.now(probe));
|
||||
if (!heights.some(Number.isFinite)) return null;
|
||||
return vesselWaterlineM(seaM, heights);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Drive the bridge camera from the selected vessel. The vessel layer redraws
|
||||
* a ship only when its feed refreshes, so the target is the last fix advanced
|
||||
* along course over ground; the shared anchor smoothing then absorbs the
|
||||
* correction each new fix brings.
|
||||
*/
|
||||
function updateVessel(nowMs) {
|
||||
// Tracking anything from the bridge (an aircraft, a satellite, a site)
|
||||
// takes the camera: entry stopped every follow, so any follow now is
|
||||
// another's. End the bridge and leave the camera following it.
|
||||
if (isFollowing(this.viewer)) {
|
||||
this.exit({ restoreTracking: false });
|
||||
return;
|
||||
}
|
||||
const info = this.readVesselInfo();
|
||||
if (!info || info.id !== this.subjectId) {
|
||||
this.exit({ restoreTracking: false });
|
||||
return;
|
||||
}
|
||||
if (
|
||||
!cockpitUiUpdateDue(
|
||||
nowMs,
|
||||
this.lastCameraUpdateMs,
|
||||
COCKPIT_CAMERA_UPDATE_MS,
|
||||
)
|
||||
)
|
||||
return;
|
||||
this.lastCameraUpdateMs = nowMs;
|
||||
|
||||
const fix = deadReckonVesselFix(
|
||||
{
|
||||
latitude: info.latitude,
|
||||
longitude: info.longitude,
|
||||
courseDeg: info.motionCourse,
|
||||
speedMps: info.velocityMps,
|
||||
fixEpochMs: info.fixEpochMs,
|
||||
receivedAtMs: info.receivedAtMs,
|
||||
feedEpochMs: info.feedEpochMs,
|
||||
},
|
||||
Date.now(),
|
||||
);
|
||||
// The radar centres here too, so it agrees with the view out the window.
|
||||
this.vesselFix = fix;
|
||||
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),
|
||||
);
|
||||
// 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
|
||||
// falling ever further behind its own ship.
|
||||
const dtSec = Math.min(
|
||||
VESSEL_DEAD_RECKON_MAX_S,
|
||||
Math.max(0, (nowMs - this.lastFrameMs) / 1000),
|
||||
);
|
||||
this.lastFrameMs = nowMs;
|
||||
if (Number.isFinite(info.track)) {
|
||||
this.heading = slewHeading(
|
||||
this.heading ?? info.track,
|
||||
info.track,
|
||||
COCKPIT_HEADING_SLEW_DPS * dtSec,
|
||||
);
|
||||
}
|
||||
// Past the projection limit the target stops advancing; hold on it rather
|
||||
// than let the inertial anchor sail on alone.
|
||||
const projectionExpired =
|
||||
Number.isFinite(fix.ageSec) && fix.ageSec > VESSEL_DEAD_RECKON_MAX_S;
|
||||
// The look eases on its own clock: the anchor's step is capped differently.
|
||||
this.lookView = easeLook(
|
||||
this.lookView,
|
||||
this.lookTarget,
|
||||
nowMs - (this.lookLastMs || nowMs),
|
||||
);
|
||||
this.lookLastMs = nowMs;
|
||||
// A ship reporting neither course nor heading has no direction to move
|
||||
// in: its anchor stays on the fix, as the dead reckoning does.
|
||||
const ridden = Number.isFinite(info.motionCourse)
|
||||
? info
|
||||
: { ...info, velocityMps: 0 };
|
||||
placeCamera.call(
|
||||
this,
|
||||
target,
|
||||
projectionExpired ? { ...ridden, stale: true } : ridden,
|
||||
nowMs,
|
||||
dtSec,
|
||||
vesselCameraProfile(info),
|
||||
this.lookView,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* 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.
|
||||
* @param {number} dtSec Seconds since the previous camera update.
|
||||
* @param {{forwardM: number, upM: number, pitchDeg: number,
|
||||
* minClearanceM: number}} profile Eye offsets for the subject kind.
|
||||
* @param {?{yawDeg: number, pitchDeg: number}} [look] A bridge view turned
|
||||
* off the bow: yaw relative to the heading and absolute pitch. It turns
|
||||
* only the view; the eye and its motion keep the heading and course.
|
||||
* Aircraft pass none and look along the heading at the profile pitch.
|
||||
*/
|
||||
function placeCamera(target, info, nowMs, dtSec, profile, look = null) {
|
||||
// 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
|
||||
@@ -88,65 +494,49 @@ export function update() {
|
||||
// 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 pitchRad = Cesium.Math.toRadians(COCKPIT_VIEW_PITCH_DEG);
|
||||
const headingRad = toRadians(this.heading ?? 0);
|
||||
const courseRad = Number.isFinite(info.motionCourse)
|
||||
? toRadians(info.motionCourse)
|
||||
: headingRad;
|
||||
const pitchRad = toRadians(look ? look.pitchDeg : profile.pitchDeg);
|
||||
const viewHeadingRad = look
|
||||
? 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(headingRad);
|
||||
this.scratchLocal.y = Math.cos(headingRad);
|
||||
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),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -156,19 +546,20 @@ export function update() {
|
||||
// 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' && targetCartographic
|
||||
? {
|
||||
latitude: toDegrees(targetCartographic.lat),
|
||||
longitude: toDegrees(targetCartographic.lon),
|
||||
}
|
||||
: info;
|
||||
let cockpitFloorM = this.services.cachedGroundFloor(
|
||||
info.latitude,
|
||||
info.longitude,
|
||||
floorAt.latitude,
|
||||
floorAt.longitude,
|
||||
);
|
||||
if (info.onGround === true) {
|
||||
const groundPoint = [{ lat: info.latitude, lon: info.longitude }];
|
||||
@@ -186,11 +577,11 @@ export function update() {
|
||||
)
|
||||
) {
|
||||
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(
|
||||
@@ -244,90 +635,64 @@ export function update() {
|
||||
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,
|
||||
COCKPIT_MIN_GROUND_CLEARANCE_M - COCKPIT_UP_OFFSET_M,
|
||||
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(headingRad) * Math.cos(pitchRad);
|
||||
this.scratchLocal.y = Math.cos(headingRad) * 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(headingRad) * Math.sin(pitchRad);
|
||||
this.scratchLocal.y = -Math.cos(headingRad) * 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,
|
||||
COCKPIT_FORWARD_OFFSET_M,
|
||||
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,
|
||||
COCKPIT_UP_OFFSET_M,
|
||||
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(
|
||||
@@ -335,23 +700,48 @@ export function update() {
|
||||
cameraFloorM,
|
||||
);
|
||||
}
|
||||
const safeHeightM = cockpitGroundSafeHeight(
|
||||
let safeHeightM = cockpitGroundSafeHeight(
|
||||
cameraCartographic.height,
|
||||
cockpitFloorM,
|
||||
COCKPIT_MIN_GROUND_CLEARANCE_M,
|
||||
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;
|
||||
|
||||
+51
-18
@@ -1,6 +1,7 @@
|
||||
/** 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';
|
||||
import {
|
||||
bearingBetweenCoordinates,
|
||||
@@ -24,6 +25,27 @@ const LOCALIZED_CONTEXT_SCOPE = Object.freeze({
|
||||
t('{scope} · INSTALLATIONS {coverage}', { scope, coverage }),
|
||||
});
|
||||
|
||||
/**
|
||||
* Which air feed the aircraft Cockpit's surrounding picture is missing. Entry
|
||||
* needs only the ridden aircraft's own layer, so the other one may be off;
|
||||
* the panels then say the picture is partial rather than present it as
|
||||
* complete. Null with both feeds on, or when the owner cannot tell.
|
||||
* @returns {?{title: string, detail: string}}
|
||||
*/
|
||||
export function readPartialPicture() {
|
||||
const isLayerEnabled = this.services.isLayerEnabled;
|
||||
if (typeof isLayerEnabled !== 'function') return null;
|
||||
const militaryOff = !isLayerEnabled('military');
|
||||
const flightsOff = !isLayerEnabled('flights');
|
||||
if (!militaryOff && !flightsOff) return null;
|
||||
return {
|
||||
title: militaryOff
|
||||
? t('MILITARY FEED OFF · PARTIAL PICTURE')
|
||||
: t('FLIGHTS FEED OFF · PARTIAL PICTURE'),
|
||||
detail: t('NEARBY AIRCRAFT INCOMPLETE · NOT AN ALL-CLEAR'),
|
||||
};
|
||||
}
|
||||
|
||||
/** Hand a fresh copy of the Contact card to the view. */
|
||||
export function publishContextView() {
|
||||
const view = this.contextView;
|
||||
@@ -52,7 +74,11 @@ export function updateContext(info, heading) {
|
||||
this.services.militaryAwarenessLayer.getContextSnapshot?.() || null;
|
||||
const trackedId = info.icao24 || info.id;
|
||||
const readout = resolveCockpitContextReadout({ snapshot, info });
|
||||
const partial = readPartialPicture.call(this);
|
||||
if (!readout.visible) {
|
||||
// Contacts just went off: the rows its snapshot built stop being
|
||||
// measured, so they go before the standby rows replace them.
|
||||
if (this.presence.context) this.dropContextSnapshotSignals?.();
|
||||
this.showContextCard(false);
|
||||
this.contextLayoutStamp = null;
|
||||
this.pushCockpitSignal(
|
||||
@@ -61,6 +87,14 @@ export function updateContext(info, heading) {
|
||||
t('CONTEXT STANDBY'),
|
||||
t('ENABLE GLOBAL CONTEXT FOR PROXIMITY PINGS'),
|
||||
);
|
||||
if (partial)
|
||||
this.pushCockpitSignal(
|
||||
'feed-status',
|
||||
'warning',
|
||||
partial.title,
|
||||
partial.detail,
|
||||
);
|
||||
else this.dropCockpitSignal?.('feed-status');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -110,6 +144,7 @@ export function updateContext(info, heading) {
|
||||
if (shown) {
|
||||
shown.count = cohort.count === null ? '?' : String(cohort.count);
|
||||
shown.unknown = cohort.relationship === 'UNKNOWN';
|
||||
shown.source = sourceStatusLabel(cohort.source, cohort.sourceStatus);
|
||||
}
|
||||
if (cohort.count === null) unknownCount += 1;
|
||||
for (const item of cohort.nearest) nearest.push({ ...item, cohort });
|
||||
@@ -151,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);
|
||||
}
|
||||
@@ -171,19 +201,22 @@ export function updateContext(info, heading) {
|
||||
angle: `${String(Math.round(Math.abs(relative))).padStart(3, '0')}°`,
|
||||
});
|
||||
}
|
||||
view.uncertainty = unknownCount
|
||||
? tn(
|
||||
unknownCount,
|
||||
'{count} INPUT UNKNOWN · NOT AN ALL-CLEAR',
|
||||
'{count} INPUTS UNKNOWN · NOT AN ALL-CLEAR',
|
||||
)
|
||||
: t('AVAILABLE INPUTS CURRENT · NOT AN ALL-CLEAR');
|
||||
// A feed that is off outranks unknown inputs: the picture is partial.
|
||||
view.uncertainty = partial
|
||||
? partial.title
|
||||
: unknownCount
|
||||
? tn(
|
||||
unknownCount,
|
||||
'{count} INPUT UNKNOWN · NOT AN ALL-CLEAR',
|
||||
'{count} INPUTS UNKNOWN · NOT AN ALL-CLEAR',
|
||||
)
|
||||
: t('AVAILABLE INPUTS CURRENT · NOT AN ALL-CLEAR');
|
||||
view.updated = Number.isFinite(snapshot.evaluatedAt)
|
||||
? new Date(snapshot.evaluatedAt).toISOString().slice(11, 19) + 'Z'
|
||||
: '--:--:--Z';
|
||||
view.state = unknownCount ? 'uncertain' : 'current';
|
||||
view.state = unknownCount || partial ? 'uncertain' : 'current';
|
||||
this.publishContextView();
|
||||
this.updateCockpitSignals(snapshot, unknownCount);
|
||||
this.updateCockpitSignals(snapshot, unknownCount, partial);
|
||||
if (this.contextLayoutStamp !== snapshot.evaluatedAt) {
|
||||
this.contextLayoutStamp = snapshot.evaluatedAt;
|
||||
this.scheduleContextLayout();
|
||||
|
||||
@@ -11,7 +11,15 @@ import {
|
||||
showContextCard,
|
||||
updateContext,
|
||||
} from './cockpitContext.js';
|
||||
import { fromDegrees } from '../geo/index.js';
|
||||
import { createContextState } from './cockpitContextState.js';
|
||||
import {
|
||||
dropCockpitSignal,
|
||||
dropContextSnapshotSignals,
|
||||
publishCockpitSignals,
|
||||
pushCockpitSignal,
|
||||
updateCockpitSignals,
|
||||
} from './cockpitSignals.js';
|
||||
import { syncWeatherToggle } from './cockpitInstruments.js';
|
||||
import { setContextCollapsed } from './cockpitLayout.js';
|
||||
import { useCockpitStore } from './stores/cockpit.js';
|
||||
@@ -96,6 +104,13 @@ test('before the controller presents, the card shows the state it starts in', (t
|
||||
),
|
||||
['—', '—', '—', '—'],
|
||||
);
|
||||
// No provider is named before a snapshot reports one.
|
||||
assert.deepEqual(
|
||||
[...document.querySelectorAll('[data-context-cohort] small')].map(
|
||||
(source) => source.textContent,
|
||||
),
|
||||
['—', '—', '—', '—'],
|
||||
);
|
||||
assert.equal(text('#cockpit-context-nearest-label'), 'NO AVAILABLE EXAMPLE');
|
||||
assert.equal(
|
||||
$('#cockpit-context-nearest-label').hasAttribute('aria-label'),
|
||||
@@ -159,6 +174,77 @@ 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';
|
||||
reported.cohorts[0].sourceStatus = 'fallback';
|
||||
reported.cohorts[1].source = 'Plane Finder';
|
||||
reported.cohorts.push(
|
||||
{
|
||||
id: 'ais-live-vessels',
|
||||
label: 'AIS vessels',
|
||||
source: 'Datalastic',
|
||||
sourceStatus: 'stale',
|
||||
count: 3,
|
||||
relationship: 'OBSERVED',
|
||||
nearest: [],
|
||||
},
|
||||
{
|
||||
id: 'military-installations',
|
||||
label: 'Mapped installations',
|
||||
source: 'OpenStreetMap',
|
||||
sourceStatus: null,
|
||||
count: 0,
|
||||
relationship: 'MAPPED',
|
||||
nearest: [],
|
||||
},
|
||||
);
|
||||
const { $, owner } = fixture(t, reported);
|
||||
updateContext.call(owner, INFO, 0);
|
||||
await nextTick();
|
||||
const source = (id) => $(`[data-context-cohort="${id}"] small`);
|
||||
assert.equal(source('flights').textContent, 'adsb.lol · FALLBACK');
|
||||
assert.equal(source('military').textContent, 'Plane Finder');
|
||||
assert.equal(source('ais-live-vessels').textContent, 'Datalastic · STALE');
|
||||
assert.equal(source('military-installations').textContent, 'OpenStreetMap');
|
||||
// The tile ellipsizes; the full name stays readable on hover.
|
||||
assert.equal(source('flights').title, 'adsb.lol · FALLBACK');
|
||||
});
|
||||
|
||||
test('a lost contact holds its readout behind the CONTACT LOST cue', async (t) => {
|
||||
const { $, text, owner, layouts } = fixture(t, snapshot());
|
||||
updateContext.call(owner, INFO, 0);
|
||||
@@ -204,6 +290,119 @@ test('without a snapshot the card stands by, hidden', async (t) => {
|
||||
assert.equal(signals.at(-1)[2], 'CONTEXT STANDBY');
|
||||
});
|
||||
|
||||
test('a feed that is off makes the card and Live Signals say the picture is partial', async (t) => {
|
||||
// Every input known, so only the feed that is off can make it partial.
|
||||
const { $, text, owner } = fixture(
|
||||
t,
|
||||
snapshot({
|
||||
cohorts: [
|
||||
{
|
||||
id: 'flights',
|
||||
label: 'Flights',
|
||||
count: 12,
|
||||
relationship: 'OBSERVED',
|
||||
nearest: [{ id: 'N1', distanceM: 4200 }],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
const rebuilt = [];
|
||||
owner.updateCockpitSignals = (...args) => rebuilt.push(args);
|
||||
owner.services.isLayerEnabled = () => true;
|
||||
updateContext.call(owner, INFO, 0);
|
||||
await nextTick();
|
||||
assert.equal($('#cockpit-context').dataset.state, 'current');
|
||||
assert.equal(rebuilt.at(-1)[2], null, 'both feeds on: nothing to add');
|
||||
|
||||
owner.services.isLayerEnabled = (layerId) => layerId !== 'military';
|
||||
updateContext.call(owner, INFO, 0);
|
||||
await nextTick();
|
||||
assert.equal($('#cockpit-context').dataset.state, 'uncertain');
|
||||
assert.equal(
|
||||
text('#cockpit-context-uncertainty'),
|
||||
'MILITARY FEED OFF · PARTIAL PICTURE',
|
||||
);
|
||||
assert.deepEqual(rebuilt.at(-1)[2], {
|
||||
title: 'MILITARY FEED OFF · PARTIAL PICTURE',
|
||||
detail: 'NEARBY AIRCRAFT INCOMPLETE · NOT AN ALL-CLEAR',
|
||||
});
|
||||
});
|
||||
|
||||
test('without Contacts, a feed that is off adds a signal until it is back', async (t) => {
|
||||
const { owner, signals } = fixture(t, null);
|
||||
const dropped = [];
|
||||
owner.dropCockpitSignal = (key) => dropped.push(key);
|
||||
// Riding a military aircraft with Live Flights off.
|
||||
owner.services.isLayerEnabled = (layerId) => layerId === 'military';
|
||||
updateContext.call(owner, { ...INFO, layerId: 'military' }, 0);
|
||||
assert.equal(signals.at(-2)[2], 'CONTEXT STANDBY');
|
||||
assert.deepEqual(signals.at(-1), [
|
||||
'feed-status',
|
||||
'warning',
|
||||
'FLIGHTS FEED OFF · PARTIAL PICTURE',
|
||||
'NEARBY AIRCRAFT INCOMPLETE · NOT AN ALL-CLEAR',
|
||||
]);
|
||||
owner.services.isLayerEnabled = () => true;
|
||||
updateContext.call(owner, { ...INFO, layerId: 'military' }, 0);
|
||||
assert.deepEqual(dropped, ['feed-status']);
|
||||
});
|
||||
|
||||
/** The fixture's owner with the real Live Signals presenters. */
|
||||
function withSignals(owner) {
|
||||
const published = [];
|
||||
Object.assign(owner, {
|
||||
signalItems: [],
|
||||
signalSignatures: new Map(),
|
||||
publishSignals: (rows) => published.push(rows),
|
||||
publishCockpitSignals,
|
||||
pushCockpitSignal,
|
||||
dropCockpitSignal,
|
||||
dropContextSnapshotSignals,
|
||||
updateCockpitSignals,
|
||||
});
|
||||
return () => published.at(-1).map((row) => row.title);
|
||||
}
|
||||
|
||||
test('Contacts going off clears its contact rows and leaves standby', async (t) => {
|
||||
const { owner } = fixture(t, snapshot());
|
||||
const rows = withSignals(owner);
|
||||
owner.services.isLayerEnabled = () => true;
|
||||
updateContext.call(owner, INFO, 0);
|
||||
assert.ok(
|
||||
owner.signalItems.some((item) => item.key.startsWith('flight:')),
|
||||
'Contacts fills the rows',
|
||||
);
|
||||
assert.ok(owner.signalItems.some((item) => item.key === 'input-status'));
|
||||
// Both feeds stay on; only Contacts goes.
|
||||
owner.snapshot = null;
|
||||
updateContext.call(owner, INFO, 0);
|
||||
assert.deepEqual(rows(), ['CONTEXT STANDBY']);
|
||||
updateContext.call(owner, INFO, 0);
|
||||
assert.deepEqual(rows(), ['CONTEXT STANDBY'], 'standby holds still');
|
||||
});
|
||||
|
||||
test('Contacts going off with a feed off keeps the feed row beside standby', async (t) => {
|
||||
const { owner } = fixture(t, snapshot());
|
||||
const rows = withSignals(owner);
|
||||
owner.services.isLayerEnabled = (layerId) => layerId !== 'military';
|
||||
updateContext.call(owner, INFO, 0);
|
||||
owner.snapshot = null;
|
||||
updateContext.call(owner, INFO, 0);
|
||||
assert.deepEqual(rows(), [
|
||||
'MILITARY FEED OFF · PARTIAL PICTURE',
|
||||
'CONTEXT STANDBY',
|
||||
]);
|
||||
});
|
||||
|
||||
test('standby without Contacts keeps the rows the session already shows', async (t) => {
|
||||
const { owner } = fixture(t, null);
|
||||
const rows = withSignals(owner);
|
||||
owner.services.isLayerEnabled = () => true;
|
||||
owner.pushCockpitSignal('track', 'track', 'TRACK ACQUIRED', 'UAL123');
|
||||
updateContext.call(owner, INFO, 0);
|
||||
assert.deepEqual(rows(), ['CONTEXT STANDBY', 'TRACK ACQUIRED']);
|
||||
});
|
||||
|
||||
test('the weather toggle renders its state and the action it offers', async (t) => {
|
||||
const { $, text, owner } = fixture(t);
|
||||
syncWeatherToggle.call(owner, true);
|
||||
|
||||
@@ -25,7 +25,10 @@ export function createContextState() {
|
||||
canPrevious: true,
|
||||
canNext: true,
|
||||
cohorts: Object.fromEntries(
|
||||
COCKPIT_CONTEXT_COHORTS.map((id) => [id, { count: '—', unknown: false }]),
|
||||
COCKPIT_CONTEXT_COHORTS.map((id) => [
|
||||
id,
|
||||
{ count: '—', unknown: false, source: '—' },
|
||||
]),
|
||||
),
|
||||
nearest: { label: t('NO AVAILABLE EXAMPLE'), ariaLabel: null },
|
||||
distance: { text: '—', ariaLabel: null },
|
||||
|
||||
+423
-26
@@ -1,10 +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,
|
||||
@@ -12,11 +24,37 @@ import {
|
||||
exit,
|
||||
} from './cockpitTrackingController.js';
|
||||
import { update } from './cockpitCamera.js';
|
||||
import {
|
||||
beginOrbital,
|
||||
endOrbital,
|
||||
resetOrbitalLook,
|
||||
jumpToSensorSwath,
|
||||
onOrbitalWheel,
|
||||
stepOrbitalZoom,
|
||||
turnOrbitalLook,
|
||||
updateOrbital,
|
||||
updateOrbitalHud,
|
||||
} from './cockpitOrbitalView.js';
|
||||
import {
|
||||
onOrbitalClick,
|
||||
onOrbitalDoubleClick,
|
||||
orbitalSiteUnder,
|
||||
routeSceneClick,
|
||||
toggleOrbitalFocus,
|
||||
} from './cockpitOrbitalFocus.js';
|
||||
import {
|
||||
handleOrbitalSignalClick,
|
||||
refreshOrbitalSignals,
|
||||
updateOrbitalSignals,
|
||||
} from './cockpitOrbitalSignals.js';
|
||||
import { rideOrbitalSatellite } from './cockpitOrbitalSatellites.js';
|
||||
import {
|
||||
publishInstrumentsView,
|
||||
publishRouteView,
|
||||
updateHud,
|
||||
updateRoute,
|
||||
updateRadar,
|
||||
presentLook,
|
||||
syncWeatherToggle,
|
||||
setVisionMode,
|
||||
cycleVisionMode,
|
||||
@@ -48,6 +86,8 @@ import {
|
||||
relocalizeBrief,
|
||||
} from './cockpitBriefing.js';
|
||||
import {
|
||||
dropCockpitSignal,
|
||||
dropContextSnapshotSignals,
|
||||
handleSignalClick,
|
||||
publishCockpitSignals,
|
||||
pushCockpitSignal,
|
||||
@@ -60,8 +100,23 @@ import {
|
||||
syncContextLayout,
|
||||
syncSignalLayout,
|
||||
} from './cockpitLayout.js';
|
||||
import { onKeyDown } from './cockpitInput.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
onKeyDown,
|
||||
onSceneDoubleClick,
|
||||
onScenePointerDown,
|
||||
routeSceneDoubleClick,
|
||||
} from './cockpitInput.js';
|
||||
import { DEFAULT_RADAR_RANGE_NM, nextRadarRange } from '../cockpitRadar.js';
|
||||
import { VESSEL_BRIDGE_PITCH_DEG } from '../cockpitSubjects.js';
|
||||
import { stepLook } from '../cockpitLook.js';
|
||||
import { createCockpitSubjectCaller } from '../cockpitSubjectProviders.js';
|
||||
|
||||
/** Whether the user asked for reduced motion: look turns then jump. */
|
||||
function prefersReducedMotion() {
|
||||
return Boolean(
|
||||
globalThis.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches,
|
||||
);
|
||||
}
|
||||
|
||||
export class CockpitViewController {
|
||||
constructor(
|
||||
@@ -72,19 +127,62 @@ export class CockpitViewController {
|
||||
getInitialVisionMode = null,
|
||||
onCameraTakeover = null,
|
||||
isEntryAllowed = null,
|
||||
isBridgeEntryAllowed = null,
|
||||
isOrbitEntryAllowed = null,
|
||||
subjectProviders = [],
|
||||
isSubjectEntryAllowed = null,
|
||||
isUtilityDisclosureOpen = null,
|
||||
onEntered = null,
|
||||
onExited = null,
|
||||
onRide = null,
|
||||
restoreTrackingFrame = null,
|
||||
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', '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.
|
||||
*/
|
||||
this.subjectId = null;
|
||||
/**
|
||||
* The orbital view's zoom, look and saved field of view while a
|
||||
* satellite is ridden (src/ui/cockpitOrbitalView.js); null otherwise.
|
||||
*/
|
||||
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;
|
||||
@@ -96,6 +194,20 @@ 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
|
||||
* positive, and absolute pitch. Aircraft never turn it.
|
||||
*/
|
||||
this.lookTarget = { yawDeg: 0, pitchDeg: VESSEL_BRIDGE_PITCH_DEG };
|
||||
this.lookView = { ...this.lookTarget };
|
||||
this.lookLastMs = 0;
|
||||
this.entry = document.getElementById('cockpit-entry');
|
||||
this.tr3bToggle = document.getElementById('tr3b-toggle');
|
||||
this._tr3bSignature = null;
|
||||
@@ -114,12 +226,28 @@ export class CockpitViewController {
|
||||
this.onCameraTakeover = onCameraTakeover;
|
||||
this.onEntered = onEntered;
|
||||
this.onExited = onExited;
|
||||
this.onRide = onRide;
|
||||
this.restoreTrackingFrame =
|
||||
typeof restoreTrackingFrame === 'function'
|
||||
? restoreTrackingFrame
|
||||
: () => false;
|
||||
this.isEntryAllowed =
|
||||
typeof isEntryAllowed === 'function' ? isEntryAllowed : () => true;
|
||||
// Without a supplied gate there is no vessel layer to ride either.
|
||||
this.isBridgeEntryAllowed =
|
||||
typeof isBridgeEntryAllowed === 'function'
|
||||
? isBridgeEntryAllowed
|
||||
: () => false;
|
||||
// Nor a satellite layer to ride without one.
|
||||
this.isOrbitEntryAllowed =
|
||||
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
|
||||
@@ -154,9 +282,23 @@ export class CockpitViewController {
|
||||
this.publishVision = publish.vision ?? (() => {});
|
||||
this.publishSignals = publish.signals ?? (() => {});
|
||||
this.publishUtilityLayout = publish.utilityLayout ?? (() => {});
|
||||
this.publishRadar = publish.radar ?? (() => {});
|
||||
this.publishOrbital = publish.orbital ?? (() => {});
|
||||
/** The bridge radar's range in nautical miles; kept across bridges. */
|
||||
this.radarRangeNm = DEFAULT_RADAR_RANGE_NM;
|
||||
this.presence = {
|
||||
active: false,
|
||||
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.
|
||||
@@ -169,7 +311,8 @@ export class CockpitViewController {
|
||||
this.contextView = createContextState();
|
||||
this.brief = createBriefState();
|
||||
this.briefTimer = null;
|
||||
this.lastAircraftInfo = null;
|
||||
// The last aircraft or vessel the HUD drew.
|
||||
this.lastSubjectInfo = null;
|
||||
this.regionalBrief = null;
|
||||
this.regionalBriefAnchor = null;
|
||||
this.regionalBriefFetchedAt = 0;
|
||||
@@ -178,33 +321,45 @@ 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();
|
||||
}),
|
||||
);
|
||||
this._listen(this.entry, 'click', () => this.enter());
|
||||
// Double-clicking the followed track is a third way in.
|
||||
this._listen(
|
||||
canvasOf(viewer),
|
||||
'pointerdown',
|
||||
() => this.onScenePointerDown(),
|
||||
true,
|
||||
);
|
||||
this._listenerRemovers.push(routeSceneDoubleClick.call(this));
|
||||
// In orbit a click on a mapped point keeps the camera on it.
|
||||
this._listenerRemovers.push(routeSceneClick.call(this));
|
||||
// In orbit the wheel steps the optical zoom (Cesium's own wheel zoom is
|
||||
// off while the Cockpit holds the camera).
|
||||
this._listen(
|
||||
canvasOf(viewer),
|
||||
'wheel',
|
||||
(event) => this.onOrbitalWheel(event),
|
||||
{ passive: false },
|
||||
);
|
||||
// The readout's entry renders inside the Intel HUD, which may mount after
|
||||
// this controller; delegated like the radar's range button.
|
||||
this._listen(document, 'click', (event) => {
|
||||
if (event.target?.closest?.('#cockpit-entry-readout')) this.enter();
|
||||
});
|
||||
this._listen(this.tr3bToggle, 'click', () => this.toggleTrackedTr3b());
|
||||
this._listen(this.mapViewButton, 'click', () => this.exit());
|
||||
this._listen(this.visionPrevious, 'click', () => this.cycleVisionMode(-1));
|
||||
@@ -231,6 +386,26 @@ export class CockpitViewController {
|
||||
this._listen(window, 'gev:cockpit-weather-state', (event) => {
|
||||
this.syncWeatherToggle(event?.detail?.enabled !== false);
|
||||
});
|
||||
// The radar mounts only on a bridge, so its range button is delegated.
|
||||
this._listen(document, 'click', (event) => {
|
||||
if (event.target?.closest?.('#cockpit-radar-range'))
|
||||
this.cycleRadarRange();
|
||||
});
|
||||
// The look-ahead button shows only on a turned bridge view; delegated.
|
||||
this._listen(document, 'click', (event) => {
|
||||
if (event.target?.closest?.('#cockpit-look-ahead')) this.lookAhead();
|
||||
});
|
||||
// The orbital HUD mounts only in orbit, so its controls are delegated.
|
||||
this._listen(document, 'click', (event) => {
|
||||
const target = event.target;
|
||||
if (target?.closest?.('#cockpit-orbital-zoom-in'))
|
||||
this.stepOrbitalZoom(1);
|
||||
else if (target?.closest?.('#cockpit-orbital-zoom-out'))
|
||||
this.stepOrbitalZoom(-1);
|
||||
else if (target?.closest?.('#cockpit-orbital-nadir')) this.orbitalNadir();
|
||||
else if (target?.closest?.('#cockpit-orbital-sensor'))
|
||||
this.jumpToSensorSwath();
|
||||
});
|
||||
this._listen(this.signalToggle, 'click', () =>
|
||||
this.setSignalCollapsed(!this.signalCollapsed, { user: true }),
|
||||
);
|
||||
@@ -272,6 +447,132 @@ export class CockpitViewController {
|
||||
readAircraftInfo() {
|
||||
return readAircraftInfo.call(this);
|
||||
}
|
||||
readVesselInfo() {
|
||||
return readVesselInfo.call(this);
|
||||
}
|
||||
readSatelliteInfo() {
|
||||
return readSatelliteInfo.call(this);
|
||||
}
|
||||
beginOrbital() {
|
||||
return beginOrbital.call(this);
|
||||
}
|
||||
endOrbital() {
|
||||
return endOrbital.call(this);
|
||||
}
|
||||
updateOrbital(nowMs) {
|
||||
return updateOrbital.call(this, nowMs);
|
||||
}
|
||||
updateOrbitalHud(info, nowMs) {
|
||||
return updateOrbitalHud.call(this, info, nowMs);
|
||||
}
|
||||
/**
|
||||
* Step the orbital view's optical zoom (the + and − keys and buttons).
|
||||
* @param {number} direction Positive zooms in, negative out.
|
||||
* @returns {boolean} True when the zoom changed.
|
||||
*/
|
||||
stepOrbitalZoom(direction) {
|
||||
return stepOrbitalZoom.call(this, direction);
|
||||
}
|
||||
jumpToSensorSwath() {
|
||||
return jumpToSensorSwath.call(this);
|
||||
}
|
||||
onOrbitalWheel(event) {
|
||||
return onOrbitalWheel.call(this, event);
|
||||
}
|
||||
/**
|
||||
* A click on the orbital picture: on a mapped point in reach it keeps the
|
||||
* camera on that point; anywhere else it ends such a focus.
|
||||
* @param {{x: number, y: number}|null|undefined} position
|
||||
* @returns {boolean} True when the click focused a point.
|
||||
*/
|
||||
onOrbitalClick(position) {
|
||||
return onOrbitalClick.call(this, position);
|
||||
}
|
||||
/**
|
||||
* A double-click on the orbital picture: on a mapped ground point it keeps
|
||||
* or starts the focus there instead of letting Cesium track the point.
|
||||
* @param {{x: number, y: number}|null|undefined} position
|
||||
* @returns {boolean} True when it was taken.
|
||||
*/
|
||||
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.
|
||||
* @param {string} key The site's id in the Mapped Installations layer.
|
||||
* @returns {boolean} True when the focus changed.
|
||||
*/
|
||||
toggleOrbitalFocus(key) {
|
||||
return toggleOrbitalFocus.call(this, key);
|
||||
}
|
||||
/** Rebuild the orbital Live Signals rows now. */
|
||||
refreshOrbitalSignals() {
|
||||
return refreshOrbitalSignals.call(this);
|
||||
}
|
||||
/** Rebuild the orbital Live Signals rows on their clock. */
|
||||
updateOrbitalSignals(nowMs) {
|
||||
return updateOrbitalSignals.call(this, nowMs);
|
||||
}
|
||||
/**
|
||||
* Ride the satellite an orbital Live Signals row names (RETURN goes back).
|
||||
* @param {number|string} noradId
|
||||
* @returns {boolean} True when the ridden satellite changed.
|
||||
*/
|
||||
rideOrbitalSatellite(noradId) {
|
||||
return rideOrbitalSatellite.call(this, noradId);
|
||||
}
|
||||
/**
|
||||
* A click on an orbital Live Signals row.
|
||||
* @returns {boolean} True in orbit.
|
||||
*/
|
||||
handleOrbitalSignalClick(layerId, id) {
|
||||
return handleOrbitalSignalClick.call(this, layerId, id);
|
||||
}
|
||||
/**
|
||||
* Tilt the orbital view one arrow step off nadir.
|
||||
* @param {{axis: 'yaw'|'pitch', sign: number, stepDeg: number}} step
|
||||
* @returns {boolean} True in an orbital view.
|
||||
*/
|
||||
turnOrbitalLook(step) {
|
||||
return turnOrbitalLook.call(this, step);
|
||||
}
|
||||
/**
|
||||
* The NADIR control and the Home and 0 keys in orbit: back to pure nadir.
|
||||
* Focus leaves the button before it hides.
|
||||
* @returns {boolean} True in an orbital view.
|
||||
*/
|
||||
orbitalNadir() {
|
||||
const button = document.getElementById('cockpit-orbital-nadir');
|
||||
const hadFocus = !!button && button.contains(document.activeElement);
|
||||
const reset = resetOrbitalLook.call(this);
|
||||
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);
|
||||
}
|
||||
resolveEntryKind() {
|
||||
return resolveEntryKind.call(this);
|
||||
}
|
||||
dispatchCockpitModeChanged(active, info) {
|
||||
return dispatchCockpitModeChanged.call(this, active, info);
|
||||
}
|
||||
@@ -287,14 +588,17 @@ export class CockpitViewController {
|
||||
syncEntry() {
|
||||
return syncEntry.call(this);
|
||||
}
|
||||
refreshSubjectWords() {
|
||||
return refreshSubjectWords.call(this);
|
||||
}
|
||||
navigateContext(direction, options) {
|
||||
return navigateContext.call(this, direction, options);
|
||||
}
|
||||
_adoptTrackedEntity(nowMs, suppliedInfo) {
|
||||
return _adoptTrackedEntity.call(this, nowMs, suppliedInfo);
|
||||
}
|
||||
enter() {
|
||||
return enter.call(this);
|
||||
enter(options) {
|
||||
return enter.call(this, options);
|
||||
}
|
||||
exit(options) {
|
||||
return exit.call(this, options);
|
||||
@@ -314,6 +618,71 @@ export class CockpitViewController {
|
||||
updateRoute(info) {
|
||||
return updateRoute.call(this, info);
|
||||
}
|
||||
updateRadar(info) {
|
||||
return updateRadar.call(this, info);
|
||||
}
|
||||
/** Step the bridge radar to its next range and redraw it at once. */
|
||||
cycleRadarRange() {
|
||||
this.radarRangeNm = nextRadarRange(this.radarRangeNm);
|
||||
if (this.active && this.subjectKind === 'vessel' && this.lastSubjectInfo)
|
||||
this.updateRadar(this.lastSubjectInfo);
|
||||
}
|
||||
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.
|
||||
* @param {{axis: 'yaw'|'pitch', sign: number, stepDeg: number}} step
|
||||
* @returns {boolean} True when a bridge view was turned.
|
||||
*/
|
||||
turnLook(step) {
|
||||
if (!this.looksAround || !step) return false;
|
||||
this.lookTarget = stepLook(this.lookTarget, step);
|
||||
if (prefersReducedMotion()) this.lookView = { ...this.lookTarget };
|
||||
this.presentLook();
|
||||
this.publishInstrumentsView();
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* Point the bridge view back over the bow at the rest pitch.
|
||||
* @param {{immediate?: boolean}} [options] Jump there instead of easing,
|
||||
* as entry and exit do.
|
||||
*/
|
||||
resetLook({ immediate = false } = {}) {
|
||||
this.lookTarget = { yawDeg: 0, pitchDeg: this.lookRestPitch };
|
||||
if (immediate || prefersReducedMotion())
|
||||
this.lookView = { ...this.lookTarget };
|
||||
this.lookLastMs = performance.now();
|
||||
this.presentLook();
|
||||
this.publishInstrumentsView();
|
||||
}
|
||||
/**
|
||||
* The LOOK AHEAD control and the Home and 0 keys: ease the bridge view
|
||||
* back over the bow. Focus leaves the button before it hides.
|
||||
* @returns {boolean} True on a bridge.
|
||||
*/
|
||||
lookAhead() {
|
||||
if (!this.looksAround) return false;
|
||||
const button = document.getElementById('cockpit-look-ahead');
|
||||
const hadFocus = !!button && button.contains(document.activeElement);
|
||||
this.resetLook();
|
||||
if (hadFocus) this.mapViewButton?.focus({ preventScroll: true });
|
||||
return true;
|
||||
}
|
||||
syncWeatherToggle(enabled) {
|
||||
return syncWeatherToggle.call(this, enabled);
|
||||
}
|
||||
@@ -368,11 +737,30 @@ 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,
|
||||
);
|
||||
}
|
||||
updateCockpitSignals(snapshot, unknownCount) {
|
||||
return updateCockpitSignals.call(this, snapshot, unknownCount);
|
||||
dropCockpitSignal(key) {
|
||||
return dropCockpitSignal.call(this, key);
|
||||
}
|
||||
dropContextSnapshotSignals() {
|
||||
return dropContextSnapshotSignals.call(this);
|
||||
}
|
||||
updateCockpitSignals(snapshot, unknownCount, partialPicture) {
|
||||
return updateCockpitSignals.call(
|
||||
this,
|
||||
snapshot,
|
||||
unknownCount,
|
||||
partialPicture,
|
||||
);
|
||||
}
|
||||
scheduleContextLayout() {
|
||||
return scheduleContextLayout.call(this);
|
||||
@@ -392,6 +780,12 @@ export class CockpitViewController {
|
||||
onKeyDown(event) {
|
||||
return onKeyDown.call(this, event);
|
||||
}
|
||||
onSceneDoubleClick(position, nowMs) {
|
||||
return onSceneDoubleClick.call(this, position, nowMs);
|
||||
}
|
||||
onScenePointerDown(nowMs) {
|
||||
return onScenePointerDown.call(this, nowMs);
|
||||
}
|
||||
|
||||
handleSignalClick(event) {
|
||||
return handleSignalClick.call(this, event);
|
||||
@@ -407,10 +801,13 @@ export class CockpitViewController {
|
||||
this.relocalizeBrief();
|
||||
this.publishVision(createVisionState(this.visionMode));
|
||||
this.routeSignature = null;
|
||||
if (this.active && this.lastAircraftInfo) {
|
||||
// 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 {
|
||||
this.updateHud(this.lastAircraftInfo, performance.now(), true);
|
||||
this.updateHud(this.lastSubjectInfo, performance.now(), true);
|
||||
} finally {
|
||||
this.rewordingSignals = false;
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
+191
-32
@@ -1,9 +1,18 @@
|
||||
import { followedOf } from '../data/followed.js';
|
||||
import { nextTick } from 'vue';
|
||||
import { CockpitViewController, CockpitDisplayPortal } from './cockpit.js';
|
||||
import { cockpitEntryAllowed } from '../contextModePolicy.js';
|
||||
import {
|
||||
COCKPIT_AIRCRAFT_LAYER_IDS,
|
||||
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 {
|
||||
@@ -37,6 +46,9 @@ export class CockpitCoordinator {
|
||||
const {
|
||||
flightsLayer,
|
||||
militaryFlightsLayer,
|
||||
aisLiveVesselsLayer,
|
||||
satellitesLayer,
|
||||
militaryInstallationsLayer,
|
||||
isTr3b,
|
||||
toggleTr3b,
|
||||
militaryAwarenessLayer,
|
||||
@@ -46,17 +58,25 @@ 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,
|
||||
militaryFlightsLayer,
|
||||
aisLiveVesselsLayer,
|
||||
satellitesLayer,
|
||||
militaryInstallationsLayer,
|
||||
isTr3b,
|
||||
toggleTr3b,
|
||||
militaryAwarenessLayer,
|
||||
@@ -67,32 +87,68 @@ export class CockpitCoordinator {
|
||||
meshFloorPreferred,
|
||||
warmGroundFloor,
|
||||
sampleMeshFloorCells,
|
||||
trackedEntityDrawn,
|
||||
holdContinuousRender,
|
||||
releaseContinuousRender,
|
||||
fetchRegionalBrief,
|
||||
regionalDistanceM,
|
||||
weatherCodeLabel,
|
||||
acquireOrbitImagery,
|
||||
// The Contact card and Live Signals say which feeds are off.
|
||||
isLayerEnabled: (layerId) => this._isLayerEnabled(layerId),
|
||||
},
|
||||
onVisionChange: (mode, active, options) =>
|
||||
this._setCockpitVision(mode, active, options),
|
||||
getInitialVisionMode: () => cockpitVisionModeForStyle(this.activeStyle),
|
||||
onCameraTakeover: () =>
|
||||
this._stampNavigation({ cancelPendingSelection: false }),
|
||||
isEntryAllowed: () =>
|
||||
cockpitEntryAllowed({
|
||||
contextMode: this._contextMode,
|
||||
// Only the tracked aircraft's own layer gates entry (see the policy).
|
||||
isEntryAllowed: () => {
|
||||
const subjectLayerId =
|
||||
this.cockpitView?.readAircraftInfo?.()?.layerId ?? null;
|
||||
return cockpitEntryAllowed({
|
||||
subjectLayerId,
|
||||
subjectLayerEnabled: this._isLayerEnabled(subjectLayerId),
|
||||
contextModeChanging: this._contextModeChanging,
|
||||
flightsEnabled: !!this._dataManager?.isEnabled('flights'),
|
||||
militaryEnabled: !!this._dataManager?.isEnabled('military'),
|
||||
});
|
||||
},
|
||||
isBridgeEntryAllowed: () =>
|
||||
bridgeEntryAllowed({
|
||||
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'),
|
||||
contextModeChanging: this._contextModeChanging,
|
||||
// The layer says whether its class may be ridden.
|
||||
subjectEnterable:
|
||||
satellitesLayer?.getCockpitSubject?.()?.enterable !== false,
|
||||
}),
|
||||
publish: this.publishCockpit,
|
||||
isUtilityDisclosureOpen: () => !!this.readUtilityDisclosureOpen?.(),
|
||||
onEntered: () => this.enterPanels(),
|
||||
onExited: () => this.exitPanels(),
|
||||
onRide: (layerId) => this._adoptRiddenLayer(layerId),
|
||||
restoreTrackingFrame: (entity) => {
|
||||
const [layerId, ...idParts] = String(entity?.gevTrackedId || '').split(
|
||||
':',
|
||||
);
|
||||
const [layerId, ...idParts] = String(
|
||||
readEntityRecord(entity)?.trackedId || '',
|
||||
).split(':');
|
||||
const trackedId = idParts.join(':');
|
||||
if (!trackedId) return false;
|
||||
if (layerId === 'flights')
|
||||
@@ -115,41 +171,143 @@ export class CockpitCoordinator {
|
||||
get activeStyle() {
|
||||
return this.readActiveStyle();
|
||||
}
|
||||
/** Whether a data layer is enabled; false for no layer. */
|
||||
_isLayerEnabled(layerId) {
|
||||
return Boolean(layerId) && !!this._dataManager?.isEnabled(layerId);
|
||||
}
|
||||
/**
|
||||
* Make the ridden layer the user's own while Contacts is on. Contacts may
|
||||
* have turned that layer on (an aircraft layer, or Live AIS Vessels), and
|
||||
* it releases the layers it owns when it goes off; the Cockpit must outlive
|
||||
* Contacts, so riding an aircraft or a vessel adopts its layer as a direct
|
||||
* selection does. Contacts then stops owning it and the Context restore
|
||||
* keeps it (session `userAdded`).
|
||||
* @param {string|null} layerId The ridden aircraft's layer, or
|
||||
* 'ais-live-vessels' on a bridge.
|
||||
*/
|
||||
_adoptRiddenLayer(layerId) {
|
||||
if (
|
||||
!COCKPIT_AIRCRAFT_LAYER_IDS.includes(layerId) &&
|
||||
layerId !== 'ais-live-vessels'
|
||||
)
|
||||
return;
|
||||
if (!this._isLayerEnabled('military-awareness')) return;
|
||||
this._dataManager?.adoptLayerVisibility?.(layerId, true, {
|
||||
origin: 'user',
|
||||
adoptedFromSelection: true,
|
||||
});
|
||||
}
|
||||
/** Whether either aircraft layer is on, so there is an aircraft to ride. */
|
||||
get _aircraftLayerEnabled() {
|
||||
return COCKPIT_AIRCRAFT_LAYER_IDS.some((layerId) =>
|
||||
this._isLayerEnabled(layerId),
|
||||
);
|
||||
}
|
||||
/**
|
||||
* Why voice entry must refuse before it touches tracking, or null. The
|
||||
* tracked aircraft's own layer is checked again by the entry itself.
|
||||
* @returns {string|null}
|
||||
*/
|
||||
_cockpitEntryRefusal() {
|
||||
if (this._contextModeChanging)
|
||||
return 'Context is still changing — try Cockpit again in a moment';
|
||||
// Tracking an aircraft from the bridge ends the bridge and clears the
|
||||
// vessel selection before the entry can run, leaving neither.
|
||||
if (this.cockpitView?.active && this.cockpitView.subjectKind === 'vessel')
|
||||
return 'Cockpit is on a vessel bridge — exit the bridge first, then track an aircraft to enter Cockpit';
|
||||
// Likewise in orbit: the aircraft's tracking takes the satellite's.
|
||||
if (
|
||||
this.cockpitView?.active &&
|
||||
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;
|
||||
}
|
||||
getCockpitState() {
|
||||
const { militaryAwarenessLayer } = this.services;
|
||||
const snapshot = militaryAwarenessLayer.getContextSnapshot?.();
|
||||
const info = this.cockpitView?.readAircraftInfo?.();
|
||||
const active = Boolean(this.cockpitView?.active);
|
||||
// Voice enters aircraft only; a bridge in use is still reported as it is.
|
||||
const vessel =
|
||||
active && this.cockpitView?.subjectKind === 'vessel'
|
||||
? this.cockpitView.readVesselInfo?.()
|
||||
: null;
|
||||
// Likewise an orbital view in use: its satellite, never an aircraft.
|
||||
const satellite =
|
||||
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
|
||||
? !this._isLayerEnabled(info.layerId)
|
||||
: !this._aircraftLayerEnabled;
|
||||
return {
|
||||
active,
|
||||
entryAllowed,
|
||||
// Why entry is unavailable, so a refusal can be explained rather than
|
||||
// guessed at.
|
||||
// guessed at. Contacts is not required, so it is never the reason.
|
||||
entryBlockedReason:
|
||||
entryAllowed || active
|
||||
? null
|
||||
: !gateOpen
|
||||
? this._contextModeChanging
|
||||
? 'contacts-starting'
|
||||
: 'contacts-inactive'
|
||||
: 'no-tracked-aircraft',
|
||||
: this._contextModeChanging
|
||||
? 'contacts-starting'
|
||||
: subjectLayerOff
|
||||
? 'subject-layer-off'
|
||||
: 'no-tracked-aircraft',
|
||||
visionMode: this.cockpitView?.visionMode || null,
|
||||
subject: info
|
||||
? {
|
||||
id: info.icao24 || info.id || null,
|
||||
layerId: info.layerId || null,
|
||||
callsign: info.callsign || null,
|
||||
}
|
||||
: null,
|
||||
subject: provided
|
||||
? provided
|
||||
: satellite
|
||||
? {
|
||||
kind: 'satellite',
|
||||
id: satellite.id,
|
||||
layerId: satellite.layerId,
|
||||
callsign: null,
|
||||
name: satellite.name,
|
||||
}
|
||||
: vessel
|
||||
? {
|
||||
kind: 'vessel',
|
||||
id: vessel.id,
|
||||
layerId: vessel.layerId,
|
||||
callsign: null,
|
||||
name: vessel.name,
|
||||
}
|
||||
: 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),
|
||||
@@ -260,17 +418,18 @@ export class CockpitCoordinator {
|
||||
};
|
||||
}
|
||||
if (normalized === 'enter') {
|
||||
// Entry is gated exactly as the manual entry chip is. Attempting it while
|
||||
// the gate is shut produced the half-entered look the operator reported
|
||||
// (a plane anchored under the camera with no cockpit around it), so
|
||||
// refuse with the reason instead of trying.
|
||||
if (!this.cockpitView.isEntryAllowed?.()) {
|
||||
// Attempting entry while the gate is shut produced the half-entered look
|
||||
// the operator reported (a plane anchored under the camera with no
|
||||
// cockpit around it), so refuse with the reason instead of trying. The
|
||||
// aircraft may not be tracked yet (a selection or a requested layer is
|
||||
// adopted below), so this checks what can be known now; the entry
|
||||
// itself then applies the manual chip's gate to the aircraft it rides.
|
||||
const refusal = this._cockpitEntryRefusal();
|
||||
if (refusal) {
|
||||
return {
|
||||
ok: false,
|
||||
action: 'control_cockpit',
|
||||
error: this._contextModeChanging
|
||||
? 'Contacts is still starting up — try Cockpit again in a moment'
|
||||
: 'Contacts must be active to enter Cockpit — say "open contacts" first',
|
||||
error: refusal,
|
||||
state: this.getCockpitState(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -0,0 +1,871 @@
|
||||
// src/ui/cockpitEntryGate.test.mjs — first person needs only the layer of
|
||||
// the vehicle it rides: Contacts and the other feeds may be off before or
|
||||
// during a session, turning the ridden layer off ends it, Contacts ending
|
||||
// keeps the ridden layer it had turned on, and the voice gate and state say
|
||||
// so without claiming Contacts is required. Over happy-dom.
|
||||
import '../testSupport/registerDom.mjs';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createPinia } from 'pinia';
|
||||
import { createApp, defineComponent, h, nextTick } from 'vue';
|
||||
import { DataLayerManager } from '../data/manager.js';
|
||||
import { 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';
|
||||
import { _handleContextLayerChange } from './contextLayerChanges.js';
|
||||
import { useCockpitStore } from './stores/cockpit.js';
|
||||
import { useHudStore } from './stores/hud.js';
|
||||
import ContextView from './views/ContextView.vue';
|
||||
import IntelHudView from './views/IntelHudView.vue';
|
||||
|
||||
const CIVIL = Object.freeze({
|
||||
icao24: 'abc123',
|
||||
callsign: 'UAL123',
|
||||
track: 92,
|
||||
latitude: 30,
|
||||
longitude: -97,
|
||||
});
|
||||
/** A tracked satellite, as the Satellites layer reports it. */
|
||||
const SATELLITE = Object.freeze({
|
||||
kind: 'satellite',
|
||||
layerId: 'satellites',
|
||||
id: '25544',
|
||||
noradId: 25544,
|
||||
name: 'ISS (ZARYA)',
|
||||
classLabel: 'STATION · ISS',
|
||||
latitude: 30,
|
||||
longitude: -97,
|
||||
altitudeM: 420_000,
|
||||
velocityMps: 7_660,
|
||||
stale: false,
|
||||
});
|
||||
const MILITARY = Object.freeze({
|
||||
...CIVIL,
|
||||
icao24: 'ae0001',
|
||||
callsign: 'RCH1',
|
||||
});
|
||||
|
||||
function fixture(
|
||||
t,
|
||||
{
|
||||
enabled = [],
|
||||
tracked = null,
|
||||
satellite = null,
|
||||
contextMode = null,
|
||||
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();
|
||||
const app = createApp(
|
||||
defineComponent(() => () => [h(ContextView), h(IntelHudView)]),
|
||||
).use(pinia);
|
||||
app.mount(host);
|
||||
const store = useCockpitStore(pinia);
|
||||
const layers = new Set(enabled);
|
||||
const dataManager = suppliedManager || {
|
||||
isEnabled: (layerId) => layers.has(layerId),
|
||||
};
|
||||
// A layer that is off has no tracked aircraft, as the flight layers clear
|
||||
// tracking on disable.
|
||||
const trackedFrom = (layerId) => () =>
|
||||
tracked?.layerId === layerId && dataManager.isEnabled(layerId)
|
||||
? tracked.info
|
||||
: null;
|
||||
const entityFor = (subject) =>
|
||||
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 = {
|
||||
clock: { currentTime: null },
|
||||
camera: { cancelFlight() {}, frustum: { fov: 1, aspectRatio: 1 } },
|
||||
entities: { contains: (candidate) => entities.has(candidate) },
|
||||
scene: {
|
||||
preUpdate: listeners(),
|
||||
screenSpaceCameraController: { enableInputs: true },
|
||||
},
|
||||
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') },
|
||||
// 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: () =>
|
||||
satellite && layers.has('satellites') ? { ...satellite } : null,
|
||||
getCockpitPosition: () => null,
|
||||
setCockpitSubject: () => true,
|
||||
},
|
||||
militaryAwarenessLayer: { getContextSnapshot: () => null },
|
||||
isTr3b: () => false,
|
||||
holdContinuousRender() {},
|
||||
releaseContinuousRender() {},
|
||||
cockpitSubjects: subjects,
|
||||
},
|
||||
elements: {},
|
||||
operations: {
|
||||
publishCockpit: { presence: (view) => store.publishPresence(view) },
|
||||
_stampNavigation() {},
|
||||
getAircraftTrackingTarget: () =>
|
||||
tracked ? { layerId: tracked.layerId, id: tracked.info.icao24 } : null,
|
||||
},
|
||||
readDataManager: () => dataManager,
|
||||
readContext: readContext || (() => context),
|
||||
readActiveStyle: () => 'normal',
|
||||
readUtilityDisclosureOpen: () => false,
|
||||
enterPanels() {},
|
||||
exitPanels() {},
|
||||
});
|
||||
const cockpit = coordinator.cockpitView;
|
||||
// The HUD, briefing and signals have their own tests.
|
||||
Object.assign(cockpit, {
|
||||
updateHud() {},
|
||||
setVisionMode() {},
|
||||
showBriefPage() {},
|
||||
startBriefRotation() {},
|
||||
stopBriefRotation() {},
|
||||
pushCockpitSignal() {},
|
||||
scheduleContextLayout() {},
|
||||
clearPredictiveRoute() {},
|
||||
});
|
||||
t.after(() => {
|
||||
coordinator.stop();
|
||||
app.unmount();
|
||||
document.body.classList.remove(
|
||||
'cockpit-mode',
|
||||
'cockpit-bridge',
|
||||
'cockpit-orbit',
|
||||
'cockpit-subject',
|
||||
);
|
||||
});
|
||||
/** Turn a layer off and tell the Context owner, as the data manager does. */
|
||||
const disable = (layerId) => {
|
||||
layers.delete(layerId);
|
||||
_handleContextLayerChange.call(
|
||||
{
|
||||
cockpitView: cockpit,
|
||||
_dataManager: dataManager,
|
||||
_contextMode: null,
|
||||
_contextModeChanging: false,
|
||||
_contextSessionSnapshot: null,
|
||||
_contextRestoreState: null,
|
||||
_syncContextModeButtons() {},
|
||||
},
|
||||
{ type: 'visibility', layerId, enabled: false, origin: 'user' },
|
||||
);
|
||||
};
|
||||
/** Track another aircraft, as Contacts navigation does mid-session. */
|
||||
const retrack = (subject) => {
|
||||
tracked = subject;
|
||||
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,
|
||||
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'],
|
||||
tracked: { layerId: 'flights', info: CIVIL },
|
||||
});
|
||||
const state = coordinator.getCockpitState();
|
||||
assert.equal(state.entryAllowed, true);
|
||||
assert.equal(state.entryBlockedReason, null);
|
||||
assert.equal(cockpit.enter(), true);
|
||||
assert.equal(cockpit.subjectKind, 'aircraft');
|
||||
});
|
||||
|
||||
test('a military aircraft enters with Military Flights alone', (t) => {
|
||||
const { coordinator, cockpit } = fixture(t, {
|
||||
enabled: ['military'],
|
||||
tracked: { layerId: 'military', info: MILITARY },
|
||||
});
|
||||
assert.equal(coordinator.getCockpitState().entryAllowed, true);
|
||||
assert.equal(cockpit.enter(), true);
|
||||
});
|
||||
|
||||
test('a Context change in flight still blocks entry, and says so', (t) => {
|
||||
const { coordinator, cockpit } = fixture(t, {
|
||||
enabled: ['flights', 'military'],
|
||||
tracked: { layerId: 'flights', info: CIVIL },
|
||||
contextMode: 'flights',
|
||||
changing: true,
|
||||
});
|
||||
const state = coordinator.getCockpitState();
|
||||
assert.equal(state.entryAllowed, false);
|
||||
assert.equal(state.entryBlockedReason, 'contacts-starting');
|
||||
assert.equal(cockpit.enter(), false);
|
||||
const voice = coordinator.controlCockpit('enter');
|
||||
assert.equal(voice.ok, false);
|
||||
assert.match(voice.error, /Context is still changing/);
|
||||
assert.equal(cockpit.active, false);
|
||||
});
|
||||
|
||||
test('with no aircraft layer on, entry is refused for that reason, never for Contacts', (t) => {
|
||||
const { coordinator, cockpit } = fixture(t);
|
||||
const state = coordinator.getCockpitState();
|
||||
assert.equal(state.entryBlockedReason, 'subject-layer-off');
|
||||
const voice = coordinator.controlCockpit('enter');
|
||||
assert.equal(voice.ok, false);
|
||||
assert.match(voice.error, /No aircraft layer is on/);
|
||||
assert.doesNotMatch(voice.error, /contacts/i);
|
||||
assert.equal(voice.state.entryBlockedReason, 'subject-layer-off');
|
||||
assert.equal(cockpit.active, false);
|
||||
});
|
||||
|
||||
test('voice entry on a vessel bridge refuses before it touches tracking', (t) => {
|
||||
const { coordinator, cockpit } = fixture(t, { enabled: ['flights'] });
|
||||
let navigated = false;
|
||||
coordinator.services.militaryAwarenessLayer.navigateNext = () => {
|
||||
navigated = true;
|
||||
return true;
|
||||
};
|
||||
// Stand in for a bridge ride: the refusal reads only these two.
|
||||
cockpit.active = true;
|
||||
cockpit.subjectKind = 'vessel';
|
||||
t.after(() => {
|
||||
cockpit.active = false;
|
||||
cockpit.subjectKind = null;
|
||||
});
|
||||
const voice = coordinator.controlCockpit('enter', { targetLayer: 'flights' });
|
||||
assert.equal(voice.ok, false);
|
||||
assert.match(voice.error, /vessel bridge/);
|
||||
assert.equal(navigated, false, 'no aircraft was tracked');
|
||||
assert.equal(cockpit.subjectKind, 'vessel');
|
||||
});
|
||||
|
||||
test('voice entry in an orbital view refuses before it touches tracking', (t) => {
|
||||
const { coordinator, cockpit } = fixture(t, { enabled: ['flights'] });
|
||||
let navigated = false;
|
||||
coordinator.services.militaryAwarenessLayer.navigateNext = () => {
|
||||
navigated = true;
|
||||
return true;
|
||||
};
|
||||
cockpit.active = true;
|
||||
cockpit.subjectKind = 'satellite';
|
||||
t.after(() => {
|
||||
cockpit.active = false;
|
||||
cockpit.subjectKind = null;
|
||||
});
|
||||
const voice = coordinator.controlCockpit('enter', { targetLayer: 'flights' });
|
||||
assert.equal(voice.ok, false);
|
||||
assert.match(voice.error, /orbital view/);
|
||||
assert.equal(navigated, false, 'no aircraft was tracked');
|
||||
assert.equal(cockpit.subjectKind, 'satellite');
|
||||
});
|
||||
|
||||
test('with an aircraft layer on but nothing tracked, the reason is the missing aircraft', (t) => {
|
||||
const { coordinator } = fixture(t, { enabled: ['military'] });
|
||||
assert.equal(
|
||||
coordinator.getCockpitState().entryBlockedReason,
|
||||
'no-tracked-aircraft',
|
||||
);
|
||||
});
|
||||
|
||||
test('voice enters without Contacts when the ridden layer is on', (t) => {
|
||||
const { coordinator, cockpit } = fixture(t, {
|
||||
enabled: ['flights'],
|
||||
tracked: { layerId: 'flights', info: CIVIL },
|
||||
});
|
||||
const result = coordinator.controlCockpit('enter');
|
||||
assert.equal(result.ok, true, result.error);
|
||||
assert.equal(cockpit.active, true);
|
||||
});
|
||||
|
||||
test('other layers may be turned off during a session; the ridden layer ends it', (t) => {
|
||||
const { cockpit, disable } = fixture(t, {
|
||||
enabled: ['flights', 'military', 'ais-live-vessels'],
|
||||
tracked: { layerId: 'flights', info: CIVIL },
|
||||
});
|
||||
assert.equal(cockpit.enter(), true);
|
||||
disable('military');
|
||||
disable('ais-live-vessels');
|
||||
assert.equal(cockpit.active, true, 'other feeds are free to go off');
|
||||
disable('flights');
|
||||
assert.equal(cockpit.active, false, 'the ridden layer going off ends it');
|
||||
});
|
||||
|
||||
test('the readout offers the same entry, labelled by kind, and enters on click', async (t) => {
|
||||
const { $, cockpit, pinia } = fixture(t, {
|
||||
enabled: ['flights'],
|
||||
tracked: { layerId: 'flights', info: CIVIL },
|
||||
});
|
||||
useHudStore(pinia);
|
||||
const readoutEntry = $('#cockpit-entry-readout');
|
||||
assert.equal(readoutEntry.hidden, true, 'hidden until entry is available');
|
||||
cockpit.syncEntry();
|
||||
await nextTick();
|
||||
assert.equal(readoutEntry.hidden, false);
|
||||
assert.match(readoutEntry.textContent, /flight/);
|
||||
assert.match(readoutEntry.textContent, /COCKPIT/);
|
||||
assert.equal(
|
||||
$('#cockpit-entry').hidden,
|
||||
false,
|
||||
'the Contacts entry follows the same presence',
|
||||
);
|
||||
readoutEntry.click();
|
||||
await nextTick();
|
||||
assert.equal(cockpit.active, true);
|
||||
assert.equal(readoutEntry.hidden, true, 'inside, there is nothing to enter');
|
||||
});
|
||||
|
||||
const AIR_AND_SEA = [
|
||||
'flights',
|
||||
'military',
|
||||
'ais-live-vessels',
|
||||
'military-installations',
|
||||
];
|
||||
|
||||
/** A source layer that settles at once, as the data manager drives it. */
|
||||
function sourceLayer(id) {
|
||||
return {
|
||||
id,
|
||||
name: id,
|
||||
icon: '',
|
||||
source: 'test',
|
||||
updateInterval: -1,
|
||||
init() {},
|
||||
enable() {},
|
||||
disable() {},
|
||||
update() {},
|
||||
getStats: () => ({ count: 0, lastUpdate: null }),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Contacts as the manager sees it: a coordinator whose real dependency
|
||||
* ownership (src/layers/awareness/dependencies.js) turns on the air and sea
|
||||
* layers it finds off and releases them when it goes off.
|
||||
*/
|
||||
function contactsCoordinator() {
|
||||
const state = {
|
||||
dataManager: null,
|
||||
enabled: false,
|
||||
passive: true,
|
||||
activationId: 0,
|
||||
ownedDependencies: new Set(),
|
||||
subject: null,
|
||||
autoFocusRetryPending: false,
|
||||
};
|
||||
const dependencies = createDependencies({
|
||||
state,
|
||||
services: {},
|
||||
parts: { subject: {}, focus: {} },
|
||||
source: null,
|
||||
});
|
||||
return {
|
||||
id: 'military-awareness',
|
||||
name: 'Contacts',
|
||||
icon: '',
|
||||
source: 'test',
|
||||
showInTogglePanel: false,
|
||||
updateInterval: -1,
|
||||
attachDataManager(dataManager) {
|
||||
state.dataManager = dataManager;
|
||||
dependencies.watchAdoptions(dataManager);
|
||||
},
|
||||
setParams(params = {}) {
|
||||
if (typeof params.passive === 'boolean') state.passive = params.passive;
|
||||
},
|
||||
getParams: () => ({ passive: state.passive }),
|
||||
init() {},
|
||||
enable() {
|
||||
state.enabled = true;
|
||||
if (!state.passive) return dependencies.enableDependencies();
|
||||
return true;
|
||||
},
|
||||
disable() {
|
||||
state.enabled = false;
|
||||
state.passive = true;
|
||||
return dependencies.releaseOwnedDependencies(++state.activationId);
|
||||
},
|
||||
update() {},
|
||||
getStats: () => ({ count: 0, lastUpdate: null }),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The Cockpit beside the real Context owner and data manager, so a Contacts
|
||||
* exit runs its whole restore: the coordinator's releases, then the snapshot.
|
||||
*/
|
||||
async function liveFixture(t, { enabled = [], tracked = null } = {}) {
|
||||
const manager = new DataLayerManager({});
|
||||
for (const layerId of AIR_AND_SEA) manager.register(sourceLayer(layerId));
|
||||
const coordinatorModule = contactsCoordinator();
|
||||
manager.register(coordinatorModule);
|
||||
coordinatorModule.attachDataManager(manager);
|
||||
for (const layerId of enabled) await manager.setEnabled(layerId, true);
|
||||
let cockpit = null;
|
||||
const controls = new ContextControls({
|
||||
elements: {},
|
||||
installations: {},
|
||||
actions: {
|
||||
getCockpit: () => cockpit,
|
||||
claimVisualAuthority() {},
|
||||
showToast() {},
|
||||
setClearBusy() {},
|
||||
syncDetection() {},
|
||||
scheduleLayout() {},
|
||||
refreshRadio() {},
|
||||
setPanelCollapsed() {},
|
||||
},
|
||||
});
|
||||
controls.connect(manager);
|
||||
t.after(() => {
|
||||
controls.stop();
|
||||
controls.disconnect();
|
||||
});
|
||||
const base = fixture(t, {
|
||||
tracked,
|
||||
dataManager: manager,
|
||||
readContext: () => controls.getContextModeState(),
|
||||
});
|
||||
cockpit = base.cockpit;
|
||||
/** Let every Context reaction the last change started settle. */
|
||||
const settle = async () => {
|
||||
for (let turn = 0; turn < 5; turn += 1) {
|
||||
await controls._waitForContextLayerSettlement();
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
}
|
||||
};
|
||||
return { ...base, manager, controls, settle };
|
||||
}
|
||||
|
||||
const on = (manager) =>
|
||||
[...AIR_AND_SEA, 'military-awareness'].filter((layerId) =>
|
||||
manager.isEnabled(layerId),
|
||||
);
|
||||
|
||||
test('Contacts ending in a Cockpit session keeps the ridden layer it had turned on', async (t) => {
|
||||
for (const [label, endContacts] of [
|
||||
[
|
||||
'Military Flights off',
|
||||
({ manager }) =>
|
||||
manager.setEnabled('military', false, { origin: 'user' }),
|
||||
],
|
||||
[
|
||||
'Contacts off by its own layer',
|
||||
({ manager }) =>
|
||||
manager.setEnabled('military-awareness', false, { origin: 'user' }),
|
||||
],
|
||||
[
|
||||
'Contacts off from its chooser',
|
||||
({ controls }) => controls._selectContextMode(null),
|
||||
],
|
||||
]) {
|
||||
await t.test(label, async (t) => {
|
||||
// Live Flights is off on the map; Contacts turns it on as its own.
|
||||
const live = await liveFixture(t, {
|
||||
tracked: { layerId: 'flights', info: CIVIL },
|
||||
});
|
||||
const { manager, controls, cockpit, settle } = live;
|
||||
assert.equal(await controls._selectContextMode('flights'), true);
|
||||
await settle();
|
||||
assert.deepEqual(on(manager), [...AIR_AND_SEA, 'military-awareness']);
|
||||
assert.equal(cockpit.enter(), true);
|
||||
await endContacts(live);
|
||||
await settle();
|
||||
assert.equal(controls.getContextModeState().mode, null, 'Contacts ended');
|
||||
assert.equal(cockpit.active, true, 'the Cockpit rides on');
|
||||
assert.deepEqual(
|
||||
on(manager),
|
||||
['flights'],
|
||||
'only the ridden layer outlives the pre-Contacts restore',
|
||||
);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test('a ride handed to an aircraft on a layer Contacts turned on keeps that layer', async (t) => {
|
||||
const live = await liveFixture(t, {
|
||||
enabled: ['flights'],
|
||||
tracked: { layerId: 'flights', info: CIVIL },
|
||||
});
|
||||
const { manager, controls, cockpit, retrack, settle } = live;
|
||||
assert.equal(await controls._selectContextMode('flights'), true);
|
||||
await settle();
|
||||
assert.equal(cockpit.enter(), true);
|
||||
// NEXT hands the view to a military aircraft; Contacts turned its layer on.
|
||||
// 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(followedOf(cockpit.viewer), null, 'adopted');
|
||||
assert.equal(cockpit.readSubjectLayerId(), 'military');
|
||||
await manager.setEnabled('ais-live-vessels', false, { origin: 'user' });
|
||||
await settle();
|
||||
assert.equal(controls.getContextModeState().mode, null);
|
||||
assert.equal(cockpit.active, true);
|
||||
assert.deepEqual(on(manager), ['flights', 'military']);
|
||||
});
|
||||
|
||||
test('Live AIS Vessels, once adopted as the ridden layer, outlives Contacts', async (t) => {
|
||||
const live = await liveFixture(t, {
|
||||
tracked: { layerId: 'flights', info: CIVIL },
|
||||
});
|
||||
const { manager, controls, coordinator, settle } = live;
|
||||
assert.equal(await controls._selectContextMode('flights'), true);
|
||||
await settle();
|
||||
assert.equal(manager.isEnabled('ais-live-vessels'), true);
|
||||
// The bridge reports its layer on entry (cockpitBridge.test.mjs).
|
||||
coordinator._adoptRiddenLayer('ais-live-vessels');
|
||||
await controls._selectContextMode(null);
|
||||
await settle();
|
||||
assert.equal(controls.getContextModeState().mode, null);
|
||||
assert.deepEqual(on(manager), ['ais-live-vessels']);
|
||||
});
|
||||
|
||||
test('the ridden layer still ends the Cockpit while Contacts is on', async (t) => {
|
||||
const live = await liveFixture(t, {
|
||||
tracked: { layerId: 'flights', info: CIVIL },
|
||||
});
|
||||
const { manager, controls, cockpit, settle } = live;
|
||||
assert.equal(await controls._selectContextMode('flights'), true);
|
||||
await settle();
|
||||
assert.equal(cockpit.enter(), true);
|
||||
await manager.setEnabled('flights', false, { origin: 'user' });
|
||||
await settle();
|
||||
assert.equal(cockpit.active, false);
|
||||
assert.equal(manager.isEnabled('flights'), false);
|
||||
});
|
||||
|
||||
test('without a Cockpit, ending Contacts restores the layers it found', async (t) => {
|
||||
const live = await liveFixture(t, {
|
||||
tracked: { layerId: 'flights', info: CIVIL },
|
||||
});
|
||||
const { manager, controls, settle } = live;
|
||||
assert.equal(await controls._selectContextMode('flights'), true);
|
||||
await settle();
|
||||
await manager.setEnabled('military', false, { origin: 'user' });
|
||||
await settle();
|
||||
assert.equal(controls.getContextModeState().mode, null);
|
||||
assert.deepEqual(on(manager), [], 'Live Flights goes back off');
|
||||
});
|
||||
|
||||
test('the readout entry reads BRIDGE for a selected vessel', async (t) => {
|
||||
const { $, store } = fixture(t);
|
||||
store.publishPresence({
|
||||
active: false,
|
||||
entryAvailable: true,
|
||||
entryKind: 'vessel',
|
||||
subjectKind: null,
|
||||
tr3b: null,
|
||||
});
|
||||
await nextTick();
|
||||
const readoutEntry = $('#cockpit-entry-readout');
|
||||
assert.equal(readoutEntry.hidden, false);
|
||||
assert.match(readoutEntry.textContent, /directions_boat/);
|
||||
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();
|
||||
await nextTick();
|
||||
assert.equal($('#cockpit-entry').hidden, true, 'Satellites off: no entry');
|
||||
assert.equal(cockpit.enter(), false);
|
||||
});
|
||||
|
||||
test('with Satellites on, the tracked satellite offers ORBIT and reports itself', async (t) => {
|
||||
const { $, cockpit, coordinator, pinia } = fixture(t, {
|
||||
enabled: ['satellites'],
|
||||
satellite: SATELLITE,
|
||||
});
|
||||
useHudStore(pinia);
|
||||
cockpit.syncEntry();
|
||||
await nextTick();
|
||||
for (const selector of ['#cockpit-entry', '#cockpit-entry-readout']) {
|
||||
assert.equal($(selector).hidden, false, selector);
|
||||
assert.match($(selector).textContent, /satellite_alt/);
|
||||
assert.match($(selector).textContent, /ORBIT/);
|
||||
}
|
||||
// Voice stays aircraft-only: it neither offers nor takes the satellite.
|
||||
assert.equal(coordinator.getCockpitState().entryAllowed, false);
|
||||
assert.equal(coordinator.controlCockpit('enter').ok, false);
|
||||
assert.equal(cockpit.active, false);
|
||||
$('#cockpit-entry-readout').click();
|
||||
await nextTick();
|
||||
assert.equal(cockpit.active, true);
|
||||
assert.equal(cockpit.subjectKind, 'satellite');
|
||||
const state = coordinator.getCockpitState();
|
||||
assert.equal(state.active, true);
|
||||
assert.deepEqual(state.subject, {
|
||||
kind: 'satellite',
|
||||
id: '25544',
|
||||
layerId: 'satellites',
|
||||
callsign: null,
|
||||
name: 'ISS (ZARYA)',
|
||||
});
|
||||
});
|
||||
|
||||
test('tracked debris offers no ORBIT entry and refuses to be entered', async (t) => {
|
||||
const { $, cockpit } = fixture(t, {
|
||||
enabled: ['satellites'],
|
||||
satellite: {
|
||||
...SATELLITE,
|
||||
id: '27386',
|
||||
noradId: 27386,
|
||||
name: 'SL-16 R/B',
|
||||
satelliteClass: 'debris',
|
||||
enterable: false,
|
||||
},
|
||||
});
|
||||
cockpit.syncEntry();
|
||||
await nextTick();
|
||||
for (const selector of ['#cockpit-entry', '#cockpit-entry-readout'])
|
||||
assert.equal($(selector).hidden, true, selector);
|
||||
assert.equal(cockpit.enter(), false);
|
||||
assert.equal(cockpit.enter({ kind: 'satellite' }), false);
|
||||
assert.equal(cockpit.active, false);
|
||||
});
|
||||
|
||||
test('a Context change in flight blocks the orbital view too', (t) => {
|
||||
const { cockpit } = fixture(t, {
|
||||
enabled: ['satellites'],
|
||||
satellite: SATELLITE,
|
||||
changing: true,
|
||||
});
|
||||
assert.equal(cockpit.enter(), false);
|
||||
});
|
||||
|
||||
test('turning Satellites off ends the orbital view', (t) => {
|
||||
const { cockpit, disable } = fixture(t, {
|
||||
enabled: ['satellites', 'flights'],
|
||||
satellite: SATELLITE,
|
||||
});
|
||||
assert.equal(cockpit.enter(), true);
|
||||
disable('flights');
|
||||
assert.equal(cockpit.active, true, 'other feeds are free to go off');
|
||||
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');
|
||||
});
|
||||
+306
-16
@@ -1,8 +1,308 @@
|
||||
/** Route Cockpit keys while preserving the active disclosure and form-control owner. */
|
||||
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;
|
||||
|
||||
/**
|
||||
* Whether a double-click landed on the followed track's mark.
|
||||
* @param {{x: number, y: number}|null} click Canvas position of the click.
|
||||
* @param {{x: number, y: number}|null|undefined} subject Canvas position of
|
||||
* the track, or nothing when it is off screen.
|
||||
* @param {number} [radiusPx]
|
||||
*/
|
||||
export function doubleClickHitsSubject(
|
||||
click,
|
||||
subject,
|
||||
radiusPx = SUBJECT_DOUBLE_CLICK_RADIUS_PX,
|
||||
) {
|
||||
if (!click || !subject) return false;
|
||||
const distance = Math.hypot(click.x - subject.x, click.y - subject.y);
|
||||
return Number.isFinite(distance) && distance <= radiusPx;
|
||||
}
|
||||
|
||||
/**
|
||||
* How long the first press of a double-click keeps its picture of the track,
|
||||
* ms: a click on a selected ship re-centres the camera, so the ship can move
|
||||
* on screen before the second click lands.
|
||||
*/
|
||||
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 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;
|
||||
// The sprite floats on the geoid, not on the ellipsoid (tens of metres
|
||||
// apart): project the height it is drawn at.
|
||||
const heightM = Number.isFinite(info.markHeightM)
|
||||
? info.markHeightM
|
||||
: Number.isFinite(info.seaSurfaceHeightM)
|
||||
? info.seaSurfaceHeightM
|
||||
: 0;
|
||||
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;
|
||||
if (!world) return null;
|
||||
return findQuery(this.viewer)?.project(world) ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Note where the selected ship is drawn as a press begins, for a
|
||||
* double-click whose first click moves it. The second press of the gesture
|
||||
* keeps the first one's picture: by then the first click may have moved it.
|
||||
* @param {number} [nowMs]
|
||||
*/
|
||||
export function onScenePointerDown(nowMs = performance.now()) {
|
||||
if (this.active || this.destroyed) return;
|
||||
const start = this.doubleClickStart;
|
||||
if (start && nowMs - start.atMs <= DOUBLE_CLICK_MEMORY_MS) return;
|
||||
// Only a ship moves under its own click (selecting it re-centres the
|
||||
// camera); a followed aircraft stays put, so its hit area stays its own.
|
||||
if (this.resolveEntryKind() !== 'vessel') {
|
||||
this.doubleClickStart = null;
|
||||
return;
|
||||
}
|
||||
const at = subjectCanvasPosition.call(this);
|
||||
const vesselId = this.readVesselInfo()?.id ?? null;
|
||||
this.doubleClickStart = at
|
||||
? { x: at.x, y: at.y, atMs: nowMs, vesselId }
|
||||
: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enter first person when the followed track itself is double-clicked: the
|
||||
* same entry, and the same gates, as the entry buttons. The click may
|
||||
* land where the track is drawn now or where it was as the gesture began. A
|
||||
* double-click anywhere else, or one a tool owns (drawing ends a shape with
|
||||
* one), is left alone.
|
||||
* @param {{x: number, y: number}|null|undefined} position Canvas position.
|
||||
* @param {number} [nowMs]
|
||||
* @returns {boolean} True when it landed on the followed track, entered or
|
||||
* refused by the gate: the caller does nothing else with it.
|
||||
*/
|
||||
export function onSceneDoubleClick(position, nowMs = performance.now()) {
|
||||
const start = this.doubleClickStart;
|
||||
this.doubleClickStart = null;
|
||||
if (this.active || this.destroyed || !isPointerFree()) return false;
|
||||
if (!Number.isFinite(position?.x) || !Number.isFinite(position?.y))
|
||||
return false;
|
||||
const hit =
|
||||
doubleClickHitsSubject(position, subjectCanvasPosition.call(this)) ||
|
||||
(Boolean(start) &&
|
||||
nowMs - start.atMs <= DOUBLE_CLICK_MEMORY_MS &&
|
||||
// The memory is the ship's it was taken for: one followed since (an
|
||||
// aircraft, another ship) is hit only where it is drawn.
|
||||
this.resolveEntryKind() === 'vessel' &&
|
||||
start.vesselId === (this.readVesselInfo()?.id ?? null) &&
|
||||
doubleClickHitsSubject(position, start));
|
||||
if (!hit) return false;
|
||||
this.enter();
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Hold the renderer's own double-click follow off; returns the release. */
|
||||
const holdStockFollow = (viewer) =>
|
||||
findInput(viewer)?.behaviours?.dblclickFollow?.suppress?.() ?? null;
|
||||
|
||||
/**
|
||||
* 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() {
|
||||
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.onSceneDoubleClick(position))
|
||||
this.onOrbitalDoubleClick?.(position);
|
||||
// The hold covers the whole double-click: it is given back once the
|
||||
// dispatch is over.
|
||||
|
||||
queueMicrotask(drop);
|
||||
});
|
||||
return () => {
|
||||
offDown();
|
||||
offUp();
|
||||
offDouble();
|
||||
drop();
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Focus inside one of these keeps its arrows (and Home): text entry, sliders,
|
||||
* tabs, radio groups, lists and menus all move with them.
|
||||
*/
|
||||
const LOOK_KEY_OWNERS = [
|
||||
'input',
|
||||
'textarea',
|
||||
'select',
|
||||
'[contenteditable]',
|
||||
'[role=combobox]',
|
||||
'[role=grid]',
|
||||
'[role=menubar]',
|
||||
'[role=menuitemcheckbox]',
|
||||
'[role=menuitemradio]',
|
||||
'[role=scrollbar]',
|
||||
'[role=searchbox]',
|
||||
'[role=slider]',
|
||||
'[role=spinbutton]',
|
||||
'[role=textbox]',
|
||||
'[role=tree]',
|
||||
'[role=treeitem]',
|
||||
'[role=tab]',
|
||||
'[role=tablist]',
|
||||
'[role=radio]',
|
||||
'[role=radiogroup]',
|
||||
'[role=listbox]',
|
||||
'[role=menu]',
|
||||
'[role=menuitem]',
|
||||
'[role=option]',
|
||||
].join(', ');
|
||||
|
||||
/**
|
||||
* Turn the bridge view with the arrow keys (Shift for 45° steps) and bring
|
||||
* it back over the bow with Home or 0. Only a bridge looks around, and only
|
||||
* while focus is on the scene or a plain HUD button.
|
||||
* @returns {boolean} True when the key was taken.
|
||||
*/
|
||||
function handleLookKey(event) {
|
||||
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');
|
||||
if (!step && !reset) return false;
|
||||
if (event.target?.closest?.(LOOK_KEY_OWNERS)) return false;
|
||||
if (this.isUtilityDisclosureOpen?.()) return false;
|
||||
event.preventDefault();
|
||||
if (step) this.turnLook(step);
|
||||
else this.lookAhead();
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Zoom keys in orbit: `+` (or `=`, unshifted) in and `-` (or `_`) out. */
|
||||
const ORBITAL_ZOOM_KEYS = Object.freeze({ '+': 1, '=': 1, '-': -1, _: -1 });
|
||||
|
||||
/**
|
||||
* In an orbital view: tilt off nadir with the arrows (single 5° steps; Shift
|
||||
* does not take the bridge's 45° step), return to nadir with Home or 0, and
|
||||
* step the zoom with + and −. The bridge's focus guards apply.
|
||||
* @returns {boolean} True when the key was taken.
|
||||
*/
|
||||
function handleOrbitalKey(event) {
|
||||
if (!this.active || this.subjectKind !== 'satellite') return false;
|
||||
if (event.metaKey || event.ctrlKey || event.altKey) return false;
|
||||
const step = lookKeyStep(event.key);
|
||||
const reset = !event.repeat && (event.key === 'Home' || event.key === '0');
|
||||
const zoom = event.repeat ? 0 : ORBITAL_ZOOM_KEYS[event.key] || 0;
|
||||
if (!step && !reset && !zoom) return false;
|
||||
if (event.target?.closest?.(LOOK_KEY_OWNERS)) return false;
|
||||
if (this.isUtilityDisclosureOpen?.()) return false;
|
||||
event.preventDefault();
|
||||
if (step) this.turnOrbitalLook(step);
|
||||
else if (reset) this.orbitalNadir();
|
||||
else this.stepOrbitalZoom(zoom);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Cockpit's capture-phase keydown: Escape, on a bridge the look-around
|
||||
* keys and in orbit the tilt and zoom keys. C is left to the app-wide CCTV
|
||||
* shortcut; entry is by double-click or the entry buttons.
|
||||
* @param {KeyboardEvent} event
|
||||
*/
|
||||
export function onKeyDown(event) {
|
||||
if (this.destroyed) return false;
|
||||
if (event.repeat || event.isComposing) return;
|
||||
if (event.isComposing) return;
|
||||
// Held arrows turn a bridge view smoothly; every other key acts once.
|
||||
if (event.repeat && !lookKeyStep(event.key)) return;
|
||||
if (event.key === 'Escape' && this.active) {
|
||||
// The credit lightbox owns Escape while its Close control or links hold
|
||||
// focus. Its target handler closes the overlay and restores attribution
|
||||
@@ -10,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();
|
||||
@@ -45,19 +348,6 @@ export function onKeyDown(event) {
|
||||
}
|
||||
if (event.target?.closest?.('input, textarea, select, [contenteditable]'))
|
||||
return;
|
||||
const key = event.key?.toLowerCase();
|
||||
if (key === 'c' && !event.metaKey && !event.ctrlKey && !event.altKey) {
|
||||
if (!this.active) {
|
||||
const cockpitAttempt = !!(
|
||||
this.readAircraftInfo() && this.viewer.trackedEntity?.position
|
||||
);
|
||||
if (!cockpitAttempt) return;
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
if (!this.active && !this.isEntryAllowed()) return;
|
||||
if (this.active) this.exit();
|
||||
else this.enter();
|
||||
return;
|
||||
}
|
||||
if (handleLookKey.call(this, event)) return;
|
||||
handleOrbitalKey.call(this, event);
|
||||
}
|
||||
@@ -52,17 +52,43 @@ function createRimState(value) {
|
||||
*/
|
||||
export function createInstrumentState() {
|
||||
return {
|
||||
// 'aircraft', 'vessel' or 'subject': which readouts the HUD shows.
|
||||
kind: 'aircraft',
|
||||
layer: null,
|
||||
callsign: t('AIRCRAFT'),
|
||||
meta: { text: t('LIVE TRACK · COURSE ALIGNED'), emergency: false },
|
||||
speed: null,
|
||||
altitude: null,
|
||||
// A vessel's course over ground, shown where an aircraft shows altitude.
|
||||
course: null,
|
||||
heading: null,
|
||||
// A vessel's `heading` readout is its true heading, or its course over
|
||||
// ground when it reports none: 'heading' | 'course' | null.
|
||||
trackSource: null,
|
||||
speedRim: createRimState('---'),
|
||||
altitudeRim: createRimState('-----'),
|
||||
compass: [],
|
||||
// A bridge tape's bow (prograde) and stern (retrograde) marks, in
|
||||
// division slots off its centre; null when off the tape or not a bridge.
|
||||
compassMarkers: { prograde: null, retrograde: null },
|
||||
// A bridge view turned off the bow: whether it is, the target yaw off
|
||||
// the bow (degrees, -180..180, starboard positive) and its worded readout.
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -73,6 +99,10 @@ export function createInstrumentState() {
|
||||
*/
|
||||
export function createRouteState() {
|
||||
return {
|
||||
// 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'),
|
||||
|
||||
@@ -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,
|
||||
@@ -11,6 +11,8 @@ import {
|
||||
cockpitAltitudeDisplayFt,
|
||||
cockpitUiUpdateDue,
|
||||
compassDivisions,
|
||||
compassMarkerSlot,
|
||||
scrollingCompassDivisions,
|
||||
formatAltitudeRulerTick,
|
||||
formatCompassDivision,
|
||||
formatCockpitEmergency,
|
||||
@@ -22,10 +24,24 @@ import {
|
||||
} from '../cockpitMath.js';
|
||||
import {
|
||||
COCKPIT_CONTEXT_UPDATE_MS,
|
||||
cockpitUnitCase,
|
||||
compassPointLabel,
|
||||
formatCockpitCoordinate,
|
||||
} from './cockpitPresentation.js';
|
||||
import { createVisionState } from './cockpitInstrumentState.js';
|
||||
import { unitLabel } from './unitLabels.js';
|
||||
import {
|
||||
VESSEL_BRIDGE_PITCH_DEG,
|
||||
vesselCameraProfile,
|
||||
} from '../cockpitSubjects.js';
|
||||
import { lookIsOffset, lookReadoutParts, wrapLookYaw } from '../cockpitLook.js';
|
||||
import { cockpitSubjectHudView } from '../cockpitSubjectProviders.js';
|
||||
import {
|
||||
RADAR_MAX_CONTACTS,
|
||||
radarPicture,
|
||||
radarRangeM,
|
||||
radarRangeNm,
|
||||
} from '../cockpitRadar.js';
|
||||
|
||||
/** A transponder status name (src/data/aircraftEmergency.js) for the HUD. */
|
||||
const emergencyLabel = ({ name }) => t(name).toUpperCase();
|
||||
@@ -68,20 +84,219 @@ export function publishInstrumentsView() {
|
||||
meta: { ...view.meta },
|
||||
speed: view.speed && { ...view.speed },
|
||||
altitude: view.altitude && { ...view.altitude },
|
||||
course: view.course && { ...view.course },
|
||||
heading: view.heading && { ...view.heading },
|
||||
speedRim: rim(view.speedRim),
|
||||
altitudeRim: rim(view.altitudeRim),
|
||||
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,
|
||||
});
|
||||
}
|
||||
|
||||
/** Word a bridge look's readout parts (see `lookReadoutParts`). */
|
||||
function wordLook({ side, bearingDeg, elevation, angleDeg }) {
|
||||
const bearing = formatHeadingReadout(bearingDeg);
|
||||
const angle = formatNumber(angleDeg);
|
||||
let direction = '';
|
||||
if (side === 'starboard') direction = t('LOOK STBD {bearing}°', { bearing });
|
||||
else if (side === 'port') direction = t('LOOK PORT {bearing}°', { bearing });
|
||||
else if (side === 'astern') direction = t('LOOK ASTERN');
|
||||
let tilt = '';
|
||||
if (elevation === 'up') tilt = t('UP {angle}°', { angle });
|
||||
else if (elevation === 'down') tilt = t('DOWN {angle}°', { angle });
|
||||
else if (elevation === 'level') tilt = t('LEVEL');
|
||||
if (direction && tilt)
|
||||
return t('{direction} · {elevation}', { direction, elevation: tilt });
|
||||
if (tilt) return t('LOOK {elevation}', { elevation: tilt });
|
||||
return direction;
|
||||
}
|
||||
|
||||
/**
|
||||
* Present the bridge look target: whether the view is turned off the bow,
|
||||
* its yaw for the radar and its worded readout. Outside a bridge the look
|
||||
* always rests. The caller publishes.
|
||||
*/
|
||||
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') ||
|
||||
(provider && this.looksAround)
|
||||
? lookIsOffset(target, rest)
|
||||
: false;
|
||||
this.instruments.look = offset
|
||||
? {
|
||||
offset: true,
|
||||
yawDeg: wrapLookYaw(target.yawDeg),
|
||||
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,
|
||||
) {
|
||||
this.lastAircraftInfo = info;
|
||||
if (this.subjectProvider && info?.generic === true) {
|
||||
updateSubjectHud.call(this, info, nowMs, forceContext);
|
||||
return;
|
||||
}
|
||||
if (info?.kind === 'vessel') {
|
||||
updateVesselHud.call(this, info, nowMs, forceContext);
|
||||
return;
|
||||
}
|
||||
// The orbital view keeps its own HUD (CockpitOrbital).
|
||||
if (info?.kind === 'satellite') {
|
||||
this.updateOrbitalHud(info, nowMs);
|
||||
return;
|
||||
}
|
||||
this.lastSubjectInfo = info;
|
||||
const view = this.instruments;
|
||||
view.kind = 'aircraft';
|
||||
view.trackSource = null;
|
||||
view.course = null;
|
||||
const heading = normalizeHeading(this.heading ?? info.track ?? 0);
|
||||
view.callsign =
|
||||
info.callsign || info.registration || info.icao24 || t('AIRCRAFT');
|
||||
@@ -128,6 +343,7 @@ export function updateHud(
|
||||
slot: index - 3,
|
||||
label: compassPointLabel(formatCompassDivision(division)),
|
||||
}));
|
||||
view.compassMarkers = { prograde: null, retrograde: null };
|
||||
view.clock = new Date().toISOString().slice(11, 19) + 'Z';
|
||||
const lat = Number.isFinite(info.latitude)
|
||||
? formatCockpitCoordinate(info.latitude, 'N', 'S')
|
||||
@@ -175,6 +391,160 @@ export function updateHud(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Present the bridge readouts: speed and course over ground, true heading,
|
||||
* the vessel type and its assumed eye height. Contact navigation and Live
|
||||
* Signals stay aircraft-only, so the Contact card is withdrawn.
|
||||
*/
|
||||
function updateVesselHud(info, nowMs, forceContext) {
|
||||
this.lastSubjectInfo = info;
|
||||
const view = this.instruments;
|
||||
view.kind = 'vessel';
|
||||
view.trackSource = info.trackSource ?? null;
|
||||
// A ship reporting neither heading nor course has no heading to read out
|
||||
// and no bow to mark; the tape still follows the camera.
|
||||
const headingKnown = Number.isFinite(info.track);
|
||||
const cameraHeading = normalizeHeading(this.heading ?? info.track ?? 0);
|
||||
const heading = headingKnown ? cameraHeading : null;
|
||||
view.callsign = info.name;
|
||||
const speedKt = Number.isFinite(info.speedKt)
|
||||
? Math.max(0, info.speedKt)
|
||||
: null;
|
||||
view.speed = {
|
||||
text: formatSpeedRulerTick(speedKt),
|
||||
value: speedKt,
|
||||
immediate: forceContext,
|
||||
};
|
||||
view.speedRim.unavailable = speedKt === null;
|
||||
view.speedRim.value = formatSpeedRulerTick(speedKt);
|
||||
placeRimTicks(
|
||||
view.speedRim.ticks,
|
||||
speedRulerTicks(speedKt, view.speedRim.ticks.length),
|
||||
(tick) => formatSpeedRulerTick(tick.valueKt),
|
||||
);
|
||||
view.altitude = null;
|
||||
view.altitudeRim.unavailable = true;
|
||||
const course = Number.isFinite(info.course)
|
||||
? normalizeHeading(info.course)
|
||||
: null;
|
||||
view.course = {
|
||||
text: formatHeadingReadout(course),
|
||||
value: course,
|
||||
immediate: forceContext,
|
||||
};
|
||||
view.heading = {
|
||||
text: formatHeadingReadout(heading),
|
||||
value: heading,
|
||||
immediate: forceContext,
|
||||
};
|
||||
// Looking around turns the tape with the camera; the readout above it
|
||||
// keeps the ship's heading, and the bow and stern marks stay on the ship.
|
||||
const viewHeading = normalizeHeading(
|
||||
cameraHeading + (this.lookView?.yawDeg ?? 0),
|
||||
);
|
||||
// The tape scrolls continuously, so the caret reads the view's exact
|
||||
// heading and the marks sit at their true bearings from it.
|
||||
view.compass = scrollingCompassDivisions(viewHeading).map((division) => ({
|
||||
slot: division.slot,
|
||||
heading: division.heading,
|
||||
active: division.nearest,
|
||||
label: compassPointLabel(formatCompassDivision(division.heading)),
|
||||
}));
|
||||
view.compassMarkers = headingKnown
|
||||
? {
|
||||
prograde: compassMarkerSlot(heading, viewHeading),
|
||||
retrograde: compassMarkerSlot(heading + 180, viewHeading),
|
||||
}
|
||||
: { prograde: null, retrograde: null };
|
||||
view.clock = new Date().toISOString().slice(11, 19) + 'Z';
|
||||
view.position = `${formatCockpitCoordinate(info.latitude, 'N', 'S')} · ${formatCockpitCoordinate(info.longitude, 'E', 'W')}`;
|
||||
const eyeHeightM = vesselCameraProfile(info).upM;
|
||||
view.meta.text = t('{vesselType} · {feedState} · EYE {height}', {
|
||||
vesselType: info.typeLabel || t('VESSEL'),
|
||||
feedState: info.stale ? t('STALE FEED') : t('LIVE AIS'),
|
||||
height: `${formatNumber(Math.round(eyeHeightM))} ${cockpitUnitCase(unitLabel('m'))}`,
|
||||
});
|
||||
view.meta.emergency = false;
|
||||
view.layer = info.layerId;
|
||||
// Reworded here too, so a language switch reaches the look readout.
|
||||
this.presentLook();
|
||||
this.publishInstrumentsView();
|
||||
updateVesselRoute.call(this, info);
|
||||
if (
|
||||
forceContext ||
|
||||
cockpitUiUpdateDue(
|
||||
nowMs,
|
||||
this.lastContextUpdateMs,
|
||||
COCKPIT_CONTEXT_UPDATE_MS,
|
||||
)
|
||||
) {
|
||||
this.lastContextUpdateMs = nowMs;
|
||||
this.updateLocalPosition(info);
|
||||
this.maybeRefreshRegionalBrief(info);
|
||||
this.updateRadar(info);
|
||||
this.showContextCard(false);
|
||||
this.pushCockpitSignal(
|
||||
'context-status',
|
||||
'info',
|
||||
t('CONTACT NAVIGATION OFF'),
|
||||
t('THE BRIDGE STAYS WITH THE SELECTED VESSEL'),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Publish the bridge radar: nearby AIS vessels drawn heading-up from the
|
||||
* camera's current heading, within the chosen range. Own ship sits where
|
||||
* the camera rides (its fix dead-reckoned); contacts sit at their last
|
||||
* fixes, where the vessel layer draws them, so the scope matches the
|
||||
* window.
|
||||
* @param {object} info The vessel subject (`readVesselInfo`).
|
||||
*/
|
||||
export function updateRadar(info) {
|
||||
const layer = this.services.aisLiveVesselsLayer;
|
||||
if (!info || typeof layer?.getRadarContacts !== 'function') {
|
||||
this.publishRadar(null);
|
||||
return;
|
||||
}
|
||||
const rangeNm = radarRangeNm(this.radarRangeNm);
|
||||
const own = this.vesselFix ?? info;
|
||||
const contacts = layer.getRadarContacts(
|
||||
own.latitude,
|
||||
own.longitude,
|
||||
radarRangeM(rangeNm),
|
||||
RADAR_MAX_CONTACTS,
|
||||
);
|
||||
const picture = radarPicture(
|
||||
{
|
||||
latitude: own.latitude,
|
||||
longitude: own.longitude,
|
||||
headingDeg: normalizeHeading(this.heading ?? info.track ?? 0),
|
||||
courseDeg: info.course,
|
||||
},
|
||||
contacts,
|
||||
rangeNm,
|
||||
);
|
||||
this.publishRadar({
|
||||
...picture,
|
||||
// A plural, as the ring spacing is: ru «3 МОР. МИЛИ», «12 МОР. МИЛЬ».
|
||||
rangeLabel: tn(rangeNm, '{range} NM', '{range} NM', {
|
||||
range: formatNumber(rangeNm),
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
/** Show the AIS voyage destination; it is crew-entered text, not a place. */
|
||||
function updateVesselRoute(info) {
|
||||
const route = this.routeView;
|
||||
route.kind = 'vessel';
|
||||
route.from = '';
|
||||
route.to = info.destination || t('UNKNOWN');
|
||||
route.status = t('AIS DESTINATION · CREW REPORTED');
|
||||
route.visible = Boolean(info.destination);
|
||||
// No coordinates, so no arrow; clearing also publishes the card.
|
||||
this.clearPredictiveRoute();
|
||||
}
|
||||
|
||||
/** Publish the route card and destination arrow when either changed. */
|
||||
export function publishRouteView() {
|
||||
const signature = JSON.stringify(this.routeView);
|
||||
@@ -188,6 +558,7 @@ export function publishRouteView() {
|
||||
|
||||
export function updateRoute(info) {
|
||||
const route = this.routeView;
|
||||
route.kind = 'aircraft';
|
||||
const origin = info?.route?.origin;
|
||||
const destination = info?.route?.destination;
|
||||
const validDestination =
|
||||
|
||||
+3
-134
@@ -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 =
|
||||
|
||||
@@ -0,0 +1,338 @@
|
||||
// src/ui/cockpitOrbital.test.mjs — the orbital view HUD shows what the
|
||||
// Cockpit controller publishes to the store, over happy-dom.
|
||||
import '../testSupport/registerDom.mjs';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createPinia } from 'pinia';
|
||||
import { createApp, nextTick } from 'vue';
|
||||
import { useCockpitStore } from './stores/cockpit.js';
|
||||
import CockpitOrbital from './views/panels/CockpitOrbital.vue';
|
||||
import { ownerFlagStyle } from './ownerFlag.js';
|
||||
|
||||
/** Let a settled promise reach the view. */
|
||||
async function settle() {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
await nextTick();
|
||||
}
|
||||
|
||||
const VIEW = Object.freeze({
|
||||
name: 'ISS (ZARYA)',
|
||||
classLabel: 'STATION · ISS',
|
||||
altitudeM: 418_400,
|
||||
velocityMps: 7_662,
|
||||
latitude: 12.3456,
|
||||
longitude: -45.6789,
|
||||
zoom: 4,
|
||||
zoomSteps: [1, 2, 4, 8],
|
||||
footprintKm: 61.4,
|
||||
transition: { active: false, blurPx: 0, lockTick: false },
|
||||
});
|
||||
|
||||
function fixture(t) {
|
||||
document.body.replaceChildren();
|
||||
const host = document.body.appendChild(document.createElement('div'));
|
||||
const pinia = createPinia();
|
||||
const app = createApp(CockpitOrbital).use(pinia);
|
||||
app.mount(host);
|
||||
t.after(() => app.unmount());
|
||||
const store = useCockpitStore(pinia);
|
||||
const section = () => document.getElementById('cockpit-orbital');
|
||||
const text = (selector) =>
|
||||
section().querySelector(selector)?.textContent.trim() ?? null;
|
||||
return { store, section, text };
|
||||
}
|
||||
|
||||
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, true);
|
||||
});
|
||||
|
||||
test('a published orbital view renders its readouts and zoom controls', async (t) => {
|
||||
const f = fixture(t);
|
||||
f.store.publishOrbital({ ...VIEW });
|
||||
await nextTick();
|
||||
assert.equal(f.section().hidden, false);
|
||||
assert.equal(f.text('.cockpit-orbital-kicker'), 'ORBITAL VIEW · NADIR');
|
||||
assert.equal(f.text('.cockpit-orbital-name'), 'ISS (ZARYA)');
|
||||
assert.equal(f.text('.cockpit-orbital-class'), 'STATION · ISS');
|
||||
assert.equal(f.text('.cockpit-orbital-altitude'), '418 KM');
|
||||
assert.equal(f.text('.cockpit-orbital-velocity'), '7.66 KM/S');
|
||||
assert.match(f.text('.cockpit-orbital-subpoint'), /12\.346°N.*45\.679°W/);
|
||||
assert.equal(f.text('.cockpit-orbital-north'), 'NORTH UP');
|
||||
assert.equal(f.text('.cockpit-orbital-zoom'), 'ZOOM 4×');
|
||||
assert.equal(f.text('.cockpit-orbital-swath'), 'SWATH 61 KM');
|
||||
|
||||
const zoomIn = document.getElementById('cockpit-orbital-zoom-in');
|
||||
const zoomOut = document.getElementById('cockpit-orbital-zoom-out');
|
||||
assert.equal(zoomIn.getAttribute('aria-label'), 'Zoom in');
|
||||
assert.equal(zoomOut.getAttribute('aria-label'), 'Zoom out');
|
||||
assert.equal(zoomIn.disabled, false);
|
||||
assert.equal(zoomOut.disabled, false);
|
||||
assert.ok(f.section().querySelector('.cockpit-orbital-reticle'));
|
||||
});
|
||||
|
||||
test('zoom buttons stop at the ends of the zoom steps', async (t) => {
|
||||
const f = fixture(t);
|
||||
f.store.publishOrbital({ ...VIEW, zoom: 8, footprintKm: 7.25 });
|
||||
await nextTick();
|
||||
assert.equal(
|
||||
document.getElementById('cockpit-orbital-zoom-in').disabled,
|
||||
true,
|
||||
);
|
||||
assert.equal(f.text('.cockpit-orbital-swath'), 'SWATH 7.3 KM');
|
||||
f.store.publishOrbital({ ...VIEW, zoom: 1 });
|
||||
await nextTick();
|
||||
assert.equal(
|
||||
document.getElementById('cockpit-orbital-zoom-out').disabled,
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
document.getElementById('cockpit-orbital-zoom-in').disabled,
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
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, true);
|
||||
assert.equal(f.text('.cockpit-orbital-altitude'), '418 KM');
|
||||
});
|
||||
|
||||
test('a zoom step reflects its blur and lock tick', async (t) => {
|
||||
const f = fixture(t);
|
||||
f.store.publishOrbital({
|
||||
...VIEW,
|
||||
transition: { active: true, blurPx: 4.5, lockTick: false },
|
||||
});
|
||||
await nextTick();
|
||||
assert.ok(f.section().classList.contains('cockpit-orbital-focusing'));
|
||||
assert.equal(
|
||||
f.section().style.getPropertyValue('--cockpit-orbital-blur'),
|
||||
'4.50px',
|
||||
);
|
||||
const reticle = f.section().querySelector('.cockpit-orbital-reticle');
|
||||
assert.equal(
|
||||
reticle.classList.contains('cockpit-orbital-reticle-lock'),
|
||||
false,
|
||||
);
|
||||
|
||||
f.store.publishOrbital({
|
||||
...VIEW,
|
||||
transition: { active: false, blurPx: 0, lockTick: true },
|
||||
});
|
||||
await nextTick();
|
||||
assert.ok(!f.section().classList.contains('cockpit-orbital-focusing'));
|
||||
assert.equal(
|
||||
f.section().style.getPropertyValue('--cockpit-orbital-blur'),
|
||||
'0px',
|
||||
);
|
||||
assert.ok(
|
||||
f
|
||||
.section()
|
||||
.querySelector('.cockpit-orbital-reticle')
|
||||
.classList.contains('cockpit-orbital-reticle-lock'),
|
||||
);
|
||||
});
|
||||
|
||||
test('publishing null hides the orbital HUD again', async (t) => {
|
||||
const f = fixture(t);
|
||||
f.store.publishOrbital({ ...VIEW });
|
||||
await nextTick();
|
||||
assert.equal(f.section().hidden, false);
|
||||
f.store.publishOrbital(null);
|
||||
await nextTick();
|
||||
assert.equal(f.section().hidden, true);
|
||||
assert.equal(f.section().querySelector('.cockpit-orbital-name') === null, true);
|
||||
});
|
||||
|
||||
const ISS_TLE = Object.freeze({
|
||||
line1:
|
||||
'1 25544U 98067A 26308.34166667 .00016717 00000-0 30306-3 0 9993',
|
||||
line2:
|
||||
'2 25544 51.6416 247.4627 0006703 130.5360 325.0288 15.50377579477310',
|
||||
epochMs: Date.UTC(2026, 10, 4, 8, 12, 0),
|
||||
});
|
||||
|
||||
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, true);
|
||||
const over = () =>
|
||||
f.section().querySelector('#cockpit-orbital-over strong')?.textContent;
|
||||
f.store.publishOrbital({
|
||||
...VIEW,
|
||||
place: { kind: 'country', name: 'France', countryCode: 'FR' },
|
||||
});
|
||||
await nextTick();
|
||||
assert.match(f.text('#cockpit-orbital-over'), /^CURRENTLY OVER/);
|
||||
assert.equal(over(), 'France');
|
||||
// The division as Natural Earth names it, the country localized.
|
||||
const sichuan = {
|
||||
kind: 'country',
|
||||
name: 'China',
|
||||
countryCode: 'CN',
|
||||
division: 'Sichuan',
|
||||
near: null,
|
||||
};
|
||||
f.store.publishOrbital({ ...VIEW, place: sichuan });
|
||||
await nextTick();
|
||||
assert.equal(over(), 'Sichuan, China');
|
||||
// From 8x, the populated place in view.
|
||||
f.store.publishOrbital({ ...VIEW, place: { ...sichuan, near: 'Chengdu' } });
|
||||
await nextTick();
|
||||
assert.equal(over(), 'Sichuan, China · near Chengdu');
|
||||
f.store.publishOrbital({
|
||||
...VIEW,
|
||||
place: { kind: 'sea', name: 'Caspian Sea', countryCode: null },
|
||||
});
|
||||
await nextTick();
|
||||
assert.equal(over(), 'Caspian Sea');
|
||||
// No feature holds the point (a gap at a simplified coastline): the band
|
||||
// says nothing rather than call land open ocean.
|
||||
f.store.publishOrbital({ ...VIEW, place: null });
|
||||
await nextTick();
|
||||
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) => {
|
||||
// The sheet loads through an Image; this one answers when told.
|
||||
const images = [];
|
||||
const RealImage = globalThis.Image;
|
||||
globalThis.Image = class {
|
||||
constructor() {
|
||||
images.push(this);
|
||||
}
|
||||
};
|
||||
t.after(() => {
|
||||
globalThis.Image = RealImage;
|
||||
});
|
||||
const f = fixture(t);
|
||||
f.store.publishOrbital({
|
||||
...VIEW,
|
||||
owner: { countryCode: 'US', label: 'USA' },
|
||||
});
|
||||
await nextTick();
|
||||
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();
|
||||
// No sheet: the code, so the owner never disappears.
|
||||
assert.equal(f.text('.cockpit-orbital-owner-badge'), 'US');
|
||||
// Another satellite of the same country asks again.
|
||||
f.store.publishOrbital({ ...f.store.orbital, noradId: 43013 });
|
||||
await nextTick();
|
||||
assert.equal(images.length, 2, 'a new ride asks again');
|
||||
images[1].onerror();
|
||||
await settle();
|
||||
// The next flag asks again; this time the sheet comes.
|
||||
f.store.publishOrbital({
|
||||
...f.store.orbital,
|
||||
owner: { countryCode: 'FR', label: 'France' },
|
||||
});
|
||||
await nextTick();
|
||||
assert.equal(images.length, 3);
|
||||
images[2].onload();
|
||||
await settle();
|
||||
const flag = f.section().querySelector('.cockpit-orbital-flag');
|
||||
assert.equal(flag.getAttribute('role'), 'img');
|
||||
assert.equal(flag.getAttribute('aria-label'), 'France');
|
||||
assert.equal(
|
||||
flag.style.backgroundPosition,
|
||||
ownerFlagStyle('FR').backgroundPosition,
|
||||
);
|
||||
assert.equal(f.section().querySelector('.cockpit-orbital-owner-badge') === null, true);
|
||||
});
|
||||
|
||||
test('the readout names the owner, operator and element set', async (t) => {
|
||||
const f = fixture(t);
|
||||
f.store.publishOrbital({
|
||||
...VIEW,
|
||||
noradId: 25544,
|
||||
cosparId: '1998-067A',
|
||||
tle: ISS_TLE,
|
||||
// A country with no flag on the sheet shows as a badge, named in the
|
||||
// reader's language.
|
||||
owner: { countryCode: 'IS', label: 'Ísland' },
|
||||
operator: 'NASA',
|
||||
});
|
||||
await nextTick();
|
||||
assert.equal(f.text('.cockpit-orbital-name'), 'ISS (ZARYA)');
|
||||
assert.equal(f.text('.cockpit-orbital-owner-badge'), 'Ísland');
|
||||
assert.equal(
|
||||
f.section().querySelector('.cockpit-orbital-owner-badge').title,
|
||||
'Iceland',
|
||||
);
|
||||
assert.equal(f.text('.cockpit-orbital-operator'), 'NASA');
|
||||
assert.equal(
|
||||
f.text('.cockpit-orbital-ident-text'),
|
||||
'NORAD 25544 · 1998-067A · EPOCH 2026-11-04 08:12Z',
|
||||
);
|
||||
// The element set's age, as the controller reads it on each publish.
|
||||
f.store.publishOrbital({
|
||||
...f.store.orbital,
|
||||
tleAgeMs: 13.5 * 3_600_000,
|
||||
});
|
||||
await nextTick();
|
||||
assert.equal(
|
||||
f.text('.cockpit-orbital-ident-text'),
|
||||
'NORAD 25544 · 1998-067A · EPOCH 2026-11-04 08:12Z · 13 H OLD',
|
||||
);
|
||||
f.store.publishOrbital({ ...f.store.orbital, tleAgeMs: 50 * 3_600_000 });
|
||||
await nextTick();
|
||||
assert.match(f.text('.cockpit-orbital-ident-text'), / · 2 D OLD$/);
|
||||
f.store.publishOrbital({ ...f.store.orbital, tleAgeMs: 10 * 60_000 });
|
||||
await nextTick();
|
||||
assert.match(f.text('.cockpit-orbital-ident-text'), / · <1 H OLD$/);
|
||||
f.store.publishOrbital({ ...f.store.orbital, tleAgeMs: null });
|
||||
await nextTick();
|
||||
const toggle = document.getElementById('cockpit-orbital-tle-toggle');
|
||||
const tle = document.getElementById('cockpit-orbital-tle');
|
||||
assert.equal(toggle.getAttribute('aria-expanded'), 'false');
|
||||
assert.equal(tle.style.display, 'none', 'folded');
|
||||
toggle.click();
|
||||
await nextTick();
|
||||
assert.equal(toggle.getAttribute('aria-expanded'), 'true');
|
||||
assert.notEqual(tle.style.display, 'none');
|
||||
assert.equal(tle.textContent, `${ISS_TLE.line1}\n${ISS_TLE.line2}`);
|
||||
// Another satellite starts folded.
|
||||
f.store.publishOrbital({ ...VIEW, noradId: 48274, tle: ISS_TLE });
|
||||
await nextTick();
|
||||
assert.equal(
|
||||
document
|
||||
.getElementById('cockpit-orbital-tle-toggle')
|
||||
.getAttribute('aria-expanded'),
|
||||
'false',
|
||||
);
|
||||
});
|
||||
|
||||
test('unknown identity fields leave their rows out', async (t) => {
|
||||
const f = fixture(t);
|
||||
f.store.publishOrbital({
|
||||
...VIEW,
|
||||
noradId: null,
|
||||
cosparId: null,
|
||||
tle: null,
|
||||
owner: null,
|
||||
operator: null,
|
||||
});
|
||||
await nextTick();
|
||||
for (const selector of [
|
||||
'.cockpit-orbital-flag',
|
||||
'.cockpit-orbital-owner-badge',
|
||||
'.cockpit-orbital-operator',
|
||||
'.cockpit-orbital-ident',
|
||||
'#cockpit-orbital-tle',
|
||||
])
|
||||
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();
|
||||
assert.equal(
|
||||
f.text('.cockpit-orbital-ident-text'),
|
||||
'EPOCH 2026-11-04 08:12Z',
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,478 @@
|
||||
/**
|
||||
* Ground focus in the Cockpit's orbital view: a site's Live Signals row, or
|
||||
* a click on a mapped site's marker, keeps the camera on that site as the
|
||||
* satellite moves; clicking elsewhere, the site's row again, NADIR or the
|
||||
* site leaving the off-nadir reach eases the view back. Sites come
|
||||
* from the Mapped Installations layer's own records and pick ids. Bound to
|
||||
* the Cockpit controller like the orbital view itself
|
||||
* (src/ui/cockpitOrbitalView.js); its state lives on the orbital session, so
|
||||
* it ends with the session.
|
||||
*/
|
||||
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 {
|
||||
easeFocusRemainder,
|
||||
focusEaseDtMs,
|
||||
focusInReach,
|
||||
focusLook,
|
||||
pointsInReach,
|
||||
} from '../cockpitOrbitalFocus.js';
|
||||
import { isPointerFree } from '../data/inputOwnership.js';
|
||||
|
||||
const NADIR_LOOK = Object.freeze({ yawDeg: 0, pitchDeg: 0 });
|
||||
|
||||
/** The Mapped Installations layer's id. */
|
||||
const SITES_LAYER_ID = 'military-installations';
|
||||
|
||||
/** The most sites asked of the layer around the sub-satellite point. */
|
||||
const SITE_QUERY_MAX = 500;
|
||||
|
||||
/** How long a site the layer dropped stays listed, ms (it may come back). */
|
||||
const SITE_MEMORY_MS = 10_000;
|
||||
|
||||
/** The farthest from the sub-satellite point a listed site may lie, m. */
|
||||
const SITE_QUERY_MAX_RANGE_M = 3_000_000;
|
||||
|
||||
/** The greatest angle off nadir the reach allows: 45° on both axes. */
|
||||
const REACH_CORNER_RAD = Math.acos(Math.cos(Math.PI / 4) ** 2);
|
||||
|
||||
/**
|
||||
* How far over the ground the reach extends from the sub-satellite point,
|
||||
* m: the central angle at the reach's corner off nadir (or the horizon, if
|
||||
* nearer), with a little margin, capped. Sites farther out are never asked
|
||||
* of the layer.
|
||||
*/
|
||||
function reachGroundRangeM(altitudeM) {
|
||||
const R = ORBITAL_EARTH_RADIUS_M;
|
||||
const h = Math.max(0, Number.isFinite(altitudeM) ? altitudeM : 0);
|
||||
const sine = ((R + h) / R) * Math.sin(REACH_CORNER_RAD);
|
||||
const central =
|
||||
sine >= 1 ? Math.acos(R / (R + h)) : Math.asin(sine) - REACH_CORNER_RAD;
|
||||
return Math.min(SITE_QUERY_MAX_RANGE_M, R * central * 1.05);
|
||||
}
|
||||
|
||||
/** Whether the user asked for reduced motion: focus turns then cut. */
|
||||
function prefersReducedMotion() {
|
||||
return Boolean(
|
||||
globalThis.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches,
|
||||
);
|
||||
}
|
||||
|
||||
function inOrbit(controller) {
|
||||
return (
|
||||
controller.active &&
|
||||
!controller.destroyed &&
|
||||
controller.subjectKind === 'satellite' &&
|
||||
Boolean(controller.orbital)
|
||||
);
|
||||
}
|
||||
|
||||
function sitesLayer(controller) {
|
||||
return controller.services?.militaryInstallationsLayer ?? null;
|
||||
}
|
||||
|
||||
/** Whether the Mapped Installations layer is on (unknown reads as off). */
|
||||
function sitesLayerOn(controller) {
|
||||
const isLayerEnabled = controller.services?.isLayerEnabled;
|
||||
return typeof isLayerEnabled === 'function'
|
||||
? isLayerEnabled(SITES_LAYER_ID) !== false
|
||||
: false;
|
||||
}
|
||||
|
||||
/**
|
||||
* A mapped site by id: as the layer has it loaded now, else, while the
|
||||
* layer is on, as the focus or the Live Signals rows last saw it. The layer
|
||||
* reloads its thinned view as the camera moves, so a site in view can leave
|
||||
* its records for a moment; a site does not move, so its last position
|
||||
* stands. Null with the layer off or the site never seen.
|
||||
*/
|
||||
function siteById(controller, id) {
|
||||
let live = null;
|
||||
try {
|
||||
live = sitesLayer(controller)?.getById?.(id) ?? null;
|
||||
} catch {
|
||||
live = null;
|
||||
}
|
||||
if (live) return live;
|
||||
if (!sitesLayerOn(controller)) return null;
|
||||
const state = controller.orbital;
|
||||
const key = String(id);
|
||||
if (state?.focus?.key === key && state.focus.site) return state.focus.site;
|
||||
return state?.listedSites?.get(key)?.site ?? null;
|
||||
}
|
||||
|
||||
/** Where a site is drawn, ECEF, or null. */
|
||||
function sitePosition(site) {
|
||||
const p = site?.position;
|
||||
return p &&
|
||||
Number.isFinite(p.x) &&
|
||||
Number.isFinite(p.y) &&
|
||||
Number.isFinite(p.z)
|
||||
? { x: p.x, y: p.y, z: p.z }
|
||||
: null;
|
||||
}
|
||||
|
||||
/** The mapped site a canvas position shows, through the layer's picks. */
|
||||
function siteAt(controller, position) {
|
||||
let picked = null;
|
||||
try {
|
||||
picked = findQuery(controller.viewer)?.pick(position.x, position.y) ?? null;
|
||||
} catch {
|
||||
picked = null;
|
||||
}
|
||||
if (!picked) return null;
|
||||
try {
|
||||
return sitesLayer(controller)?.findByPick?.(picked) ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The focus look at a site from the last frame's satellite, or null. */
|
||||
function lookAt(state, site) {
|
||||
const frame = state.focusFrame;
|
||||
if (!frame) return null;
|
||||
return focusLook(frame.nadir, frame.position, sitePosition(site));
|
||||
}
|
||||
|
||||
/**
|
||||
* Point the view at a mapped site and keep it there: from the view as it is
|
||||
* now, so switching targets turns rather than jumps. A site beyond the
|
||||
* reach is refused.
|
||||
* @returns {boolean} True when the focus is on that site.
|
||||
*/
|
||||
function startFocus(site) {
|
||||
const state = this.orbital;
|
||||
const look = lookAt(state, site);
|
||||
// Before the first frame there is nothing to measure against; the frame
|
||||
// that follows checks the reach.
|
||||
if (state.focusFrame && !focusInReach(look)) return false;
|
||||
state.focus = {
|
||||
key: String(site.id),
|
||||
label: String(site.name || site.id),
|
||||
// Where the site is, kept while the layer reloads around it.
|
||||
site: {
|
||||
id: site.id,
|
||||
name: site.name,
|
||||
class: site.class,
|
||||
position: sitePosition(site),
|
||||
},
|
||||
look,
|
||||
// The view minus the target's look, eased away; set on the next frame.
|
||||
remainder: null,
|
||||
};
|
||||
state.focusReleasing = false;
|
||||
if (look) state.lookTarget = clampOrbitalLook(look);
|
||||
this.refreshOrbitalSignals?.();
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* End the focus. The view eases back to nadir on the focus's clock (cut
|
||||
* under reduced motion), or with `handOver` stays where it is for an arrow
|
||||
* key to tilt on from.
|
||||
* @param {{handOver?: boolean}} [options]
|
||||
* @returns {boolean} True when a focus was ended.
|
||||
*/
|
||||
export function releaseOrbitalFocus({ handOver = false } = {}) {
|
||||
const state = this.orbital;
|
||||
if (!state?.focus) {
|
||||
// An arrow during the ease back takes the arrows' own clock again and
|
||||
// tilts on from where the view is, not from the nadir it was easing to.
|
||||
if (handOver && state?.focusReleasing) {
|
||||
state.lookTarget = clampOrbitalLook(state.lookView);
|
||||
state.focusReleasing = false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
state.focus = null;
|
||||
if (handOver) {
|
||||
state.lookTarget = clampOrbitalLook(state.lookView);
|
||||
state.focusReleasing = false;
|
||||
} else {
|
||||
state.lookTarget = { ...NADIR_LOOK };
|
||||
if (prefersReducedMotion()) {
|
||||
state.lookView = { ...NADIR_LOOK };
|
||||
state.focusReleasing = false;
|
||||
} else state.focusReleasing = true;
|
||||
}
|
||||
this.refreshOrbitalSignals?.();
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* A site's Live Signals row: focus that site, switch to it from another, or
|
||||
* end the focus when it is the one held.
|
||||
* @param {string} key The site's id in the Mapped Installations layer.
|
||||
* @returns {boolean} True when the focus changed.
|
||||
*/
|
||||
export function toggleOrbitalFocus(key) {
|
||||
if (!inOrbit(this) || key === null || key === undefined) return false;
|
||||
const state = this.orbital;
|
||||
if (state.focus?.key === String(key)) return releaseOrbitalFocus.call(this);
|
||||
const site = siteById(this, String(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: 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.
|
||||
*/
|
||||
export function onOrbitalDoubleClick(position) {
|
||||
if (!inOrbit(this) || !isPointerFree()) return false;
|
||||
if (!Number.isFinite(position?.x) || !Number.isFinite(position?.y))
|
||||
return false;
|
||||
const site = siteAt(this, position);
|
||||
if (!site) return false;
|
||||
// A site beyond the reach is not focused, but still never tracked.
|
||||
if (this.orbital.focus?.key !== String(site.id)) startFocus.call(this, site);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* A click on the orbital picture. One on a mapped ground point in reach
|
||||
* focuses it; any other click ends a focus. A click a tool owns (drawing)
|
||||
* is left alone, as is every click outside orbit.
|
||||
* @param {{x: number, y: number}|null|undefined} position Canvas position.
|
||||
* @returns {boolean} True when the click focused a point.
|
||||
*/
|
||||
export function onOrbitalClick(position) {
|
||||
if (!inOrbit(this) || !isPointerFree()) return false;
|
||||
if (!Number.isFinite(position?.x) || !Number.isFinite(position?.y))
|
||||
return false;
|
||||
const site = siteAt(this, position);
|
||||
const state = this.orbital;
|
||||
if (site) {
|
||||
if (state.focus?.key === String(site.id)) return true;
|
||||
if (startFocus.call(this, site)) return true;
|
||||
// A mapped site beyond the reach is a click elsewhere: the focus ends.
|
||||
}
|
||||
releaseOrbitalFocus.call(this);
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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() {
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The orbital view's look for one frame, while a focus holds or is ending.
|
||||
* A held focus aims at its target: the live look plus whatever is left of
|
||||
* the turn onto it. The focus ends, easing back, when its layer is turned
|
||||
* off or its site is beyond the reach (a site the layer stops loading is
|
||||
* held from its last record). Also rebuilds
|
||||
* the orbital Live Signals rows on their own clock.
|
||||
* @param {object} state The orbital session.
|
||||
* @param {{direction: object, up: object, right: object}} nadir This
|
||||
* frame's nadir frame.
|
||||
* @param {{x: number, y: number, z: number}} position The satellite, ECEF.
|
||||
* @param {number} nowMs
|
||||
* @returns {boolean} True when it placed `state.lookView` itself.
|
||||
*/
|
||||
export function updateOrbitalFocus(state, nadir, position, nowMs) {
|
||||
state.focusFrame = {
|
||||
nadir,
|
||||
position: { x: position.x, y: position.y, z: position.z },
|
||||
};
|
||||
// After a satellite switch the first frame on the new satellite (the hop
|
||||
// landed, or none) is the one the rows can be measured from: rebuild now.
|
||||
if (state.awaitingFrame && !state.hop) {
|
||||
state.awaitingFrame = false;
|
||||
state.signalsMs = -Infinity;
|
||||
}
|
||||
const dtMs = nowMs - (state.lookLastMs || nowMs);
|
||||
let aimed = false;
|
||||
const focus = state.focus;
|
||||
if (focus) {
|
||||
const site = siteById(this, focus.key);
|
||||
const look = site
|
||||
? focusLook(nadir, state.focusFrame.position, sitePosition(site))
|
||||
: null;
|
||||
if (!focusInReach(look)) {
|
||||
releaseOrbitalFocus.call(this);
|
||||
} else {
|
||||
focus.look = look;
|
||||
const reduced = prefersReducedMotion();
|
||||
focus.remainder = focus.remainder
|
||||
? easeFocusRemainder(focus.remainder, dtMs, { immediate: reduced })
|
||||
: reduced
|
||||
? { ...NADIR_LOOK }
|
||||
: {
|
||||
yawDeg: state.lookView.yawDeg - look.yawDeg,
|
||||
pitchDeg: state.lookView.pitchDeg - look.pitchDeg,
|
||||
};
|
||||
state.lookTarget = clampOrbitalLook(look);
|
||||
state.lookView = {
|
||||
yawDeg: look.yawDeg + focus.remainder.yawDeg,
|
||||
pitchDeg: look.pitchDeg + focus.remainder.pitchDeg,
|
||||
};
|
||||
aimed = true;
|
||||
}
|
||||
}
|
||||
this.updateOrbitalSignals?.(nowMs);
|
||||
return aimed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ease the orbital look toward its target for one frame: the look's own
|
||||
* easing, on the focus's slower clock while a focus is easing back.
|
||||
* @param {object} state The orbital session.
|
||||
* @param {number} dtMs
|
||||
* @param {{immediate?: boolean}} [options]
|
||||
* @returns {{yawDeg: number, pitchDeg: number}}
|
||||
*/
|
||||
export function easeOrbitalLook(state, dtMs, { immediate = false } = {}) {
|
||||
const view = easeLook(
|
||||
state.lookView,
|
||||
state.lookTarget,
|
||||
state.focusReleasing ? focusEaseDtMs(dtMs) : dtMs,
|
||||
{ immediate },
|
||||
);
|
||||
if (
|
||||
state.focusReleasing &&
|
||||
view.yawDeg === state.lookTarget.yawDeg &&
|
||||
view.pitchDeg === state.lookTarget.pitchDeg
|
||||
)
|
||||
state.focusReleasing = false;
|
||||
return view;
|
||||
}
|
||||
|
||||
/**
|
||||
* The focused target for the HUD: its name and the live look at it, whose
|
||||
* single off-nadir angle the readout shows. Null without a focus, or before
|
||||
* its first frame.
|
||||
* @returns {{key: string, label: string, offNadirDeg: number,
|
||||
* yawDeg: number, pitchDeg: number}|null}
|
||||
*/
|
||||
export function orbitalFocusReadout() {
|
||||
const focus = this.orbital?.focus;
|
||||
if (!focus?.look) return null;
|
||||
return {
|
||||
key: focus.key,
|
||||
label: focus.label,
|
||||
offNadirDeg: focus.look.offNadirDeg,
|
||||
yawDeg: focus.look.yawDeg,
|
||||
pitchDeg: focus.look.pitchDeg,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The mapped sites the orbital view can be turned to, for the Live Signals
|
||||
* rows: the Mapped Installations layer's loaded sites around the
|
||||
* sub-satellite point (`getNearby`), with those seen in the last
|
||||
* SITE_MEMORY_MS and the focused one, facing the satellite and within the
|
||||
* off-nadir reach, nearest to nadir first. Empty before the first frame or
|
||||
* with the layer off.
|
||||
* @param {{latitude: number, longitude: number, altitudeM: number}} info
|
||||
* The ridden satellite.
|
||||
* @returns {{entries: Array<{site: object, offNadirDeg: number,
|
||||
* focused: boolean}>}}
|
||||
*/
|
||||
export function orbitalSitesInReach(info) {
|
||||
const state = this.orbital;
|
||||
const frame = state?.focusFrame;
|
||||
const layer = sitesLayer(this);
|
||||
// The layer keeps its records when it is turned off: nothing is listed
|
||||
// then, and no row is left to focus from.
|
||||
if (state && !sitesLayerOn(this)) state.listedSites = new Map();
|
||||
if (!frame || typeof layer?.getNearby !== 'function' || !sitesLayerOn(this))
|
||||
return { entries: [] };
|
||||
if (!Number.isFinite(info?.latitude) || !Number.isFinite(info?.longitude))
|
||||
return { entries: [] };
|
||||
const rangeM = reachGroundRangeM(info.altitudeM);
|
||||
let sites = [];
|
||||
try {
|
||||
sites = layer.getNearby(
|
||||
fromDegrees(info.longitude, info.latitude, 0),
|
||||
rangeM,
|
||||
SITE_QUERY_MAX,
|
||||
);
|
||||
} catch {
|
||||
sites = [];
|
||||
}
|
||||
const byId = new Map();
|
||||
const candidates = [];
|
||||
for (const site of sites || []) {
|
||||
const position = sitePosition(site);
|
||||
if (!position || site.id === null || site.id === undefined) continue;
|
||||
const key = String(site.id);
|
||||
byId.set(key, site);
|
||||
candidates.push({ key, position });
|
||||
}
|
||||
// In orbit the layer reloads its thinned view every second or so, and a
|
||||
// site in view can drop out of its records and come back. Sites do not
|
||||
// move: one seen within SITE_MEMORY_MS stays a candidate, so the rows hold
|
||||
// still and a row's site can be focused from what the rows show.
|
||||
const nowMs = performance.now();
|
||||
const remembered = new Map();
|
||||
for (const [key, entry] of state.listedSites ?? []) {
|
||||
if (nowMs - entry.seenMs > SITE_MEMORY_MS || byId.has(key)) continue;
|
||||
remembered.set(key, entry);
|
||||
byId.set(key, entry.site);
|
||||
candidates.push({ key, position: entry.site.position });
|
||||
}
|
||||
// The focused site stays a candidate while the layer reloads around it.
|
||||
const held = state.focus;
|
||||
if (held?.site?.position && !byId.has(held.key)) {
|
||||
byId.set(held.key, held.site);
|
||||
candidates.push({ key: held.key, position: held.site.position });
|
||||
}
|
||||
for (const [key, site] of byId)
|
||||
if (!remembered.has(key))
|
||||
remembered.set(key, {
|
||||
site: { ...site, position: sitePosition(site) },
|
||||
seenMs: nowMs,
|
||||
});
|
||||
state.listedSites = remembered;
|
||||
const focusKey = state.focus?.key ?? null;
|
||||
return {
|
||||
entries: pointsInReach(candidates, {
|
||||
nadir: frame.nadir,
|
||||
satellite: frame.position,
|
||||
}).map(({ key, offNadirDeg }) => ({
|
||||
site: byId.get(key),
|
||||
offNadirDeg,
|
||||
focused: key === focusKey,
|
||||
})),
|
||||
};
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,194 @@
|
||||
/**
|
||||
* The satellites around the one the Cockpit's orbital view rides: the
|
||||
* nearest ones for the Live Signals rows, and riding one of them (or going
|
||||
* back to the one before) from its row. The view stays in orbit: the
|
||||
* satellites layer tracks the
|
||||
* new satellite, the Cockpit takes the camera straight back, any ground
|
||||
* 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 { stopFollowing } from '../data/followed.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
import { zoomTransitionProgress } from '../cockpitOrbital.js';
|
||||
import {
|
||||
ORBITAL_HOP_MS,
|
||||
ORBITAL_SATELLITES_MAX,
|
||||
hopPosition,
|
||||
} from '../cockpitOrbitalSatellites.js';
|
||||
|
||||
/** Whether the user asked for reduced motion: hops then cut. */
|
||||
function prefersReducedMotion() {
|
||||
return Boolean(
|
||||
globalThis.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches,
|
||||
);
|
||||
}
|
||||
|
||||
function inOrbit(controller) {
|
||||
return (
|
||||
controller.active &&
|
||||
!controller.destroyed &&
|
||||
controller.subjectKind === 'satellite' &&
|
||||
Boolean(controller.orbital)
|
||||
);
|
||||
}
|
||||
|
||||
/** The satellites ridden in this orbital visit, oldest first. */
|
||||
function visits(controller) {
|
||||
const state = controller.orbital;
|
||||
if (!Array.isArray(state.visits)) state.visits = [];
|
||||
const current = controller.subjectId;
|
||||
if (current !== null && current !== undefined && !state.visits.length)
|
||||
state.visits.push(current);
|
||||
return state.visits;
|
||||
}
|
||||
|
||||
/**
|
||||
* The satellites nearest the ridden one, nearest first (debris left out):
|
||||
* the layer's bounded nearest query, measured from the satellite itself
|
||||
* (not the camera, which may still be hopping to it).
|
||||
* @returns {Array<object>} As the layer's `getNearestPositions`.
|
||||
*/
|
||||
export function orbitalNearbySatellites() {
|
||||
const layer = this.services?.satellitesLayer;
|
||||
if (typeof layer?.getNearestPositions !== 'function') return [];
|
||||
try {
|
||||
const from = layer.getCockpitPosition?.();
|
||||
if (!from) return [];
|
||||
return (
|
||||
layer.getNearestPositions(from, ORBITAL_SATELLITES_MAX, {
|
||||
excludeIds: [this.subjectId],
|
||||
excludeClasses: ['debris'],
|
||||
}) || []
|
||||
);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The satellite ridden before this one in this orbital visit, or null.
|
||||
* @returns {number|string|null}
|
||||
*/
|
||||
export function previousOrbitalSatellite() {
|
||||
if (!inOrbit(this)) return null;
|
||||
const ridden = visits(this);
|
||||
return ridden.length > 1 ? ridden[ridden.length - 2] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ride the satellite a Live Signals row names: back to the one ridden before
|
||||
* (its RETURN row), or on to another, remembered so RETURN can come back.
|
||||
* @param {number|string} noradId
|
||||
* @returns {boolean} True when the ridden satellite changed.
|
||||
*/
|
||||
export function rideOrbitalSatellite(noradId) {
|
||||
if (!inOrbit(this)) return false;
|
||||
const ridden = visits(this);
|
||||
const back = ridden.length > 1 ? ridden[ridden.length - 2] : null;
|
||||
if (back !== null && String(back) === String(noradId)) {
|
||||
if (!switchOrbitalSatellite.call(this, back)) {
|
||||
// It left the catalogue: forget it, so RETURN offers the one before.
|
||||
ridden.splice(ridden.length - 2, 1);
|
||||
this.refreshOrbitalSignals?.();
|
||||
return false;
|
||||
}
|
||||
ridden.pop();
|
||||
} else {
|
||||
if (!switchOrbitalSatellite.call(this, noradId)) return false;
|
||||
ridden.push(this.subjectId);
|
||||
}
|
||||
// The RETURN row follows the history just changed.
|
||||
this.refreshOrbitalSignals?.();
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ride another satellite without leaving orbit. The satellites layer tracks
|
||||
* it (as a click on its point would); the Cockpit takes the camera back at
|
||||
* once, ends any ground focus with the view back at nadir, and starts the
|
||||
* hop from where the camera is.
|
||||
* @param {number|string} noradId
|
||||
* @returns {boolean} True when the ridden satellite changed.
|
||||
*/
|
||||
export function switchOrbitalSatellite(noradId) {
|
||||
if (!inOrbit(this)) return false;
|
||||
if (String(noradId) === String(this.subjectId)) return false;
|
||||
const layer = this.services?.satellitesLayer;
|
||||
const state = this.orbital;
|
||||
const from = state.focusFrame?.position ?? null;
|
||||
let tracked = false;
|
||||
try {
|
||||
tracked = Boolean(layer?.trackById?.(noradId, { origin: 'user' }));
|
||||
} catch {
|
||||
tracked = false;
|
||||
}
|
||||
// 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
|
||||
// on the next frame rather than ride something it did not ask for.
|
||||
return false;
|
||||
}
|
||||
layer.setCockpitSubject?.(info.noradId);
|
||||
this.subjectId = info.noradId;
|
||||
state.focus = null;
|
||||
state.focusReleasing = !prefersReducedMotion();
|
||||
state.lookTarget = { yawDeg: 0, pitchDeg: 0 };
|
||||
if (!state.focusReleasing) state.lookView = { yawDeg: 0, pitchDeg: 0 };
|
||||
state.hop =
|
||||
from && !prefersReducedMotion()
|
||||
? { from: { ...from }, startMs: performance.now() }
|
||||
: null;
|
||||
// The rows measure from the camera's frame, still the old satellite's:
|
||||
// until the camera is on the new one, they list no sites or satellites.
|
||||
state.awaitingFrame = true;
|
||||
state.previousUp = null;
|
||||
// The field of view is still the old satellite's until the next frame; the
|
||||
// HUD published below sizes the strip from the settled zoom meanwhile.
|
||||
state.verticalFov = null;
|
||||
state.place = undefined;
|
||||
state.placeTracker?.reset?.();
|
||||
this.lastHudUpdateMs = 0;
|
||||
this.lastContextUpdateMs = 0;
|
||||
this.dispatchCockpitModeChanged(true, info);
|
||||
// The new satellite's TRACK ACQUIRED replaces the old one, time and all.
|
||||
this.signalItems = this.signalItems.filter((item) => item.key !== 'track');
|
||||
this.signalSignatures.delete('track');
|
||||
this.pushCockpitSignal(
|
||||
'track',
|
||||
'track',
|
||||
t('TRACK ACQUIRED'),
|
||||
t('{label} · NADIR VIEW', { label: info.name }),
|
||||
);
|
||||
this.updateOrbitalHud(info);
|
||||
this.refreshOrbitalSignals?.();
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 {{x: number, y: number, z: number}} position The ridden
|
||||
* satellite this frame (ECEF).
|
||||
* @param {number} nowMs
|
||||
* @returns {{x: number, y: number, z: number}}
|
||||
*/
|
||||
export function orbitalEyePosition(state, position, nowMs) {
|
||||
const hop = state.hop;
|
||||
if (!hop) return position;
|
||||
const progress = zoomTransitionProgress(nowMs - hop.startMs, {
|
||||
durationMs: ORBITAL_HOP_MS,
|
||||
});
|
||||
if (progress >= 1) {
|
||||
state.hop = null;
|
||||
return position;
|
||||
}
|
||||
const eye = hopPosition(hop.from, position, progress);
|
||||
if (!eye) {
|
||||
state.hop = null;
|
||||
return position;
|
||||
}
|
||||
return { x: eye.x, y: eye.y, z: eye.z };
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
/**
|
||||
* The Live Signals rows in the orbital view. Orbit feeds no Contacts
|
||||
* snapshot, so the rows are built here, the way the aircraft rows are built
|
||||
* from one (src/ui/cockpitSignals.js): the TRACK ACQUIRED row, the nearest
|
||||
* mapped sites in reach (a row focuses its site, or releases the one held),
|
||||
* a RETURN row to the satellite ridden before, and the nearest satellites (a
|
||||
* row rides it). With Mapped Installations off a status row says why no
|
||||
* site is listed. Five rows at most, with stable keys, rebuilt on their own
|
||||
* clock. Bound to the Cockpit controller.
|
||||
*/
|
||||
import { formatNumber, t } from '../i18n/index.js';
|
||||
import { ORBITAL_REACH_REFRESH_MS } from '../cockpitOrbitalFocus.js';
|
||||
import { bearingBetweenCoordinates, relativeBearing } from '../cockpitMath.js';
|
||||
import {
|
||||
installationClassLabel,
|
||||
installationTitle,
|
||||
} from '../layers/installations/classLabel.js';
|
||||
import { formatCockpitDistance } from './cockpitPresentation.js';
|
||||
import { orbitalSitesInReach } from './cockpitOrbitalFocus.js';
|
||||
import {
|
||||
orbitalNearbySatellites,
|
||||
previousOrbitalSatellite,
|
||||
} from './cockpitOrbitalSatellites.js';
|
||||
|
||||
/** The most rows Live Signals shows, as for aircraft. */
|
||||
const SIGNAL_ROWS = 5;
|
||||
|
||||
/** Site rows when there are satellites to list too. */
|
||||
const SITE_ROWS = 2;
|
||||
|
||||
const SITES_LAYER_ID = 'military-installations';
|
||||
|
||||
function inOrbit(controller) {
|
||||
return (
|
||||
controller.active &&
|
||||
!controller.destroyed &&
|
||||
controller.subjectKind === 'satellite' &&
|
||||
Boolean(controller.orbital)
|
||||
);
|
||||
}
|
||||
|
||||
function sitesLayerOn(controller) {
|
||||
const isLayerEnabled = controller.services?.isLayerEnabled;
|
||||
return typeof isLayerEnabled === 'function'
|
||||
? isLayerEnabled(SITES_LAYER_ID) !== false
|
||||
: false;
|
||||
}
|
||||
|
||||
/** Where another satellite is, from the top of the frame, worded. */
|
||||
function bearingWords(info, satellite) {
|
||||
const bearing = bearingBetweenCoordinates(
|
||||
info.latitude,
|
||||
info.longitude,
|
||||
satellite.latitude,
|
||||
satellite.longitude,
|
||||
);
|
||||
// Relative to the top of the frame: the ground track, or north.
|
||||
const relative = relativeBearing(
|
||||
bearing,
|
||||
Number.isFinite(info.groundTrackDeg) ? info.groundTrackDeg : 0,
|
||||
);
|
||||
if (relative === null) return t('BRG —');
|
||||
if (Math.abs(relative) < 8) return t('AHEAD');
|
||||
return t('{side} {angle}', {
|
||||
side: relative < 0 ? t('L') : t('R'),
|
||||
angle: `${String(Math.round(Math.abs(relative))).padStart(3, '0')}°`,
|
||||
});
|
||||
}
|
||||
|
||||
/** The ids the rows of one layer show now, in their order. */
|
||||
function shownIds(controller, layerId, keyPrefix) {
|
||||
return controller.signalItems
|
||||
.filter((item) => item.key.startsWith(keyPrefix))
|
||||
.filter((item) => item.target?.layerId === layerId)
|
||||
.map((item) => String(item.target.id));
|
||||
}
|
||||
|
||||
/**
|
||||
* Order rows so those already shown keep their places while they still
|
||||
* qualify; new ones fill after them, nearest first. Sites pass under a low
|
||||
* orbit in seconds: re-sorting by angle every beat would move a row away
|
||||
* from the pointer reaching for it.
|
||||
* @param {Array<object>} entries Nearest first.
|
||||
* @param {(entry: object) => string} keyOf
|
||||
* @param {Array<string>} shown Ids shown now, in order.
|
||||
* @param {string|null} [first] An id that goes first (the focused site).
|
||||
*/
|
||||
function stickyOrder(entries, keyOf, shown, first = null) {
|
||||
const byKey = new Map(entries.map((entry) => [keyOf(entry), entry]));
|
||||
const ordered = [];
|
||||
const take = (key) => {
|
||||
const entry = byKey.get(key);
|
||||
if (!entry) return;
|
||||
ordered.push(entry);
|
||||
byKey.delete(key);
|
||||
};
|
||||
if (first !== null) take(first);
|
||||
for (const key of shown) take(key);
|
||||
for (const entry of entries) take(keyOf(entry));
|
||||
return ordered;
|
||||
}
|
||||
|
||||
/** The site rows: the focused site first, then those shown, then the nearest. */
|
||||
function siteRows(info, { settled = true } = {}) {
|
||||
if (!sitesLayerOn(this)) {
|
||||
// Also forgets the sites last listed, so none is focused from a row.
|
||||
orbitalSitesInReach.call(this, info);
|
||||
return [
|
||||
{
|
||||
key: 'site-status',
|
||||
tone: 'warning',
|
||||
title: t('SITES STANDBY'),
|
||||
detail: t('ENABLE MAPPED INSTALLATIONS FOR SITE PINGS'),
|
||||
target: null,
|
||||
},
|
||||
];
|
||||
}
|
||||
if (!settled) return [];
|
||||
const { entries } = orbitalSitesInReach.call(this, info);
|
||||
const focused = entries.find((entry) => entry.focused);
|
||||
return stickyOrder(
|
||||
entries,
|
||||
(entry) => String(entry.site.id),
|
||||
shownIds(this, SITES_LAYER_ID, 'site:'),
|
||||
focused ? String(focused.site.id) : null,
|
||||
).map(({ site, offNadirDeg, focused }) => {
|
||||
const title = installationTitle(site.name) || t('Unnamed site');
|
||||
const angle = t('OFF-NADIR {angle}°', {
|
||||
angle: formatNumber(offNadirDeg, {
|
||||
minimumFractionDigits: 1,
|
||||
maximumFractionDigits: 1,
|
||||
}),
|
||||
});
|
||||
const words = [installationClassLabel(site.class), angle];
|
||||
// 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.
|
||||
tone: focused ? 'track' : 'nearby',
|
||||
title,
|
||||
detail: words.join(' · '),
|
||||
target: {
|
||||
layerId: SITES_LAYER_ID,
|
||||
id: String(site.id),
|
||||
label: focused
|
||||
? t('Release the camera from {name}', { name: title })
|
||||
: t('Keep the camera on {name}', { name: title }),
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** The satellite rows: RETURN to the one before, then the nearest. */
|
||||
function satelliteRows(info) {
|
||||
const state = this.orbital;
|
||||
state.satelliteNames ??= new Map();
|
||||
state.satelliteNames.set(String(info.noradId), info.name);
|
||||
const rows = [];
|
||||
const back = previousOrbitalSatellite.call(this);
|
||||
if (back !== null) {
|
||||
const name = state.satelliteNames.get(String(back)) ?? String(back);
|
||||
rows.push({
|
||||
key: `satellite-return:${back}`,
|
||||
tone: 'nearby',
|
||||
title: t('RETURN · {name}', { name }),
|
||||
detail: t('PREVIOUS SATELLITE'),
|
||||
target: {
|
||||
layerId: 'satellites',
|
||||
id: String(back),
|
||||
label: t('Return to {name}', { name }),
|
||||
},
|
||||
});
|
||||
}
|
||||
// Measured only once the camera is on the ridden satellite.
|
||||
const measured = !state.hop && !state.awaitingFrame;
|
||||
const nearby = measured
|
||||
? stickyOrder(
|
||||
orbitalNearbySatellites.call(this),
|
||||
(satellite) => String(satellite.id),
|
||||
shownIds(this, 'satellites', 'satellite:'),
|
||||
)
|
||||
: [];
|
||||
for (const satellite of nearby) {
|
||||
if (back !== null && String(satellite.id) === String(back)) continue;
|
||||
const name = String(satellite.label ?? satellite.id);
|
||||
state.satelliteNames.set(String(satellite.id), name);
|
||||
rows.push({
|
||||
key: `satellite:${satellite.id}`,
|
||||
tone: 'nearby',
|
||||
title: name,
|
||||
detail: [
|
||||
t('SATELLITE'),
|
||||
bearingWords(info, satellite),
|
||||
formatCockpitDistance(satellite.distanceM),
|
||||
].join(' · '),
|
||||
target: {
|
||||
layerId: 'satellites',
|
||||
id: String(satellite.id),
|
||||
label: t('Ride {name}', { name }),
|
||||
},
|
||||
});
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rebuild the orbital Live Signals rows now: after a focus change, a
|
||||
* satellite switch, or on their clock. TRACK ACQUIRED stays first; sites
|
||||
* take two rows when satellites fill the rest, more when they do not.
|
||||
*/
|
||||
export function refreshOrbitalSignals() {
|
||||
if (!inOrbit(this)) return;
|
||||
const info = this.lastSubjectInfo;
|
||||
if (info?.kind !== 'satellite') return;
|
||||
this.orbital.signalsMs = performance.now();
|
||||
const previous = new Map(this.signalItems.map((item) => [item.key, item]));
|
||||
const rows = [];
|
||||
const track = this.signalItems.find((item) => item.key === 'track');
|
||||
if (track) rows.push(track);
|
||||
// While the camera hops to a new satellite its frame is not the
|
||||
// satellite's yet: the site rows wait for it (the status row does not).
|
||||
const settled = !this.orbital.hop && !this.orbital.awaitingFrame;
|
||||
const sites = siteRows.call(this, info, { settled });
|
||||
const satellites = satelliteRows.call(this, info);
|
||||
const free = SIGNAL_ROWS - rows.length;
|
||||
rows.push(...sites.slice(0, Math.max(SITE_ROWS, free - satellites.length)));
|
||||
rows.push(...satellites.slice(0, SIGNAL_ROWS - rows.length));
|
||||
const now = Date.now();
|
||||
this.signalItems = rows.map((row) => ({
|
||||
...row,
|
||||
timestamp: previous.get(row.key)?.timestamp ?? row.timestamp ?? now,
|
||||
}));
|
||||
this.signalSignatures.clear();
|
||||
this.publishCockpitSignals();
|
||||
}
|
||||
|
||||
/**
|
||||
* The rows' clock: rebuild once every ORBITAL_REACH_REFRESH_MS.
|
||||
* @param {number} nowMs
|
||||
*/
|
||||
export function updateOrbitalSignals(nowMs) {
|
||||
const state = this.orbital;
|
||||
if (!state) return;
|
||||
if (nowMs - (state.signalsMs ?? -Infinity) < ORBITAL_REACH_REFRESH_MS) return;
|
||||
refreshOrbitalSignals.call(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* A click on an orbital row: a site row focuses its site or releases it, a
|
||||
* satellite row rides that satellite (RETURN goes back).
|
||||
* @param {string} layerId
|
||||
* @param {string} id
|
||||
* @returns {boolean} True in orbit, where the row is this module's.
|
||||
*/
|
||||
export function handleOrbitalSignalClick(layerId, id) {
|
||||
if (!inOrbit(this)) return false;
|
||||
if (layerId === SITES_LAYER_ID) this.toggleOrbitalFocus(id);
|
||||
else if (layerId === 'satellites') this.rideOrbitalSatellite(id);
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,714 @@
|
||||
/** The orbital (satellite) view of the Cockpit controller: camera, zoom, look and HUD. */
|
||||
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_SETTLE_BLUR_PX,
|
||||
ORBITAL_ZOOM_LADDER,
|
||||
ORBITAL_ZOOM_TRANSITION_MS,
|
||||
footprintWidthKm,
|
||||
fovForZoom,
|
||||
interpolateZoomFov,
|
||||
nadirOrientation,
|
||||
nextOrbitalZoom,
|
||||
offNadirAngleDeg,
|
||||
offNadirOrientation,
|
||||
offNadirCentreMeetsEarth,
|
||||
offNadirSwathScale,
|
||||
orbitalBaseFovRad,
|
||||
orbitalMaxZoom,
|
||||
previousOrbitalZoom,
|
||||
sensorStripFraction,
|
||||
sensorSwathZoom,
|
||||
wheelZoomStep,
|
||||
zoomSettleHolding,
|
||||
zoomTransitionState,
|
||||
} from '../cockpitOrbital.js';
|
||||
import {
|
||||
clampOrbitalLook,
|
||||
lookIsOffset,
|
||||
orbitalLookReadoutParts,
|
||||
stepOrbitalLook,
|
||||
} from '../cockpitLook.js';
|
||||
import { cockpitUiUpdateDue } from '../cockpitMath.js';
|
||||
import { createPlaceTracker, nearPlaceRadiusKm } from '../data/placeBelow.js';
|
||||
import { isPointerFree } from '../data/inputOwnership.js';
|
||||
import { zoomableSwathKm } from '../layers/satellites/sensors.js';
|
||||
import {
|
||||
easeOrbitalLook,
|
||||
orbitalFocusReadout,
|
||||
releaseOrbitalFocus,
|
||||
updateOrbitalFocus,
|
||||
} from './cockpitOrbitalFocus.js';
|
||||
import { orbitalEyePosition } from './cockpitOrbitalSatellites.js';
|
||||
import {
|
||||
COCKPIT_CONTEXT_UPDATE_MS,
|
||||
COCKPIT_HUD_UPDATE_MS,
|
||||
compassPointLabel,
|
||||
formatCockpitCoordinate,
|
||||
} from './cockpitPresentation.js';
|
||||
|
||||
/**
|
||||
* How often the orbital view asks for a regional brief. A low orbit crosses
|
||||
* the briefing's 25 km refresh distance every few seconds, so the sub-satellite
|
||||
* point is briefed on a clock instead.
|
||||
*/
|
||||
export const ORBITAL_BRIEF_REFRESH_MS = 60_000;
|
||||
|
||||
/** Whether the user asked for reduced motion: zoom steps and tilts cut. */
|
||||
function prefersReducedMotion() {
|
||||
return Boolean(
|
||||
globalThis.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches,
|
||||
);
|
||||
}
|
||||
|
||||
const IDLE_TRANSITION = Object.freeze({
|
||||
active: false,
|
||||
blurPx: 0,
|
||||
lockTick: false,
|
||||
});
|
||||
|
||||
const NADIR_LOOK = Object.freeze({ yawDeg: 0, pitchDeg: 0 });
|
||||
|
||||
/**
|
||||
* 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 state = {
|
||||
imagery: acquireOrbitImagery(this.services),
|
||||
zoom: ORBITAL_DEFAULT_ZOOM,
|
||||
// Wheel scrolling summed toward the next zoom step (wheelZoomStep).
|
||||
wheel: null,
|
||||
// A zoom step in flight: the magnification it started from and when.
|
||||
transition: null,
|
||||
previousUp: null,
|
||||
altitudeM: null,
|
||||
verticalFov: null,
|
||||
lastBriefMs: 0,
|
||||
lookTarget: { ...NADIR_LOOK },
|
||||
lookView: { ...NADIR_LOOK },
|
||||
lookLastMs: performance.now(),
|
||||
// What the sub-satellite point is over: undefined until the first
|
||||
// lookup lands, then a place or null (nothing named there).
|
||||
place: undefined,
|
||||
placeTracker: null,
|
||||
};
|
||||
state.placeTracker = createPlaceTracker({
|
||||
lookup: this.services.placeBelow,
|
||||
onPlace: (place) => {
|
||||
if (this.orbital !== state) return;
|
||||
state.place = place;
|
||||
if (this.lastSubjectInfo?.kind === 'satellite')
|
||||
publishOrbitalView.call(this, this.lastSubjectInfo);
|
||||
},
|
||||
});
|
||||
this.orbital = state;
|
||||
}
|
||||
|
||||
/** End the orbital session: restore the field of view and clear the HUD. */
|
||||
export function endOrbital() {
|
||||
const state = this.orbital;
|
||||
if (!state) return;
|
||||
this.orbital = null;
|
||||
state.placeTracker?.reset();
|
||||
// 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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Offer the sub-satellite point to the place tracker, with the radius a
|
||||
* populated place may lie in to be named (half the settled view's smaller
|
||||
* ground dimension, from NEAR_PLACE_MIN_ZOOM on), so a zoom step refreshes
|
||||
* the place at once.
|
||||
*/
|
||||
function trackPlace(info, nowMs) {
|
||||
const state = this.orbital;
|
||||
if (!state?.placeTracker) return;
|
||||
let nearKm = null;
|
||||
if (Number.isFinite(info.altitudeM)) {
|
||||
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(
|
||||
state.zoom,
|
||||
footprintWidthKm(info.altitudeM, fov, aspect),
|
||||
footprintWidthKm(info.altitudeM, fov, 1),
|
||||
);
|
||||
}
|
||||
state.placeTracker.update(info.latitude, info.longitude, nowMs, nearKm);
|
||||
}
|
||||
|
||||
/**
|
||||
* Lease the map for flat imagery while in orbit. Another owner already
|
||||
* holding it (an imagery comparison) keeps the map as it is.
|
||||
* @returns {{release: () => Promise<void>}|null}
|
||||
*/
|
||||
function acquireOrbitImagery(services) {
|
||||
try {
|
||||
const lease = services?.acquireOrbitImagery?.() ?? null;
|
||||
lease?.ready?.catch?.(() => {});
|
||||
return lease;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The magnification the view shows at `nowMs`, mid-step included. */
|
||||
function currentMagnification(state, baseFov, nowMs) {
|
||||
const fov = verticalFovAt(state, baseFov, nowMs).fov;
|
||||
return Math.tan(baseFov / 2) / Math.tan(fov / 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* The vertical field of view at `nowMs` and the step's HUD state. Once the
|
||||
* field of view lands, the focus pull holds until the imagery has loaded
|
||||
* (see `zoomSettleHolding`), then the reticle locks. A step that has settled
|
||||
* (lock tick over) is retired.
|
||||
*/
|
||||
function verticalFovAt(state, baseFov, nowMs, tilesLoaded = true) {
|
||||
const target = fovForZoom(baseFov, state.zoom);
|
||||
const step = state.transition;
|
||||
if (!step) return { fov: target, transition: IDLE_TRANSITION, moving: false };
|
||||
const elapsedMs = nowMs - step.startMs;
|
||||
const landedMs = elapsedMs - ORBITAL_ZOOM_TRANSITION_MS;
|
||||
if (landedMs >= 0 && step.heldMs === undefined) {
|
||||
if (zoomSettleHolding(landedMs, tilesLoaded)) {
|
||||
return {
|
||||
fov: target,
|
||||
transition: {
|
||||
active: true,
|
||||
blurPx: ORBITAL_SETTLE_BLUR_PX,
|
||||
lockTick: false,
|
||||
},
|
||||
moving: true,
|
||||
};
|
||||
}
|
||||
step.heldMs = landedMs;
|
||||
}
|
||||
// The lock tick runs from the end of the hold, not the end of the move.
|
||||
const now = zoomTransitionState(elapsedMs - (step.heldMs ?? 0));
|
||||
const fov = interpolateZoomFov(
|
||||
fovForZoom(baseFov, step.fromZoom),
|
||||
target,
|
||||
now.progress,
|
||||
);
|
||||
return {
|
||||
fov,
|
||||
transition: {
|
||||
active: now.active,
|
||||
// Settled steps carry no residue of the blur curve (sin π ≠ 0).
|
||||
blurPx: now.active ? now.blurPx : 0,
|
||||
lockTick: now.lockTick,
|
||||
},
|
||||
moving: now.active || now.lockTick,
|
||||
};
|
||||
}
|
||||
|
||||
/** Apply the field of view for the altitude and time; returns the HUD state. */
|
||||
function applyFov(state, altitudeM, nowMs) {
|
||||
const baseFov = orbitalBaseFovRad(altitudeM);
|
||||
const reading = verticalFovAt(
|
||||
state,
|
||||
baseFov,
|
||||
nowMs,
|
||||
tilesLoaded(this.viewer),
|
||||
);
|
||||
// The step's last frame (its lock tick over) publishes the idle state.
|
||||
if (state.transition && !reading.moving) {
|
||||
state.transition = null;
|
||||
reading.transition = IDLE_TRANSITION;
|
||||
}
|
||||
state.verticalFov = reading.fov;
|
||||
cameraOf(this.viewer).setFov({ vertical: reading.fov });
|
||||
return reading;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the imagery under the view has loaded. Flat imagery drapes the
|
||||
* globe; with the globe hidden (Google 3D kept) there is nothing to wait for.
|
||||
*/
|
||||
function tilesLoaded(viewer) {
|
||||
const globe = findGlobe(viewer);
|
||||
if (!globe || globe.isGlobeVisible?.() === false) return true;
|
||||
return globe.isSettled('imagery') !== false;
|
||||
}
|
||||
|
||||
function canvasAspect(viewer) {
|
||||
const canvas = canvasOf(viewer);
|
||||
const width = canvas?.clientWidth;
|
||||
const height = canvas?.clientHeight;
|
||||
return width > 0 && height > 0 ? width / height : 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* the top (north at the top for a satellite with none), tilted by the
|
||||
* off-nadir look. A low orbit moves ~7.6 km/s, so there is no cadence
|
||||
* gate here; only the HUD and briefing keep theirs.
|
||||
* @param {number} nowMs Frame time.
|
||||
*/
|
||||
export function updateOrbital(nowMs) {
|
||||
// Tracking anything from orbit (an aircraft, another satellite) ends the
|
||||
// view and leaves the camera following that target.
|
||||
if (isFollowing(this.viewer)) {
|
||||
this.exit({ restoreTracking: false });
|
||||
return;
|
||||
}
|
||||
const info = this.readSatelliteInfo();
|
||||
if (!info || info.noradId !== this.subjectId || !this.orbital) {
|
||||
this.exit({ restoreTracking: false });
|
||||
return;
|
||||
}
|
||||
const position = this.services.satellitesLayer?.getCockpitPosition?.(
|
||||
this.scratchTarget,
|
||||
);
|
||||
if (!position) return;
|
||||
const state = this.orbital;
|
||||
// On the satellite, or on the way to it after Previous/Next.
|
||||
const eye = orbitalEyePosition(state, position, nowMs);
|
||||
// Track-up: the ground track at the top, so the picture scrolls along it.
|
||||
// A geostationary satellite has no track and stays north-up.
|
||||
const nadir = nadirOrientation(eye, {
|
||||
previousUp: state.previousUp,
|
||||
headingDeg: Number.isFinite(info.groundTrackDeg)
|
||||
? info.groundTrackDeg
|
||||
: null,
|
||||
});
|
||||
if (!nadir) return;
|
||||
state.previousUp = nadir.north;
|
||||
state.altitudeM = info.altitudeM;
|
||||
// The top step follows live altitude and the window's shape: when it
|
||||
// falls below the zoom shown, step back to it rather than show finer
|
||||
// ground than the sensor images.
|
||||
const maxZoom = orbitalMaxZoomFor.call(this, info);
|
||||
if (state.zoom > maxZoom) {
|
||||
this.lastSubjectInfo = info;
|
||||
goToZoom.call(this, maxZoom);
|
||||
}
|
||||
// A ground focus aims the look itself (src/ui/cockpitOrbitalFocus.js).
|
||||
if (!updateOrbitalFocus.call(this, state, nadir, eye, nowMs))
|
||||
state.lookView = easeOrbitalLook(
|
||||
state,
|
||||
nowMs - (state.lookLastMs || nowMs),
|
||||
{ immediate: prefersReducedMotion() },
|
||||
);
|
||||
state.lookLastMs = nowMs;
|
||||
const view = offNadirOrientation(nadir, {
|
||||
northDeg: state.lookView.pitchDeg,
|
||||
eastDeg: state.lookView.yawDeg,
|
||||
});
|
||||
const zoomStepping = Boolean(state.transition);
|
||||
const reading = applyFov.call(this, state, info.altitudeM, nowMs);
|
||||
cameraOf(this.viewer).setView({
|
||||
destination: { x: eye.x, y: eye.y, z: eye.z },
|
||||
orientation: {
|
||||
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;
|
||||
if (
|
||||
zoomStepping ||
|
||||
cockpitUiUpdateDue(nowMs, this.lastHudUpdateMs, COCKPIT_HUD_UPDATE_MS)
|
||||
) {
|
||||
this.lastHudUpdateMs = nowMs;
|
||||
trackPlace.call(this, info, nowMs);
|
||||
publishOrbitalView.call(this, info, reading.transition);
|
||||
}
|
||||
if (
|
||||
cockpitUiUpdateDue(
|
||||
nowMs,
|
||||
this.lastContextUpdateMs,
|
||||
COCKPIT_CONTEXT_UPDATE_MS,
|
||||
)
|
||||
) {
|
||||
this.lastContextUpdateMs = nowMs;
|
||||
updateOrbitalContext.call(this, info, nowMs);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Brief the sub-satellite point: the local page every context beat, the
|
||||
* regional brief on its own slower clock.
|
||||
*/
|
||||
function updateOrbitalContext(info, nowMs, force = false) {
|
||||
this.updateLocalPosition(info);
|
||||
const state = this.orbital;
|
||||
if (
|
||||
state &&
|
||||
(force || nowMs - state.lastBriefMs >= ORBITAL_BRIEF_REFRESH_MS)
|
||||
) {
|
||||
state.lastBriefMs = nowMs;
|
||||
this.maybeRefreshRegionalBrief(info);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A track-up view tilts along and across the ground track, not toward the
|
||||
* compass: the look's north/east axes are the frame's top and right.
|
||||
*/
|
||||
const TRACK_LOOK_LABELS = Object.freeze({
|
||||
N: msg('FWD'),
|
||||
S: msg('AFT'),
|
||||
E: msg('RIGHT'),
|
||||
W: msg('LEFT'),
|
||||
});
|
||||
|
||||
function lookDirectionLabel(code, trackUp) {
|
||||
return trackUp ? t(TRACK_LOOK_LABELS[code]) : compassPointLabel(code);
|
||||
}
|
||||
|
||||
/**
|
||||
* Word the off-nadir look with its total angle from nadir first, or '' at
|
||||
* nadir: `OFF-NADIR 18.0° · FWD 15° · RIGHT 10°`.
|
||||
*/
|
||||
function wordOffNadir(look, { trackUp = false } = {}) {
|
||||
const parts = orbitalLookReadoutParts(look);
|
||||
const words = [];
|
||||
if (parts.northSouth)
|
||||
words.push(
|
||||
t('{direction} {angle}°', {
|
||||
direction: lookDirectionLabel(parts.northSouth, trackUp),
|
||||
angle: formatNumber(parts.northSouthDeg),
|
||||
}),
|
||||
);
|
||||
if (parts.eastWest)
|
||||
words.push(
|
||||
t('{direction} {angle}°', {
|
||||
direction: lookDirectionLabel(parts.eastWest, trackUp),
|
||||
angle: formatNumber(parts.eastWestDeg),
|
||||
}),
|
||||
);
|
||||
if (!words.length) return '';
|
||||
return t('OFF-NADIR {angle}° · {offset}', {
|
||||
angle: formatNumber(offNadirAngleDeg(lookTilt(parts)), {
|
||||
minimumFractionDigits: 1,
|
||||
maximumFractionDigits: 1,
|
||||
}),
|
||||
offset: words.join(' · '),
|
||||
});
|
||||
}
|
||||
|
||||
/** The look's tilt as worded: whole degrees, signed north and east. */
|
||||
function lookTilt(parts) {
|
||||
return {
|
||||
northDeg: (parts.northSouth === 'S' ? -1 : 1) * parts.northSouthDeg,
|
||||
eastDeg: (parts.eastWest === 'W' ? -1 : 1) * parts.eastWestDeg,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Word a ground focus's off-nadir angle, as image metadata gives it:
|
||||
* `OFF-NADIR 23.4°`.
|
||||
*/
|
||||
function wordFocusOffNadir(focus) {
|
||||
return t('OFF-NADIR {angle}°', {
|
||||
angle: formatNumber(focus.offNadirDeg, {
|
||||
minimumFractionDigits: 1,
|
||||
maximumFractionDigits: 1,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Publish the orbital HUD. The swath is the nadir footprint, so it is left
|
||||
* out while the view is tilted off nadir. A ground focus reads the single
|
||||
* off-nadir angle to its target and scales the swath by the tilt onto it.
|
||||
* @param {object} info Satellite subject (`readSatelliteInfo`).
|
||||
* @param {{active: boolean, blurPx: number, lockTick: boolean}} transition
|
||||
*/
|
||||
export function publishOrbitalView(info, transition = IDLE_TRANSITION) {
|
||||
const state = this.orbital;
|
||||
if (!state || !info) return;
|
||||
const focus = orbitalFocusReadout.call(this);
|
||||
const offset = Boolean(focus) || lookIsOffset(state.lookTarget, 0);
|
||||
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
|
||||
// zooms (republished every frame then), not the step it is heading for.
|
||||
const shownKm = Number.isFinite(state.verticalFov)
|
||||
? footprintWidthKm(info.altitudeM, state.verticalFov, aspect)
|
||||
: footprintKm;
|
||||
const maxZoom = orbitalMaxZoomFor.call(this, info);
|
||||
const swathKm = sensorSwathKm(info);
|
||||
const trackUp = Number.isFinite(info.groundTrackDeg);
|
||||
// A ground focus sets the tilt; otherwise the look target does.
|
||||
const tilt = focus
|
||||
? { northDeg: focus.pitchDeg, eastDeg: focus.yawDeg }
|
||||
: offset
|
||||
? lookTilt(orbitalLookReadoutParts(state.lookTarget))
|
||||
: null;
|
||||
const swathScale = tilt ? offNadirSwathScale(tilt) : 1;
|
||||
// Tilted past the limb, the view's centre looks into space: no swath. The
|
||||
// camera eases toward the target, so both must meet the Earth; the HUD
|
||||
// republishes on its cadence, so the swath appears once the view arrives.
|
||||
// Exact angles here, not the whole degrees the readout rounds to; a ground
|
||||
// focus aims the look itself, so its angles are the target.
|
||||
const target = focus
|
||||
? { pitchDeg: focus.pitchDeg, yawDeg: focus.yawDeg }
|
||||
: clampOrbitalLook(state.lookTarget);
|
||||
// The eased view is tested even with the target at nadir: on the way back
|
||||
// from past the limb it still looks into space.
|
||||
const seesEarth =
|
||||
(!offset ||
|
||||
offNadirCentreMeetsEarth(info.altitudeM, {
|
||||
northDeg: target.pitchDeg,
|
||||
eastDeg: target.yawDeg,
|
||||
})) &&
|
||||
offNadirCentreMeetsEarth(info.altitudeM, {
|
||||
northDeg: state.lookView?.pitchDeg ?? 0,
|
||||
eastDeg: state.lookView?.yawDeg ?? 0,
|
||||
});
|
||||
this.publishOrbital({
|
||||
name: info.name,
|
||||
classLabel: info.classLabel || '',
|
||||
altitudeM: info.altitudeM,
|
||||
velocityMps: Number.isFinite(info.velocityMps) ? info.velocityMps : null,
|
||||
latitude: info.latitude,
|
||||
longitude: info.longitude,
|
||||
zoom: state.zoom,
|
||||
zoomSteps: ORBITAL_ZOOM_LADDER.filter((step) => step <= maxZoom),
|
||||
maxZoom,
|
||||
footprintKm: offset ? null : footprintKm,
|
||||
// The imaging sensor's swath, drawn to scale; null without one. The
|
||||
// SENSOR step's zoom is null when the swath lies outside 1x..maxZoom.
|
||||
// Looking past the limb there is no ground for it to cover: no sensor.
|
||||
sensor:
|
||||
swathKm === null || !seesEarth
|
||||
? null
|
||||
: {
|
||||
label: info.sensor?.label ?? null,
|
||||
swathKm,
|
||||
// Off nadir the view and the swath widen alike: the strip
|
||||
// keeps its share of the frame. No strip where it would
|
||||
// mislead: a geostationary view has no ground track to run
|
||||
// along, and a SAR images to one side of nadir, not under it.
|
||||
stripFraction:
|
||||
trackUp && info.sensor?.type !== 'SAR'
|
||||
? sensorStripFraction(swathKm, shownKm)
|
||||
: null,
|
||||
zoom: sensorSwathZoom(info.altitudeM, swathKm, aspect, maxZoom),
|
||||
},
|
||||
transition: { ...transition },
|
||||
look: {
|
||||
offset,
|
||||
readout: focus
|
||||
? wordFocusOffNadir(focus)
|
||||
: offset
|
||||
? wordOffNadir(state.lookTarget, { trackUp })
|
||||
: '',
|
||||
// The mapped point the view is held on, or null.
|
||||
focus: focus ? { key: focus.key, label: focus.label } : null,
|
||||
// Off nadir, the ground width at the view's centre, approximated from
|
||||
// the nadir footprint (`offNadirSwathScale`); 1 and null at nadir.
|
||||
swathScale,
|
||||
swathKm:
|
||||
offset && seesEarth && Number.isFinite(footprintKm)
|
||||
? footprintKm * swathScale
|
||||
: null,
|
||||
},
|
||||
// Track-up turns the frame to the ground track; north then sits at
|
||||
// `northDeg` clockwise from the top. A geostationary view stays north-up.
|
||||
trackUp,
|
||||
northDeg: trackUp ? (360 - info.groundTrackDeg) % 360 : 0,
|
||||
place: state.place,
|
||||
noradId: info.noradId ?? null,
|
||||
cosparId: info.cosparId ?? null,
|
||||
tle: info.tle ?? null,
|
||||
// Read on the HUD's cadence, so the age stays current without a timer.
|
||||
// The gap between the TLE's epoch and the time the satellite is shown
|
||||
// at (the world clock's), either side: SGP4 drifts both ways.
|
||||
tleAgeMs: Number.isFinite(info.tle?.epochMs)
|
||||
? Math.abs(
|
||||
(Number.isFinite(info.atMs) ? info.atMs : Date.now()) -
|
||||
info.tle.epochMs,
|
||||
)
|
||||
: null,
|
||||
owner: info.owner ?? null,
|
||||
operator: info.operator ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Present the orbital view on entry and after a language switch: the HUD,
|
||||
* the local page and a regional brief for the sub-satellite point.
|
||||
* @param {object} info Satellite subject.
|
||||
*/
|
||||
export function updateOrbitalHud(info, nowMs = performance.now()) {
|
||||
this.lastSubjectInfo = info;
|
||||
// A satellite has no flight plan and no Contact card.
|
||||
this.routeView.visible = false;
|
||||
this.clearPredictiveRoute();
|
||||
this.showContextCard(false);
|
||||
trackPlace.call(this, info, nowMs);
|
||||
publishOrbitalView.call(this, info);
|
||||
updateOrbitalContext.call(this, info, nowMs, true);
|
||||
}
|
||||
|
||||
/** Re-apply the field of view and publish after a zoom or look change. */
|
||||
function presentNow() {
|
||||
const state = this.orbital;
|
||||
const info = this.lastSubjectInfo;
|
||||
if (!state || info?.kind !== 'satellite') return;
|
||||
const nowMs = performance.now();
|
||||
const reading = Number.isFinite(state.altitudeM ?? info.altitudeM)
|
||||
? applyFov.call(this, state, state.altitudeM ?? info.altitudeM, nowMs)
|
||||
: null;
|
||||
publishOrbitalView.call(this, info, reading?.transition ?? IDLE_TRANSITION);
|
||||
}
|
||||
|
||||
/**
|
||||
* Step the optical zoom one step in (`direction` > 0) or out. The step
|
||||
* animates over ORBITAL_ZOOM_TRANSITION_MS with a focus-pull blur and a
|
||||
* lock tick, or cuts at once under reduced motion. The ends stay put.
|
||||
* @param {number} direction Positive to zoom in, negative to zoom out.
|
||||
* @returns {boolean} True when the zoom changed.
|
||||
*/
|
||||
export function stepOrbitalZoom(direction) {
|
||||
if (!this.active || this.subjectKind !== 'satellite' || !this.orbital)
|
||||
return false;
|
||||
const state = this.orbital;
|
||||
const next =
|
||||
direction > 0
|
||||
? nextOrbitalZoom(
|
||||
state.zoom,
|
||||
orbitalMaxZoomFor.call(this, this.lastSubjectInfo),
|
||||
)
|
||||
: previousOrbitalZoom(state.zoom);
|
||||
return goToZoom.call(this, next);
|
||||
}
|
||||
|
||||
/**
|
||||
* Jump to the zoom at which the view is exactly as wide as the imaging
|
||||
* sensor's swath (the SENSOR step), when that zoom is in range.
|
||||
* @returns {boolean} True when the zoom changed.
|
||||
*/
|
||||
export function jumpToSensorSwath() {
|
||||
if (!this.active || this.subjectKind !== 'satellite' || !this.orbital)
|
||||
return false;
|
||||
const info = this.lastSubjectInfo;
|
||||
const swathKm = sensorSwathKm(info);
|
||||
if (swathKm === null || !Number.isFinite(info?.altitudeM)) return false;
|
||||
const zoom = sensorSwathZoom(
|
||||
info.altitudeM,
|
||||
swathKm,
|
||||
viewAspect(this.viewer),
|
||||
orbitalMaxZoomFor.call(this, info),
|
||||
);
|
||||
return zoom === null ? false : goToZoom.call(this, zoom);
|
||||
}
|
||||
|
||||
/**
|
||||
* Step the zoom with the mouse wheel over the picture: one step per notch,
|
||||
* trackpad scrolling summed to a step (`wheelZoomStep`). Only in orbit, and
|
||||
* never while a tool owns the pointer.
|
||||
* @param {WheelEvent} event
|
||||
* @returns {boolean} True when the zoom changed.
|
||||
*/
|
||||
export function onOrbitalWheel(event) {
|
||||
if (!this.active || this.subjectKind !== 'satellite' || !this.orbital)
|
||||
return false;
|
||||
if (!isPointerFree()) return false;
|
||||
const state = this.orbital;
|
||||
const { accumulator, step } = wheelZoomStep(
|
||||
state.wheel,
|
||||
event,
|
||||
performance.now(),
|
||||
);
|
||||
state.wheel = accumulator;
|
||||
if (!step) return false;
|
||||
const changed = stepOrbitalZoom.call(this, step);
|
||||
if (changed) event.preventDefault?.();
|
||||
return changed;
|
||||
}
|
||||
|
||||
/** The sensor swath the view draws and the SENSOR step targets, km, or null. */
|
||||
function sensorSwathKm(info) {
|
||||
const swathKm = info?.sensor?.narrowestSwathKm;
|
||||
return Number.isFinite(swathKm) && swathKm > 0 ? swathKm : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The satellite's tightest zoom step at its live altitude. Only a swath
|
||||
* confirmed on a cited page opens steps past 8x.
|
||||
*/
|
||||
function orbitalMaxZoomFor(info) {
|
||||
return orbitalMaxZoom(
|
||||
info?.altitudeM,
|
||||
zoomableSwathKm(info?.sensor),
|
||||
viewAspect(this.viewer),
|
||||
);
|
||||
}
|
||||
|
||||
function viewAspect(viewer) {
|
||||
const aspect = cameraOf(viewer).pose().aspectRatio;
|
||||
return Number.isFinite(aspect) && aspect > 0 ? aspect : canvasAspect(viewer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Move the zoom to `next`, animated from the magnification shown now unless
|
||||
* reduced motion is on.
|
||||
* @returns {boolean} True when the zoom changed.
|
||||
*/
|
||||
function goToZoom(next) {
|
||||
const state = this.orbital;
|
||||
if (!Number.isFinite(next) || next === state.zoom) return false;
|
||||
const nowMs = performance.now();
|
||||
const altitudeM = state.altitudeM ?? this.lastSubjectInfo?.altitudeM;
|
||||
const fromZoom = Number.isFinite(altitudeM)
|
||||
? currentMagnification(state, orbitalBaseFovRad(altitudeM), nowMs)
|
||||
: state.zoom;
|
||||
state.zoom = next;
|
||||
state.transition = prefersReducedMotion()
|
||||
? null
|
||||
: { fromZoom, startMs: nowMs };
|
||||
presentNow.call(this);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tilt the orbital view one arrow step off nadir (see `lookKeyStep`); each
|
||||
* axis stops at ±45°. The view eases there unless reduced motion is on.
|
||||
* @param {{axis: 'yaw'|'pitch', sign: number, stepDeg: number}} step
|
||||
* @returns {boolean} True in an orbital view.
|
||||
*/
|
||||
export function turnOrbitalLook(step) {
|
||||
if (!this.active || this.subjectKind !== 'satellite' || !this.orbital)
|
||||
return false;
|
||||
if (!step) return false;
|
||||
const state = this.orbital;
|
||||
// An arrow takes the view over from a ground focus where it is.
|
||||
releaseOrbitalFocus.call(this, { handOver: true });
|
||||
state.lookTarget = stepOrbitalLook(state.lookTarget, step);
|
||||
if (prefersReducedMotion()) state.lookView = { ...state.lookTarget };
|
||||
presentNow.call(this);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bring the orbital view back to pure nadir (Home, 0 or the NADIR button).
|
||||
* @param {{immediate?: boolean}} [options] Jump instead of easing.
|
||||
* @returns {boolean} True in an orbital view.
|
||||
*/
|
||||
export function resetOrbitalLook({ immediate = false } = {}) {
|
||||
if (!this.active || this.subjectKind !== 'satellite' || !this.orbital)
|
||||
return false;
|
||||
const state = this.orbital;
|
||||
// Ends a ground focus too, easing back on its clock.
|
||||
releaseOrbitalFocus.call(this);
|
||||
state.lookTarget = { ...NADIR_LOOK };
|
||||
if (immediate || prefersReducedMotion()) state.lookView = { ...NADIR_LOOK };
|
||||
presentNow.call(this);
|
||||
return true;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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°');
|
||||
});
|
||||
@@ -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;
|
||||
|
||||
@@ -144,3 +146,55 @@ export function formatCockpitWindDirection(value) {
|
||||
const degrees = roundHeadingDegrees(value);
|
||||
return `${compassPointLabel(labels[Math.round(normalized / 45) % labels.length])} · ${degrees}°`;
|
||||
}
|
||||
|
||||
/**
|
||||
* A TLE epoch as compact UTC, `2026-11-04 08:12Z`, or '' when unknown.
|
||||
* @param {number|null|undefined} epochMs
|
||||
*/
|
||||
export function formatTleEpochUtc(epochMs) {
|
||||
// Beyond ±8.64e15 ms a Date is invalid and toISOString throws.
|
||||
if (!Number.isFinite(epochMs) || Math.abs(epochMs) > 8.64e15) return '';
|
||||
const iso = new Date(epochMs).toISOString();
|
||||
return `${iso.slice(0, 10)} ${iso.slice(11, 16)}Z`;
|
||||
}
|
||||
|
||||
/**
|
||||
* How old a TLE is, in the identifier line's compact units: under an hour,
|
||||
* whole hours under a day, then whole days. A TLE's propagation error grows
|
||||
* with its age, so the age is shown beside the epoch.
|
||||
* @param {number|null|undefined} ageMs Now minus the TLE epoch.
|
||||
* @returns {{unit: 'under-hour'}|{unit: 'hours'|'days', value: number}|null}
|
||||
* Null without a usable age.
|
||||
*/
|
||||
export function tleAgeParts(ageMs) {
|
||||
if (!Number.isFinite(ageMs)) return null;
|
||||
const hours = Math.max(0, ageMs) / 3_600_000;
|
||||
if (hours < 1) return { unit: 'under-hour' };
|
||||
if (hours < 24) return { unit: 'hours', value: Math.floor(hours) };
|
||||
return { unit: 'days', value: Math.floor(hours / 24) };
|
||||
}
|
||||
|
||||
/**
|
||||
* The Cockpit entry for each subject it can ride: an aircraft's cockpit, a
|
||||
* vessel's bridge or a satellite's orbit. Both entry buttons (Contacts and
|
||||
* the Intel HUD readout) show it.
|
||||
*/
|
||||
const COCKPIT_ENTRY_FACES = Object.freeze({
|
||||
aircraft: Object.freeze({ icon: 'flight', label: msg('COCKPIT') }),
|
||||
vessel: Object.freeze({ icon: 'directions_boat', label: msg('BRIDGE') }),
|
||||
satellite: Object.freeze({ icon: 'satellite_alt', label: msg('ORBIT') }),
|
||||
});
|
||||
|
||||
/**
|
||||
* 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, 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) };
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
|
||||
import {
|
||||
formatCockpitDistance,
|
||||
formatCockpitWindDirection,
|
||||
tleAgeParts,
|
||||
} from './cockpitPresentation.js';
|
||||
|
||||
test('wind just west of north reads 0°, not 360°', () => {
|
||||
@@ -16,3 +17,18 @@ test('a cockpit distance that rounds to 10.0 km drops the decimal', () => {
|
||||
assert.match(formatCockpitDistance(9949), /^9\.9\s?KM$/);
|
||||
assert.match(formatCockpitDistance(9960), /^10\s?KM$/);
|
||||
});
|
||||
|
||||
test('a TLE age reads under an hour, then whole hours, then whole days', () => {
|
||||
const HOUR = 3_600_000;
|
||||
assert.deepEqual(tleAgeParts(0), { unit: 'under-hour' });
|
||||
assert.deepEqual(tleAgeParts(59 * 60_000), { unit: 'under-hour' });
|
||||
assert.deepEqual(tleAgeParts(HOUR), { unit: 'hours', value: 1 });
|
||||
assert.deepEqual(tleAgeParts(13.9 * HOUR), { unit: 'hours', value: 13 });
|
||||
assert.deepEqual(tleAgeParts(24 * HOUR - 1), { unit: 'hours', value: 23 });
|
||||
assert.deepEqual(tleAgeParts(24 * HOUR), { unit: 'days', value: 1 });
|
||||
assert.deepEqual(tleAgeParts(50 * HOUR), { unit: 'days', value: 2 });
|
||||
// A clock a little behind the epoch is still fresh, not negative.
|
||||
assert.deepEqual(tleAgeParts(-5 * 60_000), { unit: 'under-hour' });
|
||||
assert.equal(tleAgeParts(null), null);
|
||||
assert.equal(tleAgeParts(Number.NaN), null);
|
||||
});
|
||||
+120
-20
@@ -28,7 +28,10 @@ export function publishCockpitSignals() {
|
||||
target: item.target && {
|
||||
layerId: item.target.layerId,
|
||||
id: item.target.id,
|
||||
label: t('Select flight {title}', { title: item.title }),
|
||||
// Orbit's site and satellite rows name their own action.
|
||||
label:
|
||||
item.target.label ??
|
||||
t('Select flight {title}', { title: item.title }),
|
||||
},
|
||||
};
|
||||
}),
|
||||
@@ -36,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;
|
||||
}
|
||||
@@ -62,7 +90,52 @@ export function pushCockpitSignal(key, tone, title, detail, target = null) {
|
||||
this.publishCockpitSignals();
|
||||
}
|
||||
|
||||
export function updateCockpitSignals(snapshot, unknownCount) {
|
||||
/**
|
||||
* Take a status row off the list, as when the feed it warned about is back.
|
||||
* @param {string} key The row's key.
|
||||
*/
|
||||
export function dropCockpitSignal(key) {
|
||||
this.signalSignatures.delete(key);
|
||||
const kept = this.signalItems.filter((item) => item.key !== key);
|
||||
if (kept.length === this.signalItems.length) return;
|
||||
this.signalItems = kept;
|
||||
this.publishCockpitSignals();
|
||||
}
|
||||
|
||||
/** Whether a row is one a Contacts snapshot builds, with its status rows. */
|
||||
const isContextSnapshotRow = (key) =>
|
||||
key.startsWith('flight:') ||
|
||||
['input-status', 'feed-status', 'context-status'].includes(key);
|
||||
|
||||
/**
|
||||
* Take off every row a Contacts snapshot built, as when Contacts goes off:
|
||||
* its contacts, distances and CURRENT would otherwise read as live. Rows the
|
||||
* session made without Contacts, such as TRACK ACQUIRED, stay.
|
||||
*/
|
||||
export function dropContextSnapshotSignals() {
|
||||
for (const key of [...this.signalSignatures.keys()])
|
||||
if (isContextSnapshotRow(key)) this.signalSignatures.delete(key);
|
||||
const kept = this.signalItems.filter(
|
||||
(item) => !isContextSnapshotRow(item.key),
|
||||
);
|
||||
if (kept.length === this.signalItems.length) return;
|
||||
this.signalItems = kept;
|
||||
this.publishCockpitSignals();
|
||||
}
|
||||
|
||||
/**
|
||||
* Rebuild the rows from a Contacts snapshot: the nearest flights, a row for
|
||||
* unknown inputs and, first, a row naming an air feed that is off.
|
||||
* @param {object} snapshot `militaryAwareness.getContextSnapshot()` result.
|
||||
* @param {number} unknownCount Cohorts whose count is unknown.
|
||||
* @param {?{title: string, detail: string}} [partialPicture] The feed-off
|
||||
* row (see `readPartialPicture`), or null with every air feed on.
|
||||
*/
|
||||
export function updateCockpitSignals(
|
||||
snapshot,
|
||||
unknownCount,
|
||||
partialPicture = null,
|
||||
) {
|
||||
const previous = new Map(this.signalItems.map((item) => [item.key, item]));
|
||||
const contacts = [];
|
||||
const subject = snapshot.subject;
|
||||
@@ -110,7 +183,9 @@ export function updateCockpitSignals(snapshot, unknownCount) {
|
||||
}
|
||||
}
|
||||
contacts.sort((a, b) => a.distanceM - b.distanceM);
|
||||
const nextItems = contacts.slice(0, 5).map((item) => ({
|
||||
// A feed-off row leads, so the list never reads as the whole picture.
|
||||
const reserved = partialPicture ? 1 : 0;
|
||||
const nextItems = contacts.slice(0, 5 - reserved).map((item) => ({
|
||||
...item,
|
||||
timestamp:
|
||||
previous.get(item.key)?.timestamp || snapshot.evaluatedAt || Date.now(),
|
||||
@@ -120,18 +195,35 @@ export function updateCockpitSignals(snapshot, unknownCount) {
|
||||
.filter((cohort) => cohort.count === null)
|
||||
.map((cohort) => cohort.source)
|
||||
.join(' · ');
|
||||
nextItems.splice(4, Math.max(0, nextItems.length - 4), {
|
||||
key: 'input-status',
|
||||
nextItems.splice(
|
||||
4 - reserved,
|
||||
Math.max(0, nextItems.length - 4 + reserved),
|
||||
{
|
||||
key: 'input-status',
|
||||
tone: 'warning',
|
||||
title: tn(
|
||||
unknownCount,
|
||||
'{count} INPUT UNKNOWN',
|
||||
'{count} INPUTS UNKNOWN',
|
||||
),
|
||||
detail: sources || t('SOURCE STATUS UNAVAILABLE'),
|
||||
target: null,
|
||||
timestamp:
|
||||
previous.get('input-status')?.timestamp ||
|
||||
snapshot.evaluatedAt ||
|
||||
Date.now(),
|
||||
},
|
||||
);
|
||||
}
|
||||
if (partialPicture) {
|
||||
nextItems.unshift({
|
||||
key: 'feed-status',
|
||||
tone: 'warning',
|
||||
title: tn(
|
||||
unknownCount,
|
||||
'{count} INPUT UNKNOWN',
|
||||
'{count} INPUTS UNKNOWN',
|
||||
),
|
||||
detail: sources || t('SOURCE STATUS UNAVAILABLE'),
|
||||
title: partialPicture.title,
|
||||
detail: partialPicture.detail,
|
||||
target: null,
|
||||
timestamp:
|
||||
previous.get('input-status')?.timestamp ||
|
||||
previous.get('feed-status')?.timestamp ||
|
||||
snapshot.evaluatedAt ||
|
||||
Date.now(),
|
||||
});
|
||||
@@ -148,6 +240,14 @@ export function handleSignalClick(event) {
|
||||
);
|
||||
if (!target) return;
|
||||
event.preventDefault();
|
||||
// In orbit the rows are sites and satellites (cockpitOrbitalSignals.js).
|
||||
if (
|
||||
this.handleOrbitalSignalClick?.(
|
||||
target.dataset.signalLayer,
|
||||
target.dataset.signalId,
|
||||
)
|
||||
)
|
||||
return;
|
||||
this.services.militaryAwarenessLayer.focusTarget?.(
|
||||
target.dataset.signalLayer,
|
||||
target.dataset.signalId,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,30 +1,273 @@
|
||||
/** 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';
|
||||
|
||||
/**
|
||||
* 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 || '',
|
||||
});
|
||||
}
|
||||
|
||||
/** The selected vessel the bridge view would ride, or rides; null without one. */
|
||||
export function readVesselInfo() {
|
||||
return this.services.aisLiveVesselsLayer?.getCockpitSubject?.() || null;
|
||||
}
|
||||
|
||||
/** The tracked satellite the orbital view would ride, or rides; null without one. */
|
||||
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, 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.trackedFollow?.key || '').split(':');
|
||||
return ['flights', 'military'].includes(prefix) ? prefix : 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() {
|
||||
return this.resolveEntry()?.kind ?? null;
|
||||
}
|
||||
|
||||
export function dispatchCockpitModeChanged(active, info = null) {
|
||||
const subjectId = active
|
||||
? String(info?.icao24 || '')
|
||||
? String(
|
||||
info?.icao24 ||
|
||||
(info?.kind === 'vessel' || info?.generic === true ? info.id : '') ||
|
||||
info?.noradId ||
|
||||
'',
|
||||
)
|
||||
.trim()
|
||||
.toLowerCase() || null
|
||||
: null;
|
||||
const layerId =
|
||||
active && ['flights', 'military'].includes(info?.layerId)
|
||||
active &&
|
||||
(['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(
|
||||
@@ -73,23 +316,61 @@ 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 available = !!(this.isEntryAllowed() && trackedContact);
|
||||
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) return;
|
||||
if (
|
||||
this.presence.entryAvailable === available &&
|
||||
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,
|
||||
// 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;
|
||||
if (wasActive) this.contextNavigationDeadlineMs = performance.now() + 1500;
|
||||
@@ -108,7 +389,17 @@ export function navigateContext(direction, options = {}) {
|
||||
}
|
||||
|
||||
export function _adoptTrackedEntity(nowMs, suppliedInfo = null) {
|
||||
const nextEntity = this.viewer.trackedEntity;
|
||||
// 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 nextFollowed = followedOf(this.viewer);
|
||||
const nextEntity = nextFollowed?.entity;
|
||||
if (
|
||||
!this.active ||
|
||||
!nextEntity?.position ||
|
||||
@@ -117,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;
|
||||
@@ -131,28 +423,213 @@ export function _adoptTrackedEntity(nowMs, suppliedInfo = null) {
|
||||
this.lastContextUpdateMs = 0;
|
||||
this.lastCameraUpdateMs = 0;
|
||||
this.contextNavigationDeadlineMs = 0;
|
||||
this.onRide?.(info.layerId);
|
||||
this.dispatchCockpitModeChanged(true, info);
|
||||
return true;
|
||||
}
|
||||
|
||||
export function enter() {
|
||||
/**
|
||||
* 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;
|
||||
if (!this.isEntryAllowed()) return false;
|
||||
const info = this.readAircraftInfo();
|
||||
const entity = this.viewer.trackedEntity;
|
||||
if (!info || !entity?.position) 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
|
||||
? this.isBridgeEntryAllowed()
|
||||
: satellite
|
||||
? this.isOrbitEntryAllowed()
|
||||
: this.isEntryAllowed();
|
||||
if (!allowed) return false;
|
||||
const info = vessel
|
||||
? this.readVesselInfo()
|
||||
: satellite
|
||||
? this.readSatelliteInfo()
|
||||
: this.readAircraftInfo();
|
||||
// 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
|
||||
? document.activeElement
|
||||
: 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.trackedEntityWasShown = entity.show;
|
||||
entity.show = false;
|
||||
this.heading = normalizeHeading(info.track ?? 0);
|
||||
this.trackedFollow = followed;
|
||||
if (entity) {
|
||||
this.trackedEntityWasShown = entity.show;
|
||||
entity.show = false;
|
||||
} else if (satellite) {
|
||||
// The layer hides the satellite's own marks and dims the other orbits.
|
||||
this.services.satellitesLayer?.setCockpitSubject?.(info.noradId);
|
||||
this.beginOrbital();
|
||||
} else {
|
||||
this.services.aisLiveVesselsLayer?.setCockpitSubject?.(info.id);
|
||||
}
|
||||
// A ship reporting neither heading nor course keeps the camera's own
|
||||
// heading: no direction is made up for it.
|
||||
this.heading = normalizeHeading(
|
||||
Number.isFinite(info.track)
|
||||
? info.track
|
||||
: vessel
|
||||
? cameraHeadingDeg(cameraOf(this.viewer).pose())
|
||||
: 0,
|
||||
);
|
||||
this.lastFrameMs = performance.now();
|
||||
this.lastCameraUpdateMs = 0;
|
||||
this.lastHudUpdateMs = 0;
|
||||
@@ -164,41 +641,83 @@ export function enter() {
|
||||
this.surfaceFallback = false;
|
||||
this.cockpitAnchorValid = false;
|
||||
this.lastCameraUpdateMs = 0;
|
||||
// Every bridge opens looking over the bow.
|
||||
this.resetLook({ immediate: true });
|
||||
this.active = true;
|
||||
// Cockpit animates the camera from preUpdate every frame — preUpdate only
|
||||
// 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');
|
||||
if (satellite) document.body.classList.add('cockpit-orbit');
|
||||
// Activation hides the entry and TR-3B chip; clearing the chip's signature
|
||||
// lets the exit-path syncEntry publish it again.
|
||||
this._tr3bSignature = null;
|
||||
Object.assign(this.presence, {
|
||||
active: true,
|
||||
entryAvailable: false,
|
||||
entryKind: null,
|
||||
subjectKind,
|
||||
tr3b: null,
|
||||
});
|
||||
this.publishPresenceView();
|
||||
// Only a bridge has a radar.
|
||||
if (!vessel) this.publishRadar(null);
|
||||
this.signalItems = [];
|
||||
this.signalSignatures.clear();
|
||||
this.showBriefPage(0);
|
||||
this.startBriefRotation();
|
||||
const trackLabel =
|
||||
info.callsign || info.registration || info.icao24 || t('AIRCRAFT');
|
||||
const trackHeading = formatHeadingReadout(info.track ?? 0);
|
||||
this.pushCockpitSignal(
|
||||
'track',
|
||||
'track',
|
||||
t('TRACK ACQUIRED'),
|
||||
t('{label} · COURSE {heading}°', {
|
||||
label: trackLabel,
|
||||
heading: trackHeading,
|
||||
}),
|
||||
);
|
||||
if (satellite) {
|
||||
this.pushCockpitSignal(
|
||||
'track',
|
||||
'track',
|
||||
t('TRACK ACQUIRED'),
|
||||
t('{label} · NADIR VIEW', { label: info.name }),
|
||||
);
|
||||
} else if (vessel) {
|
||||
this.pushCockpitSignal(
|
||||
'track',
|
||||
'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. 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,
|
||||
})
|
||||
: info.trackSource === 'heading'
|
||||
? t('{label} · HEADING {heading}°', {
|
||||
label: info.name,
|
||||
heading: trackHeading,
|
||||
})
|
||||
: t('{label} · NO HEADING', { label: info.name }),
|
||||
);
|
||||
} else {
|
||||
const trackLabel =
|
||||
info.callsign || info.registration || info.icao24 || t('AIRCRAFT');
|
||||
this.pushCockpitSignal(
|
||||
'track',
|
||||
'track',
|
||||
t('TRACK ACQUIRED'),
|
||||
t('{label} · COURSE {heading}°', {
|
||||
label: trackLabel,
|
||||
heading: trackHeading,
|
||||
}),
|
||||
);
|
||||
}
|
||||
this.updateHud(info, performance.now(), true);
|
||||
this.setVisionMode(this.getInitialVisionMode());
|
||||
// Orbit always opens in the plain optical picture; the vision styles stay
|
||||
// one click away.
|
||||
this.setVisionMode(satellite ? 'optical' : this.getInitialVisionMode());
|
||||
this.scheduleContextLayout();
|
||||
// The exit button shows when Vue flushes the presence; focus it after.
|
||||
Promise.resolve().then(() => {
|
||||
@@ -206,6 +725,7 @@ export function enter() {
|
||||
this.mapViewButton?.focus({ preventScroll: true });
|
||||
});
|
||||
this.onEntered?.();
|
||||
this.onRide?.(info.layerId);
|
||||
this.dispatchCockpitModeChanged(true, info);
|
||||
return true;
|
||||
}
|
||||
@@ -213,10 +733,26 @@ export function enter() {
|
||||
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;
|
||||
this.surfaceWaitStartedMs = 0;
|
||||
this.surfaceAcquiring = false;
|
||||
@@ -229,27 +765,62 @@ export function exit({ restoreTracking = true } = {}) {
|
||||
this.regionalBriefAbort = null;
|
||||
this.regionalBriefRequestToken += 1;
|
||||
this.regionalBriefSubjectId = null;
|
||||
document.body.classList.remove('cockpit-mode');
|
||||
document.body.classList.remove(
|
||||
'cockpit-mode',
|
||||
'cockpit-bridge',
|
||||
'cockpit-orbit',
|
||||
'cockpit-subject',
|
||||
);
|
||||
// The camera's own field of view returns before any follow resumes.
|
||||
this.endOrbital();
|
||||
this.onExited?.();
|
||||
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.
|
||||
this.services.aisLiveVesselsLayer?.focusSelectedVessel?.();
|
||||
} else if (restoreTracking && satelliteSubject !== null) {
|
||||
// Back to the satellite's follow camera, through the layer's own refocus.
|
||||
this.services.satellitesLayer?.refocusTrackedById?.(satelliteSubject);
|
||||
}
|
||||
this.syncEntry();
|
||||
// Return to the card or readout control that opened Cockpit.
|
||||
const readoutEntry = document.getElementById('cockpit-entry-readout');
|
||||
const restoreTarget =
|
||||
this.entryFocusOrigin === this.entry
|
||||
? this.entry
|
||||
this.entryFocusOrigin === this.entry ||
|
||||
this.entryFocusOrigin?.hasAttribute('data-entity-cockpit-entry') ||
|
||||
(readoutEntry && this.entryFocusOrigin === readoutEntry)
|
||||
? this.entryFocusOrigin
|
||||
: this.entry || this.entryFocusOrigin;
|
||||
this.entryFocusOrigin = null;
|
||||
// The entry shows when Vue flushes the presence; read it after.
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
+1597
-1
File diff suppressed because it is too large.
Load diff
@@ -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,
|
||||
|
||||
@@ -19,7 +19,10 @@ export async function _runUserFacingContextAction(
|
||||
onFailure: (error) => {
|
||||
if (this.destroyed) return;
|
||||
console.warn('[Context] user-facing transition failed', error);
|
||||
this.showToast(localizedMessage || message);
|
||||
this.showToast(
|
||||
localizedMessage ||
|
||||
(typeof message === 'function' ? message() : message),
|
||||
);
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
@@ -55,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),
|
||||
};
|
||||
}
|
||||
@@ -111,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',
|
||||
@@ -206,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;
|
||||
|
||||
@@ -1,26 +1,8 @@
|
||||
import { t } from '../i18n/index.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 ||
|
||||
@@ -49,37 +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();
|
||||
void this._runUserFacingContextAction(
|
||||
(notificationToken) =>
|
||||
this._selectContextMode(nextMode, { notificationToken }),
|
||||
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 ||
|
||||
@@ -108,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')),
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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();
|
||||
|
||||
+38
-110
@@ -1,28 +1,16 @@
|
||||
import { t, translateKnown } from '../i18n/index.js';
|
||||
import {
|
||||
SPACE_MISSIONS_LAYER_BLOCK_REASON,
|
||||
cockpitEntryAllowed,
|
||||
isExplicitUserIntentOrigin,
|
||||
parseContextLayerBlockReason,
|
||||
recordContextRestoreExplicitChange,
|
||||
recordContextSessionUserChange,
|
||||
shouldExitContextForLayerChange,
|
||||
spaceMissionEntryCancellationDisposition,
|
||||
} from '../contextModePolicy.js';
|
||||
import { localizeLayerName } from './layerNames.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,16 +47,23 @@ export function _handleContextLayerChange(change) {
|
||||
return;
|
||||
}
|
||||
if (change?.type === 'visibility-failed') {
|
||||
const failureMessage = t('{layerId} could not {action} cleanly', {
|
||||
layerId: change.layerId,
|
||||
action: change.enabled ? t('start') : t('stop'),
|
||||
});
|
||||
// A layer may name why its own start failed (Space Missions: the
|
||||
// mission index never loaded).
|
||||
const failureMessage =
|
||||
(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'),
|
||||
});
|
||||
// A failed direct Context-shell START has already had its siblings
|
||||
// cleared by the visibility guard. Wait outside the synchronous manager
|
||||
// notification for this queue to settle, then reconcile the complete
|
||||
// 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;
|
||||
@@ -208,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' &&
|
||||
[
|
||||
@@ -246,15 +159,30 @@ export function _handleContextLayerChange(change) {
|
||||
}
|
||||
}
|
||||
if (
|
||||
this.cockpitView?.active &&
|
||||
!cockpitEntryAllowed({
|
||||
contextMode: this._contextMode,
|
||||
contextModeChanging: this._contextModeChanging,
|
||||
flightsEnabled: !!this._dataManager?.isEnabled('flights'),
|
||||
militaryEnabled: !!this._dataManager?.isEnabled('military'),
|
||||
})
|
||||
change.type === 'visibility' &&
|
||||
change.enabled &&
|
||||
change.origin === 'user' &&
|
||||
!this.cockpitView?.active &&
|
||||
change.layerId === 'radio'
|
||||
) {
|
||||
this.cockpitView.exit({ restoreTracking: false });
|
||||
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 });
|
||||
}
|
||||
this._syncContextModeButtons();
|
||||
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 = controls.cockpitView?.active
|
||||
? controls.cockpitView.readSubjectLayerId?.()
|
||||
: null;
|
||||
if (riddenLayerId && !controls._dataManager?.isEnabled(riddenLayerId)) {
|
||||
controls.cockpitView.exit({ restoreTracking: false });
|
||||
}
|
||||
controls._syncContextModeButtons();
|
||||
}
|
||||
@@ -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,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) => {
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
|
||||
@@ -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.
|
||||
}
|
||||
}
|
||||
@@ -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 = '';
|
||||
}
|
||||
@@ -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
@@ -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;
|
||||
});
|
||||
|
||||
@@ -13,12 +13,13 @@ 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 {
|
||||
if (mode !== 'flights' && this.cockpitView?.active) {
|
||||
// Cockpit does not need Contacts, so leaving it keeps the view; the
|
||||
// restore below ends it only by turning off the layer it rides. Another
|
||||
// mode takes the camera, so switching to one ends it.
|
||||
if (mode && mode !== 'flights' && this.cockpitView?.active) {
|
||||
this.cockpitView.exit({ restoreTracking: false });
|
||||
}
|
||||
if (!mode) {
|
||||
@@ -44,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,
|
||||
@@ -79,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;
|
||||
@@ -96,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?.(
|
||||
@@ -111,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 ||
|
||||
@@ -179,8 +127,6 @@ export async function _selectContextMode(
|
||||
);
|
||||
}
|
||||
this._contextMode = null;
|
||||
this._contextModeEntryIntent = null;
|
||||
this._contextModeReplacementIntent = null;
|
||||
this._syncContextModeButtons();
|
||||
try {
|
||||
await this._restoreContextSession({
|
||||
@@ -202,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()) {
|
||||
@@ -218,10 +163,8 @@ export async function _deactivateContextForLayerChange({
|
||||
this._contextModeGeneration += 1;
|
||||
this._contextModeChanging = true;
|
||||
this._contextMode = null;
|
||||
this._contextModeEntryIntent = null;
|
||||
this._contextModeReplacementIntent = null;
|
||||
if (this.cockpitView?.active)
|
||||
this.cockpitView.exit({ restoreTracking: false });
|
||||
// A layer turned off ends Contacts but not the Cockpit: the view ends only
|
||||
// when the layer it rides goes off (see _handleContextLayerChange).
|
||||
this._syncContextModeButtons();
|
||||
try {
|
||||
await this._restoreContextSession({ notificationToken });
|
||||
@@ -237,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) =>
|
||||
|
||||
@@ -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');
|
||||
};
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -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);
|
||||
};
|
||||
}
|
||||
@@ -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'],
|
||||
);
|
||||
});
|
||||
@@ -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 = [];
|
||||
|
||||
@@ -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]);
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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\);/);
|
||||
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\);/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\);/,
|
||||
);
|
||||
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\);/);
|
||||
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*\}/,
|
||||
);
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
Vendored
+31
@@ -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;
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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
@@ -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');
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
};
|
||||
}
|
||||
@@ -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
@@ -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
@@ -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), []);
|
||||
});
|
||||
@@ -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(() => {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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
@@ -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
@@ -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,
|
||||
|
||||
@@ -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
@@ -1,28 +1,29 @@
|
||||
/**
|
||||
* Box selection for the Recent Imagery layer: press on the world, drag, and
|
||||
* release to hand the layer a degrees box. Follows the draw tool's ownership
|
||||
* rules — the pointer is claimed for the session, the viewer's own click
|
||||
* actions are borrowed and given back, and `destroy()` returns everything —
|
||||
* and freezes the camera only while a drag is in progress.
|
||||
* rules — the pointer is claimed for the session (a newer claim cancels it),
|
||||
* the viewer's own click actions are suppressed and given back, and
|
||||
* `destroy()` returns everything — and holds the camera only while a drag is
|
||||
* in progress.
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
import { pickWorldFromScreen } from '../annotations/annotationResolver.js';
|
||||
import {
|
||||
claimPointer,
|
||||
pointerOwner,
|
||||
releasePointer,
|
||||
} from '../data/inputOwnership.js';
|
||||
import { claimPointer, releasePointer } from '../data/inputOwnership.js';
|
||||
import { inputFor as defaultInputFor } from '../input/dispatcher.js';
|
||||
import { validateBox } from '../layers/recentImagery/model.js';
|
||||
import { createImageryBoxPreview } from '../layers/recentImagery/rendering.js';
|
||||
import { msg } from '../i18n/index.js';
|
||||
import { canvasOf } from '../render/rendererOf.js';
|
||||
|
||||
/** The id this tool claims the pointer under. */
|
||||
export const IMAGERY_BOX_POINTER_OWNER = 'recent-imagery-box';
|
||||
|
||||
/**
|
||||
* Wire the box tool.
|
||||
* @param {{ viewer: object, onBox: (box: object) => void, onCancel?: (reason: string, message?: string, box?: object) => void, onActive?: (active: boolean) => void, onEscape?: () => boolean, cesium?: object, pickWorld?: Function, documentRef?: object }} deps
|
||||
* @param {{ viewer: object, onBox: (box: object) => void, onCancel?: (reason: string, message?: string, box?: object) => void, onActive?: (active: boolean) => void, onEscape?: () => boolean, createPreview?: Function, inputFor?: Function, pickWorld?: Function, documentRef?: object }} deps
|
||||
* `onEscape` runs before the tool cancels on Escape; returning `true` claims
|
||||
* the key (it is still consumed) and leaves the tool armed.
|
||||
* `createPreview(viewer, dragBox)` draws the box being dragged
|
||||
* (`createImageryBoxPreview`).
|
||||
* @returns {{ start: () => boolean, cancel: (reason?: string) => void, isActive: () => boolean, destroy: () => Promise<void> } | null}
|
||||
*/
|
||||
export function initImageryBoxTool({
|
||||
@@ -31,22 +32,21 @@ export function initImageryBoxTool({
|
||||
onCancel,
|
||||
onActive,
|
||||
onEscape,
|
||||
cesium = Cesium,
|
||||
createPreview = createImageryBoxPreview,
|
||||
inputFor = defaultInputFor,
|
||||
pickWorld = pickWorldFromScreen,
|
||||
documentRef = globalThis.document,
|
||||
} = {}) {
|
||||
if (!viewer?.scene || typeof onBox !== 'function') return null;
|
||||
if (!viewer || typeof onBox !== 'function') return null;
|
||||
|
||||
let active = false;
|
||||
let destroyed = false;
|
||||
/** Drag corners in degrees; `anchor` is null while no drag is live. */
|
||||
let anchor = null;
|
||||
let corner = null;
|
||||
let handler = null;
|
||||
let unbindScene = null;
|
||||
let lease = null;
|
||||
let savedSingleClick = null;
|
||||
let savedDoubleClick = null;
|
||||
let savedCameraInputs = null;
|
||||
let releaseCamera = null;
|
||||
|
||||
const dragBox = () =>
|
||||
anchor && {
|
||||
@@ -56,68 +56,11 @@ export function initImageryBoxTool({
|
||||
north: Math.max(anchor.lat, corner.lat),
|
||||
};
|
||||
|
||||
const dataSource = new cesium.CustomDataSource(
|
||||
'gev-recent-imagery-box-preview',
|
||||
);
|
||||
let attaching = Promise.resolve(viewer.dataSources.add(dataSource)).catch(
|
||||
() => null,
|
||||
);
|
||||
const stroke = cesium.Color.fromCssColorString('#8be9ff');
|
||||
const previewRectangle = () => {
|
||||
const box = dragBox();
|
||||
return box
|
||||
? cesium.Rectangle.fromDegrees(box.west, box.south, box.east, box.north)
|
||||
: undefined;
|
||||
};
|
||||
const previewOutline = () => {
|
||||
const box = dragBox();
|
||||
if (!box) return [];
|
||||
return cesium.Cartesian3.fromDegreesArray([
|
||||
box.west,
|
||||
box.south,
|
||||
box.east,
|
||||
box.south,
|
||||
box.east,
|
||||
box.north,
|
||||
box.west,
|
||||
box.north,
|
||||
box.west,
|
||||
box.south,
|
||||
]);
|
||||
};
|
||||
const fill = dataSource.entities.add({
|
||||
show: false,
|
||||
rectangle: {
|
||||
coordinates: new cesium.CallbackProperty(previewRectangle, false),
|
||||
material: stroke.withAlpha(0.12),
|
||||
classificationType: cesium.ClassificationType.BOTH,
|
||||
},
|
||||
});
|
||||
// A rectangle graphic cannot draw a dashed edge on the ground, so the
|
||||
// outline is its own draped polyline traced round the same corners.
|
||||
const outline = dataSource.entities.add({
|
||||
show: false,
|
||||
polyline: {
|
||||
positions: new cesium.CallbackProperty(previewOutline, false),
|
||||
width: 2,
|
||||
clampToGround: true,
|
||||
classificationType: cesium.ClassificationType.BOTH,
|
||||
material: new cesium.PolylineDashMaterialProperty({
|
||||
color: stroke.withAlpha(0.95),
|
||||
dashLength: 12,
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
const requestRender = () => viewer.scene.requestRender?.();
|
||||
const setPreview = (visible) => {
|
||||
fill.show = visible;
|
||||
outline.show = visible;
|
||||
requestRender();
|
||||
};
|
||||
const preview = createPreview(viewer, dragBox);
|
||||
const setPreview = (visible) => preview.setVisible(visible);
|
||||
const worldAt = (position) => {
|
||||
if (!position) return null;
|
||||
const canvas = viewer.scene.canvas;
|
||||
const canvas = canvasOf(viewer);
|
||||
const w = canvas?.clientWidth || canvas?.width || 1;
|
||||
const h = canvas?.clientHeight || canvas?.height || 1;
|
||||
const point = pickWorld(viewer, position.x / w, position.y / h);
|
||||
@@ -125,19 +68,13 @@ export function initImageryBoxTool({
|
||||
const lat = Number(point?.lat);
|
||||
return Number.isFinite(lon) && Number.isFinite(lat) ? { lon, lat } : null;
|
||||
};
|
||||
const cameraController = () => viewer.scene.screenSpaceCameraController;
|
||||
|
||||
function freezeCamera() {
|
||||
const controller = cameraController();
|
||||
if (!controller || savedCameraInputs !== null) return;
|
||||
savedCameraInputs = controller.enableInputs;
|
||||
controller.enableInputs = false;
|
||||
releaseCamera ??= inputFor(viewer).suspendCamera('recent-imagery-box');
|
||||
}
|
||||
function thawCamera() {
|
||||
const controller = cameraController();
|
||||
if (controller && savedCameraInputs !== null)
|
||||
controller.enableInputs = savedCameraInputs;
|
||||
savedCameraInputs = null;
|
||||
releaseCamera?.();
|
||||
releaseCamera = null;
|
||||
}
|
||||
|
||||
function endDrag() {
|
||||
@@ -163,7 +100,7 @@ export function initImageryBoxTool({
|
||||
const point = anchor && !destroyed && worldAt(event.endPosition);
|
||||
if (!point) return;
|
||||
corner = point;
|
||||
requestRender();
|
||||
preview.changed();
|
||||
};
|
||||
const onUp = (event) => {
|
||||
if (!anchor || destroyed) return;
|
||||
@@ -190,45 +127,23 @@ export function initImageryBoxTool({
|
||||
};
|
||||
|
||||
function bindScene() {
|
||||
if (handler) return;
|
||||
handler = new cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
|
||||
handler.setInputAction(onDown, cesium.ScreenSpaceEventType.LEFT_DOWN);
|
||||
handler.setInputAction(onMove, cesium.ScreenSpaceEventType.MOUSE_MOVE);
|
||||
handler.setInputAction(onUp, cesium.ScreenSpaceEventType.LEFT_UP);
|
||||
const stock = viewer.screenSpaceEventHandler;
|
||||
if (stock) {
|
||||
savedSingleClick =
|
||||
stock.getInputAction(cesium.ScreenSpaceEventType.LEFT_CLICK) || null;
|
||||
savedDoubleClick =
|
||||
stock.getInputAction(cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK) ||
|
||||
null;
|
||||
stock.removeInputAction(cesium.ScreenSpaceEventType.LEFT_CLICK);
|
||||
stock.removeInputAction(cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
|
||||
}
|
||||
if (unbindScene) return;
|
||||
const input = inputFor(viewer);
|
||||
const held = { lease: () => lease };
|
||||
const offs = [
|
||||
input.onPointer('down', onDown, held),
|
||||
input.onPointer('move', onMove, held),
|
||||
input.onPointer('up', onUp, held),
|
||||
input.suppressStockClicks(),
|
||||
];
|
||||
unbindScene = () => offs.forEach((off) => off());
|
||||
documentRef?.addEventListener?.('keydown', onKey, true);
|
||||
documentRef?.body?.classList?.add?.('gev-imagery-box');
|
||||
}
|
||||
|
||||
function releaseScene() {
|
||||
if (handler) {
|
||||
handler.destroy();
|
||||
handler = null;
|
||||
}
|
||||
const stock = viewer.screenSpaceEventHandler;
|
||||
if (stock && savedSingleClick) {
|
||||
stock.setInputAction(
|
||||
savedSingleClick,
|
||||
cesium.ScreenSpaceEventType.LEFT_CLICK,
|
||||
);
|
||||
}
|
||||
if (stock && savedDoubleClick) {
|
||||
stock.setInputAction(
|
||||
savedDoubleClick,
|
||||
cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK,
|
||||
);
|
||||
}
|
||||
savedSingleClick = null;
|
||||
savedDoubleClick = null;
|
||||
unbindScene?.();
|
||||
unbindScene = null;
|
||||
documentRef?.removeEventListener?.('keydown', onKey, true);
|
||||
documentRef?.body?.classList?.remove?.('gev-imagery-box');
|
||||
}
|
||||
@@ -236,14 +151,16 @@ export function initImageryBoxTool({
|
||||
function setActive(next) {
|
||||
if (next === active) return active;
|
||||
if (next) {
|
||||
lease = claimPointer(IMAGERY_BOX_POINTER_OWNER);
|
||||
if (!lease) {
|
||||
onCancel?.(
|
||||
'pointer-busy',
|
||||
`${pointerOwner()} is using the pointer — close it first`,
|
||||
);
|
||||
return active;
|
||||
}
|
||||
// The newest claim takes over: a tool holding the pointer is told and
|
||||
// turns itself off, and a newer one cancels this session as if the
|
||||
// person had.
|
||||
const claimed = claimPointer(IMAGERY_BOX_POINTER_OWNER, {
|
||||
onLost: () => {
|
||||
if (lease === claimed) cancel();
|
||||
},
|
||||
});
|
||||
if (!claimed) return active;
|
||||
lease = claimed;
|
||||
active = true;
|
||||
bindScene();
|
||||
} else {
|
||||
@@ -264,7 +181,7 @@ export function initImageryBoxTool({
|
||||
}
|
||||
|
||||
return {
|
||||
/** Begin a box session. False when the pointer is held elsewhere. */
|
||||
/** Begin a box session, taking the pointer from any tool holding it. */
|
||||
start() {
|
||||
return !destroyed && setActive(true);
|
||||
},
|
||||
@@ -274,22 +191,14 @@ export function initImageryBoxTool({
|
||||
},
|
||||
/** Returns everything; resolves once the preview is detached. */
|
||||
destroy() {
|
||||
if (destroyed) return attaching;
|
||||
if (destroyed) return preview.destroy();
|
||||
if (active) setActive(false);
|
||||
destroyed = true;
|
||||
releaseScene();
|
||||
releasePointer(lease);
|
||||
lease = null;
|
||||
thawCamera();
|
||||
dataSource.entities.removeAll();
|
||||
attaching = attaching.then(() => {
|
||||
try {
|
||||
viewer.dataSources.remove(dataSource, true);
|
||||
} catch {
|
||||
/* viewer already disposed */
|
||||
}
|
||||
});
|
||||
return attaching;
|
||||
return preview.destroy();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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.
|
||||
*
|
||||
|
||||
@@ -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' },
|
||||
});
|
||||
|
||||
@@ -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
@@ -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="
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
@@ -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>
|
||||
@@ -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 },
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
@@ -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>
|
||||
@@ -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;
|
||||
}
|
||||
});
|
||||
@@ -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>
|
||||
Loaded 100 of 3290 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user