Merge origin/main into the renderer seam

Brings in main up to f24abfc88: cockpit subject providers, the render
failure notice, aircraft drawn in their own mesh colours, airport ground
vehicles, and an aircraft with no ground track facing its true heading.

Under the seam:
- The render failure notice lives in the Cesium adapter
  (src/render/cesium/renderFailure.js) and is the application hook
  renderFailureNotice({allowReload, store}); its private Cesium fields
  (Event's raise queue, the widget's render loop flag) are read through
  internals.js. The inline panel's timer waits while the frame port reports
  the loop stopped, and goes on after a Retry.
- Ordinary aircraft models draw white with the 'highlight' colour blend
  through the draw port; tracked and emergency colours tint the mesh.
- Held trains and transit vehicles hide their route set and markers through
  the draw port; the fleet model test fakes answer loads through the fake
  draw port instead of Cesium's glTF loader.
- The Cockpit's subject view follows and places the camera through the
  camera port.
This commit is contained in:
Sameh Khamis committed 2026-11-14 09:59:55 -08:00
commit 866a9816f2
142 files changed
+9067 -308

No files matched your search

+8
View File
@@ -413,6 +413,9 @@ export class StyleManager extends ShellFacade {
owner: 'cockpit-orbit',
switchPolicy: 'esri-if-photoreal',
}) ?? null,
// The application's own first-person subjects
// (src/cockpitSubjectProviders.js), checked by the coordinator.
cockpitSubjects: services.cockpitSubjects,
},
elements: {
_ppToggles: this._ppToggles,
@@ -1212,6 +1215,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(),
},
+1
View File
@@ -54,6 +54,7 @@ export class CctvControls {
this._cctvSummaryTypingTimer = null;
this._lastCctvSummaryText = '';
this._lastSeenCctvActiveId = null;
this._wasCctvEnabled = false;
this._cctvChipHideTimer = null;
this._cctvChipWasBusy = false;
// The camera grid chip as last published; its label stays while hidden.
+93
View File
@@ -513,3 +513,96 @@ test('the panel meta line reads a bearing that rounds to north as HDG 0°', () =
assert.match(meta(359.4), /· HDG 359° ·/);
assert.match(meta(359.6), /· HDG 0° ·/);
});
/** The panel collapses the test asked for, as `[panelId, collapsed]` pairs. */
function collapseCalls(controls) {
const calls = [];
controls.actions.setPanelCollapsed = (panelId, collapsed) => {
calls.push([panelId, collapsed]);
// The panel chrome owns the class the controls read back.
controls._cctvPanel.classList.toggle('collapsed', collapsed);
};
return calls;
}
const activeState = {
enabled: true,
count: 1,
cameraIndex: [],
activeCameraId: camera.id,
activeCamera: camera,
};
test('switching the layer off collapses the panel it opened', (t) => {
const { controls } = panel(t);
const calls = collapseCalls(controls);
controls._renderCctvState(activeState);
assert.deepEqual(calls, [['cctv-panel', false]]);
// The layer keeps its active camera while off.
controls._renderCctvState({ ...activeState, enabled: false });
assert.deepEqual(calls.at(-1), ['cctv-panel', true]);
// A panel reopened by hand stays open through later notifications while
// the layer is off: only the on → off change collapses.
controls._cctvPanel.classList.remove('collapsed');
controls._renderCctvState({ ...activeState, enabled: false });
assert.equal(calls.length, 2);
assert.equal(controls._cctvPanel.classList.contains('collapsed'), false);
});
test('a layer that was never on leaves an open panel alone', (t) => {
const { controls } = panel(t);
const calls = collapseCalls(controls);
controls._renderCctvState({ enabled: false, count: 3, cameraIndex: [] });
controls._renderCctvState({ enabled: false, count: 3, cameraIndex: [] });
assert.deepEqual(calls, []);
});
test('the data manager switching the layer off collapses the panel too', (t) => {
const { controls } = panel(t);
const calls = collapseCalls(controls);
let on = true;
controls.actions.isEnabled = () => on;
controls._renderCctvState(activeState);
on = false;
controls._renderCctvState(activeState);
assert.deepEqual(calls.at(-1), ['cctv-panel', true]);
});
test('a layer the application suspends keeps its panel through the round trip', (t) => {
const { controls } = panel(t);
const calls = collapseCalls(controls);
// Clear selected data layers and Context isolation both answer true.
let suspended = true;
controls.actions.preservePanelState = () => suspended;
controls._renderCctvState(activeState);
controls._renderCctvState({ ...activeState, enabled: false });
assert.equal(controls._cctvPanel.classList.contains('collapsed'), false);
suspended = false;
controls._renderCctvState(activeState);
assert.equal(controls._cctvPanel.classList.contains('collapsed'), false);
assert.ok(calls.every(([, collapsed]) => collapsed === false));
// The next switch-off is the user's again.
controls._renderCctvState({ ...activeState, enabled: false });
assert.deepEqual(calls.at(-1), ['cctv-panel', true]);
});
test('a panel the accordion folded still has its saved state closed', (t) => {
const { controls } = panel(t);
controls._renderCctvState(activeState);
const calls = [];
controls.actions.setPanelCollapsed = (...args) => calls.push(args);
// Folded for layout only: the class is there, the saved state is open. The
// panel chrome tells the two apart, so the controls always ask it.
controls._cctvPanel.classList.add('collapsed');
controls._renderCctvState({ ...activeState, enabled: false });
assert.deepEqual(calls, [['cctv-panel', true]]);
});
test('the meta line of a disabled layer does not describe its last camera', () => {
const off = { ...activeState, enabled: false, count: 3 };
assert.equal(
presentCctvPanel(off, false).meta,
'3 cameras loaded · enable CCTV to activate',
);
assert.match(presentCctvPanel(activeState, true).meta, /^Austin · HDG /);
});
+17 -1
View File
@@ -90,7 +90,9 @@ export function presentCctvPanel(state, enabled) {
}
function metaText(state, enabled, activeCamera, catalogCount) {
if (activeCamera) {
// The layer keeps its active camera while off: a disabled panel must not
// describe a feed it no longer shows.
if (enabled && activeCamera) {
const provider = cctvSourceLabelText(
activeCamera.sourceLabel || activeCamera.provider || 'Configured Source',
);
@@ -188,6 +190,20 @@ export function _renderCctvState(state) {
});
}
this._lastSeenCctvActiveId = effectiveActiveId;
// Switching the layer off closes the panel it opened: nothing is left to
// show. Only the on → off change collapses, so a panel the user opens
// while the layer is off stays open. Clear selected data layers and
// Context isolation keep the panel: the layer comes back with it. The
// panel chrome decides whether anything changes: a panel the desktop
// accordion only folded still has an open saved state to close.
if (
this._wasCctvEnabled &&
!enabled &&
!this.actions.preservePanelState?.()
) {
this.actions.setPanelCollapsed('cctv-panel', true);
}
this._wasCctvEnabled = enabled;
this._updateCctvSyncChip(state?.loading, enabled);
+1 -1
View File
@@ -164,7 +164,7 @@ export function maybeRefreshRegionalBrief(info) {
!Number.isFinite(info.longitude)
)
return;
const subjectId = `${info.layerId || 'aircraft'}:${info.icao24 || (info.kind === 'vessel' ? info.id : '') || info.noradId || info.registration || info.callsign || 'unknown'}`;
const subjectId = `${info.layerId || 'aircraft'}:${info.icao24 || (info.kind === 'vessel' || info.generic === true ? info.id : '') || info.noradId || info.registration || info.callsign || 'unknown'}`;
if (subjectId !== this.regionalBriefSubjectId) {
this.regionalBriefAbort?.abort();
this.regionalBriefAbort = null;
+161 -4
View File
@@ -23,6 +23,8 @@ import {
import {
cockpitAnchorCorrectionStep,
cockpitGroundSafeHeight,
easeCockpitLift,
cockpitSubjectStepSec,
cockpitSurfaceWaitExpired,
cockpitUiUpdateDue,
slewHeading,
@@ -36,6 +38,7 @@ import {
waterlineProbePoints,
} from '../cockpitSubjects.js';
import { easeLook } from '../cockpitLook.js';
import { cockpitSubjectFrame } from '../cockpitSubjectProviders.js';
import {
COCKPIT_HEADING_SLEW_DPS,
COCKPIT_FORWARD_OFFSET_M,
@@ -84,6 +87,10 @@ export function update() {
}
const nowMs = performance.now();
if (this.subjectProvider) {
updateSubject.call(this, nowMs);
return;
}
if (this.subjectKind === 'vessel') {
updateVessel.call(this, nowMs);
return;
@@ -323,9 +330,122 @@ function updateVessel(nowMs) {
);
}
/**
* Drive the camera from an application provider's subject: read its frame,
* stand the eye `eye.upM` above `heightM` (the shared floor where the frame
* gives none) and slew toward its heading. A frame that is null, malformed or
* for another subject ends the view, as an aircraft tracked meanwhile does.
* The update runs on the provider's `cameraIntervalMs` (0: every frame), and
* its rates advance by the time that interval spans (cockpitSubjectStepSec).
*/
function updateSubject(nowMs) {
const provider = this.subjectProvider;
if (isFollowing(this.viewer)) {
this.exit({ restoreTracking: false });
return;
}
const intervalMs = provider.cameraIntervalMs ?? COCKPIT_CAMERA_UPDATE_MS;
if (!cockpitUiUpdateDue(nowMs, this.lastCameraUpdateMs, intervalMs)) return;
this.lastCameraUpdateMs = nowMs;
const frame = cockpitSubjectFrame(
this.callSubject(provider, 'read', [nowMs, this.subjectContext()], null),
this.subjectId,
);
if (!frame) {
this.exit({ restoreTracking: false });
return;
}
this.lastSubjectFrame = frame;
let heightM = frame.heightM;
if (heightM === null) {
this.services.warmGroundFloor?.([
{ lat: frame.latitude, lon: frame.longitude },
]);
const floorM = this.services.cachedGroundFloor?.(
frame.latitude,
frame.longitude,
);
// A frame with no height stands on the shared floor; while that is cold
// it keeps the height it last stood at.
heightM = Number.isFinite(floorM) ? floorM : this.subjectHeightM;
}
if (!Number.isFinite(heightM)) {
// Nothing to stand on yet, from the first frame: the camera stays where
// it is while the floor is acquired, its HUD saying so, rather than
// standing on the ellipsoid (kilometres underground on a plateau). The
// wait is bounded as the built-in views' is. Unlike a parked aircraft,
// whose fallback is its own reported altitude, such a subject has no
// height at all to fall back to: any number would be a guess, so the
// view ends and the provider gets its subject back.
if (!this.surfaceWaitStartedMs) this.surfaceWaitStartedMs = nowMs;
if (
cockpitSurfaceWaitExpired(
nowMs,
this.surfaceWaitStartedMs,
COCKPIT_GROUND_WAIT_TIMEOUT_MS,
)
) {
this.exit({ restoreTracking: false });
return;
}
this.surfaceAcquiring = true;
if (
cockpitUiUpdateDue(nowMs, this.lastHudUpdateMs, COCKPIT_HUD_UPDATE_MS)
) {
this.lastHudUpdateMs = nowMs;
this.updateHud(this.subjectInfo(frame), nowMs);
}
return;
}
this.surfaceWaitStartedMs = 0;
this.surfaceAcquiring = false;
this.subjectHeightM = heightM;
const target = fromDegrees(frame.longitude, frame.latitude, heightM);
const dtSec = cockpitSubjectStepSec(nowMs - this.lastFrameMs, intervalMs);
this.lastFrameMs = nowMs;
if (frame.headingDeg !== null) {
const rate = provider.headingSlewDps ?? COCKPIT_HEADING_SLEW_DPS;
this.heading =
rate === Infinity
? frame.headingDeg
: slewHeading(
this.heading ?? frame.headingDeg,
frame.headingDeg,
rate * dtSec,
);
}
let look = null;
if (provider.look) {
this.lookView = easeLook(
this.lookView,
this.lookTarget,
nowMs - (this.lookLastMs || nowMs),
);
this.lookLastMs = nowMs;
look = this.lookView;
}
placeCamera.call(
this,
target,
this.subjectInfo(frame),
nowMs,
dtSec,
{
forwardM: frame.eye.forwardM,
upM: frame.eye.upM,
pitchDeg: frame.eye.pitchDeg,
minClearanceM: frame.eye.minClearanceM,
},
look,
);
}
/**
* Place the camera for one update: advance the inertial anchor, clamp it and
* the eye against the rendered surface, and look along the slewed heading.
* 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.
@@ -342,6 +462,7 @@ function placeCamera(target, info, nowMs, dtSec, profile, look = null) {
if (!this.cockpitAnchorValid) {
this.cockpitAnchor = clone(target);
this.cockpitAnchorValid = true;
this.subjectLiftM = null;
}
// First-person motion cannot use the delayed feed correction as a raw
@@ -363,7 +484,8 @@ function placeCamera(target, info, nowMs, dtSec, profile, look = null) {
? Math.max(0, info.velocityMps)
: 0;
if (info.stale) {
const groundClamp = info.groundClamp !== false;
if (info.stale || info.anchor === 'exact') {
// A feed backoff has no authoritative velocity epoch to advance from.
// Hold the cockpit on the exact layer-rendered position so the camera
// cannot coast away while the icon correctly remains fixed.
@@ -381,10 +503,13 @@ function placeCamera(target, info, nowMs, dtSec, profile, look = null) {
);
const correction = sub(target, this.cockpitAnchor);
const correctionDistanceM = magnitude(correction);
// An application subject's step is already bounded by its own update
// interval (cockpitSubjectStepSec); the built-in views keep the 0.1 s.
const correctionStepM = cockpitAnchorCorrectionStep(
correctionDistanceM,
speedMps,
dtSec,
info.generic === true ? dtSec : undefined,
);
if (correctionStepM > 0 && correctionDistanceM > 0) {
this.cockpitAnchor = add(
@@ -488,7 +613,14 @@ function placeCamera(target, info, nowMs, dtSec, profile, look = null) {
cockpitFloorM =
targetCartographic.height - this.services.GROUND_FLOOR_LIFT_M;
}
if (anchorCartographic && Number.isFinite(cockpitFloorM)) {
// An application subject's anchor is where its provider puts it; only its
// eye is kept out of the floor, below.
if (
groundClamp &&
info.generic !== true &&
anchorCartographic &&
Number.isFinite(cockpitFloorM)
) {
const minimumAnchorHeightM = cockpitGroundSafeHeight(
anchorCartographic.height,
cockpitFloorM,
@@ -536,7 +668,7 @@ function placeCamera(target, info, nowMs, dtSec, profile, look = null) {
// Recheck at the final forward-offset camera coordinate because a taxiing
// aircraft can cross into an adjacent coarse floor cell between updates.
const cameraCartographic = toCartographicRadians(eye);
if (cameraCartographic) {
if (groundClamp && cameraCartographic) {
const cameraLat = toDegrees(cameraCartographic.lat);
const cameraLon = toDegrees(cameraCartographic.lon);
const cameraFloorM = this.services.cachedGroundFloor(cameraLat, cameraLon);
@@ -546,11 +678,26 @@ function placeCamera(target, info, nowMs, dtSec, profile, look = null) {
cameraFloorM,
);
}
const safeHeightM = cockpitGroundSafeHeight(
let safeHeightM = cockpitGroundSafeHeight(
cameraCartographic.height,
cockpitFloorM,
profile.minClearanceM,
);
// An application subject's eye rides its provider's smoothed height:
// the clearance over the coarse, refining floor eases in and out
// rather than jumping at each cell (easeCockpitLift).
if (info.generic === true) {
const hardM =
cockpitGroundSafeHeight(cameraCartographic.height, cockpitFloorM, 0) -
cameraCartographic.height;
this.subjectLiftM = easeCockpitLift(
this.subjectLiftM,
safeHeightM - cameraCartographic.height,
hardM,
dtSec,
);
safeHeightM = cameraCartographic.height + this.subjectLiftM;
}
if (safeHeightM !== cameraCartographic.height) {
eye = fromRadians(
cameraCartographic.lon,
@@ -558,6 +705,16 @@ function placeCamera(target, info, nowMs, dtSec, profile, look = null) {
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,
);
}
cameraOf(this.viewer).setView({
+81 -5
View File
@@ -5,12 +5,18 @@ import {
readAircraftInfo,
readSatelliteInfo,
readVesselInfo,
readSubjectCandidate,
readSubjectLayerId,
subjectContext,
subjectInfo,
entryCandidates,
resolveEntry,
resolveEntryKind,
dispatchCockpitModeChanged,
toggleTrackedTr3b,
syncTr3bToggle,
syncEntry,
refreshSubjectWords,
publishPresenceView,
navigateContext,
_adoptTrackedEntity,
@@ -103,6 +109,7 @@ import {
import { DEFAULT_RADAR_RANGE_NM, nextRadarRange } from '../cockpitRadar.js';
import { VESSEL_BRIDGE_PITCH_DEG } from '../cockpitSubjects.js';
import { stepLook } from '../cockpitLook.js';
import { createCockpitSubjectCaller } from '../cockpitSubjectProviders.js';
/** Whether the user asked for reduced motion: look turns then jump. */
function prefersReducedMotion() {
@@ -122,6 +129,8 @@ export class CockpitViewController {
isEntryAllowed = null,
isBridgeEntryAllowed = null,
isOrbitEntryAllowed = null,
subjectProviders = [],
isSubjectEntryAllowed = null,
isUtilityDisclosureOpen = null,
onEntered = null,
onExited = null,
@@ -140,10 +149,27 @@ export class CockpitViewController {
/** Gives camera input back; held from enter to exit. */
this.releaseCameraInput = null;
/**
* 'aircraft', 'vessel' or 'satellite' while active; which subject the
* camera rides.
* 'aircraft', 'vessel', 'satellite' or a provider's kind while active;
* which subject the camera rides.
*/
this.subjectKind = null;
/**
* The application's subject providers (cockpitSubjectProviders.js),
* checked by the coordinator; the one ridden while active, else null.
*/
this.subjectProviders = Array.isArray(subjectProviders)
? subjectProviders
: [];
this.subjectProvider = null;
/** The ridden provider subject's last frame and normalized HUD view. */
this.lastSubjectFrame = null;
this.subjectHud = null;
/** The Live Signals rows the provider's HUD view pushed. */
this.subjectSignalKeys = new Set();
/** Provider methods run through one guard: a throw warns once. */
this.callSubject = createCockpitSubjectCaller();
/** The look's rest pitch for a provider's view; null on a bridge. */
this.lookRestPitchDeg = null;
/**
* The vessel subject's id or the satellite's NORAD id; aircraft are
* identified by trackedEntity.
@@ -168,6 +194,10 @@ export class CockpitViewController {
this.surfaceWaitStartedMs = 0;
this.surfaceAcquiring = false;
this.surfaceFallback = false;
/** The height an application subject's frame last stood at (m). */
this.subjectHeightM = null;
/** The ground clamp's eased lift under that subject's eye (m). */
this.subjectLiftM = null;
/**
* Where the bridge view is turned to (`lookTarget`) and where the camera
* looks on its way there (`lookView`): yaw off the bow, starboard
@@ -211,6 +241,11 @@ export class CockpitViewController {
typeof isOrbitEntryAllowed === 'function'
? isOrbitEntryAllowed
: () => false;
// Nor a provider's subject without a gate for it.
this.isSubjectEntryAllowed =
typeof isSubjectEntryAllowed === 'function'
? isSubjectEntryAllowed
: () => false;
this.isUtilityDisclosureOpen =
typeof isUtilityDisclosureOpen === 'function'
? isUtilityDisclosureOpen
@@ -254,7 +289,14 @@ export class CockpitViewController {
entryAvailable: false,
// Which subject the entry button would enter, and the active subject.
entryKind: null,
// A provider's entry face, `{icon, label}`; null for the built-ins.
entryFace: null,
subjectKind: null,
// While a provider's subject is ridden: its HUD and exit labels, and
// `{aheadLabel}` when it looks around.
subjectGeneric: false,
subjectLabels: null,
subjectLook: null,
tr3b: null,
context: false,
// The Contact and briefing cards' collapse, which their toggles show.
@@ -508,6 +550,21 @@ export class CockpitViewController {
if (reset && hadFocus) this.mapViewButton?.focus({ preventScroll: true });
return reset;
}
readSubjectCandidate(provider) {
return readSubjectCandidate.call(this, provider);
}
subjectContext() {
return subjectContext.call(this);
}
subjectInfo(frame) {
return subjectInfo.call(this, frame);
}
entryCandidates(nowMs) {
return entryCandidates.call(this, nowMs);
}
resolveEntry(nowMs) {
return resolveEntry.call(this, nowMs);
}
readSubjectLayerId() {
return readSubjectLayerId.call(this);
}
@@ -529,6 +586,9 @@ export class CockpitViewController {
syncEntry() {
return syncEntry.call(this);
}
refreshSubjectWords() {
return refreshSubjectWords.call(this);
}
navigateContext(direction, options) {
return navigateContext.call(this, direction, options);
}
@@ -568,6 +628,19 @@ export class CockpitViewController {
presentLook() {
return presentLook.call(this);
}
/** Whether the active view looks around: a bridge, or a provider's with `look`. */
get looksAround() {
return (
this.active &&
(this.subjectKind === 'vessel' || Boolean(this.subjectProvider?.look))
);
}
/** Where the look rests: the bridge's pitch, or the provider's. */
get lookRestPitch() {
return Number.isFinite(this.lookRestPitchDeg)
? this.lookRestPitchDeg
: VESSEL_BRIDGE_PITCH_DEG;
}
/**
* Turn the bridge view one arrow step (see `lookKeyStep`). The camera
* eases there unless the user prefers reduced motion.
@@ -575,7 +648,7 @@ export class CockpitViewController {
* @returns {boolean} True when a bridge view was turned.
*/
turnLook(step) {
if (!this.active || this.subjectKind !== 'vessel' || !step) return false;
if (!this.looksAround || !step) return false;
this.lookTarget = stepLook(this.lookTarget, step);
if (prefersReducedMotion()) this.lookView = { ...this.lookTarget };
this.presentLook();
@@ -588,7 +661,7 @@ export class CockpitViewController {
* as entry and exit do.
*/
resetLook({ immediate = false } = {}) {
this.lookTarget = { yawDeg: 0, pitchDeg: VESSEL_BRIDGE_PITCH_DEG };
this.lookTarget = { yawDeg: 0, pitchDeg: this.lookRestPitch };
if (immediate || prefersReducedMotion())
this.lookView = { ...this.lookTarget };
this.lookLastMs = performance.now();
@@ -601,7 +674,7 @@ export class CockpitViewController {
* @returns {boolean} True on a bridge.
*/
lookAhead() {
if (!this.active || this.subjectKind !== 'vessel') return false;
if (!this.looksAround) return false;
const button = document.getElementById('cockpit-look-ahead');
const hadFocus = !!button && button.contains(document.activeElement);
this.resetLook();
@@ -718,6 +791,9 @@ export class CockpitViewController {
this.relocalizeBrief();
this.publishVision(createVisionState(this.visionMode));
this.routeSignature = null;
// A provider's words, ridden or on the entry, follow the language.
this.refreshSubjectWords();
if (!this.active) this.syncEntry();
if (this.active && this.lastSubjectInfo) {
this.rewordingSignals = true;
try {
+55 -19
View File
@@ -6,7 +6,9 @@ import {
bridgeEntryAllowed,
cockpitEntryAllowed,
orbitEntryAllowed,
subjectEntryAllowed,
} from '../contextModePolicy.js';
import { cockpitSubjectProviders } from '../cockpitSubjectProviders.js';
import { formatAwarenessLabel } from '../data/militaryAwarenessEngine.js';
import { enterCockpitWithTracking } from '../cockpitTracking.js';
import { cockpitVisionModeForStyle } from '../cockpitVisionPolicy.js';
@@ -63,8 +65,11 @@ export class CockpitCoordinator {
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,
@@ -112,6 +117,21 @@ export class CockpitCoordinator {
vesselsEnabled: !!this._dataManager?.isEnabled('ais-live-vessels'),
contextModeChanging: this._contextModeChanging,
}),
subjectProviders,
// A provider's subject needs its own layer on, no Context change in
// flight, and the provider's own say.
isSubjectEntryAllowed: (provider, candidate) =>
subjectEntryAllowed({
layerEnabled: this._isLayerEnabled(provider.layerId),
contextModeChanging: this._contextModeChanging,
providerAllows:
this.cockpitView?.callSubject(
provider,
'isEntryAllowed',
[candidate],
false,
) === true,
}),
isOrbitEntryAllowed: () =>
orbitEntryAllowed({
satellitesEnabled: !!this._dataManager?.isEnabled('satellites'),
@@ -201,6 +221,9 @@ export class CockpitCoordinator {
this.cockpitView.subjectKind === 'satellite'
)
return 'Cockpit is in an orbital view — exit it first, then track an aircraft to enter Cockpit';
// And in an application's own first-person view.
if (this.cockpitView?.active && this.cockpitView.subjectProvider)
return 'Cockpit is in another first-person view — exit it first, then track an aircraft to enter Cockpit';
if (!this._aircraftLayerEnabled)
return 'No aircraft layer is on — turn on Flights or Military Flights and track an aircraft to enter Cockpit';
return null;
@@ -220,6 +243,17 @@ export class CockpitCoordinator {
active && this.cockpitView?.subjectKind === 'satellite'
? this.cockpitView.readSatelliteInfo?.()
: null;
// And a provider's subject in use.
const provided =
active && this.cockpitView?.subjectProvider
? {
kind: this.cockpitView.subjectProvider.kind,
id: this.cockpitView.subjectId,
layerId: this.cockpitView.subjectProvider.layerId,
callsign: null,
name: this.cockpitView.lastSubjectFrame?.name ?? null,
}
: null;
const gateOpen = Boolean(this.cockpitView?.isEntryAllowed?.());
// "Could Cockpit be ENTERED right now" — so it is false while already
// inside, unconditionally. Cockpit takes the entity off
@@ -248,30 +282,32 @@ export class CockpitCoordinator {
? 'subject-layer-off'
: 'no-tracked-aircraft',
visionMode: this.cockpitView?.visionMode || null,
subject: satellite
? {
kind: 'satellite',
id: satellite.id,
layerId: satellite.layerId,
callsign: null,
name: satellite.name,
}
: vessel
subject: provided
? provided
: satellite
? {
kind: 'vessel',
id: vessel.id,
layerId: vessel.layerId,
kind: 'satellite',
id: satellite.id,
layerId: satellite.layerId,
callsign: null,
name: vessel.name,
name: satellite.name,
}
: info
: vessel
? {
kind: 'aircraft',
id: info.icao24 || info.id || null,
layerId: info.layerId || null,
callsign: info.callsign || null,
kind: 'vessel',
id: vessel.id,
layerId: vessel.layerId,
callsign: null,
name: vessel.name,
}
: null,
: info
? {
kind: 'aircraft',
id: info.icao24 || info.id || null,
layerId: info.layerId || null,
callsign: info.callsign || null,
}
: null,
navigation: snapshot
? {
canPrevious: Boolean(snapshot.navigation?.canPrevious),
+209 -2
View File
@@ -62,8 +62,11 @@ function fixture(
changing = false,
dataManager: suppliedManager = null,
readContext = null,
subjects = [],
vessel = null,
} = {},
) {
let selectedVessel = vessel;
document.body.replaceChildren();
const host = document.body.appendChild(document.createElement('div'));
const pinia = createPinia();
@@ -112,7 +115,13 @@ function fixture(
services: {
flightsLayer: { getTrackedInfo: trackedFrom('flights') },
militaryFlightsLayer: { getTrackedInfo: trackedFrom('military') },
aisLiveVesselsLayer: { getCockpitSubject: () => null },
// Like the layer, no subject while Live AIS Vessels is off.
aisLiveVesselsLayer: {
getCockpitSubject: () =>
selectedVessel && layers.has('ais-live-vessels')
? { ...selectedVessel }
: null,
},
// Like the layer, no subject while Satellites is off.
satellitesLayer: {
getCockpitSubject: () =>
@@ -124,6 +133,7 @@ function fixture(
isTr3b: () => false,
holdContinuousRender() {},
releaseContinuousRender() {},
cockpitSubjects: subjects,
},
elements: {},
operations: {
@@ -158,6 +168,7 @@ function fixture(
'cockpit-mode',
'cockpit-bridge',
'cockpit-orbit',
'cockpit-subject',
);
});
/** Turn a layer off and tell the Context owner, as the data manager does. */
@@ -183,10 +194,35 @@ function fixture(
entities.add(next);
followEntity(viewer, next);
};
/** Select a vessel on the map, or none. */
const selectVessel = (info) => {
selectedVessel = info;
};
const $ = (selector) => document.querySelector(selector);
return { $, coordinator, cockpit, store, layers, disable, retrack, pinia };
return {
$,
coordinator,
cockpit,
store,
layers,
disable,
retrack,
selectVessel,
pinia,
};
}
/** A selected vessel as the AIS layer gives it to the bridge view. */
const VESSEL = Object.freeze({
id: '211000001',
name: 'EXAMPLE',
latitude: 54,
longitude: 10,
headingDeg: 90,
courseDeg: 90,
speedMps: 5,
});
test('a civilian aircraft enters with Live Flights alone: no Contacts, no Military', (t) => {
const { coordinator, cockpit } = fixture(t, {
enabled: ['flights'],
@@ -581,6 +617,32 @@ test('the readout entry reads BRIDGE for a selected vessel', async (t) => {
assert.match(readoutEntry.textContent, /BRIDGE/);
});
test('without providers the built-in order decides: a vessel selected after an aircraft still reads COCKPIT', async (t) => {
const { $, cockpit, store, selectVessel } = fixture(t, {
enabled: ['flights', 'ais-live-vessels'],
tracked: { layerId: 'flights', info: CIVIL },
});
cockpit.syncEntry();
assert.equal(store.presence.entryKind, 'aircraft');
await new Promise((resolve) => setTimeout(resolve, 2));
selectVessel(VESSEL);
cockpit.syncEntry();
await nextTick();
assert.equal(store.presence.entryKind, 'aircraft');
assert.match($('#cockpit-entry-readout').textContent, /COCKPIT/);
// And the other way round: an aircraft tracked after the vessel.
const later = fixture(t, {
enabled: ['flights', 'ais-live-vessels'],
vessel: VESSEL,
});
later.cockpit.syncEntry();
assert.equal(later.store.presence.entryKind, 'vessel');
await new Promise((resolve) => setTimeout(resolve, 2));
later.retrack({ layerId: 'flights', info: CIVIL });
later.cockpit.syncEntry();
assert.equal(later.store.presence.entryKind, 'aircraft');
});
test('a tracked satellite needs Satellites on for the ORBIT entry', async (t) => {
const { $, cockpit } = fixture(t, { satellite: SATELLITE });
cockpit.syncEntry();
@@ -662,3 +724,148 @@ test('turning Satellites off ends the orbital view', (t) => {
disable('satellites');
assert.equal(cockpit.active, false);
});
/** An application provider whose subject sits on `example-layer`. */
function exampleSubject() {
const released = [];
return {
released,
provider: {
kind: 'example-kind',
layerId: 'example-layer',
entryFace: { icon: 'commute', label: 'RIDE' },
labels: { view: 'Example view', exit: 'Exit example', exitText: 'EXIT' },
candidate: () => ({ id: 'a1', name: 'Example 12' }),
hold: () => true,
read: () => ({
id: 'a1',
name: 'Example 12',
latitude: 30,
longitude: -97,
heightM: 200,
headingDeg: 90,
eye: { upM: 2 },
}),
hud: () => ({ title: 'Example 12' }),
release: (id, { restore }) => released.push([id, restore]),
},
};
}
test("a provider's subject needs only its own layer, and never a Context change in flight", async (t) => {
const { provider } = exampleSubject();
let changing = false;
const off = fixture(t, { subjects: [provider] });
off.cockpit.syncEntry();
await nextTick();
assert.equal(off.$('#cockpit-entry').hidden, true, 'its layer is off');
assert.equal(off.cockpit.enter(), false);
const on = fixture(t, {
enabled: ['example-layer'],
subjects: [provider],
readContext: () => ({ mode: null, changing }),
});
changing = true;
on.cockpit.syncEntry();
await nextTick();
assert.equal(on.$('#cockpit-entry').hidden, true, 'Context is changing');
changing = false;
on.cockpit.syncEntry();
await nextTick();
assert.equal(on.$('#cockpit-entry').hidden, false);
assert.match(on.$('#cockpit-entry').textContent, /RIDE/);
assert.match(on.$('#cockpit-entry-readout').textContent, /commute/);
});
test("a provider's view reports its subject, refuses voice entry and ends with its layer", async (t) => {
const { provider, released } = exampleSubject();
const { cockpit, coordinator, disable } = fixture(t, {
enabled: ['example-layer', 'flights'],
subjects: [provider],
});
cockpit.syncEntry();
assert.equal(cockpit.enter(), true);
const state = coordinator.getCockpitState();
assert.equal(state.active, true);
assert.deepEqual(state.subject, {
kind: 'example-kind',
id: 'a1',
layerId: 'example-layer',
callsign: null,
name: 'Example 12',
});
assert.equal(coordinator.controlCockpit('enter').ok, false);
assert.match(coordinator._cockpitEntryRefusal(), /another first-person view/);
disable('flights');
assert.equal(cockpit.active, true, 'another layer is free to go off');
disable('example-layer');
assert.equal(cockpit.active, false, 'its own layer going off ends it');
assert.deepEqual(released, [['a1', false]]);
});
test("a provider's guards: a throwing candidate, gate or release, and a gate that is not true", async (t) => {
const warned = [];
t.mock.method(console, 'warn', (message) => warned.push(String(message)));
const entered = (provider) => {
const { cockpit } = fixture(t, {
enabled: ['example-layer'],
subjects: [provider],
});
cockpit.syncEntry();
return { cockpit, entered: cockpit.enter() };
};
const { provider: base } = exampleSubject();
// A candidate() that throws offers nothing.
const noCandidate = entered({
...base,
candidate: () => {
throw new Error('candidate failed');
},
});
assert.equal(noCandidate.entered, false);
assert.equal(noCandidate.cockpit.resolveEntry(), null);
// An isEntryAllowed() that throws, or answers anything but true, shuts
// the gate.
for (const isEntryAllowed of [
() => {
throw new Error('gate failed');
},
() => 1,
() => 'yes',
() => ({}),
]) {
const gated = entered({ ...base, isEntryAllowed });
assert.equal(gated.entered, false, String(isEntryAllowed));
assert.equal(gated.cockpit.active, false);
}
// A release() that throws still ends the view.
const { provider } = exampleSubject();
const releasing = entered({
...provider,
release: () => {
throw new Error('release failed');
},
});
assert.equal(releasing.entered, true);
assert.equal(releasing.cockpit.exit(), true);
assert.equal(releasing.cockpit.active, false);
assert.equal(document.body.classList.contains('cockpit-subject'), false);
for (const method of ['candidate', 'isEntryAllowed', 'release'])
assert.ok(
warned.some((line) => line.includes(`${method}() failed`)),
method,
);
});
test('a malformed provider is left out and the built-in kinds are unchanged', async (t) => {
t.mock.method(console, 'warn', () => {});
const { cockpit } = fixture(t, {
enabled: ['flights'],
tracked: { layerId: 'flights', info: CIVIL },
subjects: [{ kind: 'aircraft', layerId: 'flights' }],
});
assert.deepEqual(cockpit.subjectProviders, []);
cockpit.syncEntry();
assert.equal(cockpit.enter(), true);
assert.equal(cockpit.subjectKind, 'aircraft');
});
+4 -1
View File
@@ -40,6 +40,9 @@ function subjectWorldPosition(kind) {
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;
@@ -251,7 +254,7 @@ const LOOK_KEY_OWNERS = [
* @returns {boolean} True when the key was taken.
*/
function handleLookKey(event) {
if (!this.active || this.subjectKind !== 'vessel') return false;
if (!this.looksAround) return false;
if (event.metaKey || event.ctrlKey || event.altKey) return false;
const step = lookKeyStep(event.key, event.shiftKey);
const reset = !event.repeat && (event.key === 'Home' || event.key === '0');
+17 -2
View File
@@ -52,7 +52,7 @@ function createRimState(value) {
*/
export function createInstrumentState() {
return {
// 'aircraft' or 'vessel': which readouts the HUD labels and shows.
// 'aircraft', 'vessel' or 'subject': which readouts the HUD shows.
kind: 'aircraft',
layer: null,
callsign: t('AIRCRAFT'),
@@ -76,6 +76,19 @@ export function createInstrumentState() {
look: { offset: false, yawDeg: 0, readout: '' },
clock: '--:--:--Z',
position: '--° · --°',
// A provider subject's HUD (kind 'subject', cockpitSubjectProviders.js):
// its kicker, speed unit and tag, readouts, sources, banner, veil and
// progress line, all worded by the provider.
kicker: '',
speedUnit: '',
speedTag: '',
speedTone: 'normal',
readouts: [],
sources: [],
banner: null,
veil: null,
progress: null,
lookEnabled: false,
};
}
@@ -86,8 +99,10 @@ export function createInstrumentState() {
*/
export function createRouteState() {
return {
// A vessel's card shows only the free-text AIS destination.
// A vessel's card shows only the free-text AIS destination; a provider's
// subject's (kind 'subject') carries its own title.
kind: 'aircraft',
title: '',
visible: false,
from: t('UNKNOWN'),
to: t('UNKNOWN'),
+150 -4
View File
@@ -35,6 +35,7 @@ import {
vesselCameraProfile,
} from '../cockpitSubjects.js';
import { lookIsOffset, lookReadoutParts, wrapLookYaw } from '../cockpitLook.js';
import { cockpitSubjectHudView } from '../cockpitSubjectProviders.js';
import {
RADAR_MAX_CONTACTS,
radarPicture,
@@ -90,6 +91,13 @@ export function publishInstrumentsView() {
compass: view.compass.map((division) => ({ ...division })),
compassMarkers: { ...view.compassMarkers },
look: { ...view.look },
// A provider's view model is rebuilt on each HUD update, never edited
// in place, so it is published as it stands.
readouts: view.readouts,
sources: view.sources,
banner: view.banner,
veil: view.veil,
progress: view.progress,
});
}
@@ -118,24 +126,162 @@ function wordLook({ side, bearingDeg, elevation, angleDeg }) {
*/
export function presentLook() {
const target = this.lookTarget;
// A provider's view words its own readout (its HUD view's `lookReadout`).
const provider = Boolean(this.subjectProvider);
const rest = provider ? this.lookRestPitch : VESSEL_BRIDGE_PITCH_DEG;
const offset =
this.active &&
this.subjectKind === 'vessel' &&
lookIsOffset(target, VESSEL_BRIDGE_PITCH_DEG);
(this.active && this.subjectKind === 'vessel') ||
(provider && this.looksAround)
? lookIsOffset(target, rest)
: false;
this.instruments.look = offset
? {
offset: true,
yawDeg: wrapLookYaw(target.yawDeg),
readout: wordLook(lookReadoutParts(target, VESSEL_BRIDGE_PITCH_DEG)),
readout: provider
? (this.subjectHud?.lookReadout ?? '')
: wordLook(lookReadoutParts(target, VESSEL_BRIDGE_PITCH_DEG)),
}
: { offset: false, yawDeg: 0, readout: '' };
}
/** Live Signals' tone for a provider's signal row. */
const SUBJECT_SIGNAL_TONES = Object.freeze({
warning: 'warning',
alert: 'warning',
});
/**
* Present a provider subject's HUD: its view model (cockpitSubjectHudView)
* in the generic readouts, the compass at the camera's heading, the route
* card, and its signals in Live Signals. A HUD view that is null, a `hud()`
* that throws, or a view whose reading throws keeps the last one. Contact
* navigation stays with aircraft, so the Contact card is withdrawn.
*/
function updateSubjectHud(info, nowMs, forceContext) {
const provider = this.subjectProvider;
this.lastSubjectInfo = info;
const frame = this.lastSubjectFrame;
const look = {
yawDeg: this.lookTarget?.yawDeg ?? 0,
pitchDeg: this.lookTarget?.pitchDeg ?? 0,
offset:
this.looksAround && lookIsOffset(this.lookTarget, this.lookRestPitch),
};
const raw = frame
? this.callSubject(
provider,
'hud',
[frame, Object.freeze({ ...this.subjectContext(), look })],
null,
)
: null;
if (raw != null)
this.subjectHud = cockpitSubjectHudView(raw) ?? this.subjectHud;
const hud = this.subjectHud ?? cockpitSubjectHudView(null);
const view = this.instruments;
view.kind = 'subject';
view.trackSource = null;
view.kicker = hud.kicker || provider.labels.kicker;
view.callsign = hud.title || info.name || '';
// While the floor under a subject with no height is acquired
// (cockpitCamera.js), the meta line says so in place of the provider's.
const acquiring = this.surfaceAcquiring === true;
view.meta.text = acquiring ? t('ACQUIRING SURFACE') : hud.meta.text;
view.meta.tone = acquiring ? 'warning' : hud.meta.tone;
view.meta.emergency = !acquiring && hud.meta.tone === 'alert';
const speed = hud.speed?.value ?? null;
view.speed = hud.speed
? {
text: speed === null ? '---' : formatNumber(Math.round(speed)),
value: speed === null ? null : Math.round(speed),
immediate: forceContext,
}
: null;
view.speedUnit = hud.speed?.unit ?? '';
view.speedTag = hud.speed?.tag ?? '';
view.speedTone = hud.speed?.tone ?? 'normal';
view.speedRim.unavailable = true;
view.altitude = null;
view.altitudeRim.unavailable = true;
view.course = null;
const heading = normalizeHeading(this.heading ?? info.track ?? 0);
view.heading = {
text: formatHeadingReadout(heading),
value: heading,
immediate: forceContext,
};
const viewHeading = normalizeHeading(
heading + (provider.look ? (this.lookView?.yawDeg ?? 0) : 0),
);
view.compass = scrollingCompassDivisions(viewHeading).map((division) => ({
slot: division.slot,
heading: division.heading,
active: division.nearest,
label: compassPointLabel(formatCompassDivision(division.heading)),
}));
view.compassMarkers = {
prograde: compassMarkerSlot(heading, viewHeading),
retrograde: compassMarkerSlot(heading + 180, viewHeading),
};
view.clock = new Date().toISOString().slice(11, 19) + 'Z';
view.position = `${formatCockpitCoordinate(info.latitude, 'N', 'S')} · ${formatCockpitCoordinate(info.longitude, 'E', 'W')}`;
view.readouts = hud.readouts;
view.sources = hud.sources;
view.banner = hud.banner;
view.veil = hud.veil;
view.progress = hud.progress;
view.lookEnabled = Boolean(provider.look);
view.layer = provider.layerId;
this.presentLook();
this.publishInstrumentsView();
const route = this.routeView;
route.kind = 'subject';
route.title = hud.route?.title ?? '';
route.from = hud.route?.from ?? '';
route.to = hud.route?.to ?? '';
route.status = hud.route?.status ?? '';
route.visible = Boolean(hud.route);
// No destination arrow; clearing also publishes the card.
this.clearPredictiveRoute();
if (
forceContext ||
cockpitUiUpdateDue(
nowMs,
this.lastContextUpdateMs,
COCKPIT_CONTEXT_UPDATE_MS,
)
) {
this.lastContextUpdateMs = nowMs;
this.updateLocalPosition(info);
this.maybeRefreshRegionalBrief(info);
this.showContextCard(false);
const keys = new Set();
for (const signal of hud.signals) {
const key = `subject:${signal.id}`;
keys.add(key);
this.pushCockpitSignal(
key,
SUBJECT_SIGNAL_TONES[signal.tone] ?? 'info',
signal.title,
signal.detail || signal.title,
);
}
for (const key of this.subjectSignalKeys ?? [])
if (!keys.has(key)) this.dropCockpitSignal(key);
this.subjectSignalKeys = keys;
}
}
export function updateHud(
info,
nowMs = performance.now(),
forceContext = false,
) {
if (this.subjectProvider && info?.generic === true) {
updateSubjectHud.call(this, info, nowMs, forceContext);
return;
}
if (info?.kind === 'vessel') {
updateVesselHud.call(this, info, nowMs, forceContext);
return;
+4 -1
View File
@@ -1050,7 +1050,7 @@ test('a place that lands after the exit is dropped', async (t) => {
assert.equal(store.orbital, null, 'no HUD comes back for a stale answer');
});
test('a tracked aircraft takes entry before a tracked satellite', async (t) => {
test('an aircraft and a satellite first seen in one sync: the aircraft takes entry, by the fixed order', async (t) => {
const aircraftInfo = {
icao24: 'abc123',
callsign: 'TEST1',
@@ -1063,6 +1063,9 @@ test('a tracked aircraft takes entry before a tracked satellite', async (t) => {
};
const { cockpit, viewer, aircraft, store } = fixture(t, { aircraftInfo });
followEntity(viewer, aircraft);
// The satellite and the aircraft are both new to this sync; the fixed order
// decides between subjects first seen together. Selected one after the
// other, the later one takes entry (cockpitEntryGate.test.mjs).
cockpit.syncEntry();
assert.equal(store.presence.entryKind, 'aircraft');
});
+9 -5
View File
@@ -184,11 +184,15 @@ const COCKPIT_ENTRY_FACES = Object.freeze({
});
/**
* The entry's glyph and localized label for the subject it would ride.
* @param {'aircraft'|'vessel'|'satellite'|null|undefined} kind
* The entry's glyph and localized label for the subject it would ride. An
* application provider's subject brings its own face, already in the page's
* language (`presence.entryFace`).
* @param {string|null|undefined} kind
* @param {{icon: string, label: string}|null} [face]
* @returns {{icon: string, label: string}}
*/
export function cockpitEntryFace(kind) {
const face = COCKPIT_ENTRY_FACES[kind] ?? COCKPIT_ENTRY_FACES.aircraft;
return { icon: face.icon, label: t(face.label) };
export function cockpitEntryFace(kind, face = null) {
if (face?.icon && face?.label) return { icon: face.icon, label: face.label };
const known = COCKPIT_ENTRY_FACES[kind] ?? COCKPIT_ENTRY_FACES.aircraft;
return { icon: known.icon, label: t(known.label) };
}
File diff suppressed because it is too large. Load diff
+390 -39
View File
@@ -12,6 +12,10 @@ import {
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
@@ -49,15 +53,183 @@ export function readSatelliteInfo() {
return this.services.satellitesLayer?.getCockpitSubject?.() || null;
}
/**
* What an application subject provider would have entry ride now, or null.
* @param {object} provider A provider from cockpitSubjectProviders.
* @returns {{id: string, name: string, face: object|null}|null}
*/
export function readSubjectCandidate(provider) {
return cockpitSubjectCandidate(
this.callSubject(provider, 'candidate', [], null),
);
}
/**
* What a provider's `read` and `hud` receive besides the frame: the shared
* ground floor at a point (metres, or null), a way to warm its cells, and the
* floor service's lift.
*/
export function subjectContext() {
this._subjectContext ??= Object.freeze({
groundHeightAt: (latitude, longitude) => {
const height = this.services.cachedGroundFloor?.(latitude, longitude);
return Number.isFinite(height) ? height : null;
},
warmGround: (points) => {
this.services.warmGroundFloor?.(points);
},
liftM: Number.isFinite(this.services.GROUND_FLOOR_LIFT_M)
? this.services.GROUND_FLOOR_LIFT_M
: 0,
});
return this._subjectContext;
}
/**
* The ridden provider subject as the camera and HUD read it: the frame's
* place and motion, named like the built-in kinds' info.
* @param {object} frame From cockpitSubjectFrame.
*/
export function subjectInfo(frame) {
return {
kind: this.subjectProvider?.kind ?? null,
generic: true,
layerId: this.subjectProvider?.layerId ?? null,
id: frame.id,
name: frame.name,
latitude: frame.latitude,
longitude: frame.longitude,
track: frame.headingDeg,
motionCourse: frame.courseDeg,
velocityMps: frame.speedMps ?? 0,
stale: frame.stale,
groundClamp: frame.groundClamp,
anchor: frame.anchor,
onGround: false,
};
}
/** The built-in kinds' fixed entry order. */
const BUILT_IN_ENTRY_ORDER = Object.freeze({
aircraft: 0,
satellite: 1,
vessel: 2,
});
/**
* Every subject entry could ride now, in entry order: a tracked aircraft,
* the tracked satellite, the selected vessel and each provider's candidate.
* The built-in kinds keep their fixed order (aircraft, satellite, vessel),
* whenever each was selected. A provider's candidate goes ahead of them only
* when it was selected after every built-in one present: a train picked
* after an aircraft was tracked takes entry, an aircraft tracked after it
* takes it back. Providers' candidates are ordered most recently selected
* first, then by priority. A candidate's time is when this controller first
* saw it (it looks on its entry cadence and on tracking changes), or saw it
* selected again: another subject of a built-in kind, a provider candidate
* whose `selectedAt` changes, or one without a `selectedAt` whose id changes.
* A new id under the same `selectedAt` is the same selection, as when a
* train's selection moves to another feed's copy of it. One
* first seen together with a built-in candidate comes after it. With no
* provider, entry is the built-in order alone. Each carries `allowed()`, its
* kind's entry gate.
* @param {number} [nowMs]
* @returns {Array<{kind: string, id: string, seenAtMs: number, order: number,
* allowed: () => boolean, provider?: object, candidate?: object}>}
*/
export function entryCandidates(nowMs = performance.now()) {
const seen = (this._entrySeen ??= new Map());
const list = [];
const note = (kind, id, entry, selectedAt = null) => {
const last = seen.get(kind);
// A provider's token says when its subject was selected: a new id under
// the same token (a train handed to another feed's copy of it) is not a
// new selection. Without a token, a new id is.
if (
!last ||
last.selectedAt !== selectedAt ||
(selectedAt === null && last.id !== id)
)
seen.set(kind, { id, selectedAt, atMs: nowMs });
else if (last.id !== id) seen.set(kind, { ...last, id });
list.push({ kind, id, seenAtMs: seen.get(kind).atMs, ...entry });
};
const aircraft = this.readAircraftInfo();
const followed = aircraft ? followedOf(this.viewer) : null;
if (aircraft && followed?.entity?.position)
note(
'aircraft',
String(followed.key || aircraft.icao24 || aircraft.id || 'aircraft'),
{
order: BUILT_IN_ENTRY_ORDER.aircraft,
allowed: () => this.isEntryAllowed(),
},
);
const satellite = this.readSatelliteInfo();
if (satellite)
note('satellite', String(satellite.noradId ?? satellite.id ?? ''), {
order: BUILT_IN_ENTRY_ORDER.satellite,
allowed: () => this.isOrbitEntryAllowed(),
});
const vessel = this.readVesselInfo();
if (vessel)
note('vessel', String(vessel.id ?? ''), {
order: BUILT_IN_ENTRY_ORDER.vessel,
allowed: () => this.isBridgeEntryAllowed(),
});
this.subjectProviders.forEach((provider, index) => {
const candidate = this.readSubjectCandidate(provider);
if (candidate)
note(
provider.kind,
candidate.id,
{
order: 3 + index,
provider,
candidate,
allowed: () => this.isSubjectEntryAllowed(provider, candidate),
},
candidate.selectedAt,
);
});
// A subject gone and back counts as selected again.
for (const kind of [...seen.keys()])
if (!list.some((entry) => entry.kind === kind)) seen.delete(kind);
const builtIns = list
.filter((entry) => !entry.provider)
.sort((a, b) => a.order - b.order);
const provided = list
.filter((entry) => entry.provider)
.sort((a, b) => b.seenAtMs - a.seenAtMs || a.order - b.order);
const builtInSeenAtMs = Math.max(
-Infinity,
...builtIns.map((entry) => entry.seenAtMs),
);
const later = provided.filter((entry) => entry.seenAtMs > builtInSeenAtMs);
const earlier = provided.filter((entry) => entry.seenAtMs <= builtInSeenAtMs);
return [...later, ...builtIns, ...earlier];
}
/**
* The subject entry would ride: the first in entry order (entryCandidates).
* It decides alone, so when its own gate is shut entry is unavailable rather
* than taken by the next one.
* @returns {object|null} An entry of entryCandidates, or null.
*/
export function resolveEntry(nowMs = performance.now()) {
return this.entryCandidates(nowMs)[0] ?? null;
}
/**
* The layer the active view rides: Live AIS Vessels on a bridge, Satellites
* in orbit, else the aircraft's own layer. It is read from the followed
* aircraft's key once the layer has dropped its tracking, so a layer turned
* off still names itself.
* @returns {'flights'|'military'|'ais-live-vessels'|'satellites'|null}
* in orbit, a provider's own layer, else the aircraft's own layer. It is read
* from the followed aircraft's key once the layer has dropped its tracking,
* so a layer turned off still names itself.
* @returns {string|null}
*/
export function readSubjectLayerId() {
if (!this.active) return null;
if (this.subjectProvider) return this.subjectProvider.layerId;
if (this.subjectKind === 'vessel') return 'ais-live-vessels';
if (this.subjectKind === 'satellite') return 'satellites';
const layerId = this.readAircraftInfo()?.layerId;
@@ -67,24 +239,20 @@ export function readSubjectLayerId() {
}
/**
* The subject entry would take: a followed aircraft first, then the
* tracked satellite, else the selected vessel. Vessels are never followed
* through the camera's follow, so an aircraft and a vessel cannot be live
* through the same owner.
* @returns {'aircraft'|'satellite'|'vessel'|null}
* The kind entry would take, the first in entry order's (resolveEntry): a
* followed aircraft, the tracked satellite, the selected vessel or a
* provider's candidate.
* @returns {string|null}
*/
export function resolveEntryKind() {
if (this.readAircraftInfo() && followedOf(this.viewer)?.entity?.position)
return 'aircraft';
if (this.readSatelliteInfo()) return 'satellite';
return this.readVesselInfo() ? 'vessel' : null;
return this.resolveEntry()?.kind ?? null;
}
export function dispatchCockpitModeChanged(active, info = null) {
const subjectId = active
? String(
info?.icao24 ||
(info?.kind === 'vessel' ? info.id : '') ||
(info?.kind === 'vessel' || info?.generic === true ? info.id : '') ||
info?.noradId ||
'',
)
@@ -93,9 +261,13 @@ export function dispatchCockpitModeChanged(active, info = null) {
: null;
const layerId =
active &&
['flights', 'military', 'ais-live-vessels', 'satellites'].includes(
(['flights', 'military', 'ais-live-vessels', 'satellites'].includes(
info?.layerId,
)
) ||
(info?.generic === true &&
this.subjectProviders.some(
(provider) => provider.layerId === info.layerId,
)))
? info.layerId
: null;
window.dispatchEvent(
@@ -144,40 +316,60 @@ export function syncTr3bToggle(info) {
this.publishPresenceView();
}
/**
* Word the ridden provider subject's labels and Look ahead button again,
* after a change of the page's language: a provider may give them as
* functions (cockpitSubjectProviders).
*/
export function refreshSubjectWords() {
const provider = this.subjectProvider;
if (!this.active || !provider) return;
this.presence.subjectLabels = { ...provider.labels };
const look = provider.look;
this.presence.subjectLook = look ? { aheadLabel: look.aheadLabel } : null;
this.publishPresenceView();
}
export function syncEntry() {
if (this.destroyed) return false;
if (this.active) return;
const info = this.readAircraftInfo();
const trackedContact = !!(info && followedOf(this.viewer)?.entity?.position);
this.syncTr3bToggle(trackedContact ? info : null);
const orbitContact = !trackedContact && !!this.readSatelliteInfo();
const bridgeContact =
!trackedContact && !orbitContact && !!this.readVesselInfo();
let entryKind = null;
if (trackedContact) entryKind = this.isEntryAllowed() ? 'aircraft' : null;
else if (orbitContact)
entryKind = this.isOrbitEntryAllowed() ? 'satellite' : null;
else if (bridgeContact)
entryKind = this.isBridgeEntryAllowed() ? 'vessel' : null;
const candidates = this.entryCandidates(performance.now());
const tracked = candidates.some(({ kind }) => kind === 'aircraft');
this.syncTr3bToggle(tracked ? this.readAircraftInfo() : null);
// The first in entry order decides alone (resolveEntry).
const chosen = candidates[0] ?? null;
const entryKind = chosen?.allowed() ? chosen.kind : null;
const face =
entryKind && chosen.provider
? (chosen.candidate.face ?? chosen.provider.entryFace)
: null;
const available = entryKind !== null;
// Change-only publishes: this runs on a preUpdate cadence, and a fresh
// presence every frame would re-render the views even when nothing
// changed. (perf item 9)
if (
this.presence.entryAvailable === available &&
this.presence.entryKind === entryKind
this.presence.entryKind === entryKind &&
this.presence.entryFace?.icon === face?.icon &&
this.presence.entryFace?.label === face?.label
)
return;
this.presence.entryAvailable = available;
this.presence.entryKind = entryKind;
this.presence.entryFace = face && { icon: face.icon, label: face.label };
this.publishPresenceView();
}
export function navigateContext(direction, options = {}) {
if (this.destroyed) return false;
// Contact navigation moves between aircraft; a bridge does not jump ship
// and an orbital view stays with its satellite.
if (this.subjectKind === 'vessel' || this.subjectKind === 'satellite')
// Contact navigation moves between aircraft; a bridge does not jump ship,
// an orbital view stays with its satellite and a provider's view with its
// subject.
if (
this.subjectKind === 'vessel' ||
this.subjectKind === 'satellite' ||
this.subjectProvider
)
return false;
const method = direction < 0 ? 'navigatePrevious' : 'navigateNext';
const wasActive = this.active;
@@ -197,10 +389,14 @@ export function navigateContext(direction, options = {}) {
}
export function _adoptTrackedEntity(nowMs, suppliedInfo = null) {
// An aircraft followed from the bridge or from orbit ends that view (see
// the vessel and orbital camera updates); it is never adopted as its
// 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')
if (
this.subjectKind === 'vessel' ||
this.subjectKind === 'satellite' ||
this.subjectProvider
)
return false;
const nextFollowed = followedOf(this.viewer);
const nextEntity = nextFollowed?.entity;
@@ -233,16 +429,154 @@ export function _adoptTrackedEntity(nowMs, suppliedInfo = null) {
}
/**
* Enter first person on a tracked aircraft or, with none tracked, the
* tracked satellite's orbital view or the selected vessel's bridge.
* @param {{kind?: 'aircraft'|'satellite'|'vessel'|null}} [options] Restrict
* entry to one subject kind; voice entry is aircraft-only.
* Enter a provider's view on its candidate: hold it, read a first frame, then
* take the camera as the built-in views do. Entry fails when the gate is shut,
* the hold answers anything but `true` or no frame comes; past the gate, a
* failed entry releases the subject, since the hold may have taken it.
* @param {object} provider From cockpitSubjectProviders.
* @returns {boolean}
*/
function enterSubject(provider) {
const candidate = this.readSubjectCandidate(provider);
if (!candidate || !this.isSubjectEntryAllowed(provider, candidate))
return false;
const failed = {};
const release = () =>
this.callSubject(provider, 'release', [candidate.id, { restore: false }]);
// An asynchronous hold may land after it was refused: it is released
// again once it settles, unless this subject is being ridden by then.
const releaseLate = () => {
if (
this.active &&
this.subjectProvider === provider &&
this.subjectId === candidate.id
)
return;
release();
};
const held = this.callSubject(
provider,
'hold',
[candidate.id],
failed,
releaseLate,
);
if (held !== true) {
// `false` refuses entry; a hold that threw, returned a promise or
// answered anything else (warned of once) may still have taken the
// subject. Each is released.
if (held !== false && held !== failed)
this.callSubject.warnOnce(
provider,
'hold',
'must return true or false; entry refused',
held,
);
release();
return false;
}
const frame = cockpitSubjectFrame(
this.callSubject(
provider,
'read',
[performance.now(), this.subjectContext()],
null,
),
candidate.id,
);
if (!frame) {
this.callSubject(provider, 'release', [candidate.id, { restore: false }]);
return false;
}
this.entryFocusOrigin =
document.activeElement instanceof HTMLElement
? document.activeElement
: null;
this.onCameraTakeover?.();
cameraOf(this.viewer).cancelFlight();
this.subjectKind = provider.kind;
this.subjectProvider = provider;
this.subjectId = candidate.id;
this.lastSubjectFrame = frame;
this.subjectHud = null;
this.subjectSignalKeys = new Set();
this.vesselWaterline = null;
this.vesselFix = null;
this.trackedEntity = null;
this.heading = normalizeHeading(
frame.headingDeg ?? cameraHeadingDeg(cameraOf(this.viewer).pose()),
);
this.lastFrameMs = performance.now();
this.lastCameraUpdateMs = 0;
this.lastHudUpdateMs = 0;
this.lastContextUpdateMs = 0;
this.contextNavigationDeadlineMs = 0;
this.lastGroundProbeMs = 0;
this.surfaceWaitStartedMs = 0;
this.surfaceAcquiring = false;
this.surfaceFallback = false;
this.cockpitAnchorValid = false;
this.subjectHeightM = null;
this.lookRestPitchDeg = provider.look?.restPitchDeg ?? null;
this.resetLook({ immediate: true });
this.active = true;
this.services.holdContinuousRender('cockpit');
stopFollowing(this.viewer);
this.releaseCameraInput?.();
this.releaseCameraInput = inputFor(this.viewer).suspendCamera('cockpit');
document.body.classList.add('cockpit-mode', 'cockpit-subject');
this._tr3bSignature = null;
Object.assign(this.presence, {
active: true,
entryAvailable: false,
entryKind: null,
entryFace: null,
subjectKind: provider.kind,
subjectGeneric: true,
subjectLabels: { ...provider.labels },
subjectLook: provider.look
? { aheadLabel: provider.look.aheadLabel }
: null,
tr3b: null,
});
this.publishPresenceView();
this.publishRadar(null);
this.signalItems = [];
this.signalSignatures.clear();
this.showBriefPage(0);
this.startBriefRotation();
this.pushCockpitSignal('track', 'track', t('TRACK ACQUIRED'), frame.name);
const info = this.subjectInfo(frame);
this.updateHud(info, performance.now(), true);
this.setVisionMode(this.getInitialVisionMode());
this.scheduleContextLayout();
Promise.resolve().then(() => {
if (this.active && !this.destroyed)
this.mapViewButton?.focus({ preventScroll: true });
});
this.onEntered?.();
this.onRide?.(provider.layerId);
this.dispatchCockpitModeChanged(true, info);
return true;
}
/**
* Enter first person on the first subject in entry order (resolveEntry): a
* tracked aircraft, the tracked satellite's orbital view, the selected
* vessel's bridge or an application provider's subject.
* @param {{kind?: string|null}} [options] Restrict entry to one subject kind;
* voice entry is aircraft-only.
* @returns {boolean} True when the view was entered.
*/
export function enter({ kind = null } = {}) {
if (this.destroyed) return false;
if (this.active) return false;
const subjectKind = kind ?? this.resolveEntryKind() ?? 'aircraft';
const provider = this.subjectProviders.find(
(entry) => entry.kind === subjectKind,
);
if (provider) return enterSubject.call(this, provider);
if (!['aircraft', 'satellite', 'vessel'].includes(subjectKind)) return false;
const vessel = subjectKind === 'vessel';
const satellite = subjectKind === 'satellite';
const allowed = vessel
@@ -395,11 +729,17 @@ 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;
@@ -424,6 +764,7 @@ export function exit({ restoreTracking = true } = {}) {
'cockpit-mode',
'cockpit-bridge',
'cockpit-orbit',
'cockpit-subject',
);
// The camera's own field of view returns before any follow resumes.
this.endOrbital();
@@ -431,6 +772,9 @@ export function exit({ restoreTracking = true } = {}) {
this.publishUtilityLayout(null);
this.presence.active = false;
this.presence.subjectKind = null;
this.presence.subjectGeneric = false;
this.presence.subjectLabels = null;
this.presence.subjectLook = null;
this.publishPresenceView();
this.routeView.visible = false;
this.clearPredictiveRoute();
@@ -446,6 +790,13 @@ export function exit({ restoreTracking = true } = {}) {
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 && present()) {
resumeFollowing(this.viewer, followed);
+12
View File
@@ -51,6 +51,8 @@ export class ContextControls {
this._contextRestoreState = null;
this._contextLayerReactionPromises = new Set();
this._preservePanelStateDuringLayerClear = false;
/** Layers Context isolation is switching off right now. */
this._isolatingLayerIds = new Set();
this._userFacingContextNotificationTokens = new Set();
this._clearSelectedLayersPromise = null;
this._clearSelectedLayersManagerPromise = null;
@@ -59,6 +61,16 @@ export class ContextControls {
showToast(...args) {
if (!this.destroyed) this.actions.showToast(...args);
}
/**
* Whether Context isolation is switching this layer off right now: it is
* suspended, and leaving the mode restores it. A switch-off by the user,
* inside the mode or out of it, is not.
* @param {string} layerId Layer id.
* @returns {boolean}
*/
suspendsLayer(layerId) {
return this._isolatingLayerIds.has(layerId);
}
setClearBusy(...args) {
if (!this.destroyed) this.actions.setClearBusy(...args);
}
+53
View File
@@ -153,3 +153,56 @@ test('a rejected tracked reaction settles without an unhandled rejection', async
await controls._waitForContextLayerSettlement();
assert.equal(controls._contextLayerReactionPromises.size, 0);
});
test('only a layer Context isolation is switching off is suspended', async (t) => {
const { controls } = fixture(t);
const enabled = new Set(['cctv']);
// What the CCTV panel is told at each visibility change of its layer.
const seen = [];
controls._dataManager = {
layers: new Map([['cctv', {}]]),
getEnabledLayerIds: () => [...enabled],
getLayerParams: () => null,
setLayerParams() {},
isEnabled: (layerId) => enabled.has(layerId),
isEffectivelyEnabled: (layerId) => enabled.has(layerId),
async setEnabled(layerId, next) {
// The layer tells its panel it is off while it is being disabled.
if (next) enabled.add(layerId);
else enabled.delete(layerId);
seen.push([layerId, next, controls.suspendsLayer(layerId)]);
return true;
},
async restoreEnabledLayerIds(layerIds) {
for (const layerId of layerIds) await this.setEnabled(layerId, true);
},
};
assert.equal(controls.suspendsLayer('cctv'), false);
controls._captureContextSessionSnapshot();
await controls._clearLayersOutsideContextMode('flights');
assert.deepEqual(seen, [['cctv', false, true]]);
assert.equal(controls.suspendsLayer('cctv'), false, 'only while isolating');
// Inside the mode the user turns CCTV back on, then off: their own.
await controls._dataManager.setEnabled('cctv', true);
await controls._dataManager.setEnabled('cctv', false);
assert.deepEqual(seen.at(-1), ['cctv', false, false]);
await controls._restoreContextSession();
assert.equal(enabled.has('cctv'), true);
// A switch-off after the mode is left is the user's own too.
await controls._dataManager.setEnabled('cctv', false);
assert.deepEqual(seen.at(-1), ['cctv', false, false]);
});
test('a failed isolation leaves no layer suspended', async (t) => {
const { controls } = fixture(t);
controls._dataManager = {
layers: new Map([['cctv', {}]]),
isEffectivelyEnabled: () => true,
isEnabled: () => true,
setEnabled: async () => {
throw new Error('disable failed');
},
};
await assert.rejects(controls._clearLayersOutsideContextMode('flights'));
assert.equal(controls.suspendsLayer('cctv'), false);
});
+27 -17
View File
@@ -240,25 +240,35 @@ export async function _clearLayersOutsideContextMode(
) {
const allowed = contextAllowedLayerIds(mode);
const pending = [];
for (const [layerId] of this._dataManager.layers || []) {
// Effective visibility: a disallowed layer still mid-ENABLING must be
// isolated too, or it settles ON inside the exclusive mode.
if (
!allowed.has(layerId) &&
this._dataManager.isEffectivelyEnabled(layerId)
) {
pending.push({
layerId,
transition: this._dataManager.setEnabled(layerId, false, {
notificationToken,
...(signal ? { signal } : {}),
}),
});
// Panels read this while their layer goes off (suspendsLayer): a layer
// isolation switches off is suspended, not switched off by the user.
const isolating = [];
let results;
try {
for (const [layerId] of this._dataManager.layers || []) {
// Effective visibility: a disallowed layer still mid-ENABLING must be
// isolated too, or it settles ON inside the exclusive mode.
if (
!allowed.has(layerId) &&
this._dataManager.isEffectivelyEnabled(layerId)
) {
if (!this._isolatingLayerIds.has(layerId)) {
this._isolatingLayerIds.add(layerId);
isolating.push(layerId);
}
pending.push({
layerId,
transition: this._dataManager.setEnabled(layerId, false, {
notificationToken,
...(signal ? { signal } : {}),
}),
});
}
}
results = await Promise.all(pending.map(({ transition }) => transition));
} finally {
for (const layerId of isolating) this._isolatingLayerIds.delete(layerId);
}
const results = await Promise.all(
pending.map(({ transition }) => transition),
);
const failed = pending
.filter(
({ layerId }, index) =>
+173
View File
@@ -0,0 +1,173 @@
// The scene chrome renders the render failure notice and its actions.
import '../testSupport/registerDom.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import { createApp, nextTick } from 'vue';
import { createPinia } from 'pinia';
import { useStatusStore } from './stores/status.js';
import SceneChromeView from './views/SceneChromeView.vue';
function mount(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());
return useStatusStore(pinia);
}
const notice = () => document.getElementById('render-failure');
const buttons = () =>
[...(notice()?.querySelectorAll('button') ?? [])].map((button) =>
button.textContent.trim(),
);
test('a render failure shows an alert dialog that moves focus to Retry', async (t) => {
const store = mount(t);
assert.equal(notice(), null, 'no notice while the globe draws');
const calls = [];
store.publishRenderFailure({
reason: 'render-error',
detail: 'Expected width to be greater than 0',
retry: () => calls.push('retry'),
reset: () => calls.push('reset'),
});
await nextTick();
await nextTick();
const element = notice();
assert.equal(element.getAttribute('role'), 'alertdialog');
assert.equal(
document.getElementById(element.getAttribute('aria-labelledby'))
.textContent,
'The globe stopped drawing',
);
assert.match(
document.getElementById(element.getAttribute('aria-describedby'))
.textContent,
/^Rendering stopped after an error\./,
);
assert.equal(
element.querySelector('.render-failure-detail').textContent,
'Expected width to be greater than 0',
);
assert.deepEqual(buttons(), ['Retry', 'Reset view']);
assert.equal(document.activeElement?.textContent.trim(), 'Retry');
for (const button of element.querySelectorAll('button')) button.click();
assert.deepEqual(calls, ['retry', 'reset']);
store.publishRenderFailure(null);
await nextTick();
assert.equal(notice(), null);
});
test('a lost context offers Reload, and a panel that cannot reload offers nothing', async (t) => {
const store = mount(t);
store.publishRenderFailure({
reason: 'context-lost',
detail: '',
retry: () => {},
reset: () => {},
});
await nextTick();
assert.match(
document.getElementById('render-failure-message').textContent,
/3D graphics/,
);
assert.equal(notice().querySelector('.render-failure-detail'), null);
assert.deepEqual(buttons(), ['Reload', 'Reset view']);
store.publishRenderFailure({
reason: 'context-lost',
detail: '',
retry: null,
reset: null,
});
await nextTick();
assert.deepEqual(buttons(), []);
assert.equal(notice().querySelector('.render-failure-hint'), null);
});
const failure = () => ({
reason: 'render-error',
detail: '',
retry: () => {},
reset: null,
});
const settle = async () => {
await nextTick();
await nextTick();
};
test('focus goes back where it was when the globe draws again', async (t) => {
const store = mount(t);
const search = document.body.appendChild(document.createElement('input'));
search.focus();
store.publishRenderFailure(failure());
await settle();
assert.equal(document.activeElement?.textContent.trim(), 'Retry');
store.publishRenderFailure(null);
await settle();
assert.equal(document.activeElement, search);
});
// The globe's canvas, as CesiumWidget builds it inside the container.
const addGlobeCanvas = () => {
const widget = document.createElement('div');
widget.className = 'cesium-widget';
document.getElementById('cesiumContainer').appendChild(widget);
return widget.appendChild(document.createElement('canvas'));
};
test('focus goes to the globe canvas when the element it came from is gone', async (t) => {
const store = mount(t);
const canvas = addGlobeCanvas();
const search = document.body.appendChild(document.createElement('input'));
search.focus();
store.publishRenderFailure(failure());
await settle();
search.remove();
store.publishRenderFailure(null);
await settle();
// The map's keys, Enter to finish a drawing among them, read the canvas
// as the map (src/annotations/drawTool.js).
assert.equal(document.activeElement, canvas);
assert.equal(canvas.getAttribute('tabindex'), '-1');
canvas.blur();
assert.equal(canvas.hasAttribute('tabindex'), false, 'only this once');
});
test('focus goes to the globe canvas when the element it came from cannot take it', async (t) => {
const store = mount(t);
const canvas = addGlobeCanvas();
const button = document.body.appendChild(document.createElement('button'));
button.focus();
store.publishRenderFailure(failure());
await settle();
button.disabled = true;
store.publishRenderFailure(null);
await settle();
assert.equal(document.activeElement, canvas);
// A press on the globe leaves focus on the page again, as Cesium has it.
canvas.dispatchEvent(new Event('pointerdown'));
assert.equal(document.activeElement, document.body);
assert.equal(canvas.hasAttribute('tabindex'), false);
});
test('focus the user moved while the notice was up stays put', async (t) => {
const store = mount(t);
store.publishRenderFailure(failure());
await settle();
const chat = document.body.appendChild(document.createElement('textarea'));
chat.focus();
store.publishRenderFailure(null);
await settle();
assert.equal(document.activeElement, chat);
});
test('the globe drawing from the start leaves focus alone', async (t) => {
mount(t);
await settle();
assert.equal(document.activeElement, document.body);
assert.equal(
document.getElementById('cesiumContainer').hasAttribute('tabindex'),
false,
);
});
+4
View File
@@ -883,6 +883,10 @@ export class ShellFacade {
return this._contextControls?._preservePanelStateDuringLayerClear ?? false;
}
_contextSuspendsLayer(layerId) {
return this._contextControls?.suspendsLayer(layerId) ?? false;
}
_runUserFacingContextAction(...args) {
return this._contextControls?._runUserFacingContextAction(...args);
}
+17 -1
View File
@@ -7,7 +7,9 @@ import { markRaw, shallowRef } from 'vue';
* road network chip, CctvControls the camera grid chip; the toast shows
* what any owner's createToast() (src/ui/toast.js) publishes, and the title
* bar the FPS readout createFrameRateMonitor() publishes. Each label keeps its
* last text while hidden, so the next change flaps from what was shown.
* last text while hidden, so the next change flaps from what was shown. The
* render failure notice is what installRenderFailureNotice()
* (src/render/cesium/renderFailure.js) publishes while the globe cannot draw.
*/
export const useStatusStore = defineStore('gev-status', () => {
/**
@@ -32,6 +34,13 @@ export const useStatusStore = defineStore('gev-status', () => {
*/
const fps = shallowRef(null);
/**
* The globe's render failure, `{reason, detail, retry, reset}`; null while
* the globe draws. `reason` is 'render-error' or 'context-lost', and `retry`
* and `reset` are null where that action is not offered.
*/
const renderFailure = shallowRef(null);
/** @param {?object} next A fresh presentation of the loading status. */
function publishLoading(next) {
loading.value = next && markRaw(next);
@@ -57,6 +66,11 @@ export const useStatusStore = defineStore('gev-status', () => {
fps.value = next && markRaw(next);
}
/** @param {?object} next A fresh presentation of the render failure. */
function publishRenderFailure(next) {
renderFailure.value = next && markRaw(next);
}
return {
fps,
publishFps,
@@ -68,5 +82,7 @@ export const useStatusStore = defineStore('gev-status', () => {
publishTraffic,
cctv,
publishCctv,
renderFailure,
publishRenderFailure,
};
});
+315
View File
@@ -0,0 +1,315 @@
/* An application provider's first-person view
(src/cockpitSubjectProviders.js): a window view with the provider's board,
sources, banner, darkening veil and progress line. Every rule is scoped to
the generic view, so the built-in views keep their own looks. */
#cockpit-hud[data-generic] {
--cockpit-subject-panel: rgba(0, 7, 12, 0.66);
--cockpit-subject-live: var(--cockpit-accent);
--cockpit-subject-estimate: #c9b6ff;
--cockpit-subject-warning: #ffb800;
--cockpit-subject-alert: var(--cockpit-emergency);
--cockpit-subject-progress-band: 46px;
}
#cockpit-hud[data-generic] [data-tone='muted'] {
opacity: 0.62;
}
#cockpit-hud[data-generic] [data-tone='live'] {
color: var(--cockpit-subject-live);
}
#cockpit-hud[data-generic] [data-tone='estimate'] {
color: var(--cockpit-subject-estimate);
}
#cockpit-hud[data-generic] [data-tone='warning'] {
color: var(--cockpit-subject-warning);
}
#cockpit-hud[data-generic] [data-tone='alert'] {
color: var(--cockpit-subject-alert);
}
/* The veil darkens the picture under the HUD; its streaks are lights
passing the window. */
#cockpit-hud[data-generic] .cockpit-veil {
position: absolute;
inset: 0;
background: #000;
pointer-events: none;
transition: opacity 0.25s linear;
}
#cockpit-hud[data-generic] .cockpit-veil.streaks::before {
content: '';
position: absolute;
inset: 34% -40% 46%;
background: repeating-linear-gradient(
90deg,
transparent 0 22%,
rgba(255, 214, 150, 0.16) 23%,
rgba(255, 236, 200, 0.42) 24%,
rgba(255, 214, 150, 0.16) 25%,
transparent 26% 48%
);
filter: blur(3px);
animation: cockpit-veil-streaks 1.4s linear infinite;
}
@keyframes cockpit-veil-streaks {
from {
transform: translateX(0);
}
to {
transform: translateX(-26%);
}
}
@media (prefers-reduced-motion: reduce) {
#cockpit-hud[data-generic] .cockpit-veil.streaks::before {
animation: none;
}
#cockpit-hud[data-generic] .cockpit-veil {
transition: none;
}
}
/* The banner: top centre, below the top line. */
#cockpit-hud[data-generic] .cockpit-banner {
position: absolute;
top: clamp(92px, 13vh, 128px);
left: 50%;
display: flex;
flex-direction: column;
align-items: center;
gap: 2px;
max-width: min(560px, 80vw);
padding: 6px 14px;
border: 1px solid color-mix(in srgb, var(--cockpit-accent) 56%, transparent);
border-radius: 2px;
background: var(--cockpit-subject-panel);
text-align: center;
transform: translateX(-50%);
}
#cockpit-hud[data-generic] .cockpit-banner strong {
font-size: 15px;
letter-spacing: 0.14em;
}
#cockpit-hud[data-generic] .cockpit-banner small {
font-size: 11px;
letter-spacing: 0.08em;
}
/* The board: cards on the left, below the page's left rail and the Intel
HUD's top corner (both stay on in first person), the sources under them. */
#cockpit-hud[data-generic] {
--cockpit-subject-board-top: max(23rem, 41vh);
}
#cockpit-hud[data-generic] .cockpit-board {
position: absolute;
top: var(--cockpit-subject-board-top);
left: clamp(22px, 4vw, 58px);
display: flex;
flex-direction: column;
gap: 8px;
width: min(320px, 30vw);
min-width: 220px;
max-height: calc(100vh - var(--cockpit-subject-board-top) - 11rem);
overflow: hidden;
}
#cockpit-hud[data-generic] .cockpit-board-card {
display: flex;
flex-direction: column;
gap: 2px;
padding: 6px 10px;
border-left: 2px solid
color-mix(in srgb, var(--cockpit-accent) 72%, transparent);
background: var(--cockpit-subject-panel);
}
#cockpit-hud[data-generic] .cockpit-board-card small {
font-size: 10px;
letter-spacing: 0.16em;
opacity: 0.78;
}
#cockpit-hud[data-generic] .cockpit-board-card strong {
font-size: 17px;
letter-spacing: 0.04em;
overflow-wrap: anywhere;
}
#cockpit-hud[data-generic] .cockpit-board-card span {
font-size: 12px;
letter-spacing: 0.06em;
}
#cockpit-hud[data-generic] .cockpit-sources {
display: flex;
flex-direction: column;
gap: 3px;
margin: 0;
padding: 6px 10px;
background: rgba(0, 7, 12, 0.5);
font-size: 10px;
letter-spacing: 0.06em;
}
#cockpit-hud[data-generic] .cockpit-sources div {
display: flex;
gap: 6px;
}
#cockpit-hud[data-generic] .cockpit-sources dt {
flex: none;
min-width: 64px;
opacity: 0.7;
letter-spacing: 0.14em;
}
#cockpit-hud[data-generic] .cockpit-sources dd {
margin: 0;
overflow-wrap: anywhere;
}
/* The speed's tag (live or estimated) sits where a label would. */
#cockpit-hud[data-generic] .cockpit-speed-tag {
font-weight: 700;
}
/* With no speed readout the heading still holds the middle of the row. */
#cockpit-hud[data-generic] .cockpit-heading-value {
grid-column: 2;
}
#cockpit-hud[data-generic] .cockpit-aircraft-meta[data-tone='warning'],
#cockpit-hud[data-generic] .cockpit-aircraft-meta[data-tone='alert'] {
font-weight: 700;
}
/* Look-around: the readout and LOOK AHEAD centred under the style switcher,
in the sky over the forward view; the bottom corners hold the position
readouts. Styled as on a bridge. */
#cockpit-hud[data-generic] .cockpit-look {
position: absolute;
top: calc(clamp(22px, 4vh, 42px) + 70px);
left: 50%;
transform: translateX(-50%);
display: flex;
align-items: center;
gap: 8px;
}
#cockpit-hud[data-generic] .cockpit-look[hidden] {
display: none;
}
#cockpit-hud[data-generic] .cockpit-look-readout {
padding: 2px 6px;
border: 1px solid color-mix(in srgb, var(--cockpit-accent) 46%, transparent);
border-radius: 2px;
background: rgba(0, 7, 12, 0.62);
color: var(--cockpit-accent);
font-family: var(--font-mono);
font-size: 11px;
letter-spacing: 0.12em;
white-space: nowrap;
}
#cockpit-hud[data-generic] .cockpit-look-ahead {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 3px 8px;
border: 1px solid color-mix(in srgb, var(--cockpit-accent) 64%, transparent);
border-radius: 2px;
background: rgba(0, 7, 12, 0.78);
color: #f4fbff;
font: inherit;
font-size: 10px;
letter-spacing: 0.14em;
cursor: pointer;
pointer-events: auto;
}
#cockpit-hud[data-generic] .cockpit-look-ahead:hover {
border-color: var(--cockpit-accent);
}
#cockpit-hud[data-generic] .cockpit-look-ahead:focus-visible {
outline: 2px solid var(--cockpit-accent);
outline-offset: 2px;
}
/* The progress line takes a band along the bottom edge; the readouts that
sit there move up above it. */
#cockpit-hud[data-generic][data-progress]
:is(.cockpit-help, .cockpit-position-readout) {
bottom: calc(
clamp(22px, 4vh, 42px) + var(--cockpit-subject-progress-band) - 14px
);
}
#cockpit-hud[data-generic][data-progress] .cockpit-compass {
bottom: calc(clamp(44px, 7vh, 72px) + var(--cockpit-subject-progress-band));
}
#cockpit-hud[data-generic] .cockpit-progress {
position: absolute;
right: clamp(22px, 4vw, 58px);
bottom: 6px;
left: clamp(22px, 4vw, 58px);
height: var(--cockpit-subject-progress-band);
}
#cockpit-hud[data-generic] .cockpit-progress-line {
position: absolute;
right: 0;
bottom: 8px;
left: 0;
height: 2px;
background: color-mix(in srgb, var(--cockpit-accent) 78%, transparent);
}
#cockpit-hud[data-generic] .cockpit-progress-travelled {
position: absolute;
inset: 0 auto 0 0;
background: rgba(0, 7, 12, 0.72);
}
#cockpit-hud[data-generic] .cockpit-progress-tick {
position: absolute;
bottom: 5px;
width: 2px;
height: 8px;
margin-left: -1px;
background: currentColor;
}
#cockpit-hud[data-generic] .cockpit-progress-tick.labelled {
height: 12px;
}
#cockpit-hud[data-generic] .cockpit-progress-tick.merged {
width: 4px;
margin-left: -2px;
}
#cockpit-hud[data-generic] .cockpit-progress-tick.travelled {
opacity: 0.45;
}
#cockpit-hud[data-generic] .cockpit-progress-label {
position: absolute;
bottom: 20px;
display: flex;
flex-direction: column;
overflow: hidden;
font-size: 10px;
letter-spacing: 0.06em;
line-height: 1.2;
white-space: nowrap;
}
#cockpit-hud[data-generic] .cockpit-progress-label[data-align='center'] {
align-items: center;
text-align: center;
}
#cockpit-hud[data-generic] .cockpit-progress-label[data-align='end'] {
align-items: flex-end;
text-align: end;
}
#cockpit-hud[data-generic] .cockpit-progress-label small {
opacity: 0.82;
}
#cockpit-hud[data-generic] .cockpit-progress-marker {
position: absolute;
bottom: 4px;
width: 10px;
height: 10px;
margin-left: -5px;
border-radius: 50%;
background: var(--cockpit-accent);
box-shadow: 0 0 10px var(--cockpit-accent);
}
#cockpit-hud[data-generic] .cockpit-progress-marker.dwell {
background: transparent;
border: 2px solid var(--cockpit-accent);
}
#cockpit-hud[data-generic] .cockpit-progress-tag {
position: absolute;
right: 0;
bottom: -2px;
font-size: 9px;
letter-spacing: 0.14em;
opacity: 0.7;
}
+70
View File
@@ -405,6 +405,76 @@ html:not([lang='en']) #global-loading-detail {
}
}
/* ── Render failure notice ───────────────────── */
/* Above the loading screen, so a globe that fails while it loads says so too,
and above floating panels such as the Québec camera viewer (2000). */
#render-failure {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 2001;
box-sizing: border-box;
width: min(420px, calc(100vw - 32px));
max-height: calc(100vh - 32px);
overflow-y: auto;
padding: 20px 22px;
background: var(--glass-bg);
border: 1px solid #ff7272;
border-radius: 12px;
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
box-shadow: 0 0 24px rgba(255, 88, 88, 0.18);
color: var(--text-primary);
font-family: var(--font-sans);
font-size: 13px;
line-height: 1.5;
}
#render-failure-title {
margin: 0 0 8px;
font-family: var(--font-mono);
font-size: 12px;
font-weight: 600;
letter-spacing: 2px;
text-transform: uppercase;
color: #ff7272;
}
#render-failure p {
margin: 0 0 10px;
}
#render-failure .render-failure-detail {
font-family: var(--font-mono);
font-size: 11px;
color: var(--text-secondary);
overflow-wrap: anywhere;
}
#render-failure .render-failure-hint {
font-size: 12px;
color: var(--text-secondary);
}
#render-failure .render-failure-actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 14px;
}
#render-failure .gev-action-button {
font-size: 11px;
padding: 8px 14px;
}
@media (pointer: coarse) {
#render-failure .gev-action-button {
min-height: 44px;
}
}
/* ── Toast Notification ──────────────────────── */
#toast {
position: fixed;
+91 -38
View File
@@ -13,6 +13,7 @@ import { useGlobeActionsStore } from '../stores/globeActions.js';
import CockpitBriefing from './panels/CockpitBriefing.vue';
import CockpitContext from './panels/CockpitContext.vue';
import CockpitOrbital from './panels/CockpitOrbital.vue';
import CockpitProgress from './panels/CockpitProgress.vue';
import CockpitRadar from './panels/CockpitRadar.vue';
import CockpitRollingValue from './panels/CockpitRollingValue.vue';
import CockpitUtilityControls from './panels/CockpitUtilityControls.vue';
@@ -29,30 +30,58 @@ const active = computed(() => Boolean(presence.value?.active));
const bridge = computed(() => presence.value?.subjectKind === 'vessel');
// A satellite subject keeps only its orbital HUD over the nadir picture.
const orbital = computed(() => presence.value?.subjectKind === 'satellite');
// An application provider's subject (src/cockpitSubjectProviders.js): a
// window view whose readouts, labels and texts the provider words.
const generic = computed(() => presence.value?.subjectGeneric === true);
const labels = computed(() => presence.value?.subjectLabels ?? null);
const subject = computed(() =>
bridge.value ? 'vessel' : orbital.value ? 'satellite' : 'aircraft',
generic.value
? presence.value.subjectKind
: bridge.value
? 'vessel'
: orbital.value
? 'satellite'
: 'aircraft',
);
const hudLabel = computed(() =>
bridge.value
? t('Ship bridge view')
: orbital.value
? t('Satellite orbital view')
: t('Aircraft cockpit view'),
generic.value
? labels.value?.view
: bridge.value
? t('Ship bridge view')
: orbital.value
? t('Satellite orbital view')
: t('Aircraft cockpit view'),
);
const exitLabel = computed(() =>
bridge.value
? t('Exit bridge view')
: orbital.value
? t('Exit orbital view')
: t('Exit cockpit view'),
generic.value
? labels.value?.exit
: bridge.value
? t('Exit bridge view')
: orbital.value
? t('Exit orbital view')
: t('Exit cockpit view'),
);
const exitText = computed(() =>
bridge.value
? t('EXIT BRIDGE')
: orbital.value
? t('EXIT ORBIT')
: t('EXIT COCKPIT'),
generic.value
? labels.value?.exitText
: bridge.value
? t('EXIT BRIDGE')
: orbital.value
? t('EXIT ORBIT')
: t('EXIT COCKPIT'),
);
// Look-around: on a bridge, or in a provider's view that has it.
const looks = computed(
() => bridge.value || (generic.value && Boolean(presence.value?.subjectLook)),
);
const aheadLabel = computed(() =>
generic.value
? presence.value?.subjectLook?.aheadLabel
: t('Look ahead: turn the bridge view back to the bow'),
);
const veilStyle = computed(() => ({
opacity: String(hud.value.veil?.level ?? 0),
}));
const globe = useGlobeActionsStore();
const { resetBusy } = storeToRefs(globe);
const initialInstruments = createInstrumentState();
@@ -92,7 +121,9 @@ const tickStyle = (tick) =>
<template>
<!-- Aircraft first-person view, a vessel's bridge or a satellite's nadir view. It can be entered from the visible view switcher. -->
<section id="cockpit-hud" :aria-label="hudLabel" :hidden="!active" :data-subject="subject" :style="utilityStyle" v-class-toggle="{ 'signals-active': active, 'context-active': Boolean(presence?.context) }" :data-layer="orbital ? 'satellites' : hud.layer ?? undefined">
<section id="cockpit-hud" :aria-label="hudLabel" :hidden="!active" :data-subject="subject" :data-generic="generic ? '' : undefined" :data-progress="generic && hud.progress ? '' : undefined" :style="utilityStyle" v-class-toggle="{ 'signals-active': active, 'context-active': Boolean(presence?.context) }" :data-layer="orbital ? 'satellites' : hud.layer ?? undefined">
<!-- A provider's view may darken the picture (a veil), the HUD above it. -->
<div v-if="generic && hud.veil" class="cockpit-veil" :class="{ streaks: hud.veil.streaks }" :style="veilStyle" aria-hidden="true"></div>
<!-- In orbit the picture keeps only the nadir reticle, readout and zoom. -->
<CockpitOrbital v-if="orbital" />
<!-- One optical coordinate system: every targeting mark shares this center.
@@ -106,7 +137,7 @@ const tickStyle = (tick) =>
<path d="M0 600H324 M876 600H1200"/>
</g>
</svg>
<svg v-else-if="!orbital" class="cockpit-frame-lines" viewBox="0 0 1200 720" preserveAspectRatio="none" aria-hidden="true" focusable="false">
<svg v-else-if="!orbital && !generic" class="cockpit-frame-lines" viewBox="0 0 1200 720" preserveAspectRatio="none" aria-hidden="true" focusable="false">
<g fill="none" stroke="currentColor">
<path d="M42 106H234L266 126H334 M866 126H934L966 106H1158 M42 114H226L258 136H318 M882 136H942L974 114H1158"/>
<path d="M42 616H226L254 598H320 M880 598H946L974 616H1158 M42 624H238L266 606H330 M870 606H934L962 624H1158"/>
@@ -116,7 +147,7 @@ const tickStyle = (tick) =>
<path class="cockpit-frame-warning" d="M338 645H476L490 654H710L724 645H862" fill="none"/>
<path class="cockpit-frame-meter" d="M372 642H418 M782 642H828"/>
</svg>
<div v-if="!bridge && !orbital" class="cockpit-scan-array" aria-hidden="true">
<div v-if="!bridge && !orbital && !generic" class="cockpit-scan-array" aria-hidden="true">
<svg class="cockpit-target-geometry" viewBox="0 0 600 600" fill="none" focusable="false">
<g class="cockpit-target-hairline">
<circle cx="300" cy="300" r="276"/>
@@ -150,7 +181,7 @@ const tickStyle = (tick) =>
</div>
<div v-if="!orbital" class="cockpit-visor-shell" aria-hidden="true">
<!-- A ship's bridge keeps no roll arc or pitch ladder. -->
<div v-if="!bridge" class="cockpit-roll-arc">
<div v-if="!bridge && !generic" class="cockpit-roll-arc">
<span style="--slot:-3;--depth:3">−30</span>
<span style="--slot:-2;--depth:2">−20</span>
<span style="--slot:-1;--depth:1">−10</span>
@@ -159,10 +190,10 @@ const tickStyle = (tick) =>
<span style="--slot:2;--depth:2">+20</span>
<span style="--slot:3;--depth:3">+30</span>
</div>
<div v-if="!bridge" class="cockpit-pitch-rail cockpit-pitch-rail-left">
<div v-if="!bridge && !generic" class="cockpit-pitch-rail cockpit-pitch-rail-left">
<span>+20</span><span>+10</span><span class="active">00</span><span>−10</span><span>−20</span>
</div>
<div v-if="!bridge" class="cockpit-pitch-rail cockpit-pitch-rail-right">
<div v-if="!bridge && !generic" class="cockpit-pitch-rail cockpit-pitch-rail-right">
<span>+20</span><span>+10</span><span class="active">00</span><span>−10</span><span>−20</span>
</div>
<div class="cockpit-horizon-guide">
@@ -174,10 +205,10 @@ const tickStyle = (tick) =>
</svg>
<small id="cockpit-route-direction-label">{{ direction.label }}</small>
</div>
<div class="cockpit-visor-status cockpit-visor-status-left">{{ bridge ? t('BRIDGE WINDOW · FWD') : t('OPTICAL PLANE · 01') }}</div>
<div class="cockpit-visor-status cockpit-visor-status-right">{{ bridge ? (hud.trackSource === 'course' ? t('COURSE HOLD · AIS') : hud.trackSource === 'heading' ? t('HEADING HOLD · AIS') : t('NO HEADING · AIS')) : t('VISOR LOCK · ACTIVE') }}</div>
<div v-if="!generic" class="cockpit-visor-status cockpit-visor-status-left">{{ bridge ? t('BRIDGE WINDOW · FWD') : t('OPTICAL PLANE · 01') }}</div>
<div v-if="!generic" class="cockpit-visor-status cockpit-visor-status-right">{{ bridge ? (hud.trackSource === 'course' ? t('COURSE HOLD · AIS') : hud.trackSource === 'heading' ? t('HEADING HOLD · AIS') : t('NO HEADING · AIS')) : t('VISOR LOCK · ACTIVE') }}</div>
</div>
<div v-if="!orbital" id="cockpit-speed-rim" class="cockpit-altitude-rim cockpit-speed-rim" v-class-toggle="{ unavailable: hud.speedRim.unavailable }">
<div v-if="!orbital && !generic" id="cockpit-speed-rim" class="cockpit-altitude-rim cockpit-speed-rim" v-class-toggle="{ unavailable: hud.speedRim.unavailable }">
<span class="cockpit-altitude-rim-label">{{ bridge ? t('SPEED OVER GROUND · KTS') : t('GROUND SPEED · KTS') }}</span>
<div class="cockpit-altitude-rim-rail"></div>
<div class="cockpit-altitude-rim-scale">
@@ -188,7 +219,7 @@ const tickStyle = (tick) =>
<strong id="cockpit-speed-rim-value">{{ hud.speedRim.value }}</strong>
</div>
</div>
<div v-if="!orbital" id="cockpit-altitude-rim" class="cockpit-altitude-rim" :hidden="bridge" v-class-toggle="{ unavailable: hud.altitudeRim.unavailable }">
<div v-if="!orbital && !generic" id="cockpit-altitude-rim" class="cockpit-altitude-rim" :hidden="bridge" v-class-toggle="{ unavailable: hud.altitudeRim.unavailable }">
<span class="cockpit-altitude-rim-label">{{ t('ALTITUDE · FT') }}</span>
<div class="cockpit-altitude-rim-rail"></div>
<div class="cockpit-altitude-rim-scale">
@@ -201,9 +232,9 @@ const tickStyle = (tick) =>
</div>
<div class="cockpit-topline">
<div>
<span class="cockpit-kicker">{{ bridge ? t('BRIDGE VIEW') : t('FIRST PERSON') }}</span>
<span class="cockpit-kicker">{{ generic ? hud.kicker : bridge ? t('BRIDGE VIEW') : t('FIRST PERSON') }}</span>
<strong id="cockpit-callsign">{{ hud.callsign }}</strong>
<span id="cockpit-aircraft-meta" v-class-toggle="{ emergency: hud.meta.emergency }" class="cockpit-aircraft-meta">{{ hud.meta.text }}</span>
<span id="cockpit-aircraft-meta" v-class-toggle="{ emergency: hud.meta.emergency }" class="cockpit-aircraft-meta" :data-tone="generic ? hud.meta.tone : undefined">{{ hud.meta.text }}</span>
</div>
<div class="cockpit-vision-controls" role="group" :aria-label="t('Cockpit vision style')">
<button id="cockpit-vision-previous" class="cockpit-vision-nav" type="button" :aria-label="t('Previous cockpit vision style')" :title="t('Previous vision style')">
@@ -220,20 +251,27 @@ const tickStyle = (tick) =>
</button>
</div>
</div>
<div v-if="!orbital" class="cockpit-reticle material-symbols-outlined" aria-hidden="true">my_location</div>
<!-- A bridge view turned off the bow says where it looks and offers the way back. -->
<div v-if="bridge" class="cockpit-look" :hidden="!look.offset">
<div v-if="!orbital && !generic" class="cockpit-reticle material-symbols-outlined" aria-hidden="true">my_location</div>
<!-- A provider's banner: a status that names where the subject is. -->
<div v-if="generic && hud.banner" class="cockpit-banner" role="status" :data-tone="hud.banner.tone">
<strong>{{ hud.banner.title }}</strong>
<small v-if="hud.banner.detail">{{ hud.banner.detail }}</small>
</div>
<!-- A view turned off its rest says where it looks and offers the way back. -->
<div v-if="looks" class="cockpit-look" :hidden="!look.offset">
<span id="cockpit-look-readout" class="cockpit-look-readout" aria-live="polite">{{ look.readout }}</span>
<button id="cockpit-look-ahead" type="button" class="cockpit-look-ahead" :aria-label="t('Look ahead: turn the bridge view back to the bow')" :title="t('Look ahead (Home or 0)')" aria-keyshortcuts="Home 0">
<button id="cockpit-look-ahead" type="button" class="cockpit-look-ahead" :aria-label="aheadLabel" :title="t('Look ahead (Home or 0)')" aria-keyshortcuts="Home 0">
<span>{{ t('LOOK AHEAD') }}</span>
</button>
</div>
<div v-if="!orbital" class="cockpit-compass" :aria-label="bridge ? t('Current vessel heading') : t('Current aircraft heading')">
<div v-if="!orbital" class="cockpit-compass" :aria-label="generic ? hudLabel : bridge ? t('Current vessel heading') : t('Current aircraft heading')">
<div class="cockpit-instrument-row">
<div class="cockpit-readout cockpit-speed">
<span class="cockpit-readout-label">{{ bridge ? t('SPEED OVER GROUND') : t('GROUND SPEED') }}</span>
<!-- A provider's HUD view without a speed has no speed readout. -->
<div v-if="!generic || hud.speed" class="cockpit-readout cockpit-speed">
<span v-if="!generic" class="cockpit-readout-label">{{ bridge ? t('SPEED OVER GROUND') : t('GROUND SPEED') }}</span>
<span v-else-if="hud.speedTag" class="cockpit-readout-label cockpit-speed-tag" :data-tone="hud.speedTone">{{ hud.speedTag }}</span>
<CockpitRollingValue id="cockpit-speed-value" tag="strong" :reading="hud.speed" placeholder="---" />
<span class="cockpit-readout-unit">{{ t('KTS') }}</span>
<span class="cockpit-readout-unit">{{ generic ? hud.speedUnit : t('KTS') }}</span>
</div>
<div class="cockpit-heading-value"><CockpitRollingValue id="cockpit-heading-value" :reading="hud.heading" placeholder="---" :circular-range="360" /><small>°</small></div>
<div v-if="bridge" class="cockpit-readout cockpit-altitude cockpit-course">
@@ -241,7 +279,7 @@ const tickStyle = (tick) =>
<CockpitRollingValue id="cockpit-course-value" tag="strong" :reading="hud.course" placeholder="---" :circular-range="360" />
<span class="cockpit-readout-unit">°</span>
</div>
<div v-else class="cockpit-readout cockpit-altitude">
<div v-else-if="!generic" class="cockpit-readout cockpit-altitude">
<span class="cockpit-readout-label">{{ t('ALTITUDE') }}</span>
<CockpitRollingValue id="cockpit-altitude-value" tag="strong" :reading="hud.altitude" placeholder="-----" />
<span class="cockpit-readout-unit">{{ t('FT') }}</span>
@@ -254,6 +292,21 @@ const tickStyle = (tick) =>
<span id="cockpit-clock">{{ hud.clock }}</span>
<span id="cockpit-position">{{ hud.position }}</span>
</div>
<!-- A provider's board: its readout cards, then the sources of what they show. -->
<div v-if="generic && (hud.readouts.length || hud.sources.length)" class="cockpit-board">
<div v-for="row in hud.readouts" :key="row.id" class="cockpit-board-card" :data-readout="row.id" :data-tone="row.tone">
<small v-if="row.label">{{ row.label }}</small>
<strong v-if="row.value">{{ row.value }}</strong>
<span v-if="row.detail">{{ row.detail }}</span>
</div>
<dl v-if="hud.sources.length" class="cockpit-sources">
<div v-for="row in hud.sources" :key="row.id" :data-source="row.id" :data-tone="row.tone">
<dt v-if="row.label">{{ row.label }}</dt>
<dd>{{ row.text }}</dd>
</div>
</dl>
</div>
<CockpitProgress v-if="generic && hud.progress" :progress="hud.progress" />
<CockpitContext />
<CockpitBriefing />
<!-- The bridge radar's console: bottom right, below the briefing card. -->
@@ -261,7 +314,7 @@ const tickStyle = (tick) =>
<CockpitRadar />
</div>
<CockpitUtilityControls />
<div class="cockpit-help"><bdi>{{ t('ESC EXIT') }}</bdi><template v-if="bridge"> <span>·</span> <bdi>{{ t('ARROWS LOOK') }}</bdi> <span>·</span> <bdi>{{ t('HOME RESET') }}</bdi></template><template v-if="orbital"> <span>·</span> <bdi>{{ t('+/− ZOOM') }}</bdi> <span>·</span> <bdi>{{ t('ARROWS TILT') }}</bdi> <span>·</span> <bdi>{{ t('HOME NADIR') }}</bdi></template></div>
<div class="cockpit-help"><bdi>{{ t('ESC EXIT') }}</bdi><template v-if="looks"> <span>·</span> <bdi>{{ t('ARROWS LOOK') }}</bdi> <span>·</span> <bdi>{{ t('HOME RESET') }}</bdi></template><template v-if="orbital"> <span>·</span> <bdi>{{ t('+/− ZOOM') }}</bdi> <span>·</span> <bdi>{{ t('ARROWS TILT') }}</bdi> <span>·</span> <bdi>{{ t('HOME NADIR') }}</bdi></template></div>
</section>
<nav id="view-switcher" :aria-label="t('View switcher')">
+3 -1
View File
@@ -21,7 +21,9 @@ import { cockpitEntryFace } from '../cockpitPresentation.js';
const { view: ctx } = storeToRefs(useContextStore());
const { presence: cockpit } = storeToRefs(useCockpitStore());
// The entry names the subject it would ride (cockpitEntryFace).
const entry = computed(() => cockpitEntryFace(cockpit.value?.entryKind));
const entry = computed(() =>
cockpitEntryFace(cockpit.value?.entryKind, cockpit.value?.entryFace),
);
// While the Bhote Koshi event is on, its panel is the rail's only content.
const { panel: bhotePanel } = storeToRefs(useBhoteKoshiPanelStore());
// The Scene runtime chip SceneControls presents while a scene plays.
+3 -1
View File
@@ -17,7 +17,9 @@ const view = computed(() => hud.value ?? EMPTY);
// answers its clicks.
const { presence: cockpit } = storeToRefs(useCockpitStore());
// The entry names the subject it would ride (cockpitEntryFace).
const entry = computed(() => cockpitEntryFace(cockpit.value?.entryKind));
const entry = computed(() =>
cockpitEntryFace(cockpit.value?.entryKind, cockpit.value?.entryFace),
);
</script>
<template>
+2
View File
@@ -18,6 +18,7 @@ import ScreenAnnotations from './panels/ScreenAnnotations.vue';
import AwarenessDirection from './panels/AwarenessDirection.vue';
import UiButton from '../kit/UiButton.vue';
import GlobeActions from './panels/GlobeActions.vue';
import RenderFailure from './panels/RenderFailure.vue';
import WorldTimeline from './panels/WorldTimeline.vue';
// The ACTIVE STYLE corner shows the style VisualSettings publishes.
@@ -61,6 +62,7 @@ const vToastText = {
<template>
<div id="cesiumContainer"></div>
<RenderFailure />
<div id="world-overlay-root" aria-hidden="true">
<canvas id="world-overlay-canvas"></canvas>
</div>
+57
View File
@@ -0,0 +1,57 @@
<script setup>
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
import { cockpitProgressLayout } from '../../../cockpitProgress.js';
// A provider subject's progress line (src/cockpitSubjectProviders.js): a thin
// line along the bottom of the view, its ticks, labels and marker laid out
// at the line's own width (src/cockpitProgress.js). The part before the
// marker is dimmed. Everything it shows is worded by the provider. It is an
// image named by the provider's summary; with no summary it is decoration,
// hidden from assistive technology.
const props = defineProps({
progress: { type: Object, required: true },
});
/** The width laid out at before the line is measured (px). */
const FALLBACK_WIDTH_PX = 960;
const root = ref(null);
const widthPx = ref(0);
let observer = null;
const measure = () => {
widthPx.value = root.value?.clientWidth || 0;
};
onMounted(() => {
measure();
if (typeof ResizeObserver === 'function' && root.value) {
observer = new ResizeObserver(measure);
observer.observe(root.value);
}
});
onBeforeUnmount(() => observer?.disconnect());
const width = computed(() => widthPx.value || FALLBACK_WIDTH_PX);
const layout = computed(() =>
cockpitProgressLayout(props.progress, width.value),
);
// Positions as shares of the line, so a resize between measurements keeps
// every mark in place.
const percent = (x) => `${((x / width.value) * 100).toFixed(3)}%`;
</script>
<template>
<div ref="root" class="cockpit-progress" :role="progress.summary ? 'img' : undefined" :aria-label="progress.summary || undefined" :aria-hidden="progress.summary ? undefined : 'true'">
<template v-if="layout">
<div class="cockpit-progress-line" aria-hidden="true">
<span class="cockpit-progress-travelled" :style="{ width: percent(layout.travelledX) }"></span>
</div>
<i v-for="(tick, index) in layout.ticks" :key="`t${index}`" class="cockpit-progress-tick" :class="{ labelled: tick.labelled, merged: tick.count > 1, travelled: tick.x <= layout.travelledX }" :data-tone="tick.tone" :style="{ left: percent(tick.x) }" aria-hidden="true"></i>
<span v-for="(label, index) in layout.labels" :key="`l${index}`" class="cockpit-progress-label" :data-align="label.align" :data-tone="label.tone" :style="{ left: percent(label.left), width: `${label.width}px` }" aria-hidden="true"><b>{{ label.text }}</b><small v-if="label.detail">{{ label.detail }}</small></span>
<i v-if="layout.marker" class="cockpit-progress-marker" :class="{ dwell: layout.marker.dwell }" :style="{ left: percent(layout.marker.x) }" aria-hidden="true"></i>
<span v-if="layout.tag" class="cockpit-progress-tag" aria-hidden="true">{{ layout.tag }}</span>
</template>
</div>
</template>
+17 -2
View File
@@ -11,12 +11,27 @@ import { useCockpitStore } from '../../stores/cockpit.js';
const { route } = storeToRefs(useCockpitStore());
const initial = createRouteState();
const r = computed(() => route.value ?? initial);
// A provider subject's card is titled by its provider, in the page's language.
const kicker = computed(() =>
r.value.kind === 'subject'
? r.value.title
: r.value.kind === 'vessel'
? t('REPORTED VOYAGE')
: t('ESTIMATED FLIGHT PLAN'),
);
const label = computed(() =>
r.value.kind === 'subject'
? r.value.title || undefined
: r.value.kind === 'vessel'
? t('Reported voyage')
: t('Estimated flight plan'),
);
</script>
<template>
<section id="cockpit-route" class="cockpit-route-card" :aria-label="r.kind === 'vessel' ? t('Reported voyage') : t('Estimated flight plan')" :hidden="!r.visible">
<section id="cockpit-route" class="cockpit-route-card" :aria-label="label" :hidden="!r.visible">
<div class="cockpit-route-heading">
<span class="cockpit-route-kicker">{{ r.kind === 'vessel' ? t('REPORTED VOYAGE') : t('ESTIMATED FLIGHT PLAN') }}</span>
<span class="cockpit-route-kicker">{{ kicker }}</span>
<small id="cockpit-route-status">{{ r.status }}</small>
</div>
<div class="cockpit-route-endpoints">
+87
View File
@@ -0,0 +1,87 @@
<script setup>
import { nextTick, ref, watch } from 'vue';
import { storeToRefs } from 'pinia';
import { msg, t } from '../../../i18n/index.js';
import { useStatusStore } from '../../stores/status.js';
import UiButton from '../../kit/UiButton.vue';
// Published by installRenderFailureNotice() (src/render/cesium/renderFailure.js).
const { renderFailure: failure } = storeToRefs(useStatusStore());
const panel = ref(null);
const MESSAGES = {
'context-lost': msg(
"The browser took back the globe's 3D graphics. Layers and controls still work, but the map cannot draw until the page reloads.",
),
'render-error': msg(
'Rendering stopped after an error. Layers and controls still work, but the map is not updating.',
),
};
// Focus goes to the first action when the notice appears. When the globe
// draws again, it goes back, or to the map, unless the user moved it.
let focusBefore;
watch(
() => Boolean(failure.value),
async (shown) => {
if (shown) {
focusBefore = document.activeElement;
await nextTick();
panel.value?.querySelector('button')?.focus();
return;
}
if (focusBefore === undefined) return;
const previous = focusBefore;
focusBefore = undefined;
await nextTick();
const active = document.activeElement;
if (active && active !== document.body) return;
if (previous?.isConnected && previous !== document.body) {
previous.focus({ preventScroll: true });
// A control disabled, hidden or made inert meanwhile does not take it.
if (document.activeElement === previous) return;
}
focusMap();
},
{ immediate: true },
);
// The map's keys (Enter to finish a drawing, Space to talk) read the canvas
// as the map. It stays focusable only until focus leaves or the globe is
// pressed; a press leaves focus on the page, as in Cesium.
function focusMap() {
const canvas = document.querySelector(
'#cesiumContainer .cesium-widget canvas',
);
if (!canvas) return;
if (!canvas.hasAttribute('tabindex')) {
canvas.tabIndex = -1;
const done = new AbortController();
const release = () => {
done.abort();
canvas.removeAttribute('tabindex');
};
canvas.addEventListener('blur', release, { signal: done.signal });
canvas.addEventListener(
'pointerdown',
() => {
release();
canvas.blur();
},
{ capture: true, signal: done.signal },
);
}
canvas.focus({ preventScroll: true });
}
</script>
<template>
<div v-if="failure" id="render-failure" ref="panel" role="alertdialog" aria-labelledby="render-failure-title" aria-describedby="render-failure-message">
<h2 id="render-failure-title">{{ t('The globe stopped drawing') }}</h2>
<p id="render-failure-message">{{ t(MESSAGES[failure.reason] ?? MESSAGES['render-error']) }}</p>
<p v-if="failure.detail" class="render-failure-detail" translate="no">{{ failure.detail }}</p>
<p v-if="failure.reset" class="render-failure-hint">{{ t('Reset view reloads the app without the view restored from the address bar.') }}</p>
<div v-if="failure.retry || failure.reset" class="render-failure-actions">
<UiButton v-if="failure.retry" class="gev-action-button render-failure-retry" :onClick="failure.retry">{{ failure.reason === 'context-lost' ? t('Reload') : t('Retry') }}</UiButton>
<UiButton v-if="failure.reset" class="gev-action-button render-failure-reset" :onClick="failure.reset">{{ t('Reset view') }}</UiButton>
</div>
</div>
</template>