Files
gods-eye-view/src/ui/cockpitPresentation.js
T
Denis Groshev f75179eea0 feat(cockpit): an application can add its own cockpit subjects; the Rail and Transit layers expose the read and hold APIs such a subject needs
GEV itself registers no new subject: with no provider, the Cockpit offers
aircraft, satellites and vessels as before, except that the most recently
selected of them now wins entry.

- services.cockpitSubjects: providers ({kind, layerId, entryFace, priority,
  isEntryAllowed, read, hold, release, hud}) are checked once by the
  coordinator; frames and HUD views on every update; a throwing provider
  ends its view or keeps the last HUD.
- Entry: the most recently selected subject wins, across all kinds.
- Camera: a frame may turn the ground clamp off, anchor exactly on the
  subject and update every frame.
- A generic HUD: kicker, title, cards, always-visible source rows, banner,
  a veil with light streaks (off under reduced motion) and a bottom
  progress line whose close ticks merge.
- Text comes from the provider, already in the page's language
  (./i18n/locale: getLocale, onLocaleChange).
- Rail and Transit read and hold APIs (getSelectedTrain/Vehicle,
  getCockpitSubject, setCockpitSubject, focusTrain/Vehicle); a held
  train's marker, card and route line are hidden, and its feed keeps
  polling while held.
- ./layers/rail/paths is exported.
2026-11-12 10:50:26 +01:00

199 lines
6.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/** Pure formatting and fixed presentation constants used by Cockpit components. */
import { formatNumber, getLocale, isolate, t, msg } from '../i18n/index.js';
import { formatQuantity } from './unitLabels.js';
import {
normalizeHeading,
roundHeadingDegrees,
} from '../data/headingDegrees.js';
import { kilometreDigits } from '../data/distanceFormat.js';
export const COCKPIT_HEADING_SLEW_DPS = 28;
export const COCKPIT_FORWARD_OFFSET_M = 7;
export const COCKPIT_UP_OFFSET_M = 2.6;
export const COCKPIT_MIN_GROUND_CLEARANCE_M = 12;
export const COCKPIT_VIEW_PITCH_DEG = -4;
export const COCKPIT_CAMERA_UPDATE_MS = 50;
export const COCKPIT_HUD_UPDATE_MS = 100;
export const COCKPIT_CONTEXT_UPDATE_MS = 250;
export const COCKPIT_UTILITY_REC_GAP_PX = 12;
export const COCKPIT_UTILITY_SIGNAL_GAP_PX = 8;
export const COCKPIT_UTILITY_MIN_TOP_PX = 96;
export const COCKPIT_UTILITY_MIN_TOP_RATIO = 0.12;
export const COCKPIT_UTILITY_LAUNCHER_MIN_HEIGHT_PX = 50;
export const COCKPIT_GROUND_PROBE_MS = 500;
export const COCKPIT_GROUND_WAIT_TIMEOUT_MS = 5000;
export const COCKPIT_BRIEF_ROTATE_MS = 9000;
export const COCKPIT_REGIONAL_REFRESH_MS = 5 * 60_000;
export const COCKPIT_REGIONAL_REFRESH_DISTANCE_M = 25_000;
export function isRenderedOnScreen(element) {
if (!element) return false;
for (let node = element; node instanceof Element; node = node.parentElement) {
const style = getComputedStyle(node);
if (
style.display === 'none' ||
style.visibility === 'hidden' ||
Number(style.opacity) === 0
) {
return false;
}
}
const rect = element.getBoundingClientRect();
return rect.width > 0 && rect.height > 0;
}
export function formatCockpitBriefAge(value) {
const timestamp = Date.parse(value);
if (!Number.isFinite(timestamp)) return t('TIME UNKNOWN');
const minutes = Math.max(0, Math.round((Date.now() - timestamp) / 60_000));
if (minutes < 60) return t('{count}M AGO', { count: minutes });
const hours = Math.round(minutes / 60);
return hours < 48
? t('{count}H AGO', { count: hours })
: t('{count}D AGO', { count: Math.round(hours / 24) });
}
/** Compass point codes in display order and the label shown for each. */
const COMPASS_POINT_LABELS = Object.freeze({
N: msg('N'),
NE: msg('NE'),
E: msg('E'),
SE: msg('SE'),
S: msg('S'),
SW: msg('SW'),
W: msg('W'),
NW: msg('NW'),
});
/**
* The shown label for a compass point code (`N`, `SW`…): С, ЮЗ… in Russian.
* Anything else (a degree reading such as `030`) passes through unchanged.
*/
export function compassPointLabel(code) {
return Object.hasOwn(COMPASS_POINT_LABELS, code)
? t(COMPASS_POINT_LABELS[code])
: code;
}
/** `30.203°N` in the active language: `30,203° с. ш.` in Russian. */
export function formatCockpitCoordinate(value, positive, negative) {
const amount = formatNumber(Math.abs(value), {
useGrouping: false,
minimumFractionDigits: 3,
maximumFractionDigits: 3,
});
const code = value >= 0 ? positive : negative;
// Not «30,203°С»: after a degree sign «С» reads as Celsius. Isolated, so
// an Arabic hemisphere letter does not pull the next number into its run.
switch (code) {
case 'N':
return isolate(t('{value}°N', { value: amount }));
case 'S':
return isolate(t('{value}°S', { value: amount }));
case 'E':
return isolate(t('{value}°E', { value: amount }));
case 'W':
return isolate(t('{value}°W', { value: amount }));
default:
return isolate(`${amount}°${compassPointLabel(code)}`);
}
}
/**
* A contact distance such as `4.2 KM` / `44 KM` in the active language
* (`4,2 КМ`): one decimal under 10 km, whole kilometres beyond.
*/
export function formatCockpitDistance(distanceM) {
const digits = kilometreDigits(distanceM);
const distance = formatQuantity(distanceM / 1000, 'km', {
minimumFractionDigits: digits,
maximumFractionDigits: digits,
});
return cockpitUnitCase(distance);
}
/**
* Upper-case a cockpit unit the HUD way (`9.5 KM`), except in Chinese and
* Japanese, which have no case and keep units as the catalog writes them.
*/
export function cockpitUnitCase(text) {
return /^(zh|ja)(-|$)/.test(getLocale()) ? text : text.toUpperCase();
}
export function formatCockpitWindDirection(value) {
if (!Number.isFinite(value)) return t('DIR UNKNOWN');
const labels = Object.keys(COMPASS_POINT_LABELS);
const normalized = normalizeHeading(value);
const degrees = roundHeadingDegrees(value);
return `${compassPointLabel(labels[Math.round(normalized / 45) % labels.length])} · ${degrees}°`;
}
/**
* A TLE epoch as compact UTC, `2026-11-04 08:12Z`, or '' when unknown.
* @param {number|null|undefined} epochMs
*/
export function formatTleEpochUtc(epochMs) {
// Beyond ±8.64e15 ms a Date is invalid and toISOString throws.
if (!Number.isFinite(epochMs) || Math.abs(epochMs) > 8.64e15) return '';
const iso = new Date(epochMs).toISOString();
return `${iso.slice(0, 10)} ${iso.slice(11, 16)}Z`;
}
/**
* How old a TLE is, in the identifier line's compact units: under an hour,
* whole hours under a day, then whole days. A TLE's propagation error grows
* with its age, so the age is shown beside the epoch.
* @param {number|null|undefined} ageMs Now minus the TLE epoch.
* @returns {{unit: 'under-hour'}|{unit: 'hours'|'days', value: number}|null}
* Null without a usable age.
*/
export function tleAgeParts(ageMs) {
if (!Number.isFinite(ageMs)) return null;
const hours = Math.max(0, ageMs) / 3_600_000;
if (hours < 1) return { unit: 'under-hour' };
if (hours < 24) return { unit: 'hours', value: Math.floor(hours) };
return { unit: 'days', value: Math.floor(hours / 24) };
}
/**
* The Cockpit entry for each subject it can ride: an aircraft's cockpit, a
* vessel's bridge or a satellite's orbit. Both entry buttons (Contacts and
* the Intel HUD readout) show it.
*/
const COCKPIT_ENTRY_FACES = Object.freeze({
aircraft: Object.freeze({ icon: 'flight', label: msg('COCKPIT') }),
vessel: Object.freeze({ icon: 'directions_boat', label: msg('BRIDGE') }),
satellite: Object.freeze({ icon: 'satellite_alt', label: msg('ORBIT') }),
});
/**
* The entry's glyph and localized label for the subject it would ride. An
* application provider's subject brings its own face, already in the page's
* language (`presence.entryFace`).
* @param {string|null|undefined} kind
* @param {{icon: string, label: string}|null} [face]
* @returns {{icon: string, label: string}}
*/
export function cockpitEntryFace(kind, face = null) {
if (face?.icon && face?.label) return { icon: face.icon, label: face.label };
const known = COCKPIT_ENTRY_FACES[kind] ?? COCKPIT_ENTRY_FACES.aircraft;
return { icon: known.icon, label: t(known.label) };
}