mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 08:12:24 +00:00
Merge upstream/main into fix/drone-airspace
Move the share-link token to 6 (3 is gnss-integrity), build altitude ranges from LOWER/UPPER VAL, UOM and CODE, mark card and legend strings for translation, rename the layer to Prohibited & Restricted Airspace, move the changelog entry to changelog.d, and keep the layer voice-off while the Realtime prompt is at its budget.
This commit is contained in:
1387 files changed
+160157
-23954
No files matched your search
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* Create an ordinary native action button. Static templates use the same CSS
|
||||
* classes. Labels are already translated; feature owners retain callbacks,
|
||||
* disabled-state updates and listener cleanup. Construction binds no listeners.
|
||||
* @param {object} options
|
||||
* @param {Document} [options.documentRef] Document that owns the button.
|
||||
* @param {string} options.label Visible text, never interpreted as markup.
|
||||
* @param {string} [options.className] Additional feature/layout hooks.
|
||||
* @param {'default'|'danger'} [options.variant]
|
||||
* @param {'default'|'compact'} [options.size]
|
||||
* @param {boolean} [options.disabled]
|
||||
* @param {string} [options.ariaLabel] Accessible name when visible text needs context.
|
||||
* @param {string} [options.title]
|
||||
* @returns {HTMLButtonElement}
|
||||
*/
|
||||
export function createActionButton({
|
||||
documentRef = globalThis.document,
|
||||
label,
|
||||
className = '',
|
||||
variant = 'default',
|
||||
size = 'default',
|
||||
disabled = false,
|
||||
ariaLabel,
|
||||
title,
|
||||
}) {
|
||||
const button = documentRef.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = [
|
||||
'gev-action-button',
|
||||
variant === 'danger' && 'gev-action-button--danger',
|
||||
size === 'compact' && 'gev-action-button--compact',
|
||||
className,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' ');
|
||||
button.textContent = label;
|
||||
button.disabled = disabled;
|
||||
if (ariaLabel !== undefined) button.setAttribute('aria-label', ariaLabel);
|
||||
if (title !== undefined) button.title = title;
|
||||
return button;
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import { syncSegmentedControl } from './segmentedControl.js';
|
||||
|
||||
/** Own the shared aircraft display preference and its controls. */
|
||||
export class AircraftDisplay {
|
||||
constructor({ elements, readDataManager, layout }) {
|
||||
@@ -28,12 +30,9 @@ export class AircraftDisplay {
|
||||
this._models3dMode = options.models3dMode === 'all' ? 'all' : 'proximity';
|
||||
this._syncModels3dButtonState();
|
||||
this._models3dModeRow?.classList.toggle('visible', this._models3dEnabled);
|
||||
for (const button of this._models3dModeBtns || []) {
|
||||
if (!button) continue;
|
||||
const active = button.dataset.mode === this._models3dMode;
|
||||
button.classList.toggle('active', active);
|
||||
button.setAttribute('aria-checked', String(active));
|
||||
}
|
||||
syncSegmentedControl(this._models3dModeBtns, this._models3dMode, {
|
||||
valueOf: (button) => button.dataset.mode,
|
||||
});
|
||||
this._layoutRightPanels();
|
||||
}
|
||||
|
||||
@@ -59,12 +58,9 @@ export class AircraftDisplay {
|
||||
const normalized = mode === 'all' ? 'all' : 'proximity';
|
||||
this._models3dMode = normalized;
|
||||
this._setModels3dParams({ models3dMode: normalized });
|
||||
for (const button of this._models3dModeBtns) {
|
||||
if (!button) continue;
|
||||
const active = button.dataset.mode === normalized;
|
||||
button.classList.toggle('active', active);
|
||||
button.setAttribute('aria-checked', String(active));
|
||||
}
|
||||
syncSegmentedControl(this._models3dModeBtns, normalized, {
|
||||
valueOf: (button) => button.dataset.mode,
|
||||
});
|
||||
this._syncModels3dButtonState();
|
||||
}
|
||||
|
||||
@@ -74,7 +70,6 @@ export class AircraftDisplay {
|
||||
// a screen reader without this. It matters more now that the button ships
|
||||
// ACTIVE from markup (default-on, 2026-08-22): the very first thing assistive
|
||||
// tech reported was an unpressed-looking control over an armed layer.
|
||||
// Mirrors #scope-toggle, which has always carried aria-pressed.
|
||||
this._models3dBtn?.setAttribute(
|
||||
'aria-pressed',
|
||||
String(this._models3dEnabled),
|
||||
|
||||
+252
-34
@@ -3,6 +3,7 @@ import { ShellFacade } from './shellFacade.js';
|
||||
import { AircraftDisplay } from './aircraftDisplay.js';
|
||||
import { LayerBindings } from './layerBindings.js';
|
||||
import { PanelChrome } from './panelChrome.js';
|
||||
import { initMobileShell } from './mobileShell.js';
|
||||
import { VisualSettings } from './visualSettings.js';
|
||||
import { NavigationController } from './navigationController.js';
|
||||
import { ShareRestoration } from './shareRestoration.js';
|
||||
@@ -34,17 +35,30 @@ import * as Cesium from 'cesium';
|
||||
import { aircraftTrackingTarget } from '../cockpitTracking.js';
|
||||
|
||||
import { ShellFeedback } from './shellFeedback.js';
|
||||
import {
|
||||
applyShareFollowOffset,
|
||||
readShareFollowSubject,
|
||||
} from './shareFollow.js';
|
||||
|
||||
import { runCctvLayerEnableTransition } from '../cctvFocusPolicy.js';
|
||||
|
||||
import {
|
||||
describeUnsavedWork,
|
||||
getLocale,
|
||||
msg,
|
||||
persistLocaleAndReload,
|
||||
registerUnsavedWork,
|
||||
t,
|
||||
} from '../i18n/index.js';
|
||||
import { applyLocaleChoice, mountLocalePicker } from './localePicker.js';
|
||||
|
||||
/**
|
||||
* Central UI orchestrator for the God's Eye View application.
|
||||
*
|
||||
* Responsibilities:
|
||||
* - Visual controls and presets backed by the VisualEffects controller.
|
||||
* - Bloom and sharpen post-processing toggle/intensity control.
|
||||
* - Draggable/collapsible panel system with localStorage persistence,
|
||||
* z-order stacking, and viewport-clamped positioning.
|
||||
* - Collapsible rail panels with their collapsed state kept in localStorage.
|
||||
* - CCTV panel: camera selection, coverage toggle, projection, calibration
|
||||
* sliders, auto-hop, and summary typewriter effect.
|
||||
* - Location bar with city/POI preset pills, QWERTY key navigation,
|
||||
@@ -64,7 +78,13 @@ export class StyleManager extends ShellFacade {
|
||||
*/
|
||||
constructor(
|
||||
viewer,
|
||||
{ mapStackController = null, placeSearch, services, requestServices } = {},
|
||||
{
|
||||
mapStackController = null,
|
||||
placeSearch,
|
||||
services,
|
||||
requestServices,
|
||||
initialShareCode = null,
|
||||
} = {},
|
||||
) {
|
||||
super();
|
||||
const {
|
||||
@@ -105,7 +125,6 @@ export class StyleManager extends ShellFacade {
|
||||
_setRadioDisclosure: (...args) => this._setRadioDisclosure(...args),
|
||||
_syncCctvPanelViewport: (...args) =>
|
||||
this._syncCctvPanelViewport(...args),
|
||||
_onPanelResized: (...args) => this._onPanelResized(...args),
|
||||
_syncContextRadioLauncherState: (...args) =>
|
||||
this._syncContextRadioLauncherState(...args),
|
||||
_showToast: (...args) => this._showToast(...args),
|
||||
@@ -116,6 +135,8 @@ export class StyleManager extends ShellFacade {
|
||||
readInitialShare: () => this._initialShareState,
|
||||
readScrollRestoreOwner: () => this._displayPortalScrollRestoreOwner,
|
||||
readDisplayScrollTop: () => this._standardDisplayScrollTop,
|
||||
readSharedCollapsed: (panelId) =>
|
||||
this._mobileShell?.sharedCollapsed(panelId),
|
||||
});
|
||||
this._feedback = new ShellFeedback({
|
||||
readLayers: () => this._dataManager?.getAll?.() || [],
|
||||
@@ -136,6 +157,7 @@ export class StyleManager extends ShellFacade {
|
||||
},
|
||||
searchInput: this._locationSearch,
|
||||
interruptCameraMotion: services.interruptCameraMotion,
|
||||
interruptGlobeRotation: services.interruptGlobeRotation,
|
||||
isCockpitActive: () => !!this.cockpitView?.active,
|
||||
clearLocation: () => this.clearSearchedLocation(),
|
||||
cancelShareSelection: () => this._shareRestoration.cancelSelection(),
|
||||
@@ -153,6 +175,8 @@ export class StyleManager extends ShellFacade {
|
||||
this._showGlobalStatusNotice(message, options),
|
||||
feedback: this._feedback,
|
||||
updateFeedback: () => this._updateGlobalLoadingFeedback(),
|
||||
applyFollowOffset: (entity, offset) =>
|
||||
applyShareFollowOffset(viewer, entity, offset),
|
||||
});
|
||||
|
||||
this._visualSettings = new VisualSettings({
|
||||
@@ -265,6 +289,7 @@ export class StyleManager extends ShellFacade {
|
||||
_contextControls: this._contextControls,
|
||||
_cctvControls: this._cctvControls,
|
||||
_radioControls: this._radioControls,
|
||||
_streetLevelControls: this._streetLevelControls,
|
||||
}),
|
||||
operations: {
|
||||
_updateTrafficSyncChip: (...args) =>
|
||||
@@ -310,6 +335,7 @@ export class StyleManager extends ShellFacade {
|
||||
GLOBE_VIEW: services.GLOBE_VIEW,
|
||||
flyToGlobeView: services.flyToGlobeView,
|
||||
interruptCameraMotion: services.interruptCameraMotion,
|
||||
interruptGlobeRotation: services.interruptGlobeRotation,
|
||||
flightsLayer: services.flightsLayer,
|
||||
militaryFlightsLayer: services.militaryFlightsLayer,
|
||||
satellitesLayer: services.satellitesLayer,
|
||||
@@ -322,6 +348,7 @@ export class StyleManager extends ShellFacade {
|
||||
_poiRow: this._poiRow,
|
||||
_locationBarDivider: this._locationBarDivider,
|
||||
_locationSearch: this._locationSearch,
|
||||
_locationSearchError: this._locationSearchError,
|
||||
_searchToggle: this._searchToggle,
|
||||
_resetGlobeBtn: this._resetGlobeBtn,
|
||||
_cockpitResetGlobeBtn: this._cockpitResetGlobeBtn,
|
||||
@@ -416,7 +443,12 @@ export class StyleManager extends ShellFacade {
|
||||
isNavigationCurrent: (generation) =>
|
||||
generation === this._navigationGeneration,
|
||||
cancelOwnedNavigation: () => this.viewer.camera.cancelFlight(),
|
||||
// A host may open a share code without a `/share/<code>` address.
|
||||
initialShareCode,
|
||||
});
|
||||
this.shareLinkManager.setFollowSubjectProvider(({ nowMs }) =>
|
||||
readShareFollowSubject({ viewer: this.viewer, nowMs }),
|
||||
);
|
||||
this.shareLinkManager.setPanelStateProvider(() =>
|
||||
this._buildSharePanelState(),
|
||||
);
|
||||
@@ -566,7 +598,11 @@ export class StyleManager extends ShellFacade {
|
||||
});
|
||||
this._initUI();
|
||||
this._initMapStackControl();
|
||||
// Headers first: panel chrome builds its toggle labels from them.
|
||||
this._applyRuntimeStaticHeaderText();
|
||||
this._initPanelChrome();
|
||||
this._initLocaleSelector();
|
||||
this._sizeDisplayLabelColumn();
|
||||
this._initLeftPanelAdaptiveLayout();
|
||||
this._initRightPanelAdaptiveLayout();
|
||||
this._initRadioPanel();
|
||||
@@ -574,6 +610,7 @@ export class StyleManager extends ShellFacade {
|
||||
this._initStreetLevelPanel();
|
||||
this._initGlobalContextPanel();
|
||||
this._initLocationBar();
|
||||
this._initMobileShell();
|
||||
this._initShareButton();
|
||||
this._initCameraOrientationControls();
|
||||
this._initClearSelectedLayersButton();
|
||||
@@ -700,6 +737,183 @@ export class StyleManager extends ShellFacade {
|
||||
this._displayBindings._initUI();
|
||||
}
|
||||
|
||||
/**
|
||||
* Mounts the language picker (src/ui/localePicker.js). A choice reloads the
|
||||
* page; _confirmLocaleReload asks first when that would lose work.
|
||||
* @returns {void}
|
||||
*/
|
||||
_initLocaleSelector() {
|
||||
// Work this shell can see that a reload drops. Other modules register
|
||||
// their own (registerUnsavedWork in src/i18n/index.js).
|
||||
this._unsavedWorkChecks = [
|
||||
registerUnsavedWork(() =>
|
||||
this.services?.cctvLayer
|
||||
?.getUIState?.()
|
||||
?.cameras?.some((camera) => camera.calDirty)
|
||||
? msg('unsaved CCTV calibration')
|
||||
: null,
|
||||
),
|
||||
registerUnsavedWork(() =>
|
||||
this.cockpitView?.active ? msg('the open cockpit') : null,
|
||||
),
|
||||
];
|
||||
const root = globalThis.document?.getElementById?.('locale-picker');
|
||||
if (!root) return;
|
||||
this._localePicker = mountLocalePicker({
|
||||
root,
|
||||
current: getLocale(),
|
||||
onSelect: (locale) => this._chooseLocale(locale),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Switch to `locale`: nothing for the active language, otherwise store it
|
||||
* and reload once _confirmLocaleReload agrees.
|
||||
* @param {string} locale
|
||||
* @returns {'unchanged'|'declined'|'switched'}
|
||||
*/
|
||||
_chooseLocale(locale) {
|
||||
return applyLocaleChoice(locale, {
|
||||
current: getLocale(),
|
||||
confirmSwitch: () => this._confirmLocaleReload(),
|
||||
switchLocale: (next) => persistLocaleAndReload(next),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Switching language reloads the page. While that would lose work the page
|
||||
* cannot restore, ask first.
|
||||
* @returns {boolean} true to switch.
|
||||
*/
|
||||
_confirmLocaleReload() {
|
||||
const lost = describeUnsavedWork();
|
||||
if (!lost.length || typeof globalThis.confirm !== 'function') return true;
|
||||
return globalThis.confirm(
|
||||
t(
|
||||
'Switching language reloads the page. This will be lost: {items}. Switch anyway?',
|
||||
{ items: lost.join(', ') },
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sizes one Display-panel label column to the longest label in the active
|
||||
* language, so slider tracks line up. Counts characters (labels are
|
||||
* monospace and often hidden); CSS turns the count into a width.
|
||||
* @returns {void}
|
||||
*/
|
||||
_sizeDisplayLabelColumn() {
|
||||
const labels = document.querySelectorAll(
|
||||
'#pp-toggles .pp-slider-row > .pp-slider-mini-label',
|
||||
);
|
||||
let longest = 0;
|
||||
for (const label of labels) {
|
||||
longest = Math.max(longest, label.textContent.trim().length);
|
||||
}
|
||||
if (longest > 0) {
|
||||
document.documentElement.style.setProperty(
|
||||
'--pp-label-chars',
|
||||
String(longest),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rewrites a header's last text node, keeping the leading icon span that a
|
||||
* textContent write would destroy.
|
||||
* @param {Element|null} element
|
||||
* @param {string} text
|
||||
* @returns {void}
|
||||
*/
|
||||
_setHeaderText(element, text) {
|
||||
if (!element) return;
|
||||
const textNode = Array.from(element.childNodes)
|
||||
.reverse()
|
||||
.find(
|
||||
(node) => node.nodeType === Node.TEXT_NODE && node.nodeValue?.trim(),
|
||||
);
|
||||
if (textNode) textNode.nodeValue = text;
|
||||
else element.textContent = text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates at boot the header texts that share their element with an
|
||||
* icon or a <br> (data-i18n-runtime in the templates).
|
||||
* @returns {void}
|
||||
*/
|
||||
_applyRuntimeStaticHeaderText() {
|
||||
this._setHeaderText(
|
||||
document.querySelector('#control-panel .panel-title'),
|
||||
t('VISUAL PRESETS'),
|
||||
);
|
||||
this._setHeaderText(
|
||||
document.querySelector('#location-bar .location-toolbar-label'),
|
||||
t('LOCATION'),
|
||||
);
|
||||
// One span holds both mode descriptions around a <br>; keep the <br>.
|
||||
const standbyDescription = document.querySelector(
|
||||
'#context-mode-standby span',
|
||||
);
|
||||
if (standbyDescription) {
|
||||
standbyDescription.replaceChildren(
|
||||
document.createTextNode(
|
||||
t('CONTACTS — nearest planes · vessels · sites'),
|
||||
),
|
||||
document.createElement('br'),
|
||||
document.createTextNode(
|
||||
t('SPACE MISSIONS — launches & orbital assets'),
|
||||
),
|
||||
);
|
||||
}
|
||||
// Leading space after the live dot, as showBriefPage writes it.
|
||||
const briefKicker = document.querySelector('#cockpit-brief-kicker');
|
||||
if (briefKicker) {
|
||||
this._setHeaderText(briefKicker, ` ${t('LIVE SIGNALS')}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Phone layout: a bottom tab bar presenting one panel sheet at a time
|
||||
* (src/ui/mobileShell.js). Inactive above 720px.
|
||||
* @returns {void}
|
||||
*/
|
||||
_initMobileShell() {
|
||||
this._mobileShell = initMobileShell({
|
||||
setPanelCollapsed: (panelId, collapsed, options) =>
|
||||
this._panelChrome.setPanelCollapsed(panelId, collapsed, options),
|
||||
onSheetsClosed: () => this._syncShareState(),
|
||||
onTabOpened: (sheet) => {
|
||||
void this._onMobileTabOpened(sheet);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Reveal a tracked aircraft through Contacts when its phone tab is opened. */
|
||||
async _onMobileTabOpened(sheet) {
|
||||
const context = this.getContextModeState();
|
||||
if (
|
||||
sheet !== 'context' ||
|
||||
this._disposed ||
|
||||
!context ||
|
||||
context.mode ||
|
||||
context.changing ||
|
||||
context.entering ||
|
||||
!this.getAircraftTrackingTarget()
|
||||
)
|
||||
return false;
|
||||
try {
|
||||
const result = await this.setContextMode('contacts');
|
||||
if (result?.ok) return true;
|
||||
if (result?.cancelled || this._disposed) return false;
|
||||
} catch {
|
||||
if (this._disposed) return false;
|
||||
}
|
||||
this._showToast(
|
||||
t('Contacts could not complete the requested transition; try again'),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the owner-approved map stack chip row from the matching controller
|
||||
* entries. Cesium ion/Bing chips remain keyboard-focusable but unavailable,
|
||||
@@ -708,6 +922,7 @@ export class StyleManager extends ShellFacade {
|
||||
*/
|
||||
_initMapStackControl() {
|
||||
if (!this.mapStackController) return;
|
||||
|
||||
this._mapSourceControls?.destroy();
|
||||
this._mapSourceControls = createMapSourceControls({
|
||||
container: this._mapStackChips,
|
||||
@@ -939,13 +1154,11 @@ export class StyleManager extends ShellFacade {
|
||||
this._streetLevelControls?.destroy();
|
||||
this._streetLevelControls = null;
|
||||
if (!this._streetLevelPanel || !streetLevelLayer) return;
|
||||
// Photo framing and FOLLOW release tracking like any explicit flight.
|
||||
// Photo framing yields to newer navigation and releases tracking like
|
||||
// any deferred flight.
|
||||
streetLevelLayer.attachNavigation?.({
|
||||
run: (noun, move) => this._runExplicitNavigation(noun, move),
|
||||
begin: (noun) => this._beginDeferredNavigation(noun),
|
||||
reassert: (generation) => this._reassertNavigationHandoff(generation),
|
||||
subscribeHandoff: (listener) =>
|
||||
this._navigation.subscribeCameraHandoff(listener),
|
||||
});
|
||||
this._streetLevelControls = new StreetLevelControls({
|
||||
root: this._streetLevelPanel,
|
||||
@@ -960,7 +1173,6 @@ export class StyleManager extends ShellFacade {
|
||||
this._dataManager?.setLayerParams('street-level', params, options),
|
||||
setPanelCollapsed: (collapsed, options) =>
|
||||
this.setPanelCollapsed('street-level-panel', collapsed, options),
|
||||
dockPanel: () => this._panelChrome.dockPanel('street-level-panel'),
|
||||
showToast: (message) => this._showToast(message),
|
||||
// Lets the panel open for a user, voice or tool switch-on, not a restore.
|
||||
subscribeEnableRequests: (listener) =>
|
||||
@@ -1029,7 +1241,7 @@ export class StyleManager extends ShellFacade {
|
||||
const { cctvLayer } = this.services;
|
||||
if (this._disposed) return false;
|
||||
if (!this._dataManager || !this._dataManager.layers?.has('cctv')) {
|
||||
this._showToast('CCTV layer unavailable');
|
||||
this._showToast(t('CCTV layer unavailable'));
|
||||
return false;
|
||||
}
|
||||
const enabled = this._dataManager.isEnabled('cctv');
|
||||
@@ -1057,19 +1269,6 @@ export class StyleManager extends ShellFacade {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes a panel draggable via its handle element. Implements:
|
||||
* - Z-order promotion: each pointerdown increments the global z-counter
|
||||
* so the clicked panel floats above siblings.
|
||||
* - Viewport clamping: drag moves are clamped to a 6px inset from all edges.
|
||||
* - Right-rail pinning: pp-toggles panel is re-anchored right after drag.
|
||||
* - CCTV viewport sync: cctv-panel recalculates scroll height after drag.
|
||||
* @param {string} panelId - DOM id of the panel.
|
||||
* @param {HTMLElement} panelEl - The panel DOM element.
|
||||
* @param {HTMLElement} handleEl - The drag handle element within the panel.
|
||||
* @returns {void}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Programmatically collapses or expands a panel, persists the state,
|
||||
* and triggers layout recalculation for dependent panels.
|
||||
@@ -1471,14 +1670,35 @@ export class StyleManager extends ShellFacade {
|
||||
// ── Share Button ─────────────────────────────
|
||||
|
||||
/**
|
||||
* Wires the share button click to copy the current share link to the clipboard.
|
||||
* Wires the share button. By default it copies the current share link to the
|
||||
* clipboard; a host may pass `services.shareLink(url)` to share it another way
|
||||
* (a system share sheet, for example). It resolves to 'shared', 'copied',
|
||||
* 'cancelled' (no toast) or false (failed).
|
||||
* @returns {void}
|
||||
*/
|
||||
_initShareButton() {
|
||||
this._lifetime.listen(this._shareBtn, 'click', async () => {
|
||||
const success = await this.shareLinkManager.copyLink();
|
||||
if (!this._disposed)
|
||||
this._showToast(success ? 'Link copied!' : 'Copy failed');
|
||||
const share = this.services.shareLink;
|
||||
let result;
|
||||
if (typeof share === 'function') {
|
||||
// A host's hook may return a plain value or throw; both are answers.
|
||||
result = await Promise.resolve()
|
||||
.then(() => {
|
||||
const href = this.shareLinkManager.buildLink();
|
||||
return href ? share(href) : false;
|
||||
})
|
||||
.catch(() => false);
|
||||
} else {
|
||||
result = (await this.shareLinkManager.copyLink()) ? 'copied' : false;
|
||||
}
|
||||
if (this._disposed || result === 'cancelled') return;
|
||||
this._showToast(
|
||||
result === 'shared'
|
||||
? t('Link shared')
|
||||
: result === 'copied'
|
||||
? t('Link copied!')
|
||||
: t('Copy failed'),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1516,13 +1736,6 @@ export class StyleManager extends ShellFacade {
|
||||
this._initCockpitDisplayPortal();
|
||||
}
|
||||
|
||||
/** A portable panel was resized or docked: refit any viewport inside it. */
|
||||
_onPanelResized(panelId) {
|
||||
if (panelId === 'cctv-panel') this._syncCctvPanelViewport();
|
||||
if (panelId === 'street-level-panel')
|
||||
this._streetLevelControls?.onPanelResized();
|
||||
}
|
||||
|
||||
/**
|
||||
* Recalculates the CCTV panel max-height based on its current top position
|
||||
* and the window height, enabling internal scroll without viewport overflow.
|
||||
@@ -1576,7 +1789,12 @@ export class StyleManager extends ShellFacade {
|
||||
this._shareState.destroy();
|
||||
this._locationNavigation.destroy();
|
||||
this._lifetime.destroy();
|
||||
for (const unregister of this._unsavedWorkChecks?.splice(0) ?? [])
|
||||
unregister();
|
||||
this._localePicker?.destroy();
|
||||
this._localePicker = null;
|
||||
this._recording.destroy();
|
||||
this._mobileShell?.destroy();
|
||||
this._panelChrome.destroy();
|
||||
this._feedback.destroy();
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { isPickedWorldPosition } from '../data/scenePick.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
|
||||
function trackedTarget(viewer) {
|
||||
const entity = viewer.trackedEntity;
|
||||
@@ -106,7 +107,7 @@ export function readCameraTargetFrame(viewer) {
|
||||
}
|
||||
|
||||
/** Apply an orbit frame, then return the camera to Cesium's fixed-world frame. */
|
||||
export function setCameraTargetFrame(viewer, frame) {
|
||||
function setCameraTargetFrame(viewer, frame) {
|
||||
const camera = viewer?.camera;
|
||||
if (!camera || !frame?.target || !Number.isFinite(frame.range)) return false;
|
||||
try {
|
||||
@@ -155,7 +156,7 @@ export function setCameraTargetFrame(viewer, frame) {
|
||||
*
|
||||
* @param {{pitch: number}|null} frame From {@link readCameraTargetFrame}.
|
||||
*/
|
||||
export function frameIsTilted(frame) {
|
||||
function frameIsTilted(frame) {
|
||||
const pitch = Number(frame?.pitch);
|
||||
return Number.isFinite(pitch) ? pitch > OBLIQUE_THRESHOLD : false;
|
||||
}
|
||||
@@ -288,8 +289,8 @@ export function bindCameraOrientationControls({
|
||||
tiltButton?.setAttribute(
|
||||
'aria-label',
|
||||
next.tilted
|
||||
? 'Return map to straight-down view'
|
||||
: 'Tilt map to oblique view',
|
||||
? t('Return map to straight-down view')
|
||||
: t('Tilt map to oblique view'),
|
||||
);
|
||||
}
|
||||
if (!applied || applied.heading !== next.heading) {
|
||||
@@ -297,7 +298,9 @@ export function bindCameraOrientationControls({
|
||||
northButton?.style?.setProperty('--camera-heading', `${next.heading}deg`);
|
||||
northButton?.setAttribute(
|
||||
'aria-label',
|
||||
`Reset map to north up. Current heading ${next.heading} degrees`,
|
||||
t('Reset map to north up. Current heading {heading} degrees', {
|
||||
heading: next.heading,
|
||||
}),
|
||||
);
|
||||
}
|
||||
applied = next;
|
||||
@@ -323,7 +326,7 @@ export function bindCameraOrientationControls({
|
||||
: false;
|
||||
});
|
||||
if (result) {
|
||||
showToast?.(result.tilted ? 'Tilted view' : 'Straight-down view');
|
||||
showToast?.(result.tilted ? t('Tilted view') : t('Straight-down view'));
|
||||
// The action reports the state it just commanded, so the button can
|
||||
// follow it without a second pick.
|
||||
tilted = result.tilted;
|
||||
@@ -342,7 +345,7 @@ export function bindCameraOrientationControls({
|
||||
})
|
||||
);
|
||||
});
|
||||
if (result) showToast?.('North up');
|
||||
if (result) showToast?.(t('North up'));
|
||||
sync();
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { CctvControls } from './cctvControls.js';
|
||||
import { railFixture } from './railTestFixture.mjs';
|
||||
import { setLocale, t } from '../i18n/index.js';
|
||||
|
||||
function fixture(t) {
|
||||
const { document } = railFixture();
|
||||
const controls = new CctvControls({
|
||||
elements: {
|
||||
_cctvQualityChip: document.createElement('span'),
|
||||
_cctvSourceBadge: document.createElement('div'),
|
||||
},
|
||||
cctv: {},
|
||||
actions: { isEnabled: () => true, setPanelCollapsed() {} },
|
||||
});
|
||||
t.after(() => controls.destroy());
|
||||
return { controls, document };
|
||||
}
|
||||
|
||||
test('source and frame states retain their distinct meanings, including retained pixels', (testContext) => {
|
||||
const { controls, document } = fixture(testContext);
|
||||
const camera = { sourceKind: 'snapshot', sourceStatus: 'degraded' };
|
||||
controls._cctvFrame = document.createElement('img');
|
||||
controls._cctvFrameWrap = document.createElement('div');
|
||||
controls._cctvFrame.removeAttribute = () => {};
|
||||
for (const node of [controls._cctvFrame, controls._cctvFrameWrap]) {
|
||||
node.classList.remove = (...names) =>
|
||||
names.forEach((name) => node.classList.toggle(name, false));
|
||||
}
|
||||
const expect = (label, state, active = camera, enabled = true) => {
|
||||
controls._syncCctvSourceBadge(active, enabled);
|
||||
assert.equal(controls._cctvSourceBadge.textContent, label);
|
||||
assert.equal(controls._cctvSourceBadge.dataset.frameState, state);
|
||||
};
|
||||
expect('SOURCE · UNKNOWN', 'idle', camera, false);
|
||||
expect('SOURCE · UNKNOWN', 'idle', null);
|
||||
controls._cctvFrame.dataset.loading = 'true';
|
||||
expect('FRAME · LOADING', 'loading');
|
||||
controls._cctvFrame.dataset.loading = '';
|
||||
controls._cctvFrame.dataset.error = 'true';
|
||||
expect('FRAME · UNAVAILABLE', 'error');
|
||||
// A refresh failure keeps the settled pixels and the provider's source status.
|
||||
controls._cctvFrameWrap.classList.toggle('has-frame', true);
|
||||
expect('SNAPSHOT · DEGRADED', 'ready');
|
||||
controls._cctvFrame.dataset.loading = 'true';
|
||||
expect('SNAPSHOT · DEGRADED', 'ready');
|
||||
controls._cctvFrame.dataset.loading = '';
|
||||
controls._cctvFrame.dataset.error = '';
|
||||
for (const status of ['ok', 'error', 'unknown', 'vendor-specific']) {
|
||||
expect(`SNAPSHOT · ${status.toUpperCase()}`, 'ready', {
|
||||
...camera,
|
||||
sourceStatus: status,
|
||||
});
|
||||
}
|
||||
expect('LIVE · OK', 'ready', { feedType: 'live', sourceStatus: 'ok' });
|
||||
});
|
||||
|
||||
test('calibration labels follow supplied provenance and dirty/save/reset transitions without writes to the camera', (testContext) => {
|
||||
const { controls } = fixture(testContext);
|
||||
const cases = [
|
||||
['raw-prior', false, 'CAL · RAW PRIOR'],
|
||||
['curated', false, 'CAL · CURATED'],
|
||||
['curated', true, 'CAL · EDITED (UNSAVED)'],
|
||||
['calibrated', false, 'CAL · CALIBRATED'],
|
||||
['calibrated', true, 'CAL · EDITED (UNSAVED)'],
|
||||
['raw-prior', false, 'CAL · RAW PRIOR'],
|
||||
[null, false, 'CAL · --'],
|
||||
];
|
||||
for (const [calBadge, calDirty, label] of cases) {
|
||||
const activeCamera = Object.freeze({ id: 'a', calBadge, calDirty });
|
||||
controls._renderCctvState({
|
||||
enabled: true,
|
||||
activeCameraId: 'a',
|
||||
activeCamera,
|
||||
});
|
||||
assert.equal(controls._cctvQualityChip.textContent, label);
|
||||
assert.equal(
|
||||
controls._cctvQualityChip.dataset.calBadge,
|
||||
calDirty ? 'edited' : calBadge || '',
|
||||
);
|
||||
}
|
||||
controls._renderCctvState(null);
|
||||
assert.equal(controls._cctvQualityChip.textContent, 'CAL · --');
|
||||
assert.equal(controls._cctvQualityChip.dataset.calBadge, '');
|
||||
});
|
||||
|
||||
test('localization changes badge copy while preserving machine state ids', (testContext) => {
|
||||
const { controls } = fixture(testContext);
|
||||
testContext.after(() => setLocale('en'));
|
||||
setLocale('ru');
|
||||
controls._syncCctvSourceBadge(
|
||||
{ sourceKind: 'snapshot', sourceStatus: 'degraded' },
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
controls._cctvSourceBadge.textContent,
|
||||
`${t('SNAPSHOT')} · ${t('DEGRADED')}`,
|
||||
);
|
||||
assert.notEqual(controls._cctvSourceBadge.textContent, 'SNAPSHOT · DEGRADED');
|
||||
assert.equal(controls._cctvSourceBadge.dataset.frameState, 'ready');
|
||||
controls._renderCctvState({
|
||||
enabled: true,
|
||||
activeCameraId: 'a',
|
||||
activeCamera: { id: 'a', calBadge: 'curated', calDirty: true },
|
||||
});
|
||||
assert.equal(
|
||||
controls._cctvQualityChip.textContent,
|
||||
t('CAL · EDITED (UNSAVED)'),
|
||||
);
|
||||
assert.equal(controls._cctvQualityChip.dataset.calBadge, 'edited');
|
||||
});
|
||||
@@ -1,3 +1,5 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
|
||||
export function _initCctvPanel() {
|
||||
if (!this._cctvPanel) return;
|
||||
|
||||
@@ -143,7 +145,7 @@ export function _initCctvPanel() {
|
||||
},
|
||||
{ origin: 'user' },
|
||||
);
|
||||
this.actions.showToast('CCTV calibration saved');
|
||||
this.actions.showToast(t('CCTV calibration saved'));
|
||||
});
|
||||
|
||||
this.listen(this._cctvCalibResetBtn, 'click', () => {
|
||||
|
||||
+42
-17
@@ -1,3 +1,6 @@
|
||||
import { formatNumber, t, msg } from '../i18n/index.js';
|
||||
import { createNumberInput } from './formField.js';
|
||||
|
||||
/** Shortest-wrap signed degrees, for heading offsets typed as absolute values. */
|
||||
const signedNormalizeDeg = (deg) => ((((deg + 180) % 360) + 360) % 360) - 180;
|
||||
|
||||
@@ -10,7 +13,7 @@ const signedNormalizeDeg = (deg) => ((((deg + 180) % 360) + 360) % 360) - 180;
|
||||
*/
|
||||
const CCTV_CAL_FIELDS = {
|
||||
heading: {
|
||||
label: 'HDG',
|
||||
label: msg('HDG'),
|
||||
unit: '°',
|
||||
decimals: 1,
|
||||
get: (cam) => cam.headingDeg,
|
||||
@@ -19,21 +22,21 @@ const CCTV_CAL_FIELDS = {
|
||||
}),
|
||||
},
|
||||
pitch: {
|
||||
label: 'PITCH',
|
||||
label: msg('PITCH'),
|
||||
unit: '°',
|
||||
decimals: 1,
|
||||
get: (cam) => cam.pitchDeg,
|
||||
toPatch: (value, base) => ({ pitchDeg: value - base.pitchDeg }),
|
||||
},
|
||||
fov: {
|
||||
label: 'FOV',
|
||||
label: msg('FOV'),
|
||||
unit: '°',
|
||||
decimals: 0,
|
||||
get: (cam) => cam.fovDeg,
|
||||
toPatch: (value, base) => ({ fovDeg: value - base.fovDeg }),
|
||||
},
|
||||
range: {
|
||||
label: 'RANGE',
|
||||
label: msg('RANGE'),
|
||||
unit: 'm',
|
||||
decimals: 0,
|
||||
get: (cam) => cam.rangeM,
|
||||
@@ -42,21 +45,21 @@ const CCTV_CAL_FIELDS = {
|
||||
}),
|
||||
},
|
||||
height: {
|
||||
label: 'HGT',
|
||||
label: msg('HGT'),
|
||||
unit: 'm',
|
||||
decimals: 0,
|
||||
get: (cam) => cam.mountHeightM,
|
||||
toPatch: (value, base) => ({ heightM: value - base.mountHeightM }),
|
||||
},
|
||||
north: {
|
||||
label: 'ΔN',
|
||||
label: msg('ΔN'),
|
||||
unit: 'm',
|
||||
decimals: 1,
|
||||
get: (cam) => cam.calibration?.offsetNorthM || 0,
|
||||
toPatch: (value) => ({ offsetNorthM: value }),
|
||||
},
|
||||
east: {
|
||||
label: 'ΔE',
|
||||
label: msg('ΔE'),
|
||||
unit: 'm',
|
||||
decimals: 1,
|
||||
get: (cam) => cam.calibration?.offsetEastM || 0,
|
||||
@@ -64,6 +67,27 @@ const CCTV_CAL_FIELDS = {
|
||||
},
|
||||
};
|
||||
|
||||
/** Chip text for one pose value: locale decimals, translated metre unit. */
|
||||
function calValueText(field, value) {
|
||||
const options = {
|
||||
minimumFractionDigits: field.decimals,
|
||||
maximumFractionDigits: field.decimals,
|
||||
};
|
||||
if (field.unit === 'm') {
|
||||
// English keeps its compact "RANGE 120m"; other languages space the unit.
|
||||
const metres = formatNumber(Number(value), {
|
||||
useGrouping: false,
|
||||
...options,
|
||||
});
|
||||
return `${t(field.label)} ${t('{value}m', { value: metres })}`;
|
||||
}
|
||||
const number = formatNumber(Number(value), {
|
||||
useGrouping: false,
|
||||
...options,
|
||||
});
|
||||
return `${t(field.label)} ${number}${field.unit}`;
|
||||
}
|
||||
|
||||
export function _activeCctvCameraId() {
|
||||
return this._cctvState?.activeCameraId || this._cctvSelect?.value || '';
|
||||
}
|
||||
@@ -81,7 +105,7 @@ export function _resetCctvCalibration() {
|
||||
},
|
||||
{ origin: 'user' },
|
||||
);
|
||||
this.actions.showToast('CCTV calibration reset');
|
||||
this.actions.showToast(t('CCTV calibration reset'));
|
||||
}
|
||||
|
||||
export function _beginCctvCalValueEdit(chip) {
|
||||
@@ -94,12 +118,13 @@ export function _beginCctvCalValueEdit(chip) {
|
||||
const basePose = { ...activeCamera.basePose };
|
||||
const editListeners = new AbortController();
|
||||
const startValue = field.get(activeCamera);
|
||||
const input = document.createElement('input');
|
||||
input.type = 'number';
|
||||
input.step = field.decimals > 0 ? '0.1' : '1';
|
||||
input.value = Number(startValue).toFixed(field.decimals);
|
||||
input.className = 'cctv-cal-input';
|
||||
chip.textContent = `${field.label} `;
|
||||
const input = createNumberInput({
|
||||
className: 'gev-field--inline cctv-cal-input',
|
||||
step: field.decimals > 0 ? '0.1' : '1',
|
||||
value: Number(startValue).toFixed(field.decimals),
|
||||
ariaLabel: t(field.label),
|
||||
});
|
||||
chip.textContent = `${t(field.label)} `;
|
||||
chip.appendChild(input);
|
||||
input.focus();
|
||||
input.select();
|
||||
@@ -162,7 +187,7 @@ export function _syncCctvCalReadout(enabled, activeCamera) {
|
||||
if (this._cctvAdjustBtn) {
|
||||
const adjustOn = !!this._cctvState?.calibrationMode;
|
||||
this._cctvAdjustBtn.classList.toggle('active', adjustOn && canCalibrate);
|
||||
this._cctvAdjustBtn.textContent = adjustOn ? 'ADJUST ON' : 'ADJUST';
|
||||
this._cctvAdjustBtn.textContent = adjustOn ? t('ADJUST ON') : t('ADJUST');
|
||||
this._cctvAdjustBtn.disabled = !canCalibrate;
|
||||
}
|
||||
if (this._cctvCalReadout) {
|
||||
@@ -174,8 +199,8 @@ export function _syncCctvCalReadout(enabled, activeCamera) {
|
||||
if (!field) continue;
|
||||
const value = canCalibrate ? field.get(activeCamera) : null;
|
||||
chip.textContent = Number.isFinite(value)
|
||||
? `${field.label} ${Number(value).toFixed(field.decimals)}${field.unit}`
|
||||
: `${field.label} --`;
|
||||
? calValueText(field, value)
|
||||
: `${t(field.label)} --`;
|
||||
chip.disabled = !canCalibrate;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,6 +105,9 @@ function calibrationFixture(t) {
|
||||
Object.assign(input, {
|
||||
focus() {},
|
||||
select() {},
|
||||
setAttribute(name, value) {
|
||||
this[name] = value;
|
||||
},
|
||||
remove() {
|
||||
this.parent.input = null;
|
||||
},
|
||||
|
||||
+89
-7
@@ -1,3 +1,83 @@
|
||||
import { updateStatusBadge } from './statusBadge.js';
|
||||
import { msg, t } from '../i18n/index.js';
|
||||
|
||||
/**
|
||||
* Display text for the CCTV source health the server reports
|
||||
* (server/providers/cctv.js `setHealth`). The server keeps its English codes
|
||||
* and messages; the panel translates them where it renders.
|
||||
*/
|
||||
|
||||
const SOURCE_KIND_LABELS = Object.freeze({
|
||||
snapshot: msg('SNAPSHOT'),
|
||||
live: msg('LIVE'),
|
||||
fallback: msg('FALLBACK'),
|
||||
upstream: msg('UPSTREAM'),
|
||||
synthetic: msg('SYNTHETIC'),
|
||||
configured: msg('CONFIGURED'),
|
||||
seed: msg('SEED'),
|
||||
image: msg('IMAGE'),
|
||||
unknown: msg('UNKNOWN'),
|
||||
});
|
||||
|
||||
const SOURCE_STATUS_LABELS = Object.freeze({
|
||||
ok: msg('OK'),
|
||||
degraded: msg('DEGRADED'),
|
||||
error: msg('ERROR'),
|
||||
unknown: msg('UNKNOWN'),
|
||||
});
|
||||
|
||||
const SOURCE_MESSAGES = Object.freeze({
|
||||
'Live HLS connected': msg('Live HLS connected'),
|
||||
'Live HLS unavailable': msg('Live HLS unavailable'),
|
||||
'No stream URL configured': msg('No stream URL configured'),
|
||||
'Live stream connected': msg('Live stream connected'),
|
||||
'Snapshot feed connected': msg('Snapshot feed connected'),
|
||||
'Media fetch failed': msg('Media fetch failed'),
|
||||
'Upstream snapshot active': msg('Upstream snapshot active'),
|
||||
'Fallback Street View frame': msg('Fallback Street View frame'),
|
||||
'Upstream unavailable': msg('Upstream unavailable'),
|
||||
'No source configured': msg('No source configured'),
|
||||
});
|
||||
|
||||
const SOURCE_LABELS = Object.freeze({
|
||||
'Configured source': msg('Configured source'),
|
||||
'Configured Source': msg('Configured Source'),
|
||||
'Synthetic fallback': msg('Synthetic fallback'),
|
||||
});
|
||||
|
||||
/** "SNAPSHOT" / "СНИМОК"; unknown codes (HLS, MJPEG…) stay as uppercase codes. */
|
||||
function cctvSourceKindLabel(kind) {
|
||||
const key = String(kind || 'unknown').toLowerCase();
|
||||
return SOURCE_KIND_LABELS[key]
|
||||
? t(SOURCE_KIND_LABELS[key])
|
||||
: key.toUpperCase();
|
||||
}
|
||||
|
||||
/** "DEGRADED" / "ПЕРЕБОИ"; unknown codes stay as uppercase codes. */
|
||||
export function cctvSourceStatusLabel(status) {
|
||||
const key = String(status || 'unknown').toLowerCase();
|
||||
return SOURCE_STATUS_LABELS[key]
|
||||
? t(SOURCE_STATUS_LABELS[key])
|
||||
: key.toUpperCase();
|
||||
}
|
||||
|
||||
/** A server health message in the page language; unknown text passes through. */
|
||||
export function cctvSourceMessageText(message) {
|
||||
const text = String(message || '');
|
||||
if (SOURCE_MESSAGES[text]) return t(SOURCE_MESSAGES[text]);
|
||||
const http = /^Upstream HTTP (\d{3})$/.exec(text);
|
||||
if (http) return t('Upstream HTTP {status}', { status: http[1] });
|
||||
const media = /^Unexpected media type (.+)$/.exec(text);
|
||||
if (media) return t('Unexpected media type {type}', { type: media[1] });
|
||||
return text;
|
||||
}
|
||||
|
||||
/** A generic provider label from the server; real provider names pass through. */
|
||||
export function cctvSourceLabelText(label) {
|
||||
const text = String(label || '');
|
||||
return SOURCE_LABELS[text] ? t(SOURCE_LABELS[text]) : text;
|
||||
}
|
||||
|
||||
export function _clearCctvFrame() {
|
||||
this._cctvFrameRequestToken += 1;
|
||||
if (this._cctvFramePreloader) {
|
||||
@@ -86,26 +166,28 @@ export function _settleCctvFrame(token, src, ok) {
|
||||
export function _syncCctvSourceBadge(activeCamera, enabled) {
|
||||
if (!this._cctvSourceBadge) return;
|
||||
if (!enabled || !activeCamera) {
|
||||
this._cctvSourceBadge.textContent = 'SOURCE · UNKNOWN';
|
||||
updateStatusBadge(this._cctvSourceBadge, { label: t('SOURCE · UNKNOWN') });
|
||||
this._cctvSourceBadge.dataset.frameState = 'idle';
|
||||
return;
|
||||
}
|
||||
const hasDisplayedFrame =
|
||||
this._cctvFrameWrap?.classList.contains('has-frame');
|
||||
if (this._cctvFrame?.dataset.loading === 'true' && !hasDisplayedFrame) {
|
||||
this._cctvSourceBadge.textContent = 'FRAME · LOADING';
|
||||
updateStatusBadge(this._cctvSourceBadge, { label: t('FRAME · LOADING') });
|
||||
this._cctvSourceBadge.dataset.frameState = 'loading';
|
||||
return;
|
||||
}
|
||||
if (this._cctvFrame?.dataset.error === 'true' && !hasDisplayedFrame) {
|
||||
this._cctvSourceBadge.textContent = 'FRAME · UNAVAILABLE';
|
||||
updateStatusBadge(this._cctvSourceBadge, {
|
||||
label: t('FRAME · UNAVAILABLE'),
|
||||
});
|
||||
this._cctvSourceBadge.dataset.frameState = 'error';
|
||||
return;
|
||||
}
|
||||
const kind = String(
|
||||
const kind = cctvSourceKindLabel(
|
||||
activeCamera.sourceKind || activeCamera.feedType || 'unknown',
|
||||
).toUpperCase();
|
||||
const status = String(activeCamera.sourceStatus || 'unknown').toUpperCase();
|
||||
this._cctvSourceBadge.textContent = `${kind} · ${status}`;
|
||||
);
|
||||
const status = cctvSourceStatusLabel(activeCamera.sourceStatus || 'unknown');
|
||||
updateStatusBadge(this._cctvSourceBadge, { label: `${kind} · ${status}` });
|
||||
this._cctvSourceBadge.dataset.frameState = 'ready';
|
||||
}
|
||||
+60
-26
@@ -1,12 +1,16 @@
|
||||
import { updateStatusBadge } from './statusBadge.js';
|
||||
import { t, tn } from '../i18n/index.js';
|
||||
import { cctvSourceLabelText, cctvSourceMessageText } from './cctvFrames.js';
|
||||
|
||||
import { createCctvVideoSurface } from './cctvVideo.js';
|
||||
export function _calBadgeLabel(badge) {
|
||||
switch (badge) {
|
||||
case 'calibrated':
|
||||
return 'CALIBRATED';
|
||||
return t('CALIBRATED');
|
||||
case 'curated':
|
||||
return 'CURATED';
|
||||
return t('CURATED');
|
||||
case 'raw-prior':
|
||||
return 'RAW PRIOR';
|
||||
return t('RAW PRIOR');
|
||||
default:
|
||||
return '--';
|
||||
}
|
||||
@@ -51,7 +55,7 @@ export function _renderCctvState(state) {
|
||||
|
||||
if (this._cctvEnableBtn) {
|
||||
this._cctvEnableBtn.classList.toggle('active', enabled);
|
||||
this._cctvEnableBtn.textContent = enabled ? 'CCTV ON' : 'CCTV OFF';
|
||||
this._cctvEnableBtn.textContent = enabled ? t('CCTV ON') : t('CCTV OFF');
|
||||
}
|
||||
|
||||
if (this._cctvSelect) {
|
||||
@@ -99,17 +103,19 @@ export function _renderCctvState(state) {
|
||||
this._cctvCoverageBtn.classList.toggle('active', mode !== 'off');
|
||||
this._cctvCoverageBtn.textContent =
|
||||
mode === 'viewshed'
|
||||
? 'VIEWSHED ON'
|
||||
? t('VIEWSHED ON')
|
||||
: mode === 'on'
|
||||
? 'COVERAGE ON'
|
||||
: 'COVERAGE OFF';
|
||||
? t('COVERAGE ON')
|
||||
: t('COVERAGE OFF');
|
||||
this._cctvCoverageBtn.disabled = !enabled;
|
||||
}
|
||||
|
||||
if (this._cctvAutoHopBtn) {
|
||||
const autoHop = !!state?.autoHop;
|
||||
this._cctvAutoHopBtn.classList.toggle('active', autoHop);
|
||||
this._cctvAutoHopBtn.textContent = autoHop ? 'AUTO HOP ON' : 'AUTO HOP OFF';
|
||||
this._cctvAutoHopBtn.textContent = autoHop
|
||||
? t('AUTO HOP ON')
|
||||
: t('AUTO HOP OFF');
|
||||
this._cctvAutoHopBtn.disabled = !enabled;
|
||||
}
|
||||
|
||||
@@ -117,8 +123,8 @@ export function _renderCctvState(state) {
|
||||
const showProjection = state?.showProjection !== false;
|
||||
this._cctvProjectionBtn.classList.toggle('active', showProjection);
|
||||
this._cctvProjectionBtn.textContent = showProjection
|
||||
? 'PROJECTION ON'
|
||||
: 'PROJECTION OFF';
|
||||
? t('PROJECTION ON')
|
||||
: t('PROJECTION OFF');
|
||||
this._cctvProjectionBtn.disabled = !enabled;
|
||||
}
|
||||
|
||||
@@ -132,9 +138,13 @@ export function _renderCctvState(state) {
|
||||
// promotes to CALIBRATED, RESET CAL clears.
|
||||
const badge = activeCamera?.calBadge || null;
|
||||
const dirty = !!activeCamera?.calDirty;
|
||||
this._cctvQualityChip.textContent = dirty
|
||||
? 'CAL · EDITED (UNSAVED)'
|
||||
: `CAL · ${this._calBadgeLabel(badge)}`;
|
||||
updateStatusBadge(this._cctvQualityChip, {
|
||||
label: dirty
|
||||
? t('CAL · EDITED (UNSAVED)')
|
||||
: t('CAL · {badge}', {
|
||||
badge: this._calBadgeLabel(badge),
|
||||
}),
|
||||
});
|
||||
this._cctvQualityChip.dataset.calBadge = dirty ? 'edited' : badge || '';
|
||||
}
|
||||
|
||||
@@ -142,26 +152,50 @@ export function _renderCctvState(state) {
|
||||
|
||||
if (this._cctvMeta) {
|
||||
if (activeCamera) {
|
||||
const provider =
|
||||
const provider = cctvSourceLabelText(
|
||||
activeCamera.sourceLabel ||
|
||||
activeCamera.provider ||
|
||||
'Configured Source';
|
||||
activeCamera.provider ||
|
||||
'Configured Source',
|
||||
);
|
||||
const statusMsg = activeCamera.sourceMessage
|
||||
? ` · ${activeCamera.sourceMessage}`
|
||||
? ` · ${cctvSourceMessageText(activeCamera.sourceMessage)}`
|
||||
: '';
|
||||
// A partner-supplied feed inside a pack names its owner here.
|
||||
const credit = activeCamera.credit ? ` · ${activeCamera.credit}` : '';
|
||||
const calBadge = activeCamera.calBadge
|
||||
? this._calBadgeLabel(activeCamera.calBadge)
|
||||
: '';
|
||||
const projLabel = state?.showProjection !== false ? 'MONITOR' : 'OFF';
|
||||
this._cctvMeta.textContent = `${activeCamera.city} · HDG ${Math.round(activeCamera.headingDeg)}° · FOV ${Math.round(activeCamera.fovDeg)}° · RANGE ${Math.round(activeCamera.rangeM)}m · ${projLabel}${calBadge ? ` · ${calBadge}` : ''} · ${provider}${credit}${statusMsg}`;
|
||||
const projLabel =
|
||||
state?.showProjection !== false ? t('MONITOR') : t('OFF');
|
||||
this._cctvMeta.textContent = t(
|
||||
'{city} · HDG {heading} · FOV {fov} · RANGE {range}m · {projection}{calBadge} · {provider}{status}',
|
||||
{
|
||||
city: activeCamera.city,
|
||||
heading: `${Math.round(activeCamera.headingDeg)}°`,
|
||||
fov: `${Math.round(activeCamera.fovDeg)}°`,
|
||||
range: Math.round(activeCamera.rangeM),
|
||||
projection: projLabel,
|
||||
calBadge: calBadge ? ` · ${calBadge}` : '',
|
||||
provider,
|
||||
status: `${credit}${statusMsg}`,
|
||||
},
|
||||
);
|
||||
} else if (cameras.length > 0) {
|
||||
this._cctvMeta.textContent = enabled
|
||||
? `${cameras.length} cameras loaded · click a camera to activate`
|
||||
: `${cameras.length} cameras loaded · enable CCTV to activate`;
|
||||
? tn(
|
||||
cameras.length,
|
||||
'{count} camera loaded · click a camera to activate',
|
||||
'{count} cameras loaded · click a camera to activate',
|
||||
)
|
||||
: tn(
|
||||
cameras.length,
|
||||
'{count} camera loaded · enable CCTV to activate',
|
||||
'{count} cameras loaded · enable CCTV to activate',
|
||||
);
|
||||
} else {
|
||||
this._cctvMeta.textContent = 'Enable CCTV to load camera intersections';
|
||||
this._cctvMeta.textContent = t(
|
||||
'Enable CCTV to load camera intersections',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -211,13 +245,13 @@ export function _renderCctvState(state) {
|
||||
this._syncCctvSourceBadge(activeCamera, enabled);
|
||||
this._typeCctvSummary(
|
||||
state?.summary ||
|
||||
'Enable CCTV to start camera-linked intelligence summaries.',
|
||||
t('Enable CCTV to start camera-linked intelligence summaries.'),
|
||||
);
|
||||
}
|
||||
|
||||
export function _typeCctvSummary(text) {
|
||||
if (this.destroyed || !this._cctvSummary) return;
|
||||
const nextText = String(text || '').trim() || 'No summary available.';
|
||||
const nextText = String(text || '').trim() || t('No summary available.');
|
||||
if (nextText === this._lastCctvSummaryText) return;
|
||||
this._lastCctvSummaryText = nextText;
|
||||
|
||||
@@ -249,7 +283,7 @@ export function _updateCctvSyncChip(loading, enabled) {
|
||||
clearTimeout(this._cctvChipHideTimer);
|
||||
this._cctvChipHideTimer = null;
|
||||
this._cctvChipWasBusy = true;
|
||||
this.actions.setSplitFlapText(this._cctvSyncLabel, 'loading frames');
|
||||
this.actions.setSplitFlapText(this._cctvSyncLabel, t('loading frames'));
|
||||
// The counter is left plain on purpose: it ticks every few frames
|
||||
// during a grid load, and flapping it would read as a slot machine.
|
||||
this._cctvSyncProgress.textContent = `${loaded}/${total}`;
|
||||
@@ -260,7 +294,7 @@ export function _updateCctvSyncChip(loading, enabled) {
|
||||
if (this._cctvChipWasBusy && enabled && total > 0) {
|
||||
// Load just completed — flash the final count, then auto-hide.
|
||||
this._cctvChipWasBusy = false;
|
||||
this.actions.setSplitFlapText(this._cctvSyncLabel, 'camera grid ready');
|
||||
this.actions.setSplitFlapText(this._cctvSyncLabel, t('camera grid ready'));
|
||||
this._cctvSyncProgress.textContent = `${total}/${total}`;
|
||||
this._cctvSyncChip.classList.add('visible');
|
||||
clearTimeout(this._cctvChipHideTimer);
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
|
||||
/** Keep the clear action focusable while busy; the caller owns its transaction. */
|
||||
export function bindClearLayersControl(button, clear) {
|
||||
let destroyed = false;
|
||||
@@ -12,7 +14,9 @@ export function bindClearLayersControl(button, clear) {
|
||||
button.setAttribute('aria-busy', String(busy));
|
||||
button.setAttribute(
|
||||
'aria-label',
|
||||
busy ? 'Clearing selected data layers' : 'Clear selected data layers',
|
||||
busy
|
||||
? t('Clearing selected data layers')
|
||||
: t('Clear selected data layers'),
|
||||
);
|
||||
},
|
||||
destroy() {
|
||||
|
||||
+75
-23
@@ -1,4 +1,5 @@
|
||||
/** Regional briefing requests, pages and rotation for the Cockpit controller. */
|
||||
import { formatNumber, t, msg } from '../i18n/index.js';
|
||||
import {
|
||||
COCKPIT_BRIEF_ROTATE_MS,
|
||||
COCKPIT_BRIEF_CYCLE_OFF_HELP,
|
||||
@@ -7,9 +8,27 @@ import {
|
||||
COCKPIT_REGIONAL_REFRESH_DISTANCE_M,
|
||||
COCKPIT_BRIEF_PAGES,
|
||||
formatCockpitBriefAge,
|
||||
formatCockpitCoordinate,
|
||||
formatCockpitWindDirection,
|
||||
} from './cockpitPresentation.js';
|
||||
|
||||
// regionalModel.weatherCodeLabel is shared with node code and returns
|
||||
// English; translate it here.
|
||||
const WEATHER_CONDITION_KEYS = Object.freeze({
|
||||
'CONDITIONS UNKNOWN': msg('CONDITIONS UNKNOWN'),
|
||||
CLEAR: msg('CLEAR'),
|
||||
'PARTLY CLOUDY': msg('PARTLY CLOUDY'),
|
||||
OVERCAST: msg('OVERCAST'),
|
||||
FOG: msg('FOG'),
|
||||
DRIZZLE: msg('DRIZZLE'),
|
||||
RAIN: msg('RAIN'),
|
||||
SNOW: msg('SNOW'),
|
||||
'RAIN SHOWERS': msg('RAIN SHOWERS'),
|
||||
'SNOW SHOWERS': msg('SNOW SHOWERS'),
|
||||
THUNDERSTORM: msg('THUNDERSTORM'),
|
||||
'MIXED CONDITIONS': msg('MIXED CONDITIONS'),
|
||||
});
|
||||
|
||||
export function showBriefPage(index, { manual = false } = {}) {
|
||||
if (this.destroyed) return;
|
||||
const count = COCKPIT_BRIEF_PAGES.length;
|
||||
@@ -26,15 +45,18 @@ export function showBriefPage(index, { manual = false } = {}) {
|
||||
if (this.briefKicker) {
|
||||
const indicator = this.briefKicker.querySelector('i');
|
||||
this.briefKicker.replaceChildren(
|
||||
...[indicator, document.createTextNode(` ${page.kicker}`)].filter(
|
||||
...[indicator, document.createTextNode(` ${t(page.kickerKey)}`)].filter(
|
||||
Boolean,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (this.briefSubtitle) this.briefSubtitle.textContent = page.subtitle;
|
||||
if (this.briefSubtitle) this.briefSubtitle.textContent = t(page.subtitleKey);
|
||||
if (this.briefPosition)
|
||||
this.briefPosition.textContent = `${this.briefPageIndex + 1} / ${count}`;
|
||||
if (this.briefSource) this.briefSource.textContent = page.source;
|
||||
if (this.briefSource)
|
||||
this.briefSource.textContent = page.sourceKey
|
||||
? t(page.sourceKey, { source: page.sourceName })
|
||||
: page.source;
|
||||
if (this.signalStream) this.signalStream.dataset.briefPage = page.id;
|
||||
if (manual && this.briefAutoRotateEnabled)
|
||||
this.startBriefRotation({ reset: true });
|
||||
@@ -56,6 +78,22 @@ export function setBriefAutoRotate(enabled) {
|
||||
: COCKPIT_BRIEF_CYCLE_OFF_HELP;
|
||||
this.briefAutoToggle.setAttribute('aria-label', label);
|
||||
this.briefAutoToggle.title = help;
|
||||
// cockpitMarkup.test.mjs pins the English writes above; these translate
|
||||
// them.
|
||||
const labelKey = this.briefAutoRotateEnabled
|
||||
? msg('CYCLE ON')
|
||||
: msg('CYCLE OFF');
|
||||
this.briefAutoToggle.textContent = t(labelKey);
|
||||
this.briefAutoToggle.setAttribute('aria-label', t(labelKey));
|
||||
this.briefAutoToggle.title = t(
|
||||
this.briefAutoRotateEnabled
|
||||
? msg(
|
||||
'Stop automatic page cycling. Previous, Next, and the SIG/NEWS/LOCAL tabs stay available.',
|
||||
)
|
||||
: msg(
|
||||
'Cycle briefing pages automatically every 9 seconds (Signals → News → Local). Pauses while you hover or focus the panel. Live signal data refreshes continuously either way.',
|
||||
),
|
||||
);
|
||||
}
|
||||
if (this.briefAutoRotateEnabled) this.startBriefRotation({ reset: true });
|
||||
else this.stopBriefRotation();
|
||||
@@ -94,11 +132,11 @@ export function stopBriefRotation() {
|
||||
export function updateLocalPosition(info) {
|
||||
if (!this.localCoordinates) return;
|
||||
if (!Number.isFinite(info.latitude) || !Number.isFinite(info.longitude)) {
|
||||
this.localCoordinates.textContent = 'POSITION UNAVAILABLE';
|
||||
this.localCoordinates.textContent = t('POSITION UNAVAILABLE');
|
||||
return;
|
||||
}
|
||||
const lat = `${Math.abs(info.latitude).toFixed(3)}°${info.latitude >= 0 ? 'N' : 'S'}`;
|
||||
const lon = `${Math.abs(info.longitude).toFixed(3)}°${info.longitude >= 0 ? 'E' : 'W'}`;
|
||||
const lat = formatCockpitCoordinate(info.latitude, 'N', 'S');
|
||||
const lon = formatCockpitCoordinate(info.longitude, 'E', 'W');
|
||||
this.localCoordinates.textContent = `${lat} · ${lon}`;
|
||||
}
|
||||
|
||||
@@ -175,14 +213,14 @@ export function renderRegionalBriefStatus(status, info) {
|
||||
this.newsStatus.dataset.state = status;
|
||||
this.newsStatus.textContent =
|
||||
status === 'loading'
|
||||
? 'ACQUIRING REGIONAL NEWS'
|
||||
: 'REGIONAL NEWS UNAVAILABLE';
|
||||
? t('ACQUIRING REGIONAL NEWS')
|
||||
: t('REGIONAL NEWS UNAVAILABLE');
|
||||
}
|
||||
if (status === 'unavailable') this.newsList?.replaceChildren();
|
||||
if (this.localPlace && status === 'loading')
|
||||
this.localPlace.textContent = 'RESOLVING REGION';
|
||||
this.localPlace.textContent = t('RESOLVING REGION');
|
||||
if (this.localPlace && status === 'unavailable')
|
||||
this.localPlace.textContent = 'REGION UNAVAILABLE';
|
||||
this.localPlace.textContent = t('REGION UNAVAILABLE');
|
||||
this.updateLocalPosition(info);
|
||||
}
|
||||
|
||||
@@ -193,8 +231,8 @@ export function renderRegionalBrief(payload, info) {
|
||||
this.newsStatus.dataset.state = payload?.newsStatus || 'unavailable';
|
||||
this.newsStatus.textContent =
|
||||
payload?.newsStatus === 'empty'
|
||||
? 'NO RECENT LOCATION MATCHES'
|
||||
: 'REGIONAL NEWS UNAVAILABLE';
|
||||
? t('NO RECENT LOCATION MATCHES')
|
||||
: t('REGIONAL NEWS UNAVAILABLE');
|
||||
}
|
||||
if (this.newsList) {
|
||||
this.newsList.replaceChildren(
|
||||
@@ -207,7 +245,10 @@ export function renderRegionalBrief(payload, info) {
|
||||
const title = document.createElement('strong');
|
||||
title.textContent = article.title;
|
||||
const metadata = document.createElement('span');
|
||||
metadata.textContent = `${article.domain || 'SOURCE'} · ${formatCockpitBriefAge(article.publishedAt)}`;
|
||||
metadata.textContent = t('{domain} · {age}', {
|
||||
domain: article.domain || t('SOURCE'),
|
||||
age: formatCockpitBriefAge(article.publishedAt),
|
||||
});
|
||||
link.append(title, metadata);
|
||||
entry.append(link);
|
||||
return entry;
|
||||
@@ -216,7 +257,7 @@ export function renderRegionalBrief(payload, info) {
|
||||
}
|
||||
|
||||
const placeLabel =
|
||||
payload?.place?.label || payload?.place?.country || 'REGION UNAVAILABLE';
|
||||
payload?.place?.label || payload?.place?.country || t('REGION UNAVAILABLE');
|
||||
if (this.localPlace) this.localPlace.textContent = placeLabel.toUpperCase();
|
||||
this.updateLocalPosition(info);
|
||||
const weather = payload?.weather;
|
||||
@@ -227,7 +268,7 @@ export function renderRegionalBrief(payload, info) {
|
||||
}
|
||||
if (this.localWind) {
|
||||
this.localWind.textContent = Number.isFinite(weather?.windKph)
|
||||
? `${Math.round(weather.windKph)} KM/H`
|
||||
? t('{value} KM/H', { value: Math.round(weather.windKph) })
|
||||
: '—';
|
||||
}
|
||||
if (this.localWindDirection) {
|
||||
@@ -235,26 +276,37 @@ export function renderRegionalBrief(payload, info) {
|
||||
weather?.windDirectionDeg,
|
||||
);
|
||||
}
|
||||
if (this.localCondition)
|
||||
this.localCondition.textContent = this.services.weatherCodeLabel(
|
||||
weather?.weatherCode,
|
||||
);
|
||||
if (this.localCondition) {
|
||||
const condition = this.services.weatherCodeLabel(weather?.weatherCode);
|
||||
const conditionKey = WEATHER_CONDITION_KEYS[condition];
|
||||
this.localCondition.textContent = conditionKey
|
||||
? t(conditionKey)
|
||||
: condition;
|
||||
}
|
||||
if (this.localCloud) {
|
||||
this.localCloud.textContent = Number.isFinite(weather?.cloudCoverPct)
|
||||
? `CLOUD ${Math.round(weather.cloudCoverPct)}%`
|
||||
: 'CLOUD UNKNOWN';
|
||||
? t('CLOUD {pct}%', {
|
||||
pct: Math.round(weather.cloudCoverPct),
|
||||
})
|
||||
: t('CLOUD UNKNOWN');
|
||||
}
|
||||
if (this.localPrecipitation) {
|
||||
this.localPrecipitation.textContent = Number.isFinite(
|
||||
weather?.precipitationMm,
|
||||
)
|
||||
? weather.precipitationMm.toFixed(1)
|
||||
? formatNumber(weather.precipitationMm, {
|
||||
useGrouping: false,
|
||||
minimumFractionDigits: 1,
|
||||
maximumFractionDigits: 1,
|
||||
})
|
||||
: '—';
|
||||
}
|
||||
if (this.signalStream)
|
||||
this.signalStream.dataset.regionalStatus = payload?.status || 'partial';
|
||||
if (this.briefPageIndex === 1 && this.briefSource) {
|
||||
this.briefSource.textContent = `${String(payload?.newsSource || 'REGIONAL NEWS').toUpperCase()} · LOCATION QUERY`;
|
||||
this.briefSource.textContent = t('{source} · LOCATION QUERY', {
|
||||
source: String(payload?.newsSource || t('REGIONAL NEWS')).toUpperCase(),
|
||||
});
|
||||
}
|
||||
this.scheduleContextLayout();
|
||||
}
|
||||
+49
-17
@@ -1,11 +1,25 @@
|
||||
/** Contact readouts and nearby-signal presentation for the Cockpit controller. */
|
||||
import * as Cesium from 'cesium';
|
||||
import { formatNumber, getLocale, t, tn } from '../i18n/index.js';
|
||||
import { unitLabel } from './unitLabels.js';
|
||||
import {
|
||||
bearingBetweenCoordinates,
|
||||
formatCockpitContextScope,
|
||||
relativeBearing,
|
||||
resolveCockpitContextReadout,
|
||||
} from '../cockpitMath.js';
|
||||
import { formatCockpitDistance } from './cockpitPresentation.js';
|
||||
|
||||
/** The Context scope line in the active language (see cockpitMath.js). */
|
||||
const LOCALIZED_CONTEXT_SCOPE = Object.freeze({
|
||||
window: ({ label, radiusKm }) =>
|
||||
t('{label} · {radius} AIR/SEA WINDOW', {
|
||||
label,
|
||||
radius: `${radiusKm === null ? '—' : formatNumber(radiusKm)}\u00a0${getLocale() === 'zh-CN' ? unitLabel('km') : unitLabel('km').toUpperCase()}`,
|
||||
}),
|
||||
installations: ({ scope, coverage }) =>
|
||||
t('{scope} · INSTALLATIONS {coverage}', { scope, coverage }),
|
||||
});
|
||||
|
||||
export function updateContext(info, heading) {
|
||||
if (!this.context) return;
|
||||
@@ -20,8 +34,8 @@ export function updateContext(info, heading) {
|
||||
this.pushCockpitSignal(
|
||||
'context-status',
|
||||
'info',
|
||||
'CONTEXT STANDBY',
|
||||
'ENABLE GLOBAL CONTEXT FOR PROXIMITY PINGS',
|
||||
t('CONTEXT STANDBY'),
|
||||
t('ENABLE GLOBAL CONTEXT FOR PROXIMITY PINGS'),
|
||||
);
|
||||
return;
|
||||
}
|
||||
@@ -36,6 +50,7 @@ export function updateContext(info, heading) {
|
||||
snapshot.subject.label || trackedId,
|
||||
snapshot.radiusM,
|
||||
installationCoverage,
|
||||
LOCALIZED_CONTEXT_SCOPE,
|
||||
);
|
||||
}
|
||||
// Navigation stays wired in every state — the operator must always be able
|
||||
@@ -52,8 +67,9 @@ export function updateContext(info, heading) {
|
||||
const enteringLost = this.context.dataset.state !== 'lost';
|
||||
this.context.dataset.state = 'lost';
|
||||
if (this.contextUncertainty) {
|
||||
this.contextUncertainty.textContent =
|
||||
'CONTACT LOST · LAST KNOWN READOUT · NOT AN ALL-CLEAR';
|
||||
this.contextUncertainty.textContent = t(
|
||||
'CONTACT LOST · LAST KNOWN READOUT · NOT AN ALL-CLEAR',
|
||||
);
|
||||
}
|
||||
// The cue changes the footer's height; re-run layout once on the way in
|
||||
// rather than every frame the contact stays lost.
|
||||
@@ -61,8 +77,10 @@ export function updateContext(info, heading) {
|
||||
this.pushCockpitSignal(
|
||||
'context-status',
|
||||
'warning',
|
||||
`CONTACT LOST · ${snapshot.subject.label || snapshot.subject.id || 'SUBJECT'}`,
|
||||
'SUBJECT LEFT ITS FEED · READOUT HOLDING LAST KNOWN',
|
||||
t('CONTACT LOST · {subject}', {
|
||||
subject: snapshot.subject.label || snapshot.subject.id || 'SUBJECT',
|
||||
}),
|
||||
t('SUBJECT LEFT ITS FEED · READOUT HOLDING LAST KNOWN'),
|
||||
);
|
||||
return;
|
||||
}
|
||||
@@ -83,25 +101,30 @@ export function updateContext(info, heading) {
|
||||
const closestLabel = this.services.formatAwarenessLabel(closest);
|
||||
if (this.contextNearestLabel) {
|
||||
this.contextNearestLabel.textContent = closest
|
||||
? `${closest.cohort.label.toUpperCase()} · ${closestLabel}`
|
||||
: 'NO AVAILABLE EXAMPLE';
|
||||
? t('{cohort} · {contact}', {
|
||||
cohort: closest.cohort.label.toUpperCase(),
|
||||
contact: closestLabel,
|
||||
})
|
||||
: t('NO AVAILABLE EXAMPLE');
|
||||
this.contextNearestLabel.setAttribute(
|
||||
'aria-label',
|
||||
closest && closestLabel === '—'
|
||||
? `${closest.cohort.label}, Unavailable`
|
||||
? t('{cohort}, Unavailable', {
|
||||
cohort: closest.cohort.label,
|
||||
})
|
||||
: this.contextNearestLabel.textContent,
|
||||
);
|
||||
}
|
||||
if (this.contextDistance) {
|
||||
const distanceM = closest?.distanceM;
|
||||
this.contextDistance.textContent = Number.isFinite(distanceM)
|
||||
? `${distanceM < 10000 ? (distanceM / 1000).toFixed(1) : Math.round(distanceM / 1000)} KM`
|
||||
? formatCockpitDistance(distanceM)
|
||||
: '—';
|
||||
this.contextDistance.setAttribute(
|
||||
'aria-label',
|
||||
Number.isFinite(distanceM)
|
||||
? this.contextDistance.textContent
|
||||
: 'Unavailable',
|
||||
: t('Unavailable'),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -133,15 +156,24 @@ export function updateContext(info, heading) {
|
||||
this.contextDirection.classList.toggle('unknown', relative === null);
|
||||
}
|
||||
if (this.contextBearing) {
|
||||
if (relative === null) this.contextBearing.textContent = 'BRG —';
|
||||
else if (Math.abs(relative) < 8) this.contextBearing.textContent = 'AHEAD';
|
||||
else
|
||||
this.contextBearing.textContent = `${relative < 0 ? 'L' : 'R'} ${String(Math.round(Math.abs(relative))).padStart(3, '0')}°`;
|
||||
if (relative === null) this.contextBearing.textContent = t('BRG —');
|
||||
else if (Math.abs(relative) < 8)
|
||||
this.contextBearing.textContent = t('AHEAD');
|
||||
else {
|
||||
this.contextBearing.textContent = t('{side} {angle}', {
|
||||
side: relative < 0 ? t('L') : t('R'),
|
||||
angle: `${String(Math.round(Math.abs(relative))).padStart(3, '0')}°`,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (this.contextUncertainty) {
|
||||
this.contextUncertainty.textContent = unknownCount
|
||||
? `${unknownCount} INPUT${unknownCount === 1 ? '' : 'S'} UNKNOWN · NOT AN ALL-CLEAR`
|
||||
: 'AVAILABLE INPUTS CURRENT · NOT AN ALL-CLEAR';
|
||||
? tn(
|
||||
unknownCount,
|
||||
'{count} INPUT UNKNOWN · NOT AN ALL-CLEAR',
|
||||
'{count} INPUTS UNKNOWN · NOT AN ALL-CLEAR',
|
||||
)
|
||||
: t('AVAILABLE INPUTS CURRENT · NOT AN ALL-CLEAR');
|
||||
}
|
||||
if (this.contextUpdated) {
|
||||
this.contextUpdated.textContent = Number.isFinite(snapshot.evaluatedAt)
|
||||
|
||||
@@ -64,7 +64,8 @@ export function onKeyDown(event) {
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
if (!this.active && !this.isEntryAllowed()) return;
|
||||
const changed = this.active ? this.exit() : this.enter();
|
||||
if (this.active) this.exit();
|
||||
else this.enter();
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
/** Instrument values, routes and vision controls for the Cockpit controller. */
|
||||
import { formatNumber, t } from '../i18n/index.js';
|
||||
import {
|
||||
COCKPIT_VISION_MODES,
|
||||
normalizeCockpitVisionMode,
|
||||
@@ -12,6 +13,8 @@ import {
|
||||
compassDivisions,
|
||||
formatAltitudeRulerTick,
|
||||
formatCompassDivision,
|
||||
formatCockpitEmergency,
|
||||
formatHeadingReadout,
|
||||
formatSpeedRulerTick,
|
||||
normalizeHeading,
|
||||
relativeBearing,
|
||||
@@ -19,9 +22,27 @@ import {
|
||||
} from '../cockpitMath.js';
|
||||
import {
|
||||
COCKPIT_CONTEXT_UPDATE_MS,
|
||||
compassPointLabel,
|
||||
formatCockpitCoordinate,
|
||||
setCockpitRollingValue,
|
||||
} from './cockpitPresentation.js';
|
||||
|
||||
/** A transponder status name (src/data/aircraftEmergency.js) for the HUD. */
|
||||
const emergencyLabel = ({ name }) => t(name).toUpperCase();
|
||||
|
||||
/** The emergency line in the active language (see cockpitMath.js). */
|
||||
const LOCALIZED_EMERGENCY = Object.freeze({
|
||||
squawk: (parts) =>
|
||||
t('SQUAWK {code} · {status}', {
|
||||
code: parts.squawk,
|
||||
status: emergencyLabel(parts),
|
||||
}),
|
||||
adsb: (parts) =>
|
||||
parts.priority
|
||||
? t('ADS-B PRIORITY · {status}', { status: emergencyLabel(parts) })
|
||||
: t('ADS-B EMERGENCY · {status}', { status: emergencyLabel(parts) }),
|
||||
});
|
||||
|
||||
export function updateHud(
|
||||
info,
|
||||
nowMs = performance.now(),
|
||||
@@ -31,7 +52,7 @@ export function updateHud(
|
||||
const heading = normalizeHeading(this.heading ?? info.track ?? 0);
|
||||
if (this.callsign) {
|
||||
this.callsign.textContent =
|
||||
info.callsign || info.registration || info.icao24 || 'AIRCRAFT';
|
||||
info.callsign || info.registration || info.icao24 || t('AIRCRAFT');
|
||||
}
|
||||
const speedKt = Number.isFinite(info.velocityMps)
|
||||
? info.velocityMps * 1.94384
|
||||
@@ -66,7 +87,7 @@ export function updateHud(
|
||||
setCockpitRollingValue(
|
||||
this.altitude,
|
||||
displayedAltitudeFt !== null
|
||||
? displayedAltitudeFt.toLocaleString('en-US')
|
||||
? formatNumber(displayedAltitudeFt)
|
||||
: '-----',
|
||||
displayedAltitudeFt,
|
||||
{ immediate: forceContext },
|
||||
@@ -109,7 +130,7 @@ export function updateHud(
|
||||
this.compassTape.innerHTML = divisions
|
||||
.map((division, index) => {
|
||||
const slot = index - 3;
|
||||
return `<span class="${slot === 0 ? 'active' : ''}" style="--slot:${slot};--depth:${Math.abs(slot)}">${formatCompassDivision(division)}</span>`;
|
||||
return `<span class="${slot === 0 ? 'active' : ''}" style="--slot:${slot};--depth:${Math.abs(slot)}">${compassPointLabel(formatCompassDivision(division))}</span>`;
|
||||
})
|
||||
.join('');
|
||||
}
|
||||
@@ -118,22 +139,41 @@ export function updateHud(
|
||||
this.clock.textContent = new Date().toISOString().slice(11, 19) + 'Z';
|
||||
if (this.position) {
|
||||
const lat = Number.isFinite(info.latitude)
|
||||
? `${Math.abs(info.latitude).toFixed(3)}°${info.latitude >= 0 ? 'N' : 'S'}`
|
||||
? formatCockpitCoordinate(info.latitude, 'N', 'S')
|
||||
: '--';
|
||||
const lon = Number.isFinite(info.longitude)
|
||||
? `${Math.abs(info.longitude).toFixed(3)}°${info.longitude >= 0 ? 'E' : 'W'}`
|
||||
? formatCockpitCoordinate(info.longitude, 'E', 'W')
|
||||
: '--';
|
||||
this.position.textContent = `${lat} · ${lon}`;
|
||||
}
|
||||
if (this.aircraftMeta) {
|
||||
const feedState = this.surfaceAcquiring
|
||||
? 'ACQUIRING SURFACE'
|
||||
? t('ACQUIRING SURFACE')
|
||||
: this.surfaceFallback
|
||||
? 'SURFACE FALLBACK'
|
||||
? t('SURFACE FALLBACK')
|
||||
: info.stale
|
||||
? 'STALE FEED'
|
||||
: 'LIVE TRACK';
|
||||
this.aircraftMeta.textContent = `${info.layerId === 'military' ? 'MILITARY' : 'COMMERCIAL'} · ${feedState} · COURSE ALIGNED`;
|
||||
? t('STALE FEED')
|
||||
: t('LIVE TRACK');
|
||||
const aircraftClass =
|
||||
info.layerId === 'military' ? t('MILITARY') : t('COMMERCIAL');
|
||||
const emergency = formatCockpitEmergency(
|
||||
info.emergency,
|
||||
LOCALIZED_EMERGENCY,
|
||||
);
|
||||
this.aircraftMeta.textContent = emergency
|
||||
? t('{aircraftClass} · {emergency} · {feedState}', {
|
||||
aircraftClass,
|
||||
emergency,
|
||||
feedState,
|
||||
})
|
||||
: t('{aircraftClass} · {feedState} · COURSE ALIGNED', {
|
||||
aircraftClass,
|
||||
feedState,
|
||||
});
|
||||
this.aircraftMeta.classList.toggle(
|
||||
'emergency',
|
||||
info.emergency?.severity === 'emergency',
|
||||
);
|
||||
}
|
||||
this.updateRoute(info);
|
||||
if (
|
||||
@@ -158,13 +198,13 @@ export function updateRoute(info) {
|
||||
const validDestination =
|
||||
Number.isFinite(destination?.lat) && Number.isFinite(destination?.lon);
|
||||
const routeLabel = (airport) =>
|
||||
[airport?.code, airport?.name].filter(Boolean).join(' · ') || 'UNKNOWN';
|
||||
[airport?.code, airport?.name].filter(Boolean).join(' · ') || t('UNKNOWN');
|
||||
if (this.routeFrom) this.routeFrom.textContent = routeLabel(origin);
|
||||
if (this.routeTo) this.routeTo.textContent = routeLabel(destination);
|
||||
if (this.routeStatus) {
|
||||
this.routeStatus.textContent = validDestination
|
||||
? 'ARROW · ESTIMATED DIRECTION'
|
||||
: 'ROUTE DATA UNAVAILABLE';
|
||||
? t('ARROW · ESTIMATED DIRECTION')
|
||||
: t('ROUTE DATA UNAVAILABLE');
|
||||
}
|
||||
if (this.route) this.route.hidden = !origin && !destination;
|
||||
if (
|
||||
@@ -198,7 +238,9 @@ export function updateRoute(info) {
|
||||
);
|
||||
}
|
||||
if (this.routeDirectionLabel) {
|
||||
this.routeDirectionLabel.textContent = `DEST ${String(Math.round(destinationBearing)).padStart(3, '0')}°`;
|
||||
this.routeDirectionLabel.textContent = t('DEST {bearing}', {
|
||||
bearing: `${formatHeadingReadout(destinationBearing)}°`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -206,42 +248,48 @@ export function syncWeatherToggle(enabled) {
|
||||
if (!this.weatherToggle) return;
|
||||
const active = !!enabled;
|
||||
this.weatherToggle.setAttribute('aria-pressed', String(active));
|
||||
this.weatherToggle.setAttribute(
|
||||
'aria-label',
|
||||
`${active ? 'Disable' : 'Enable'} cockpit weather effects`,
|
||||
);
|
||||
this.weatherToggle.title = `${active ? 'Disable' : 'Enable'} cockpit weather effects`;
|
||||
if (this.weatherState) this.weatherState.textContent = active ? 'ON' : 'OFF';
|
||||
const weatherLabel = active
|
||||
? t('Disable cockpit weather effects')
|
||||
: t('Enable cockpit weather effects');
|
||||
this.weatherToggle.setAttribute('aria-label', weatherLabel);
|
||||
this.weatherToggle.title = weatherLabel;
|
||||
if (this.weatherState) {
|
||||
this.weatherState.textContent = active ? t('ON') : t('OFF');
|
||||
}
|
||||
}
|
||||
|
||||
export function setVisionMode(mode, { revealParameters = false } = {}) {
|
||||
const next = normalizeCockpitVisionMode(mode);
|
||||
this.visionMode = next;
|
||||
const labels = {
|
||||
optical: 'NORMAL',
|
||||
crt: 'CRT',
|
||||
nvg: 'NVG',
|
||||
thermal: 'FLIR',
|
||||
anime: 'ANIME',
|
||||
noir: 'NOIR',
|
||||
snow: 'SNOW',
|
||||
optical: t('NORMAL'),
|
||||
crt: t('CRT'),
|
||||
nvg: t('NVG'),
|
||||
thermal: t('FLIR'),
|
||||
anime: t('ANIME'),
|
||||
noir: t('NOIR'),
|
||||
snow: t('SNOW'),
|
||||
};
|
||||
const names = {
|
||||
optical: 'Normal',
|
||||
crt: 'CRT',
|
||||
nvg: 'Night vision',
|
||||
thermal: 'Thermal',
|
||||
anime: 'Anime',
|
||||
noir: 'Noir',
|
||||
snow: 'Snow',
|
||||
optical: t('Normal'),
|
||||
crt: t('CRT'),
|
||||
nvg: t('Night vision'),
|
||||
thermal: t('Thermal'),
|
||||
anime: t('Anime'),
|
||||
noir: t('Noir'),
|
||||
snow: t('Snow'),
|
||||
};
|
||||
if (this.visionCurrent) {
|
||||
this.visionCurrent.dataset.cockpitVision = next;
|
||||
this.visionCurrent.setAttribute(
|
||||
'aria-label',
|
||||
`Current cockpit vision style: ${names[next]}. Activate for next style.`,
|
||||
t('Current cockpit vision style: {style}. Activate for next style.', {
|
||||
style: names[next],
|
||||
}),
|
||||
);
|
||||
this.visionCurrent.title = `Current style: ${names[next]} — click for next`;
|
||||
this.visionCurrent.title = t('Current style: {style} — click for next', {
|
||||
style: names[next],
|
||||
});
|
||||
}
|
||||
if (this.visionCurrentLabel)
|
||||
this.visionCurrentLabel.textContent = labels[next];
|
||||
|
||||
+13
-4
@@ -1,4 +1,5 @@
|
||||
/** Measure Cockpit panels against visible HUD and viewport obstacles. */
|
||||
import { t, msg } from '../i18n/index.js';
|
||||
import {
|
||||
resolveCockpitUtilityAnchor,
|
||||
resolveCockpitUtilityLayout,
|
||||
@@ -37,9 +38,11 @@ export function setContextCollapsed(collapsed) {
|
||||
this.contextToggle.setAttribute('aria-expanded', String(expanded));
|
||||
this.contextToggle.setAttribute(
|
||||
'aria-label',
|
||||
`${expanded ? 'Collapse' : 'Expand'} Contact panel`,
|
||||
expanded ? t('Collapse Contact panel') : t('Expand Contact panel'),
|
||||
);
|
||||
this.contextToggle.title = t(
|
||||
expanded ? msg('Collapse contact panel') : msg('Expand contact panel'),
|
||||
);
|
||||
this.contextToggle.title = `${expanded ? 'Collapse' : 'Expand'} contact panel`;
|
||||
const icon = this.contextToggle.querySelector('.material-symbols-outlined');
|
||||
if (icon) icon.textContent = expanded ? 'chevron_left' : 'chevron_right';
|
||||
}
|
||||
@@ -60,9 +63,15 @@ export function setSignalCollapsed(collapsed, { user = false } = {}) {
|
||||
this.signalToggle.setAttribute('aria-expanded', String(expanded));
|
||||
this.signalToggle.setAttribute(
|
||||
'aria-label',
|
||||
`${expanded ? 'Collapse' : 'Expand'} cockpit briefing panel`,
|
||||
t(
|
||||
expanded
|
||||
? msg('Collapse cockpit briefing panel')
|
||||
: msg('Expand cockpit briefing panel'),
|
||||
),
|
||||
);
|
||||
this.signalToggle.title = t(
|
||||
expanded ? msg('Collapse briefing panel') : msg('Expand briefing panel'),
|
||||
);
|
||||
this.signalToggle.title = `${expanded ? 'Collapse' : 'Expand'} briefing panel`;
|
||||
const icon = this.signalToggle.querySelector('.material-symbols-outlined');
|
||||
if (icon)
|
||||
icon.textContent = expanded ? 'right_panel_close' : 'right_panel_open';
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
/** Pure formatting and fixed presentation constants used by Cockpit components. */
|
||||
import { formatNumber, getLocale, t, msg } from '../i18n/index.js';
|
||||
import { formatQuantity } from './unitLabels.js';
|
||||
|
||||
export const COCKPIT_HEADING_SLEW_DPS = 28;
|
||||
|
||||
export const COCKPIT_FORWARD_OFFSET_M = 7;
|
||||
@@ -44,20 +47,22 @@ export const COCKPIT_REGIONAL_REFRESH_DISTANCE_M = 25_000;
|
||||
export const COCKPIT_BRIEF_PAGES = [
|
||||
{
|
||||
id: 'signals',
|
||||
kicker: 'LIVE SIGNALS',
|
||||
subtitle: 'OBSERVED / MAPPED PINGS',
|
||||
source: 'SOURCE-BACKED EVENTS · NO SYNTHETIC NEWS',
|
||||
kickerKey: msg('LIVE SIGNALS'),
|
||||
subtitleKey: msg('OBSERVED / MAPPED PINGS'),
|
||||
sourceKey: msg('SOURCE-BACKED EVENTS · NO SYNTHETIC NEWS'),
|
||||
},
|
||||
{
|
||||
id: 'news',
|
||||
kicker: 'REGIONAL NEWS',
|
||||
subtitle: 'LATEST LOCATION-MATCHED REPORTING',
|
||||
source: 'GOOGLE NEWS RSS · LOCATION QUERY · RECENT',
|
||||
kickerKey: msg('REGIONAL NEWS'),
|
||||
subtitleKey: msg('LATEST LOCATION-MATCHED REPORTING'),
|
||||
sourceKey: msg('{source} · LOCATION QUERY · RECENT'),
|
||||
sourceName: 'GOOGLE NEWS RSS', // i18n-ignore: provider name
|
||||
},
|
||||
{
|
||||
id: 'local',
|
||||
kicker: 'LOCAL INFO',
|
||||
subtitle: 'PLACE / CONDITIONS / POSITION',
|
||||
kickerKey: msg('LOCAL INFO'),
|
||||
subtitleKey: msg('PLACE / CONDITIONS / POSITION'),
|
||||
// Attribution stays English.
|
||||
source: 'NATURAL EARTH · OPEN-METEO · UTC',
|
||||
},
|
||||
];
|
||||
@@ -80,18 +85,90 @@ export function isRenderedOnScreen(element) {
|
||||
|
||||
export function formatCockpitBriefAge(value) {
|
||||
const timestamp = Date.parse(value);
|
||||
if (!Number.isFinite(timestamp)) return 'TIME UNKNOWN';
|
||||
if (!Number.isFinite(timestamp)) return t('TIME UNKNOWN');
|
||||
const minutes = Math.max(0, Math.round((Date.now() - timestamp) / 60_000));
|
||||
if (minutes < 60) return `${minutes}M AGO`;
|
||||
if (minutes < 60) return t('{count}M AGO', { count: minutes });
|
||||
const hours = Math.round(minutes / 60);
|
||||
return hours < 48 ? `${hours}H AGO` : `${Math.round(hours / 24)}D AGO`;
|
||||
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.
|
||||
switch (code) {
|
||||
case 'N':
|
||||
return t('{value}°N', { value: amount });
|
||||
case 'S':
|
||||
return t('{value}°S', { value: amount });
|
||||
case 'E':
|
||||
return t('{value}°E', { value: amount });
|
||||
case 'W':
|
||||
return t('{value}°W', { value: amount });
|
||||
default:
|
||||
return `${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 = distanceM < 10000 ? 1 : 0;
|
||||
const distance = formatQuantity(distanceM / 1000, 'km', {
|
||||
minimumFractionDigits: digits,
|
||||
maximumFractionDigits: digits,
|
||||
});
|
||||
return getLocale() === 'zh-CN' ? distance : distance.toUpperCase();
|
||||
}
|
||||
|
||||
export function formatCockpitWindDirection(value) {
|
||||
if (!Number.isFinite(value)) return 'DIR UNKNOWN';
|
||||
const labels = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'];
|
||||
if (!Number.isFinite(value)) return t('DIR UNKNOWN');
|
||||
const labels = Object.keys(COMPASS_POINT_LABELS);
|
||||
const normalized = ((value % 360) + 360) % 360;
|
||||
return `${labels[Math.round(normalized / 45) % labels.length]} · ${Math.round(normalized)}°`;
|
||||
// 359.5° and above is north. Modulo keeps that from printing 360°.
|
||||
const degrees = Math.round(normalized) % 360;
|
||||
return `${compassPointLabel(labels[Math.round(normalized / 45) % labels.length])} · ${degrees}°`;
|
||||
}
|
||||
|
||||
// Digit grouping and decimal marks (`26,175`, `26 175`, `26.175`) take a
|
||||
// narrow cell; a full digit cell would open a gap in the middle of a number.
|
||||
const ROLL_SEPARATOR = /^[,.\u00a0\u202f]$/;
|
||||
|
||||
function rollTokenClass(character) {
|
||||
return ROLL_SEPARATOR.test(character)
|
||||
? 'cockpit-roll-token is-separator'
|
||||
: 'cockpit-roll-token';
|
||||
}
|
||||
|
||||
export function setCockpitRollingValue(
|
||||
@@ -130,7 +207,7 @@ export function setCockpitRollingValue(
|
||||
element.replaceChildren(
|
||||
...Array.from(nextText, (character) => {
|
||||
const token = document.createElement('span');
|
||||
token.className = 'cockpit-roll-token';
|
||||
token.className = rollTokenClass(character);
|
||||
token.setAttribute('aria-hidden', 'true');
|
||||
token.textContent = character;
|
||||
return token;
|
||||
@@ -159,7 +236,7 @@ export function setCockpitRollingValue(
|
||||
const previousCharacter = from[index];
|
||||
const nextCharacter = to[index];
|
||||
const token = document.createElement('span');
|
||||
token.className = 'cockpit-roll-token';
|
||||
token.className = rollTokenClass(nextCharacter);
|
||||
token.setAttribute('aria-hidden', 'true');
|
||||
|
||||
if (
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { formatCockpitWindDirection } from './cockpitPresentation.js';
|
||||
|
||||
test('wind just west of north reads 0°, not 360°', () => {
|
||||
assert.equal(formatCockpitWindDirection(90), 'E · 90°');
|
||||
assert.equal(formatCockpitWindDirection(0), 'N · 0°');
|
||||
assert.equal(formatCockpitWindDirection(359.4), 'N · 359°');
|
||||
assert.equal(formatCockpitWindDirection(359.6), 'N · 0°');
|
||||
});
|
||||
@@ -1,4 +1,6 @@
|
||||
/** Reconcile actionable signal rows without disturbing native keyboard focus. */
|
||||
import { t, tn } from '../i18n/index.js';
|
||||
import { formatCockpitDistance } from './cockpitPresentation.js';
|
||||
|
||||
export function renderCockpitSignals() {
|
||||
if (!this.signalList) return;
|
||||
@@ -57,7 +59,7 @@ export function renderCockpitSignals() {
|
||||
if (item.target) {
|
||||
heading.dataset.signalLayer = item.target.layerId;
|
||||
heading.dataset.signalId = item.target.id;
|
||||
const label = `Select flight ${item.title}`;
|
||||
const label = t('Select flight {title}', { title: item.title });
|
||||
if (heading.getAttribute('aria-label') !== label)
|
||||
heading.setAttribute('aria-label', label);
|
||||
setText(heading.children[0], item.title);
|
||||
@@ -126,7 +128,12 @@ export function updateCockpitSignals(snapshot, unknownCount) {
|
||||
key: `flight:${subject.layerId}:${subject.id}`,
|
||||
tone: 'track',
|
||||
title: subject.label || subject.id,
|
||||
detail: `${subject.layerId === 'military' ? 'MILITARY FLIGHT' : 'COMMERCIAL FLIGHT'} · CURRENT`,
|
||||
detail: t('{aircraftClass} · CURRENT', {
|
||||
aircraftClass:
|
||||
subject.layerId === 'military'
|
||||
? t('MILITARY FLIGHT')
|
||||
: t('COMMERCIAL FLIGHT'),
|
||||
}),
|
||||
target: { layerId: subject.layerId, id: String(subject.id) },
|
||||
distanceM: -1,
|
||||
});
|
||||
@@ -145,11 +152,15 @@ export function updateCockpitSignals(snapshot, unknownCount) {
|
||||
// contact reads as its registration here too. Same helper the
|
||||
// Context panel's nearest list uses.
|
||||
title: this.services.formatAwarenessLabel(item),
|
||||
detail: `${cohort.id === 'military' ? 'MILITARY FLIGHT' : 'COMMERCIAL FLIGHT'} · ${
|
||||
Number.isFinite(item.distanceM)
|
||||
? `${item.distanceM < 10000 ? (item.distanceM / 1000).toFixed(1) : Math.round(item.distanceM / 1000)} KM`
|
||||
: 'DISTANCE UNKNOWN'
|
||||
}`,
|
||||
detail: t('{aircraftClass} · {distance}', {
|
||||
aircraftClass:
|
||||
cohort.id === 'military'
|
||||
? t('MILITARY FLIGHT')
|
||||
: t('COMMERCIAL FLIGHT'),
|
||||
distance: Number.isFinite(item.distanceM)
|
||||
? formatCockpitDistance(item.distanceM)
|
||||
: t('DISTANCE UNKNOWN'),
|
||||
}),
|
||||
target: { layerId: cohort.id, id: String(id) },
|
||||
distanceM: item.distanceM ?? Infinity,
|
||||
});
|
||||
@@ -169,8 +180,12 @@ export function updateCockpitSignals(snapshot, unknownCount) {
|
||||
nextItems.splice(4, Math.max(0, nextItems.length - 4), {
|
||||
key: 'input-status',
|
||||
tone: 'warning',
|
||||
title: `${unknownCount} INPUT${unknownCount === 1 ? '' : 'S'} UNKNOWN`,
|
||||
detail: sources || 'SOURCE STATUS UNAVAILABLE',
|
||||
title: tn(
|
||||
unknownCount,
|
||||
'{count} INPUT UNKNOWN',
|
||||
'{count} INPUTS UNKNOWN',
|
||||
),
|
||||
detail: sources || t('SOURCE STATUS UNAVAILABLE'),
|
||||
target: null,
|
||||
timestamp:
|
||||
previous.get('input-status')?.timestamp ||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
/** Tracking identity, entry, exit and contact navigation for the Cockpit controller. */
|
||||
import { t } from '../i18n/index.js';
|
||||
import {
|
||||
normalizeHeading,
|
||||
resolveTrackedAircraftInfo,
|
||||
@@ -58,8 +59,8 @@ export function syncTr3bToggle(info) {
|
||||
this.tr3bToggle.hidden = !icao24;
|
||||
this.tr3bToggle.setAttribute('aria-pressed', converted ? 'true' : 'false');
|
||||
this.tr3bToggle.title = converted
|
||||
? 'Restore real aircraft'
|
||||
: 'Reclassify as TR-3B';
|
||||
? t('Restore real aircraft')
|
||||
: t('Reclassify as TR-3B');
|
||||
}
|
||||
|
||||
export function syncEntry() {
|
||||
@@ -183,15 +184,18 @@ export function enter() {
|
||||
this.showBriefPage(0);
|
||||
this.startBriefRotation();
|
||||
const trackLabel =
|
||||
info.callsign || info.registration || info.icao24 || 'AIRCRAFT';
|
||||
info.callsign || info.registration || info.icao24 || t('AIRCRAFT');
|
||||
const trackHeading = String(
|
||||
Math.round(normalizeHeading(info.track ?? 0)),
|
||||
).padStart(3, '0');
|
||||
this.pushCockpitSignal(
|
||||
'track',
|
||||
'track',
|
||||
'TRACK ACQUIRED',
|
||||
`${trackLabel} · COURSE ${trackHeading}°`,
|
||||
t('TRACK ACQUIRED'),
|
||||
t('{label} · COURSE {heading}°', {
|
||||
label: trackLabel,
|
||||
heading: trackHeading,
|
||||
}),
|
||||
);
|
||||
this.updateHud(info, performance.now(), true);
|
||||
this.setVisionMode(this.getInitialVisionMode());
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
/** Compose UI controls with the application's existing engines and layer instances. */
|
||||
import { StyleManager as ApplicationShell } from './applicationShell.js';
|
||||
import { LocationSearch } from './location.js';
|
||||
import { CITY_POIS } from '../cityPois.js';
|
||||
import {
|
||||
CITY_POIS,
|
||||
GLOBE_VIEW,
|
||||
flyToGlobeView,
|
||||
flyToPresetLocation,
|
||||
flyToPOI,
|
||||
searchAndFlyTo,
|
||||
} from '../locations.js';
|
||||
import { interruptCameraMotion } from '../cameraVerbs.js';
|
||||
import {
|
||||
interruptCameraMotion,
|
||||
interruptGlobeRotation,
|
||||
} from '../cameraVerbs.js';
|
||||
import { IntelHUD } from '../hud.js';
|
||||
import { ShareLinkManager } from '../sharelink.js';
|
||||
import { OrbitController } from '../orbit.js';
|
||||
@@ -73,6 +76,7 @@ export class StyleManager extends ApplicationShell {
|
||||
flyToPOI,
|
||||
searchAndFlyTo,
|
||||
interruptCameraMotion,
|
||||
interruptGlobeRotation,
|
||||
IntelHUD,
|
||||
ShareLinkManager,
|
||||
OrbitController,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { t, tn } from '../i18n/index.js';
|
||||
import {
|
||||
settleUserFacingContextAction,
|
||||
contextModeWord,
|
||||
@@ -5,8 +6,8 @@ import {
|
||||
|
||||
export async function _runUserFacingContextAction(
|
||||
operation,
|
||||
message = 'Context could not restore every layer; try again',
|
||||
{ falseIsFailure = true } = {},
|
||||
message = t('Context could not restore every layer; try again'),
|
||||
{ falseIsFailure = true, localizedMessage = null } = {},
|
||||
) {
|
||||
if (this.destroyed) return false;
|
||||
const notificationToken = Symbol('user-facing-context-action');
|
||||
@@ -18,7 +19,7 @@ export async function _runUserFacingContextAction(
|
||||
onFailure: (error) => {
|
||||
if (this.destroyed) return;
|
||||
console.warn('[Context] user-facing transition failed', error);
|
||||
this.showToast(message);
|
||||
this.showToast(localizedMessage || message);
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
@@ -222,21 +223,29 @@ export function clearSelectedLayers() {
|
||||
const operation = managerOperation
|
||||
.then((result) => {
|
||||
if (result.targetIds.length === 0) {
|
||||
this.showToast('No selected data layers');
|
||||
this.showToast(t('No selected data layers'));
|
||||
} else if (result.notClearedIds.length > 0) {
|
||||
this.showToast(
|
||||
`${result.notClearedIds.length} data layer${result.notClearedIds.length === 1 ? '' : 's'} could not be cleared`,
|
||||
tn(
|
||||
result.notClearedIds.length,
|
||||
'{count} data layer could not be cleared',
|
||||
'{count} data layers could not be cleared',
|
||||
),
|
||||
);
|
||||
} else {
|
||||
this.showToast(
|
||||
`Cleared ${result.clearedIds.length} data layer${result.clearedIds.length === 1 ? '' : 's'}`,
|
||||
tn(
|
||||
result.clearedIds.length,
|
||||
'Cleared {count} data layer',
|
||||
'Cleared {count} data layers',
|
||||
),
|
||||
);
|
||||
}
|
||||
return result;
|
||||
})
|
||||
.catch((error) => {
|
||||
console.warn('[Data] clear selected layers failed', error);
|
||||
this.showToast('Selected data layers could not be cleared');
|
||||
this.showToast(t('Selected data layers could not be cleared'));
|
||||
return {
|
||||
targetIds: [],
|
||||
items: [],
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { shouldExpandGlobalContextPanel } from '../rightRailPolicy.js';
|
||||
|
||||
export function _initGlobalContextPanel() {
|
||||
@@ -32,7 +33,7 @@ export function _initGlobalContextPanel() {
|
||||
void this._runUserFacingContextAction(
|
||||
(notificationToken) =>
|
||||
this._selectContextMode(nextMode, { notificationToken }),
|
||||
'Contacts could not complete the requested transition; try again',
|
||||
t('Contacts could not complete the requested transition; try again'),
|
||||
).then((succeeded) => {
|
||||
if (
|
||||
!this.destroyed &&
|
||||
@@ -61,7 +62,9 @@ export function _initGlobalContextPanel() {
|
||||
void this._runUserFacingContextAction(
|
||||
(notificationToken) =>
|
||||
this._selectContextMode(nextMode, { notificationToken }),
|
||||
'Space Missions could not complete the requested transition; try again',
|
||||
t(
|
||||
'Space Missions could not complete the requested transition; try again',
|
||||
),
|
||||
).then((succeeded) => {
|
||||
if (
|
||||
!this.destroyed &&
|
||||
@@ -108,14 +111,16 @@ export function _initGlobalContextPanel() {
|
||||
this.showToast(
|
||||
stats?.statusMessage ||
|
||||
(stats?.status === 'zoom-in'
|
||||
? 'Zoom in to search mapped installations'
|
||||
: 'Nearby installations refreshed'),
|
||||
? t('Zoom in to search mapped installations')
|
||||
: t('Nearby installations refreshed')),
|
||||
);
|
||||
return true;
|
||||
}, 'Nearby installations could not be refreshed; try again').finally(() => {
|
||||
if (this.destroyed) return;
|
||||
button.setAttribute('aria-disabled', 'false');
|
||||
button.setAttribute('aria-busy', 'false');
|
||||
});
|
||||
}, t('Nearby installations could not be refreshed; try again')).finally(
|
||||
() => {
|
||||
if (this.destroyed) return;
|
||||
button.setAttribute('aria-disabled', 'false');
|
||||
button.setAttribute('aria-busy', 'false');
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
// The blocked-visibility toast reason in the UI language.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { setLocale } from '../i18n/index.js';
|
||||
import {
|
||||
contextLayerEnableBlockReason,
|
||||
parseContextLayerBlockReason,
|
||||
} from '../contextModePolicy.js';
|
||||
import {
|
||||
_handleContextLayerChange,
|
||||
localizeVisibilityBlockReason,
|
||||
} from './contextLayerChanges.js';
|
||||
|
||||
function fakeShell() {
|
||||
const toasts = [];
|
||||
return {
|
||||
destroyed: false,
|
||||
_userFacingContextNotificationTokens: new Set(),
|
||||
_contextSessionSnapshot: null,
|
||||
_contextModeChanging: false,
|
||||
_contextMode: 'space-missions',
|
||||
_contextModeEntering: null,
|
||||
_syncContextModeButtons() {},
|
||||
showToast(message) {
|
||||
toasts.push(message);
|
||||
},
|
||||
toasts,
|
||||
};
|
||||
}
|
||||
|
||||
const ENGLISH_GUARD =
|
||||
'Space Missions isolates replay data. Exit the mode to enable Live Flights.';
|
||||
|
||||
test.afterEach(() => setLocale('en'));
|
||||
|
||||
test('the guard reason is English data and parses back to its layer name', () => {
|
||||
const reason = contextLayerEnableBlockReason({
|
||||
contextMode: 'space-missions',
|
||||
change: { layerId: 'flights', enabled: true, origin: 'user' },
|
||||
layerName: 'Live Flights',
|
||||
});
|
||||
assert.equal(reason, ENGLISH_GUARD);
|
||||
assert.deepEqual(parseContextLayerBlockReason(reason), {
|
||||
layer: 'Live Flights',
|
||||
});
|
||||
assert.equal(parseContextLayerBlockReason('Data source unavailable'), null);
|
||||
assert.equal(
|
||||
parseContextLayerBlockReason(
|
||||
'Space Missions isolates replay data. Exit the mode to enable .',
|
||||
),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('en: the toast shows the reason unchanged', () => {
|
||||
setLocale('en');
|
||||
const shell = fakeShell();
|
||||
_handleContextLayerChange.call(shell, {
|
||||
type: 'visibility-blocked',
|
||||
layerId: 'flights',
|
||||
enabled: true,
|
||||
origin: 'user',
|
||||
reason: ENGLISH_GUARD,
|
||||
});
|
||||
assert.deepEqual(shell.toasts, [ENGLISH_GUARD]);
|
||||
assert.equal(
|
||||
localizeVisibilityBlockReason('Overpass returned HTTP 503'),
|
||||
'Overpass returned HTTP 503',
|
||||
);
|
||||
});
|
||||
|
||||
for (const locale of ['es', 'ru']) {
|
||||
test(`${locale}: the Space Missions block toast is localized with the layer name`, () => {
|
||||
setLocale(locale);
|
||||
const reason = contextLayerEnableBlockReason({
|
||||
contextMode: 'space-missions',
|
||||
change: { layerId: 'flights', enabled: true, origin: 'user' },
|
||||
layerName: 'Live Flights',
|
||||
});
|
||||
const shell = fakeShell();
|
||||
_handleContextLayerChange.call(shell, {
|
||||
type: 'visibility-blocked',
|
||||
layerId: 'flights',
|
||||
enabled: true,
|
||||
origin: 'user',
|
||||
reason,
|
||||
});
|
||||
assert.equal(shell.toasts.length, 1);
|
||||
assert.notEqual(shell.toasts[0], ENGLISH_GUARD, 'toast must be localized');
|
||||
assert.doesNotMatch(shell.toasts[0], /Space Missions isolates/);
|
||||
assert.doesNotMatch(shell.toasts[0], /Live Flights/);
|
||||
});
|
||||
|
||||
test(`${locale}: a known lifecycle reason is looked up in the catalog`, () => {
|
||||
setLocale(locale);
|
||||
const shell = fakeShell();
|
||||
shell._contextMode = null;
|
||||
_handleContextLayerChange.call(shell, {
|
||||
type: 'visibility-blocked',
|
||||
layerId: 'street-level',
|
||||
enabled: true,
|
||||
origin: 'user',
|
||||
reason: 'Data source unavailable',
|
||||
});
|
||||
assert.equal(shell.toasts.length, 1);
|
||||
assert.notEqual(shell.toasts[0], 'Data source unavailable');
|
||||
});
|
||||
|
||||
test(`${locale}: an unknown provider message passes through verbatim`, () => {
|
||||
setLocale(locale);
|
||||
assert.equal(
|
||||
localizeVisibilityBlockReason('Overpass returned HTTP 503'),
|
||||
'Overpass returned HTTP 503',
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -1,11 +1,30 @@
|
||||
import { t, translateKnown } from '../i18n/index.js';
|
||||
import {
|
||||
SPACE_MISSIONS_LAYER_BLOCK_REASON,
|
||||
cockpitEntryAllowed,
|
||||
isExplicitUserIntentOrigin,
|
||||
parseContextLayerBlockReason,
|
||||
recordContextRestoreExplicitChange,
|
||||
recordContextSessionUserChange,
|
||||
shouldExitContextForLayerChange,
|
||||
spaceMissionEntryCancellationDisposition,
|
||||
} from '../contextModePolicy.js';
|
||||
import { localizeLayerName } from './layerNames.js';
|
||||
|
||||
/**
|
||||
* A blocked-visibility reason in the UI language. Reasons stay English (voice
|
||||
* and tools read them): the Space Missions refusal is rebuilt with the layer
|
||||
* name localized, a known sentence is looked up, anything else passes.
|
||||
*/
|
||||
export function localizeVisibilityBlockReason(reason) {
|
||||
if (typeof reason !== 'string' || !reason) return reason;
|
||||
const blocked = parseContextLayerBlockReason(reason);
|
||||
if (blocked)
|
||||
return t(SPACE_MISSIONS_LAYER_BLOCK_REASON, {
|
||||
layer: localizeLayerName(blocked.layer),
|
||||
});
|
||||
return translateKnown(reason);
|
||||
}
|
||||
|
||||
export function _handleContextLayerChange(change) {
|
||||
if (this.destroyed) return;
|
||||
@@ -58,12 +77,23 @@ export function _handleContextLayerChange(change) {
|
||||
if (this._contextSessionSnapshot && !this._contextModeChanging) {
|
||||
this._contextMode = null;
|
||||
void this._trackContextLayerReaction(
|
||||
this._runUserFacingContextAction(async (notificationToken) => {
|
||||
await this._restoreContextSessionAfterLayerSettles(change.layerId, {
|
||||
notificationToken,
|
||||
});
|
||||
return true;
|
||||
}, 'Space Missions cancellation could not restore the previous layer state'),
|
||||
this._runUserFacingContextAction(
|
||||
async (notificationToken) => {
|
||||
await this._restoreContextSessionAfterLayerSettles(
|
||||
change.layerId,
|
||||
{
|
||||
notificationToken,
|
||||
},
|
||||
);
|
||||
return true;
|
||||
},
|
||||
'Space Missions cancellation could not restore the previous layer state', // i18n-ignore: English message; the toast shows localizedMessage
|
||||
{
|
||||
localizedMessage: t(
|
||||
'Space Missions cancellation could not restore the previous layer state',
|
||||
),
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -83,15 +113,18 @@ export function _handleContextLayerChange(change) {
|
||||
!this._userFacingContextNotificationTokens.has(change.notificationToken)
|
||||
) {
|
||||
this.showToast(
|
||||
change.reason ||
|
||||
'That layer is unavailable in the current Context mode',
|
||||
localizeVisibilityBlockReason(change.reason) ||
|
||||
t('That layer is unavailable in the current Context mode'),
|
||||
);
|
||||
}
|
||||
this._syncContextModeButtons();
|
||||
return;
|
||||
}
|
||||
if (change?.type === 'visibility-failed') {
|
||||
const failureMessage = `${change.layerId} could not ${change.enabled ? 'start' : 'stop'} cleanly`;
|
||||
const failureMessage = t('{layerId} could not {action} cleanly', {
|
||||
layerId: change.layerId,
|
||||
action: change.enabled ? t('start') : t('stop'),
|
||||
});
|
||||
// A failed direct Context-shell START has already had its siblings
|
||||
// cleared by the visibility guard. Wait outside the synchronous manager
|
||||
// notification for this queue to settle, then reconcile the complete
|
||||
|
||||
@@ -86,6 +86,9 @@ export async function _restoreContextSession({
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
// Clear All may have run while Contacts settled. It owns the selection
|
||||
// now, so the snapshot must not come back behind it.
|
||||
if (restoreState.cancelled) return;
|
||||
await this._dataManager.restoreEnabledLayerIds(
|
||||
restoreState.enabledLayerIds,
|
||||
{
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import {
|
||||
contextLayerEnableBlockReason,
|
||||
isExplicitUserIntentOrigin,
|
||||
@@ -124,7 +125,15 @@ export function connectContextManager(manager) {
|
||||
restoreError,
|
||||
);
|
||||
}
|
||||
return `${entryMode === 'space-missions' ? 'Space Missions' : 'Context'} could not start because another layer did not stop cleanly`;
|
||||
return t(
|
||||
'{mode} could not start because another layer did not stop cleanly',
|
||||
{
|
||||
mode:
|
||||
entryMode === 'space-missions'
|
||||
? t('Space Missions')
|
||||
: t('Context'),
|
||||
},
|
||||
);
|
||||
} finally {
|
||||
if (ownsNotificationToken) {
|
||||
this._userFacingContextNotificationTokens.delete(
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
// The CCTV "ACQUIRING FRAME" caption lives in CSS `content:` and the
|
||||
// i18n scanner (scripts/i18n.mjs) never reads CSS, so es/ru show it in English.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync, readdirSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
const STYLES = path.join(HERE, 'styles');
|
||||
const LOCALES = path.join(HERE, '..', 'i18n', 'locales');
|
||||
// cyber.css carries decorative theme strings (LOC / GRID, SYS 06 // ...);
|
||||
// street-level.css ' · ESC' is a key cap. Neither is UI copy.
|
||||
const DECORATIVE = new Set(['cyber.css', 'street-level.css']);
|
||||
|
||||
test('no user-visible text in CSS content: outside decorative themes', () => {
|
||||
const hits = [];
|
||||
for (const file of readdirSync(STYLES)) {
|
||||
if (!file.endsWith('.css') || DECORATIVE.has(file)) continue;
|
||||
const css = readFileSync(path.join(STYLES, file), 'utf8');
|
||||
css.split('\n').forEach((line, i) => {
|
||||
if (/^\s*content:\s*['"][^'"]*[A-Za-z]{2,}/.test(line))
|
||||
hits.push(`${file}:${i + 1} ${line.trim()}`);
|
||||
});
|
||||
}
|
||||
assert.deepEqual(hits, []);
|
||||
});
|
||||
|
||||
test('the CCTV acquisition caption has es and ru translations', () => {
|
||||
for (const lang of ['es', 'ru']) {
|
||||
const dict = JSON.parse(readFileSync(path.join(LOCALES, `${lang}.json`), 'utf8'));
|
||||
assert.ok('ACQUIRING FRAME' in dict, `${lang}.json lacks "ACQUIRING FRAME"`);
|
||||
}
|
||||
});
|
||||
@@ -85,16 +85,3 @@ test('non-Cyber explicit panels and restored preferences retain their existing p
|
||||
} finally { globalThis.document = prior; }
|
||||
}
|
||||
});
|
||||
|
||||
test('opening a floating Cyber window leaves the docked rail panels open', () => {
|
||||
const f = fixture(), prior = globalThis.document;
|
||||
globalThis.document = f.doc;
|
||||
try {
|
||||
f.owner.setPanelCollapsed('pp-toggles', false, { explicit: true });
|
||||
f.cctv.classList.add('panel-floating');
|
||||
f.owner.setPanelCollapsed('cctv-panel', false, { explicit: true });
|
||||
assert.equal(f.cctv.classList.contains('collapsed'), false);
|
||||
assert.equal(f.display.classList.contains('collapsed'), false, 'DISPLAY stays open');
|
||||
assert.ok(!f.saved.some(([id, collapsed]) => id === 'pp-toggles' && collapsed));
|
||||
} finally { globalThis.document = prior; }
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import { getScopeMaskFeather, isScopeMaskEnabled, setScopeMaskEnabled, setScopeMaskFeather } from '../scopeMask.js';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import test from 'node:test';
|
||||
@@ -271,6 +272,35 @@ test('Display and voice HUD routes preserve explicit Cyber entry and exit author
|
||||
assert.equal(voice.owner.activeStyle, 'snow');
|
||||
});
|
||||
|
||||
test('scope choice and expanded feather survive every HUD layout and both restore paths', async (t) => {
|
||||
const { owner } = styleOwner(t, 'tactical');
|
||||
const previous = { enabled: isScopeMaskEnabled(), feather: getScopeMaskFeather() };
|
||||
t.after(() => { setScopeMaskEnabled(previous.enabled); setScopeMaskFeather(previous.feather); });
|
||||
Object.assign(owner.services, { setScopeMaskEnabled, setScopeMaskFeather });
|
||||
owner._scopeBtn = { checked: true };
|
||||
owner._scopeFeatherSlider = { value: '11', disabled: false };
|
||||
owner._scopeFeatherValue = {};
|
||||
await owner.restoreShareState({ scopeEnabled: false, scopeFeatherPct: 200 });
|
||||
assert.equal(owner._scopeBtn.checked, false);
|
||||
assert.equal(owner._scopeFeatherSlider.disabled, true);
|
||||
assert.equal(owner._scopeFeatherSlider.value, '200');
|
||||
for (const layout of ['minimal', 'operator', 'cyber', 'tactical']) {
|
||||
owner._setHudVariant(layout, { applyVisualDefaults: true });
|
||||
assert.equal(isScopeMaskEnabled(), false, layout);
|
||||
assert.equal(getScopeMaskFeather(), 2, layout);
|
||||
assert.equal(owner._scopeBtn.checked, false, layout);
|
||||
}
|
||||
await owner.applyVisualState({ scope: { enabled: true, featherPct: 175 } });
|
||||
assert.equal(isScopeMaskEnabled(), true);
|
||||
assert.equal(getScopeMaskFeather(), 1.75);
|
||||
assert.equal(owner._scopeBtn.checked, true);
|
||||
assert.equal(owner._scopeFeatherSlider.disabled, false);
|
||||
assert.equal(owner._scopeFeatherValue.textContent, '175%');
|
||||
await owner.applyVisualState({ scope: { featherPct: 500 } });
|
||||
assert.equal(getScopeMaskFeather(), 2);
|
||||
assert.equal(owner._scopeFeatherSlider.value, '200');
|
||||
});
|
||||
|
||||
test('scene and share HUD transitions do not restore a local pre-Cyber preset', async (t) => {
|
||||
const { owner, hud } = styleOwner(t, 'tactical');
|
||||
owner.setStyle('noir');
|
||||
@@ -617,7 +647,7 @@ test('the Display selector, voice schema and final stylesheet expose Cyber', ()
|
||||
const militaryRendering = read('../layers/military/rendering.js');
|
||||
const setHud = GEV_ACTION_SCHEMAS.find((schema) => schema.name === 'set_hud');
|
||||
|
||||
assert.match(display, /<option value="cyber">Cyber<\/option>/);
|
||||
assert.match(display, /<option value="cyber" data-i18n>Cyber<\/option>/);
|
||||
assert.match(display, /id="cyber-sonar-toggle"/);
|
||||
assert.match(
|
||||
display,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { clampScopeFeatherPct } from '../scopeMaskPolicy.js';
|
||||
import { createFrameRateMonitor } from './frameRateMonitor.js';
|
||||
import { bindApplicationShortcuts } from './visualInput.js';
|
||||
import { bindDisplayControls } from './displayControls.js';
|
||||
import { bindDisplayControls, syncScopeControls } from './displayControls.js';
|
||||
import { canonicalizeDensity } from '../data/detectionPolicy.js';
|
||||
|
||||
/** Own keyboard/display event subscriptions; settings remain with their state owners. */
|
||||
@@ -92,6 +93,11 @@ export class DisplayBindings {
|
||||
},
|
||||
});
|
||||
|
||||
syncScopeControls(
|
||||
this._scopeBtn,
|
||||
this._scopeFeatherSlider,
|
||||
isScopeMaskEnabled(),
|
||||
);
|
||||
this._displayControls?.destroy();
|
||||
this._displayControls = bindDisplayControls({
|
||||
elements: {
|
||||
@@ -100,7 +106,7 @@ export class DisplayBindings {
|
||||
bloomSlider: this._bloomSlider,
|
||||
sharpenButton: this._sharpenBtn,
|
||||
sharpenSlider: this._sharpenSlider,
|
||||
scopeButton: this._scopeBtn,
|
||||
scopeToggle: this._scopeBtn,
|
||||
scopeFeatherSlider: this._scopeFeatherSlider,
|
||||
hudLayout: this._hudLayoutSelect,
|
||||
hudButton: this._hudBtn,
|
||||
@@ -134,17 +140,15 @@ export class DisplayBindings {
|
||||
this.shareLinkManager?.claimRestoreLane?.('visual');
|
||||
this._setSharpenEnabled(!this.sharpenEnabled);
|
||||
},
|
||||
toggleScope: () => {
|
||||
setScopeEnabled: (enabled) => {
|
||||
this.shareLinkManager?.claimRestoreLane?.('visual');
|
||||
const next = !isScopeMaskEnabled();
|
||||
setScopeMaskEnabled(next);
|
||||
this._scopeBtn.classList.toggle('active', next);
|
||||
this._scopeBtn.setAttribute('aria-pressed', String(next));
|
||||
setScopeMaskEnabled(enabled);
|
||||
syncScopeControls(this._scopeBtn, this._scopeFeatherSlider, enabled);
|
||||
this._syncShareState();
|
||||
},
|
||||
setScopeFeather: (value) => {
|
||||
this.shareLinkManager?.claimRestoreLane?.('visual');
|
||||
const pct = Math.max(0, Math.min(100, value || 0));
|
||||
const pct = clampScopeFeatherPct(value);
|
||||
if (this._scopeFeatherValue)
|
||||
this._scopeFeatherValue.textContent = `${pct}%`;
|
||||
setScopeMaskFeather(pct / 100);
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { createSegmentedControl } from './segmentedControl.js';
|
||||
|
||||
/**
|
||||
* Bind Display controls to application actions. Inputs remain native DOM controls;
|
||||
* the caller owns settings and effect state. Destroy before replacing the view.
|
||||
@@ -16,7 +18,6 @@ export function bindDisplayControls({ elements, actions }) {
|
||||
for (const [name, action] of [
|
||||
['bloomButton', 'toggleBloom'],
|
||||
['sharpenButton', 'toggleSharpen'],
|
||||
['scopeButton', 'toggleScope'],
|
||||
['cleanViewButton', 'toggleCleanView'],
|
||||
['cleanViewExitButton', 'exitCleanView'],
|
||||
['celestialButton', 'toggleCelestial'],
|
||||
@@ -32,6 +33,7 @@ export function bindDisplayControls({ elements, actions }) {
|
||||
['scopeFeatherSlider', 'setScopeFeather'],
|
||||
])
|
||||
listen(elements[name], 'input', action, integer);
|
||||
listen(elements.scopeToggle, 'change', 'setScopeEnabled', (el) => el.checked);
|
||||
listen(elements.densitySlider, 'input', 'setDensity', (el) => el.value);
|
||||
listen(elements.hudLayout, 'change', 'setHudLayout', (el) => el.value);
|
||||
for (const [name, action] of [
|
||||
@@ -44,12 +46,25 @@ export function bindDisplayControls({ elements, actions }) {
|
||||
listen(elements[name], 'input', action, integer);
|
||||
for (const el of elements.styleButtons || [])
|
||||
listen(el, 'click', 'setStyle', (el) => el.dataset.style);
|
||||
for (const el of elements.allocationButtons || [])
|
||||
listen(el, 'click', 'setAllocation', (el) => el.dataset.allocation);
|
||||
for (const el of elements.modelModeButtons || [])
|
||||
listen(el, 'click', 'setModelsMode', (el) =>
|
||||
el.dataset.mode === 'all' ? 'all' : 'proximity',
|
||||
);
|
||||
for (const [buttons, valueOf, action] of [
|
||||
[
|
||||
elements.allocationButtons || [],
|
||||
(el) => el.dataset.allocation,
|
||||
'setAllocation',
|
||||
],
|
||||
[
|
||||
elements.modelModeButtons || [],
|
||||
(el) => (el.dataset.mode === 'all' ? 'all' : 'proximity'),
|
||||
'setModelsMode',
|
||||
],
|
||||
]) {
|
||||
const control = createSegmentedControl({
|
||||
buttons,
|
||||
valueOf,
|
||||
onChange: (value) => actions[action](value),
|
||||
});
|
||||
removers.push(() => control.destroy());
|
||||
}
|
||||
for (const el of elements.fadeSliders || []) listen(el, 'input', 'setFade');
|
||||
return {
|
||||
destroy() {
|
||||
@@ -57,3 +72,9 @@ export function bindDisplayControls({ elements, actions }) {
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Keep the native Scope checkbox and feather availability in step with the mask. */
|
||||
export function syncScopeControls(toggle, featherSlider, enabled) {
|
||||
if (toggle) toggle.checked = enabled;
|
||||
if (featherSlider) featherSlider.disabled = !enabled;
|
||||
}
|
||||
@@ -158,3 +158,29 @@ test('optional controls are absent safely and subscriptions stay instance-owned'
|
||||
assert.deepEqual(calls, ['b']);
|
||||
two.destroy();
|
||||
});
|
||||
|
||||
test('the native Scope checkbox reads checked state on change and disposes its listener', () => {
|
||||
const scopeToggle = element();
|
||||
scopeToggle.checked = true;
|
||||
const scopeFeatherSlider = element('200');
|
||||
const calls = [];
|
||||
const controls = bindDisplayControls({
|
||||
elements: { scopeToggle, scopeFeatherSlider },
|
||||
actions: {
|
||||
setScopeEnabled: (value) => calls.push(['enabled', value]),
|
||||
setScopeFeather: (value) => calls.push(['feather', value]),
|
||||
},
|
||||
});
|
||||
scopeToggle.checked = false;
|
||||
scopeToggle.dispatchEvent(new Event('change'));
|
||||
scopeToggle.checked = true;
|
||||
scopeToggle.dispatchEvent(new Event('change'));
|
||||
scopeFeatherSlider.dispatchEvent(new Event('input'));
|
||||
controls.destroy();
|
||||
scopeToggle.dispatchEvent(new Event('change'));
|
||||
assert.deepEqual(calls, [
|
||||
['enabled', false],
|
||||
['enabled', true],
|
||||
['feather', 200],
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
// Flights / Military feed failure texts reach the DATA LAYERS row in the
|
||||
// UI language; the feeds keep them in English.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { LayerPanel } from './layerPanel.js';
|
||||
import { setLocale } from '../i18n/index.js';
|
||||
import { httpError, LiveSourceError } from '../sources/live/contract.js';
|
||||
|
||||
const panel = LayerPanel.prototype;
|
||||
|
||||
function flightsRow(error) {
|
||||
return panel._buildMetaText({
|
||||
id: 'flights',
|
||||
enabled: true,
|
||||
stats: {
|
||||
count: 0,
|
||||
stale: true,
|
||||
error,
|
||||
status: 429,
|
||||
retryInSec: 45,
|
||||
source: 'OpenSky',
|
||||
lastUpdate: Date.now(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const cases = [
|
||||
['OpenSky 429 anonymous', 'OpenSky rate limited (anonymous)'],
|
||||
['OpenSky auth', 'OpenSky auth required'],
|
||||
['generic 429', httpError({ status: 429 }, 'Flights').message],
|
||||
['HTTP 503', httpError({ status: 503 }, 'Military aircraft').message],
|
||||
[
|
||||
'network error',
|
||||
new LiveSourceError('unavailable', 'Flights network error').message,
|
||||
],
|
||||
['stale snapshot', 'Source snapshot 7 min old'],
|
||||
['snapshot time unknown', 'Source snapshot time unavailable'],
|
||||
['non-LiveSourceError', 'Live data unavailable'],
|
||||
['malformed', 'Malformed OpenSky response'],
|
||||
['malformed rows', 'Malformed adsb.lol aircraft rows'],
|
||||
];
|
||||
|
||||
test('en: feed failure texts stay English', () => {
|
||||
setLocale('en');
|
||||
for (const [, message] of cases)
|
||||
assert.equal(
|
||||
flightsRow(message),
|
||||
`STALE · OpenSky · ${message} · retry 45s`,
|
||||
);
|
||||
});
|
||||
|
||||
for (const locale of ['es', 'ru']) {
|
||||
test(`${locale}: feed failure texts are translated in the layer row`, () => {
|
||||
setLocale(locale);
|
||||
try {
|
||||
for (const [name, message] of cases) {
|
||||
const row = flightsRow(message);
|
||||
assert.ok(
|
||||
!row.includes(message),
|
||||
`${locale} ${name}: row still contains English detail: ${row}`,
|
||||
);
|
||||
}
|
||||
assert.match(flightsRow('Source snapshot 7 min old'), /\b7\b/);
|
||||
assert.match(flightsRow('Flights HTTP 503'), /\b503\b/);
|
||||
} finally {
|
||||
setLocale('en');
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
/** Frame the complete finite footprint of a session-local file. */
|
||||
import * as Cesium from 'cesium';
|
||||
import { guardCameraAboveGround } from '../cameraGroundGuard.js';
|
||||
import { rangeForBoundingSphere } from '../data/cameraFraming.js';
|
||||
import { cancelCameraArrival } from '../data/cameraArrival.js';
|
||||
|
||||
/** All visible positions, path vertices, polygon rings, walls and overlay bounds. */
|
||||
export function dataSourcePoints(dataSource, time = Cesium.JulianDate.now()) {
|
||||
const points = [];
|
||||
const add = (position, grounded = false) => {
|
||||
if (
|
||||
!position ||
|
||||
![position.x, position.y, position.z].every(Number.isFinite)
|
||||
)
|
||||
return;
|
||||
const c = Cesium.Cartographic.fromCartesian(position);
|
||||
if (c && Number.isFinite(c.longitude) && Number.isFinite(c.latitude))
|
||||
points.push([
|
||||
Cesium.Math.toDegrees(c.longitude),
|
||||
Cesium.Math.toDegrees(c.latitude),
|
||||
grounded ? 0 : c.height,
|
||||
]);
|
||||
};
|
||||
if (dataSource?.show === false) return points;
|
||||
for (const entity of dataSource?.importedEntities ??
|
||||
dataSource?.entities?.values ??
|
||||
[]) {
|
||||
if (entity.isShowing === false) continue;
|
||||
add(
|
||||
entity.position?.getValue?.(time),
|
||||
entity.billboard?.heightReference?.getValue?.(time) ===
|
||||
Cesium.HeightReference.CLAMP_TO_GROUND,
|
||||
);
|
||||
for (const graphic of [entity.polyline, entity.wall])
|
||||
for (const position of graphic?.positions?.getValue?.(time) || [])
|
||||
add(position, graphic.clampToGround?.getValue?.(time) === true);
|
||||
const rings = [entity.polygon?.hierarchy?.getValue?.(time)];
|
||||
while (rings.length) {
|
||||
const ring = rings.pop();
|
||||
for (const position of ring?.positions || [])
|
||||
add(
|
||||
position,
|
||||
entity.polygon?.perPositionHeight?.getValue?.(time) !== true,
|
||||
);
|
||||
for (const hole of ring?.holes || []) rings.push(hole);
|
||||
}
|
||||
const rectangle = entity.rectangle?.coordinates?.getValue?.(time);
|
||||
if (rectangle) {
|
||||
const bounds = Cesium.RectangleGeometry.computeRectangle({
|
||||
rectangle,
|
||||
rotation: entity.rectangle.rotation?.getValue?.(time) || 0,
|
||||
});
|
||||
for (const corner of [
|
||||
'southwest',
|
||||
'southeast',
|
||||
'northwest',
|
||||
'northeast',
|
||||
]) {
|
||||
const c = Cesium.Rectangle[corner](bounds);
|
||||
if (Number.isFinite(c.longitude) && Number.isFinite(c.latitude))
|
||||
points.push([
|
||||
Cesium.Math.toDegrees(c.longitude),
|
||||
Cesium.Math.toDegrees(c.latitude),
|
||||
entity.rectangle.height?.getValue?.(time) || 0,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return points;
|
||||
}
|
||||
|
||||
/** Fly synchronously to the footprint; later navigation always owns its camera. */
|
||||
export function flyToDataSource(
|
||||
viewer,
|
||||
dataSource,
|
||||
{ duration = 1.5, ground = null } = {},
|
||||
) {
|
||||
const points = dataSourcePoints(dataSource);
|
||||
if (!points.length) return false;
|
||||
cancelCameraArrival(viewer);
|
||||
const positions = points.map(([lon, lat, height]) =>
|
||||
Cesium.Cartesian3.fromDegrees(lon, lat, height),
|
||||
);
|
||||
const sphere = Cesium.BoundingSphere.fromPoints(positions);
|
||||
const center =
|
||||
Cesium.Cartographic.fromCartesian(sphere.center) ||
|
||||
Cesium.Cartographic.fromDegrees(points[0][0], points[0][1]);
|
||||
const lat = Cesium.Math.toDegrees(center.latitude),
|
||||
lon = Cesium.Math.toDegrees(center.longitude);
|
||||
const terrain = viewer.scene?.globe?.getHeight?.(center);
|
||||
const cached = ground?.cachedGroundFloor?.(lat, lon);
|
||||
const height =
|
||||
Number.isFinite(terrain) && terrain > 0
|
||||
? terrain
|
||||
: Number.isFinite(cached)
|
||||
? cached
|
||||
: Number.isFinite(terrain)
|
||||
? terrain
|
||||
: 0;
|
||||
ground?.warmGroundFloor?.([{ lat, lon }]);
|
||||
sphere.center = Cesium.Cartesian3.fromRadians(
|
||||
center.longitude,
|
||||
center.latitude,
|
||||
Math.max(0, height, center.height),
|
||||
);
|
||||
sphere.radius = 0;
|
||||
for (const position of positions)
|
||||
sphere.radius = Math.max(
|
||||
sphere.radius,
|
||||
Cesium.Cartesian3.distance(sphere.center, position),
|
||||
);
|
||||
viewer.camera?.flyToBoundingSphere?.(sphere, {
|
||||
offset: new Cesium.HeadingPitchRange(
|
||||
viewer.camera.heading || 0,
|
||||
-Math.PI / 2,
|
||||
Math.max(800, rangeForBoundingSphere(viewer, sphere.radius)),
|
||||
),
|
||||
duration,
|
||||
complete: () => guardCameraAboveGround(viewer, { lat, lon }),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { cancelCameraArrival } from '../data/cameraArrival.js';
|
||||
import { dataSourcePoints, flyToDataSource } from './flyToDataSource.js';
|
||||
|
||||
function source() {
|
||||
const ds = new Cesium.CustomDataSource('t');
|
||||
ds.entities.add({
|
||||
position: Cesium.Cartesian3.fromDegrees(-122.4862, 37.7694, -2667),
|
||||
billboard: { heightReference: Cesium.HeightReference.CLAMP_TO_GROUND },
|
||||
});
|
||||
ds.entities.add({
|
||||
polyline: {
|
||||
positions: Cesium.Cartesian3.fromDegreesArray([
|
||||
-122.49, 37.77, -122.48, 37.771,
|
||||
]),
|
||||
},
|
||||
});
|
||||
ds.entities.add({
|
||||
polygon: {
|
||||
hierarchy: Cesium.Cartesian3.fromDegreesArray([
|
||||
-122.5, 37.76, -122.49, 37.76, -122.49, 37.765,
|
||||
]),
|
||||
},
|
||||
});
|
||||
return ds;
|
||||
}
|
||||
|
||||
test('points come from positions, lines and polygons, as lon/lat only', () => {
|
||||
const points = dataSourcePoints(source());
|
||||
assert.equal(points.length, 6);
|
||||
assert.ok(Math.abs(points[0][0] + 122.4862) < 1e-6);
|
||||
assert.ok(Math.abs(points[0][1] - 37.7694) < 1e-6);
|
||||
});
|
||||
|
||||
test('the camera frames the footprint at the surface, never a buried center', () => {
|
||||
const calls = [];
|
||||
const viewer = {
|
||||
camera: {
|
||||
heading: 0,
|
||||
flyToBoundingSphere: (sphere, options) => calls.push({ sphere, options }),
|
||||
},
|
||||
flyTo: () => calls.push('viewer.flyTo'),
|
||||
};
|
||||
assert.equal(flyToDataSource(viewer, source()), true);
|
||||
const center = Cesium.Cartographic.fromCartesian(calls[0].sphere.center);
|
||||
assert.ok(Math.abs(center.height) < 50, `center height ${center.height}`);
|
||||
assert.ok(calls[0].options.offset.range >= 800);
|
||||
assert.equal(
|
||||
typeof calls[0].options.complete,
|
||||
'function',
|
||||
'the ground guard runs on landing',
|
||||
);
|
||||
assert.equal(
|
||||
flyToDataSource(viewer, new Cesium.CustomDataSource('empty')),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
calls.length,
|
||||
1,
|
||||
'empty sources never start deferred navigation',
|
||||
);
|
||||
});
|
||||
|
||||
test('a very long track is framed without spreading it into a call', () => {
|
||||
// 400k vertices: `push(...line)` throws RangeError (too many arguments)
|
||||
// well below this; the walk keeps a bounded sample and both ends.
|
||||
const n = 400_000;
|
||||
const line = new Array(n);
|
||||
for (let i = 0; i < n; i++)
|
||||
line[i] = Cesium.Cartesian3.fromDegrees(-120 + (i / n) * 2, 40);
|
||||
const ds = new Cesium.CustomDataSource('long');
|
||||
ds.entities.add({ polyline: { positions: line } });
|
||||
ds.entities.add({ position: Cesium.Cartesian3.fromDegrees(-110, 41) });
|
||||
const points = dataSourcePoints(ds);
|
||||
assert.equal(points.length, n + 1, 'every vertex contributes to framing');
|
||||
const lons = points.map(([lon]) => lon);
|
||||
assert.ok(
|
||||
lons.reduce((a, b) => Math.min(a, b), Infinity) < -119.99 &&
|
||||
lons.reduce((a, b) => Math.max(a, b), -Infinity) > -110.01,
|
||||
);
|
||||
assert.ok(lons.some((lon) => Math.abs(lon - -118.000005) < 0.01));
|
||||
});
|
||||
|
||||
test('framing includes a sparse interior outlier, walls and rotated overlays', () => {
|
||||
const ds = new Cesium.CustomDataSource('bounds');
|
||||
const line = Array.from({ length: 200031 }, () =>
|
||||
Cesium.Cartesian3.fromDegrees(0, 0),
|
||||
);
|
||||
line[12345] = Cesium.Cartesian3.fromDegrees(20, 10);
|
||||
ds.entities.add({ polyline: { positions: line } });
|
||||
ds.entities.add({
|
||||
wall: { positions: Cesium.Cartesian3.fromDegreesArray([30, 10, 31, 11]) },
|
||||
});
|
||||
ds.entities.add({
|
||||
rectangle: {
|
||||
coordinates: Cesium.Rectangle.fromDegrees(40, 0, 41, 1),
|
||||
rotation: Math.PI / 4,
|
||||
},
|
||||
});
|
||||
const points = dataSourcePoints(ds);
|
||||
assert.ok(points.some(([lon]) => Math.abs(lon - 20) < 1e-6));
|
||||
assert.ok(points.some(([lon]) => Math.abs(lon - 31) < 1e-6));
|
||||
assert.ok(points.some(([lon]) => lon > 41));
|
||||
});
|
||||
|
||||
test('portrait framing accounts for FOV, high ground and symmetric extents', () => {
|
||||
const ds = new Cesium.CustomDataSource('view');
|
||||
ds.entities.add({
|
||||
polyline: {
|
||||
positions: Cesium.Cartesian3.fromDegreesArray([-105, 39, -104.9, 39]),
|
||||
},
|
||||
});
|
||||
const calls = [];
|
||||
const viewer = {
|
||||
scene: { globe: { getHeight: () => 2600 } },
|
||||
camera: {
|
||||
frustum: { fov: Math.PI / 3, aspectRatio: 390 / 844 },
|
||||
flyToBoundingSphere: (sphere, options) => calls.push({ sphere, options }),
|
||||
},
|
||||
};
|
||||
flyToDataSource(viewer, ds);
|
||||
assert.ok(
|
||||
Math.abs(
|
||||
Cesium.Cartographic.fromCartesian(calls[0].sphere.center).height - 2600,
|
||||
) < 1e-6,
|
||||
);
|
||||
assert.equal(calls[0].options.offset.pitch, -Math.PI / 2);
|
||||
viewer.camera.frustum.aspectRatio = 16 / 9;
|
||||
flyToDataSource(viewer, ds);
|
||||
assert.ok(calls[0].options.offset.range > calls[1].options.offset.range);
|
||||
const symmetric = {
|
||||
entities: {
|
||||
values: [
|
||||
{ position: { getValue: () => new Cesium.Cartesian3(6378137, 0, 0) } },
|
||||
{ position: { getValue: () => new Cesium.Cartesian3(-6378137, 0, 0) } },
|
||||
],
|
||||
},
|
||||
};
|
||||
assert.doesNotThrow(() => flyToDataSource(viewer, symmetric));
|
||||
assert.ok(Number.isFinite(calls.at(-1).options.offset.range));
|
||||
assert.doesNotThrow(() => calls.at(-1).options.complete());
|
||||
cancelCameraArrival(viewer);
|
||||
});
|
||||
|
||||
test('non-finite positions and hidden features never enter the camera footprint', () => {
|
||||
const position = (p) => ({ position: { getValue: () => p } });
|
||||
const points = dataSourcePoints({
|
||||
entities: {
|
||||
values: [
|
||||
position(new Cesium.Cartesian3(NaN, 1, 2)),
|
||||
{
|
||||
...position(Cesium.Cartesian3.fromDegrees(10, 10)),
|
||||
isShowing: false,
|
||||
},
|
||||
position(Cesium.Cartesian3.fromDegrees(20, 20)),
|
||||
],
|
||||
},
|
||||
});
|
||||
assert.equal(points.length, 1);
|
||||
assert.ok(Math.abs(points[0][0] - 20) < 1e-6);
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* Build a native numeric field without listeners, parsing or commit policy.
|
||||
* Owners retain drafts, validation, input/change timing and disposal. Static
|
||||
* selects and number inputs share the gev-field surface in their templates;
|
||||
* options remain owned by each feature (no replacement popup or keyboard code).
|
||||
* @param {object} options
|
||||
* @param {Document} [options.documentRef]
|
||||
* @param {string} [options.className] Additional density/layout hooks.
|
||||
* @param {number|string} [options.min]
|
||||
* @param {number|string} [options.max]
|
||||
* @param {number|string} [options.step]
|
||||
* @param {number|string} [options.value]
|
||||
* @param {boolean} [options.disabled]
|
||||
* @param {string} [options.ariaLabel] Already translated accessible name.
|
||||
* @returns {HTMLInputElement}
|
||||
*/
|
||||
export function createNumberInput({
|
||||
documentRef = globalThis.document,
|
||||
className = '',
|
||||
min,
|
||||
max,
|
||||
step,
|
||||
value,
|
||||
disabled = false,
|
||||
ariaLabel,
|
||||
} = {}) {
|
||||
const input = documentRef.createElement('input');
|
||||
input.type = 'number';
|
||||
input.className = `gev-field${className ? ` ${className}` : ''}`;
|
||||
for (const [key, setting] of Object.entries({ min, max, step, value })) {
|
||||
if (setting !== undefined) input[key] = setting;
|
||||
}
|
||||
input.disabled = disabled;
|
||||
if (ariaLabel !== undefined) input.setAttribute('aria-label', ariaLabel);
|
||||
return input;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
/** Count rendered globe frames while the optional readout is visible. */
|
||||
export function createFrameRateMonitor({ viewer, documentRef = document }) {
|
||||
const host = documentRef.getElementById('title-bar');
|
||||
@@ -5,10 +6,11 @@ export function createFrameRateMonitor({ viewer, documentRef = document }) {
|
||||
if (!host || !frameEvent) return { destroy() {} };
|
||||
|
||||
const readout = documentRef.createElement('div');
|
||||
readout.className = 'frame-rate-readout';
|
||||
readout.className = 'frame-rate-readout scene-text-holdout';
|
||||
readout.hidden = true;
|
||||
// i18n-ignore: FPS is a unit code, the same in every language
|
||||
readout.textContent = 'FPS —';
|
||||
readout.title = 'Rendered globe frames per second · toggle with `';
|
||||
readout.title = t('Rendered globe frames per second · toggle with `');
|
||||
host.appendChild(readout);
|
||||
let removeFrameListener = null;
|
||||
let timer = null;
|
||||
@@ -27,6 +29,7 @@ export function createFrameRateMonitor({ viewer, documentRef = document }) {
|
||||
function show() {
|
||||
frames = 0;
|
||||
startedAt = performance.now();
|
||||
// i18n-ignore: FPS is a unit code, the same in every language
|
||||
readout.textContent = 'FPS —';
|
||||
readout.hidden = false;
|
||||
removeFrameListener = frameEvent.addEventListener(() => {
|
||||
@@ -36,6 +39,7 @@ export function createFrameRateMonitor({ viewer, documentRef = document }) {
|
||||
const now = performance.now();
|
||||
const elapsed = now - startedAt;
|
||||
readout.textContent =
|
||||
// i18n-ignore: FPS is a unit code, the same in every language
|
||||
documentRef.hidden || elapsed <= 0
|
||||
? 'FPS —'
|
||||
: `FPS ${Math.round((frames * 1000) / elapsed)}`;
|
||||
|
||||
@@ -0,0 +1,499 @@
|
||||
/** Session-local file controls, serial loading and application-owned navigation. */
|
||||
import {
|
||||
GEO_FILE_ACCEPT,
|
||||
GeoImportError,
|
||||
MAX_IMPORTED_FILES,
|
||||
loadGeoFile,
|
||||
} from '../data/geoFileImport.js';
|
||||
import {
|
||||
formatNumber,
|
||||
msg,
|
||||
registerUnsavedWork,
|
||||
t,
|
||||
tn,
|
||||
translateKnown,
|
||||
} from '../i18n/index.js';
|
||||
import { flyToDataSource } from './flyToDataSource.js';
|
||||
|
||||
// One color per file, in import order, from the whiteboard palette.
|
||||
const COLORS = ['#39d0ff', '#ffb547', '#5dff9f', '#ff6b6b', '#8be9ff'];
|
||||
|
||||
/**
|
||||
* Wire the Import control.
|
||||
* @param {{viewer: object, load?: Function, document?: Document}} deps
|
||||
* `load(file, {viewer, color})` defaults to `loadGeoFile`; tests pass a double.
|
||||
* @returns {{destroy: Function, importFiles: Function, list: Function,
|
||||
* setVisible: Function, flyTo: Function, remove: Function,
|
||||
* diagnostics: Function}|null}
|
||||
*/
|
||||
export function initGeoFileImport({
|
||||
viewer,
|
||||
load = loadGeoFile,
|
||||
document: doc = globalThis.document,
|
||||
flyToSource = flyToDataSource,
|
||||
navigation = null,
|
||||
ground = null,
|
||||
subscribeMapSource = null,
|
||||
}) {
|
||||
const button = doc?.getElementById('geo-import-button');
|
||||
const input = doc?.getElementById('geo-import-input');
|
||||
const listEl = doc?.getElementById('geo-import-list');
|
||||
const hint = doc?.getElementById('geo-import-hint');
|
||||
if (!viewer || !button || !input || !listEl) return null;
|
||||
|
||||
const imports = [];
|
||||
const listeners = [];
|
||||
let queue = Promise.resolve();
|
||||
let seq = 0;
|
||||
let colorAt = 0;
|
||||
let destroyed = false;
|
||||
let dragDepth = 0;
|
||||
let cameraIntent = 0;
|
||||
const lifetime = new AbortController();
|
||||
let removeMapSource;
|
||||
// Imports live for the page session: switching language (a reload) asks
|
||||
// first while any are on the map.
|
||||
const unregisterUnsavedWork = registerUnsavedWork(() =>
|
||||
!destroyed && imports.length ? msg('imported map files') : null,
|
||||
);
|
||||
|
||||
const listen = (target, type, listener, options) => {
|
||||
if (!target?.addEventListener) return;
|
||||
target.addEventListener(type, listener, options);
|
||||
listeners.push([target, type, listener, options]);
|
||||
};
|
||||
const setHint = (text) => {
|
||||
if (hint) hint.textContent = text || '';
|
||||
};
|
||||
const render = () => viewer.scene?.requestRender?.();
|
||||
let groundTimer,
|
||||
groundQueued = false,
|
||||
groundAgain = false;
|
||||
const groundRemovers = [];
|
||||
const scheduleGround = () => {
|
||||
if (destroyed || !imports.length) return;
|
||||
if (groundQueued) {
|
||||
groundAgain = true;
|
||||
return;
|
||||
}
|
||||
clearTimeout(groundTimer);
|
||||
groundTimer = setTimeout(() => {
|
||||
groundQueued = true;
|
||||
queue = queue
|
||||
.catch(() => {})
|
||||
.then(async () => {
|
||||
try {
|
||||
for (const item of imports) {
|
||||
if (destroyed) return;
|
||||
if (item.visible) await item.refreshGround?.(lifetime.signal);
|
||||
}
|
||||
render();
|
||||
} catch {
|
||||
if (!destroyed)
|
||||
setHint(
|
||||
t(
|
||||
'Ground heights could not be refreshed. Try the file again when the map has loaded.',
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
groundQueued = false;
|
||||
if (groundAgain) {
|
||||
groundAgain = false;
|
||||
scheduleGround();
|
||||
}
|
||||
}
|
||||
});
|
||||
}, 200);
|
||||
};
|
||||
removeMapSource = subscribeMapSource?.(scheduleGround);
|
||||
const ownEvent = (event, listener) => {
|
||||
const remove = event?.addEventListener?.(listener);
|
||||
if (remove) groundRemovers.push(remove);
|
||||
};
|
||||
ownEvent(viewer.camera?.moveEnd, scheduleGround);
|
||||
ownEvent(viewer.scene?.globe?.tileLoadProgressEvent, (pending) => {
|
||||
if (!pending) scheduleGround();
|
||||
});
|
||||
|
||||
/** Which row button has focus, so a re-render can give it back. */
|
||||
function focusedAction() {
|
||||
const active = doc.activeElement;
|
||||
if (!active || !listEl.contains?.(active)) return null;
|
||||
const row = active.closest?.('[data-import-id]');
|
||||
return row
|
||||
? { id: row.dataset.importId, action: active.dataset?.action }
|
||||
: null;
|
||||
}
|
||||
|
||||
function restoreFocus(was) {
|
||||
if (!was) return;
|
||||
const rows = [...listEl.querySelectorAll('[data-import-id]')];
|
||||
let row = rows.find((r) => r.dataset.importId === was.id);
|
||||
// The row is gone (removed): the next row's same control, else the
|
||||
// previous row's, else the Import button.
|
||||
if (!row && was.index != null)
|
||||
row = rows[Math.min(was.index, rows.length - 1)];
|
||||
const target =
|
||||
row?.querySelector?.(`button[data-action="${was.action}"]`) ||
|
||||
(row ? row.querySelector?.('button') : button);
|
||||
target?.focus?.();
|
||||
}
|
||||
|
||||
function renderList(keep = focusedAction()) {
|
||||
listEl.replaceChildren(
|
||||
...imports.map((item) => {
|
||||
const row = doc.createElement('li');
|
||||
row.className = 'geo-import-row';
|
||||
row.dataset.importId = item.id;
|
||||
const swatch = doc.createElement('span');
|
||||
// KML and KMZ draw with their own styles; their swatch says so
|
||||
// instead of claiming a color the globe does not show.
|
||||
swatch.className = `geo-import-swatch${item.ownStyles ? ' own-styles' : ''}`;
|
||||
if (!item.ownStyles) swatch.style.background = item.color;
|
||||
const name = doc.createElement('span');
|
||||
name.className = 'geo-import-name';
|
||||
// textContent, never markup: the name comes from the file system.
|
||||
name.textContent = item.name;
|
||||
name.title = `${item.name} — ${item.format.toUpperCase()}, ${tn(
|
||||
item.entityCount,
|
||||
'{count} map object',
|
||||
'{count} map objects',
|
||||
{ count: formatNumber(item.entityCount) },
|
||||
)}${item.ownStyles ? t(', drawn with its own styles') : ''}`;
|
||||
const actions = [
|
||||
[
|
||||
item.visible ? 'visibility' : 'visibility_off',
|
||||
item.visible
|
||||
? t('Hide {name}', { name: item.name })
|
||||
: t('Show {name}', { name: item.name }),
|
||||
'toggle',
|
||||
],
|
||||
['my_location', t('Fly to {name}', { name: item.name }), 'fly'],
|
||||
['close', t('Remove {name}', { name: item.name }), 'remove'],
|
||||
].map(([icon, label, action]) => {
|
||||
const btn = doc.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.className = 'geo-import-action';
|
||||
btn.dataset.action = action;
|
||||
btn.title = label;
|
||||
btn.setAttribute('aria-label', label);
|
||||
if (action === 'toggle')
|
||||
btn.setAttribute('aria-pressed', String(item.visible));
|
||||
const glyph = doc.createElement('span');
|
||||
glyph.className = 'material-symbols-outlined';
|
||||
glyph.setAttribute('aria-hidden', 'true');
|
||||
glyph.textContent = icon;
|
||||
btn.append(glyph);
|
||||
return btn;
|
||||
});
|
||||
row.append(swatch, name, ...actions);
|
||||
return row;
|
||||
}),
|
||||
);
|
||||
listEl.classList.toggle('visible', imports.length > 0);
|
||||
restoreFocus(keep);
|
||||
}
|
||||
|
||||
const find = (id) => imports.find((item) => item.id === id) || null;
|
||||
|
||||
/** Show or hide one imported file. */
|
||||
function setVisible(id, visible) {
|
||||
const item = find(id);
|
||||
if (!item) return false;
|
||||
item.visible = Boolean(visible);
|
||||
item.dataSource.show = item.visible;
|
||||
if (item.visible) scheduleGround();
|
||||
renderList();
|
||||
render();
|
||||
return true;
|
||||
}
|
||||
|
||||
// Not viewer.flyTo: it frames ground-clamped points underground until the
|
||||
// destination's terrain has loaded (see ./flyToDataSource.js).
|
||||
const fly = (item) => {
|
||||
if (!item.visible) setVisible(item.id, true);
|
||||
flyToSource(viewer, item.dataSource, { ground });
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* Fly the camera to one imported file: an immediate navigation, so Cockpit
|
||||
* can refuse it and the current follow/track owner is released first.
|
||||
*/
|
||||
function flyTo(id) {
|
||||
const item = find(id);
|
||||
if (!item) return false;
|
||||
if (typeof navigation?.runImmediateNavigation === 'function')
|
||||
return (
|
||||
navigation.runImmediateNavigation('file', () => fly(item)) !== false
|
||||
);
|
||||
return fly(item);
|
||||
}
|
||||
|
||||
/** Stamp a deferred fly for an import batch; false when refused. */
|
||||
const beginAutoFly = () =>
|
||||
typeof navigation?.beginDeferredLocationNavigation === 'function'
|
||||
? navigation.beginDeferredLocationNavigation()
|
||||
: null;
|
||||
/** Re-assert the stamp right before flying; false when superseded. */
|
||||
const autoFlyStillOwns = (generation) => {
|
||||
if (generation === false) return false;
|
||||
if (generation === null) return true;
|
||||
return typeof navigation?.reassertDeferredLocationNavigation === 'function'
|
||||
? navigation.reassertDeferredLocationNavigation(generation) === true
|
||||
: true;
|
||||
};
|
||||
|
||||
/** Remove one imported file from the globe and the list. */
|
||||
function remove(id) {
|
||||
const at = imports.findIndex((item) => item.id === id);
|
||||
if (at < 0) return false;
|
||||
const keep = focusedAction();
|
||||
if (keep) keep.index = at;
|
||||
const [item] = imports.splice(at, 1);
|
||||
viewer.dataSources?.remove?.(item.dataSource, true);
|
||||
item.revoke?.();
|
||||
renderList(keep);
|
||||
render();
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Import files, one after another. Returns one outcome per file.
|
||||
* @param {Iterable<File>} files
|
||||
* @returns {Promise<Array<{name: string, ok: boolean, id?: string,
|
||||
* removed?: number, error?: string}>>}
|
||||
*/
|
||||
function importFiles(files) {
|
||||
const list = [...(files || [])];
|
||||
if (destroyed || !list.length) return Promise.resolve([]);
|
||||
// Capture the user's intent when the files are chosen, including time
|
||||
// spent waiting for an earlier batch. Later navigation must still win.
|
||||
const generation = beginAutoFly();
|
||||
const intent = ++cameraIntent;
|
||||
const run = queue.then(() => importBatch(list, generation, intent));
|
||||
queue = run.catch(() => {});
|
||||
return run;
|
||||
}
|
||||
|
||||
async function importBatch(list, generation, intent) {
|
||||
const outcomes = [];
|
||||
if (destroyed || !list.length) return outcomes;
|
||||
for (const file of list) {
|
||||
if (destroyed) break;
|
||||
const fileName = String(file?.name || 'file');
|
||||
if (imports.length >= MAX_IMPORTED_FILES) {
|
||||
outcomes.push({
|
||||
name: fileName,
|
||||
ok: false,
|
||||
error: t('At most {count} files at once — remove one first.', {
|
||||
count: formatNumber(MAX_IMPORTED_FILES),
|
||||
}),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
setHint(t('Reading {name}…', { name: fileName }));
|
||||
const color = COLORS[colorAt % COLORS.length];
|
||||
let loaded;
|
||||
try {
|
||||
loaded = await load(file, { viewer, color, signal: lifetime.signal });
|
||||
} catch (error) {
|
||||
outcomes.push({
|
||||
name: fileName,
|
||||
ok: false,
|
||||
error:
|
||||
error instanceof GeoImportError || error?.name === 'GeoImportError'
|
||||
? t(error.template || error.message, error.values)
|
||||
: t('That file could not be read.'),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (destroyed) {
|
||||
loaded.revoke?.();
|
||||
break;
|
||||
}
|
||||
colorAt += 1;
|
||||
seq += 1;
|
||||
const item = {
|
||||
id: `import-${seq}`,
|
||||
name: loaded.name || fileName,
|
||||
format: loaded.format,
|
||||
ownStyles: loaded.format === 'kml' || loaded.format === 'kmz',
|
||||
entityCount: loaded.entityCount,
|
||||
removed: loaded.removed || 0,
|
||||
color,
|
||||
visible: true,
|
||||
dataSource: loaded.dataSource,
|
||||
revoke: loaded.revoke,
|
||||
refreshGround: loaded.refreshGround,
|
||||
};
|
||||
await viewer.dataSources.add(item.dataSource);
|
||||
if (destroyed) {
|
||||
viewer.dataSources.remove?.(item.dataSource, true);
|
||||
item.revoke?.();
|
||||
break;
|
||||
}
|
||||
loaded.mount?.();
|
||||
imports.push(item);
|
||||
renderList();
|
||||
render();
|
||||
outcomes.push({
|
||||
name: fileName,
|
||||
ok: true,
|
||||
id: item.id,
|
||||
removed: item.removed,
|
||||
});
|
||||
// Fly to the first file of a batch that lands, so a drop shows its
|
||||
// result, unless something else took the camera meanwhile.
|
||||
if (
|
||||
outcomes.filter((o) => o.ok).length === 1 &&
|
||||
intent === cameraIntent &&
|
||||
autoFlyStillOwns(generation)
|
||||
)
|
||||
fly(item);
|
||||
}
|
||||
if (!destroyed) setHint(summarize(outcomes));
|
||||
return outcomes;
|
||||
}
|
||||
|
||||
// ---- controls ----------------------------------------------------------
|
||||
input.accept = GEO_FILE_ACCEPT;
|
||||
listen(button, 'click', () => input.click());
|
||||
listen(input, 'change', () => {
|
||||
const files = [...(input.files || [])];
|
||||
// Clear the selection so choosing the same file again fires `change`.
|
||||
input.value = '';
|
||||
if (files.length) void importFiles(files);
|
||||
});
|
||||
listen(listEl, 'click', (event) => {
|
||||
const btn = event.target?.closest?.('button[data-action]');
|
||||
const id = btn?.closest?.('[data-import-id]')?.dataset.importId;
|
||||
if (!btn || !id) return;
|
||||
const action = btn.dataset.action;
|
||||
if (action === 'toggle') setVisible(id, !find(id)?.visible);
|
||||
else if (action === 'fly') flyTo(id);
|
||||
else if (action === 'remove') remove(id);
|
||||
});
|
||||
|
||||
// ---- drop onto the globe ----------------------------------------------
|
||||
const container = viewer.container;
|
||||
const gesture = () => {
|
||||
cameraIntent += 1;
|
||||
};
|
||||
listen(viewer.scene?.canvas || container, 'pointerdown', gesture, {
|
||||
passive: true,
|
||||
});
|
||||
listen(viewer.scene?.canvas || container, 'wheel', gesture, {
|
||||
passive: true,
|
||||
});
|
||||
const hasFiles = (event) =>
|
||||
[...(event.dataTransfer?.types || [])].includes('Files');
|
||||
const setDragging = (on) =>
|
||||
doc.body?.classList?.toggle('gev-geo-import-drag', on);
|
||||
listen(container, 'dragenter', (event) => {
|
||||
if (!hasFiles(event)) return;
|
||||
event.preventDefault();
|
||||
dragDepth += 1;
|
||||
setDragging(true);
|
||||
});
|
||||
listen(doc, 'dragover', (event) => {
|
||||
if (!hasFiles(event)) return;
|
||||
event.preventDefault();
|
||||
if (event.dataTransfer) event.dataTransfer.dropEffect = 'copy';
|
||||
});
|
||||
listen(container, 'dragleave', (event) => {
|
||||
if (!hasFiles(event)) return;
|
||||
dragDepth = Math.max(0, dragDepth - 1);
|
||||
if (!dragDepth) setDragging(false);
|
||||
});
|
||||
listen(doc, 'drop', (event) => {
|
||||
if (!hasFiles(event)) return;
|
||||
event.preventDefault();
|
||||
dragDepth = 0;
|
||||
setDragging(false);
|
||||
const files = [...(event.dataTransfer?.files || [])];
|
||||
if (files.length) void importFiles(files);
|
||||
});
|
||||
|
||||
renderList();
|
||||
|
||||
const handle = {
|
||||
importFiles,
|
||||
list: () =>
|
||||
imports.map(({ id, name, format, entityCount, removed, visible }) => ({
|
||||
id,
|
||||
name,
|
||||
format,
|
||||
entityCount,
|
||||
removed,
|
||||
visible,
|
||||
})),
|
||||
setVisible,
|
||||
flyTo,
|
||||
remove,
|
||||
diagnostics: () => ({
|
||||
files: imports.length,
|
||||
entities: imports.reduce((n, item) => n + item.entityCount, 0),
|
||||
listeners: listeners.length,
|
||||
destroyed,
|
||||
}),
|
||||
destroy() {
|
||||
if (destroyed) return;
|
||||
destroyed = true;
|
||||
unregisterUnsavedWork();
|
||||
lifetime.abort();
|
||||
removeMapSource?.();
|
||||
clearTimeout(groundTimer);
|
||||
for (const remove of groundRemovers) remove();
|
||||
for (const item of imports.splice(0)) {
|
||||
viewer.dataSources?.remove?.(item.dataSource, true);
|
||||
item.revoke?.();
|
||||
}
|
||||
for (const [target, type, listener, options] of listeners.splice(0))
|
||||
target.removeEventListener(type, listener, options);
|
||||
setDragging(false);
|
||||
listEl.replaceChildren();
|
||||
listEl.classList.remove('visible');
|
||||
setHint('');
|
||||
if (globalThis.window?.__gevGeoImport === handle)
|
||||
delete globalThis.window.__gevGeoImport;
|
||||
},
|
||||
};
|
||||
if (globalThis.window) globalThis.window.__gevGeoImport = handle;
|
||||
return handle;
|
||||
}
|
||||
|
||||
/**
|
||||
* One line for the hint after an import batch.
|
||||
* @param {Array<{name: string, ok: boolean, error?: string, removed?: number}>} outcomes
|
||||
* @returns {string}
|
||||
*/
|
||||
export function summarize(outcomes) {
|
||||
const failed = outcomes.filter((o) => !o.ok);
|
||||
const added = outcomes.length - failed.length;
|
||||
const parts = [];
|
||||
if (added)
|
||||
parts.push(
|
||||
tn(added, 'Added {count} file.', 'Added {count} files.', {
|
||||
count: formatNumber(added),
|
||||
}),
|
||||
);
|
||||
// Import errors stay English in the outcome; they translate here.
|
||||
const error = translateKnown(failed[0]?.error);
|
||||
if (failed.length === 1) parts.push(`${failed[0].name}: ${error}`);
|
||||
else if (failed.length > 1)
|
||||
parts.push(
|
||||
tn(
|
||||
failed.length,
|
||||
'{count} file could not be added ({name}: {error})',
|
||||
'{count} files could not be added ({name}: {error})',
|
||||
{ count: formatNumber(failed.length), name: failed[0].name, error },
|
||||
),
|
||||
);
|
||||
const stripped = outcomes.reduce(
|
||||
(n, o) => n + (o.ok ? o.removed || 0 : 0),
|
||||
0,
|
||||
);
|
||||
if (added && stripped) parts.push(t('Some KML content was left out.'));
|
||||
return parts.join(' ');
|
||||
}
|
||||
@@ -0,0 +1,731 @@
|
||||
// Behavioral tests for DISPLAY ▸ Import: the controller is driven against
|
||||
// fake DOM and viewer doubles with an injected loader, and its observable
|
||||
// effects are asserted — data sources added and removed, list rows, the hint,
|
||||
// drop handling, the file limit, and what destroy() gives back. Real parsing
|
||||
// and rendering run in `scripts/qa-geo-import.mjs`.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { initGeoFileImport, summarize } from './geoFileImport.js';
|
||||
import { GeoImportError, MAX_IMPORTED_FILES } from '../data/geoFileImport.js';
|
||||
import { describeUnsavedWork } from '../i18n/index.js';
|
||||
|
||||
class FakeClassList {
|
||||
constructor() {
|
||||
this.names = new Set();
|
||||
}
|
||||
add(...n) {
|
||||
n.forEach((x) => this.names.add(x));
|
||||
}
|
||||
remove(...n) {
|
||||
n.forEach((x) => this.names.delete(x));
|
||||
}
|
||||
contains(n) {
|
||||
return this.names.has(n);
|
||||
}
|
||||
toggle(n, force) {
|
||||
const on = force === undefined ? !this.names.has(n) : Boolean(force);
|
||||
if (on) this.names.add(n);
|
||||
else this.names.delete(n);
|
||||
return on;
|
||||
}
|
||||
}
|
||||
|
||||
// The one focused element across every fake document (tests run one at a time).
|
||||
const focus = { active: null };
|
||||
|
||||
class FakeElement {
|
||||
constructor(tagName = 'div', id = '') {
|
||||
this.tagName = tagName.toUpperCase();
|
||||
this.id = id;
|
||||
this.classList = new FakeClassList();
|
||||
this.dataset = {};
|
||||
this.style = {};
|
||||
this.attributes = new Map();
|
||||
this.children = [];
|
||||
this.parent = null;
|
||||
this.listeners = [];
|
||||
this.textContent = '';
|
||||
this.value = '';
|
||||
this.clicks = 0;
|
||||
}
|
||||
set className(v) {
|
||||
this.classList = new FakeClassList();
|
||||
String(v)
|
||||
.split(/\s+/)
|
||||
.filter(Boolean)
|
||||
.forEach((n) => this.classList.add(n));
|
||||
}
|
||||
setAttribute(n, v) {
|
||||
this.attributes.set(n, String(v));
|
||||
}
|
||||
getAttribute(n) {
|
||||
return this.attributes.get(n) ?? null;
|
||||
}
|
||||
append(...kids) {
|
||||
for (const k of kids) {
|
||||
k.parent = this;
|
||||
this.children.push(k);
|
||||
}
|
||||
}
|
||||
replaceChildren(...kids) {
|
||||
this.children = [];
|
||||
this.append(...kids);
|
||||
}
|
||||
addEventListener(type, listener, options) {
|
||||
this.listeners.push({ type, listener, options });
|
||||
}
|
||||
removeEventListener(type, listener) {
|
||||
const at = this.listeners.findIndex(
|
||||
(l) => l.type === type && l.listener === listener,
|
||||
);
|
||||
if (at >= 0) this.listeners.splice(at, 1);
|
||||
}
|
||||
emit(type, event = {}) {
|
||||
for (const { listener } of this.listeners.filter((l) => l.type === type))
|
||||
listener({
|
||||
target: this,
|
||||
preventDefault() {
|
||||
this.prevented = true;
|
||||
},
|
||||
...event,
|
||||
});
|
||||
}
|
||||
click() {
|
||||
this.clicks += 1;
|
||||
this.emit('click');
|
||||
}
|
||||
focus() {
|
||||
focus.active = this;
|
||||
}
|
||||
contains(el) {
|
||||
for (let at = el; at; at = at.parent) if (at === this) return true;
|
||||
return false;
|
||||
}
|
||||
*walk() {
|
||||
for (const kid of this.children) {
|
||||
yield kid;
|
||||
yield* kid.walk();
|
||||
}
|
||||
}
|
||||
querySelectorAll(selector) {
|
||||
if (selector !== '[data-import-id]') throw new Error(`fake: ${selector}`);
|
||||
return [...this.walk()].filter((el) => el.dataset.importId);
|
||||
}
|
||||
querySelector(selector) {
|
||||
const exact = /^button\[data-action="([a-z]+)"\]$/.exec(selector);
|
||||
for (const el of this.walk()) {
|
||||
if (el.tagName !== 'BUTTON') continue;
|
||||
if (selector === 'button' || (exact && el.dataset.action === exact[1]))
|
||||
return el;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
closest(selector) {
|
||||
for (let el = this; el; el = el.parent) {
|
||||
if (
|
||||
selector === 'button[data-action]' &&
|
||||
el.tagName === 'BUTTON' &&
|
||||
el.dataset.action
|
||||
)
|
||||
return el;
|
||||
if (selector === '[data-import-id]' && el.dataset.importId) return el;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function setup({ load, navigation, flyToSource, subscribeMapSource } = {}) {
|
||||
focus.active = null;
|
||||
const els = {
|
||||
'geo-import-button': new FakeElement('button', 'geo-import-button'),
|
||||
'geo-import-input': new FakeElement('input', 'geo-import-input'),
|
||||
'geo-import-list': new FakeElement('ul', 'geo-import-list'),
|
||||
'geo-import-hint': new FakeElement('span', 'geo-import-hint'),
|
||||
};
|
||||
const document = {
|
||||
body: new FakeElement('body'),
|
||||
getElementById: (id) => els[id] ?? null,
|
||||
createElement: (tag) => new FakeElement(tag),
|
||||
get activeElement() {
|
||||
return focus.active;
|
||||
},
|
||||
};
|
||||
Object.setPrototypeOf(document, new FakeElement('document'));
|
||||
const added = [];
|
||||
const removed = [];
|
||||
const flights = [];
|
||||
let renders = 0;
|
||||
const viewer = {
|
||||
container: new FakeElement('div', 'cesiumContainer'),
|
||||
scene: { requestRender: () => (renders += 1) },
|
||||
dataSources: {
|
||||
add: async (ds) => {
|
||||
added.push(ds);
|
||||
return ds;
|
||||
},
|
||||
remove: (ds, destroy) => {
|
||||
removed.push({ ds, destroy });
|
||||
return true;
|
||||
},
|
||||
},
|
||||
flyTo: (target) => flights.push(target),
|
||||
};
|
||||
const revoked = [];
|
||||
const loads = [];
|
||||
const defaultLoad = async (file, opts) => {
|
||||
loads.push({ file, opts });
|
||||
if (file.fail) throw new GeoImportError(file.fail);
|
||||
if (file.crash) throw new Error('boom');
|
||||
return {
|
||||
dataSource: { show: true },
|
||||
name: file.name,
|
||||
format: 'geojson',
|
||||
entityCount: 3,
|
||||
removed: file.removed || 0,
|
||||
revoke: () => revoked.push(file.name),
|
||||
};
|
||||
};
|
||||
const tool = initGeoFileImport({
|
||||
viewer,
|
||||
load: load || defaultLoad,
|
||||
document,
|
||||
...(navigation ? { navigation } : {}),
|
||||
...(subscribeMapSource ? { subscribeMapSource } : {}),
|
||||
flyToSource: flyToSource || ((_viewer, ds) => flights.push(ds)),
|
||||
});
|
||||
return {
|
||||
tool,
|
||||
els,
|
||||
document,
|
||||
viewer,
|
||||
added,
|
||||
removed,
|
||||
flights,
|
||||
revoked,
|
||||
loads,
|
||||
renders: () => renders,
|
||||
};
|
||||
}
|
||||
const file = (name, extra = {}) => ({ name, size: 10, ...extra });
|
||||
const rows = (els) => els['geo-import-list'].children;
|
||||
const action = (row, name) =>
|
||||
row.children.find((c) => c.dataset.action === name);
|
||||
|
||||
// Runs first: tools left by later tests would answer the same registry.
|
||||
test('imported files make the language switch ask first', async () => {
|
||||
const t = setup();
|
||||
assert.deepEqual(describeUnsavedWork(), []);
|
||||
await t.tool.importFiles([file('a.geojson')]);
|
||||
assert.deepEqual(describeUnsavedWork(), ['imported map files']);
|
||||
t.tool.remove(t.tool.list()[0].id);
|
||||
assert.deepEqual(describeUnsavedWork(), [], 'nothing left to lose');
|
||||
await t.tool.importFiles([file('b.kml')]);
|
||||
t.tool.destroy();
|
||||
assert.deepEqual(describeUnsavedWork(), [], 'destroy unregisters');
|
||||
});
|
||||
|
||||
test('returns null without its markup or viewer', () => {
|
||||
const document = { getElementById: () => null };
|
||||
assert.equal(initGeoFileImport({ viewer: {}, document }), null);
|
||||
assert.equal(
|
||||
initGeoFileImport({
|
||||
viewer: null,
|
||||
document: { getElementById: () => new FakeElement() },
|
||||
}),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('the Import button opens the picker and a pick imports each file', async () => {
|
||||
const t = setup();
|
||||
t.els['geo-import-button'].click();
|
||||
assert.equal(t.els['geo-import-input'].clicks, 1);
|
||||
assert.equal(
|
||||
t.els['geo-import-input'].accept,
|
||||
'.geojson,.json,.kml,.kmz,.gpx',
|
||||
);
|
||||
const out = await t.tool.importFiles([file('a.geojson'), file('b.kml')]);
|
||||
assert.deepEqual(
|
||||
out.map((o) => o.ok),
|
||||
[true, true],
|
||||
);
|
||||
assert.equal(t.added.length, 2);
|
||||
assert.notEqual(
|
||||
t.loads[0].opts.color,
|
||||
t.loads[1].opts.color,
|
||||
'each file gets its own color',
|
||||
);
|
||||
assert.equal(rows(t.els).length, 2);
|
||||
assert.ok(t.els['geo-import-list'].classList.contains('visible'));
|
||||
assert.equal(t.flights.length, 1, 'the first file of a batch is flown to');
|
||||
assert.equal(t.els['geo-import-hint'].textContent, 'Added 2 files.');
|
||||
assert.deepEqual(
|
||||
t.tool.list().map((f) => f.name),
|
||||
['a.geojson', 'b.kml'],
|
||||
);
|
||||
});
|
||||
|
||||
test('file names are text, never markup', async () => {
|
||||
const t = setup();
|
||||
await t.tool.importFiles([file('<img src=x onerror=alert(1)>.kml')]);
|
||||
const name = rows(t.els)[0].children.find((c) =>
|
||||
c.classList.contains('geo-import-name'),
|
||||
);
|
||||
assert.equal(name.textContent, '<img src=x onerror=alert(1)>.kml');
|
||||
assert.equal(name.innerHTML, undefined);
|
||||
});
|
||||
|
||||
test('row buttons hide, show, fly to and remove a file', async () => {
|
||||
const t = setup();
|
||||
await t.tool.importFiles([file('a.gpx')]);
|
||||
const [{ id }] = t.tool.list();
|
||||
const ds = t.added[0];
|
||||
// the click lands on the glyph inside the button, as in a browser
|
||||
const glyphClick = (name) =>
|
||||
t.els['geo-import-list'].emit('click', {
|
||||
target: action(rows(t.els)[0], name).children[0],
|
||||
});
|
||||
assert.equal(ds.show, true);
|
||||
glyphClick('toggle');
|
||||
assert.equal(ds.show, false);
|
||||
assert.equal(t.tool.list()[0].visible, false);
|
||||
assert.equal(
|
||||
action(rows(t.els)[0], 'toggle').getAttribute('aria-pressed'),
|
||||
'false',
|
||||
);
|
||||
glyphClick('fly');
|
||||
assert.equal(ds.show, true, 'flying to a hidden file shows it');
|
||||
assert.equal(t.flights.at(-1), ds);
|
||||
glyphClick('remove');
|
||||
assert.deepEqual(t.removed, [{ ds, destroy: true }]);
|
||||
assert.deepEqual(t.revoked, ['a.gpx']);
|
||||
assert.equal(t.tool.list().length, 0);
|
||||
assert.ok(!t.els['geo-import-list'].classList.contains('visible'));
|
||||
assert.equal(t.tool.remove(id), false);
|
||||
});
|
||||
|
||||
test('a refused file says why and does not stop the rest of the batch', async () => {
|
||||
const t = setup();
|
||||
const out = await t.tool.importFiles([
|
||||
file('bad.kml', { fail: 'That KML file is not valid XML.' }),
|
||||
file('odd.gpx', { crash: true }),
|
||||
file('good.geojson'),
|
||||
]);
|
||||
assert.deepEqual(
|
||||
out.map((o) => o.ok),
|
||||
[false, false, true],
|
||||
);
|
||||
assert.equal(out[0].error, 'That KML file is not valid XML.');
|
||||
assert.match(out[1].error, /could not be read\./);
|
||||
assert.match(
|
||||
t.els['geo-import-hint'].textContent,
|
||||
/^Added 1 file\. 2 files could not be added \(bad\.kml: That KML file is not valid XML\.\)/,
|
||||
);
|
||||
assert.equal(t.tool.list().length, 1);
|
||||
});
|
||||
|
||||
test('the number of files on the globe is bounded', async () => {
|
||||
const t = setup();
|
||||
const many = Array.from({ length: MAX_IMPORTED_FILES + 2 }, (_, i) =>
|
||||
file(`f${i}.geojson`),
|
||||
);
|
||||
const out = await t.tool.importFiles(many);
|
||||
assert.equal(out.filter((o) => o.ok).length, MAX_IMPORTED_FILES);
|
||||
assert.match(out.at(-1).error, /At most 12 files/);
|
||||
assert.equal(
|
||||
t.loads.length,
|
||||
MAX_IMPORTED_FILES,
|
||||
'files over the limit are not even read',
|
||||
);
|
||||
});
|
||||
|
||||
test('dropping files on the globe imports them; other drags are left alone', async () => {
|
||||
const t = setup();
|
||||
const c = t.viewer.container;
|
||||
const files = { types: ['Files'], files: [file('drop.kmz')] };
|
||||
let ev = { dataTransfer: { types: ['text/plain'] } };
|
||||
t.document.emit('dragover', ev);
|
||||
c.emit('dragenter', { dataTransfer: files });
|
||||
assert.ok(t.document.body.classList.contains('gev-geo-import-drag'));
|
||||
c.emit('dragleave', { dataTransfer: files });
|
||||
assert.ok(!t.document.body.classList.contains('gev-geo-import-drag'));
|
||||
c.emit('dragenter', { dataTransfer: files });
|
||||
t.document.emit('drop', { dataTransfer: files });
|
||||
assert.ok(!t.document.body.classList.contains('gev-geo-import-drag'));
|
||||
await new Promise((r) => setImmediate(r));
|
||||
assert.deepEqual(
|
||||
t.tool.list().map((f) => f.name),
|
||||
['drop.kmz'],
|
||||
);
|
||||
});
|
||||
|
||||
test('stripped KML content is mentioned once, for the batch that had it', () => {
|
||||
assert.equal(
|
||||
summarize([{ name: 'a.kml', ok: true, removed: 3 }]),
|
||||
'Added 1 file. Some KML content was left out.',
|
||||
);
|
||||
assert.equal(
|
||||
summarize([{ name: 'b.geojson', ok: true, removed: 0 }]),
|
||||
'Added 1 file.',
|
||||
);
|
||||
});
|
||||
|
||||
test('destroy removes every file and listener and the window handle', async () => {
|
||||
globalThis.window = {};
|
||||
try {
|
||||
const t = setup();
|
||||
assert.equal(globalThis.window.__gevGeoImport, t.tool);
|
||||
await t.tool.importFiles([file('a.geojson'), file('b.geojson')]);
|
||||
t.tool.destroy();
|
||||
assert.equal(t.removed.length, 2);
|
||||
assert.deepEqual(t.revoked.sort(), ['a.geojson', 'b.geojson']);
|
||||
for (const el of [
|
||||
t.viewer.container,
|
||||
t.els['geo-import-button'],
|
||||
t.els['geo-import-input'],
|
||||
t.els['geo-import-list'],
|
||||
])
|
||||
assert.equal(el.listeners.length, 0);
|
||||
assert.equal(rows(t.els).length, 0);
|
||||
assert.equal(globalThis.window.__gevGeoImport, undefined);
|
||||
assert.equal(t.tool.diagnostics().destroyed, true);
|
||||
} finally {
|
||||
delete globalThis.window;
|
||||
}
|
||||
});
|
||||
|
||||
test('a file that finishes loading after destroy is released, not added', async () => {
|
||||
let release;
|
||||
const gate = new Promise((r) => (release = r));
|
||||
const revoked = [];
|
||||
const t = setup({
|
||||
load: async () => {
|
||||
await gate;
|
||||
return {
|
||||
dataSource: {},
|
||||
name: 'late',
|
||||
format: 'kml',
|
||||
entityCount: 1,
|
||||
removed: 0,
|
||||
revoke: () => revoked.push('late'),
|
||||
};
|
||||
},
|
||||
});
|
||||
const pending = t.tool.importFiles([file('late.kml')]);
|
||||
// Imports are queued: let the batch start loading before destroy lands.
|
||||
await new Promise((r) => setImmediate(r));
|
||||
t.tool.destroy();
|
||||
release();
|
||||
await pending;
|
||||
assert.equal(t.added.length, 0);
|
||||
assert.deepEqual(revoked, ['late']);
|
||||
});
|
||||
|
||||
test('the application composition wires the import and owns its teardown', () => {
|
||||
const tools = fs.readFileSync(
|
||||
new URL('../app/tools.js', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
const drawAt = tools.indexOf(
|
||||
'const drawTool = initDrawTool({ viewer, annotations });',
|
||||
);
|
||||
const importAt = tools.indexOf('const geoFileImport = initGeoFileImport({');
|
||||
assert.ok(importAt > drawAt && drawAt >= 0);
|
||||
// Fly-to goes through the application shell's navigation policy.
|
||||
assert.match(
|
||||
tools.slice(importAt, importAt + 200),
|
||||
/navigation: styleManager/,
|
||||
);
|
||||
assert.ok(tools.indexOf('defer(() => geoFileImport?.destroy());') > importAt);
|
||||
const markup = fs.readFileSync(
|
||||
new URL('./templates/display-controls.html', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
for (const id of [
|
||||
'geo-import-button',
|
||||
'geo-import-input',
|
||||
'geo-import-list',
|
||||
'geo-import-hint',
|
||||
])
|
||||
assert.ok(
|
||||
markup.includes(`id="${id}"`),
|
||||
`${id} missing from the DISPLAY template`,
|
||||
);
|
||||
});
|
||||
|
||||
test('two imports at once never pass the file cap: batches run one after another', async () => {
|
||||
const t = setup();
|
||||
const first = t.tool.importFiles(
|
||||
Array.from({ length: 8 }, (_, i) => file(`a${i}.geojson`)),
|
||||
);
|
||||
const second = t.tool.importFiles(
|
||||
Array.from({ length: 8 }, (_, i) => file(`b${i}.geojson`)),
|
||||
);
|
||||
const [a, b] = await Promise.all([first, second]);
|
||||
assert.equal(t.tool.list().length, MAX_IMPORTED_FILES);
|
||||
assert.equal(a.filter((o) => o.ok).length, 8);
|
||||
assert.equal(b.filter((o) => o.ok).length, MAX_IMPORTED_FILES - 8);
|
||||
assert.equal(b.filter((o) => !o.ok).length, 16 - MAX_IMPORTED_FILES);
|
||||
// The second batch's loads started only after the first batch finished.
|
||||
assert.deepEqual(
|
||||
t.loads.map((l) => l.file.name.slice(0, 1)).join(''),
|
||||
'a'.repeat(8) + 'b'.repeat(MAX_IMPORTED_FILES - 8),
|
||||
);
|
||||
});
|
||||
|
||||
function navigationDouble({ immediate = true, reassert = true } = {}) {
|
||||
const calls = [];
|
||||
let generation = 0;
|
||||
return {
|
||||
calls,
|
||||
runImmediateNavigation(noun, navigate) {
|
||||
calls.push(['immediate', noun]);
|
||||
return immediate ? navigate(++generation) : false;
|
||||
},
|
||||
beginDeferredLocationNavigation() {
|
||||
calls.push(['begin']);
|
||||
return ++generation;
|
||||
},
|
||||
reassertDeferredLocationNavigation(g) {
|
||||
calls.push(['reassert', g]);
|
||||
return reassert;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('a direct camera gesture cancels the fly-to of a file still being read', async () => {
|
||||
for (const gesture of ['pointerdown', 'wheel']) {
|
||||
let release;
|
||||
const t = setup({
|
||||
load: async () => {
|
||||
await new Promise((r) => (release = r));
|
||||
return {
|
||||
name: 'slow.geojson',
|
||||
format: 'geojson',
|
||||
entityCount: 1,
|
||||
dataSource: {},
|
||||
};
|
||||
},
|
||||
});
|
||||
const result = t.tool.importFiles([file('slow.geojson')]);
|
||||
await new Promise((r) => setImmediate(r));
|
||||
t.viewer.container.emit(gesture);
|
||||
release();
|
||||
await result;
|
||||
assert.equal(t.added.length, 1);
|
||||
assert.equal(t.flights.length, 0);
|
||||
t.tool.destroy();
|
||||
assert.equal(t.document.listeners.length, 0);
|
||||
}
|
||||
});
|
||||
|
||||
test('dropping on panel controls is accepted and file drags prevent browser navigation', async () => {
|
||||
const t = setup();
|
||||
let prevented = 0;
|
||||
const event = {
|
||||
target: t.els['geo-import-button'],
|
||||
dataTransfer: { types: ['Files'], files: [file('panel.kml')] },
|
||||
preventDefault: () => prevented++,
|
||||
};
|
||||
t.document.emit('dragover', event);
|
||||
t.document.emit('drop', event);
|
||||
await new Promise((r) => setImmediate(r));
|
||||
assert.equal(prevented, 2);
|
||||
assert.equal(t.tool.list()[0].name, 'panel.kml');
|
||||
t.tool.destroy();
|
||||
assert.equal(t.document.listeners.length, 0);
|
||||
});
|
||||
|
||||
test('ground refresh coalesces map changes and releases its subscription on teardown', async () => {
|
||||
let changed,
|
||||
unsubscribed = 0,
|
||||
refreshed = 0;
|
||||
const t = setup({
|
||||
subscribeMapSource: (listener) => {
|
||||
changed = listener;
|
||||
return () => unsubscribed++;
|
||||
},
|
||||
load: async () => ({
|
||||
name: 'point.geojson',
|
||||
format: 'geojson',
|
||||
entityCount: 1,
|
||||
dataSource: {},
|
||||
refreshGround: async () => refreshed++,
|
||||
}),
|
||||
});
|
||||
await t.tool.importFiles([file('point.geojson')]);
|
||||
changed();
|
||||
changed();
|
||||
changed();
|
||||
await new Promise((resolve) => setTimeout(resolve, 300));
|
||||
assert.equal(refreshed, 1);
|
||||
t.tool.destroy();
|
||||
changed();
|
||||
await new Promise((resolve) => setTimeout(resolve, 250));
|
||||
assert.equal(refreshed, 1);
|
||||
assert.equal(unsubscribed, 1);
|
||||
});
|
||||
|
||||
test('Fly to is an immediate navigation that Cockpit can refuse', async () => {
|
||||
const flown = [];
|
||||
const nav = navigationDouble({ immediate: false });
|
||||
const t = setup({ navigation: nav, flyToSource: (v, ds) => flown.push(ds) });
|
||||
// Batch auto-fly is deferred: stamped at the start, re-asserted before flying.
|
||||
await t.tool.importFiles([file('a.geojson')]);
|
||||
assert.deepEqual(nav.calls, [['begin'], ['reassert', 1]]);
|
||||
assert.equal(flown.length, 1);
|
||||
// The button goes through the immediate route; refused, nothing flies.
|
||||
const id = t.tool.list()[0].id;
|
||||
assert.equal(t.tool.flyTo(id), false);
|
||||
assert.deepEqual(nav.calls.at(-1), ['immediate', 'file']);
|
||||
assert.equal(flown.length, 1);
|
||||
const nav2 = navigationDouble();
|
||||
const t2 = setup({
|
||||
navigation: nav2,
|
||||
flyToSource: (v, ds) => flown.push(ds),
|
||||
});
|
||||
await t2.tool.importFiles([file('b.geojson')]);
|
||||
assert.equal(t2.tool.flyTo(t2.tool.list()[0].id), true);
|
||||
assert.equal(flown.length, 3);
|
||||
});
|
||||
|
||||
test('a slow import does not fly once something newer took the camera', async () => {
|
||||
let release;
|
||||
const gate = new Promise((r) => (release = r));
|
||||
const flown = [];
|
||||
const nav = navigationDouble({ reassert: false });
|
||||
const t = setup({
|
||||
navigation: nav,
|
||||
flyToSource: (v, ds) => flown.push(ds),
|
||||
load: async (f) => {
|
||||
await gate;
|
||||
return {
|
||||
dataSource: {},
|
||||
name: f.name,
|
||||
format: 'geojson',
|
||||
entityCount: 1,
|
||||
removed: 0,
|
||||
revoke() {},
|
||||
};
|
||||
},
|
||||
});
|
||||
const pending = t.tool.importFiles([file('slow.geojson')]);
|
||||
release();
|
||||
const [out] = await pending;
|
||||
assert.equal(out.ok, true);
|
||||
assert.deepEqual(nav.calls, [['begin'], ['reassert', 1]]);
|
||||
assert.equal(flown.length, 0);
|
||||
});
|
||||
|
||||
test('a queued import cannot fly over navigation that happened while it waited', async () => {
|
||||
let release;
|
||||
const gate = new Promise((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
let generation = 0;
|
||||
const flown = [];
|
||||
const nav = {
|
||||
beginDeferredLocationNavigation: () => ++generation,
|
||||
reassertDeferredLocationNavigation: (stamp) => stamp === generation,
|
||||
};
|
||||
const t = setup({
|
||||
navigation: nav,
|
||||
flyToSource: (v, ds) => flown.push(ds),
|
||||
load: async (f) => {
|
||||
if (f.name === 'first.geojson') await gate;
|
||||
return {
|
||||
dataSource: {},
|
||||
name: f.name,
|
||||
format: 'geojson',
|
||||
entityCount: 1,
|
||||
revoke() {},
|
||||
};
|
||||
},
|
||||
});
|
||||
const first = t.tool.importFiles([file('first.geojson')]);
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
const queued = t.tool.importFiles([file('queued.geojson')]);
|
||||
generation++; // A newer user camera action while the second batch is waiting.
|
||||
release();
|
||||
const results = await Promise.all([first, queued]);
|
||||
assert.ok(results.every(([outcome]) => outcome.ok));
|
||||
assert.equal(t.tool.list().length, 2);
|
||||
assert.equal(flown.length, 0);
|
||||
});
|
||||
|
||||
test('a refused deferred stamp (Cockpit) imports without flying', async () => {
|
||||
const flown = [];
|
||||
const nav = navigationDouble();
|
||||
nav.beginDeferredLocationNavigation = () => false;
|
||||
nav.reassertDeferredLocationNavigation = () => {
|
||||
throw new Error('must not re-assert a refused stamp');
|
||||
};
|
||||
const t = setup({ navigation: nav, flyToSource: (v, ds) => flown.push(ds) });
|
||||
const [out] = await t.tool.importFiles([file('a.geojson')]);
|
||||
assert.equal(out.ok, true);
|
||||
assert.equal(flown.length, 0);
|
||||
});
|
||||
|
||||
test('keyboard focus stays on the control after hide, show and remove', async () => {
|
||||
const t = setup();
|
||||
await t.tool.importFiles([file('a.geojson'), file('b.geojson')]);
|
||||
// Clicks reach the list's delegated listener, as they bubble in a page.
|
||||
const press = (btn) =>
|
||||
t.els['geo-import-list'].emit('click', { target: btn });
|
||||
const [first] = rows(t.els);
|
||||
action(first, 'toggle').focus();
|
||||
press(action(first, 'toggle'));
|
||||
// The list was rebuilt; focus is on the NEW toggle of the same row.
|
||||
const again = rows(t.els)[0];
|
||||
assert.notEqual(again, first);
|
||||
assert.equal(t.document.activeElement, action(again, 'toggle'));
|
||||
assert.equal(action(again, 'toggle').getAttribute('aria-pressed'), 'false');
|
||||
press(action(again, 'toggle'));
|
||||
assert.equal(t.document.activeElement, action(rows(t.els)[0], 'toggle'));
|
||||
// Remove the first row: focus moves to the same control on the next row.
|
||||
action(rows(t.els)[0], 'remove').focus();
|
||||
press(action(rows(t.els)[0], 'remove'));
|
||||
assert.equal(rows(t.els).length, 1);
|
||||
assert.equal(t.document.activeElement, action(rows(t.els)[0], 'remove'));
|
||||
// Remove the last row: focus goes back to the Import button.
|
||||
press(action(rows(t.els)[0], 'remove'));
|
||||
assert.equal(t.document.activeElement, t.els['geo-import-button']);
|
||||
});
|
||||
|
||||
test('KML and KMZ rows say they keep their own styles instead of showing a color', async () => {
|
||||
const t = setup({
|
||||
load: async (f) => ({
|
||||
dataSource: {},
|
||||
name: f.name,
|
||||
format: f.name.endsWith('.kml') ? 'kml' : 'gpx',
|
||||
entityCount: 2,
|
||||
removed: 0,
|
||||
revoke() {},
|
||||
}),
|
||||
});
|
||||
await t.tool.importFiles([file('a.kml'), file('b.gpx')]);
|
||||
const [kml, gpx] = rows(t.els);
|
||||
assert.ok(kml.children[0].classList.contains('own-styles'));
|
||||
assert.equal(kml.children[0].style.background, undefined);
|
||||
assert.match(kml.children[1].title, /drawn with its own styles/);
|
||||
assert.ok(!gpx.children[0].classList.contains('own-styles'));
|
||||
assert.ok(gpx.children[0].style.background);
|
||||
});
|
||||
|
||||
test('the map-object count in a row title keeps digit grouping', async () => {
|
||||
const t = setup({
|
||||
load: async (f) => ({
|
||||
dataSource: {},
|
||||
name: f.name,
|
||||
format: 'geojson',
|
||||
entityCount: 12345,
|
||||
removed: 0,
|
||||
revoke() {},
|
||||
}),
|
||||
});
|
||||
await t.tool.importFiles([file('big.geojson')]);
|
||||
const [row] = rows(t.els);
|
||||
assert.match(row.children[1].title, /12,345 map objects/);
|
||||
t.tool.destroy();
|
||||
});
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
releasePointer,
|
||||
} from '../data/inputOwnership.js';
|
||||
import { validateBox } from '../layers/recentImagery/model.js';
|
||||
import { msg } from '../i18n/index.js';
|
||||
|
||||
/** The id this tool claims the pointer under. */
|
||||
export const IMAGERY_BOX_POINTER_OWNER = 'recent-imagery-box';
|
||||
@@ -150,7 +151,7 @@ export function initImageryBoxTool({
|
||||
if (!active || destroyed || anchor) return;
|
||||
const point = worldAt(event.position);
|
||||
if (!point) {
|
||||
onCancel?.('sky', 'Press on the ground, not the sky');
|
||||
onCancel?.('sky', msg('Press on the ground, not the sky'));
|
||||
return;
|
||||
}
|
||||
anchor = point;
|
||||
@@ -169,7 +170,8 @@ export function initImageryBoxTool({
|
||||
corner = worldAt(event.position) || corner;
|
||||
const box = dragBox();
|
||||
const result = validateBox(box);
|
||||
if (result.reason === 'degenerate') result.message = 'Drag to size the box';
|
||||
if (result.reason === 'degenerate')
|
||||
result.message = msg('Drag to size the box');
|
||||
endDrag();
|
||||
setActive(false);
|
||||
if (result.ok) onBox(result.box);
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* Key guidance in the UI language. keySetupCore.mjs builds the same sentences
|
||||
* in English for the server and the AI tools; these are the ones people read.
|
||||
*/
|
||||
import {
|
||||
KEY_SETUP_KEYS,
|
||||
keySetupRequirementEnvVars,
|
||||
} from '../keySetupCore.mjs';
|
||||
import { t, translateKnown } from '../i18n/index.js';
|
||||
|
||||
/** "Needs X — add it in Provider Settings", or '' for an unknown or hidden key. */
|
||||
export function keyRequirementText(id) {
|
||||
const envVars = id ? keySetupRequirementEnvVars(id) : null;
|
||||
return envVars
|
||||
? t('Needs {envVars} — add it in Provider Settings', { envVars })
|
||||
: '';
|
||||
}
|
||||
|
||||
/** The key's product name in title case: GOOGLE MAPS → Google Maps. */
|
||||
function keyName(id) {
|
||||
const entry = KEY_SETUP_KEYS.find((candidate) => candidate.id === id);
|
||||
return entry
|
||||
? entry.title
|
||||
.toLowerCase()
|
||||
.replace(/\b\w/g, (letter) => letter.toUpperCase())
|
||||
: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The requirement, then the switched-off sources that would draw with a key
|
||||
* already set (see keySetupWithAlternatives).
|
||||
*
|
||||
* @param {string} requirement
|
||||
* @param {Array<{label: string, requiresKeyId: string|null}>} [alternatives]
|
||||
*/
|
||||
export function keyGuidanceText(requirement, alternatives = []) {
|
||||
const options = alternatives.map(({ label, requiresKeyId }) => {
|
||||
const name = keyName(requiresKeyId);
|
||||
const source = translateKnown(label);
|
||||
return name
|
||||
? t('light {source} to use your {name} key', { source, name })
|
||||
: t('light {source}', { source });
|
||||
});
|
||||
if (!options.length) return requirement;
|
||||
const offer = options.join(t(', or '));
|
||||
if (requirement)
|
||||
return t('{requirement}, or {offer}', { requirement, offer });
|
||||
return offer.charAt(0).toLocaleUpperCase() + offer.slice(1);
|
||||
}
|
||||
@@ -55,6 +55,9 @@ export class LayerBindings {
|
||||
get _radioControls() {
|
||||
return this.readControls()._radioControls;
|
||||
}
|
||||
get _streetLevelControls() {
|
||||
return this.readControls()._streetLevelControls;
|
||||
}
|
||||
observeCamera() {
|
||||
this._cctvRequestFocusHandler = (event) =>
|
||||
routeCctvFocusRequest(
|
||||
@@ -130,9 +133,10 @@ export class LayerBindings {
|
||||
]) {
|
||||
const layer = this._dataManager?.layers?.get(id)?.module;
|
||||
if (typeof layer?.attachShellServices !== 'function') continue;
|
||||
const noun = id === 'weather-cyclones' ? 'cyclone' : 'weather';
|
||||
layer.attachShellServices({
|
||||
runNavigation: (navigate) =>
|
||||
this.runImmediateNavigation('weather', navigate),
|
||||
this.runImmediateNavigation(noun, navigate),
|
||||
imageryHost: this.services.imageryHost,
|
||||
});
|
||||
this._weatherShellModules.push(layer);
|
||||
@@ -234,6 +238,8 @@ export class LayerBindings {
|
||||
this._syncContextModeButtons();
|
||||
this._cctvControls.connect();
|
||||
this._radioControls.connect();
|
||||
// Its switch-on requests come from the manager, which arrives after it.
|
||||
this._streetLevelControls?.connect();
|
||||
this._connectDirectionsCamera();
|
||||
this._connectWeatherCamera();
|
||||
if (!this._awarenessSelectedHandler) {
|
||||
|
||||
@@ -141,3 +141,19 @@ test('the manager publishes the declared key id on the row', async () => {
|
||||
);
|
||||
assert.equal(layerKeyRequirementTooltip(ungated), '');
|
||||
});
|
||||
|
||||
test('a key-gated layer with another source ready says how to use it', () => {
|
||||
const text = layerKeyRequirementTooltip({
|
||||
requiresKeyId: 'mapillary',
|
||||
stats: {
|
||||
keyRequired: true,
|
||||
keyAlternatives: [
|
||||
{ id: 'google', label: 'STREET VIEW', requiresKeyId: 'google-maps' },
|
||||
],
|
||||
},
|
||||
});
|
||||
assert.equal(
|
||||
text,
|
||||
'Needs MAPILLARY_CLIENT_TOKEN — add it in Provider Settings, or light STREET VIEW to use your Google Maps key',
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,140 @@
|
||||
/**
|
||||
* Layer and source names as the page shows them.
|
||||
*
|
||||
* Layer ids, English module names (`layer.name`) and declared source names
|
||||
* stay English in layer state, share links and AI tool output; these helpers
|
||||
* translate them only at a presentation boundary. The layer panel, the HUD
|
||||
* and the voice card name a layer the same way through them.
|
||||
*
|
||||
* Pure: imports only i18n, no DOM.
|
||||
* @module ui/layerNames
|
||||
*/
|
||||
import { msg, t, translateKnown } from '../i18n/index.js';
|
||||
|
||||
/** English module names (`layer.name`) by layer id. */
|
||||
export const LAYER_NAME_KEYS = Object.freeze({
|
||||
flights: msg('Live Flights'),
|
||||
military: msg('Military Flights'),
|
||||
earthquakes: msg('Earthquakes (24h)'),
|
||||
satellites: msg('Satellites'),
|
||||
'rocket-launches': msg('Space Missions (30d)'),
|
||||
traffic: msg('Street Traffic'),
|
||||
cctv: msg('CCTV'),
|
||||
radio: msg('Radio'),
|
||||
bikeshare: msg('Bikeshare'),
|
||||
'ais-live-vessels': msg('Live AIS Vessels'),
|
||||
'military-installations': msg('Mapped Installations'),
|
||||
'military-awareness': msg('Global Context'),
|
||||
'local-datacenters': msg('Datacenters'),
|
||||
'local-dams': msg('Dams'),
|
||||
'telegeography-submarine-cables': msg('Submarine Cables'),
|
||||
'local-firms': msg('FIRMS Active Fires'),
|
||||
'local-adsb': msg('Local ADS-B'),
|
||||
transit: msg('Transit'),
|
||||
'recent-imagery': msg('Recent Imagery'),
|
||||
'fire-perimeters': msg('Fire Perimeters'),
|
||||
'gnss-integrity': msg('GNSS Integrity'),
|
||||
'drone-airspace': msg('Prohibited & Restricted Airspace'),
|
||||
's2-ghostmaps': msg('S2 GhostMaps'),
|
||||
wind: msg('Wind'),
|
||||
'weather-radar': msg('Rain radar'),
|
||||
'weather-satellite': msg('Satellite clouds'),
|
||||
'weather-lightning': msg('Lightning density'),
|
||||
'weather-cyclones': msg('Cyclone advisories'),
|
||||
'air-quality': msg('Air quality'),
|
||||
directions: msg('Directions'),
|
||||
'alpr-cameras': msg('ALPR Cameras'),
|
||||
});
|
||||
|
||||
/** The layer panel's own English names, where they differ from the module's. */
|
||||
export const PANEL_LABEL_KEYS = Object.freeze({
|
||||
'ais-live-vessels': msg('Live Vessels'),
|
||||
bikeshare: msg('Bike Share'),
|
||||
cctv: msg('Cameras'),
|
||||
'street-level': msg('Street Level'),
|
||||
'alpr-cameras': msg('Mapped ALPR Cameras'),
|
||||
'local-datacenters': msg('Data Centers'),
|
||||
'local-firms': msg('Active Fires'),
|
||||
});
|
||||
|
||||
// Looked up by the English text, so a surface that holds `layer.name` keeps
|
||||
// its English data and only the shown text translates.
|
||||
const MODULE_NAME_KEYS = new Map(
|
||||
[...Object.values(LAYER_NAME_KEYS), ...Object.values(PANEL_LABEL_KEYS)].map(
|
||||
(key) => [key, key],
|
||||
),
|
||||
);
|
||||
|
||||
/**
|
||||
* Translate a layer's English module name for display; any other text
|
||||
* (a provider name, an unknown layer) is returned unchanged.
|
||||
* @param {string} name English `layer.name`.
|
||||
* @returns {string}
|
||||
*/
|
||||
export function localizeLayerName(name) {
|
||||
const key = MODULE_NAME_KEYS.get(String(name ?? '').trim());
|
||||
return key ? t(key) : name;
|
||||
}
|
||||
|
||||
/**
|
||||
* A layer id's module name in the active language, or null for an id this
|
||||
* module does not know.
|
||||
* @param {string} id Layer id, e.g. `earthquakes`.
|
||||
* @returns {string|null}
|
||||
*/
|
||||
export function layerNameForId(id) {
|
||||
const key = Object.hasOwn(LAYER_NAME_KEYS, id)
|
||||
? LAYER_NAME_KEYS[id]
|
||||
: Object.hasOwn(PANEL_LABEL_KEYS, id)
|
||||
? PANEL_LABEL_KEYS[id]
|
||||
: null;
|
||||
return key ? t(key) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A layer as shown: its English module name or its id, whichever is known,
|
||||
* in the active language; otherwise the text as given.
|
||||
* @param {string} [name] English `layer.name`, or an id when the layer had none.
|
||||
* @param {string} [id] Layer id.
|
||||
* @returns {string}
|
||||
*/
|
||||
export function shownLayerName(name, id) {
|
||||
const text = String(name ?? '').trim();
|
||||
if (text && MODULE_NAME_KEYS.has(text)) return t(MODULE_NAME_KEYS.get(text));
|
||||
return layerNameForId(id || text) || text || String(id ?? '');
|
||||
}
|
||||
|
||||
// Layer-declared source names. Provider names (USGS, CelesTrak, GTFS-RT…)
|
||||
// are not listed and pass through unchanged unless the catalog knows them.
|
||||
const SOURCE_LABEL_KEYS = new Map(
|
||||
[
|
||||
msg('Flights'),
|
||||
msg('Military aircraft'),
|
||||
msg('Vessels'),
|
||||
msg('CCTV + Street View fallback'),
|
||||
msg('OpenStreetMap + optional Google Maps Places'),
|
||||
msg('GFS / ECMWF IFS · FORECAST'),
|
||||
msg('NOAA nowCOAST · OBSERVED'),
|
||||
msg('NASA FIRMS · LIVE'),
|
||||
msg('OSM routing'),
|
||||
msg('Mapped camera locations'),
|
||||
msg('OpenStreetMap · community mapped'),
|
||||
].map((key) => [key, key]),
|
||||
);
|
||||
|
||||
/**
|
||||
* A layer's declared source name as shown.
|
||||
* @param {string} source English source name, e.g. `Flights` or `OpenSky`.
|
||||
* @returns {string}
|
||||
*/
|
||||
export function sourceLabel(source) {
|
||||
if (typeof source !== 'string') return source;
|
||||
if (source === 'Local') return t('Local', { context: 'data source' });
|
||||
const key = SOURCE_LABEL_KEYS.get(source);
|
||||
if (key) return t(key);
|
||||
// A layer with several providers joins their names ("Mapillary · Google
|
||||
// Street View"); a name with a translation shows it.
|
||||
return source.includes(' · ')
|
||||
? source.split(' · ').map(translateKnown).join(' · ')
|
||||
: translateKnown(source);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { APPLICATION_LAYER_METADATA } from '../app/constructCatalog.js';
|
||||
import { setLocale, t } from '../i18n/index.js';
|
||||
import { FEED_SOURCE, COMBINED_SOURCE } from '../layers/localAdsb/status.js';
|
||||
import {
|
||||
LAYER_NAME_KEYS,
|
||||
PANEL_LABEL_KEYS,
|
||||
sourceLabel,
|
||||
} from './layerNames.js';
|
||||
|
||||
// Layers whose module name is a proper name and stays as it is in every
|
||||
// language: the Bhote Koshi pair belong to a scripted scene.
|
||||
const UNTRANSLATED_NAMES = new Set(['bhote-koshi-2026', 'bhote-koshi-locator']);
|
||||
|
||||
const catalogIds = APPLICATION_LAYER_METADATA.map((layer) => layer.id);
|
||||
|
||||
test('every catalog layer has a translatable name', () => {
|
||||
const missing = catalogIds.filter(
|
||||
(id) =>
|
||||
!UNTRANSLATED_NAMES.has(id) &&
|
||||
!Object.hasOwn(LAYER_NAME_KEYS, id) &&
|
||||
!Object.hasOwn(PANEL_LABEL_KEYS, id),
|
||||
);
|
||||
assert.deepEqual(
|
||||
missing,
|
||||
[],
|
||||
'add the layer to LAYER_NAME_KEYS in src/ui/layerNames.js',
|
||||
);
|
||||
});
|
||||
|
||||
test('the name tables list only catalog layers', () => {
|
||||
const unknown = [
|
||||
...Object.keys(LAYER_NAME_KEYS),
|
||||
...Object.keys(PANEL_LABEL_KEYS),
|
||||
...UNTRANSLATED_NAMES,
|
||||
].filter((id) => !catalogIds.includes(id));
|
||||
assert.deepEqual(unknown, []);
|
||||
});
|
||||
|
||||
for (const locale of ['es', 'ru']) {
|
||||
test(`${locale}: Local ADS-B source names translate without their own entry`, () => {
|
||||
setLocale(locale);
|
||||
try {
|
||||
for (const source of [FEED_SOURCE, COMBINED_SOURCE]) {
|
||||
assert.notEqual(t(source), source, 'the catalog has the entry');
|
||||
assert.equal(sourceLabel(source), t(source));
|
||||
}
|
||||
} finally {
|
||||
setLocale('en');
|
||||
}
|
||||
});
|
||||
}
|
||||
+242
-75
@@ -3,22 +3,43 @@ import { syncRowList } from './rowList.js';
|
||||
import { layerFeedState } from '../data/feedState.js';
|
||||
export { layerFeedState } from '../data/feedState.js';
|
||||
import { GUIDANCE_STATUSES } from '../loadingFeedback.js';
|
||||
import { keySetupRequirement } from '../keySetupCore.mjs';
|
||||
import { keyGuidanceText, keyRequirementText } from './keyGuidance.js';
|
||||
import {
|
||||
LAYER_NAME_KEYS,
|
||||
PANEL_LABEL_KEYS as PANEL_LABELS,
|
||||
sourceLabel,
|
||||
} from './layerNames.js';
|
||||
export { localizeLayerName } from './layerNames.js';
|
||||
import { createWeatherPanel } from './weatherPanel.js';
|
||||
const FEED_STATE_LABELS = Object.freeze({
|
||||
nominal: 'ON',
|
||||
loading: 'LOADING',
|
||||
degraded: 'DEGRADED',
|
||||
stale: 'STALE',
|
||||
partial: 'PARTIAL',
|
||||
fallback: 'FALLBACK',
|
||||
unavailable: 'UNAVAILABLE',
|
||||
import { translateFeedError, translateStatusLine } from './statusText.js';
|
||||
import {
|
||||
formatNumber,
|
||||
getLocale,
|
||||
msg,
|
||||
t,
|
||||
translateKnown,
|
||||
} from '../i18n/index.js';
|
||||
|
||||
// Feed-state values are machine ids (QA hooks, CSS feed-* classes); only the
|
||||
// label translates.
|
||||
const FEED_STATE_LABEL_KEYS = Object.freeze({
|
||||
nominal: msg('ON'),
|
||||
loading: msg('LOADING'),
|
||||
degraded: msg('DEGRADED'),
|
||||
stale: msg('STALE'),
|
||||
partial: msg('PARTIAL'),
|
||||
fallback: msg('FALLBACK'),
|
||||
unavailable: msg('UNAVAILABLE'),
|
||||
});
|
||||
|
||||
function lifecycleStateLabel(lifecycleState) {
|
||||
return t(lifecycleState === 'enabling' ? msg('ENABLING') : msg('DISABLING'));
|
||||
}
|
||||
|
||||
// Presentation order is independent of catalog registration and startup order.
|
||||
const PANEL_GROUPS = [
|
||||
{
|
||||
label: 'Movement',
|
||||
label: msg('Movement'),
|
||||
ids: [
|
||||
'satellites',
|
||||
'flights',
|
||||
@@ -31,11 +52,11 @@ const PANEL_GROUPS = [
|
||||
],
|
||||
},
|
||||
{
|
||||
label: 'Cameras',
|
||||
label: msg('Cameras'),
|
||||
ids: ['cctv', 'recent-imagery', 'street-level'],
|
||||
},
|
||||
{
|
||||
label: 'Infrastructure',
|
||||
label: msg('Infrastructure'),
|
||||
ids: [
|
||||
'alpr-cameras',
|
||||
'military-installations',
|
||||
@@ -46,12 +67,20 @@ const PANEL_GROUPS = [
|
||||
],
|
||||
},
|
||||
{
|
||||
label: 'Events',
|
||||
ids: ['rocket-launches', 'earthquakes', 'local-firms', 'fire-perimeters'],
|
||||
label: msg('Events'),
|
||||
ids: [
|
||||
'rocket-launches',
|
||||
'earthquakes',
|
||||
'local-firms',
|
||||
'fire-perimeters',
|
||||
'gnss-integrity',
|
||||
's2-ghostmaps',
|
||||
],
|
||||
},
|
||||
{
|
||||
label: 'Weather',
|
||||
label: msg('Weather'),
|
||||
ids: [
|
||||
'air-quality',
|
||||
'wind',
|
||||
'weather-radar',
|
||||
'weather-satellite',
|
||||
@@ -60,7 +89,7 @@ const PANEL_GROUPS = [
|
||||
],
|
||||
},
|
||||
{
|
||||
label: 'Utilities',
|
||||
label: msg('Utilities'),
|
||||
ids: ['directions', 'radio'],
|
||||
},
|
||||
];
|
||||
@@ -70,18 +99,16 @@ const PANEL_ORDER = PANEL_GROUPS.flatMap(({ label, ids }) =>
|
||||
const PANEL_POSITIONS = new Map(
|
||||
PANEL_ORDER.map(({ id }, index) => [id, index]),
|
||||
);
|
||||
const PANEL_LABELS = {
|
||||
'ais-live-vessels': 'Live Vessels',
|
||||
bikeshare: 'Bike Share',
|
||||
cctv: 'Cameras',
|
||||
'street-level': 'Street Level',
|
||||
'alpr-cameras': 'Mapped ALPR Cameras',
|
||||
'local-datacenters': 'Data Centers',
|
||||
'local-firms': 'Active Fires',
|
||||
};
|
||||
|
||||
function englishPanelLabel(layer) {
|
||||
return PANEL_LABELS[layer.id] || LAYER_NAME_KEYS[layer.id] || layer.name;
|
||||
}
|
||||
|
||||
// PANEL_LABELS win over layer-name keys; otherwise the module's own name.
|
||||
function panelLabel(layer) {
|
||||
return PANEL_LABELS[layer.id] || layer.name;
|
||||
if (PANEL_LABELS[layer.id]) return t(PANEL_LABELS[layer.id]);
|
||||
const key = LAYER_NAME_KEYS[layer.id];
|
||||
return key ? t(key) : layer.name;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -101,7 +128,70 @@ function panelLabel(layer) {
|
||||
export function layerKeyRequirementTooltip(layer = {}) {
|
||||
if (layer?.stats?.keyRequired !== true) return '';
|
||||
const requiresKeyId = String(layer.requiresKeyId || '').trim();
|
||||
return requiresKeyId ? keySetupRequirement(requiresKeyId) : '';
|
||||
// A layer with several sources also names the ones it could use instead.
|
||||
return keyGuidanceText(
|
||||
requiresKeyId ? keyRequirementText(requiresKeyId) : '',
|
||||
layer.stats.keyAlternatives || [],
|
||||
);
|
||||
}
|
||||
|
||||
const ROW_TEXT_SEPARATOR = ' · ';
|
||||
|
||||
// A short Latin code joined by hyphens. Longer runs (a URL, a token in an
|
||||
// error) keep their break opportunities so they cannot overflow the rail.
|
||||
const HYPHENATED_CODE = /[A-Za-z0-9]+(?:-[A-Za-z0-9]+)+/g;
|
||||
const HYPHENATED_CODE_MAX = 16;
|
||||
|
||||
/** A span for one run of row text; `keep` stops the browser breaking inside it. */
|
||||
function rowTextSpan(text, keep) {
|
||||
const span = document.createElement('span');
|
||||
if (keep) span.className = 'data-keep';
|
||||
span.textContent = text;
|
||||
return span;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a row's name, count or meta line so that a narrow column wraps it well
|
||||
* in every language: a Latin code with hyphens (ADS-B, RTL-SDR, GTFS-RT) never
|
||||
* splits at its hyphen, and a " · " separator stays at the end of the line it
|
||||
* closes, so no line starts with "·". The element's textContent is still the
|
||||
* plain string; text with neither feature is set directly.
|
||||
*
|
||||
* @param {HTMLElement} element
|
||||
* @param {string} text
|
||||
*/
|
||||
export function setRowText(element, text) {
|
||||
const value = String(text ?? '');
|
||||
// Refreshes run every second; leave unchanged text (and its spans) alone.
|
||||
if (element.textContent === value) return;
|
||||
const codes = [...value.matchAll(HYPHENATED_CODE)].filter(
|
||||
(match) => match[0].length <= HYPHENATED_CODE_MAX,
|
||||
);
|
||||
if (!codes.length && !value.includes(ROW_TEXT_SEPARATOR)) {
|
||||
element.textContent = value;
|
||||
return;
|
||||
}
|
||||
const spans = [];
|
||||
const pushPlain = (from, to) => {
|
||||
if (to <= from) return;
|
||||
const pieces = value.slice(from, to).split(ROW_TEXT_SEPARATOR);
|
||||
pieces.forEach((piece, index) => {
|
||||
// The space before the dot belongs to a no-wrap span, so the only break
|
||||
// opportunity around a separator is the space after it.
|
||||
if (index > 0) spans.push(rowTextSpan(' ·', true));
|
||||
const textPiece = index > 0 ? ` ${piece}` : piece;
|
||||
if (textPiece) spans.push(rowTextSpan(textPiece, false));
|
||||
});
|
||||
};
|
||||
let cursor = 0;
|
||||
for (const match of codes) {
|
||||
pushPlain(cursor, match.index);
|
||||
spans.push(rowTextSpan(match[0], true));
|
||||
cursor = match.index + match[0].length;
|
||||
}
|
||||
pushPlain(cursor, value.length);
|
||||
element.textContent = '';
|
||||
for (const span of spans) element.appendChild(span);
|
||||
}
|
||||
|
||||
/** Layer row presentation over supplied state and actions; no layer imports. */
|
||||
@@ -205,17 +295,20 @@ export class LayerPanel {
|
||||
for (const layer of layers) {
|
||||
if (!layer.showInTogglePanel) continue;
|
||||
const group =
|
||||
PANEL_ORDER[PANEL_POSITIONS.get(layer.id)]?.label ?? 'Other layers';
|
||||
PANEL_ORDER[PANEL_POSITIONS.get(layer.id)]?.label ??
|
||||
msg('Other layers');
|
||||
if (group && group !== previousGroup) {
|
||||
const heading = document.createElement('h3');
|
||||
heading.className = 'data-layer-group-heading';
|
||||
heading.textContent = group;
|
||||
heading.textContent = t(group);
|
||||
this._toggleContainer.appendChild(heading);
|
||||
}
|
||||
previousGroup = group;
|
||||
const row = document.createElement('div');
|
||||
row.className = 'data-toggle-row';
|
||||
row.dataset.layerId = layer.id;
|
||||
// English name for voice tools, which must not receive translated text.
|
||||
row.dataset.layerName = englishPanelLabel(layer);
|
||||
|
||||
const topRow = document.createElement('div');
|
||||
topRow.className = 'data-toggle-top';
|
||||
@@ -228,7 +321,7 @@ export class LayerPanel {
|
||||
icon.textContent = layer.icon;
|
||||
const name = document.createElement('span');
|
||||
name.className = 'data-name';
|
||||
name.textContent = panelLabel(layer);
|
||||
setRowText(name, panelLabel(layer));
|
||||
left.appendChild(icon);
|
||||
left.appendChild(name);
|
||||
|
||||
@@ -237,7 +330,7 @@ export class LayerPanel {
|
||||
|
||||
const count = document.createElement('span');
|
||||
count.className = 'data-count';
|
||||
count.textContent = this._layerCountText(layer.stats);
|
||||
this._syncCount(row, count, layer.stats);
|
||||
|
||||
const toggle = document.createElement('button');
|
||||
toggle.type = 'button';
|
||||
@@ -276,7 +369,7 @@ export class LayerPanel {
|
||||
|
||||
const bottomRow = document.createElement('div');
|
||||
bottomRow.className = 'data-toggle-meta';
|
||||
bottomRow.textContent = this._buildMetaText(layer);
|
||||
setRowText(bottomRow, this._buildMetaText(layer));
|
||||
|
||||
row.appendChild(topRow);
|
||||
row.appendChild(bottomRow);
|
||||
@@ -369,6 +462,7 @@ export class LayerPanel {
|
||||
'weather-satellite',
|
||||
'weather-lightning',
|
||||
'weather-cyclones',
|
||||
'air-quality',
|
||||
].includes(layer.id),
|
||||
)
|
||||
.map((layer) => ({
|
||||
@@ -379,6 +473,23 @@ export class LayerPanel {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Write a row's count. Outside English a count phrase ("24 nearby · 2 on
|
||||
* screen") gets its own line, or it squeezes a longer translated name to a
|
||||
* word per line. "—" is marked so a wide status chip can replace it
|
||||
* (radio.css).
|
||||
*/
|
||||
_syncCount(row, count, stats) {
|
||||
const text = this._layerCountText(stats);
|
||||
setRowText(count, text);
|
||||
const phrase =
|
||||
getLocale() !== 'en' &&
|
||||
typeof stats.countLabel === 'string' &&
|
||||
/\d/.test(stats.countLabel);
|
||||
row.classList.toggle('data-toggle-row--count-line', phrase);
|
||||
count.classList.toggle('data-count-empty', text === '—');
|
||||
}
|
||||
|
||||
/** Qualify a loaded count when it does not mean items currently on screen. */
|
||||
_layerCountText(stats) {
|
||||
if (typeof stats.countLabel === 'string' && stats.countLabel.trim())
|
||||
@@ -502,12 +613,12 @@ export class LayerPanel {
|
||||
|
||||
const count = row.querySelector('.data-count');
|
||||
if (count) {
|
||||
count.textContent = this._layerCountText(layer.stats);
|
||||
this._syncCount(row, count, layer.stats);
|
||||
}
|
||||
|
||||
const meta = row.querySelector('.data-toggle-meta');
|
||||
if (meta) {
|
||||
meta.textContent = this._buildMetaText(layer);
|
||||
setRowText(meta, this._buildMetaText(layer));
|
||||
}
|
||||
|
||||
this._syncRowControls(
|
||||
@@ -522,23 +633,39 @@ export class LayerPanel {
|
||||
_buildMetaText(layer) {
|
||||
const stats = layer.stats || {};
|
||||
const feedState = layerFeedState(stats);
|
||||
const stateLabel = FEED_STATE_LABELS[feedState];
|
||||
const source = stats.source || layer.source;
|
||||
const stateLabel = t(FEED_STATE_LABEL_KEYS[feedState]);
|
||||
const source = sourceLabel(stats.source || layer.source);
|
||||
const lifecycleState =
|
||||
layer.lifecycleState || (layer.enabled ? 'enabled' : 'disabled');
|
||||
if (lifecycleState === 'enabling' || lifecycleState === 'disabling') {
|
||||
return `${lifecycleState.toUpperCase()} · ${source}`;
|
||||
return t('{state} · {source}', {
|
||||
state: lifecycleStateLabel(lifecycleState),
|
||||
source,
|
||||
});
|
||||
}
|
||||
if (layer.lifecycleUncertain) {
|
||||
return `UNCERTAIN · ${source} · lifecycle state requires reconciliation`;
|
||||
return t(
|
||||
'UNCERTAIN · {source} · lifecycle state requires reconciliation',
|
||||
{ source },
|
||||
);
|
||||
}
|
||||
const presentedError =
|
||||
stats.error || stats.lastError || stats.managerRefreshError;
|
||||
const presentedError = translateFeedError(
|
||||
stats.error || stats.lastError || stats.managerRefreshError,
|
||||
);
|
||||
if (presentedError) {
|
||||
if (typeof stats.retryInSec === 'number' && stats.retryInSec > 0) {
|
||||
return `${stateLabel} · ${source} · ${presentedError} · retry ${stats.retryInSec}s`;
|
||||
return t('{state} · {source} · {detail} · retry {seconds}s', {
|
||||
state: stateLabel,
|
||||
source,
|
||||
detail: presentedError,
|
||||
seconds: stats.retryInSec,
|
||||
});
|
||||
}
|
||||
return `${stateLabel} · ${source} · ${presentedError}`;
|
||||
return t('{state} · {source} · {detail}', {
|
||||
state: stateLabel,
|
||||
source,
|
||||
detail: presentedError,
|
||||
});
|
||||
}
|
||||
// A guidance status carries its prompt in `statusMessage`, not `error`, so
|
||||
// the row still tells the operator what to do without reporting a fault.
|
||||
@@ -547,22 +674,26 @@ export class LayerPanel {
|
||||
typeof stats.statusMessage === 'string' &&
|
||||
stats.statusMessage.trim()
|
||||
) {
|
||||
return `${source} · ${stats.statusMessage.trim()}`;
|
||||
return `${source} · ${translateKnown(stats.statusMessage.trim())}`;
|
||||
}
|
||||
const ago = stats.lastUpdate ? this._timeAgo(stats.lastUpdate) : 'never';
|
||||
const ago = stats.lastUpdate ? this._timeAgo(stats.lastUpdate) : t('never');
|
||||
if (stats.loading) {
|
||||
const loadingLabel =
|
||||
typeof stats.loadingLabel === 'string' && stats.loadingLabel.trim()
|
||||
? stats.loadingLabel.trim()
|
||||
: 'loading...';
|
||||
return `${source} · ${loadingLabel}`;
|
||||
? translateStatusLine(stats.loadingLabel.trim())
|
||||
: t('loading...');
|
||||
return t('{source} · {loadingLabel}', { source, loadingLabel });
|
||||
}
|
||||
if (feedState === 'fallback') {
|
||||
const detail =
|
||||
typeof stats.loadingLabel === 'string' && stats.loadingLabel.trim()
|
||||
? stats.loadingLabel.trim()
|
||||
? translateStatusLine(stats.loadingLabel.trim())
|
||||
: stats.coverage || ago;
|
||||
return `${stateLabel} · ${source} · ${detail}`;
|
||||
return t('{state} · {source} · {detail}', {
|
||||
state: stateLabel,
|
||||
source,
|
||||
detail,
|
||||
});
|
||||
}
|
||||
if (feedState === 'partial') {
|
||||
const { acceptedRowCount, rawRowCount } = stats;
|
||||
@@ -571,21 +702,40 @@ export class LayerPanel {
|
||||
Number.isInteger(rawRowCount) &&
|
||||
acceptedRowCount >= 0 &&
|
||||
rawRowCount > acceptedRowCount
|
||||
? `${acceptedRowCount} of ${rawRowCount} records accepted`
|
||||
: 'incomplete snapshot';
|
||||
return `${stateLabel} · ${source} · ${detail} · ${ago}`;
|
||||
? t('{accepted} of {raw} records accepted', {
|
||||
accepted: acceptedRowCount,
|
||||
raw: rawRowCount,
|
||||
})
|
||||
: t('incomplete snapshot');
|
||||
return t('{state} · {source} · {detail} · {ago}', {
|
||||
state: stateLabel,
|
||||
source,
|
||||
detail,
|
||||
ago,
|
||||
});
|
||||
}
|
||||
if (feedState === 'stale') {
|
||||
const retry =
|
||||
typeof stats.retryInSec === 'number' && stats.retryInSec > 0
|
||||
? ` · retrying in ${stats.retryInSec}s`
|
||||
: '';
|
||||
return `${stateLabel} · ${source} · ${ago}${retry}`;
|
||||
if (typeof stats.retryInSec === 'number' && stats.retryInSec > 0) {
|
||||
return t('{state} · {source} · {ago} · retrying in {seconds}s', {
|
||||
state: stateLabel,
|
||||
source,
|
||||
ago,
|
||||
seconds: stats.retryInSec,
|
||||
});
|
||||
}
|
||||
return t('{state} · {source} · {ago}', {
|
||||
state: stateLabel,
|
||||
source,
|
||||
ago,
|
||||
});
|
||||
}
|
||||
if (typeof stats.loadingLabel === 'string' && stats.loadingLabel.trim()) {
|
||||
return `${source} · ${stats.loadingLabel.trim()}`;
|
||||
return t('{source} · {loadingLabel}', {
|
||||
source,
|
||||
loadingLabel: translateStatusLine(stats.loadingLabel.trim()),
|
||||
});
|
||||
}
|
||||
return `${source} · ${ago}`;
|
||||
return t('{source} · {ago}', { source, ago });
|
||||
}
|
||||
|
||||
_syncToggleButton(button, layer) {
|
||||
@@ -604,7 +754,7 @@ export class LayerPanel {
|
||||
button.classList.toggle('enabling', layer.lifecycleState === 'enabling');
|
||||
button.classList.toggle('disabling', layer.lifecycleState === 'disabling');
|
||||
button.classList.toggle('lifecycle-uncertain', uncertain);
|
||||
for (const state of Object.keys(FEED_STATE_LABELS)) {
|
||||
for (const state of Object.keys(FEED_STATE_LABEL_KEYS)) {
|
||||
button.classList.toggle(
|
||||
`feed-${state}`,
|
||||
(layer.enabled || unavailable) && !uncertain && feedState === state,
|
||||
@@ -624,38 +774,55 @@ export class LayerPanel {
|
||||
String(transitioning || (unavailable && !layer.enabled)),
|
||||
);
|
||||
button.setAttribute('aria-busy', String(transitioning));
|
||||
button.textContent = transitioning
|
||||
? layer.lifecycleState.toUpperCase()
|
||||
const showsFeedState =
|
||||
!transitioning && !uncertain && (layer.enabled || unavailable);
|
||||
const stateText = transitioning
|
||||
? lifecycleStateLabel(layer.lifecycleState)
|
||||
: uncertain
|
||||
? 'UNCERTAIN'
|
||||
: layer.enabled || unavailable
|
||||
? FEED_STATE_LABELS[feedState]
|
||||
: 'OFF';
|
||||
? t('UNCERTAIN')
|
||||
: showsFeedState
|
||||
? t(FEED_STATE_LABEL_KEYS[feedState])
|
||||
: t('OFF');
|
||||
// The chip may abbreviate where a language's word is wider than the
|
||||
// status column; the meta line and the accessible name keep the full word.
|
||||
button.textContent =
|
||||
showsFeedState && feedState === 'unavailable'
|
||||
? t('UNAVAILABLE', { context: 'status chip' })
|
||||
: stateText;
|
||||
const keyGuidance = unavailable
|
||||
? String(layer.stats.error || 'Data source unavailable')
|
||||
? String(
|
||||
translateFeedError(layer.stats.error) || t('Data source unavailable'),
|
||||
)
|
||||
: layerKeyRequirementTooltip(layer);
|
||||
// Name the missing key on the control itself: a row reading KEY REQUIRED
|
||||
// without saying WHICH key leaves a dead control and no next step. Empty
|
||||
// when the layer needs no key, or already has one.
|
||||
button.title = keyGuidance;
|
||||
const ariaLabel = t('{name}: {state}', {
|
||||
name: panelLabel(layer),
|
||||
state: stateText,
|
||||
});
|
||||
button.setAttribute(
|
||||
'aria-label',
|
||||
keyGuidance
|
||||
? `${panelLabel(layer)}: ${button.textContent}. ${keyGuidance}`
|
||||
: `${panelLabel(layer)}: ${button.textContent}`,
|
||||
keyGuidance ? `${ariaLabel}. ${keyGuidance}` : ariaLabel,
|
||||
);
|
||||
}
|
||||
|
||||
_formatCount(n) {
|
||||
if (n >= 1000) return `${(n / 1000).toFixed(1)}K`;
|
||||
if (n >= 1000)
|
||||
return `${formatNumber(n / 1000, {
|
||||
minimumFractionDigits: 1,
|
||||
maximumFractionDigits: 1,
|
||||
useGrouping: false,
|
||||
})}K`;
|
||||
return String(n);
|
||||
}
|
||||
|
||||
_timeAgo(timestamp) {
|
||||
const diff = Math.floor((Date.now() - timestamp) / 1000);
|
||||
if (diff < 5) return 'just now';
|
||||
if (diff < 60) return `${diff}s ago`;
|
||||
if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
|
||||
return `${Math.floor(diff / 3600)}h ago`;
|
||||
if (diff < 5) return t('just now');
|
||||
if (diff < 60) return t('{count}s ago', { count: diff });
|
||||
if (diff < 3600) return t('{count}m ago', { count: Math.floor(diff / 60) });
|
||||
return t('{count}h ago', { count: Math.floor(diff / 3600) });
|
||||
}
|
||||
}
|
||||
+100
-1
@@ -13,7 +13,9 @@ test('panel presentation places Transit between Street Traffic and Bike Share in
|
||||
source.indexOf('const PANEL_POSITIONS ='),
|
||||
);
|
||||
const order = JSON.parse(
|
||||
runInNewContext(`${declarations}\nJSON.stringify(PANEL_ORDER)`),
|
||||
runInNewContext(
|
||||
`const msg = (text) => text;\n${declarations}\nJSON.stringify(PANEL_ORDER)`,
|
||||
),
|
||||
);
|
||||
assert.deepEqual(
|
||||
order.filter(({ label }) => label === 'Movement').map(({ id }) => id),
|
||||
@@ -258,3 +260,100 @@ test('an omitted source is visibly unavailable and cannot be toggled on', async
|
||||
'an active layer can always be switched off',
|
||||
);
|
||||
});
|
||||
|
||||
test('row text keeps a hyphenated code whole and never starts a line with the separator', async () => {
|
||||
const { setRowText } = await import('./layerPanel.js');
|
||||
const previousDocument = globalThis.document;
|
||||
const element = () => ({
|
||||
className: '',
|
||||
textContent: '',
|
||||
children: [],
|
||||
appendChild(child) {
|
||||
this.children.push(child);
|
||||
return child;
|
||||
},
|
||||
});
|
||||
globalThis.document = { createElement: element };
|
||||
try {
|
||||
const text = (node) =>
|
||||
node.children.length
|
||||
? node.children.map((child) => child.textContent).join('')
|
||||
: node.textContent;
|
||||
const kept = (node) =>
|
||||
node.children
|
||||
.filter((child) => child.className === 'data-keep')
|
||||
.map((child) => child.textContent);
|
||||
|
||||
const name = element();
|
||||
setRowText(name, 'Локальный ADS-B');
|
||||
assert.equal(text(name), 'Локальный ADS-B');
|
||||
assert.deepEqual(kept(name), ['ADS-B']);
|
||||
|
||||
const meta = element();
|
||||
setRowText(meta, 'UNAVAILABLE · NASA FIRMS · LIVE · KEY REQUIRED');
|
||||
assert.equal(text(meta), 'UNAVAILABLE · NASA FIRMS · LIVE · KEY REQUIRED');
|
||||
assert.deepEqual(kept(meta), [' ·', ' ·', ' ·']);
|
||||
assert.ok(
|
||||
meta.children.every((child) => !child.textContent.startsWith('·')),
|
||||
'the space before each dot is held to the piece it closes',
|
||||
);
|
||||
|
||||
const plain = element();
|
||||
setRowText(plain, 'Satellites');
|
||||
assert.equal(plain.textContent, 'Satellites');
|
||||
assert.equal(plain.children.length, 0);
|
||||
|
||||
const long = element();
|
||||
setRowText(long, 'see https-proxy-endpoint-config-x');
|
||||
assert.deepEqual(kept(long), [], 'a long hyphenated run may still wrap');
|
||||
} finally {
|
||||
globalThis.document = previousDocument;
|
||||
}
|
||||
});
|
||||
|
||||
test('the unavailable chip may abbreviate, but its accessible name keeps the full state', async () => {
|
||||
const { LayerPanel } = await import('./layerPanel.js');
|
||||
const attrs = new Map();
|
||||
const button = {
|
||||
classList: { toggle() {} },
|
||||
dataset: {},
|
||||
setAttribute: (key, value) => attrs.set(key, value),
|
||||
};
|
||||
LayerPanel.prototype._syncToggleButton(button, {
|
||||
id: 'local-firms',
|
||||
name: 'FIRMS Active Fires',
|
||||
enabled: false,
|
||||
stats: { sourceUnavailable: true, error: 'KEY REQUIRED' },
|
||||
});
|
||||
assert.equal(button.textContent, 'UNAVAILABLE');
|
||||
assert.equal(button.dataset.feedState, 'unavailable');
|
||||
assert.match(attrs.get('aria-label'), /^Active Fires: UNAVAILABLE\./);
|
||||
});
|
||||
|
||||
test('the Weather readout receives enabled air-quality alongside weather layers', async () => {
|
||||
const { LayerPanel } = await import('./layerPanel.js');
|
||||
const layers = ['wind', 'air-quality', 'other'].map((id) => ({
|
||||
id,
|
||||
icon: '*',
|
||||
enabled: true,
|
||||
}));
|
||||
layers.push({ id: 'weather-radar', icon: '*', enabled: false });
|
||||
const panel = new LayerPanel({
|
||||
getLayers: () => layers,
|
||||
getRowControls: (id) => ({ readout: true, summary: { label: id } }),
|
||||
});
|
||||
let entries = null;
|
||||
panel._weatherPanel = {
|
||||
update: (next) => {
|
||||
entries = next;
|
||||
},
|
||||
};
|
||||
panel._refreshWeatherPanel();
|
||||
assert.deepEqual(
|
||||
entries.map(({ id, summary }) => [id, summary.label]),
|
||||
[
|
||||
['wind', 'wind'],
|
||||
['air-quality', 'air-quality'],
|
||||
],
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
// The DATA LAYERS row shows the English status texts that GNSS, Transit,
|
||||
// CelesTrak and AQHI produce in the UI language.
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { setLocale } from '../i18n/index.js';
|
||||
import { LayerPanel } from './layerPanel.js';
|
||||
|
||||
const row = (id, stats) =>
|
||||
LayerPanel.prototype._buildMetaText({ id, enabled: true, stats });
|
||||
const now = Date.now();
|
||||
|
||||
// [layer id, stats, English fragment that must not reach the row]
|
||||
const cases = [
|
||||
[
|
||||
'gnss-integrity',
|
||||
{
|
||||
count: 0,
|
||||
error: 'GNSS feed rate limited (HTTP 429)',
|
||||
source: 'GNSS',
|
||||
lastUpdate: now,
|
||||
},
|
||||
'rate limited',
|
||||
],
|
||||
[
|
||||
'gnss-integrity',
|
||||
{
|
||||
count: 0,
|
||||
error: 'GNSS feed unavailable (HTTP 503)',
|
||||
source: 'GNSS',
|
||||
lastUpdate: now,
|
||||
},
|
||||
'feed unavailable',
|
||||
],
|
||||
[
|
||||
'transit',
|
||||
{
|
||||
count: 0,
|
||||
error: 'GO Transit feed unavailable',
|
||||
source: 'GTFS-RT',
|
||||
lastUpdate: now,
|
||||
},
|
||||
'feed unavailable',
|
||||
],
|
||||
[
|
||||
'transit',
|
||||
{
|
||||
count: 0,
|
||||
loading: true,
|
||||
loadingLabel: 'Loading GO Transit, Metro Transit',
|
||||
source: 'GTFS-RT',
|
||||
},
|
||||
'Loading',
|
||||
],
|
||||
[
|
||||
'satellites',
|
||||
{
|
||||
count: 10,
|
||||
error: '1 CelesTrak group unavailable',
|
||||
source: 'CelesTrak',
|
||||
lastUpdate: now,
|
||||
},
|
||||
'group unavailable',
|
||||
],
|
||||
[
|
||||
'air-quality',
|
||||
{
|
||||
count: 0,
|
||||
error: 'ECCC request timed out',
|
||||
source: 'ECCC',
|
||||
lastUpdate: now,
|
||||
},
|
||||
'request timed out',
|
||||
],
|
||||
];
|
||||
|
||||
for (const locale of ['es', 'ru']) {
|
||||
test(`${locale}: layer status texts are translated in the row`, () => {
|
||||
setLocale(locale);
|
||||
try {
|
||||
const english = cases
|
||||
.map(([id, stats, marker]) => [id, row(id, stats), marker])
|
||||
.filter(([, text, marker]) => text.includes(marker))
|
||||
.map(([id, text]) => `${id}: ${text}`);
|
||||
assert.deepEqual(english, []);
|
||||
} finally {
|
||||
setLocale('en');
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
test('Local ADS-B guidance hint is translated in the layer row', async () => {
|
||||
const { setLocale, t } = await import('../i18n/index.js');
|
||||
const { LayerPanel } = await import('./layerPanel.js');
|
||||
const { localAdsbStatus } = await import('../layers/localAdsb/status.js');
|
||||
const english = localAdsbStatus({
|
||||
receiver: { webUsbSupported: true, connected: false },
|
||||
feedState: null,
|
||||
heard: 0,
|
||||
});
|
||||
assert.equal(
|
||||
LayerPanel.prototype._buildMetaText.call(LayerPanel.prototype, {
|
||||
id: 'local-adsb',
|
||||
enabled: true,
|
||||
lifecycleState: 'enabled',
|
||||
stats: { count: 0, lastUpdate: null, ...english },
|
||||
}),
|
||||
'RTL-SDR · WebUSB · connect a receiver in Radio',
|
||||
);
|
||||
for (const locale of ['es', 'ru']) {
|
||||
setLocale(locale);
|
||||
for (const receiver of [
|
||||
{ webUsbSupported: true, connected: false },
|
||||
{ webUsbSupported: false, connected: false },
|
||||
{ webUsbSupported: true, connected: true, mode: 'fm' },
|
||||
]) {
|
||||
const stats = localAdsbStatus({ receiver, feedState: null, heard: 0 });
|
||||
const text = LayerPanel.prototype._buildMetaText.call(
|
||||
LayerPanel.prototype,
|
||||
{
|
||||
id: 'local-adsb',
|
||||
enabled: true,
|
||||
lifecycleState: 'enabled',
|
||||
stats: { count: 0, lastUpdate: null, ...stats },
|
||||
},
|
||||
);
|
||||
assert.notEqual(
|
||||
t(stats.statusMessage),
|
||||
stats.statusMessage,
|
||||
`${locale}: no catalog entry for "${stats.statusMessage}"`,
|
||||
);
|
||||
assert.ok(
|
||||
!text.includes(stats.statusMessage),
|
||||
`${locale}: row shows English hint: ${text}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
setLocale('en');
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { localSdrCardView } from './localSdrPresentation.js';
|
||||
import { setLocale } from '../i18n/index.js';
|
||||
|
||||
const fmStreaming = {
|
||||
webUsbSupported: true,
|
||||
connected: true,
|
||||
status: 'streaming',
|
||||
message: 'Streaming',
|
||||
mode: 'fm',
|
||||
frequencyHz: 98_500_000,
|
||||
volume: 0.8,
|
||||
gain: 'auto',
|
||||
seeking: false,
|
||||
seekMessage: '',
|
||||
decodedMessages: 0,
|
||||
messagesPerSecond: null,
|
||||
aircraftHeard: 0,
|
||||
aircraftPositioned: 0,
|
||||
deviceLabel: 'RTL2838',
|
||||
locationStatus: 'unknown',
|
||||
audioState: 'running',
|
||||
samplesPerSecond: 2_400_000,
|
||||
workerBlocks: 3,
|
||||
iqLevelDbfs: -20,
|
||||
audioLevelDbfs: -12,
|
||||
};
|
||||
|
||||
test('FM status line names the AudioContext state in the UI language', () => {
|
||||
try {
|
||||
for (const [locale, state] of [
|
||||
['es', 'running'],
|
||||
['ru', 'running'],
|
||||
['es', 'suspended'],
|
||||
['ru', 'closed'],
|
||||
['es', 'idle'],
|
||||
['ru', 'idle'],
|
||||
]) {
|
||||
setLocale(locale);
|
||||
const text = localSdrCardView({
|
||||
...fmStreaming,
|
||||
audioState: state,
|
||||
}).statusText;
|
||||
assert.doesNotMatch(
|
||||
text,
|
||||
new RegExp(`audio[: ]+${state}\\b|аудио[: ]+${state}\\b`),
|
||||
`${locale}: ${text}`,
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
setLocale('en');
|
||||
}
|
||||
});
|
||||
|
||||
test('FM status line keeps the English AudioContext state words', () => {
|
||||
setLocale('en');
|
||||
for (const state of ['running', 'suspended', 'closed', 'idle']) {
|
||||
const text = localSdrCardView({
|
||||
...fmStreaming,
|
||||
audioState: state,
|
||||
}).statusText;
|
||||
assert.ok(text.endsWith(` · audio ${state}`), text);
|
||||
}
|
||||
});
|
||||
@@ -1,8 +1,10 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import {
|
||||
internetRadioAudioActive,
|
||||
localSdrCardView,
|
||||
localSdrFeedLine,
|
||||
localSdrFmAudioActive,
|
||||
localSdrGainOptionLabel,
|
||||
} from './localSdrPresentation.js';
|
||||
|
||||
const ELEMENT_IDS = Object.freeze({
|
||||
@@ -77,6 +79,7 @@ export class LocalSdrControls {
|
||||
this._renderFrame = null;
|
||||
this._destroyed = false;
|
||||
if (!this.elements.card) return;
|
||||
this._labelGainOptions();
|
||||
this._bind();
|
||||
this._receiverUnsubscribe = receiver.subscribe((state) =>
|
||||
this._onReceiverState(state),
|
||||
@@ -95,6 +98,14 @@ export class LocalSdrControls {
|
||||
return Boolean(this._state?.connected);
|
||||
}
|
||||
|
||||
/** Numeric gain options read in the page language; values stay numeric. */
|
||||
_labelGainOptions() {
|
||||
for (const option of this.elements.gain?.options || []) {
|
||||
if (option.value !== 'auto')
|
||||
option.textContent = localSdrGainOptionLabel(option.value);
|
||||
}
|
||||
}
|
||||
|
||||
_listen(element, type, handler) {
|
||||
element?.addEventListener(type, handler, {
|
||||
signal: this._listeners.signal,
|
||||
@@ -188,7 +199,7 @@ export class LocalSdrControls {
|
||||
// Internet radio just started: it takes over from local FM.
|
||||
if (radioAudioActive && !this._radioAudioActive && this._fmAudioActive) {
|
||||
void this.receiver.stop({
|
||||
message: 'Local FM stopped: internet radio started',
|
||||
message: t('Local FM stopped: internet radio started'),
|
||||
});
|
||||
}
|
||||
this._radioAudioActive = radioAudioActive;
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { setLocale } from '../i18n/index.js';
|
||||
import { localSdrFeedLine } from './localSdrPresentation.js';
|
||||
|
||||
for (const locale of ['es', 'ru']) {
|
||||
test(`decoder feed line is translated in ${locale}`, () => {
|
||||
setLocale(locale);
|
||||
try {
|
||||
const feeds = [{ id: '1090', band: '1090', status: 'live' }];
|
||||
const polling = localSdrFeedLine({
|
||||
configured: true,
|
||||
polling: true,
|
||||
feeds: [{ ...feeds[0], status: 'unreachable' }],
|
||||
});
|
||||
const idle = localSdrFeedLine({
|
||||
configured: true,
|
||||
polling: false,
|
||||
feeds,
|
||||
});
|
||||
assert.doesNotMatch(polling, /Decoder feeds|unreachable/);
|
||||
assert.match(polling, /1090/);
|
||||
assert.doesNotMatch(idle, /Decoder feeds|read while Local ADS-B is on/);
|
||||
assert.match(idle, /1090/);
|
||||
} finally {
|
||||
setLocale('en');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test('an unknown feed status is shown as given', () => {
|
||||
setLocale('en');
|
||||
const feeds = [{ band: '1090', status: 'odd' }];
|
||||
assert.equal(
|
||||
localSdrFeedLine({ configured: true, polling: true, feeds }),
|
||||
'Decoder feeds: 1090 odd',
|
||||
);
|
||||
});
|
||||
|
||||
// A feed status agrees with "fuente" in Spanish; the shared "invalid" key
|
||||
// (any other masculine noun) is left alone.
|
||||
test('es: an invalid decoder feed reads "no válida"', () => {
|
||||
setLocale('es');
|
||||
try {
|
||||
const line = localSdrFeedLine({
|
||||
configured: true,
|
||||
polling: true,
|
||||
feeds: [
|
||||
{ band: '1090', status: 'live' },
|
||||
{ band: '1090', status: 'invalid' },
|
||||
],
|
||||
});
|
||||
assert.match(line, /no válida/);
|
||||
assert.doesNotMatch(line, /no válido\b/);
|
||||
} finally {
|
||||
setLocale('en');
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import { setLocale } from '../i18n/index.js';
|
||||
import { SdrController } from '../sdr/controller.js';
|
||||
import { LocalSdrControls } from './localSdrControls.js';
|
||||
import { localSdrCardView } from './localSdrPresentation.js';
|
||||
|
||||
function stubDocument() {
|
||||
const elements = new Map();
|
||||
const doc = {
|
||||
activeElement: null,
|
||||
getElementById(id) {
|
||||
if (!elements.has(id)) {
|
||||
const listeners = new Map();
|
||||
elements.set(id, {
|
||||
id,
|
||||
value: '',
|
||||
hidden: false,
|
||||
disabled: false,
|
||||
textContent: '',
|
||||
ownerDocument: doc,
|
||||
classList: { toggle() {} },
|
||||
setAttribute() {},
|
||||
closest: () => null,
|
||||
addEventListener(type, handler) {
|
||||
listeners.set(type, handler);
|
||||
},
|
||||
});
|
||||
}
|
||||
return elements.get(id);
|
||||
},
|
||||
};
|
||||
return doc;
|
||||
}
|
||||
|
||||
function stubRadio() {
|
||||
const listeners = new Set();
|
||||
return {
|
||||
subscribe(fn) {
|
||||
listeners.add(fn);
|
||||
return () => listeners.delete(fn);
|
||||
},
|
||||
stopPlayback() {},
|
||||
emit(state) {
|
||||
for (const fn of listeners) fn(state);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function stopLocalFmForInternetRadio(t, locale) {
|
||||
setLocale(locale);
|
||||
const receiver = new SdrController({ webUsb: {}, storage: null });
|
||||
// Pretend local FM is streaming (no real device: stop() has nothing to tear down).
|
||||
receiver._setState({ connected: true, status: 'streaming', mode: 'fm' });
|
||||
const radio = stubRadio();
|
||||
const controls = new LocalSdrControls({
|
||||
document: stubDocument(),
|
||||
receiver,
|
||||
radio,
|
||||
});
|
||||
t.after(() => {
|
||||
controls.destroy();
|
||||
setLocale('en');
|
||||
});
|
||||
|
||||
radio.emit({ audioState: 'playing' });
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
assert.equal(receiver.state.connected, false);
|
||||
return localSdrCardView(receiver.state);
|
||||
}
|
||||
|
||||
for (const locale of ['es', 'ru']) {
|
||||
test(`FM stop message after internet radio start is shown in ${locale}`, async (t) => {
|
||||
const view = await stopLocalFmForInternetRadio(t, locale);
|
||||
assert.notEqual(
|
||||
view.connectLabel,
|
||||
'CONNECT',
|
||||
'surrounding UI is translated',
|
||||
);
|
||||
assert.notEqual(
|
||||
view.statusText,
|
||||
'Local FM stopped: internet radio started',
|
||||
`status must not be the English literal under ${locale}`,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
test('FM stop message after internet radio start stays English', async (t) => {
|
||||
const view = await stopLocalFmForInternetRadio(t, 'en');
|
||||
assert.equal(view.statusText, 'Local FM stopped: internet radio started');
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
// The SDR status line and stats write numbers in the UI language, like
|
||||
// the frequency next to them ("Сканирование 101,1 МГц…").
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { setLocale } from '../i18n/index.js';
|
||||
import { localSdrCardView } from './localSdrPresentation.js';
|
||||
|
||||
const fm = {
|
||||
connected: true,
|
||||
status: 'streaming',
|
||||
mode: 'fm',
|
||||
message: 'Tuned',
|
||||
seekMessage: '',
|
||||
samplesPerSecond: 2_400_000,
|
||||
iqLevelDbfs: -21.44,
|
||||
audioLevelDbfs: -18.26,
|
||||
workerBlocks: 0,
|
||||
audioState: 'running',
|
||||
gain: 20.7,
|
||||
frequencyHz: 101_100_000,
|
||||
volume: 0.5,
|
||||
messagesPerSecond: 13.8,
|
||||
webUsbSupported: true,
|
||||
};
|
||||
|
||||
test('en: SDR readings keep their English digits', () => {
|
||||
setLocale('en');
|
||||
const view = localSdrCardView(fm);
|
||||
assert.match(view.statusText, /· 2\.40 MS\/s IQ ·/);
|
||||
assert.match(view.statusText, /· RF -21\.4 dBFS ·/);
|
||||
assert.match(view.statusText, /-18\.3 dBFS audio/);
|
||||
});
|
||||
|
||||
for (const locale of ['es', 'ru']) {
|
||||
test(`${locale}: SDR readings use the locale's decimal comma`, () => {
|
||||
setLocale(locale);
|
||||
try {
|
||||
const view = localSdrCardView(fm);
|
||||
assert.match(view.statusText, /· 2,40 MS\/s IQ ·/);
|
||||
assert.match(view.statusText, /· RF -21,4 dBFS ·/);
|
||||
assert.match(view.statusText, /-18,3 dBFS/);
|
||||
const adsb = localSdrCardView({ ...fm, mode: 'adsb' });
|
||||
assert.equal(adsb.stats.rate, '13,8');
|
||||
assert.equal(adsb.stats.iq, '-21,4 dBFS');
|
||||
assert.equal(adsb.gainValue, '20.7', 'input values stay machine');
|
||||
} finally {
|
||||
setLocale('en');
|
||||
}
|
||||
});
|
||||
}
|
||||
+102
-22
@@ -1,17 +1,89 @@
|
||||
import { localReceiverFeedName } from '../layers/localAdsb/feedNames.js';
|
||||
import { formatNumber, msg, t, tn } from '../i18n/index.js';
|
||||
import { formatQuantity } from './unitLabels.js';
|
||||
|
||||
/**
|
||||
* Pure presentation of the Local RTL-SDR card in the Radio panel. Receives the
|
||||
* receiver session snapshot and returns what each control should show.
|
||||
*/
|
||||
|
||||
// Receiver status codes shown on the connection chip and the connect button.
|
||||
const STATUS_LABELS = Object.freeze({
|
||||
idle: msg('IDLE'),
|
||||
connecting: msg('CONNECTING'),
|
||||
tuning: msg('TUNING'),
|
||||
streaming: msg('STREAMING'),
|
||||
error: msg('ERROR'),
|
||||
unsupported: msg('UNSUPPORTED'),
|
||||
});
|
||||
|
||||
function statusLabel(status) {
|
||||
const key = String(status || 'idle');
|
||||
return STATUS_LABELS[key] ? t(STATUS_LABELS[key]) : key.toUpperCase();
|
||||
}
|
||||
|
||||
// AudioContext.state values (plus the controller's "idle") as shown in the
|
||||
// FM status line; the value itself stays machine.
|
||||
const AUDIO_STATE_LABELS = Object.freeze({
|
||||
idle: msg('idle'),
|
||||
running: msg('running'),
|
||||
suspended: msg('suspended'),
|
||||
closed: msg('closed'),
|
||||
});
|
||||
|
||||
function audioStateLabel(audioState) {
|
||||
const key = String(audioState || 'idle');
|
||||
return AUDIO_STATE_LABELS[key] ? t(AUDIO_STATE_LABELS[key]) : key;
|
||||
}
|
||||
|
||||
// Decoder feed statuses from the server route, as shown on the card. They
|
||||
// carry their own context: the word agrees with "feed" (es "fuente no válida"),
|
||||
// unlike the shared "invalid" / "stale" elsewhere.
|
||||
function feedStatusLabel(status) {
|
||||
const key = String(status || 'unreachable');
|
||||
switch (key) {
|
||||
case 'live':
|
||||
return t('live', { context: 'feed status' });
|
||||
case 'stale':
|
||||
return t('stale', { context: 'feed status' });
|
||||
case 'unreachable':
|
||||
return t('unreachable', { context: 'feed status' });
|
||||
case 'invalid':
|
||||
return t('invalid', { context: 'feed status' });
|
||||
default:
|
||||
return key;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Text for a numeric gain option: the option value stays the machine value
|
||||
* ("28.0"); only the label follows the locale ("28,0 дБ").
|
||||
*/
|
||||
export function localSdrGainOptionLabel(value) {
|
||||
const gain = Number(value);
|
||||
if (!Number.isFinite(gain)) return String(value);
|
||||
return formatQuantity(gain, 'dB', {
|
||||
minimumFractionDigits: 1,
|
||||
maximumFractionDigits: 1,
|
||||
});
|
||||
}
|
||||
|
||||
function formatGain(gain) {
|
||||
return gain === 'auto' || !Number.isFinite(gain) ? 'auto' : gain.toFixed(1);
|
||||
}
|
||||
|
||||
/** A reading with a fixed number of decimals, in the UI language ("2,40"). */
|
||||
function fixed(value, digits) {
|
||||
return formatNumber(value, {
|
||||
minimumFractionDigits: digits,
|
||||
maximumFractionDigits: digits,
|
||||
useGrouping: false,
|
||||
});
|
||||
}
|
||||
|
||||
function formatIq(state) {
|
||||
return Number.isFinite(state.iqLevelDbfs)
|
||||
? `${state.iqLevelDbfs.toFixed(1)} dBFS`
|
||||
? `${fixed(state.iqLevelDbfs, 1)} dBFS`
|
||||
: '--';
|
||||
}
|
||||
|
||||
@@ -19,11 +91,16 @@ function statusText(state) {
|
||||
const fmActive = state.mode === 'fm';
|
||||
const iqStatus =
|
||||
state.samplesPerSecond > 0
|
||||
? `${(state.samplesPerSecond / 1_000_000).toFixed(2)} MS/s IQ`
|
||||
: 'waiting for IQ';
|
||||
? `${fixed(state.samplesPerSecond / 1_000_000, 2)} MS/s IQ`
|
||||
: t('waiting for IQ');
|
||||
const device = state.deviceLabel ? ` · ${state.deviceLabel}` : '';
|
||||
if (state.connected && !fmActive) {
|
||||
return `${state.message}${device} · ${iqStatus} · ${state.decodedMessages} messages`;
|
||||
const decoded = tn(
|
||||
state.decodedMessages,
|
||||
'{count} message',
|
||||
'{count} messages',
|
||||
);
|
||||
return `${state.message}${device} · ${iqStatus} · ${decoded}`;
|
||||
}
|
||||
const detail = state.seeking
|
||||
? state.seekMessage
|
||||
@@ -31,13 +108,16 @@ function statusText(state) {
|
||||
if (state.connected && fmActive) {
|
||||
const workerStatus =
|
||||
state.workerBlocks > 0
|
||||
? `DSP ${state.workerBlocks} blocks`
|
||||
: 'DSP waiting';
|
||||
? tn(state.workerBlocks, 'DSP {count} block', 'DSP {count} blocks')
|
||||
: t('DSP waiting');
|
||||
const rfStatus = `RF ${formatIq(state)}`;
|
||||
const audioSignal = Number.isFinite(state.audioLevelDbfs)
|
||||
? `${state.audioLevelDbfs.toFixed(1)} dBFS audio`
|
||||
: 'audio signal --';
|
||||
return `${detail}${device} · ${iqStatus} · ${workerStatus} · ${rfStatus} · ${audioSignal} · audio ${state.audioState}`;
|
||||
? t('{level} dBFS audio', { level: fixed(state.audioLevelDbfs, 1) })
|
||||
: t('audio signal --');
|
||||
const audio = t('audio {state}', {
|
||||
state: audioStateLabel(state.audioState),
|
||||
});
|
||||
return `${detail}${device} · ${iqStatus} · ${workerStatus} · ${rfStatus} · ${audioSignal} · ${audio}`;
|
||||
}
|
||||
return detail;
|
||||
}
|
||||
@@ -57,15 +137,15 @@ export function localSdrCardView(state) {
|
||||
return {
|
||||
connectionLabel: state.connected
|
||||
? adsbActive
|
||||
? `${state.aircraftHeard || 0} HEARD`
|
||||
: 'STREAMING'
|
||||
: String(state.status || 'idle').toUpperCase(),
|
||||
? tn(state.aircraftHeard || 0, '{count} HEARD', '{count} HEARD')
|
||||
: t('STREAMING')
|
||||
: statusLabel(state.status),
|
||||
connectionActive: Boolean(state.connected),
|
||||
connectLabel: transitional
|
||||
? String(state.status).toUpperCase()
|
||||
? statusLabel(state.status)
|
||||
: state.connected
|
||||
? 'DISCONNECT'
|
||||
: 'CONNECT',
|
||||
? t('DISCONNECT')
|
||||
: t('CONNECT'),
|
||||
connectDisabled: transitional || !state.webUsbSupported,
|
||||
connectPressed: Boolean(state.connected),
|
||||
fmActive,
|
||||
@@ -73,10 +153,10 @@ export function localSdrCardView(state) {
|
||||
modeDisabled: transitional,
|
||||
locateLabel:
|
||||
state.locationStatus === 'requesting'
|
||||
? 'LOCATING…'
|
||||
? t('LOCATING…')
|
||||
: state.locationStatus === 'ready'
|
||||
? 'LOCATED'
|
||||
: 'LOCATE',
|
||||
? t('LOCATED')
|
||||
: t('LOCATE'),
|
||||
locateDisabled: state.locationStatus === 'requesting',
|
||||
locateActive: state.locationStatus === 'ready',
|
||||
changeDeviceDisabled: transitional || !state.webUsbSupported,
|
||||
@@ -85,7 +165,7 @@ export function localSdrCardView(state) {
|
||||
statsHidden: !(adsbActive && state.connected),
|
||||
stats: {
|
||||
rate: Number.isFinite(state.messagesPerSecond)
|
||||
? state.messagesPerSecond.toFixed(1)
|
||||
? fixed(state.messagesPerSecond, 1)
|
||||
: '--',
|
||||
heard: String(state.aircraftHeard || 0),
|
||||
positioned: String(state.aircraftPositioned || 0),
|
||||
@@ -138,9 +218,9 @@ export function localSdrFeedLine(feedState) {
|
||||
const names = feeds.map((feed) => {
|
||||
const name = localReceiverFeedName(feed, feeds);
|
||||
return feedState.polling || feed?.status === 'invalid'
|
||||
? `${name} ${feed?.status || 'unreachable'}`
|
||||
? `${name} ${feedStatusLabel(feed?.status)}`
|
||||
: name;
|
||||
});
|
||||
const suffix = feedState.polling ? '' : ' · read while Local ADS-B is on';
|
||||
return `Decoder feeds: ${names.join(' · ')}${suffix}`;
|
||||
const suffix = feedState.polling ? '' : t(' · read while Local ADS-B is on');
|
||||
return `${t('Decoder feeds: {feeds}', { feeds: names.join(' · ') })}${suffix}`;
|
||||
}
|
||||
@@ -6,7 +6,9 @@ import {
|
||||
localSdrCardView,
|
||||
localSdrFeedLine,
|
||||
localSdrFmAudioActive,
|
||||
localSdrGainOptionLabel,
|
||||
} from './localSdrPresentation.js';
|
||||
import { setLocale } from '../i18n/index.js';
|
||||
|
||||
const idle = Object.freeze({
|
||||
webUsbSupported: true,
|
||||
@@ -153,3 +155,15 @@ test('two feeds on one band are told apart by their ordinal labels', () => {
|
||||
'Decoder feeds: 1090 · 978 MHz UAT #1 · 978 MHz UAT #2 · read while Local ADS-B is on',
|
||||
);
|
||||
});
|
||||
|
||||
test('gain option labels follow the page language; values stay numeric', () => {
|
||||
try {
|
||||
setLocale('en');
|
||||
assert.equal(localSdrGainOptionLabel('28.0'), '28.0\u00a0dB');
|
||||
assert.equal(localSdrGainOptionLabel('0.9'), '0.9\u00a0dB');
|
||||
setLocale('ru');
|
||||
assert.match(localSdrGainOptionLabel('28.0'), /^28,0\u00a0\S+$/);
|
||||
} finally {
|
||||
setLocale('en');
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,629 @@
|
||||
/**
|
||||
* Interface language picker: a HUD button in the bottom-right corner that
|
||||
* opens a listbox of the shipped languages.
|
||||
*
|
||||
* The logic is pure and DOM-free; mountLocalePicker() only renders it. The
|
||||
* shell decides what a choice does (confirm, reload).
|
||||
*
|
||||
* The list follows the ARIA listbox pattern: the button opens it, focus moves
|
||||
* into the list (or into the search field, which is a combobox, once there are
|
||||
* more than LOCALE_SEARCH_THRESHOLD languages), and aria-activedescendant
|
||||
* marks the active option.
|
||||
*/
|
||||
|
||||
import { t } from '../i18n/index.js';
|
||||
import { LOCALES, LOCALE_NAMES } from '../i18n/locale.js';
|
||||
|
||||
/** Above this many languages the list gets a search field. */
|
||||
export const LOCALE_SEARCH_THRESHOLD = 8;
|
||||
|
||||
/** Type-ahead keystrokes closer together than this extend one prefix. */
|
||||
export const TYPEAHEAD_RESET_MS = 500;
|
||||
|
||||
/**
|
||||
* Text folded for search: no diacritics, lower case. 'Español' → 'espanol',
|
||||
* 'Ёжик' → 'ежик'.
|
||||
* @param {unknown} text
|
||||
* @returns {string}
|
||||
*/
|
||||
export function foldSearchText(text) {
|
||||
return String(text ?? '')
|
||||
.normalize('NFD')
|
||||
.replace(/\p{M}+/gu, '')
|
||||
.toLowerCase()
|
||||
.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* A reader of language names in the interface language, via Intl.DisplayNames.
|
||||
* Returns '' for anything it cannot name (no Intl support, unknown code).
|
||||
* @param {string} locale Interface language.
|
||||
* @param {typeof Intl.DisplayNames} [DisplayNames]
|
||||
* @returns {(code: string) => string}
|
||||
*/
|
||||
export function createLocalNameReader(
|
||||
locale,
|
||||
DisplayNames = globalThis.Intl?.DisplayNames,
|
||||
) {
|
||||
let names = null;
|
||||
try {
|
||||
names = new DisplayNames([locale], { type: 'language', fallback: 'none' });
|
||||
} catch {
|
||||
return () => '';
|
||||
}
|
||||
return (code) => {
|
||||
try {
|
||||
const name = names.of(code);
|
||||
return typeof name === 'string' && name !== code ? name : '';
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The rows of the list: the current language first, then the rest in
|
||||
* alphabetical order of their own-language names (collated for the
|
||||
* interface language). `localName` is the name in the interface language,
|
||||
* left empty when it only repeats `nativeName`.
|
||||
* @param {object} input
|
||||
* @param {readonly string[]} input.locales
|
||||
* @param {string} input.current
|
||||
* @param {Record<string, string>} input.nativeNames
|
||||
* @param {(code: string) => string} [input.localName]
|
||||
* @returns {Array<{code: string, nativeName: string, localName: string, selected: boolean}>}
|
||||
*/
|
||||
export function buildLocaleOptions({
|
||||
locales,
|
||||
current,
|
||||
nativeNames,
|
||||
localName = () => '',
|
||||
}) {
|
||||
const rows = locales.map((code) => {
|
||||
const nativeName = nativeNames[code] || code;
|
||||
const translated = localName(code) || '';
|
||||
return {
|
||||
code,
|
||||
nativeName,
|
||||
localName:
|
||||
foldSearchText(translated) === foldSearchText(nativeName)
|
||||
? ''
|
||||
: translated,
|
||||
selected: code === current,
|
||||
};
|
||||
});
|
||||
let collate;
|
||||
try {
|
||||
collate = new Intl.Collator(current).compare;
|
||||
} catch {
|
||||
collate = (a, b) => a.localeCompare(b);
|
||||
}
|
||||
const others = rows
|
||||
.filter((row) => !row.selected)
|
||||
.sort((a, b) => collate(a.nativeName, b.nativeName));
|
||||
return [...rows.filter((row) => row.selected), ...others];
|
||||
}
|
||||
|
||||
/**
|
||||
* Rows matching a search: by own-language name, interface-language name or
|
||||
* code, ignoring case and diacritics. An empty query keeps every row.
|
||||
* @template {{code: string, nativeName: string, localName: string}} Row
|
||||
* @param {Row[]} options
|
||||
* @param {string} query
|
||||
* @returns {Row[]}
|
||||
*/
|
||||
export function filterLocaleOptions(options, query) {
|
||||
const needle = foldSearchText(query);
|
||||
if (!needle) return options.slice();
|
||||
return options.filter((option) =>
|
||||
[option.nativeName, option.localName, option.code].some((value) =>
|
||||
foldSearchText(value).includes(needle),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The option a navigation key moves to; null for any other key. The list
|
||||
* does not wrap, as in the ARIA listbox pattern.
|
||||
* @param {string} key
|
||||
* @param {number} index Active option, -1 for none.
|
||||
* @param {number} count
|
||||
* @returns {number|null}
|
||||
*/
|
||||
export function moveActiveIndex(key, index, count) {
|
||||
if (count <= 0) return null;
|
||||
switch (key) {
|
||||
case 'ArrowDown':
|
||||
return index < 0 ? 0 : Math.min(index + 1, count - 1);
|
||||
case 'ArrowUp':
|
||||
return index < 0 ? count - 1 : Math.max(index - 1, 0);
|
||||
case 'Home':
|
||||
return 0;
|
||||
case 'End':
|
||||
return count - 1;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Type-ahead: the next option after `fromIndex` (wrapping) whose own-language
|
||||
* or interface-language name starts with `buffer`. A buffer of one repeated
|
||||
* letter cycles through the options starting with that letter.
|
||||
* @param {Array<{nativeName: string, localName: string}>} options
|
||||
* @param {string} buffer
|
||||
* @param {number} fromIndex
|
||||
* @returns {number} -1 when nothing matches.
|
||||
*/
|
||||
export function typeaheadIndex(options, buffer, fromIndex) {
|
||||
const folded = foldSearchText(buffer);
|
||||
if (!folded || !options.length) return -1;
|
||||
const repeated = [...folded].every((char) => char === folded[0]);
|
||||
const prefix = repeated ? folded[0] : folded;
|
||||
// A longer prefix keeps refining the current option; a single letter moves on.
|
||||
const start = repeated ? fromIndex + 1 : Math.max(fromIndex, 0);
|
||||
for (let step = 0; step < options.length; step++) {
|
||||
const index = (start + step) % options.length;
|
||||
const option = options[index];
|
||||
if (
|
||||
foldSearchText(option.nativeName).startsWith(prefix) ||
|
||||
foldSearchText(option.localName).startsWith(prefix)
|
||||
)
|
||||
return index;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* What choosing a language does. The current one changes nothing; another one
|
||||
* switches after `confirmSwitch()` agrees (it asks when a reload loses work).
|
||||
* @param {string} locale
|
||||
* @param {{current: string, confirmSwitch: () => boolean, switchLocale: (locale: string) => void}} actions
|
||||
* @returns {'unchanged'|'declined'|'switched'}
|
||||
*/
|
||||
export function applyLocaleChoice(
|
||||
locale,
|
||||
{ current, confirmSwitch, switchLocale },
|
||||
) {
|
||||
if (locale === current) return 'unchanged';
|
||||
if (!confirmSwitch()) return 'declined';
|
||||
switchLocale(locale);
|
||||
return 'switched';
|
||||
}
|
||||
|
||||
/**
|
||||
* The picker's state without a DOM: open/closed, query, visible rows, active
|
||||
* row and type-ahead. `keydown` answers what a key did so the DOM layer only
|
||||
* has to render and focus.
|
||||
* @param {object} input
|
||||
* @param {readonly string[]} [input.locales]
|
||||
* @param {string} input.current
|
||||
* @param {Record<string, string>} [input.nativeNames]
|
||||
* @param {(code: string) => string} [input.localName]
|
||||
* @param {number} [input.searchThreshold]
|
||||
* @param {() => number} [input.now]
|
||||
*/
|
||||
export function createLocalePickerModel({
|
||||
locales = LOCALES,
|
||||
current,
|
||||
nativeNames = LOCALE_NAMES,
|
||||
localName = () => '',
|
||||
searchThreshold = LOCALE_SEARCH_THRESHOLD,
|
||||
now = () => Date.now(),
|
||||
}) {
|
||||
const options = buildLocaleOptions({
|
||||
locales,
|
||||
current,
|
||||
nativeNames,
|
||||
localName,
|
||||
});
|
||||
const searchable = locales.length > searchThreshold;
|
||||
let open = false;
|
||||
let query = '';
|
||||
let visible = options;
|
||||
let active = -1;
|
||||
let typed = '';
|
||||
let typedAt = -Infinity;
|
||||
|
||||
const activateSelected = () => {
|
||||
const selected = visible.findIndex((option) => option.selected);
|
||||
active = visible.length ? Math.max(selected, 0) : -1;
|
||||
};
|
||||
|
||||
return {
|
||||
current,
|
||||
options,
|
||||
searchable,
|
||||
get open() {
|
||||
return open;
|
||||
},
|
||||
get query() {
|
||||
return query;
|
||||
},
|
||||
get visible() {
|
||||
return visible;
|
||||
},
|
||||
get activeIndex() {
|
||||
return active;
|
||||
},
|
||||
get activeOption() {
|
||||
return visible[active] || null;
|
||||
},
|
||||
openList() {
|
||||
open = true;
|
||||
query = '';
|
||||
visible = options;
|
||||
typed = '';
|
||||
activateSelected();
|
||||
},
|
||||
closeList() {
|
||||
open = false;
|
||||
typed = '';
|
||||
},
|
||||
setQuery(text) {
|
||||
query = String(text ?? '');
|
||||
visible = filterLocaleOptions(options, query);
|
||||
// The current language stays active while it matches; else the first.
|
||||
activateSelected();
|
||||
},
|
||||
setActive(index) {
|
||||
if (index >= 0 && index < visible.length) active = index;
|
||||
},
|
||||
/**
|
||||
* @param {{key: string, altKey?: boolean, ctrlKey?: boolean, metaKey?: boolean}} event
|
||||
* @returns {{handled: boolean, close?: boolean, choose?: string}}
|
||||
*/
|
||||
keydown({ key, altKey = false, ctrlKey = false, metaKey = false }) {
|
||||
if (!open) return { handled: false };
|
||||
if (key === 'Escape') return { handled: true, close: true };
|
||||
if (key === 'Enter' || (key === ' ' && !searchable)) {
|
||||
const option = visible[active];
|
||||
return option
|
||||
? { handled: true, choose: option.code }
|
||||
: { handled: true };
|
||||
}
|
||||
// In the search field Home/End move the caret, as in the APG combobox.
|
||||
if (searchable && (key === 'Home' || key === 'End'))
|
||||
return { handled: false };
|
||||
const moved = moveActiveIndex(key, active, visible.length);
|
||||
if (moved !== null) {
|
||||
active = moved;
|
||||
return { handled: true };
|
||||
}
|
||||
const printable =
|
||||
key.length === 1 && key !== ' ' && !altKey && !ctrlKey && !metaKey;
|
||||
// With a search field, letters are typed into it.
|
||||
if (!printable || searchable) return { handled: false };
|
||||
const time = now();
|
||||
typed = time - typedAt > TYPEAHEAD_RESET_MS ? key : typed + key;
|
||||
typedAt = time;
|
||||
const match = typeaheadIndex(visible, typed, active);
|
||||
if (match >= 0) active = match;
|
||||
return { handled: true };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/* ── DOM ───────────────────────────────────────────────────────────────── */
|
||||
|
||||
const SVG_NS = 'http://www.w3.org/2000/svg';
|
||||
|
||||
/** Thin-line globe, check mark and caret, drawn in currentColor. */
|
||||
const ICONS = Object.freeze({
|
||||
globe: {
|
||||
stroke: [
|
||||
'M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18Z',
|
||||
'M12 3c-2.6 2.5-3.9 5.5-3.9 9s1.3 6.5 3.9 9',
|
||||
'M12 3c2.6 2.5 3.9 5.5 3.9 9s-1.3 6.5-3.9 9',
|
||||
'M3 12h18',
|
||||
'M4.3 7.5h15.4',
|
||||
'M4.3 16.5h15.4',
|
||||
],
|
||||
},
|
||||
check: { stroke: ['M5 12.5l4.3 4.3L19 7'] },
|
||||
caret: { fill: ['M7 10h10l-5 5.5Z'] },
|
||||
});
|
||||
|
||||
function icon(documentRef, name, className) {
|
||||
const svg = documentRef.createElementNS(SVG_NS, 'svg');
|
||||
svg.setAttribute('viewBox', '0 0 24 24');
|
||||
svg.setAttribute('aria-hidden', 'true');
|
||||
svg.setAttribute('focusable', 'false');
|
||||
svg.setAttribute('class', className);
|
||||
const { stroke = [], fill = [] } = ICONS[name];
|
||||
for (const d of stroke) {
|
||||
const path = documentRef.createElementNS(SVG_NS, 'path');
|
||||
path.setAttribute('d', d);
|
||||
path.setAttribute('fill', 'none');
|
||||
path.setAttribute('stroke', 'currentColor');
|
||||
path.setAttribute('stroke-width', '1.4');
|
||||
path.setAttribute('stroke-linecap', 'round');
|
||||
path.setAttribute('stroke-linejoin', 'round');
|
||||
svg.append(path);
|
||||
}
|
||||
for (const d of fill) {
|
||||
const path = documentRef.createElementNS(SVG_NS, 'path');
|
||||
path.setAttribute('d', d);
|
||||
path.setAttribute('fill', 'currentColor');
|
||||
svg.append(path);
|
||||
}
|
||||
return svg;
|
||||
}
|
||||
|
||||
function element(documentRef, tag, className) {
|
||||
const node = documentRef.createElement(tag);
|
||||
if (className) node.className = className;
|
||||
return node;
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the picker into `root` and wire it.
|
||||
* @param {object} input
|
||||
* @param {HTMLElement} input.root Empty #locale-picker container.
|
||||
* @param {string} input.current Active interface language.
|
||||
* @param {(locale: string) => void} input.onSelect Called after the list
|
||||
* closes, for a language other than the current one.
|
||||
* @param {readonly string[]} [input.locales]
|
||||
* @param {Record<string, string>} [input.nativeNames]
|
||||
* @param {number} [input.searchThreshold]
|
||||
* @returns {{open: Function, close: Function, isOpen: () => boolean, destroy: Function}}
|
||||
*/
|
||||
export function mountLocalePicker({
|
||||
root,
|
||||
current,
|
||||
onSelect,
|
||||
locales = LOCALES,
|
||||
nativeNames = LOCALE_NAMES,
|
||||
searchThreshold = LOCALE_SEARCH_THRESHOLD,
|
||||
}) {
|
||||
const documentRef = root.ownerDocument;
|
||||
const windowRef = documentRef.defaultView;
|
||||
const model = createLocalePickerModel({
|
||||
locales,
|
||||
current,
|
||||
nativeNames,
|
||||
localName: createLocalNameReader(current),
|
||||
searchThreshold,
|
||||
});
|
||||
const id = root.id || 'locale-picker';
|
||||
const ids = {
|
||||
popup: `${id}-popup`,
|
||||
heading: `${id}-heading`,
|
||||
listbox: `${id}-listbox`,
|
||||
option: (code) => `${id}-option-${code}`,
|
||||
};
|
||||
|
||||
root.textContent = '';
|
||||
root.classList.add('locale-picker');
|
||||
|
||||
const button = element(documentRef, 'button', 'locale-picker-button');
|
||||
button.type = 'button';
|
||||
button.setAttribute('aria-haspopup', 'listbox');
|
||||
button.setAttribute('aria-expanded', 'false');
|
||||
button.setAttribute('aria-controls', ids.popup);
|
||||
button.setAttribute(
|
||||
'aria-label',
|
||||
t('Language: {language}', {
|
||||
language: nativeNames[current] || current,
|
||||
}),
|
||||
);
|
||||
button.title = t('Change the interface language');
|
||||
const code = element(documentRef, 'span', 'locale-picker-code');
|
||||
code.setAttribute('translate', 'no');
|
||||
code.setAttribute('aria-hidden', 'true');
|
||||
code.textContent = current.toUpperCase();
|
||||
button.append(
|
||||
icon(documentRef, 'globe', 'locale-picker-globe'),
|
||||
code,
|
||||
icon(documentRef, 'caret', 'locale-picker-caret'),
|
||||
);
|
||||
|
||||
const popup = element(documentRef, 'div', 'locale-picker-popup');
|
||||
popup.id = ids.popup;
|
||||
popup.hidden = true;
|
||||
const heading = element(documentRef, 'div', 'locale-picker-heading');
|
||||
heading.id = ids.heading;
|
||||
heading.textContent = t('Interface language');
|
||||
popup.append(heading);
|
||||
|
||||
const listbox = element(documentRef, 'ul', 'locale-picker-list');
|
||||
listbox.id = ids.listbox;
|
||||
listbox.setAttribute('role', 'listbox');
|
||||
listbox.setAttribute('aria-labelledby', ids.heading);
|
||||
listbox.tabIndex = -1;
|
||||
|
||||
let search = null;
|
||||
if (model.searchable) {
|
||||
search = element(documentRef, 'input', 'locale-picker-search');
|
||||
search.type = 'search';
|
||||
search.autocomplete = 'off';
|
||||
search.spellcheck = false;
|
||||
search.setAttribute('role', 'combobox');
|
||||
search.setAttribute('aria-autocomplete', 'list');
|
||||
search.setAttribute('aria-expanded', 'true');
|
||||
search.setAttribute('aria-controls', ids.listbox);
|
||||
search.setAttribute('aria-label', t('Search languages'));
|
||||
search.placeholder = t('Search languages');
|
||||
popup.append(search);
|
||||
}
|
||||
popup.append(listbox);
|
||||
const empty = element(documentRef, 'p', 'locale-picker-empty');
|
||||
empty.setAttribute('role', 'status');
|
||||
empty.textContent = t('No matching languages');
|
||||
empty.hidden = true;
|
||||
popup.append(empty);
|
||||
root.append(button, popup);
|
||||
|
||||
const optionNodes = new Map();
|
||||
for (const option of model.options) {
|
||||
const item = element(documentRef, 'li', 'locale-picker-option');
|
||||
item.id = ids.option(option.code);
|
||||
item.setAttribute('role', 'option');
|
||||
item.setAttribute('aria-selected', String(option.selected));
|
||||
item.lang = option.code;
|
||||
item.dataset.locale = option.code;
|
||||
const name = element(documentRef, 'span', 'locale-picker-native');
|
||||
name.textContent = option.nativeName;
|
||||
// Every row reads the same: the language named in itself, then its code.
|
||||
// The interface-language name only helps the search find it.
|
||||
const meta = element(documentRef, 'span', 'locale-picker-meta');
|
||||
const codeLabel = element(documentRef, 'span', 'locale-picker-option-code');
|
||||
codeLabel.setAttribute('translate', 'no');
|
||||
codeLabel.textContent = option.code.toUpperCase();
|
||||
meta.append(codeLabel);
|
||||
const text = element(documentRef, 'span', 'locale-picker-text');
|
||||
text.append(name, meta);
|
||||
item.append(text);
|
||||
if (option.selected)
|
||||
item.append(icon(documentRef, 'check', 'locale-picker-check'));
|
||||
optionNodes.set(option.code, item);
|
||||
}
|
||||
|
||||
const focusTarget = () => search || listbox;
|
||||
|
||||
const render = () => {
|
||||
const visible = new Set(model.visible.map((option) => option.code));
|
||||
listbox.replaceChildren(
|
||||
...model.visible.map((option) => optionNodes.get(option.code)),
|
||||
);
|
||||
for (const [localeCode, item] of optionNodes) {
|
||||
item.classList.toggle(
|
||||
'is-active',
|
||||
visible.has(localeCode) && model.activeOption?.code === localeCode,
|
||||
);
|
||||
}
|
||||
empty.hidden = model.visible.length > 0;
|
||||
const activeNode = model.activeOption
|
||||
? optionNodes.get(model.activeOption.code)
|
||||
: null;
|
||||
if (activeNode) {
|
||||
focusTarget().setAttribute('aria-activedescendant', activeNode.id);
|
||||
activeNode.scrollIntoView?.({ block: 'nearest' });
|
||||
} else {
|
||||
focusTarget().removeAttribute('aria-activedescendant');
|
||||
}
|
||||
};
|
||||
|
||||
let swallowSpaceKeyup = false;
|
||||
|
||||
const close = ({ restoreFocus = false } = {}) => {
|
||||
if (!model.open) return;
|
||||
model.closeList();
|
||||
popup.hidden = true;
|
||||
root.classList.remove('is-open');
|
||||
button.setAttribute('aria-expanded', 'false');
|
||||
windowRef?.removeEventListener('keydown', onWindowKeyDown, true);
|
||||
documentRef.removeEventListener('pointerdown', onDocumentPointerDown, true);
|
||||
if (restoreFocus) button.focus({ preventScroll: true });
|
||||
};
|
||||
|
||||
const choose = (localeCode) => {
|
||||
close({ restoreFocus: true });
|
||||
if (localeCode !== current) onSelect(localeCode);
|
||||
};
|
||||
|
||||
const open = () => {
|
||||
if (model.open) return;
|
||||
model.openList();
|
||||
if (search) search.value = '';
|
||||
popup.hidden = false;
|
||||
root.classList.add('is-open');
|
||||
button.setAttribute('aria-expanded', 'true');
|
||||
render();
|
||||
// Window capture runs before the document-level shortcut handlers
|
||||
// (cockpit, hotkeys, push-to-talk), so keys typed in the list stay here.
|
||||
windowRef?.addEventListener('keydown', onWindowKeyDown, true);
|
||||
documentRef.addEventListener('pointerdown', onDocumentPointerDown, true);
|
||||
focusTarget().focus({ preventScroll: true });
|
||||
};
|
||||
|
||||
function onWindowKeyDown(event) {
|
||||
if (!model.open || event.isComposing) return;
|
||||
const inside = root.contains(event.target);
|
||||
if (!inside && event.key !== 'Escape') return;
|
||||
const result = model.keydown(event);
|
||||
if (!result.handled) return;
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
if (result.close) close({ restoreFocus: true });
|
||||
else if (result.choose) {
|
||||
if (event.key === ' ') swallowSpaceKeyup = true;
|
||||
choose(result.choose);
|
||||
} else render();
|
||||
}
|
||||
|
||||
function onDocumentPointerDown(event) {
|
||||
if (!root.contains(event.target)) close();
|
||||
}
|
||||
|
||||
const onButtonClick = () => {
|
||||
if (model.open) close({ restoreFocus: true });
|
||||
else open();
|
||||
};
|
||||
|
||||
const onButtonKeyDown = (event) => {
|
||||
if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
open();
|
||||
};
|
||||
|
||||
// Space chose an option and moved focus here; its keyup must not click.
|
||||
const onButtonKeyUp = (event) => {
|
||||
if (event.key !== ' ' || !swallowSpaceKeyup) return;
|
||||
swallowSpaceKeyup = false;
|
||||
event.preventDefault();
|
||||
};
|
||||
|
||||
const optionFromEvent = (event) =>
|
||||
event.target?.closest?.('[role="option"]')?.dataset.locale || null;
|
||||
|
||||
const onListClick = (event) => {
|
||||
const localeCode = optionFromEvent(event);
|
||||
if (localeCode) choose(localeCode);
|
||||
};
|
||||
|
||||
const onListPointerMove = (event) => {
|
||||
const localeCode = optionFromEvent(event);
|
||||
if (!localeCode || model.activeOption?.code === localeCode) return;
|
||||
model.setActive(
|
||||
model.visible.findIndex((option) => option.code === localeCode),
|
||||
);
|
||||
render();
|
||||
};
|
||||
|
||||
const onSearchInput = () => {
|
||||
model.setQuery(search.value);
|
||||
render();
|
||||
};
|
||||
|
||||
const onFocusOut = (event) => {
|
||||
const next = event.relatedTarget;
|
||||
if (model.open && next && !root.contains(next)) close();
|
||||
};
|
||||
|
||||
button.addEventListener('click', onButtonClick);
|
||||
button.addEventListener('keydown', onButtonKeyDown);
|
||||
button.addEventListener('keyup', onButtonKeyUp);
|
||||
listbox.addEventListener('click', onListClick);
|
||||
listbox.addEventListener('pointermove', onListPointerMove);
|
||||
search?.addEventListener('input', onSearchInput);
|
||||
root.addEventListener('focusout', onFocusOut);
|
||||
|
||||
return {
|
||||
open,
|
||||
close,
|
||||
isOpen: () => model.open,
|
||||
destroy() {
|
||||
close();
|
||||
button.removeEventListener('click', onButtonClick);
|
||||
button.removeEventListener('keydown', onButtonKeyDown);
|
||||
button.removeEventListener('keyup', onButtonKeyUp);
|
||||
listbox.removeEventListener('click', onListClick);
|
||||
listbox.removeEventListener('pointermove', onListPointerMove);
|
||||
search?.removeEventListener('input', onSearchInput);
|
||||
root.removeEventListener('focusout', onFocusOut);
|
||||
root.textContent = '';
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
// The interface language picker without a DOM: row order, search, the
|
||||
// keyboard model and what choosing a language does.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
LOCALE_SEARCH_THRESHOLD,
|
||||
TYPEAHEAD_RESET_MS,
|
||||
applyLocaleChoice,
|
||||
buildLocaleOptions,
|
||||
createLocalNameReader,
|
||||
createLocalePickerModel,
|
||||
filterLocaleOptions,
|
||||
foldSearchText,
|
||||
moveActiveIndex,
|
||||
typeaheadIndex,
|
||||
} from './localePicker.js';
|
||||
import { LOCALES, LOCALE_NAMES } from '../i18n/locale.js';
|
||||
|
||||
const NAMES = {
|
||||
en: 'English',
|
||||
es: 'Español',
|
||||
ru: 'Русский',
|
||||
de: 'Deutsch',
|
||||
fr: 'Français',
|
||||
pt: 'Português',
|
||||
tr: 'Türkçe',
|
||||
uk: 'Українська',
|
||||
ja: '日本語',
|
||||
};
|
||||
const MANY = Object.keys(NAMES);
|
||||
|
||||
const codes = (rows) => rows.map((row) => row.code);
|
||||
|
||||
test('the current language comes first, the rest by their own names', () => {
|
||||
assert.deepEqual(
|
||||
codes(
|
||||
buildLocaleOptions({
|
||||
locales: LOCALES,
|
||||
current: 'ru',
|
||||
nativeNames: LOCALE_NAMES,
|
||||
}),
|
||||
),
|
||||
['ru', 'en', 'es', 'zh-CN'],
|
||||
);
|
||||
assert.deepEqual(
|
||||
codes(
|
||||
buildLocaleOptions({
|
||||
locales: LOCALES,
|
||||
current: 'es',
|
||||
nativeNames: LOCALE_NAMES,
|
||||
}),
|
||||
),
|
||||
['es', 'en', 'ru', 'zh-CN'],
|
||||
);
|
||||
assert.deepEqual(
|
||||
codes(
|
||||
buildLocaleOptions({
|
||||
locales: LOCALES,
|
||||
current: 'en',
|
||||
nativeNames: LOCALE_NAMES,
|
||||
}),
|
||||
),
|
||||
['en', 'es', 'ru', 'zh-CN'],
|
||||
);
|
||||
const rows = buildLocaleOptions({
|
||||
locales: MANY,
|
||||
current: 'en',
|
||||
nativeNames: NAMES,
|
||||
});
|
||||
assert.deepEqual(codes(rows), [
|
||||
'en',
|
||||
'de',
|
||||
'es',
|
||||
'fr',
|
||||
'pt',
|
||||
'tr',
|
||||
'ru',
|
||||
'uk',
|
||||
'ja',
|
||||
]);
|
||||
assert.deepEqual(
|
||||
rows.map((row) => row.selected),
|
||||
[true, false, false, false, false, false, false, false, false],
|
||||
);
|
||||
});
|
||||
|
||||
test('each row gets the interface-language name for search, unless it only repeats the native one', () => {
|
||||
const local = createLocalNameReader('ru');
|
||||
const rows = buildLocaleOptions({
|
||||
locales: LOCALES,
|
||||
current: 'ru',
|
||||
nativeNames: LOCALE_NAMES,
|
||||
localName: local,
|
||||
});
|
||||
const byCode = Object.fromEntries(rows.map((row) => [row.code, row]));
|
||||
assert.equal(byCode.en.localName, 'английский');
|
||||
assert.equal(byCode.es.localName, 'испанский');
|
||||
assert.equal(byCode.ru.localName, '', 'русский only repeats Русский');
|
||||
const english = buildLocaleOptions({
|
||||
locales: LOCALES,
|
||||
current: 'en',
|
||||
nativeNames: LOCALE_NAMES,
|
||||
localName: createLocalNameReader('en'),
|
||||
});
|
||||
assert.equal(english.find((row) => row.code === 'es').localName, 'Spanish');
|
||||
});
|
||||
|
||||
test('without Intl.DisplayNames the interface-language name is simply left out', () => {
|
||||
const read = createLocalNameReader('ru', null);
|
||||
assert.equal(read('en'), '');
|
||||
class Broken {
|
||||
of() {
|
||||
throw new RangeError('bad code');
|
||||
}
|
||||
}
|
||||
assert.equal(createLocalNameReader('ru', Broken)('en'), '');
|
||||
class Echo {
|
||||
of(code) {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
assert.equal(
|
||||
createLocalNameReader('ru', Echo)('xx'),
|
||||
'',
|
||||
'a code echoed back is no name',
|
||||
);
|
||||
});
|
||||
|
||||
test('search folds case and diacritics, and matches either name or the code', () => {
|
||||
assert.equal(foldSearchText(' Español '), 'espanol');
|
||||
assert.equal(foldSearchText('Français'), 'francais');
|
||||
assert.equal(foldSearchText('Ёлка'), 'елка');
|
||||
const rows = buildLocaleOptions({
|
||||
locales: MANY,
|
||||
current: 'ru',
|
||||
nativeNames: NAMES,
|
||||
localName: createLocalNameReader('ru'),
|
||||
});
|
||||
assert.deepEqual(codes(filterLocaleOptions(rows, 'espan')), ['es']);
|
||||
assert.deepEqual(codes(filterLocaleOptions(rows, 'ESPAÑ')), ['es']);
|
||||
assert.deepEqual(codes(filterLocaleOptions(rows, 'francais')), ['fr']);
|
||||
assert.deepEqual(codes(filterLocaleOptions(rows, 'turkce')), ['tr']);
|
||||
assert.deepEqual(
|
||||
codes(filterLocaleOptions(rows, 'испан')),
|
||||
['es'],
|
||||
'by the interface-language name',
|
||||
);
|
||||
assert.deepEqual(
|
||||
codes(filterLocaleOptions(rows, 'УКРАИН')),
|
||||
['uk'],
|
||||
'й folds to и',
|
||||
);
|
||||
assert.deepEqual(
|
||||
codes(filterLocaleOptions(rows, 'JA')),
|
||||
['ja'],
|
||||
'by the code',
|
||||
);
|
||||
assert.deepEqual(
|
||||
codes(filterLocaleOptions(rows, ' ')),
|
||||
codes(rows),
|
||||
'empty keeps all',
|
||||
);
|
||||
assert.deepEqual(filterLocaleOptions(rows, 'klingon'), []);
|
||||
});
|
||||
|
||||
test('the search field appears only above the threshold', () => {
|
||||
assert.equal(LOCALE_SEARCH_THRESHOLD, 8);
|
||||
assert.equal(createLocalePickerModel({ current: 'en' }).searchable, false);
|
||||
const eight = MANY.slice(0, 8);
|
||||
assert.equal(
|
||||
createLocalePickerModel({
|
||||
locales: eight,
|
||||
nativeNames: NAMES,
|
||||
current: 'en',
|
||||
}).searchable,
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
createLocalePickerModel({
|
||||
locales: MANY,
|
||||
nativeNames: NAMES,
|
||||
current: 'en',
|
||||
}).searchable,
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
test('choosing the current language changes nothing; another asks, then switches', () => {
|
||||
const calls = [];
|
||||
const actions = (answer) => ({
|
||||
current: 'ru',
|
||||
confirmSwitch: () => {
|
||||
calls.push('confirm');
|
||||
return answer;
|
||||
},
|
||||
switchLocale: (locale) => calls.push(`switch:${locale}`),
|
||||
});
|
||||
assert.equal(applyLocaleChoice('ru', actions(true)), 'unchanged');
|
||||
assert.deepEqual(calls, [], 'no prompt, no reload');
|
||||
assert.equal(applyLocaleChoice('es', actions(false)), 'declined');
|
||||
assert.deepEqual(calls, ['confirm']);
|
||||
assert.equal(applyLocaleChoice('es', actions(true)), 'switched');
|
||||
assert.deepEqual(calls, ['confirm', 'confirm', 'switch:es']);
|
||||
});
|
||||
|
||||
test('navigation keys move without wrapping', () => {
|
||||
assert.equal(moveActiveIndex('ArrowDown', 0, 3), 1);
|
||||
assert.equal(moveActiveIndex('ArrowDown', 2, 3), 2);
|
||||
assert.equal(moveActiveIndex('ArrowUp', 0, 3), 0);
|
||||
assert.equal(moveActiveIndex('ArrowUp', 2, 3), 1);
|
||||
assert.equal(moveActiveIndex('ArrowDown', -1, 3), 0);
|
||||
assert.equal(moveActiveIndex('ArrowUp', -1, 3), 2);
|
||||
assert.equal(moveActiveIndex('Home', 2, 3), 0);
|
||||
assert.equal(moveActiveIndex('End', 0, 3), 2);
|
||||
assert.equal(moveActiveIndex('Tab', 0, 3), null);
|
||||
assert.equal(moveActiveIndex('ArrowDown', 0, 0), null);
|
||||
});
|
||||
|
||||
test('type-ahead cycles by first letter and refines with more letters', () => {
|
||||
const rows = buildLocaleOptions({
|
||||
locales: MANY,
|
||||
current: 'en',
|
||||
nativeNames: NAMES,
|
||||
});
|
||||
// en, de, es, fr, pt, tr, ru, uk, ja
|
||||
assert.equal(
|
||||
typeaheadIndex(rows, 'e', 0),
|
||||
2,
|
||||
'from English, e moves on to Español',
|
||||
);
|
||||
assert.equal(typeaheadIndex(rows, 'e', 2), 0, 'and wraps back to English');
|
||||
assert.equal(
|
||||
typeaheadIndex(rows, 'ee', 2),
|
||||
0,
|
||||
'a repeated letter keeps cycling',
|
||||
);
|
||||
assert.equal(typeaheadIndex(rows, 'es', 0), 2);
|
||||
assert.equal(
|
||||
typeaheadIndex(rows, 'en', 0),
|
||||
0,
|
||||
'a longer prefix may stay put',
|
||||
);
|
||||
assert.equal(
|
||||
typeaheadIndex(rows, 'р', 0),
|
||||
6,
|
||||
'Русский by its Cyrillic letter',
|
||||
);
|
||||
assert.equal(typeaheadIndex(rows, 'q', 0), -1);
|
||||
});
|
||||
|
||||
test('keyboard model: open on the current language, move, choose, close', () => {
|
||||
const model = createLocalePickerModel({
|
||||
current: 'ru',
|
||||
localName: createLocalNameReader('ru'),
|
||||
});
|
||||
assert.deepEqual(
|
||||
model.keydown({ key: 'ArrowDown' }),
|
||||
{ handled: false },
|
||||
'closed: ignored',
|
||||
);
|
||||
model.openList();
|
||||
assert.equal(model.activeOption.code, 'ru');
|
||||
assert.deepEqual(model.keydown({ key: 'ArrowDown' }), { handled: true });
|
||||
assert.equal(model.activeOption.code, 'en');
|
||||
model.keydown({ key: 'End' });
|
||||
assert.equal(model.activeOption.code, 'zh-CN');
|
||||
model.keydown({ key: 'Home' });
|
||||
assert.equal(model.activeOption.code, 'ru');
|
||||
model.keydown({ key: 'ArrowUp' });
|
||||
assert.equal(model.activeOption.code, 'ru', 'no wrap at the top');
|
||||
assert.deepEqual(model.keydown({ key: 'Enter' }), {
|
||||
handled: true,
|
||||
choose: 'ru',
|
||||
});
|
||||
model.keydown({ key: 'ArrowDown' });
|
||||
assert.deepEqual(model.keydown({ key: ' ' }), {
|
||||
handled: true,
|
||||
choose: 'en',
|
||||
});
|
||||
assert.deepEqual(model.keydown({ key: 'Escape' }), {
|
||||
handled: true,
|
||||
close: true,
|
||||
});
|
||||
assert.deepEqual(
|
||||
model.keydown({ key: 'Tab' }),
|
||||
{ handled: false },
|
||||
'Tab leaves the list',
|
||||
);
|
||||
model.closeList();
|
||||
assert.equal(model.open, false);
|
||||
});
|
||||
|
||||
test('keyboard model: type-ahead resets after a pause and ignores shortcuts', () => {
|
||||
let clock = 0;
|
||||
const model = createLocalePickerModel({ current: 'en', now: () => clock });
|
||||
model.openList();
|
||||
assert.deepEqual(model.keydown({ key: 'e' }), { handled: true });
|
||||
assert.equal(model.activeOption.code, 'es');
|
||||
clock += 100;
|
||||
model.keydown({ key: 's' });
|
||||
assert.equal(model.activeOption.code, 'es', '"es" keeps Español');
|
||||
clock += TYPEAHEAD_RESET_MS + 1;
|
||||
model.keydown({ key: 'Р' });
|
||||
assert.equal(model.activeOption.code, 'ru');
|
||||
assert.deepEqual(
|
||||
model.keydown({ key: 'z' }),
|
||||
{ handled: true },
|
||||
'an unmatched letter is still the list’s, not a global hotkey',
|
||||
);
|
||||
assert.equal(model.activeOption.code, 'ru');
|
||||
assert.deepEqual(model.keydown({ key: 'c', metaKey: true }), {
|
||||
handled: false,
|
||||
});
|
||||
});
|
||||
|
||||
test('keyboard model with search: letters, Space, Home and End belong to the field', () => {
|
||||
const model = createLocalePickerModel({
|
||||
locales: MANY,
|
||||
nativeNames: NAMES,
|
||||
current: 'en',
|
||||
localName: createLocalNameReader('en'),
|
||||
});
|
||||
model.openList();
|
||||
assert.deepEqual(model.keydown({ key: 'f' }), { handled: false });
|
||||
assert.deepEqual(model.keydown({ key: ' ' }), { handled: false });
|
||||
assert.deepEqual(model.keydown({ key: 'Home' }), { handled: false });
|
||||
model.setQuery('SPAN');
|
||||
assert.deepEqual(codes(model.visible), ['es']);
|
||||
assert.equal(model.activeOption.code, 'es');
|
||||
assert.deepEqual(model.keydown({ key: 'Enter' }), {
|
||||
handled: true,
|
||||
choose: 'es',
|
||||
});
|
||||
model.setQuery('e');
|
||||
assert.equal(
|
||||
model.activeOption.code,
|
||||
'en',
|
||||
'the current language stays active while it matches',
|
||||
);
|
||||
model.keydown({ key: 'ArrowDown' });
|
||||
assert.notEqual(model.activeOption.code, 'en');
|
||||
model.setQuery('nothing like it');
|
||||
assert.equal(model.activeOption, null);
|
||||
assert.deepEqual(
|
||||
model.keydown({ key: 'Enter' }),
|
||||
{ handled: true },
|
||||
'nothing to choose',
|
||||
);
|
||||
model.openList();
|
||||
assert.equal(model.query, '', 'reopening clears the search');
|
||||
assert.equal(model.visible.length, MANY.length);
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
// The language picker reloads the page, so it asks first while the
|
||||
// reload would lose work (unsaved CCTV calibration, the open cockpit, anything
|
||||
// a module registers). Choosing the language already active does nothing.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { StyleManager } from './applicationShell.js';
|
||||
import {
|
||||
describeUnsavedWork,
|
||||
msg,
|
||||
registerUnsavedWork,
|
||||
setLocale,
|
||||
} from '../i18n/index.js';
|
||||
|
||||
/** Wire the shell's language choice with the given shell state. No picker
|
||||
* markup here: the picker's own behaviour is covered by localePicker.test. */
|
||||
function renderSwitch({ calDirty = false, cockpit = false } = {}) {
|
||||
const previous = {
|
||||
document: globalThis.document,
|
||||
location: globalThis.location,
|
||||
history: globalThis.history,
|
||||
confirm: globalThis.confirm,
|
||||
};
|
||||
const reloads = [];
|
||||
const prompts = [];
|
||||
let answer = true;
|
||||
globalThis.document = { getElementById: () => null };
|
||||
globalThis.location = {
|
||||
href: 'https://gev.example/#v=2',
|
||||
assign() {},
|
||||
reload: () => reloads.push(true),
|
||||
};
|
||||
globalThis.history = { replaceState() {} };
|
||||
globalThis.confirm = (text) => {
|
||||
prompts.push(text);
|
||||
return answer;
|
||||
};
|
||||
const shell = {
|
||||
services: {
|
||||
cctvLayer: {
|
||||
getUIState: () => ({ cameras: [{ calDirty: false }, { calDirty }] }),
|
||||
},
|
||||
},
|
||||
cockpitView: { active: cockpit },
|
||||
_confirmLocaleReload: StyleManager.prototype._confirmLocaleReload,
|
||||
_chooseLocale: StyleManager.prototype._chooseLocale,
|
||||
};
|
||||
StyleManager.prototype._initLocaleSelector.call(shell);
|
||||
return {
|
||||
choose: (locale) => shell._chooseLocale(locale),
|
||||
reloads,
|
||||
prompts,
|
||||
answer: (value) => (answer = value),
|
||||
restore() {
|
||||
for (const unregister of shell._unsavedWorkChecks) unregister();
|
||||
Object.assign(globalThis, previous);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const storage = globalThis.localStorage;
|
||||
test.before(() => {
|
||||
globalThis.localStorage = { setItem() {}, getItem: () => null };
|
||||
});
|
||||
test.after(() => {
|
||||
globalThis.localStorage = storage;
|
||||
});
|
||||
|
||||
test('nothing to lose: the switch reloads without asking', () => {
|
||||
const view = renderSwitch();
|
||||
try {
|
||||
view.choose('es');
|
||||
assert.deepEqual(view.prompts, []);
|
||||
assert.equal(view.reloads.length, 1);
|
||||
} finally {
|
||||
view.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('unsaved calibration or the open cockpit: the switch asks first', () => {
|
||||
const view = renderSwitch({ calDirty: true, cockpit: true });
|
||||
try {
|
||||
view.answer(false);
|
||||
view.choose('ru');
|
||||
assert.equal(view.prompts.length, 1);
|
||||
assert.match(view.prompts[0], /unsaved CCTV calibration/);
|
||||
assert.match(view.prompts[0], /the open cockpit/);
|
||||
assert.equal(view.reloads.length, 0, 'declined: no reload');
|
||||
view.answer(true);
|
||||
view.choose('ru');
|
||||
assert.equal(view.reloads.length, 1, 'confirmed: reload');
|
||||
} finally {
|
||||
view.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('modules register their own unsaved work', () => {
|
||||
const unregister = registerUnsavedWork(() => msg('drawings on the map'));
|
||||
const failing = registerUnsavedWork(() => {
|
||||
throw new Error('broken check');
|
||||
});
|
||||
const view = renderSwitch();
|
||||
try {
|
||||
view.answer(false);
|
||||
view.choose('es');
|
||||
assert.match(view.prompts[0], /drawings on the map/);
|
||||
assert.equal(view.reloads.length, 0);
|
||||
} finally {
|
||||
view.restore();
|
||||
unregister();
|
||||
failing();
|
||||
}
|
||||
assert.deepEqual(describeUnsavedWork(), []);
|
||||
});
|
||||
|
||||
test('the prompt reads in the active language', () => {
|
||||
setLocale('es');
|
||||
const view = renderSwitch({ calDirty: true });
|
||||
try {
|
||||
view.answer(false);
|
||||
view.choose('en');
|
||||
assert.equal(view.prompts.length, 1);
|
||||
assert.doesNotMatch(view.prompts[0], /Switching language/);
|
||||
} finally {
|
||||
view.restore();
|
||||
setLocale('en');
|
||||
}
|
||||
});
|
||||
|
||||
test('the language already active neither asks nor reloads', () => {
|
||||
const view = renderSwitch({ calDirty: true });
|
||||
try {
|
||||
assert.equal(view.choose('en'), 'unchanged');
|
||||
assert.deepEqual(view.prompts, []);
|
||||
assert.equal(view.reloads.length, 0);
|
||||
} finally {
|
||||
view.restore();
|
||||
}
|
||||
});
|
||||
@@ -1,6 +1,18 @@
|
||||
import { locationMiniStatus } from '../locationStatus.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
import { localizePlaceName } from './placeNames.js';
|
||||
|
||||
const POI_KEYS = ['Q', 'W', 'E', 'R', 'T'];
|
||||
|
||||
/**
|
||||
* locationStatus.js placeholder lines, built by the module itself; renderStatus
|
||||
* swaps them for translated text. Place names are shown as they are.
|
||||
*/
|
||||
const LOCATION_MINI_EMPTY = Object.freeze(locationMiniStatus());
|
||||
const LOCATION_MINI_SEARCHED_PLACEHOLDER = Object.freeze(
|
||||
locationMiniStatus({ searchedLabel: '·' }),
|
||||
);
|
||||
|
||||
/** Location DOM, keyboard handling and pending row animation over supplied actions. */
|
||||
export class LocationControls {
|
||||
constructor({
|
||||
@@ -10,6 +22,7 @@ export class LocationControls {
|
||||
onCity,
|
||||
onPoi,
|
||||
onSearch,
|
||||
onSearchEdit,
|
||||
onReset,
|
||||
doc = document,
|
||||
requestFrame = (callback) => requestAnimationFrame(callback),
|
||||
@@ -38,7 +51,7 @@ export class LocationControls {
|
||||
pill.type = 'button';
|
||||
pill.className = 'location-pill';
|
||||
pill.dataset.locationId = id;
|
||||
pill.textContent = city.name;
|
||||
pill.textContent = localizePlaceName(city.name);
|
||||
this.bind(pill, 'click', () => onCity(id));
|
||||
elements.pills.appendChild(pill);
|
||||
}
|
||||
@@ -62,6 +75,11 @@ export class LocationControls {
|
||||
this.bind(elements.search, 'keydown', (event) => {
|
||||
if (event.key === 'Enter') void onSearch(elements.search.value);
|
||||
});
|
||||
// Typing corrects a failed query; closing the field (which empties it) drops its error.
|
||||
this.bind(elements.search, 'input', () => onSearchEdit?.());
|
||||
this.bind(elements.search, 'blur', () => {
|
||||
if (!elements.search.value) onSearchEdit?.();
|
||||
});
|
||||
for (const button of elements.resetButtons)
|
||||
this.bind(button, 'click', onReset);
|
||||
}
|
||||
@@ -129,12 +147,28 @@ export class LocationControls {
|
||||
for (const pill of this.elements.pills.querySelectorAll('.location-pill'))
|
||||
pill.classList.toggle('active', pill.dataset.locationId === id);
|
||||
}
|
||||
renderStatus(state) {
|
||||
renderStatus(record) {
|
||||
if (this.destroyed || !this.elements.statusCity || !this.elements.statusPoi)
|
||||
return;
|
||||
// A preset city shows its name in the UI language; the record stays English.
|
||||
const state = record?.city?.name
|
||||
? {
|
||||
...record,
|
||||
city: { ...record.city, name: localizePlaceName(record.city.name) },
|
||||
}
|
||||
: record;
|
||||
const lines = locationMiniStatus(state);
|
||||
this.elements.statusCity.textContent = lines.city;
|
||||
this.elements.statusPoi.textContent = lines.poi;
|
||||
this.elements.statusCity.textContent =
|
||||
lines.city === LOCATION_MINI_EMPTY.city
|
||||
? t('📍 Location: --')
|
||||
: lines.city;
|
||||
if (lines.poi === LOCATION_MINI_EMPTY.poi) {
|
||||
this.elements.statusPoi.textContent = t('Landmark: --');
|
||||
} else if (lines.poi === LOCATION_MINI_SEARCHED_PLACEHOLDER.poi) {
|
||||
this.elements.statusPoi.textContent = t('Searched location');
|
||||
} else {
|
||||
this.elements.statusPoi.textContent = lines.poi;
|
||||
}
|
||||
}
|
||||
createOrbitIndicator() {
|
||||
if (this.destroyed) return null;
|
||||
@@ -144,7 +178,7 @@ export class LocationControls {
|
||||
const icon = this.doc.createElement('span');
|
||||
icon.className = 'orbit-icon';
|
||||
icon.textContent = '↻';
|
||||
this.orbitIndicator.append(icon, ' ORBIT');
|
||||
this.orbitIndicator.append(icon, ` ${t('ORBIT')}`);
|
||||
this.doc.body.appendChild(this.orbitIndicator);
|
||||
}
|
||||
return this.orbitIndicator;
|
||||
|
||||
@@ -86,6 +86,7 @@ function fixture() {
|
||||
onCity: (id) => calls.push(['city', id]),
|
||||
onPoi: (id, index) => calls.push(['poi', id, index]),
|
||||
onSearch: (query) => calls.push(['search', query]),
|
||||
onSearchEdit: () => calls.push(['edit']),
|
||||
onReset: () => calls.push(['reset']),
|
||||
doc,
|
||||
requestFrame: (fn) => {
|
||||
@@ -147,3 +148,13 @@ test('location and POI keys route once while form controls retain typing', () =>
|
||||
f.elements.resetButtons[1].fire('click');
|
||||
assert.deepEqual(f.calls, [['poi', 'a', 1], ['reset']]);
|
||||
});
|
||||
test('typing clears a failed search error and closing the emptied field drops it too', () => {
|
||||
const f = fixture();
|
||||
f.elements.search.value = 'Pariss';
|
||||
f.elements.search.fire('blur');
|
||||
assert.deepEqual(f.calls, [], 'leaving a kept query keeps its error');
|
||||
f.elements.search.fire('input');
|
||||
f.elements.search.value = '';
|
||||
f.elements.search.fire('blur');
|
||||
assert.deepEqual(f.calls, [['edit'], ['edit']]);
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { t } from '../i18n/index.js';
|
||||
import { createStateChannel } from '../app/stateChannel.js';
|
||||
import { LocationControls } from './location.js';
|
||||
|
||||
@@ -79,18 +80,27 @@ export class LocationNavigation {
|
||||
|
||||
_handleLocationSearchState(state, change) {
|
||||
if (this._disposed || !change) return;
|
||||
if (change.type === 'started')
|
||||
if (change.type === 'started') {
|
||||
this._activeLocationSearchGeneration = change.generation;
|
||||
else if (change.type === 'found') {
|
||||
this._setLocationSearchError(null);
|
||||
} else if (change.type === 'found') {
|
||||
this._searchedLocationLabel = state.destination.label || state.query;
|
||||
this._setActiveLocation(null);
|
||||
this._currentPoi = null;
|
||||
this._collapsePOIRow();
|
||||
this._updateLocationMiniStatus();
|
||||
} else if (change.type === 'missing') this._showToast('Location not found');
|
||||
else if (change.type === 'failed') this._showToast('Search failed');
|
||||
} else if (change.type === 'missing')
|
||||
this._setLocationSearchError(
|
||||
`${t('Location not found')}. ${t('Check the spelling and press Enter to search again.')}`,
|
||||
);
|
||||
else if (change.type === 'failed')
|
||||
this._setLocationSearchError(
|
||||
`${t('Search failed')}. ${t('Press Enter to try again.')}`,
|
||||
);
|
||||
else if (change.type === 'settled')
|
||||
this._settleLocationSearchUi(change.generation);
|
||||
this._settleLocationSearchUi(change.generation, {
|
||||
keepQuery: state.status === 'missing' || state.status === 'failed',
|
||||
});
|
||||
else if (
|
||||
change.type === 'reset' &&
|
||||
this._activeLocationSearchGeneration !== null
|
||||
@@ -99,6 +109,21 @@ export class LocationNavigation {
|
||||
}
|
||||
}
|
||||
|
||||
/** Show, or with null clear, the announced error under the search field. */
|
||||
_setLocationSearchError(message) {
|
||||
const input = this._locationSearch;
|
||||
const error = this._locationSearchError;
|
||||
if (error) error.textContent = message || '';
|
||||
if (!input) return;
|
||||
if (message) {
|
||||
input.setAttribute('aria-invalid', 'true');
|
||||
if (error?.id) input.setAttribute('aria-describedby', error.id);
|
||||
} else {
|
||||
input.removeAttribute('aria-invalid');
|
||||
input.removeAttribute('aria-describedby');
|
||||
}
|
||||
}
|
||||
|
||||
_initLocationBar() {
|
||||
const { CITY_POIS, searchAndFlyTo, LocationSearch } = this.services;
|
||||
this._locationControls?.destroy();
|
||||
@@ -117,7 +142,7 @@ export class LocationNavigation {
|
||||
}),
|
||||
onResult: (destination) => {
|
||||
if (destination.outlineUnavailable)
|
||||
this._showToast('Detailed outline unavailable');
|
||||
this._showToast(t('Detailed outline unavailable'));
|
||||
},
|
||||
onError: (error) => console.error('[Search] Geocoding failed:', error),
|
||||
});
|
||||
@@ -142,6 +167,7 @@ export class LocationNavigation {
|
||||
onCity: (id) => this._onCityPillClick(id),
|
||||
onPoi: (id, index) => this._onPoiClick(id, index),
|
||||
onSearch: (query) => this._locationLookup.run(query),
|
||||
onSearchEdit: () => this._setLocationSearchError(null),
|
||||
onReset: () => this.resetToGlobeView(),
|
||||
});
|
||||
}
|
||||
@@ -277,10 +303,11 @@ export class LocationNavigation {
|
||||
|
||||
_toggleOrbit() {
|
||||
if (!this._currentTarget) {
|
||||
this._showToast('Fly to a POI first');
|
||||
this._showToast(t('Fly to a POI first'));
|
||||
return;
|
||||
}
|
||||
|
||||
this.services.interruptGlobeRotation?.('orbit-intent');
|
||||
const isActive = this.orbitController.toggle(this._currentTarget, {
|
||||
radius: this._currentPoi?.alt || 500,
|
||||
pitch: this._currentPoi?.pitch || -30,
|
||||
@@ -379,11 +406,11 @@ export class LocationNavigation {
|
||||
};
|
||||
this._resetGlobeBtn?.setAttribute(
|
||||
'aria-label',
|
||||
'Reset to full globe view',
|
||||
t('Reset to full globe view'),
|
||||
);
|
||||
this._cockpitResetGlobeBtn?.setAttribute(
|
||||
'aria-label',
|
||||
'Reset cockpit to full globe view',
|
||||
t('Reset cockpit to full globe view'),
|
||||
);
|
||||
this._globeResetPromise = null;
|
||||
this._cancelGlobeReset = null;
|
||||
@@ -399,11 +426,11 @@ export class LocationNavigation {
|
||||
}, 4200);
|
||||
this._resetGlobeBtn?.setAttribute(
|
||||
'aria-label',
|
||||
'Resetting to full globe view',
|
||||
t('Resetting to full globe view'),
|
||||
);
|
||||
this._cockpitResetGlobeBtn?.setAttribute(
|
||||
'aria-label',
|
||||
'Resetting cockpit to full globe view',
|
||||
t('Resetting cockpit to full globe view'),
|
||||
);
|
||||
const target = flyToGlobeView(this.viewer, {
|
||||
onComplete: () => finish(false),
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { NavigationController } from './navigationController.js';
|
||||
import { LocationNavigation } from './locationNavigation.js';
|
||||
|
||||
function input() {
|
||||
const classes = new Set(['expanded', 'searching']);
|
||||
const attributes = new Map();
|
||||
return {
|
||||
id: 'location-search',
|
||||
value: 'Pariss',
|
||||
focused: false,
|
||||
selected: false,
|
||||
classList: {
|
||||
remove: (...names) => names.forEach((name) => classes.delete(name)),
|
||||
contains: (name) => classes.has(name),
|
||||
},
|
||||
focus() {
|
||||
this.focused = true;
|
||||
},
|
||||
blur() {
|
||||
this.focused = false;
|
||||
},
|
||||
select() {
|
||||
this.selected = true;
|
||||
},
|
||||
setAttribute: (name, value) => attributes.set(name, value),
|
||||
removeAttribute: (name) => attributes.delete(name),
|
||||
getAttribute: (name) => attributes.get(name) ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function settle(searchInput, options) {
|
||||
const owner = { _activeLocationSearchGeneration: 4, searchInput };
|
||||
NavigationController.prototype._settleLocationSearchUi.call(
|
||||
owner,
|
||||
4,
|
||||
options,
|
||||
);
|
||||
return owner;
|
||||
}
|
||||
|
||||
test('a search that found nothing keeps its query, the open field and focus', () => {
|
||||
const field = input();
|
||||
const owner = settle(field, { keepQuery: true });
|
||||
assert.equal(owner._activeLocationSearchGeneration, null);
|
||||
assert.equal(field.value, 'Pariss');
|
||||
assert.equal(field.classList.contains('expanded'), true);
|
||||
assert.equal(field.classList.contains('searching'), false);
|
||||
assert.equal(field.focused, true);
|
||||
assert.equal(field.selected, true);
|
||||
});
|
||||
|
||||
test('a search that arrived still clears and closes the field', () => {
|
||||
const field = input();
|
||||
field.focused = true;
|
||||
settle(field);
|
||||
assert.equal(field.value, '');
|
||||
assert.equal(field.classList.contains('expanded'), false);
|
||||
assert.equal(field.focused, false);
|
||||
});
|
||||
|
||||
function navigation() {
|
||||
const field = input();
|
||||
const error = { id: 'location-search-error', textContent: '' };
|
||||
const settled = [];
|
||||
const toasts = [];
|
||||
const owner = {
|
||||
_disposed: false,
|
||||
_locationSearch: field,
|
||||
_locationSearchError: error,
|
||||
_activeLocationSearchGeneration: null,
|
||||
_settleLocationSearchUi: (generation, options) =>
|
||||
settled.push([generation, options]),
|
||||
_showToast: (message) => toasts.push(message),
|
||||
_setLocationSearchError:
|
||||
LocationNavigation.prototype._setLocationSearchError,
|
||||
};
|
||||
const handle = (status, type) =>
|
||||
LocationNavigation.prototype._handleLocationSearchState.call(
|
||||
owner,
|
||||
{ status, query: field.value },
|
||||
{ type, generation: 7 },
|
||||
);
|
||||
return { owner, field, error, settled, toasts, handle };
|
||||
}
|
||||
|
||||
for (const [status, text] of [
|
||||
['missing', 'Location not found'],
|
||||
['failed', 'Search failed'],
|
||||
]) {
|
||||
test(`a ${status} search announces a lasting error on the field instead of a toast`, () => {
|
||||
const n = navigation();
|
||||
n.handle('searching', 'started');
|
||||
n.handle(status, status);
|
||||
n.handle(status, 'settled');
|
||||
assert.match(n.error.textContent, new RegExp(`^${text}\\. `));
|
||||
assert.equal(n.field.getAttribute('aria-invalid'), 'true');
|
||||
assert.equal(
|
||||
n.field.getAttribute('aria-describedby'),
|
||||
'location-search-error',
|
||||
);
|
||||
assert.deepEqual(n.settled, [[7, { keepQuery: true }]]);
|
||||
assert.deepEqual(n.toasts, []);
|
||||
n.handle('searching', 'started');
|
||||
assert.equal(n.error.textContent, '');
|
||||
assert.equal(n.field.getAttribute('aria-invalid'), null);
|
||||
assert.equal(n.field.getAttribute('aria-describedby'), null);
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { renderMapStackChips, syncMapStackChips } from '../mapStackChips.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
|
||||
/**
|
||||
* Own Map Source presentation and selection without constructing map providers.
|
||||
@@ -28,7 +29,7 @@ export function createMapSourceControls({
|
||||
statusElement.textContent =
|
||||
state.status === 'switching'
|
||||
? '...'
|
||||
: stack?.shortLabel || stack?.label || 'MAP';
|
||||
: stack?.shortLabel || stack?.label || t('MAP');
|
||||
statusElement.classList.toggle('warn', !!state.lastError);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,520 @@
|
||||
/**
|
||||
* Phone shell for narrow viewports (≤720px). The globe stays full screen and a
|
||||
* bottom tab bar opens one sheet at a time; each sheet shows existing panels,
|
||||
* which stay where they are in the rails and dock while CSS presents them
|
||||
* (styles/mobile-shell.css). Desktop never sees the class or the sheet state.
|
||||
*
|
||||
* Sheets borrow panels: the panels a sheet expands are put back exactly as
|
||||
* they were when the sheets close, and nothing a sheet does is persisted or
|
||||
* treated as the user's own panel choice.
|
||||
*
|
||||
* Adapted from the phone tab-shell proposed in public PR #203 by blearymoth.
|
||||
*/
|
||||
|
||||
import { EXCLUSIVE_SURFACE_CLASSES } from '../exclusiveSurfaces.js';
|
||||
import { msg, t } from '../i18n/index.js';
|
||||
|
||||
export const MOBILE_SHELL_MEDIA_QUERY = '(max-width: 720px)';
|
||||
export const MOBILE_SHELL_CLASS = 'mobile-shell';
|
||||
export const MOBILE_SHEET_ATTR = 'data-mobile-sheet';
|
||||
|
||||
/**
|
||||
* Panels each sheet expands. A sheet also shows its rail's other panels
|
||||
* collapsed (Scenes under Layers), per styles/mobile-shell.css.
|
||||
*/
|
||||
export const MOBILE_SHEET_PANELS = Object.freeze({
|
||||
layers: Object.freeze(['data-panel']),
|
||||
cameras: Object.freeze(['cctv-panel', 'street-level-panel']),
|
||||
context: Object.freeze(['global-context-panel']),
|
||||
search: Object.freeze(['location-bar']),
|
||||
more: Object.freeze(['control-panel', 'pp-toggles']),
|
||||
});
|
||||
|
||||
export const MOBILE_TABS = Object.freeze([
|
||||
Object.freeze({ sheet: 'layers', label: msg('Layers'), icon: 'layers' }),
|
||||
Object.freeze({ sheet: 'cameras', label: msg('Cameras'), icon: 'videocam' }),
|
||||
Object.freeze({ sheet: 'context', label: msg('Context'), icon: 'radar' }),
|
||||
Object.freeze({ sheet: 'search', label: msg('Search'), icon: 'search' }),
|
||||
Object.freeze({ sheet: 'more', label: msg('More'), icon: 'more_horiz' }),
|
||||
]);
|
||||
|
||||
/**
|
||||
* Surfaces that own the screen close the open sheet and keep sheets closed.
|
||||
* Scene playback is the exception: its STOP control lives in the Scenes panel
|
||||
* (Layers sheet), and a phone has no Escape key to stop it otherwise.
|
||||
*/
|
||||
const SHEET_BLOCKING_CLASSES = Object.freeze(
|
||||
EXCLUSIVE_SURFACE_CLASSES.filter((name) => name !== 'scene-playback-mode'),
|
||||
);
|
||||
|
||||
/** Every panel any sheet borrows; the dock trays close each other. */
|
||||
const BORROWED_PANELS = Object.freeze([
|
||||
...new Set(Object.values(MOBILE_SHEET_PANELS).flat()),
|
||||
]);
|
||||
|
||||
const BORROW_OPTIONS = Object.freeze({ persist: false, syncShare: false });
|
||||
|
||||
/**
|
||||
* @param {string} panelId
|
||||
* @returns {string|null} The sheet that presents `panelId`.
|
||||
*/
|
||||
export function sheetForPanelId(panelId) {
|
||||
for (const [sheet, ids] of Object.entries(MOBILE_SHEET_PANELS)) {
|
||||
if (ids.includes(panelId)) return sheet;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The sheet after a tab press: the same tab closes its sheet, another opens.
|
||||
* @param {string|null} current
|
||||
* @param {string|null} pressed
|
||||
* @returns {string|null}
|
||||
*/
|
||||
export function nextSheet(current, pressed) {
|
||||
if (!pressed || !Object.hasOwn(MOBILE_SHEET_PANELS, pressed)) return null;
|
||||
return current === pressed ? null : pressed;
|
||||
}
|
||||
|
||||
function sheetBlocked(body) {
|
||||
return SHEET_BLOCKING_CLASSES.some((name) => body.classList.contains(name));
|
||||
}
|
||||
|
||||
function currentSheetOf(body) {
|
||||
const value = body.getAttribute(MOBILE_SHEET_ATTR);
|
||||
return value && Object.hasOwn(MOBILE_SHEET_PANELS, value) ? value : null;
|
||||
}
|
||||
|
||||
function buildChrome(documentRef) {
|
||||
const backdrop = documentRef.createElement('div');
|
||||
backdrop.id = 'mobile-sheet-backdrop';
|
||||
backdrop.hidden = true;
|
||||
|
||||
const tabBar = documentRef.createElement('nav');
|
||||
tabBar.id = 'mobile-tab-bar';
|
||||
tabBar.setAttribute('aria-label', t('Panels'));
|
||||
for (const tab of MOBILE_TABS) {
|
||||
const button = documentRef.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'mobile-tab';
|
||||
button.dataset.mobileSheet = tab.sheet;
|
||||
button.setAttribute('aria-expanded', 'false');
|
||||
const icon = documentRef.createElement('span');
|
||||
icon.className = 'material-symbols-outlined mobile-tab-icon';
|
||||
icon.setAttribute('aria-hidden', 'true');
|
||||
icon.textContent = tab.icon;
|
||||
const label = documentRef.createElement('span');
|
||||
label.className = 'mobile-tab-label';
|
||||
label.textContent = t(tab.label);
|
||||
button.append(icon, label);
|
||||
tabBar.append(button);
|
||||
}
|
||||
documentRef.body.append(backdrop, tabBar);
|
||||
return { backdrop, tabBar };
|
||||
}
|
||||
|
||||
/**
|
||||
* Wires the phone shell: the media gate, tab bar, backdrop, Escape, focus,
|
||||
* and closing for full-screen modes.
|
||||
* @param {object} input
|
||||
* @param {(panelId: string, collapsed: boolean, options?: object) => void} input.setPanelCollapsed
|
||||
* @param {Document} [input.documentRef]
|
||||
* @param {(query: string) => MediaQueryList} [input.matchMedia]
|
||||
* @param {typeof MutationObserver} [input.MutationObserverImpl]
|
||||
* @param {typeof ResizeObserver} [input.ResizeObserverImpl]
|
||||
* @param {(callback: () => void) => number} [input.requestFrame]
|
||||
* @param {() => void} [input.onSheetsClosed] Runs after the last sheet closes
|
||||
* and its panels are put back (e.g. to refresh the share link).
|
||||
* @param {(sheet: string) => void} [input.onTabOpened] Runs only when the user
|
||||
* opens a sheet from its tab, never on close or programmatic presentation.
|
||||
* @returns {{ destroy: () => void, setSheet: (sheet: string|null) => void, getSheet: () => string|null, sharedCollapsed: (panelId: string) => boolean|undefined }}
|
||||
*/
|
||||
export function initMobileShell({
|
||||
setPanelCollapsed,
|
||||
documentRef = globalThis.document,
|
||||
matchMedia = globalThis.matchMedia?.bind(globalThis),
|
||||
MutationObserverImpl = globalThis.MutationObserver,
|
||||
ResizeObserverImpl = globalThis.ResizeObserver,
|
||||
requestFrame = globalThis.requestAnimationFrame?.bind(globalThis),
|
||||
onSheetsClosed = () => {},
|
||||
onTabOpened = () => {},
|
||||
} = {}) {
|
||||
const body = documentRef.body;
|
||||
const { backdrop, tabBar } = buildChrome(documentRef);
|
||||
const viewport = documentRef.querySelector('meta[name="viewport"]');
|
||||
const viewportContent = viewport?.getAttribute('content') ?? null;
|
||||
const removers = [];
|
||||
const listen = (target, type, handler, options) => {
|
||||
target.addEventListener(type, handler, options);
|
||||
removers.push(() => target.removeEventListener(type, handler, options));
|
||||
};
|
||||
const element = (id) => documentRef.getElementById(id);
|
||||
const rails = ['left-panel-stack', 'right-context-rail']
|
||||
.map(element)
|
||||
.filter(Boolean);
|
||||
const dock = element('command-dock');
|
||||
const shown = (node) =>
|
||||
node && globalThis.getComputedStyle?.(node).display !== 'none';
|
||||
|
||||
/**
|
||||
* Panel states from before the first sheet opened (`before`) and right after
|
||||
* the open sheet was set up (`applied`); null when closed.
|
||||
*/
|
||||
let borrowed = null;
|
||||
let returnFocus = null;
|
||||
let swipe = null;
|
||||
const written = new Map();
|
||||
|
||||
const writeVar = (name, value) => {
|
||||
if (written.get(name) === value) return;
|
||||
written.set(name, value);
|
||||
body.style.setProperty(name, value);
|
||||
};
|
||||
|
||||
// The dock (Presets, Search) sits on top of whichever rail is the sheet,
|
||||
// and the required map attribution sits above everything the sheet covers.
|
||||
const measureSheet = () => {
|
||||
if (!body.classList.contains(MOBILE_SHELL_CLASS)) return;
|
||||
const height = Math.max(
|
||||
0,
|
||||
...rails.map((rail) =>
|
||||
shown(rail) ? rail.getBoundingClientRect().height : 0,
|
||||
),
|
||||
);
|
||||
writeVar('--mobile-sheet-height', `${Math.round(height)}px`);
|
||||
const viewportHeight = globalThis.innerHeight || 0;
|
||||
const cover = Math.max(
|
||||
0,
|
||||
...[...rails, currentSheetOf(body) ? dock : null]
|
||||
.filter(shown)
|
||||
.map((node) => viewportHeight - node.getBoundingClientRect().top),
|
||||
);
|
||||
writeVar('--mobile-sheet-cover', `${Math.round(cover)}px`);
|
||||
};
|
||||
|
||||
const resize =
|
||||
typeof ResizeObserverImpl === 'function'
|
||||
? new ResizeObserverImpl(measureSheet)
|
||||
: null;
|
||||
removers.push(() => resize?.disconnect());
|
||||
|
||||
const isCollapsed = (panelId) =>
|
||||
element(panelId)?.classList.contains('collapsed') ?? true;
|
||||
// The user's preference, as share links record it: a collapse that layout
|
||||
// applies only for space (Tactical, Cyber) still counts as expanded.
|
||||
const prefersCollapsed = (panelId) => {
|
||||
const classes = element(panelId)?.classList;
|
||||
if (!classes) return true;
|
||||
return (
|
||||
classes.contains('collapsed') &&
|
||||
!classes.contains('layout-auto-collapsed') &&
|
||||
!classes.contains('cyber-accordion-collapsed')
|
||||
);
|
||||
};
|
||||
|
||||
const panelStates = () =>
|
||||
new Map(
|
||||
BORROWED_PANELS.map((panelId) => [panelId, prefersCollapsed(panelId)]),
|
||||
);
|
||||
|
||||
// Undo only what opening the sheet did (including side effects, such as dock
|
||||
// trays closing each other). A panel the user changed since stays as they
|
||||
// left it, and becomes the state later sheets put back.
|
||||
const restoreBorrowed = () => {
|
||||
if (!borrowed) return;
|
||||
for (const [panelId, before] of borrowed.before) {
|
||||
const now = prefersCollapsed(panelId);
|
||||
if (now !== borrowed.applied.get(panelId))
|
||||
borrowed.before.set(panelId, now);
|
||||
else if (now !== before)
|
||||
setPanelCollapsed(panelId, before, BORROW_OPTIONS);
|
||||
}
|
||||
};
|
||||
|
||||
const present = (sheet) => {
|
||||
if (sheet) body.setAttribute(MOBILE_SHEET_ATTR, sheet);
|
||||
else body.removeAttribute(MOBILE_SHEET_ATTR);
|
||||
backdrop.hidden = !sheet;
|
||||
for (const button of tabBar.querySelectorAll('[data-mobile-sheet]'))
|
||||
button.setAttribute(
|
||||
'aria-expanded',
|
||||
String(button.dataset.mobileSheet === sheet),
|
||||
);
|
||||
measureSheet();
|
||||
};
|
||||
|
||||
/** The first visible control of the sheet's first panel, for focus on open. */
|
||||
const sheetFocusTarget = (sheet) => {
|
||||
if (sheet === 'search') return element('location-search');
|
||||
const panel = element(MOBILE_SHEET_PANELS[sheet][0]);
|
||||
const controls =
|
||||
panel?.querySelectorAll?.(
|
||||
'button:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])',
|
||||
) ?? [];
|
||||
// Sheets hide some panel chrome (tray toggles, pins) that stays in the
|
||||
// DOM, and a panel's own collapse control is a poor first stop.
|
||||
return (
|
||||
[...controls].find(
|
||||
(control) =>
|
||||
control.getClientRects().length > 0 &&
|
||||
!control.matches?.('.panel-collapse-btn'),
|
||||
) ?? null
|
||||
);
|
||||
};
|
||||
|
||||
const setSheet = (requested) => {
|
||||
swipe = null;
|
||||
if (!body.classList.contains(MOBILE_SHELL_CLASS)) return;
|
||||
const sheet = sheetBlocked(body) ? null : requested;
|
||||
const previous = currentSheetOf(body);
|
||||
if (previous === sheet) return;
|
||||
if (!previous) {
|
||||
borrowed = { before: panelStates(), applied: panelStates() };
|
||||
returnFocus = documentRef.activeElement ?? null;
|
||||
} else {
|
||||
if (previous === 'search') element('location-search')?.blur?.();
|
||||
restoreBorrowed();
|
||||
}
|
||||
present(sheet);
|
||||
if (!sheet) {
|
||||
borrowed = null;
|
||||
onSheetsClosed();
|
||||
const focus = returnFocus;
|
||||
returnFocus = null;
|
||||
if (focus && focus !== body && body.contains?.(focus)) focus.focus?.();
|
||||
return;
|
||||
}
|
||||
for (const panelId of MOBILE_SHEET_PANELS[sheet])
|
||||
if (isCollapsed(panelId))
|
||||
setPanelCollapsed(panelId, false, BORROW_OPTIONS);
|
||||
borrowed.applied = panelStates();
|
||||
// Rail layout settles on a later frame; what it does is part of opening.
|
||||
const opening = (borrowed.opening ?? 0) + 1;
|
||||
borrowed.opening = opening;
|
||||
const opened = borrowed;
|
||||
requestFrame?.(() => {
|
||||
if (borrowed === opened && opened.opening === opening)
|
||||
opened.applied = panelStates();
|
||||
});
|
||||
measureSheet();
|
||||
sheetFocusTarget(sheet)?.focus?.();
|
||||
};
|
||||
|
||||
const tabFor = (sheet) =>
|
||||
[...tabBar.querySelectorAll('[data-mobile-sheet]')].find(
|
||||
(button) => button.dataset.mobileSheet === sheet,
|
||||
);
|
||||
|
||||
const onMedia = (matches) => {
|
||||
if (matches) {
|
||||
body.classList.add(MOBILE_SHELL_CLASS);
|
||||
// Lets the page draw under the notch and system bars; the shell's CSS
|
||||
// keeps its chrome clear of them.
|
||||
if (viewport && !/viewport-fit\s*=/.test(viewportContent || ''))
|
||||
viewport.setAttribute(
|
||||
'content',
|
||||
`${viewportContent || ''}, viewport-fit=cover`,
|
||||
);
|
||||
for (const node of [...rails, dock].filter(Boolean))
|
||||
resize?.observe(node);
|
||||
measureSheet();
|
||||
} else {
|
||||
// Crossing to desktop closes the sheet, which puts its panels back.
|
||||
setSheet(null);
|
||||
body.classList.remove(MOBILE_SHELL_CLASS);
|
||||
present(null);
|
||||
resize?.disconnect();
|
||||
if (viewport && viewportContent !== null)
|
||||
viewport.setAttribute('content', viewportContent);
|
||||
}
|
||||
tabBar.setAttribute('aria-hidden', String(!matches));
|
||||
};
|
||||
|
||||
const media =
|
||||
typeof matchMedia === 'function'
|
||||
? matchMedia(MOBILE_SHELL_MEDIA_QUERY)
|
||||
: null;
|
||||
onMedia(Boolean(media?.matches));
|
||||
const onChange = (event) => onMedia(event.matches);
|
||||
if (media?.addEventListener) {
|
||||
media.addEventListener('change', onChange);
|
||||
removers.push(() => media.removeEventListener('change', onChange));
|
||||
} else if (media?.addListener) {
|
||||
// Safari before 14 only offers the legacy listener API.
|
||||
media.addListener(onChange);
|
||||
removers.push(() => media.removeListener(onChange));
|
||||
}
|
||||
|
||||
listen(tabBar, 'click', (event) => {
|
||||
const button = event.target?.closest?.('[data-mobile-sheet]');
|
||||
if (!button) return;
|
||||
event.preventDefault();
|
||||
const sheet = nextSheet(currentSheetOf(body), button.dataset.mobileSheet);
|
||||
// Closing from the tab bar returns focus to the tab that was pressed.
|
||||
if (!sheet) returnFocus = button;
|
||||
setSheet(sheet);
|
||||
if (sheet && currentSheetOf(body) === sheet) onTabOpened(sheet);
|
||||
});
|
||||
listen(backdrop, 'click', () => setSheet(null));
|
||||
// Touch events let native scrolling continue until a downward pull at the
|
||||
// top is intentional. Pointer capture/touch-action:none would also seize
|
||||
// ordinary vertical scrolling inside the borrowed panels.
|
||||
const sheetRoot = (target, sheet) => {
|
||||
const roots =
|
||||
sheet === 'layers'
|
||||
? [element('left-panel-stack')]
|
||||
: sheet === 'search'
|
||||
? [dock]
|
||||
: sheet === 'more'
|
||||
? [element('right-context-rail'), dock]
|
||||
: [element('right-context-rail')];
|
||||
return roots.find((root) => root?.contains(target));
|
||||
};
|
||||
const scrolled = (target, root) => {
|
||||
for (let node = target; node; node = node.parentElement) {
|
||||
if (node.scrollTop > 0) return true;
|
||||
if (node === root) break;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
listen(
|
||||
documentRef,
|
||||
'touchstart',
|
||||
(event) => {
|
||||
swipe = null;
|
||||
const sheet = currentSheetOf(body);
|
||||
const target = event.target;
|
||||
if (
|
||||
!sheet ||
|
||||
!body.classList.contains(MOBILE_SHELL_CLASS) ||
|
||||
event.defaultPrevented ||
|
||||
event.touches.length !== 1 ||
|
||||
target?.closest?.(
|
||||
'button, a, input, select, textarea, label, [contenteditable]:not([contenteditable="false"]), [role="slider"], [role="button"]',
|
||||
)
|
||||
)
|
||||
return;
|
||||
const root = sheetRoot(target, sheet);
|
||||
if (!root || scrolled(target, root)) return;
|
||||
const touch = event.touches[0];
|
||||
swipe = {
|
||||
sheet,
|
||||
target,
|
||||
root,
|
||||
id: touch.identifier,
|
||||
x: touch.clientX,
|
||||
y: touch.clientY,
|
||||
claimed: false,
|
||||
};
|
||||
},
|
||||
{ passive: true },
|
||||
);
|
||||
listen(
|
||||
documentRef,
|
||||
'touchmove',
|
||||
(event) => {
|
||||
if (!swipe) return;
|
||||
const touch = event.touches[0];
|
||||
if (
|
||||
event.defaultPrevented ||
|
||||
event.touches.length !== 1 ||
|
||||
touch.identifier !== swipe.id ||
|
||||
currentSheetOf(body) !== swipe.sheet ||
|
||||
scrolled(swipe.target, swipe.root)
|
||||
) {
|
||||
swipe = null;
|
||||
return;
|
||||
}
|
||||
const dx = touch.clientX - swipe.x;
|
||||
const dy = touch.clientY - swipe.y;
|
||||
if (!swipe.claimed) {
|
||||
// Claim direction before the browser crosses its native scroll slop.
|
||||
// Android can make the next move non-cancelable after a ~9px first move.
|
||||
if (Math.max(Math.abs(dx), Math.abs(dy)) < 4) return;
|
||||
if (dy <= Math.abs(dx) * 1.25 || !event.cancelable) {
|
||||
swipe = null;
|
||||
return;
|
||||
}
|
||||
swipe.claimed = true;
|
||||
}
|
||||
// Cancelling only the claimed pull leaves taps, sliders and normal scroll
|
||||
// native, and suppresses the synthetic click at the end of a dismissal.
|
||||
event.preventDefault();
|
||||
},
|
||||
{ passive: false },
|
||||
);
|
||||
listen(
|
||||
documentRef,
|
||||
'touchend',
|
||||
(event) => {
|
||||
const pull = swipe;
|
||||
swipe = null;
|
||||
if (!pull?.claimed || event.touches.length) return;
|
||||
const touch = [...event.changedTouches].find(
|
||||
(item) => item.identifier === pull.id,
|
||||
);
|
||||
if (!touch || currentSheetOf(body) !== pull.sheet) return;
|
||||
const dx = Math.abs(touch.clientX - pull.x);
|
||||
const dy = touch.clientY - pull.y;
|
||||
if (dy < 64 || dy <= dx * 1.25) return;
|
||||
returnFocus = tabFor(pull.sheet) ?? returnFocus;
|
||||
setSheet(null);
|
||||
},
|
||||
{ passive: true },
|
||||
);
|
||||
listen(
|
||||
documentRef,
|
||||
'touchcancel',
|
||||
() => {
|
||||
swipe = null;
|
||||
},
|
||||
{ passive: true },
|
||||
);
|
||||
// Bubble phase, so fields cancelling an edit, lightboxes, viewers and tools
|
||||
// take Escape first; panels yield it to the sheet (PanelChrome), and an open
|
||||
// dialog keeps its own native close.
|
||||
listen(documentRef, 'keydown', (event) => {
|
||||
if (event.key !== 'Escape' || event.defaultPrevented) return;
|
||||
const sheet = currentSheetOf(body);
|
||||
if (!sheet || documentRef.querySelector('dialog[open]')) return;
|
||||
event.preventDefault();
|
||||
returnFocus = tabFor(sheet) ?? returnFocus;
|
||||
setSheet(null);
|
||||
});
|
||||
|
||||
if (typeof MutationObserverImpl === 'function') {
|
||||
const observer = new MutationObserverImpl(() => {
|
||||
if (currentSheetOf(body) && sheetBlocked(body)) setSheet(null);
|
||||
});
|
||||
observer.observe(body, { attributes: true, attributeFilter: ['class'] });
|
||||
removers.push(() => observer.disconnect());
|
||||
}
|
||||
|
||||
return {
|
||||
setSheet,
|
||||
getSheet: () => currentSheetOf(body),
|
||||
/**
|
||||
* The collapsed state to share for a panel a sheet borrowed: its state
|
||||
* before the sheets, or the user's own change since. Undefined otherwise.
|
||||
*/
|
||||
sharedCollapsed(panelId) {
|
||||
if (!borrowed?.before.has(panelId)) return undefined;
|
||||
const now = prefersCollapsed(panelId);
|
||||
return now !== borrowed.applied.get(panelId)
|
||||
? now
|
||||
: borrowed.before.get(panelId);
|
||||
},
|
||||
destroy() {
|
||||
setSheet(null);
|
||||
for (const remove of removers.splice(0)) remove();
|
||||
body.classList.remove(MOBILE_SHELL_CLASS);
|
||||
body.removeAttribute(MOBILE_SHEET_ATTR);
|
||||
body.style.removeProperty('--mobile-sheet-height');
|
||||
body.style.removeProperty('--mobile-sheet-cover');
|
||||
if (viewport && viewportContent !== null)
|
||||
viewport.setAttribute('content', viewportContent);
|
||||
backdrop.remove();
|
||||
tabBar.remove();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,865 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import test from 'node:test';
|
||||
import { StyleManager } from './applicationShell.js';
|
||||
import { ContextControls } from './contextControls.js';
|
||||
import {
|
||||
MOBILE_SHEET_PANELS,
|
||||
MOBILE_TABS,
|
||||
initMobileShell,
|
||||
nextSheet,
|
||||
sheetForPanelId,
|
||||
} from './mobileShell.js';
|
||||
|
||||
function element(tag, document) {
|
||||
const node = new EventTarget();
|
||||
const attributes = new Map();
|
||||
const classes = new Set();
|
||||
Object.assign(node, {
|
||||
tagName: tag.toUpperCase(),
|
||||
children: [],
|
||||
dataset: {},
|
||||
hidden: false,
|
||||
textContent: '',
|
||||
className: '',
|
||||
parent: null,
|
||||
scrollTop: 0,
|
||||
parentElement: null,
|
||||
classList: {
|
||||
add: (...names) => names.forEach((name) => classes.add(name)),
|
||||
remove: (...names) => names.forEach((name) => classes.delete(name)),
|
||||
contains: (name) => classes.has(name),
|
||||
},
|
||||
style: {
|
||||
values: new Map(),
|
||||
setProperty(name, value) {
|
||||
this.values.set(name, value);
|
||||
},
|
||||
removeProperty(name) {
|
||||
this.values.delete(name);
|
||||
},
|
||||
},
|
||||
setAttribute: (key, value) => attributes.set(key, String(value)),
|
||||
getAttribute: (key) => attributes.get(key) ?? null,
|
||||
removeAttribute: (key) => attributes.delete(key),
|
||||
append(...children) {
|
||||
for (const child of children) {
|
||||
child.parent = node;
|
||||
child.parentElement = node;
|
||||
node.children.push(child);
|
||||
if (child.id) document.ids.set(child.id, child);
|
||||
}
|
||||
},
|
||||
remove() {
|
||||
const siblings = node.parent?.children;
|
||||
siblings?.splice(siblings.indexOf(node), 1);
|
||||
document.ids.delete(node.id);
|
||||
},
|
||||
contains(other) {
|
||||
for (let current = other; current; current = current.parent)
|
||||
if (current === node) return true;
|
||||
return false;
|
||||
},
|
||||
closest(selector) {
|
||||
for (let current = node; current; current = current.parent) {
|
||||
if (
|
||||
selector.startsWith('button, a') &&
|
||||
(['BUTTON', 'A', 'INPUT', 'SELECT', 'TEXTAREA', 'LABEL'].includes(
|
||||
current.tagName,
|
||||
) ||
|
||||
['slider', 'button'].includes(current.getAttribute('role')) ||
|
||||
(current.getAttribute('contenteditable') !== null &&
|
||||
current.getAttribute('contenteditable') !== 'false'))
|
||||
)
|
||||
return current;
|
||||
if (selector === '[data-mobile-sheet]' && current.dataset.mobileSheet)
|
||||
return current;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
querySelectorAll(selector) {
|
||||
const found = [];
|
||||
const matches = (child) =>
|
||||
selector === '[data-mobile-sheet]'
|
||||
? Boolean(child.dataset.mobileSheet)
|
||||
: child.tagName === 'BUTTON';
|
||||
const walk = (parent) => {
|
||||
for (const child of parent.children) {
|
||||
if (matches(child)) found.push(child);
|
||||
walk(child);
|
||||
}
|
||||
};
|
||||
walk(node);
|
||||
return found;
|
||||
},
|
||||
getBoundingClientRect: () => ({ top: 0, height: 0 }),
|
||||
getClientRects: () => (node.hidden ? [] : [{}]),
|
||||
matches: (selector) =>
|
||||
selector === '.panel-collapse-btn' &&
|
||||
node.className.split(' ').includes('panel-collapse-btn'),
|
||||
focus() {
|
||||
document.activeElement = node;
|
||||
},
|
||||
blur() {
|
||||
if (document.activeElement === node)
|
||||
document.activeElement = document.body;
|
||||
},
|
||||
});
|
||||
return node;
|
||||
}
|
||||
|
||||
const PANEL_IDS = [...new Set(Object.values(MOBILE_SHEET_PANELS).flat())];
|
||||
|
||||
function fixture({
|
||||
mobile = true,
|
||||
expanded = [],
|
||||
onTabOpened = () => {},
|
||||
} = {}) {
|
||||
const document = new EventTarget();
|
||||
document.ids = new Map();
|
||||
document.createElement = (tag) => element(tag, document);
|
||||
document.getElementById = (id) => document.ids.get(id) ?? null;
|
||||
const viewport = element('meta', document);
|
||||
viewport.setAttribute('content', 'width=device-width, initial-scale=1.0');
|
||||
document.querySelector = (selector) =>
|
||||
selector === 'meta[name="viewport"]'
|
||||
? viewport
|
||||
: selector === 'dialog[open]' && document.openDialog
|
||||
? {}
|
||||
: null;
|
||||
document.body = element('body', document);
|
||||
document.activeElement = document.body;
|
||||
const search = element('input', document);
|
||||
search.id = 'location-search';
|
||||
document.body.append(search);
|
||||
const rails = {};
|
||||
for (const id of ['left-panel-stack', 'right-context-rail', 'command-dock']) {
|
||||
rails[id] = element('div', document);
|
||||
rails[id].id = id;
|
||||
document.body.append(rails[id]);
|
||||
}
|
||||
for (const id of PANEL_IDS) {
|
||||
const panel = element('section', document);
|
||||
panel.id = id;
|
||||
if (!expanded.includes(id)) panel.classList.add('collapsed');
|
||||
// A hidden tray toggle and a collapse control first, like the panels'
|
||||
// own chrome in a sheet.
|
||||
const toggle = element('button', document);
|
||||
toggle.hidden = true;
|
||||
const collapse = element('button', document);
|
||||
collapse.className = 'panel-collapse-btn';
|
||||
panel.append(toggle, collapse, element('button', document));
|
||||
const root =
|
||||
id === 'data-panel'
|
||||
? 'left-panel-stack'
|
||||
: ['location-bar', 'control-panel'].includes(id)
|
||||
? 'command-dock'
|
||||
: 'right-context-rail';
|
||||
rails[root].append(panel);
|
||||
}
|
||||
|
||||
const media = new EventTarget();
|
||||
media.matches = mobile;
|
||||
const calls = [];
|
||||
const frames = [];
|
||||
let closedCount = 0;
|
||||
let observed = null;
|
||||
class FakeMutationObserver {
|
||||
constructor(callback) {
|
||||
observed = callback;
|
||||
}
|
||||
observe() {}
|
||||
disconnect() {
|
||||
observed = null;
|
||||
}
|
||||
}
|
||||
const shell = initMobileShell({
|
||||
documentRef: document,
|
||||
onTabOpened,
|
||||
matchMedia: () => media,
|
||||
MutationObserverImpl: FakeMutationObserver,
|
||||
ResizeObserverImpl: null,
|
||||
requestFrame: (callback) => frames.push(callback),
|
||||
onSheetsClosed: () => {
|
||||
closedCount += 1;
|
||||
},
|
||||
setPanelCollapsed: (panelId, collapsed, options) => {
|
||||
calls.push({ panelId, collapsed, ...options });
|
||||
const panel = document.getElementById(panelId);
|
||||
if (collapsed) panel.classList.add('collapsed');
|
||||
else panel.classList.remove('collapsed');
|
||||
},
|
||||
});
|
||||
const tab = (sheet) =>
|
||||
document
|
||||
.getElementById('mobile-tab-bar')
|
||||
.children.find((button) => button.dataset.mobileSheet === sheet);
|
||||
const press = (sheet) => {
|
||||
const event = new Event('click', { cancelable: true });
|
||||
Object.defineProperty(event, 'target', { value: tab(sheet) });
|
||||
document.getElementById('mobile-tab-bar').dispatchEvent(event);
|
||||
};
|
||||
const resize = (matches) => {
|
||||
media.matches = matches;
|
||||
const event = new Event('change');
|
||||
event.matches = matches;
|
||||
media.dispatchEvent(event);
|
||||
};
|
||||
const setBodyClass = (name) => {
|
||||
document.body.classList.add(name);
|
||||
observed?.();
|
||||
};
|
||||
const collapsed = (id) =>
|
||||
document.getElementById(id).classList.contains('collapsed');
|
||||
const runFrames = () => frames.splice(0).forEach((callback) => callback());
|
||||
return {
|
||||
document,
|
||||
shell,
|
||||
calls,
|
||||
runFrames,
|
||||
closedCount: () => closedCount,
|
||||
press,
|
||||
tab,
|
||||
resize,
|
||||
viewport,
|
||||
search,
|
||||
setBodyClass,
|
||||
collapsed,
|
||||
};
|
||||
}
|
||||
|
||||
test('every tab names a sheet and every sheet panel maps back to its sheet', () => {
|
||||
assert.deepEqual(
|
||||
MOBILE_TABS.map(({ sheet }) => sheet),
|
||||
Object.keys(MOBILE_SHEET_PANELS),
|
||||
);
|
||||
for (const [sheet, panels] of Object.entries(MOBILE_SHEET_PANELS))
|
||||
for (const panelId of panels) assert.equal(sheetForPanelId(panelId), sheet);
|
||||
assert.equal(sheetForPanelId('unknown-panel'), null);
|
||||
});
|
||||
|
||||
test('pressing a tab opens its sheet, pressing it again closes it', () => {
|
||||
assert.equal(nextSheet(null, 'layers'), 'layers');
|
||||
assert.equal(nextSheet('layers', 'layers'), null);
|
||||
assert.equal(nextSheet('layers', 'more'), 'more');
|
||||
assert.equal(nextSheet('layers', 'nonsense'), null);
|
||||
assert.equal(nextSheet(null, 'constructor'), null);
|
||||
});
|
||||
|
||||
test('one sheet at a time, presented with aria-expanded and a backdrop', () => {
|
||||
const { document, shell, press, tab } = fixture();
|
||||
assert.equal(document.body.classList.contains('mobile-shell'), true);
|
||||
press('layers');
|
||||
assert.equal(shell.getSheet(), 'layers');
|
||||
assert.equal(document.body.getAttribute('data-mobile-sheet'), 'layers');
|
||||
assert.equal(tab('layers').getAttribute('aria-expanded'), 'true');
|
||||
assert.equal(document.getElementById('mobile-sheet-backdrop').hidden, false);
|
||||
press('more');
|
||||
assert.equal(shell.getSheet(), 'more');
|
||||
assert.equal(tab('layers').getAttribute('aria-expanded'), 'false');
|
||||
assert.equal(tab('more').getAttribute('aria-expanded'), 'true');
|
||||
press('more');
|
||||
assert.equal(shell.getSheet(), null);
|
||||
assert.equal(document.body.getAttribute('data-mobile-sheet'), null);
|
||||
assert.equal(document.getElementById('mobile-sheet-backdrop').hidden, true);
|
||||
});
|
||||
|
||||
test('sheets borrow panels and put them back exactly as they were', () => {
|
||||
// The user left Data Layers and Presets open on desktop.
|
||||
const kept = ['data-panel', 'control-panel'];
|
||||
const { calls, press, collapsed } = fixture({ expanded: kept });
|
||||
press('cameras');
|
||||
assert.equal(collapsed('cctv-panel'), false);
|
||||
assert.equal(collapsed('street-level-panel'), false);
|
||||
press('search');
|
||||
assert.equal(collapsed('cctv-panel'), true, 'Cameras put back on switch');
|
||||
assert.equal(collapsed('location-bar'), false);
|
||||
press('search');
|
||||
for (const id of PANEL_IDS)
|
||||
assert.equal(collapsed(id), !kept.includes(id), `${id} is back as it was`);
|
||||
// Nothing a sheet does is the user's choice, persisted or shared.
|
||||
assert.ok(calls.length > 0);
|
||||
for (const call of calls) {
|
||||
assert.equal(call.explicit, undefined, `${call.panelId} is not explicit`);
|
||||
assert.equal(call.persist, false);
|
||||
assert.equal(call.syncShare, false);
|
||||
}
|
||||
// Already-open panels are not touched.
|
||||
assert.ok(!calls.some(({ panelId }) => kept.includes(panelId)));
|
||||
});
|
||||
|
||||
test('a panel the user changes inside a sheet stays as they left it', () => {
|
||||
const { press, collapsed, document } = fixture();
|
||||
press('cameras');
|
||||
// The user collapses CCTV inside the sheet (their own, persisted choice).
|
||||
document.getElementById('cctv-panel').classList.add('collapsed');
|
||||
press('cameras');
|
||||
assert.equal(collapsed('cctv-panel'), true, 'their collapse is kept');
|
||||
assert.equal(
|
||||
collapsed('street-level-panel'),
|
||||
true,
|
||||
'the borrowed one is put back',
|
||||
);
|
||||
|
||||
// Expanding one in a sheet is kept too, and later sheets respect it.
|
||||
press('layers');
|
||||
document.getElementById('cctv-panel').classList.remove('collapsed');
|
||||
press('more');
|
||||
press('more');
|
||||
assert.equal(collapsed('cctv-panel'), false);
|
||||
});
|
||||
|
||||
test('focus moves into the sheet and returns to the tab on close', () => {
|
||||
const { document, press, search, tab } = fixture();
|
||||
press('search');
|
||||
assert.equal(document.activeElement, search);
|
||||
press('search');
|
||||
assert.equal(document.activeElement, tab('search'));
|
||||
|
||||
press('layers');
|
||||
const dataPanel = document.getElementById('data-panel');
|
||||
// The first visible control that is not the panel's own collapse button.
|
||||
assert.equal(document.activeElement, dataPanel.children[2]);
|
||||
const escape = new Event('keydown', { cancelable: true });
|
||||
escape.key = 'Escape';
|
||||
document.dispatchEvent(escape);
|
||||
assert.equal(escape.defaultPrevented, true);
|
||||
assert.equal(document.activeElement, tab('layers'));
|
||||
});
|
||||
|
||||
test('the share link keeps the state from before the sheets', () => {
|
||||
const { shell, press, document, closedCount } = fixture({
|
||||
expanded: ['street-level-panel'],
|
||||
});
|
||||
assert.equal(shell.sharedCollapsed('data-panel'), undefined);
|
||||
press('layers');
|
||||
// Data Layers is open only because the sheet borrowed it.
|
||||
assert.equal(shell.sharedCollapsed('data-panel'), true);
|
||||
assert.equal(shell.sharedCollapsed('street-level-panel'), false);
|
||||
assert.equal(shell.sharedCollapsed('unrelated-panel'), undefined);
|
||||
// A user change inside the sheet is theirs to share.
|
||||
document.getElementById('cctv-panel').classList.remove('collapsed');
|
||||
assert.equal(shell.sharedCollapsed('cctv-panel'), false);
|
||||
press('more');
|
||||
assert.equal(closedCount(), 0, 'switching sheets is not closing');
|
||||
press('more');
|
||||
assert.equal(closedCount(), 1, 'closing refreshes the share link once');
|
||||
assert.equal(shell.sharedCollapsed('data-panel'), undefined);
|
||||
});
|
||||
|
||||
test('Escape closes the sheet only when nothing else took it', () => {
|
||||
const { document, shell, press } = fixture();
|
||||
const escape = () => {
|
||||
const event = new Event('keydown', { cancelable: true, bubbles: true });
|
||||
event.key = 'Escape';
|
||||
return event;
|
||||
};
|
||||
press('layers');
|
||||
// A field cancelling its edit (or a lightbox closing) handles it first.
|
||||
const handled = escape();
|
||||
handled.preventDefault();
|
||||
document.dispatchEvent(handled);
|
||||
assert.equal(shell.getSheet(), 'layers');
|
||||
// An open dialog keeps Escape for its native close.
|
||||
document.openDialog = true;
|
||||
document.dispatchEvent(escape());
|
||||
assert.equal(shell.getSheet(), 'layers');
|
||||
document.openDialog = false;
|
||||
const plain = escape();
|
||||
document.dispatchEvent(plain);
|
||||
assert.equal(shell.getSheet(), null);
|
||||
assert.equal(plain.defaultPrevented, true);
|
||||
});
|
||||
|
||||
test('share state and restores follow the preference, not layout collapse', () => {
|
||||
const { shell, press, collapsed, document } = fixture();
|
||||
// Layout collapsed Street Level only for space; the user left it open.
|
||||
const street = document.getElementById('street-level-panel');
|
||||
street.classList.add('layout-auto-collapsed');
|
||||
press('cameras');
|
||||
assert.equal(shell.sharedCollapsed('street-level-panel'), false);
|
||||
press('cameras');
|
||||
assert.equal(
|
||||
collapsed('street-level-panel'),
|
||||
false,
|
||||
'not turned into a real collapse',
|
||||
);
|
||||
});
|
||||
|
||||
test('layout settling after a sheet opens is part of opening', () => {
|
||||
const { press, runFrames, collapsed, document } = fixture({
|
||||
expanded: ['street-level-panel'],
|
||||
});
|
||||
press('cameras');
|
||||
// A rail layout pass on the next frame collapses Street Level.
|
||||
document.getElementById('street-level-panel').classList.add('collapsed');
|
||||
runFrames();
|
||||
press('cameras');
|
||||
assert.equal(collapsed('street-level-panel'), false, 'put back as it was');
|
||||
});
|
||||
|
||||
test('the backdrop closes the open sheet', () => {
|
||||
const { document, shell, press } = fixture();
|
||||
press('context');
|
||||
document
|
||||
.getElementById('mobile-sheet-backdrop')
|
||||
.dispatchEvent(new Event('click'));
|
||||
assert.equal(shell.getSheet(), null);
|
||||
});
|
||||
|
||||
test('surfaces that own the screen close sheets; scene playback does not', () => {
|
||||
for (const mode of ['cockpit-mode', 'recording-mode', 'ui-clean-view']) {
|
||||
const { shell, press, setBodyClass, collapsed } = fixture();
|
||||
press('layers');
|
||||
setBodyClass(mode);
|
||||
assert.equal(shell.getSheet(), null, `${mode} closes the sheet`);
|
||||
assert.equal(collapsed('data-panel'), true, `${mode} puts panels back`);
|
||||
press('layers');
|
||||
assert.equal(shell.getSheet(), null, `${mode} keeps sheets closed`);
|
||||
}
|
||||
// Scene STOP lives in the Scenes panel of the Layers sheet.
|
||||
const playback = fixture();
|
||||
playback.setBodyClass('scene-playback-mode');
|
||||
playback.press('layers');
|
||||
assert.equal(playback.shell.getSheet(), 'layers');
|
||||
});
|
||||
|
||||
test('desktop widths never see the shell; crossing to desktop restores it', () => {
|
||||
const desktop = fixture({ mobile: false });
|
||||
assert.equal(desktop.document.body.classList.contains('mobile-shell'), false);
|
||||
desktop.press('layers');
|
||||
assert.equal(desktop.shell.getSheet(), null);
|
||||
assert.equal(
|
||||
desktop.viewport.getAttribute('content'),
|
||||
'width=device-width, initial-scale=1.0',
|
||||
);
|
||||
|
||||
const phone = fixture({ expanded: ['street-level-panel'] });
|
||||
assert.match(phone.viewport.getAttribute('content'), /viewport-fit=cover$/);
|
||||
phone.press('cameras');
|
||||
phone.resize(false);
|
||||
assert.equal(phone.shell.getSheet(), null);
|
||||
assert.equal(phone.document.body.classList.contains('mobile-shell'), false);
|
||||
assert.equal(phone.collapsed('cctv-panel'), true);
|
||||
assert.equal(phone.collapsed('street-level-panel'), false);
|
||||
assert.equal(
|
||||
phone.viewport.getAttribute('content'),
|
||||
'width=device-width, initial-scale=1.0',
|
||||
);
|
||||
});
|
||||
|
||||
test('destroy puts panels back and removes the shell', () => {
|
||||
const { document, shell, press, viewport, collapsed } = fixture();
|
||||
press('layers');
|
||||
shell.destroy();
|
||||
assert.equal(collapsed('data-panel'), true);
|
||||
assert.equal(document.getElementById('mobile-tab-bar'), null);
|
||||
assert.equal(document.getElementById('mobile-sheet-backdrop'), null);
|
||||
assert.equal(document.body.classList.contains('mobile-shell'), false);
|
||||
assert.equal(document.body.getAttribute('data-mobile-sheet'), null);
|
||||
assert.equal(document.body.style.values.size, 0);
|
||||
assert.equal(
|
||||
viewport.getAttribute('content'),
|
||||
'width=device-width, initial-scale=1.0',
|
||||
);
|
||||
});
|
||||
|
||||
test('the phone shell keeps the required attribution visible', () => {
|
||||
// Whitespace-normalised, so formatter line wrapping cannot hide a rule.
|
||||
const css = readFileSync(
|
||||
new URL('./styles/mobile-shell.css', import.meta.url),
|
||||
'utf8',
|
||||
)
|
||||
.replace(/\s+/g, ' ')
|
||||
.replace(/\( /g, '(')
|
||||
.replace(/ \)/g, ')');
|
||||
/** The declaration block of the rule whose selector list ends with `selector`. */
|
||||
const rule = (selector) => {
|
||||
const end = css.indexOf(`${selector} {`);
|
||||
assert.notEqual(end, -1, `missing rule ending in ${selector}`);
|
||||
const open = css.indexOf('{', end);
|
||||
return css.slice(open, css.indexOf('}', open));
|
||||
};
|
||||
const lift = (block) =>
|
||||
Number(
|
||||
/bottom: calc\(var\(--mobile-tab-space\) \+ (\d+)px\)/.exec(block)?.[1],
|
||||
);
|
||||
const z = (block) => Number(/z-index: (\d+);/.exec(block)?.[1]);
|
||||
const idleCredit = rule(
|
||||
'body.mobile-shell:not(.recording-mode):not(.cockpit-mode):not(.ui-clean-view) #cesium-credits',
|
||||
);
|
||||
const dock = rule('body.mobile-shell #command-dock');
|
||||
const voice = rule('body.mobile-shell #command-dock #gev-voice-control');
|
||||
const voiceHeightPx = Number(/height: ([\d.]+)rem/.exec(voice)[1]) * 16;
|
||||
// Idle: the credit line clears the voice bar, which clears the tab bar.
|
||||
assert.ok(lift(idleCredit) > lift(dock) + voiceHeightPx);
|
||||
// It must beat the dock's :has() placements, so the offset is !important.
|
||||
assert.match(idleCredit, /\) !important;/);
|
||||
assert.doesNotMatch(
|
||||
idleCredit,
|
||||
/display:\s*none|visibility:\s*hidden|opacity:\s*0/,
|
||||
);
|
||||
// Open sheet: above everything the sheet covers, drawn above the sheets.
|
||||
const sheetCredit = rule(
|
||||
'body.mobile-shell[data-mobile-sheet]:not(.recording-mode):not(.cockpit-mode):not(.ui-clean-view) #cesium-credits',
|
||||
);
|
||||
assert.match(
|
||||
sheetCredit,
|
||||
/bottom: calc\(var\(--mobile-sheet-cover, 0px\) \+ 6px\) !important;/,
|
||||
);
|
||||
const openDock = rule('body.mobile-shell[data-mobile-sheet] #command-dock');
|
||||
const railSheet = rule(
|
||||
"body.mobile-shell[data-mobile-sheet='more'] #right-context-rail",
|
||||
);
|
||||
assert.ok(z(sheetCredit) > z(openDock));
|
||||
assert.ok(z(sheetCredit) > z(railSheet));
|
||||
});
|
||||
|
||||
function touchEvent(
|
||||
document,
|
||||
type,
|
||||
target,
|
||||
{ x = 10, y = 10, count = 1, id = 1, cancelable = true } = {},
|
||||
) {
|
||||
const event = new Event(type, { cancelable });
|
||||
const touch = { identifier: id, clientX: x, clientY: y };
|
||||
Object.defineProperty(event, 'target', { value: target });
|
||||
event.touches =
|
||||
type === 'touchend' || type === 'touchcancel'
|
||||
? []
|
||||
: Array.from({ length: count }, (_, i) => ({
|
||||
...touch,
|
||||
identifier: id + i,
|
||||
}));
|
||||
event.changedTouches = [touch];
|
||||
document.dispatchEvent(event);
|
||||
return event;
|
||||
}
|
||||
|
||||
test('downward sheet pull closes through borrowed-panel lifecycle and returns tab focus', () => {
|
||||
for (const sheet of Object.keys(MOBILE_SHEET_PANELS)) {
|
||||
const phone = fixture();
|
||||
const { document, shell, press, tab } = phone;
|
||||
press(sheet);
|
||||
const target = document.getElementById(MOBILE_SHEET_PANELS[sheet][0]);
|
||||
touchEvent(document, 'touchstart', target);
|
||||
const move = touchEvent(document, 'touchmove', target, { y: 90 });
|
||||
assert.equal(move.defaultPrevented, true);
|
||||
assert.equal(shell.getSheet(), sheet, 'waits until finger lifts');
|
||||
touchEvent(document, 'touchend', target, { y: 90 });
|
||||
assert.equal(shell.getSheet(), null);
|
||||
assert.equal(phone.closedCount(), 1);
|
||||
assert.equal(document.activeElement, tab(sheet));
|
||||
for (const id of MOBILE_SHEET_PANELS[sheet])
|
||||
assert.equal(phone.collapsed(id), true);
|
||||
assert.ok(
|
||||
phone.calls.every(
|
||||
(call) => call.persist === false && call.syncShare === false,
|
||||
),
|
||||
);
|
||||
shell.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
test('content scroll stays native, including a scroll that reaches the top mid-gesture', () => {
|
||||
for (const nested of [false, true]) {
|
||||
const { document, shell, press } = fixture();
|
||||
press('layers');
|
||||
const panel = document.getElementById('data-panel');
|
||||
const scroller = nested
|
||||
? panel
|
||||
: document.getElementById('left-panel-stack');
|
||||
scroller.scrollTop = 40;
|
||||
touchEvent(document, 'touchstart', panel);
|
||||
scroller.scrollTop = 0;
|
||||
assert.equal(
|
||||
touchEvent(document, 'touchmove', panel, { y: 120 }).defaultPrevented,
|
||||
false,
|
||||
);
|
||||
touchEvent(document, 'touchend', panel, { y: 120 });
|
||||
assert.equal(shell.getSheet(), 'layers');
|
||||
shell.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
test('taps, short pulls, upward and horizontal gestures never dismiss', () => {
|
||||
for (const path of [
|
||||
[],
|
||||
[{ x: 12, y: 14 }],
|
||||
[{ y: 40 }],
|
||||
[{ y: -30 }, { y: 120 }],
|
||||
[{ x: 60, y: 12 }, { y: 120 }],
|
||||
]) {
|
||||
const { document, shell, press } = fixture();
|
||||
press('layers');
|
||||
const panel = document.getElementById('data-panel');
|
||||
touchEvent(document, 'touchstart', panel);
|
||||
for (const point of path) touchEvent(document, 'touchmove', panel, point);
|
||||
touchEvent(document, 'touchend', panel, path.at(-1) ?? {});
|
||||
assert.equal(shell.getSheet(), 'layers');
|
||||
shell.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
test('native controls and custom sliders keep touch gestures', () => {
|
||||
for (const tag of [
|
||||
'button',
|
||||
'a',
|
||||
'input',
|
||||
'select',
|
||||
'textarea',
|
||||
'label',
|
||||
'slider',
|
||||
'editable',
|
||||
]) {
|
||||
const { document, shell, press } = fixture();
|
||||
press('more');
|
||||
const control = document.createElement(
|
||||
['slider', 'editable'].includes(tag) ? 'div' : tag,
|
||||
);
|
||||
if (tag === 'slider') control.setAttribute('role', 'slider');
|
||||
if (tag === 'editable') control.setAttribute('contenteditable', 'true');
|
||||
const child = document.createElement('span');
|
||||
control.append(child);
|
||||
document.getElementById('control-panel').append(control);
|
||||
touchEvent(document, 'touchstart', child);
|
||||
assert.equal(
|
||||
touchEvent(document, 'touchmove', child, { y: 120 }).defaultPrevented,
|
||||
false,
|
||||
);
|
||||
touchEvent(document, 'touchend', child, { y: 120 });
|
||||
assert.equal(shell.getSheet(), 'more');
|
||||
shell.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
test('multitouch, cancellation, sheet changes and desktop transitions abandon the gesture', () => {
|
||||
for (const cancel of [
|
||||
'multitouch',
|
||||
'cancel',
|
||||
'sheet',
|
||||
'desktop',
|
||||
'noncancelable',
|
||||
]) {
|
||||
const { document, shell, press, resize } = fixture();
|
||||
press('layers');
|
||||
const panel = document.getElementById('data-panel');
|
||||
touchEvent(document, 'touchstart', panel);
|
||||
if (cancel === 'multitouch')
|
||||
touchEvent(document, 'touchstart', document.body, { count: 2 });
|
||||
if (cancel === 'cancel') touchEvent(document, 'touchcancel', panel);
|
||||
if (cancel === 'sheet') press('context');
|
||||
if (cancel === 'desktop') {
|
||||
resize(false);
|
||||
resize(true);
|
||||
press('layers');
|
||||
}
|
||||
if (cancel === 'noncancelable')
|
||||
touchEvent(document, 'touchmove', panel, { y: 30, cancelable: false });
|
||||
assert.equal(
|
||||
touchEvent(document, 'touchmove', panel, { y: 120 }).defaultPrevented,
|
||||
false,
|
||||
);
|
||||
touchEvent(document, 'touchend', panel, { y: 120 });
|
||||
assert.equal(shell.getSheet(), cancel === 'sheet' ? 'context' : 'layers');
|
||||
shell.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
test('touches outside the active sheet and destroyed listeners cannot dismiss or claim a gesture', () => {
|
||||
const { document, shell, press } = fixture();
|
||||
press('layers');
|
||||
const hiddenPanel = document.getElementById('global-context-panel');
|
||||
touchEvent(document, 'touchstart', hiddenPanel);
|
||||
assert.equal(
|
||||
touchEvent(document, 'touchmove', hiddenPanel, { y: 120 }).defaultPrevented,
|
||||
false,
|
||||
);
|
||||
touchEvent(document, 'touchend', hiddenPanel, { y: 120 });
|
||||
assert.equal(shell.getSheet(), 'layers');
|
||||
const panel = document.getElementById('data-panel');
|
||||
touchEvent(document, 'touchstart', panel);
|
||||
shell.destroy();
|
||||
assert.equal(
|
||||
touchEvent(document, 'touchmove', panel, { y: 120 }).defaultPrevented,
|
||||
false,
|
||||
);
|
||||
touchEvent(document, 'touchend', panel, { y: 120 });
|
||||
assert.equal(shell.getSheet(), null);
|
||||
});
|
||||
|
||||
test('the tab-open callback reports only a successful manual opening', () => {
|
||||
const opened = [];
|
||||
const phone = fixture({ onTabOpened: (sheet) => opened.push(sheet) });
|
||||
phone.shell.setSheet('context');
|
||||
assert.deepEqual(opened, []);
|
||||
phone.press('context');
|
||||
assert.deepEqual(opened, [], 'closing is not a new context request');
|
||||
phone.press('context');
|
||||
assert.deepEqual(opened, ['context']);
|
||||
phone.setBodyClass('cockpit-mode');
|
||||
phone.press('context');
|
||||
assert.deepEqual(
|
||||
opened,
|
||||
['context'],
|
||||
'blocked sheets cannot activate a mode',
|
||||
);
|
||||
phone.shell.destroy();
|
||||
});
|
||||
|
||||
test('manual Context opens the existing transaction without disabling the tracked aircraft', async () => {
|
||||
const calls = [];
|
||||
const tracked = { layerId: 'flights', icao24: 'abc123', callsign: 'EJA225' };
|
||||
const viewer = { trackedEntity: { gevTrackedId: 'flights:abc123' } };
|
||||
const entity = viewer.trackedEntity;
|
||||
const enabled = new Set(['flights', 'weather']);
|
||||
const controls = new ContextControls({
|
||||
elements: {},
|
||||
installations: {},
|
||||
actions: {
|
||||
getCockpit: () => null,
|
||||
claimVisualAuthority: () => calls.push('claim'),
|
||||
syncDetection() {},
|
||||
scheduleLayout() {},
|
||||
showToast() {},
|
||||
},
|
||||
});
|
||||
controls.connect({
|
||||
layers: new Map(
|
||||
['flights', 'weather', 'military-awareness'].map((id) => [id, {}]),
|
||||
),
|
||||
getEnabledLayerIds: () => [...enabled],
|
||||
getLayerParams: () => ({}),
|
||||
isEffectivelyEnabled: (id) => enabled.has(id),
|
||||
isEnabled: (id) => enabled.has(id),
|
||||
setLayerParams: (id, params) => calls.push({ id, params }),
|
||||
setEnabled: async (id, value) => {
|
||||
calls.push({ id, value });
|
||||
if (!value) enabled.delete(id);
|
||||
if (id === 'flights' && !value) viewer.trackedEntity = null;
|
||||
return true;
|
||||
},
|
||||
_setEnabledWithIntent: (id, value) => {
|
||||
calls.push({ id, value });
|
||||
enabled.add(id);
|
||||
return { intentEpoch: 1, promise: Promise.resolve(true) };
|
||||
},
|
||||
});
|
||||
const shell = {
|
||||
cockpitView: {
|
||||
readAircraftInfo: () => (viewer.trackedEntity ? tracked : null),
|
||||
},
|
||||
getAircraftTrackingTarget: StyleManager.prototype.getAircraftTrackingTarget,
|
||||
getContextModeState: () => controls.getContextModeState(),
|
||||
setContextMode: (mode) => controls.setContextMode(mode),
|
||||
_showToast: () => assert.fail('successful entry must not report a failure'),
|
||||
};
|
||||
try {
|
||||
assert.equal(
|
||||
await StyleManager.prototype._onMobileTabOpened.call(shell, 'context'),
|
||||
true,
|
||||
);
|
||||
assert.equal(controls.getContextModeState().mode, 'flights');
|
||||
assert.equal(viewer.trackedEntity, entity);
|
||||
assert.deepEqual(shell.getAircraftTrackingTarget(), {
|
||||
layerId: 'flights',
|
||||
id: 'abc123',
|
||||
});
|
||||
assert.ok(enabled.has('flights'));
|
||||
assert.ok(
|
||||
calls.some(
|
||||
(call) => call.id === 'military-awareness' && call.value === true,
|
||||
),
|
||||
);
|
||||
assert.ok(!calls.some((call) => call.id === 'flights'));
|
||||
const count = calls.length;
|
||||
assert.equal(
|
||||
await StyleManager.prototype._onMobileTabOpened.call(shell, 'context'),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
calls.length,
|
||||
count,
|
||||
'an already active Contacts session is not restarted',
|
||||
);
|
||||
} finally {
|
||||
controls.stop();
|
||||
controls.disconnect();
|
||||
}
|
||||
});
|
||||
|
||||
test('manual Context respects Space Missions, busy transitions, missing tracks and disposal', async () => {
|
||||
for (const state of [
|
||||
{ mode: 'space-missions' },
|
||||
{ mode: 'flights' },
|
||||
{ changing: true },
|
||||
{ entering: 'space-missions' },
|
||||
{ noTrack: true },
|
||||
{ disposed: true },
|
||||
{ sheet: 'layers' },
|
||||
]) {
|
||||
const shell = {
|
||||
_disposed: state.disposed,
|
||||
getContextModeState: () => state,
|
||||
getAircraftTrackingTarget: () =>
|
||||
state.noTrack ? null : { layerId: 'flights', id: 'abc123' },
|
||||
setContextMode: () =>
|
||||
assert.fail('guarded tab must not mutate Context or tracking'),
|
||||
};
|
||||
assert.equal(
|
||||
await StyleManager.prototype._onMobileTabOpened.call(
|
||||
shell,
|
||||
state.sheet || 'context',
|
||||
),
|
||||
false,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('failed mobile Contacts entry uses the existing notice and cancelled/disposed entries stay quiet', async () => {
|
||||
for (const outcome of ['failure', 'throw', 'cancelled', 'disposed']) {
|
||||
const notices = [];
|
||||
const shell = {
|
||||
getContextModeState: () => ({ mode: null }),
|
||||
getAircraftTrackingTarget: () => ({ layerId: 'flights', id: 'abc123' }),
|
||||
setContextMode: async () => {
|
||||
if (outcome === 'throw') throw new Error('source unavailable');
|
||||
if (outcome === 'disposed') shell._disposed = true;
|
||||
return { ok: false, cancelled: outcome === 'cancelled' };
|
||||
},
|
||||
_showToast: (message) => notices.push(message),
|
||||
};
|
||||
assert.equal(
|
||||
await StyleManager.prototype._onMobileTabOpened.call(shell, 'context'),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
notices.length,
|
||||
['failure', 'throw'].includes(outcome) ? 1 : 0,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('a slow downward pull is claimed before Android native scroll takes ownership', () => {
|
||||
const { document, shell, press } = fixture();
|
||||
press('layers');
|
||||
const panel = document.getElementById('data-panel');
|
||||
touchEvent(document, 'touchstart', panel, { y: 100 });
|
||||
assert.equal(
|
||||
touchEvent(document, 'touchmove', panel, { y: 102 }).defaultPrevented,
|
||||
false,
|
||||
'tap jitter is left native',
|
||||
);
|
||||
assert.equal(
|
||||
touchEvent(document, 'touchmove', panel, { y: 109.3 }).defaultPrevented,
|
||||
true,
|
||||
'cancel the first directional move while Android still allows it',
|
||||
);
|
||||
assert.equal(
|
||||
touchEvent(document, 'touchmove', panel, { y: 131 }).defaultPrevented,
|
||||
true,
|
||||
);
|
||||
touchEvent(document, 'touchend', panel, { y: 175 });
|
||||
assert.equal(shell.getSheet(), null);
|
||||
shell.destroy();
|
||||
});
|
||||
@@ -14,6 +14,7 @@ export class NavigationController {
|
||||
tracking,
|
||||
searchInput,
|
||||
interruptCameraMotion,
|
||||
interruptGlobeRotation = () => {},
|
||||
isCockpitActive,
|
||||
clearLocation,
|
||||
cancelShareSelection,
|
||||
@@ -27,6 +28,7 @@ export class NavigationController {
|
||||
tracking,
|
||||
searchInput,
|
||||
interruptCameraMotion,
|
||||
interruptGlobeRotation,
|
||||
isCockpitActive,
|
||||
clearLocation,
|
||||
cancelShareSelection,
|
||||
@@ -46,6 +48,7 @@ export class NavigationController {
|
||||
cancelPendingSelection = true,
|
||||
clearSearchedLocation = true,
|
||||
} = {}) {
|
||||
this.interruptGlobeRotation('navigation-intent');
|
||||
cancelCameraArrival(this.viewer);
|
||||
this.cancelOrientation();
|
||||
const { flightsLayer, militaryFlightsLayer, satellitesLayer } =
|
||||
@@ -116,10 +119,17 @@ export class NavigationController {
|
||||
return this._navigationGeneration;
|
||||
}
|
||||
|
||||
_settleLocationSearchUi(generation) {
|
||||
/** A search that found nothing keeps its query and focus so it can be corrected. */
|
||||
_settleLocationSearchUi(generation, { keepQuery = false } = {}) {
|
||||
if (this._activeLocationSearchGeneration !== generation) return;
|
||||
this._activeLocationSearchGeneration = null;
|
||||
this.searchInput?.classList.remove('searching', 'expanded');
|
||||
this.searchInput?.classList.remove('searching');
|
||||
if (keepQuery) {
|
||||
this.searchInput?.focus();
|
||||
this.searchInput?.select?.();
|
||||
return;
|
||||
}
|
||||
this.searchInput?.classList.remove('expanded');
|
||||
if (this.searchInput) this.searchInput.value = '';
|
||||
this.searchInput?.blur();
|
||||
}
|
||||
@@ -238,7 +248,7 @@ export class NavigationController {
|
||||
});
|
||||
}
|
||||
|
||||
_reassertNavigationHandoff(generation) {
|
||||
_reassertNavigationHandoff(generation, { trackingOrigin = 'tool' } = {}) {
|
||||
return reassertNavigationHandoff({
|
||||
generation,
|
||||
currentGeneration: this._navigationGeneration,
|
||||
@@ -250,7 +260,7 @@ export class NavigationController {
|
||||
// was refused by the cockpit leaves the old readout standing.
|
||||
release: () => {
|
||||
this.clearLocation();
|
||||
return this._releaseFollowCamera();
|
||||
return this._releaseFollowCamera({ trackingOrigin });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
+65
-31
@@ -1,4 +1,5 @@
|
||||
import { UiLifetime } from './uiLifetime.js';
|
||||
import { t, msg } from '../i18n/index.js';
|
||||
import { displayPanelScroller } from './displayPanelScroll.js';
|
||||
import { PanelPositionControls } from './panelPositionControls.js';
|
||||
import { PanelLayoutController } from './panelLayoutController.js';
|
||||
@@ -45,6 +46,7 @@ export class PanelChrome {
|
||||
readInitialShare,
|
||||
readScrollRestoreOwner,
|
||||
readDisplayScrollTop,
|
||||
readSharedCollapsed = () => undefined,
|
||||
}) {
|
||||
Object.assign(this, elements, operations, {
|
||||
readHud,
|
||||
@@ -53,6 +55,7 @@ export class PanelChrome {
|
||||
readInitialShare,
|
||||
readScrollRestoreOwner,
|
||||
readDisplayScrollTop,
|
||||
readSharedCollapsed,
|
||||
});
|
||||
this._disposed = false;
|
||||
this._lifetime = new UiLifetime();
|
||||
@@ -60,10 +63,7 @@ export class PanelChrome {
|
||||
this._cockpitContextCollapsedForDataPanel = false;
|
||||
this._panelPosition = new PanelPositionControls({
|
||||
syncPanelCollapseButton: (panel) => this._syncPanelCollapseButton(panel),
|
||||
layoutRightPanels: () => this._layoutRightPanels(),
|
||||
syncCctvPanelViewport: () => this._syncCctvPanelViewport(),
|
||||
showToast: (message) => this._showToast(message),
|
||||
onPanelResized: (panelId) => this._onPanelResized(panelId),
|
||||
});
|
||||
this._panelLayout = new PanelLayoutController({
|
||||
readHud: () => ({
|
||||
@@ -71,7 +71,8 @@ export class PanelChrome {
|
||||
variant: this.hud.getVariant(),
|
||||
}),
|
||||
scheduleCockpitLayout: () => this.cockpitView?.scheduleContextLayout(),
|
||||
syncPanelCollapseButton: (panel) => this._syncPanelCollapseButton(panel),
|
||||
syncPanelCollapseButton: (panel) =>
|
||||
this._syncRailPanelCollapseButton(panel),
|
||||
readDisplayScrollTop: () =>
|
||||
this._displayPortalScrollRestoreOwner === 'standard'
|
||||
? this._standardDisplayScrollTop
|
||||
@@ -147,10 +148,12 @@ export class PanelChrome {
|
||||
this._initCommandDockPins();
|
||||
this._initCommandDockTrayMetrics();
|
||||
this._maybeNotifyLayoutReset();
|
||||
this._panelPosition._initPanelDrag();
|
||||
}
|
||||
|
||||
_collapsePanelOnEscape(event, panelId) {
|
||||
// In a phone sheet, Escape closes the sheet (mobileShell.js), not a panel.
|
||||
if (globalThis.document?.body?.hasAttribute?.('data-mobile-sheet'))
|
||||
return false;
|
||||
return collapsePanelOnEscape(event, {
|
||||
panel: document.getElementById(panelId),
|
||||
onChange: (collapsed, options) =>
|
||||
@@ -252,7 +255,10 @@ export class PanelChrome {
|
||||
disclosure: panel.querySelector(`[data-dock-toggle-target="${panelId}"]`),
|
||||
openDelayMs,
|
||||
closeDelayMs,
|
||||
isActive: () => !this._disposed,
|
||||
// A phone sheet holds its trays open; the tab bar closes them.
|
||||
isActive: () =>
|
||||
!this._disposed &&
|
||||
!globalThis.document?.body?.hasAttribute?.('data-mobile-sheet'),
|
||||
onChange: (collapsed, options) =>
|
||||
this.setPanelCollapsed(panelId, collapsed, options),
|
||||
onEscape: (event) => this._collapsePanelOnEscape(event, panelId),
|
||||
@@ -286,6 +292,19 @@ export class PanelChrome {
|
||||
return this._panelLayout._scheduleLeftPanelLayout(options0);
|
||||
}
|
||||
|
||||
_syncRailPanelCollapseButton(panelEl) {
|
||||
// Adaptive rail layout may directly restore an auto-collapsed Context
|
||||
// without invoking setPanelCollapsed(). Enforce Radio ownership there too.
|
||||
if (
|
||||
panelEl?.id === 'global-context-panel' &&
|
||||
!panelEl.classList.contains('collapsed') &&
|
||||
this._contextRadioDock?.classList.contains('disclosure-open')
|
||||
) {
|
||||
this._setRadioDisclosure?.(false);
|
||||
}
|
||||
this._syncPanelCollapseButton(panelEl);
|
||||
}
|
||||
|
||||
_syncPanelCollapseButton(panelEl) {
|
||||
const isRightRail = [
|
||||
'pp-toggles',
|
||||
@@ -310,14 +329,25 @@ export class PanelChrome {
|
||||
const panelName =
|
||||
panelEl
|
||||
.querySelector('.panel-title, .pp-header-label')
|
||||
?.textContent?.trim() || 'panel';
|
||||
const action = collapsed ? 'Expand' : 'Collapse';
|
||||
btn.title = `${action} ${panelName}`;
|
||||
btn.setAttribute('aria-label', `${action} ${panelName}`);
|
||||
?.textContent?.trim() || t('panel');
|
||||
const titleKey = collapsed
|
||||
? msg('Expand {name}')
|
||||
: msg('Collapse {name}');
|
||||
btn.title = t(titleKey, { name: panelName });
|
||||
btn.setAttribute('aria-label', t(titleKey, { name: panelName }));
|
||||
if (panelEl.id === 'radio-panel') {
|
||||
const action = collapsed ? 'Expand' : 'Collapse';
|
||||
btn.title = `${action} Radio`;
|
||||
btn.setAttribute('aria-label', `${action} Radio section`);
|
||||
// Radio keeps the wording of its static button (context.html).
|
||||
btn.title = t(
|
||||
collapsed ? msg('Expand Radio') : msg('Collapse Radio'),
|
||||
);
|
||||
btn.setAttribute(
|
||||
'aria-label',
|
||||
t(
|
||||
collapsed
|
||||
? msg('Expand Radio section')
|
||||
: msg('Collapse Radio section'),
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
const dockToggle = panelEl.querySelector(
|
||||
@@ -327,11 +357,13 @@ export class PanelChrome {
|
||||
const panelName =
|
||||
panelEl
|
||||
.querySelector('.panel-title, .location-toolbar-label')
|
||||
?.textContent?.trim() || 'panel';
|
||||
const action = collapsed ? 'Expand' : 'Collapse';
|
||||
?.textContent?.trim() || t('panel');
|
||||
const titleKey = collapsed
|
||||
? msg('Expand {name}')
|
||||
: msg('Collapse {name}');
|
||||
dockToggle.setAttribute('aria-expanded', String(!collapsed));
|
||||
dockToggle.setAttribute('aria-label', `${action} ${panelName}`);
|
||||
dockToggle.title = `${action} ${panelName}`;
|
||||
dockToggle.setAttribute('aria-label', t(titleKey, { name: panelName }));
|
||||
dockToggle.title = t(titleKey, { name: panelName });
|
||||
}
|
||||
if (panelEl.id === 'radio-panel' && this._contextRadioDetailsBtn) {
|
||||
this._contextRadioDetailsBtn.setAttribute(
|
||||
@@ -356,7 +388,11 @@ export class PanelChrome {
|
||||
panelEl.classList.contains('cyber-accordion-collapsed')
|
||||
? false
|
||||
: panelEl.classList.contains('collapsed');
|
||||
const entry = { id: spec.id, collapsed };
|
||||
// A panel the phone shell only borrowed for a sheet shares its own state.
|
||||
const entry = {
|
||||
id: spec.id,
|
||||
collapsed: this.readSharedCollapsed(spec.id) ?? collapsed,
|
||||
};
|
||||
if (spec.pinnable)
|
||||
entry.pinned = panelEl.classList.contains('dock-pinned');
|
||||
specs.push(entry);
|
||||
@@ -388,11 +424,6 @@ export class PanelChrome {
|
||||
this.shareLinkManager?.onPanelStateChange?.();
|
||||
}
|
||||
|
||||
/** @returns {boolean} Whether the panel was floating and is now docked. */
|
||||
dockPanel(panelId) {
|
||||
return this._panelPosition?.dockPanel?.(panelId) === true;
|
||||
}
|
||||
|
||||
setPanelCollapsed(
|
||||
panelId,
|
||||
collapsed,
|
||||
@@ -415,20 +446,19 @@ export class PanelChrome {
|
||||
panelEl.classList.contains('cyber-accordion-collapsed');
|
||||
// A user opening a Cyber rail panel owns the whole accordion, including
|
||||
// peers that were only presentation-collapsed during a saved-state restore.
|
||||
// A floating window is outside the accordion both ways.
|
||||
if (
|
||||
explicit &&
|
||||
!restore &&
|
||||
!nextCollapsed &&
|
||||
document.documentElement?.dataset.uiTheme === 'cyber' &&
|
||||
panelEl.parentElement === this._rightPanelStack &&
|
||||
!panelEl.classList.contains('panel-floating')
|
||||
// Phone sheets show several rail panels at once.
|
||||
!document.body?.classList?.contains('mobile-shell')
|
||||
) {
|
||||
for (const peer of this._rightPanelStack.children) {
|
||||
if (
|
||||
peer !== panelEl &&
|
||||
peer.matches('[data-panel-id]') &&
|
||||
!peer.classList.contains('panel-floating') &&
|
||||
!peer.hidden
|
||||
) {
|
||||
this.setPanelCollapsed(peer.id, true, {
|
||||
@@ -487,6 +517,15 @@ export class PanelChrome {
|
||||
syncShare,
|
||||
});
|
||||
}
|
||||
// A repeated Context-open request must clear a stale compact Radio mini
|
||||
// even when no collapsed class changes.
|
||||
if (
|
||||
!nextCollapsed &&
|
||||
panelId === 'global-context-panel' &&
|
||||
this._contextRadioDock?.classList.contains('disclosure-open')
|
||||
) {
|
||||
this._setRadioDisclosure?.(false);
|
||||
}
|
||||
if (
|
||||
panelEl.classList.contains('collapsed') === nextCollapsed &&
|
||||
!wasAutoCollapsed
|
||||
@@ -556,10 +595,6 @@ export class PanelChrome {
|
||||
}
|
||||
}
|
||||
panelEl.classList.toggle('collapsed', nextCollapsed);
|
||||
// Only a user's own collapse docks a floating window; restores, cockpit
|
||||
// entry and accordion peers keep its place.
|
||||
if (explicit && !restore)
|
||||
this._panelPosition?.onPanelCollapsed?.(panelId, nextCollapsed);
|
||||
if (
|
||||
nextCollapsed &&
|
||||
this.cockpitView?.active &&
|
||||
@@ -629,7 +664,6 @@ export class PanelChrome {
|
||||
if (this._disposed) return;
|
||||
this._disposed = true;
|
||||
this._lifetime.destroy();
|
||||
this._panelPosition.destroy();
|
||||
this._panelLayout.destroy();
|
||||
for (const control of this._panelDisclosureControls || [])
|
||||
control.destroy();
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import { PanelChrome } from './panelChrome.js';
|
||||
import { PanelLayoutController } from './panelLayoutController.js';
|
||||
|
||||
function classList(initial = []) {
|
||||
const values = new Set(initial);
|
||||
return {
|
||||
contains: (value) => values.has(value),
|
||||
add: (...items) => items.forEach((item) => values.add(item)),
|
||||
remove: (...items) => items.forEach((item) => values.delete(item)),
|
||||
toggle(value, force) {
|
||||
if (force === true) values.add(value);
|
||||
else if (force === false) values.delete(value);
|
||||
else if (values.has(value)) values.delete(value);
|
||||
else values.add(value);
|
||||
return values.has(value);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('opening an already-open Context still closes a stale compact Radio disclosure', (t) => {
|
||||
const priorDocument = globalThis.document;
|
||||
const contextPanel = {
|
||||
id: 'global-context-panel',
|
||||
classList: classList(),
|
||||
};
|
||||
globalThis.document = {
|
||||
documentElement: { dataset: { uiTheme: 'tactical' } },
|
||||
getElementById(id) {
|
||||
return id === 'global-context-panel' ? contextPanel : null;
|
||||
},
|
||||
};
|
||||
t.after(() => {
|
||||
globalThis.document = priorDocument;
|
||||
});
|
||||
|
||||
const radioDock = { classList: classList(['disclosure-open']) };
|
||||
const calls = [];
|
||||
const owner = {
|
||||
_contextRadioDock: radioDock,
|
||||
_setRadioDisclosure(open) {
|
||||
calls.push(open);
|
||||
radioDock.classList.toggle('disclosure-open', open);
|
||||
},
|
||||
_leftPanelStack: null,
|
||||
_rightPanelStack: null,
|
||||
_panelLayout: {
|
||||
_leftStackPreferredPanelId: null,
|
||||
_rightStackPreferredPanelId: null,
|
||||
},
|
||||
_syncPanelCollapseButton() {},
|
||||
_scheduleLeftPanelLayout() {},
|
||||
_scheduleRightPanelLayout() {},
|
||||
shareLinkManager: null,
|
||||
cockpitView: null,
|
||||
};
|
||||
|
||||
PanelChrome.prototype.setPanelCollapsed.call(
|
||||
owner,
|
||||
'global-context-panel',
|
||||
false,
|
||||
);
|
||||
|
||||
assert.deepEqual(calls, [false]);
|
||||
assert.equal(radioDock.classList.contains('disclosure-open'), false);
|
||||
});
|
||||
|
||||
test('adaptive rail restore hides compact Radio before revealing Context', (t) => {
|
||||
const priorRaf = globalThis.requestAnimationFrame;
|
||||
let nextFrame;
|
||||
globalThis.requestAnimationFrame = (callback) => {
|
||||
nextFrame = callback;
|
||||
return 1;
|
||||
};
|
||||
t.after(() => {
|
||||
globalThis.requestAnimationFrame = priorRaf;
|
||||
});
|
||||
|
||||
// Valid starting state: the tactical rail automatically collapsed Context,
|
||||
// and the user opened the compact Radio controls from its header.
|
||||
const contextPanel = {
|
||||
id: 'global-context-panel',
|
||||
classList: classList(['collapsed', 'layout-auto-collapsed']),
|
||||
};
|
||||
const radioDock = { classList: classList(['disclosure-open']) };
|
||||
const radioMini = { hidden: false };
|
||||
const calls = [];
|
||||
const chrome = {
|
||||
_contextRadioDock: radioDock,
|
||||
_setRadioDisclosure(open) {
|
||||
calls.push(`disclosure:${open}`);
|
||||
radioDock.classList.toggle('disclosure-open', open);
|
||||
radioMini.hidden = !open;
|
||||
},
|
||||
_syncPanelCollapseButton(panel) {
|
||||
calls.push(`button:${panel.id}`);
|
||||
},
|
||||
};
|
||||
const layout = {
|
||||
destroyed: false,
|
||||
_rightStackLayoutFrame: null,
|
||||
_rightStackReconsiderAutoCollapse: false,
|
||||
_rightPanelStack: {
|
||||
querySelectorAll: (selector) =>
|
||||
selector === '.layout-auto-collapsed' ? [contextPanel] : [],
|
||||
},
|
||||
_syncPanelCollapseButton(panel) {
|
||||
PanelChrome.prototype._syncRailPanelCollapseButton.call(chrome, panel);
|
||||
},
|
||||
_syncRightPanelAdaptiveLayout() {
|
||||
calls.push('layout');
|
||||
},
|
||||
};
|
||||
|
||||
PanelLayoutController.prototype._scheduleRightPanelLayout.call(layout, {
|
||||
reconsiderAutoCollapse: true,
|
||||
});
|
||||
assert.equal(contextPanel.classList.contains('collapsed'), true);
|
||||
assert.equal(radioMini.hidden, false);
|
||||
nextFrame();
|
||||
|
||||
assert.equal(contextPanel.classList.contains('collapsed'), false);
|
||||
assert.equal(contextPanel.classList.contains('layout-auto-collapsed'), false);
|
||||
assert.equal(radioDock.classList.contains('disclosure-open'), false);
|
||||
assert.equal(radioMini.hidden, true);
|
||||
assert.deepEqual(calls, [
|
||||
'disclosure:false',
|
||||
'button:global-context-panel',
|
||||
'layout',
|
||||
]);
|
||||
});
|
||||
|
||||
test('real PanelChrome constructor wires rail restore to compact Radio owner', (t) => {
|
||||
const priorDocument = globalThis.document;
|
||||
const priorRaf = globalThis.requestAnimationFrame;
|
||||
let nextFrame;
|
||||
const contextPanel = {
|
||||
id: 'global-context-panel',
|
||||
classList: classList(['collapsed', 'layout-auto-collapsed']),
|
||||
};
|
||||
const rightRail = {
|
||||
querySelectorAll(selector) {
|
||||
return selector === '.layout-auto-collapsed' ? [contextPanel] : [];
|
||||
},
|
||||
};
|
||||
globalThis.document = {
|
||||
getElementById(id) {
|
||||
return id === 'right-context-rail' ? rightRail : null;
|
||||
},
|
||||
};
|
||||
globalThis.requestAnimationFrame = (callback) => {
|
||||
nextFrame = callback;
|
||||
return 1;
|
||||
};
|
||||
t.after(() => {
|
||||
globalThis.document = priorDocument;
|
||||
globalThis.requestAnimationFrame = priorRaf;
|
||||
});
|
||||
|
||||
const dock = { classList: classList(['disclosure-open']) };
|
||||
const calls = [];
|
||||
const chrome = new PanelChrome({
|
||||
elements: { _contextRadioDock: dock },
|
||||
operations: {
|
||||
_setRadioDisclosure(open) {
|
||||
calls.push(`disclosure:${open}`);
|
||||
dock.classList.toggle('disclosure-open', open);
|
||||
},
|
||||
_syncPanelCollapseButton(panel) {
|
||||
calls.push(`button:${panel.id}`);
|
||||
},
|
||||
},
|
||||
readHud: () => ({ visible: true, getVariant: () => 'tactical' }),
|
||||
readCockpit: () => null,
|
||||
readShareLinks: () => null,
|
||||
readInitialShare: () => null,
|
||||
readScrollRestoreOwner: () => null,
|
||||
readDisplayScrollTop: () => 0,
|
||||
});
|
||||
chrome._panelLayout._syncRightPanelAdaptiveLayout = () => {
|
||||
calls.push('layout');
|
||||
};
|
||||
|
||||
chrome._panelLayout._scheduleRightPanelLayout({
|
||||
reconsiderAutoCollapse: true,
|
||||
});
|
||||
assert.equal(typeof nextFrame, 'function');
|
||||
assert.equal(dock.classList.contains('disclosure-open'), true);
|
||||
nextFrame();
|
||||
|
||||
assert.equal(contextPanel.classList.contains('collapsed'), false);
|
||||
assert.equal(dock.classList.contains('disclosure-open'), false);
|
||||
assert.deepEqual(calls, [
|
||||
'disclosure:false',
|
||||
'button:global-context-panel',
|
||||
'layout',
|
||||
]);
|
||||
});
|
||||
@@ -1,580 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { PanelPositionControls } from './panelPositionControls.js';
|
||||
|
||||
/** Just enough DOM for PanelPositionControls' portable-panel paths. */
|
||||
function fixture() {
|
||||
const saved = Object.fromEntries(
|
||||
['document', 'window', 'localStorage', 'performance', 'ResizeObserver'].map(
|
||||
(key) => [key, globalThis[key]],
|
||||
),
|
||||
);
|
||||
const store = new Map();
|
||||
const element = () => {
|
||||
const classes = new Set();
|
||||
const style = {
|
||||
removeProperty(name) {
|
||||
// Like CSSStyleDeclaration: 'z-index' also clears style.zIndex.
|
||||
delete this[name];
|
||||
delete this[name.replace(/-([a-z])/g, (_, c) => c.toUpperCase())];
|
||||
},
|
||||
getPropertyValue: () => '',
|
||||
};
|
||||
return Object.assign(new EventTarget(), {
|
||||
id: '',
|
||||
style,
|
||||
dataset: {},
|
||||
classList: {
|
||||
add: (...names) => names.forEach((name) => classes.add(name)),
|
||||
remove: (...names) => names.forEach((name) => classes.delete(name)),
|
||||
contains: (name) => classes.has(name),
|
||||
toggle: (name, on) => (on ? classes.add(name) : classes.delete(name)),
|
||||
},
|
||||
querySelector: () => null,
|
||||
querySelectorAll: () => [],
|
||||
closest: () => null,
|
||||
setAttribute() {},
|
||||
removeAttribute() {},
|
||||
appendChild() {},
|
||||
remove() {},
|
||||
getBoundingClientRect: () => ({
|
||||
left: 100,
|
||||
top: 80,
|
||||
width: 360,
|
||||
height: 420,
|
||||
right: 460,
|
||||
bottom: 500,
|
||||
}),
|
||||
});
|
||||
};
|
||||
globalThis.document = Object.assign(new EventTarget(), {
|
||||
getElementById: () => null,
|
||||
querySelectorAll: () => [],
|
||||
createElement: () => element(),
|
||||
});
|
||||
globalThis.window = Object.assign(new EventTarget(), {
|
||||
innerWidth: 1440,
|
||||
innerHeight: 900,
|
||||
});
|
||||
globalThis.localStorage = {
|
||||
getItem: (key) => (store.has(key) ? store.get(key) : null),
|
||||
setItem: (key, value) => store.set(key, String(value)),
|
||||
removeItem: (key) => store.delete(key),
|
||||
};
|
||||
const calls = { layout: 0, resized: [] };
|
||||
const owner = new PanelPositionControls({
|
||||
syncPanelCollapseButton() {},
|
||||
layoutRightPanels: () => calls.layout++,
|
||||
syncCctvPanelViewport() {},
|
||||
showToast() {},
|
||||
onPanelResized: (id) => calls.resized.push(id),
|
||||
});
|
||||
return {
|
||||
owner,
|
||||
element,
|
||||
store,
|
||||
calls,
|
||||
restore() {
|
||||
owner.destroy();
|
||||
Object.assign(globalThis, saved);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function floatingPanel(f, id, { dockOnCollapse = false } = {}) {
|
||||
const panel = f.element();
|
||||
const handle = f.element();
|
||||
panel.id = id;
|
||||
panel.classList.add('panel-floating', 'panel-draggable');
|
||||
Object.assign(panel.style, {
|
||||
left: '100px',
|
||||
top: '80px',
|
||||
width: '360px',
|
||||
height: '420px',
|
||||
});
|
||||
f.store.set(`godsEyeView.v8.panelPos.${id}`, '{"floating":true}');
|
||||
f.owner._portablePanels.set(id, {
|
||||
panel,
|
||||
min: { width: 320, height: 280 },
|
||||
dockOnCollapse,
|
||||
});
|
||||
f.owner._makePanelDraggable(id, panel, handle);
|
||||
return { panel, handle };
|
||||
}
|
||||
|
||||
/** A left-button header press; `timeStamp` is a read-only getter on Event. */
|
||||
function press(handle, { timeStamp, clientX = 200, clientY = 90 }) {
|
||||
const event = new Event('pointerdown', { cancelable: true });
|
||||
for (const [key, value] of Object.entries({
|
||||
button: 0,
|
||||
clientX,
|
||||
clientY,
|
||||
timeStamp,
|
||||
}))
|
||||
Object.defineProperty(event, key, { value });
|
||||
handle.dispatchEvent(event);
|
||||
}
|
||||
|
||||
test('dockPanel returns a floating window to its rail and forgets its place', () => {
|
||||
const f = fixture();
|
||||
try {
|
||||
const { panel } = floatingPanel(f, 'street-level-panel');
|
||||
assert.equal(f.owner.dockPanel('street-level-panel'), true);
|
||||
assert.equal(panel.classList.contains('panel-floating'), false);
|
||||
assert.equal(panel.style.width, undefined);
|
||||
assert.equal(panel.style.height, undefined);
|
||||
assert.equal(
|
||||
f.store.has('godsEyeView.v8.panelPos.street-level-panel'),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(f.calls.resized, ['street-level-panel']);
|
||||
assert.equal(
|
||||
f.owner.dockPanel('street-level-panel'),
|
||||
false,
|
||||
'already docked',
|
||||
);
|
||||
assert.equal(f.owner.dockPanel('unknown'), false);
|
||||
} finally {
|
||||
f.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('only a dockOnCollapse panel docks when collapsed, and only on collapse', () => {
|
||||
const f = fixture();
|
||||
try {
|
||||
const street = floatingPanel(f, 'street-level-panel', {
|
||||
dockOnCollapse: true,
|
||||
});
|
||||
const cctv = floatingPanel(f, 'cctv-panel');
|
||||
f.owner.onPanelCollapsed('street-level-panel', false);
|
||||
assert.equal(
|
||||
street.panel.classList.contains('panel-floating'),
|
||||
true,
|
||||
'expanding keeps it',
|
||||
);
|
||||
f.owner.onPanelCollapsed('cctv-panel', true);
|
||||
assert.equal(
|
||||
cctv.panel.classList.contains('panel-floating'),
|
||||
true,
|
||||
'CCTV did not opt in',
|
||||
);
|
||||
f.owner.onPanelCollapsed('street-level-panel', true);
|
||||
assert.equal(street.panel.classList.contains('panel-floating'), false);
|
||||
} finally {
|
||||
f.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('two quick header presses snap a floating panel back; slow or distant ones do not', () => {
|
||||
const f = fixture();
|
||||
try {
|
||||
const { panel, handle } = floatingPanel(f, 'cctv-panel');
|
||||
press(handle, { timeStamp: 1000 });
|
||||
window.dispatchEvent(new Event('pointerup'));
|
||||
press(handle, { timeStamp: 1600 });
|
||||
window.dispatchEvent(new Event('pointerup'));
|
||||
assert.equal(
|
||||
panel.classList.contains('panel-floating'),
|
||||
true,
|
||||
'600 ms apart is two clicks',
|
||||
);
|
||||
press(handle, { timeStamp: 1700, clientX: 260 });
|
||||
window.dispatchEvent(new Event('pointerup'));
|
||||
assert.equal(
|
||||
panel.classList.contains('panel-floating'),
|
||||
true,
|
||||
'60 px apart is two clicks',
|
||||
);
|
||||
press(handle, { timeStamp: 1900, clientX: 262 });
|
||||
assert.equal(
|
||||
panel.classList.contains('panel-floating'),
|
||||
false,
|
||||
'a double press docks',
|
||||
);
|
||||
} finally {
|
||||
f.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('a restored floating window stacks above the docked DISPLAY panel (z 110)', () => {
|
||||
const f = fixture();
|
||||
try {
|
||||
const panel = f.element();
|
||||
panel.id = 'street-level-panel';
|
||||
f.owner._portablePanels.set('street-level-panel', {
|
||||
panel,
|
||||
min: { width: 320, height: 280 },
|
||||
dockOnCollapse: true,
|
||||
});
|
||||
f.store.set(
|
||||
'godsEyeView.v8.panelPos.street-level-panel',
|
||||
JSON.stringify({
|
||||
left: 900,
|
||||
top: 200,
|
||||
width: 420,
|
||||
height: 600,
|
||||
floating: true,
|
||||
}),
|
||||
);
|
||||
f.owner._restorePanelPosition('street-level-panel', panel);
|
||||
assert.equal(panel.classList.contains('panel-floating'), true);
|
||||
assert.ok(Number(panel.style.zIndex) > 110, `z ${panel.style.zIndex}`);
|
||||
f.owner.dockPanel('street-level-panel');
|
||||
assert.equal(panel.style.zIndex, undefined, 'docking drops the promotion');
|
||||
} finally {
|
||||
f.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('renumbering the z ladder never drops a window below the docked panels', () => {
|
||||
const f = fixture();
|
||||
try {
|
||||
const windows = [f.element(), f.element(), f.element()];
|
||||
windows.forEach((node, index) => {
|
||||
node.classList.add('panel-draggable');
|
||||
node.style.zIndex = String(130 + index);
|
||||
});
|
||||
globalThis.document.querySelectorAll = (selector) =>
|
||||
selector === '.panel-draggable' ? windows : [];
|
||||
f.owner._panelZCounter = 139;
|
||||
const top = f.element();
|
||||
top.classList.add('panel-draggable');
|
||||
f.owner._promotePanelZ(top);
|
||||
for (const node of [...windows, top])
|
||||
assert.ok(Number(node.style.zIndex) > 110, `z ${node.style.zIndex}`);
|
||||
assert.ok(Number(top.style.zIndex) > Number(windows[2].style.zIndex));
|
||||
} finally {
|
||||
f.restore();
|
||||
}
|
||||
});
|
||||
|
||||
/** A portable panel still in its rail, with its header and resize handles. */
|
||||
function dockedPanel(f, id) {
|
||||
const panel = f.element();
|
||||
const handle = f.element();
|
||||
panel.id = id;
|
||||
const portable = { panel, min: { width: 320, height: 280 } };
|
||||
f.owner._portablePanels.set(id, portable);
|
||||
f.owner._makePanelDraggable(id, panel, handle);
|
||||
f.owner._makePanelResizable(id, panel, portable.min);
|
||||
const edges = Object.fromEntries(
|
||||
f.owner._resizeHandles.map((node) => [node.dataset.dir, node]),
|
||||
);
|
||||
return { panel, handle, edges };
|
||||
}
|
||||
|
||||
/** A pointer event; `pointerType` defaults to what a mouse reports. */
|
||||
function pointer(target, type, { x = 200, y = 90, pointerType = 'mouse' }) {
|
||||
const event = new Event(type, { cancelable: true });
|
||||
for (const [key, value] of Object.entries({
|
||||
button: 0,
|
||||
clientX: x,
|
||||
clientY: y,
|
||||
pointerType,
|
||||
}))
|
||||
Object.defineProperty(event, key, { value });
|
||||
target.dispatchEvent(event);
|
||||
return event;
|
||||
}
|
||||
|
||||
const POSITION_KEY = 'godsEyeView.v8.panelPos.street-level-panel';
|
||||
|
||||
test('a click on a docked panel’s resize edge leaves it docked and stores nothing', () => {
|
||||
const f = fixture();
|
||||
try {
|
||||
const { panel, edges } = dockedPanel(f, 'street-level-panel');
|
||||
pointer(edges.w, 'pointerdown', { x: 101, y: 200 });
|
||||
pointer(window, 'pointermove', { x: 103, y: 201 }); // a jittery click
|
||||
pointer(window, 'pointerup', { x: 103, y: 201 });
|
||||
assert.equal(panel.classList.contains('panel-floating'), false);
|
||||
assert.equal(panel.style.width, undefined, 'no size was pinned');
|
||||
assert.equal(f.store.has(POSITION_KEY), false);
|
||||
assert.deepEqual(f.calls.resized, []);
|
||||
|
||||
// A real resize still lifts it out and remembers the window.
|
||||
pointer(edges.w, 'pointerdown', { x: 101, y: 200 });
|
||||
pointer(window, 'pointermove', { x: 61, y: 200 });
|
||||
pointer(window, 'pointerup', { x: 61, y: 200 });
|
||||
assert.equal(panel.classList.contains('panel-floating'), true);
|
||||
assert.equal(JSON.parse(f.store.get(POSITION_KEY)).floating, true);
|
||||
} finally {
|
||||
f.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('a touch on the header or an edge does not lift the panel, and the rail can still scroll', () => {
|
||||
const f = fixture();
|
||||
try {
|
||||
const { panel, handle, edges } = dockedPanel(f, 'street-level-panel');
|
||||
const press = pointer(handle, 'pointerdown', { pointerType: 'touch' });
|
||||
assert.equal(press.defaultPrevented, false, 'the swipe can scroll');
|
||||
pointer(window, 'pointermove', { y: 190, pointerType: 'touch' });
|
||||
pointer(window, 'pointerup', { y: 190, pointerType: 'touch' });
|
||||
pointer(edges.s, 'pointerdown', { y: 500, pointerType: 'touch' });
|
||||
pointer(window, 'pointermove', { y: 600, pointerType: 'touch' });
|
||||
pointer(window, 'pointerup', { y: 600, pointerType: 'touch' });
|
||||
assert.equal(panel.classList.contains('panel-floating'), false);
|
||||
assert.equal(f.store.has(POSITION_KEY), false);
|
||||
} finally {
|
||||
f.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('a pointercancel mid-drag saves nothing and puts the panel back', () => {
|
||||
const f = fixture();
|
||||
try {
|
||||
const { panel, handle, edges } = dockedPanel(f, 'street-level-panel');
|
||||
pointer(handle, 'pointerdown', {});
|
||||
pointer(window, 'pointermove', { x: 260, y: 140 });
|
||||
assert.equal(panel.classList.contains('panel-floating'), true, 'lifted');
|
||||
pointer(window, 'pointercancel', { x: 260, y: 140 });
|
||||
assert.equal(panel.classList.contains('panel-floating'), false, 'docked');
|
||||
assert.equal(f.store.has(POSITION_KEY), false);
|
||||
|
||||
pointer(edges.e, 'pointerdown', { x: 459 });
|
||||
pointer(window, 'pointermove', { x: 520 });
|
||||
pointer(window, 'pointercancel', { x: 520 });
|
||||
assert.equal(panel.classList.contains('panel-floating'), false);
|
||||
assert.equal(f.store.has(POSITION_KEY), false);
|
||||
} finally {
|
||||
f.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('a pointercancel while dragging a floating window returns it to where it was', () => {
|
||||
const f = fixture();
|
||||
try {
|
||||
const { panel, handle } = floatingPanel(f, 'cctv-panel');
|
||||
const stored = f.store.get('godsEyeView.v8.panelPos.cctv-panel');
|
||||
pointer(handle, 'pointerdown', {});
|
||||
pointer(window, 'pointermove', { x: 400, y: 300 });
|
||||
assert.notEqual(panel.style.left, '100px', 'it moved');
|
||||
pointer(window, 'pointercancel', { x: 400, y: 300 });
|
||||
assert.equal(panel.style.left, '100px');
|
||||
assert.equal(panel.style.top, '80px');
|
||||
assert.equal(panel.classList.contains('panel-floating'), true);
|
||||
assert.equal(f.store.get('godsEyeView.v8.panelPos.cctv-panel'), stored);
|
||||
} finally {
|
||||
f.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('a header press that travels under the drag threshold is a click, not a lift', () => {
|
||||
const f = fixture();
|
||||
try {
|
||||
const { panel, handle } = dockedPanel(f, 'street-level-panel');
|
||||
pointer(handle, 'pointerdown', { x: 200, y: 90 });
|
||||
pointer(window, 'pointermove', { x: 202, y: 90 });
|
||||
pointer(window, 'pointerup', { x: 202, y: 90 });
|
||||
assert.equal(panel.classList.contains('panel-floating'), false);
|
||||
assert.equal(panel.classList.contains('panel-dragging'), false);
|
||||
assert.equal(f.store.has(POSITION_KEY), false);
|
||||
assert.equal(f.calls.layout, 0, 'the rail was not re-laid out');
|
||||
assert.deepEqual(f.calls.resized, []);
|
||||
} finally {
|
||||
f.restore();
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Both portable panels wired through _initPanelDrag. Headers are the top
|
||||
* 36 px; `obstacles` stand in for the command dock and voice pill.
|
||||
* ResizeObserver callbacks run on `observe()`.
|
||||
*/
|
||||
function portableShell(f, { stored = {}, box = {}, obstacles = {} } = {}) {
|
||||
const observers = [];
|
||||
globalThis.ResizeObserver = class {
|
||||
constructor(callback) {
|
||||
this.callback = callback;
|
||||
this.targets = [];
|
||||
observers.push(this);
|
||||
}
|
||||
observe(target) {
|
||||
this.targets.push(target);
|
||||
}
|
||||
disconnect() {}
|
||||
};
|
||||
const nodes = new Map();
|
||||
const panels = {};
|
||||
for (const id of ['cctv-panel', 'street-level-panel']) {
|
||||
const panel = f.element();
|
||||
const handle = f.element();
|
||||
const natural = { width: 360, height: 420, ...box[id] };
|
||||
panel.id = id;
|
||||
panel.querySelector = (selector) =>
|
||||
selector === '.panel-header' ? handle : null;
|
||||
panel.getBoundingClientRect = () => {
|
||||
const left = parseFloat(panel.style.left) || 0;
|
||||
const top = parseFloat(panel.style.top) || 0;
|
||||
const width = parseFloat(panel.style.width) || natural.width;
|
||||
const height = parseFloat(panel.style.height) || natural.height;
|
||||
return {
|
||||
left,
|
||||
top,
|
||||
width,
|
||||
height,
|
||||
right: left + width,
|
||||
bottom: top + height,
|
||||
};
|
||||
};
|
||||
handle.getBoundingClientRect = () => {
|
||||
const rect = panel.getBoundingClientRect();
|
||||
return { ...rect, height: 36, bottom: rect.top + 36 };
|
||||
};
|
||||
if (stored[id])
|
||||
f.store.set(
|
||||
`godsEyeView.v8.panelPos.${id}`,
|
||||
JSON.stringify({ floating: true, ...stored[id] }),
|
||||
);
|
||||
nodes.set(id, panel);
|
||||
panels[id] = { panel, handle, natural };
|
||||
}
|
||||
const obstacle = (id, rect) =>
|
||||
nodes.set(id, {
|
||||
getBoundingClientRect: () => ({
|
||||
...rect,
|
||||
width: rect.right - rect.left,
|
||||
height: rect.bottom - rect.top,
|
||||
}),
|
||||
});
|
||||
for (const [id, rect] of Object.entries(obstacles)) obstacle(id, rect);
|
||||
globalThis.document.getElementById = (id) => nodes.get(id) ?? null;
|
||||
f.owner._initPanelDrag();
|
||||
return {
|
||||
...panels,
|
||||
obstacle,
|
||||
observed: (node) => observers.some(({ targets }) => targets.includes(node)),
|
||||
contentResized: () => observers.forEach(({ callback }) => callback([])),
|
||||
};
|
||||
}
|
||||
|
||||
test('a floating window whose content grows is pulled back on-screen', () => {
|
||||
const f = fixture();
|
||||
try {
|
||||
const shell = portableShell(f, {
|
||||
stored: { 'cctv-panel': { left: 900, top: 380 } },
|
||||
});
|
||||
const { panel, natural } = shell['cctv-panel'];
|
||||
assert.equal(panel.style.top, '380px');
|
||||
assert.equal(shell.observed(panel), true, 'its size is watched');
|
||||
assert.equal(shell.observed(shell['street-level-panel'].panel), true);
|
||||
// Expanding the collapsed strip, or an image opening in Street Level.
|
||||
natural.height = 800;
|
||||
shell.contentResized();
|
||||
assert.equal(panel.style.top, `${900 - 800 - 6}px`);
|
||||
assert.equal(panel.style.left, '900px');
|
||||
} finally {
|
||||
f.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('a live window resize shrinks a floating window larger than the viewport', () => {
|
||||
const f = fixture();
|
||||
try {
|
||||
const shell = portableShell(f, {
|
||||
stored: {
|
||||
'cctv-panel': { left: 100, top: 80, width: 1300, height: 700 },
|
||||
},
|
||||
});
|
||||
const { panel } = shell['cctv-panel'];
|
||||
assert.equal(panel.style.width, '1300px');
|
||||
Object.assign(window, { innerWidth: 1000, innerHeight: 500 });
|
||||
window.dispatchEvent(new Event('resize'));
|
||||
assert.equal(panel.style.width, '988px');
|
||||
assert.equal(panel.style.height, '488px');
|
||||
assert.equal(panel.style.left, '6px');
|
||||
assert.equal(panel.style.top, '6px');
|
||||
// A window that already fits keeps the size the user gave it.
|
||||
Object.assign(window, { innerWidth: 1440, innerHeight: 900 });
|
||||
window.dispatchEvent(new Event('resize'));
|
||||
assert.equal(panel.style.width, '988px');
|
||||
} finally {
|
||||
f.restore();
|
||||
}
|
||||
});
|
||||
|
||||
const DOCK = { left: 300, top: 820, right: 1140, bottom: 882 };
|
||||
|
||||
test('a floating header never lands under the command dock or voice pill', () => {
|
||||
const f = fixture();
|
||||
try {
|
||||
const shell = portableShell(f, {
|
||||
stored: { 'cctv-panel': { left: 100, top: 80 } },
|
||||
// A collapsed CCTV window is just its header strip.
|
||||
box: { 'cctv-panel': { height: 36 } },
|
||||
obstacles: { 'command-dock': DOCK },
|
||||
});
|
||||
const { panel, handle, natural } = shell['cctv-panel'];
|
||||
const above = DOCK.top - 36 - 6;
|
||||
|
||||
// Drag: the strip dropped at the bottom centre stops above the dock.
|
||||
pointer(handle, 'pointerdown', { x: 200, y: 90 });
|
||||
pointer(window, 'pointermove', { x: 720, y: 880 });
|
||||
assert.equal(panel.style.top, `${above}px`);
|
||||
pointer(window, 'pointerup', { x: 720, y: 880 });
|
||||
const key = 'godsEyeView.v8.panelPos.cctv-panel';
|
||||
assert.equal(JSON.parse(f.store.get(key)).top, above);
|
||||
|
||||
// Restore: a place saved under the dock (older build) comes back clear.
|
||||
f.store.set(key, JSON.stringify({ left: 620, top: 858, floating: true }));
|
||||
f.owner._restorePanelPosition('cctv-panel', panel);
|
||||
assert.equal(panel.style.top, `${above}px`);
|
||||
|
||||
// Re-clamp: the voice pill measured when the window resizes.
|
||||
Object.assign(panel.style, { left: '1000px', top: '700px' });
|
||||
shell.obstacle('gev-voice-control', {
|
||||
left: 1190,
|
||||
top: 690,
|
||||
right: 1404,
|
||||
bottom: 740,
|
||||
});
|
||||
window.dispatchEvent(new Event('resize'));
|
||||
assert.equal(panel.style.top, `${690 - 36 - 6}px`);
|
||||
|
||||
// Only the header has to stay clear: a body over the dock is fine.
|
||||
natural.height = 200;
|
||||
Object.assign(panel.style, { left: '620px', top: '650px' });
|
||||
window.dispatchEvent(new Event('resize'));
|
||||
assert.equal(panel.style.top, '650px');
|
||||
} finally {
|
||||
f.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('a collapsed floating window keeps its chosen height through a drag and a reload', () => {
|
||||
const f = fixture();
|
||||
try {
|
||||
const { panel, handle } = floatingPanel(f, 'cctv-panel');
|
||||
panel.style.height = '500px';
|
||||
panel.classList.add('collapsed');
|
||||
// Collapsed, the window measures only its header strip.
|
||||
panel.getBoundingClientRect = () => {
|
||||
const left = parseFloat(panel.style.left);
|
||||
const top = parseFloat(panel.style.top);
|
||||
return {
|
||||
left,
|
||||
top,
|
||||
width: 360,
|
||||
height: 50,
|
||||
right: left + 360,
|
||||
bottom: top + 50,
|
||||
};
|
||||
};
|
||||
pointer(handle, 'pointerdown', { x: 200, y: 90 });
|
||||
pointer(window, 'pointermove', { x: 260, y: 140 });
|
||||
pointer(window, 'pointerup', { x: 260, y: 140 });
|
||||
const record = JSON.parse(
|
||||
f.store.get('godsEyeView.v8.panelPos.cctv-panel'),
|
||||
);
|
||||
assert.equal(record.height, 500, 'the chosen height, not the strip');
|
||||
assert.equal(record.width, 360);
|
||||
|
||||
// Reload: a fresh panel restores the size it expands to.
|
||||
const reloaded = f.element();
|
||||
reloaded.id = 'cctv-panel';
|
||||
f.owner._restorePanelPosition('cctv-panel', reloaded);
|
||||
assert.equal(reloaded.style.height, '500px');
|
||||
} finally {
|
||||
f.restore();
|
||||
}
|
||||
});
|
||||
@@ -189,13 +189,6 @@ export class PanelLayoutController {
|
||||
const stack = this._rightPanelStack;
|
||||
if (!stack || !this._ppToggles) return;
|
||||
|
||||
this._ppToggles.style.removeProperty('top');
|
||||
this._ppToggles.style.removeProperty('right');
|
||||
this._ppToggles.style.removeProperty('bottom');
|
||||
this._ppToggles.style.removeProperty('left');
|
||||
this._ppToggles.style.removeProperty('z-index');
|
||||
this._ppToggles.classList.remove('panel-draggable', 'panel-dragging');
|
||||
this._ppToggles.querySelector('.pp-header-row')?.removeAttribute('title');
|
||||
stack.prepend(this._ppToggles);
|
||||
const globalContextPanel = document.getElementById('global-context-panel');
|
||||
for (const panel of [
|
||||
@@ -205,12 +198,6 @@ export class PanelLayoutController {
|
||||
this._streetLevelPanel,
|
||||
]) {
|
||||
if (!panel) continue;
|
||||
// A floating window keeps its restored place and size.
|
||||
if (!panel.classList.contains('panel-floating')) {
|
||||
for (const property of ['top', 'right', 'bottom', 'left', 'z-index'])
|
||||
panel.style.removeProperty(property);
|
||||
panel.classList.remove('panel-draggable', 'panel-dragging');
|
||||
}
|
||||
stack.insertBefore(panel, globalContextPanel);
|
||||
this._syncPanelCollapseButton(panel);
|
||||
}
|
||||
|
||||
+19
-761
@@ -1,217 +1,26 @@
|
||||
/** Own panel position preferences, viewport clamping and drag listeners. */
|
||||
import { RESIZE_DIRECTIONS, resizeBox } from './panelResize.js';
|
||||
|
||||
/** Own panel collapsed-state preferences and the one-time layout-reset notice. */
|
||||
import { t } from '../i18n/index.js';
|
||||
/** Versioned localStorage namespace prefix to invalidate stale panel layouts. */
|
||||
const PANEL_LAYOUT_STORAGE_VERSION = 'v6';
|
||||
/**
|
||||
* Position keys are versioned separately from collapsed-state keys so layout
|
||||
* default changes (e.g. right-rail origin) can reset positions without also
|
||||
* resetting every panel's open/closed preference.
|
||||
* Position keys are versioned separately from collapsed-state keys. The rails
|
||||
* now lay panels out themselves and store no position; the version still names
|
||||
* the layout-reset notice and the documented key.
|
||||
*/
|
||||
const PANEL_POSITION_STORAGE_VERSION = 'v8';
|
||||
/** Z ladder: panels promote within [100, 139]; voice pill 150, toast 200, clean-view-exit 300. */
|
||||
const PANEL_Z_BASE = 100;
|
||||
const PANEL_Z_MAX = 139;
|
||||
/**
|
||||
* Lowest z for a promoted panel: above every docked rail panel (#pp-toggles is
|
||||
* 110). Keep in step with `#right-context-rail > .panel-floating` in controls.css.
|
||||
*/
|
||||
const PANEL_Z_FLOATING_FLOOR = PANEL_Z_BASE + 11;
|
||||
/** Pointer travel before a press becomes a drag or resize. */
|
||||
const DRAG_THRESHOLD_PX = 4;
|
||||
/**
|
||||
* Double press that snaps a floating panel back. Detected from pointerdown
|
||||
* because the drag's preventDefault() suppresses a native dblclick.
|
||||
*/
|
||||
const DOUBLE_PRESS_MS = 400;
|
||||
const DOUBLE_PRESS_SLOP_PX = 6;
|
||||
const VIEWPORT_MARGIN_PX = 6;
|
||||
/**
|
||||
* Fixed chrome that paints over the rail's stacking context; a floating
|
||||
* window keeps its header clear of it so it can always be grabbed again.
|
||||
*/
|
||||
const PANEL_OBSTACLE_IDS = ['command-dock', 'gev-voice-control'];
|
||||
const PANEL_FLOAT_HINT_STORAGE_KEY = `godsEyeView.${PANEL_POSITION_STORAGE_VERSION}.panelFloatHintShown`;
|
||||
const PANEL_FLOAT_HINT = 'Double-click the header to snap the panel back';
|
||||
/** Header children whose own interaction wins over a drag or a snap-back. */
|
||||
const INTERACTIVE_SELECTOR =
|
||||
'input, select, option, textarea, button, a, [role="button"]';
|
||||
const FLOATING_STYLE_PROPERTIES = [
|
||||
'left',
|
||||
'top',
|
||||
'right',
|
||||
'bottom',
|
||||
'width',
|
||||
'height',
|
||||
'z-index',
|
||||
/** Floating panels' stored positions and hint flag: nothing reads them now. */
|
||||
const RETIRED_PANEL_KEY_PREFIXES = [
|
||||
`godsEyeView.${PANEL_POSITION_STORAGE_VERSION}.panelPos.`,
|
||||
`godsEyeView.${PANEL_POSITION_STORAGE_VERSION}.panelFloatHintShown`,
|
||||
];
|
||||
|
||||
function clamp(value, min, max) {
|
||||
return Math.max(min, Math.min(max, value));
|
||||
}
|
||||
|
||||
function fitWindowExtent(value, minimum, viewportExtent) {
|
||||
return clamp(
|
||||
Math.round(value),
|
||||
minimum,
|
||||
Math.max(minimum, viewportExtent - 2 * VIEWPORT_MARGIN_PX),
|
||||
);
|
||||
}
|
||||
|
||||
function placeAt(panelEl, left, top) {
|
||||
panelEl.style.left = `${left}px`;
|
||||
panelEl.style.top = `${top}px`;
|
||||
panelEl.style.right = 'auto';
|
||||
panelEl.style.bottom = 'auto';
|
||||
}
|
||||
|
||||
/** On a phone the rail scrolls, so a finger on a header is a swipe, not a drag. */
|
||||
function isPrecisePointer(event) {
|
||||
const pointerType = event.pointerType || 'mouse';
|
||||
return pointerType === 'mouse' || pointerType === 'pen';
|
||||
}
|
||||
|
||||
function geometryOf(panelEl) {
|
||||
const { left, top, width, height } = panelEl.style;
|
||||
return { left, top, width, height };
|
||||
}
|
||||
|
||||
export class PanelPositionControls {
|
||||
/** `onPanelResized(panelId)` runs after a portable panel moves, resizes or docks. */
|
||||
constructor({
|
||||
syncPanelCollapseButton,
|
||||
layoutRightPanels,
|
||||
syncCctvPanelViewport,
|
||||
showToast,
|
||||
onPanelResized = null,
|
||||
}) {
|
||||
constructor({ syncPanelCollapseButton, showToast }) {
|
||||
this._syncPanelCollapseButton = syncPanelCollapseButton;
|
||||
this._layoutRightPanels = layoutRightPanels;
|
||||
this._syncCctvPanelViewport = syncCctvPanelViewport;
|
||||
this._showToast = showToast;
|
||||
this._onPanelResized = onPanelResized;
|
||||
this._ppToggles = document.getElementById('pp-toggles');
|
||||
this._panelZCounter = PANEL_Z_BASE + 10;
|
||||
this._draggableResizeObserver = null;
|
||||
this._cancelDrag = null;
|
||||
this._portablePanels = new Map();
|
||||
this._resizeHandles = [];
|
||||
this._dragInitialized = false;
|
||||
this.removers = [];
|
||||
this.destroyed = false;
|
||||
}
|
||||
listen(target, type, callback, options) {
|
||||
if (this.destroyed || !target) return;
|
||||
const listener = (event) => {
|
||||
if (!this.destroyed) callback(event);
|
||||
};
|
||||
target.addEventListener(type, listener, options);
|
||||
this.removers.push(() =>
|
||||
target.removeEventListener(type, listener, options),
|
||||
);
|
||||
}
|
||||
_reclampDraggablePanels() {
|
||||
if (this.destroyed) return;
|
||||
const el = this._ppToggles;
|
||||
if (el && el.style.top && el.style.top !== 'auto') {
|
||||
const top = parseInt(el.style.top, 10);
|
||||
if (Number.isFinite(top)) {
|
||||
el.style.top = `${this._clampToViewport(0, top, el).top}px`;
|
||||
this._pinPanelToRight(el);
|
||||
}
|
||||
}
|
||||
for (const entry of this._portablePanels.values()) {
|
||||
const { classList } = entry.panel;
|
||||
if (!classList.contains('panel-floating')) continue;
|
||||
// A live gesture owns the box; it re-clamps when it ends.
|
||||
if (classList.contains('panel-dragging')) continue;
|
||||
if (classList.contains('panel-resizing')) continue;
|
||||
this._reclampPortablePanel(entry);
|
||||
}
|
||||
}
|
||||
|
||||
/** Bring a floating window on-screen; shrink it only if it exceeds the viewport. */
|
||||
_reclampPortablePanel(entry) {
|
||||
const { panel, min } = entry;
|
||||
const left = parseInt(panel.style.left, 10);
|
||||
const top = parseInt(panel.style.top, 10);
|
||||
if (!Number.isFinite(left) || !Number.isFinite(top)) return;
|
||||
for (const [property, viewportExtent] of [
|
||||
['width', window.innerWidth],
|
||||
['height', window.innerHeight],
|
||||
]) {
|
||||
const extent = parseFloat(panel.style[property]);
|
||||
if (!Number.isFinite(extent)) continue;
|
||||
const fitted = fitWindowExtent(extent, min[property], viewportExtent);
|
||||
if (fitted < extent) panel.style[property] = `${fitted}px`;
|
||||
}
|
||||
const next = this._clampPortableWindow(entry, left, top);
|
||||
panel.style.left = `${next.left}px`;
|
||||
panel.style.top = `${next.top}px`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clamp a floating window inside the viewport margin with its header above
|
||||
* the command dock and voice pill, measured each time since the dock resizes.
|
||||
*/
|
||||
_clampPortableWindow(
|
||||
entry,
|
||||
left,
|
||||
top,
|
||||
geometry = this._windowGeometry(entry),
|
||||
) {
|
||||
const { width, height, header } = geometry;
|
||||
const maxLeft = Math.max(
|
||||
VIEWPORT_MARGIN_PX,
|
||||
window.innerWidth - width - VIEWPORT_MARGIN_PX,
|
||||
);
|
||||
const maxTop = Math.max(
|
||||
VIEWPORT_MARGIN_PX,
|
||||
window.innerHeight - height - VIEWPORT_MARGIN_PX,
|
||||
);
|
||||
const x = clamp(left, VIEWPORT_MARGIN_PX, maxLeft);
|
||||
let y = clamp(top, VIEWPORT_MARGIN_PX, maxTop);
|
||||
const obstacles = this._panelObstacles();
|
||||
for (let pass = 0; pass < obstacles.length; pass++) {
|
||||
const hit = obstacles.find(
|
||||
(rect) =>
|
||||
rect.left < x + width &&
|
||||
rect.right > x &&
|
||||
rect.top < y + header &&
|
||||
rect.bottom > y,
|
||||
);
|
||||
if (!hit) break;
|
||||
const above = hit.top - header - VIEWPORT_MARGIN_PX;
|
||||
y =
|
||||
above >= VIEWPORT_MARGIN_PX
|
||||
? above
|
||||
: Math.min(maxTop, hit.bottom + VIEWPORT_MARGIN_PX);
|
||||
}
|
||||
return { left: x, top: y };
|
||||
}
|
||||
|
||||
_windowGeometry({ panel, handle }, rect = panel.getBoundingClientRect()) {
|
||||
const handleRect = handle?.getBoundingClientRect();
|
||||
const header = handleRect ? handleRect.bottom - rect.top : 0;
|
||||
return {
|
||||
width: rect.width,
|
||||
height: rect.height,
|
||||
// Without a measurable header, keep the whole window clear.
|
||||
header: header > 0 ? Math.min(header, rect.height) : rect.height,
|
||||
};
|
||||
}
|
||||
|
||||
_panelObstacles() {
|
||||
const rects = [];
|
||||
for (const id of PANEL_OBSTACLE_IDS) {
|
||||
const rect = document.getElementById(id)?.getBoundingClientRect();
|
||||
// A hidden dock, or a voice UI switched off, measures empty.
|
||||
if (rect && rect.width > 0 && rect.height > 0) rects.push(rect);
|
||||
}
|
||||
return rects;
|
||||
}
|
||||
|
||||
_maybeNotifyLayoutReset() {
|
||||
this._dropRetiredPanelKeys();
|
||||
try {
|
||||
const marker = `godsEyeView.${PANEL_POSITION_STORAGE_VERSION}.layoutResetNotified`;
|
||||
if (localStorage.getItem(marker)) return;
|
||||
@@ -221,7 +30,7 @@ export class PanelPositionControls {
|
||||
);
|
||||
if (hadOldPositions) {
|
||||
this._showToast(
|
||||
'Panel layout updated — positions reset to new defaults',
|
||||
t('Panel layout updated — positions reset to new defaults'),
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
@@ -229,77 +38,14 @@ export class PanelPositionControls {
|
||||
}
|
||||
}
|
||||
|
||||
_initPanelDrag() {
|
||||
if (this.destroyed || this._dragInitialized) return;
|
||||
this._dragInitialized = true;
|
||||
const cctvPanel = document.getElementById('cctv-panel');
|
||||
const streetLevelPanel = document.getElementById('street-level-panel');
|
||||
// A `portable` panel lifts out of its rail on a header drag, resizes from
|
||||
// every edge and remembers its window; the others only reposition.
|
||||
const dragSpecs = [
|
||||
{
|
||||
id: 'pp-toggles',
|
||||
panel: this._ppToggles,
|
||||
handle: this._ppToggles?.querySelector('.panel-drag-handle.compact'),
|
||||
},
|
||||
{
|
||||
id: 'cctv-panel',
|
||||
panel: cctvPanel,
|
||||
handle: cctvPanel?.querySelector('.panel-header'),
|
||||
portable: true,
|
||||
min: { width: 300, height: 160 },
|
||||
},
|
||||
{
|
||||
id: 'street-level-panel',
|
||||
panel: streetLevelPanel,
|
||||
handle: streetLevelPanel?.querySelector('.panel-header'),
|
||||
portable: true,
|
||||
min: { width: 320, height: 280 },
|
||||
// Shrinking the window to its strip docks it, so it never sits
|
||||
// over the globe as a stray header.
|
||||
dockOnCollapse: true,
|
||||
},
|
||||
].filter(Boolean);
|
||||
|
||||
for (const spec of dragSpecs) {
|
||||
if (!spec.panel || !spec.handle) continue;
|
||||
if (spec.portable) {
|
||||
this._portablePanels.set(spec.id, {
|
||||
panel: spec.panel,
|
||||
handle: spec.handle,
|
||||
min: { width: 300, height: 160, ...spec.min },
|
||||
dockOnCollapse: spec.dockOnCollapse === true,
|
||||
});
|
||||
spec.panel.classList.add('panel-portable');
|
||||
}
|
||||
this._restorePanelPosition(spec.id, spec.panel);
|
||||
this._makePanelDraggable(spec.id, spec.panel, spec.handle);
|
||||
if (spec.portable) {
|
||||
this._makePanelResizable(spec.id, spec.panel, spec.min);
|
||||
}
|
||||
_dropRetiredPanelKeys() {
|
||||
try {
|
||||
for (const key of Object.keys(localStorage))
|
||||
if (RETIRED_PANEL_KEY_PREFIXES.some((prefix) => key.startsWith(prefix)))
|
||||
localStorage.removeItem(key);
|
||||
} catch {
|
||||
// storage unavailable
|
||||
}
|
||||
// Keep a positioned panel on-screen when its HEIGHT changes after restore — it expands to its
|
||||
// full row set a frame or two later, so the restore-time clamp used a stale (shorter) height and
|
||||
// the panel could still hang off the bottom (audit U2). Re-clamp on every size change. Floating
|
||||
// windows grow the same way when their content does.
|
||||
const observed = [
|
||||
this._ppToggles,
|
||||
...[...this._portablePanels.values()].map(({ panel }) => panel),
|
||||
].filter(Boolean);
|
||||
if (observed.length && typeof ResizeObserver !== 'undefined') {
|
||||
this._draggableResizeObserver = new ResizeObserver(() =>
|
||||
this._reclampDraggablePanels(),
|
||||
);
|
||||
for (const panel of observed)
|
||||
this._draggableResizeObserver.observe(panel);
|
||||
}
|
||||
if (this._portablePanels.size) {
|
||||
this.listen(window, 'resize', () => this._reclampDraggablePanels());
|
||||
}
|
||||
}
|
||||
|
||||
_panelStorageKey(panelId) {
|
||||
return `godsEyeView.${PANEL_POSITION_STORAGE_VERSION}.panelPos.${panelId}`;
|
||||
}
|
||||
|
||||
_panelCollapseStorageKey(panelId) {
|
||||
@@ -351,492 +97,4 @@ export class PanelPositionControls {
|
||||
// storage unavailable
|
||||
}
|
||||
}
|
||||
|
||||
_pinPanelToRight(panelEl) {
|
||||
if (!panelEl) return;
|
||||
const rect = panelEl.getBoundingClientRect();
|
||||
const rightOffset = Math.max(6, Math.round(window.innerWidth - rect.right));
|
||||
panelEl.style.right = `${rightOffset}px`;
|
||||
panelEl.style.left = 'auto';
|
||||
}
|
||||
|
||||
_restorePanelPosition(panelId, panelEl) {
|
||||
try {
|
||||
const raw = localStorage.getItem(this._panelStorageKey(panelId));
|
||||
if (!raw) return;
|
||||
const pos = JSON.parse(raw);
|
||||
if (!pos || typeof pos.left !== 'number' || typeof pos.top !== 'number')
|
||||
return;
|
||||
// Only portable panels store, and accept, floating records.
|
||||
const portable = this._portablePanels.get(panelId);
|
||||
if (Boolean(pos.floating) !== Boolean(portable)) return;
|
||||
if (portable) {
|
||||
panelEl.classList.add('panel-floating', 'panel-draggable');
|
||||
// A restored window must stack above the docked rail panels too.
|
||||
this._promotePanelZ(panelEl);
|
||||
if (Number.isFinite(pos.width)) {
|
||||
panelEl.style.width = `${fitWindowExtent(
|
||||
pos.width,
|
||||
portable.min.width,
|
||||
window.innerWidth,
|
||||
)}px`;
|
||||
}
|
||||
if (Number.isFinite(pos.height)) {
|
||||
panelEl.style.height = `${fitWindowExtent(
|
||||
pos.height,
|
||||
portable.min.height,
|
||||
window.innerHeight,
|
||||
)}px`;
|
||||
}
|
||||
}
|
||||
// Clamp to the viewport: a position saved at one window size would otherwise land off-screen at
|
||||
// another (audit U2 — observed a panel at x:-192). The drag handler clamps; restore must too,
|
||||
// and a window saved under the command dock must not come back there.
|
||||
const { left, top } = portable
|
||||
? this._clampPortableWindow(
|
||||
portable,
|
||||
Math.round(pos.left),
|
||||
Math.round(pos.top),
|
||||
)
|
||||
: this._clampToViewport(
|
||||
Math.round(pos.left),
|
||||
Math.round(pos.top),
|
||||
panelEl,
|
||||
);
|
||||
placeAt(panelEl, left, top);
|
||||
if (panelId === 'pp-toggles') {
|
||||
this._pinPanelToRight(panelEl);
|
||||
}
|
||||
} catch {
|
||||
// ignore malformed saved panel position
|
||||
}
|
||||
}
|
||||
|
||||
_clampToViewport(left, top, panelEl) {
|
||||
const rect = panelEl.getBoundingClientRect();
|
||||
const maxLeft = Math.max(6, window.innerWidth - rect.width - 6);
|
||||
const maxTop = Math.max(6, window.innerHeight - rect.height - 6);
|
||||
return {
|
||||
left: Math.max(6, Math.min(maxLeft, left)),
|
||||
top: Math.max(6, Math.min(maxTop, top)),
|
||||
};
|
||||
}
|
||||
|
||||
_savePanelPosition(panelId, panelEl) {
|
||||
const rect = panelEl.getBoundingClientRect();
|
||||
const record = {
|
||||
left: Math.round(rect.left),
|
||||
top: Math.round(rect.top),
|
||||
};
|
||||
if (this._portablePanels.has(panelId)) {
|
||||
// Only an explicitly set size is remembered, and the inline value
|
||||
// rather than the measured box: a collapsed window measures only its
|
||||
// header but keeps the size the user chose for when it expands.
|
||||
const chosen = (inline, measured) => {
|
||||
const px = parseFloat(inline);
|
||||
return Math.round(Number.isFinite(px) ? px : measured);
|
||||
};
|
||||
if (panelEl.style.width)
|
||||
record.width = chosen(panelEl.style.width, rect.width);
|
||||
if (panelEl.style.height)
|
||||
record.height = chosen(panelEl.style.height, rect.height);
|
||||
record.floating = true;
|
||||
}
|
||||
try {
|
||||
localStorage.setItem(
|
||||
this._panelStorageKey(panelId),
|
||||
JSON.stringify(record),
|
||||
);
|
||||
} catch {
|
||||
// storage unavailable
|
||||
}
|
||||
}
|
||||
|
||||
_promotePanelZ(panelEl) {
|
||||
this._panelZCounter += 1;
|
||||
if (this._panelZCounter > PANEL_Z_MAX) {
|
||||
const promoted = [...document.querySelectorAll('.panel-draggable')]
|
||||
.filter((el) => el.style.zIndex)
|
||||
.sort((a, b) => Number(a.style.zIndex) - Number(b.style.zIndex));
|
||||
let z = PANEL_Z_FLOATING_FLOOR;
|
||||
for (const el of promoted) {
|
||||
el.style.zIndex = String(z);
|
||||
z += 1;
|
||||
}
|
||||
this._panelZCounter = z;
|
||||
}
|
||||
panelEl.style.zIndex = String(this._panelZCounter);
|
||||
}
|
||||
|
||||
_maybeShowFloatHint() {
|
||||
try {
|
||||
if (localStorage.getItem(PANEL_FLOAT_HINT_STORAGE_KEY)) return;
|
||||
localStorage.setItem(PANEL_FLOAT_HINT_STORAGE_KEY, '1');
|
||||
} catch {
|
||||
// storage unavailable: still show it once this session
|
||||
if (this._floatHintShown) return;
|
||||
this._floatHintShown = true;
|
||||
}
|
||||
this._showToast(PANEL_FLOAT_HINT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn a rail panel into a fixed window in place. Width is frozen so a
|
||||
* `width: 100%` panel keeps its size; height stays natural until a resize.
|
||||
*/
|
||||
_liftPanelOut(panelId, panelEl, rect = panelEl.getBoundingClientRect()) {
|
||||
if (panelEl.classList.contains('panel-floating')) return false;
|
||||
placeAt(panelEl, Math.round(rect.left), Math.round(rect.top));
|
||||
if (!panelEl.classList.contains('collapsed')) {
|
||||
panelEl.style.width = `${Math.round(rect.width)}px`;
|
||||
}
|
||||
panelEl.style.removeProperty('--right-panel-allocated-height');
|
||||
panelEl.removeAttribute('aria-hidden');
|
||||
panelEl.classList.add('panel-floating', 'panel-draggable');
|
||||
this._promotePanelZ(panelEl);
|
||||
this._layoutRightPanels();
|
||||
this._maybeShowFloatHint();
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Snap a floating panel back into its rail and forget its window. */
|
||||
_resetPanelPosition(panelId) {
|
||||
const portable = this._portablePanels.get(panelId);
|
||||
if (!portable) return;
|
||||
const panelEl = portable.panel;
|
||||
this._cancelDrag?.();
|
||||
panelEl.classList.remove(
|
||||
'panel-floating',
|
||||
'panel-draggable',
|
||||
'panel-dragging',
|
||||
'panel-resizing',
|
||||
);
|
||||
for (const property of FLOATING_STYLE_PROPERTIES) {
|
||||
panelEl.style.removeProperty(property);
|
||||
}
|
||||
try {
|
||||
localStorage.removeItem(this._panelStorageKey(panelId));
|
||||
} catch {
|
||||
// storage unavailable
|
||||
}
|
||||
this._layoutRightPanels();
|
||||
this._onPanelResized?.(panelId);
|
||||
}
|
||||
|
||||
_makePanelDraggable(panelId, panelEl, handleEl) {
|
||||
// Z-order promotion: bring clicked panel to front of the stacking context
|
||||
this.listen(panelEl, 'pointerdown', () => {
|
||||
this._promotePanelZ(panelEl);
|
||||
});
|
||||
if (this._portablePanels.has(panelId)) {
|
||||
this._makePortablePanelDraggable(panelId, panelEl, handleEl);
|
||||
return;
|
||||
}
|
||||
|
||||
this.listen(handleEl, 'pointerdown', (event) => {
|
||||
if (event.button !== 0) return;
|
||||
if (event.target.closest('.panel-collapse-btn')) return;
|
||||
if (
|
||||
event.target.closest(
|
||||
'input, select, option, button:not(.panel-collapse-btn)',
|
||||
)
|
||||
)
|
||||
return;
|
||||
|
||||
this._cancelDrag?.();
|
||||
event.preventDefault();
|
||||
const rect = panelEl.getBoundingClientRect();
|
||||
const offsetX = event.clientX - rect.left;
|
||||
const offsetY = event.clientY - rect.top;
|
||||
|
||||
placeAt(panelEl, rect.left, rect.top);
|
||||
panelEl.classList.add('panel-dragging');
|
||||
this._promotePanelZ(panelEl);
|
||||
|
||||
this._trackPointerGesture(event, {
|
||||
onMove: (moveEvent) => {
|
||||
const nextLeftRaw = moveEvent.clientX - offsetX;
|
||||
const nextTopRaw = moveEvent.clientY - offsetY;
|
||||
const maxLeft = Math.max(6, window.innerWidth - rect.width - 6);
|
||||
const maxTop = Math.max(6, window.innerHeight - rect.height - 6);
|
||||
const nextLeft = Math.max(6, Math.min(maxLeft, nextLeftRaw));
|
||||
const nextTop = Math.max(6, Math.min(maxTop, nextTopRaw));
|
||||
panelEl.style.left = `${nextLeft}px`;
|
||||
panelEl.style.top = `${nextTop}px`;
|
||||
if (panelId === 'pp-toggles') {
|
||||
this._layoutRightPanels();
|
||||
}
|
||||
if (panelId === 'cctv-panel') {
|
||||
this._syncCctvPanelViewport();
|
||||
}
|
||||
},
|
||||
onStop: () => panelEl.classList.remove('panel-dragging'),
|
||||
// A cancelled press keeps the place too: there is no rail to revert to.
|
||||
onEnd: () => {
|
||||
if (panelId === 'pp-toggles') {
|
||||
this._pinPanelToRight(panelEl);
|
||||
}
|
||||
this._savePanelPosition(panelId, panelEl);
|
||||
if (panelId === 'cctv-panel') {
|
||||
this._syncCctvPanelViewport();
|
||||
}
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Track one pointer gesture. With a `threshold`, `onStart` and `onMove` wait
|
||||
* until the pointer has travelled that far; `onEnd`/`onCancel` get whether
|
||||
* it started. Stopping through `_cancelDrag` calls neither.
|
||||
*/
|
||||
_trackPointerGesture(
|
||||
event,
|
||||
{ threshold = 0, onStart, onMove, onStop, onEnd, onCancel = onEnd },
|
||||
) {
|
||||
const startX = event.clientX;
|
||||
const startY = event.clientY;
|
||||
let started = threshold <= 0;
|
||||
const move = (moveEvent) => {
|
||||
const dx = moveEvent.clientX - startX;
|
||||
const dy = moveEvent.clientY - startY;
|
||||
if (!started) {
|
||||
if (Math.hypot(dx, dy) < threshold) return;
|
||||
started = true;
|
||||
onStart?.();
|
||||
}
|
||||
onMove(moveEvent, dx, dy);
|
||||
};
|
||||
const stop = () => {
|
||||
onStop?.();
|
||||
window.removeEventListener('pointermove', move);
|
||||
window.removeEventListener('pointerup', up);
|
||||
window.removeEventListener('pointercancel', cancel);
|
||||
if (this._cancelDrag === stop) this._cancelDrag = null;
|
||||
};
|
||||
const up = () => {
|
||||
stop();
|
||||
onEnd?.(started);
|
||||
};
|
||||
const cancel = () => {
|
||||
stop();
|
||||
onCancel?.(started);
|
||||
};
|
||||
this._cancelDrag = stop;
|
||||
window.addEventListener('pointermove', move);
|
||||
window.addEventListener('pointerup', up);
|
||||
window.addEventListener('pointercancel', cancel);
|
||||
}
|
||||
|
||||
/** @returns {boolean} Whether the panel was floating and is now docked. */
|
||||
dockPanel(panelId) {
|
||||
const portable = this._portablePanels.get(panelId);
|
||||
if (!portable?.panel.classList.contains('panel-floating')) return false;
|
||||
this._resetPanelPosition(panelId);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** A `dockOnCollapse` panel returns to its rail when collapsed while floating. */
|
||||
onPanelCollapsed(panelId, collapsed) {
|
||||
if (!collapsed || !this._portablePanels.get(panelId)?.dockOnCollapse)
|
||||
return;
|
||||
this.dockPanel(panelId);
|
||||
}
|
||||
|
||||
/**
|
||||
* The collapse button still toggles on a plain click; the click that ends a
|
||||
* real drag is swallowed so it cannot toggle by accident.
|
||||
*/
|
||||
_makePortablePanelDraggable(panelId, panelEl, handleEl) {
|
||||
let swallowNextClick = false;
|
||||
this.listen(
|
||||
handleEl,
|
||||
'click',
|
||||
(event) => {
|
||||
if (!swallowNextClick) return;
|
||||
swallowNextClick = false;
|
||||
event.stopImmediatePropagation();
|
||||
event.preventDefault();
|
||||
},
|
||||
{ capture: true },
|
||||
);
|
||||
this.listen(handleEl, 'dblclick', (event) => {
|
||||
if (event.target.closest?.(INTERACTIVE_SELECTOR)) return;
|
||||
if (!panelEl.classList.contains('panel-floating')) return;
|
||||
event.preventDefault();
|
||||
this._resetPanelPosition(panelId);
|
||||
});
|
||||
let lastPress = null;
|
||||
this.listen(handleEl, 'pointerdown', (event) => {
|
||||
if (event.button !== 0 || !isPrecisePointer(event)) return;
|
||||
const interactive = event.target.closest?.(INTERACTIVE_SELECTOR);
|
||||
if (interactive && !interactive.matches('.panel-collapse-btn')) return;
|
||||
|
||||
const now = event.timeStamp || performance.now();
|
||||
const doublePress =
|
||||
!interactive &&
|
||||
lastPress &&
|
||||
now - lastPress.time <= DOUBLE_PRESS_MS &&
|
||||
Math.hypot(event.clientX - lastPress.x, event.clientY - lastPress.y) <=
|
||||
DOUBLE_PRESS_SLOP_PX;
|
||||
lastPress = doublePress
|
||||
? null
|
||||
: { time: now, x: event.clientX, y: event.clientY };
|
||||
if (doublePress && panelEl.classList.contains('panel-floating')) {
|
||||
event.preventDefault();
|
||||
this._resetPanelPosition(panelId);
|
||||
return;
|
||||
}
|
||||
|
||||
this._cancelDrag?.();
|
||||
// A header press must not start a text selection across the page.
|
||||
event.preventDefault();
|
||||
const entry = this._portablePanels.get(panelId);
|
||||
let lifted = false;
|
||||
let before = null;
|
||||
let offsetX = 0;
|
||||
let offsetY = 0;
|
||||
let geometry = null;
|
||||
|
||||
this._trackPointerGesture(event, {
|
||||
threshold: DRAG_THRESHOLD_PX,
|
||||
onStart: () => {
|
||||
// A drag between two presses is not a double-click.
|
||||
lastPress = null;
|
||||
const rect = panelEl.getBoundingClientRect();
|
||||
offsetX = event.clientX - rect.left;
|
||||
offsetY = event.clientY - rect.top;
|
||||
geometry = this._windowGeometry(entry, rect);
|
||||
before = geometryOf(panelEl);
|
||||
lifted = this._liftPanelOut(panelId, panelEl, rect);
|
||||
panelEl.classList.add('panel-dragging');
|
||||
this._promotePanelZ(panelEl);
|
||||
},
|
||||
onMove: (moveEvent) => {
|
||||
moveEvent.preventDefault();
|
||||
const next = this._clampPortableWindow(
|
||||
entry,
|
||||
moveEvent.clientX - offsetX,
|
||||
moveEvent.clientY - offsetY,
|
||||
geometry,
|
||||
);
|
||||
panelEl.style.left = `${next.left}px`;
|
||||
panelEl.style.top = `${next.top}px`;
|
||||
},
|
||||
onStop: () => panelEl.classList.remove('panel-dragging'),
|
||||
onEnd: (dragged) => {
|
||||
if (!dragged) return;
|
||||
swallowNextClick = true;
|
||||
setTimeout(() => {
|
||||
swallowNextClick = false;
|
||||
}, 0);
|
||||
this._savePanelPosition(panelId, panelEl);
|
||||
this._onPanelResized?.(panelId);
|
||||
},
|
||||
onCancel: (dragged) => {
|
||||
if (dragged)
|
||||
this._revertPanelGesture(panelId, panelEl, lifted, before);
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** On pointercancel, restore the panel as the gesture found it; save nothing. */
|
||||
_revertPanelGesture(panelId, panelEl, lifted, before) {
|
||||
if (lifted) {
|
||||
this._resetPanelPosition(panelId);
|
||||
return;
|
||||
}
|
||||
Object.assign(panelEl.style, before);
|
||||
this._onPanelResized?.(panelId);
|
||||
}
|
||||
|
||||
/** Resizing a docked panel lifts it out first, so handles work in both states. */
|
||||
_makePanelResizable(panelId, panelEl, min = {}) {
|
||||
const limits = { width: 300, height: 160, ...min };
|
||||
for (const dir of RESIZE_DIRECTIONS) {
|
||||
const handle = document.createElement('div');
|
||||
handle.className =
|
||||
dir === 'se' ? 'panel-resize-grip' : 'panel-resize-edge';
|
||||
handle.dataset.dir = dir;
|
||||
handle.setAttribute('aria-hidden', 'true');
|
||||
if (dir === 'se') {
|
||||
handle.title = 'Drag to resize · double-click the header to snap back';
|
||||
}
|
||||
panelEl.appendChild(handle);
|
||||
this._resizeHandles.push(handle);
|
||||
this.listen(handle, 'pointerdown', (event) =>
|
||||
this._startPanelResize(event, panelId, panelEl, dir, limits),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
_startPanelResize(event, panelId, panelEl, dir, limits) {
|
||||
if (event.button !== 0 || !isPrecisePointer(event)) return;
|
||||
event.preventDefault();
|
||||
this._cancelDrag?.();
|
||||
// Set once the pointer has travelled: a plain click on an edge must not
|
||||
// lift the panel out.
|
||||
let startBox = null;
|
||||
let lifted = false;
|
||||
let before = null;
|
||||
const apply = ({ left, top, width, height }) => {
|
||||
panelEl.style.left = `${left}px`;
|
||||
panelEl.style.top = `${top}px`;
|
||||
panelEl.style.width = `${width}px`;
|
||||
panelEl.style.height = `${height}px`;
|
||||
};
|
||||
|
||||
this._trackPointerGesture(event, {
|
||||
threshold: DRAG_THRESHOLD_PX,
|
||||
onStart: () => {
|
||||
const rect = panelEl.getBoundingClientRect();
|
||||
before = geometryOf(panelEl);
|
||||
lifted = this._liftPanelOut(panelId, panelEl, rect);
|
||||
startBox = {
|
||||
left: Math.round(rect.left),
|
||||
top: Math.round(rect.top),
|
||||
width: Math.round(rect.width),
|
||||
height: Math.round(rect.height),
|
||||
};
|
||||
panelEl.classList.add('panel-resizing');
|
||||
this._promotePanelZ(panelEl);
|
||||
apply(startBox);
|
||||
},
|
||||
onMove: (moveEvent, dx, dy) => {
|
||||
moveEvent.preventDefault();
|
||||
apply(
|
||||
resizeBox(startBox, dir, dx, dy, {
|
||||
minWidth: limits.width,
|
||||
minHeight: limits.height,
|
||||
viewportWidth: window.innerWidth,
|
||||
viewportHeight: window.innerHeight,
|
||||
}),
|
||||
);
|
||||
},
|
||||
onStop: () => panelEl.classList.remove('panel-resizing'),
|
||||
onEnd: (resized) => {
|
||||
if (!resized) return;
|
||||
// Re-clamping skipped the live gesture; a north edge may have moved
|
||||
// the header under the command dock.
|
||||
const entry = this._portablePanels.get(panelId);
|
||||
if (entry) this._reclampPortablePanel(entry);
|
||||
this._savePanelPosition(panelId, panelEl);
|
||||
this._onPanelResized?.(panelId);
|
||||
},
|
||||
onCancel: (resized) => {
|
||||
if (resized) this._revertPanelGesture(panelId, panelEl, lifted, before);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
destroy() {
|
||||
if (this.destroyed) return;
|
||||
this.destroyed = true;
|
||||
this._cancelDrag?.();
|
||||
for (const remove of this.removers.splice(0)) remove();
|
||||
for (const handle of this._resizeHandles.splice(0)) handle.remove();
|
||||
this._draggableResizeObserver?.disconnect();
|
||||
this._draggableResizeObserver = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { PanelPositionControls } from './panelPositionControls.js';
|
||||
|
||||
/** A localStorage stand-in whose keys enumerate like the real one. */
|
||||
function fakeStorage(entries) {
|
||||
const storage = {};
|
||||
Object.defineProperties(storage, {
|
||||
getItem: { value: (key) => (key in storage ? storage[key] : null) },
|
||||
setItem: { value: (key, value) => (storage[key] = String(value)) },
|
||||
removeItem: { value: (key) => delete storage[key] },
|
||||
});
|
||||
Object.assign(storage, entries);
|
||||
return storage;
|
||||
}
|
||||
|
||||
test('the floating panels’ stored positions and hint flag are dropped; collapse state stays', (t) => {
|
||||
const saved = globalThis.localStorage;
|
||||
globalThis.localStorage = fakeStorage({
|
||||
'godsEyeView.v8.panelPos.cctv-panel': '{"x":1}',
|
||||
'godsEyeView.v8.panelFloatHintShown': '1',
|
||||
'godsEyeView.v6.panelCollapsed.cctv-panel': '1',
|
||||
'godsEyeView.v8.layoutResetNotified': '1',
|
||||
});
|
||||
t.after(() => {
|
||||
globalThis.localStorage = saved;
|
||||
});
|
||||
const controls = new PanelPositionControls({ showToast() {} });
|
||||
controls._maybeNotifyLayoutReset();
|
||||
assert.deepEqual(Object.keys(globalThis.localStorage).sort(), [
|
||||
'godsEyeView.v6.panelCollapsed.cctv-panel',
|
||||
'godsEyeView.v8.layoutResetNotified',
|
||||
]);
|
||||
});
|
||||
+63
-27
@@ -21,7 +21,7 @@ test('Display uses an inner scroll body only in Cyber', () => {
|
||||
});
|
||||
|
||||
test('Cyber restores one expanded owner, keeps launchers, and restores other theme preferences', () => {
|
||||
for (const mobile of [false, true]) {
|
||||
for (const mobile of [false]) {
|
||||
const f = fixture('right', {
|
||||
mobile,
|
||||
hud: { visible: true, variant: 'cyber' },
|
||||
@@ -50,6 +50,22 @@ test('Cyber restores one expanded owner, keeps launchers, and restores other the
|
||||
}
|
||||
});
|
||||
|
||||
test('Cyber keeps no accordion on phones, where the rail is presented as tab sheets', () => {
|
||||
// A sheet (for example Cameras: CCTV with Street Level) shows several of the
|
||||
// rail's panels at once; the accordion would collapse all but one.
|
||||
const f = fixture('right', {
|
||||
mobile: true,
|
||||
hud: { visible: true, variant: 'cyber' },
|
||||
});
|
||||
f.expand(f.first, 250);
|
||||
f.expand(f.second, 250);
|
||||
f.options.preferredPanelId = f.second.id;
|
||||
f.run();
|
||||
assert.equal(f.first.classList.contains('collapsed'), false);
|
||||
assert.equal(f.first.classList.contains('cyber-accordion-collapsed'), false);
|
||||
assert.equal(f.second.classList.contains('collapsed'), false);
|
||||
});
|
||||
|
||||
test('Cyber restored accordion prefers keyboard focus when no explicit owner exists', () => {
|
||||
const f = fixture('right', { hud: { visible: true, variant: 'cyber' } });
|
||||
f.expand(f.first, 250);
|
||||
@@ -113,10 +129,7 @@ function element(
|
||||
getBoundingClientRect() {
|
||||
return this.rect;
|
||||
},
|
||||
matches: (selector) =>
|
||||
selector === '[data-panel-id]' ||
|
||||
(selector === '[data-panel-id]:not(.panel-floating)' &&
|
||||
!classes.has('panel-floating')),
|
||||
matches: (selector) => selector === '[data-panel-id]',
|
||||
contains(target) {
|
||||
return (
|
||||
target === this || this.children.some((child) => child.contains(target))
|
||||
@@ -325,28 +338,6 @@ test('right layout retains Display allocation during measurement and caps restor
|
||||
);
|
||||
});
|
||||
|
||||
test('right rail neither measures nor allocates a panel floating out of it', () => {
|
||||
const f = fixture('right');
|
||||
f.expand(f.first, 900);
|
||||
f.expand(f.second, 300);
|
||||
f.first.classList.add('panel-floating');
|
||||
f.first.style.setProperty('--right-panel-allocated-height', '500px');
|
||||
f.first.writes.length = 0;
|
||||
f.run();
|
||||
assert.equal(f.stack.dataset.expandedCount, '1');
|
||||
assert.deepEqual(
|
||||
f.first.writes,
|
||||
[],
|
||||
'a floating panel keeps whatever inline style it left the rail with',
|
||||
);
|
||||
assert.equal(f.first.getAttribute('aria-hidden'), undefined);
|
||||
assert.equal(f.first.classList.contains('layout-auto-collapsed'), false);
|
||||
assert.ok(
|
||||
f.second.style.getPropertyValue('--right-panel-allocated-height'),
|
||||
'the docked panel still receives its allocation',
|
||||
);
|
||||
});
|
||||
|
||||
test('right rail aligns to the current left rail and excludes hidden obstacles', () => {
|
||||
const f = fixture('right');
|
||||
f.options.leftStack.rect.top = 200;
|
||||
@@ -704,6 +695,51 @@ test('narrow-screen rails pin every hosted panel glow inside its panel box', ()
|
||||
}
|
||||
});
|
||||
|
||||
test('right layout ignores a CSS-hidden expanded panel when deciding exclusivity', () => {
|
||||
const f = fixture('right');
|
||||
const weather = element('weather-panel', { height: 300 });
|
||||
weather.computed.display = 'none';
|
||||
f.stack.children.push(weather);
|
||||
weather.parentElement = f.stack;
|
||||
|
||||
f.run();
|
||||
|
||||
assert.equal(f.stack.classList.contains('layout-exclusive'), false);
|
||||
assert.equal(f.stack.dataset.expandedCount, '0');
|
||||
assert.equal(f.first.getAttribute('aria-hidden'), undefined);
|
||||
assert.equal(f.second.getAttribute('aria-hidden'), undefined);
|
||||
assert.equal(
|
||||
weather.style.getPropertyValue('--right-panel-allocated-height'),
|
||||
'',
|
||||
);
|
||||
});
|
||||
|
||||
test('right layout still restores panels that exclusive presentation hides', () => {
|
||||
const f = fixture('right');
|
||||
// Model layers.css: an exclusive rail hides its collapsed panels.
|
||||
f.options.windowRef.getComputedStyle = (node) => ({
|
||||
...node.computed,
|
||||
display:
|
||||
f.stack.classList.contains('layout-exclusive') &&
|
||||
node.classList.contains('collapsed')
|
||||
? 'none'
|
||||
: node.computed.display,
|
||||
});
|
||||
f.expand(f.first, 250);
|
||||
f.second.classList.add('layout-auto-collapsed');
|
||||
f.stack.classList.add('layout-exclusive');
|
||||
|
||||
f.run();
|
||||
assert.equal(f.stack.classList.contains('layout-exclusive'), true);
|
||||
assert.equal(f.second.getAttribute('aria-hidden'), 'true');
|
||||
|
||||
f.options.hud.visible = false;
|
||||
f.run();
|
||||
assert.equal(f.second.classList.contains('collapsed'), false);
|
||||
assert.equal(f.second.classList.contains('layout-auto-collapsed'), false);
|
||||
assert.deepEqual(f.collapsed, ['second']);
|
||||
});
|
||||
|
||||
test('right layout ignores a hidden panel: no lane, no gap, no auto-collapse', () => {
|
||||
const f = fixture('right');
|
||||
const imagery = element('recent-imagery-panel', { height: 0 });
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
// Pure resize geometry for floating panels; PanelPositionControls wires the DOM.
|
||||
|
||||
const EDGE_MARGIN_PX = 6;
|
||||
export const RESIZE_DIRECTIONS = ['n', 's', 'e', 'w', 'ne', 'nw', 'sw', 'se'];
|
||||
|
||||
function clamp(value, min, max) {
|
||||
return Math.max(min, Math.min(max, value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Edges named in `dir` follow the pointer (dx, dy since gesture start) and the
|
||||
* opposite edge stays put. Minimum size and the viewport margin win.
|
||||
*/
|
||||
export function resizeBox(
|
||||
box,
|
||||
dir,
|
||||
dx,
|
||||
dy,
|
||||
{
|
||||
minWidth,
|
||||
minHeight,
|
||||
viewportWidth = Infinity,
|
||||
viewportHeight = Infinity,
|
||||
margin = EDGE_MARGIN_PX,
|
||||
} = {},
|
||||
) {
|
||||
let { left, top, width, height } = box;
|
||||
const right = box.left + box.width;
|
||||
const bottom = box.top + box.height;
|
||||
if (dir.includes('e'))
|
||||
width = clamp(box.width + dx, minWidth, viewportWidth - margin - box.left);
|
||||
if (dir.includes('s'))
|
||||
height = clamp(
|
||||
box.height + dy,
|
||||
minHeight,
|
||||
viewportHeight - margin - box.top,
|
||||
);
|
||||
if (dir.includes('w')) {
|
||||
width = clamp(box.width - dx, minWidth, right - margin);
|
||||
left = right - width;
|
||||
}
|
||||
if (dir.includes('n')) {
|
||||
height = clamp(box.height - dy, minHeight, bottom - margin);
|
||||
top = bottom - height;
|
||||
}
|
||||
return { left, top, width, height };
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { resizeBox } from './panelResize.js';
|
||||
|
||||
const box = { left: 100, top: 100, width: 400, height: 300 };
|
||||
const limits = {
|
||||
minWidth: 200,
|
||||
minHeight: 150,
|
||||
viewportWidth: 1000,
|
||||
viewportHeight: 800,
|
||||
};
|
||||
|
||||
test('east and south edges grow away from the anchored corner', () => {
|
||||
assert.deepEqual(resizeBox(box, 'se', 50, 20, limits), {
|
||||
left: 100,
|
||||
top: 100,
|
||||
width: 450,
|
||||
height: 320,
|
||||
});
|
||||
assert.deepEqual(resizeBox(box, 'e', -30, 999, limits), {
|
||||
left: 100,
|
||||
top: 100,
|
||||
width: 370,
|
||||
height: 300,
|
||||
});
|
||||
});
|
||||
|
||||
test('west and north edges keep the opposite edge pinned', () => {
|
||||
assert.deepEqual(resizeBox(box, 'w', -40, 0, limits), {
|
||||
left: 60,
|
||||
top: 100,
|
||||
width: 440,
|
||||
height: 300,
|
||||
});
|
||||
assert.deepEqual(resizeBox(box, 'nw', 40, 30, limits), {
|
||||
left: 140,
|
||||
top: 130,
|
||||
width: 360,
|
||||
height: 270,
|
||||
});
|
||||
assert.deepEqual(
|
||||
resizeBox(box, 'n', -50, 0, limits).top,
|
||||
100,
|
||||
'horizontal motion does not move a north edge',
|
||||
);
|
||||
});
|
||||
|
||||
test('minimum size stops the moving edge, not the anchored one', () => {
|
||||
const small = resizeBox(box, 'w', 350, 0, limits);
|
||||
assert.deepEqual(small, { left: 300, top: 100, width: 200, height: 300 });
|
||||
assert.equal(resizeBox(box, 'ne', 0, 400, limits).height, 150);
|
||||
assert.equal(resizeBox(box, 'ne', 0, 400, limits).top, 250);
|
||||
});
|
||||
|
||||
test('the viewport margin caps growth in every direction', () => {
|
||||
assert.equal(resizeBox(box, 'e', 2000, 0, limits).width, 1000 - 6 - 100);
|
||||
assert.equal(resizeBox(box, 's', 0, 2000, limits).height, 800 - 6 - 100);
|
||||
const west = resizeBox(box, 'w', -2000, 0, limits);
|
||||
assert.equal(west.left, 6);
|
||||
assert.equal(west.left + west.width, 500);
|
||||
const north = resizeBox(box, 'n', 0, -2000, limits);
|
||||
assert.equal(north.top, 6);
|
||||
assert.equal(north.top + north.height, 400);
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* Preset place names as the page shows them.
|
||||
*
|
||||
* The preset cities in src/cityPois.js keep their English names in data:
|
||||
* those are what voice tools, the AI model, share links and lookups match on.
|
||||
* This helper translates a known English name at a presentation boundary
|
||||
* only; any other place (a geocoded address, a name the model chose) is shown
|
||||
* as given.
|
||||
*
|
||||
* Pure: imports only i18n, no DOM.
|
||||
* @module ui/placeNames
|
||||
*/
|
||||
import { msg, t } from '../i18n/index.js';
|
||||
|
||||
// The preset cities (CITY_POIS names, kept in step by placeNames.test.mjs),
|
||||
// and Los Angeles, which voice results name for the analyst's region scopes.
|
||||
const PLACE_NAME_KEYS = new Map(
|
||||
[
|
||||
msg('Austin'),
|
||||
msg('San Francisco'),
|
||||
msg('New York'),
|
||||
msg('Tokyo'),
|
||||
msg('London'),
|
||||
msg('Paris'),
|
||||
msg('Dubai'),
|
||||
msg('Washington DC'),
|
||||
msg('Tallinn'),
|
||||
msg('Los Angeles'),
|
||||
].map((key) => [key, key]),
|
||||
);
|
||||
|
||||
/**
|
||||
* A preset place name in the active language; any other text unchanged.
|
||||
* @param {string} name English place name, e.g. `Tokyo`.
|
||||
* @returns {string}
|
||||
*/
|
||||
export function localizePlaceName(name) {
|
||||
if (typeof name !== 'string') return name;
|
||||
const key = PLACE_NAME_KEYS.get(name.trim());
|
||||
return key ? t(key) : name;
|
||||
}
|
||||
|
||||
/** The English names this module translates (for tests). */
|
||||
export const KNOWN_PLACE_NAMES = Object.freeze([...PLACE_NAME_KEYS.keys()]);
|
||||
@@ -0,0 +1,82 @@
|
||||
// Preset place names show in the UI language at the presentation boundary
|
||||
// (voice results, location pills, HUD); the preset data stays English.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { setLocale } from '../i18n/index.js';
|
||||
import { CITY_POIS } from '../cityPois.js';
|
||||
import { KNOWN_PLACE_NAMES, localizePlaceName } from './placeNames.js';
|
||||
import { LocationControls } from './locationControls.js';
|
||||
|
||||
test.afterEach(() => setLocale('en'));
|
||||
|
||||
test('every preset city has a display name entry', () => {
|
||||
for (const city of Object.values(CITY_POIS))
|
||||
assert.ok(KNOWN_PLACE_NAMES.includes(city.name), city.name);
|
||||
});
|
||||
|
||||
test('en: place names pass through unchanged', () => {
|
||||
setLocale('en');
|
||||
for (const name of KNOWN_PLACE_NAMES)
|
||||
assert.equal(localizePlaceName(name), name);
|
||||
});
|
||||
|
||||
for (const [locale, tokyo, losAngeles] of [
|
||||
['ru', 'Токио', 'Лос-Анджелес'],
|
||||
['es', 'Tokio', 'Los Ángeles'],
|
||||
]) {
|
||||
test(`${locale}: preset names are translated, other places shown as given`, () => {
|
||||
setLocale(locale);
|
||||
assert.equal(localizePlaceName('Tokyo'), tokyo);
|
||||
assert.equal(localizePlaceName('Los Angeles'), losAngeles);
|
||||
assert.equal(localizePlaceName('Ulaanbaatar'), 'Ulaanbaatar');
|
||||
assert.equal(localizePlaceName(undefined), undefined);
|
||||
});
|
||||
}
|
||||
|
||||
function element() {
|
||||
return {
|
||||
children: [],
|
||||
dataset: {},
|
||||
textContent: '',
|
||||
addEventListener() {},
|
||||
removeEventListener() {},
|
||||
appendChild(child) {
|
||||
this.children.push(child);
|
||||
},
|
||||
replaceChildren() {
|
||||
this.children = [];
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('ru: location pills and the mini-status show the translated city', () => {
|
||||
setLocale('ru');
|
||||
const elements = {
|
||||
pills: element(),
|
||||
poiRow: element(),
|
||||
divider: element(),
|
||||
search: element(),
|
||||
searchToggle: element(),
|
||||
resetButtons: [],
|
||||
statusCity: element(),
|
||||
statusPoi: element(),
|
||||
};
|
||||
const doc = { ...element(), createElement: element };
|
||||
const cities = { tokyo: CITY_POIS.tokyo };
|
||||
const controls = new LocationControls({
|
||||
elements,
|
||||
cities,
|
||||
getExpandedCity: () => null,
|
||||
onCity() {},
|
||||
onPoi() {},
|
||||
onSearch() {},
|
||||
onReset() {},
|
||||
doc,
|
||||
requestFrame: () => 0,
|
||||
cancelFrame() {},
|
||||
});
|
||||
assert.equal(elements.pills.children[0].textContent, 'Токио');
|
||||
controls.renderStatus({ city: CITY_POIS.tokyo, currentPoi: null });
|
||||
assert.equal(elements.statusCity.textContent, '📍 Токио');
|
||||
assert.equal(CITY_POIS.tokyo.name, 'Tokyo');
|
||||
});
|
||||
+43
-14
@@ -1,3 +1,4 @@
|
||||
import { t, msg } from '../i18n/index.js';
|
||||
import {
|
||||
radioTunerSlot,
|
||||
radioTunerCommitSlot,
|
||||
@@ -47,22 +48,36 @@ export function bindRadioControls() {
|
||||
);
|
||||
if (displayOpen) this.actions.revealStyleParameters();
|
||||
if (this._cockpitDisplayToggleBtn) {
|
||||
const action = displayOpen ? 'Collapse' : 'Expand';
|
||||
this._cockpitDisplayToggleBtn.textContent = displayOpen ? '▶' : '◀';
|
||||
this._cockpitDisplayToggleBtn.setAttribute(
|
||||
'aria-label',
|
||||
`${action} Cockpit display options`,
|
||||
t(
|
||||
displayOpen
|
||||
? msg('Collapse Cockpit display options')
|
||||
: msg('Expand Cockpit display options'),
|
||||
),
|
||||
);
|
||||
this._cockpitDisplayToggleBtn.title = t(
|
||||
displayOpen
|
||||
? msg('Collapse Cockpit display options')
|
||||
: msg('Expand Cockpit display options'),
|
||||
);
|
||||
this._cockpitDisplayToggleBtn.title = `${action} Cockpit display options`;
|
||||
}
|
||||
if (this._cockpitRadioToggleBtn) {
|
||||
const action = radioOpen ? 'Collapse' : 'Expand';
|
||||
this._cockpitRadioToggleBtn.textContent = radioOpen ? '▶' : '◀';
|
||||
this._cockpitRadioToggleBtn.setAttribute(
|
||||
'aria-label',
|
||||
`${action} Cockpit Radio controls`,
|
||||
t(
|
||||
radioOpen
|
||||
? msg('Collapse Cockpit Radio controls')
|
||||
: msg('Expand Cockpit Radio controls'),
|
||||
),
|
||||
);
|
||||
this._cockpitRadioToggleBtn.title = t(
|
||||
radioOpen
|
||||
? msg('Collapse Cockpit Radio controls')
|
||||
: msg('Expand Cockpit Radio controls'),
|
||||
);
|
||||
this._cockpitRadioToggleBtn.title = `${action} Cockpit Radio controls`;
|
||||
}
|
||||
if (!expanded && returnFocus) {
|
||||
(kind === 'display'
|
||||
@@ -139,18 +154,25 @@ export function bindRadioControls() {
|
||||
syncTunerTape(resolvedCoordinate);
|
||||
if (this._radioTunerValue) {
|
||||
this._radioTunerValue.textContent = station
|
||||
? `CH ${String(slot.stationIndex + 1).padStart(2, '0')} / ${String(this._radioTunerStations.length).padStart(2, '0')}`
|
||||
: 'NO STATIONS';
|
||||
? t('CH {index} / {total}', {
|
||||
index: String(slot.stationIndex + 1).padStart(2, '0'),
|
||||
total: String(this._radioTunerStations.length).padStart(2, '0'),
|
||||
})
|
||||
: t('NO STATIONS');
|
||||
}
|
||||
if (this._radioTunerStation)
|
||||
this._radioTunerStation.textContent =
|
||||
station?.name || 'NO STATION AVAILABLE';
|
||||
station?.name || t('NO STATION AVAILABLE');
|
||||
if (this._radioTunerSlider) {
|
||||
this._radioTunerSlider.setAttribute(
|
||||
'aria-valuetext',
|
||||
station
|
||||
? `${station.name}, station ${slot.stationIndex + 1} of ${this._radioTunerStations.length}`
|
||||
: 'No station available',
|
||||
? t('{name}, station {index} of {total}', {
|
||||
name: station.name,
|
||||
index: slot.stationIndex + 1,
|
||||
total: this._radioTunerStations.length,
|
||||
})
|
||||
: t('No station available'),
|
||||
);
|
||||
}
|
||||
if (syncStatic)
|
||||
@@ -301,12 +323,12 @@ export function bindRadioControls() {
|
||||
this._radioTunerBandPinnedForNavigation = false;
|
||||
if (result.reason === 'station-unavailable') {
|
||||
if (this._radioTunerValue)
|
||||
this._radioTunerValue.textContent = 'OFF AIR';
|
||||
this._radioTunerValue.textContent = t('OFF AIR');
|
||||
if (this._radioTunerStation)
|
||||
this._radioTunerStation.textContent = 'STATION UNAVAILABLE';
|
||||
this._radioTunerStation.textContent = t('STATION UNAVAILABLE');
|
||||
this._radioTunerSlider?.setAttribute(
|
||||
'aria-valuetext',
|
||||
'Station unavailable after directory refresh',
|
||||
t('Station unavailable after directory refresh'),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -340,7 +362,14 @@ export function bindRadioControls() {
|
||||
origin: 'user',
|
||||
notificationToken,
|
||||
}),
|
||||
// contextSessionOrdering.test.mjs pins this English argument; the
|
||||
// toast shows localizedMessage.
|
||||
`Radio could not ${enabling ? 'start' : 'stop'} cleanly`,
|
||||
{
|
||||
localizedMessage: t('Radio could not {action} cleanly', {
|
||||
action: enabling ? t('start') : t('stop'),
|
||||
}),
|
||||
},
|
||||
);
|
||||
if (this.destroyed || toggled === false) return;
|
||||
if (
|
||||
|
||||
+12
-8
@@ -1,3 +1,4 @@
|
||||
import { t, msg } from '../i18n/index.js';
|
||||
import { bindRadioControls } from './radioBindings.js';
|
||||
import { renderRadioState } from './radioPresentation.js';
|
||||
|
||||
@@ -178,9 +179,11 @@ export class RadioControls {
|
||||
'aria-expanded',
|
||||
String(radioExpanded),
|
||||
);
|
||||
const label = radioExpanded
|
||||
? 'Go to expanded Radio section'
|
||||
: 'Expand Radio section in Context';
|
||||
const label = t(
|
||||
radioExpanded
|
||||
? msg('Go to expanded Radio section')
|
||||
: msg('Expand Radio section in Context'),
|
||||
);
|
||||
this._contextRadioToggleBtn.setAttribute('aria-label', label);
|
||||
this._contextRadioToggleBtn.title = label;
|
||||
return;
|
||||
@@ -198,12 +201,13 @@ export class RadioControls {
|
||||
'aria-expanded',
|
||||
String(compactOpen),
|
||||
);
|
||||
const action = compactOpen ? 'Close' : 'Open';
|
||||
this._contextRadioToggleBtn.setAttribute(
|
||||
'aria-label',
|
||||
`${action} compact Radio controls`,
|
||||
const launcherLabel = t(
|
||||
compactOpen
|
||||
? msg('Close compact Radio controls')
|
||||
: msg('Open compact Radio controls'),
|
||||
);
|
||||
this._contextRadioToggleBtn.title = `${action} compact Radio controls`;
|
||||
this._contextRadioToggleBtn.setAttribute('aria-label', launcherLabel);
|
||||
this._contextRadioToggleBtn.title = launcherLabel;
|
||||
}
|
||||
|
||||
destroy() {
|
||||
|
||||
+99
-106
@@ -1,4 +1,6 @@
|
||||
/** Render Radio state without making playback or Context decisions. */
|
||||
import { t } from '../i18n/index.js';
|
||||
|
||||
export function renderRadioState(state) {
|
||||
if (this.destroyed || !state || !this._radioPanel) return;
|
||||
const lifecycle = this.actions.getLifecycle() || null;
|
||||
@@ -30,33 +32,36 @@ export function renderRadioState(state) {
|
||||
}
|
||||
this._syncContextRadioLauncherState();
|
||||
this._radioLayerState?.classList.toggle('active', enabled);
|
||||
const lifecycleLabel =
|
||||
lifecycleState === 'enabling' ? t('ENABLING') : t('DISABLING');
|
||||
if (this._radioLayerState) {
|
||||
this._radioLayerState.textContent = transitioning
|
||||
? lifecycleState.toUpperCase()
|
||||
? lifecycleLabel
|
||||
: uncertain
|
||||
? 'UNCERTAIN'
|
||||
? t('UNCERTAIN')
|
||||
: state.loading
|
||||
? 'SYNC'
|
||||
? t('SYNC')
|
||||
: enabled
|
||||
? `${state.filteredCount}/${state.stationCount}`
|
||||
: 'OFF';
|
||||
: t('OFF');
|
||||
}
|
||||
const enableLabel = uncertain
|
||||
? t('RECONCILE')
|
||||
: enabled
|
||||
? t('DISABLE')
|
||||
: t('ENABLE');
|
||||
const enableAria = uncertain
|
||||
? t('Reconcile Radio — lifecycle uncertain')
|
||||
: enabled
|
||||
? t('Disable Radio')
|
||||
: t('Enable Radio');
|
||||
if (this._radioEnableBtn) {
|
||||
this._radioEnableBtn.classList.toggle('active', enabled);
|
||||
this._radioEnableBtn.setAttribute('aria-pressed', String(enabled));
|
||||
this._radioEnableBtn.textContent = transitioning
|
||||
? lifecycleState.toUpperCase()
|
||||
: uncertain
|
||||
? 'RECONCILE'
|
||||
: enabled
|
||||
? 'DISABLE'
|
||||
: 'ENABLE';
|
||||
this._radioEnableBtn.setAttribute(
|
||||
'aria-label',
|
||||
uncertain
|
||||
? 'Reconcile Radio — lifecycle uncertain'
|
||||
: `${enabled ? 'Disable' : 'Enable'} Radio`,
|
||||
);
|
||||
? lifecycleLabel
|
||||
: enableLabel;
|
||||
this._radioEnableBtn.setAttribute('aria-label', enableAria);
|
||||
this._radioEnableBtn.disabled = false;
|
||||
this._radioEnableBtn.setAttribute('aria-disabled', String(transitioning));
|
||||
this._radioEnableBtn.setAttribute('aria-busy', String(transitioning));
|
||||
@@ -68,18 +73,9 @@ export function renderRadioState(state) {
|
||||
String(enabled),
|
||||
);
|
||||
this._contextRadioMiniEnableBtn.textContent = transitioning
|
||||
? lifecycleState.toUpperCase()
|
||||
: uncertain
|
||||
? 'RECONCILE'
|
||||
: enabled
|
||||
? 'DISABLE'
|
||||
: 'ENABLE';
|
||||
this._contextRadioMiniEnableBtn.setAttribute(
|
||||
'aria-label',
|
||||
uncertain
|
||||
? 'Reconcile Radio — lifecycle uncertain'
|
||||
: `${enabled ? 'Disable' : 'Enable'} Radio`,
|
||||
);
|
||||
? lifecycleLabel
|
||||
: enableLabel;
|
||||
this._contextRadioMiniEnableBtn.setAttribute('aria-label', enableAria);
|
||||
this._contextRadioMiniEnableBtn.disabled = false;
|
||||
this._contextRadioMiniEnableBtn.setAttribute(
|
||||
'aria-disabled',
|
||||
@@ -94,18 +90,9 @@ export function renderRadioState(state) {
|
||||
this._cockpitRadioEnableBtn.classList.toggle('active', enabled);
|
||||
this._cockpitRadioEnableBtn.setAttribute('aria-pressed', String(enabled));
|
||||
this._cockpitRadioEnableBtn.textContent = transitioning
|
||||
? lifecycleState.toUpperCase()
|
||||
: uncertain
|
||||
? 'RECONCILE'
|
||||
: enabled
|
||||
? 'DISABLE'
|
||||
: 'ENABLE';
|
||||
this._cockpitRadioEnableBtn.setAttribute(
|
||||
'aria-label',
|
||||
uncertain
|
||||
? 'Reconcile Radio — lifecycle uncertain'
|
||||
: `${enabled ? 'Disable' : 'Enable'} Radio`,
|
||||
);
|
||||
? lifecycleLabel
|
||||
: enableLabel;
|
||||
this._cockpitRadioEnableBtn.setAttribute('aria-label', enableAria);
|
||||
this._cockpitRadioEnableBtn.disabled = false;
|
||||
this._cockpitRadioEnableBtn.setAttribute(
|
||||
'aria-disabled',
|
||||
@@ -127,13 +114,14 @@ export function renderRadioState(state) {
|
||||
...state.categories.map((category) => {
|
||||
const option = document.createElement('option');
|
||||
option.value = category.id;
|
||||
option.textContent = `● ${category.label} (${category.count})`;
|
||||
const label = t('{category} ({count})', {
|
||||
category: category.label,
|
||||
count: category.count,
|
||||
});
|
||||
option.textContent = `● ${label}`;
|
||||
option.dataset.radioColor = category.color;
|
||||
option.style.color = category.color;
|
||||
option.setAttribute(
|
||||
'aria-label',
|
||||
`${category.label} (${category.count})`,
|
||||
);
|
||||
option.setAttribute('aria-label', label);
|
||||
return option;
|
||||
}),
|
||||
);
|
||||
@@ -156,8 +144,12 @@ export function renderRadioState(state) {
|
||||
);
|
||||
this._radioTunerBandLabel.textContent =
|
||||
state.filter === 'all'
|
||||
? 'DIRECTORY BAND'
|
||||
: `${String(activeCategory?.label || state.filter).toUpperCase()} BAND`;
|
||||
? t('DIRECTORY BAND')
|
||||
: t('{category} BAND', {
|
||||
category: String(
|
||||
activeCategory?.label || state.filter,
|
||||
).toUpperCase(),
|
||||
});
|
||||
}
|
||||
this._radioTuner?.classList.toggle('is-static', Boolean(state.tuningStatic));
|
||||
if (tunerAvailable) this._refreshRadioTunerBand?.();
|
||||
@@ -176,7 +168,7 @@ export function renderRadioState(state) {
|
||||
|
||||
if (this._radioStationName)
|
||||
this._radioStationName.textContent =
|
||||
selected?.name || 'NO STATION SELECTED';
|
||||
selected?.name || t('NO STATION SELECTED');
|
||||
if (this._radioStationMeta) {
|
||||
const place = selected
|
||||
? [selected.state, selected.countryCode].filter(Boolean).join(' · ')
|
||||
@@ -188,15 +180,15 @@ export function renderRadioState(state) {
|
||||
: '';
|
||||
this._radioStationMeta.textContent = selected
|
||||
? [place, signal].filter(Boolean).join(' / ') ||
|
||||
'Directory metadata only'
|
||||
t('Directory metadata only')
|
||||
: state.loading
|
||||
? 'Loading station directory…'
|
||||
: 'Choose a globe marker or use next.';
|
||||
? t('Loading station directory…')
|
||||
: t('Choose a globe marker or use next.');
|
||||
}
|
||||
if (this._radioStationTags) {
|
||||
const tags = Array.isArray(selected?.tags) ? selected.tags.slice(0, 8) : [];
|
||||
this._radioStationTags.textContent = tags.length
|
||||
? `TAGS · ${tags.join(' · ')}`
|
||||
? t('TAGS · {tags}', { tags: tags.join(' · ') })
|
||||
: '';
|
||||
}
|
||||
if (this._radioStationHomepage) {
|
||||
@@ -218,49 +210,41 @@ export function renderRadioState(state) {
|
||||
this._cockpitRadioPrevBtn.disabled = !interactive || !hasStations;
|
||||
if (this._cockpitRadioNextBtn)
|
||||
this._cockpitRadioNextBtn.disabled = !interactive || !hasStations;
|
||||
const playbackAction = activePlayback
|
||||
? t('Pause')
|
||||
: state.audioState === 'paused'
|
||||
? t('Resume')
|
||||
: t('Play');
|
||||
// The transport button is narrow: it gets its own short uppercase labels.
|
||||
const playbackButtonLabel = activePlayback
|
||||
? t('PAUSE')
|
||||
: state.audioState === 'paused'
|
||||
? t('RESUME')
|
||||
: t('PLAY');
|
||||
const playTargetWord = selected ? t('selected') : t('nearest');
|
||||
const playAria = t('{action} {target} radio station', {
|
||||
action: playbackAction,
|
||||
target: playTargetWord,
|
||||
});
|
||||
if (this._radioPlayBtn) {
|
||||
const action = activePlayback
|
||||
? 'Pause'
|
||||
: state.audioState === 'paused'
|
||||
? 'Resume'
|
||||
: 'Play';
|
||||
this._radioPlayBtn.disabled = !interactive || !hasStations;
|
||||
this._radioPlayBtn.classList.toggle('active', activePlayback);
|
||||
this._radioPlayBtn.textContent = action.toUpperCase();
|
||||
this._radioPlayBtn.setAttribute(
|
||||
'aria-label',
|
||||
`${action} ${selected ? 'selected' : 'nearest'} radio station`,
|
||||
);
|
||||
this._radioPlayBtn.textContent = playbackButtonLabel;
|
||||
this._radioPlayBtn.setAttribute('aria-label', playAria);
|
||||
}
|
||||
if (this._contextRadioMiniPlayBtn) {
|
||||
const action = activePlayback
|
||||
? 'Pause'
|
||||
: state.audioState === 'paused'
|
||||
? 'Resume'
|
||||
: 'Play';
|
||||
this._contextRadioMiniPlayBtn.disabled = !interactive || !hasStations;
|
||||
this._contextRadioMiniPlayBtn.classList.toggle('active', activePlayback);
|
||||
this._contextRadioMiniPlayBtn.textContent = activePlayback ? 'Ⅱ' : '▶';
|
||||
this._contextRadioMiniPlayBtn.setAttribute(
|
||||
'aria-label',
|
||||
`${action} ${selected ? 'selected' : 'nearest'} radio station`,
|
||||
);
|
||||
this._contextRadioMiniPlayBtn.title = action;
|
||||
this._contextRadioMiniPlayBtn.setAttribute('aria-label', playAria);
|
||||
this._contextRadioMiniPlayBtn.title = playbackAction;
|
||||
}
|
||||
if (this._cockpitRadioPlayBtn) {
|
||||
const action = activePlayback
|
||||
? 'Pause'
|
||||
: state.audioState === 'paused'
|
||||
? 'Resume'
|
||||
: 'Play';
|
||||
this._cockpitRadioPlayBtn.disabled = !interactive || !hasStations;
|
||||
this._cockpitRadioPlayBtn.classList.toggle('active', activePlayback);
|
||||
this._cockpitRadioPlayBtn.textContent = activePlayback ? 'Ⅱ' : '▶';
|
||||
this._cockpitRadioPlayBtn.setAttribute(
|
||||
'aria-label',
|
||||
`${action} ${selected ? 'selected' : 'nearest'} radio station`,
|
||||
);
|
||||
this._cockpitRadioPlayBtn.title = action;
|
||||
this._cockpitRadioPlayBtn.setAttribute('aria-label', playAria);
|
||||
this._cockpitRadioPlayBtn.title = playbackAction;
|
||||
}
|
||||
if (this._radioStopBtn)
|
||||
this._radioStopBtn.disabled =
|
||||
@@ -295,56 +279,65 @@ export function renderRadioState(state) {
|
||||
}
|
||||
if (this._contextRadioMiniStation) {
|
||||
this._contextRadioMiniStation.textContent = uncertain
|
||||
? 'RADIO STATE UNCERTAIN'
|
||||
: selected?.name || (state.loading ? 'SYNCING DIRECTORY' : 'RADIO READY');
|
||||
? t('RADIO STATE UNCERTAIN')
|
||||
: selected?.name ||
|
||||
(state.loading ? t('SYNCING DIRECTORY') : t('RADIO READY'));
|
||||
}
|
||||
if (this._cockpitRadioStation) {
|
||||
this._cockpitRadioStation.textContent = uncertain
|
||||
? 'UNCERTAIN'
|
||||
: selected?.name || (state.loading ? 'SYNCING' : 'READY');
|
||||
? t('UNCERTAIN')
|
||||
: selected?.name || (state.loading ? t('SYNCING') : t('READY'));
|
||||
}
|
||||
if (this._radioPlaybackState) {
|
||||
const stationName = selected?.name || t('station');
|
||||
const catalogSuffix = state.degraded
|
||||
? state.stale
|
||||
? ' · stale/degraded directory'
|
||||
: ' · degraded directory'
|
||||
? t(' · stale/degraded directory')
|
||||
: t(' · degraded directory')
|
||||
: state.stale
|
||||
? ' · stale directory'
|
||||
? t(' · stale directory')
|
||||
: '';
|
||||
const outsideFilter =
|
||||
selected && state.selectedIndex < 0 ? ' · outside current filter' : '';
|
||||
selected && state.selectedIndex < 0 ? t(' · outside current filter') : '';
|
||||
const messages = {
|
||||
stopped: enabled
|
||||
? 'Ready — playback starts only from your action'
|
||||
: 'Radio off',
|
||||
loading: 'Connecting directly to broadcaster…',
|
||||
buffering: 'Buffering broadcaster stream…',
|
||||
playing: `Playing ${selected?.name || 'station'}`,
|
||||
paused: `Paused ${selected?.name || 'station'}`,
|
||||
error: state.audioError || 'Broadcaster stream unavailable',
|
||||
? t('Ready — playback starts only from your action')
|
||||
: t('Radio off'),
|
||||
loading: t('Connecting directly to broadcaster…'),
|
||||
buffering: t('Buffering broadcaster stream…'),
|
||||
playing: t('Playing {station}', { station: stationName }),
|
||||
paused: t('Paused {station}', { station: stationName }),
|
||||
// Playback keeps its messages in English (msg()); shown in the UI language.
|
||||
error: state.audioError
|
||||
? t(state.audioError)
|
||||
: t('Broadcaster stream unavailable'),
|
||||
};
|
||||
const voiceSuffix = state.voiceDucked
|
||||
? ' · muted during voice interaction'
|
||||
? t(' · muted during voice interaction')
|
||||
: state.voiceRestoring
|
||||
? ' · restoring volume after voice'
|
||||
? t(' · restoring volume after voice')
|
||||
: '';
|
||||
const tuningSuffix = state.tuningAwaitingStationId
|
||||
? state.audioState === 'error'
|
||||
? ' · static indicates no broadcaster audio'
|
||||
: ' · tuning static until broadcaster starts'
|
||||
? t(' · static indicates no broadcaster audio')
|
||||
: t(' · tuning static until broadcaster starts')
|
||||
: '';
|
||||
const unavailable = state.tuningUnavailableStationId
|
||||
? 'Station unavailable after directory refresh — choose another channel'
|
||||
? t(
|
||||
'Station unavailable after directory refresh — choose another channel',
|
||||
)
|
||||
: null;
|
||||
const lifecycleMessage = transitioning
|
||||
? lifecycleState === 'enabling'
|
||||
? 'Radio is enabling…'
|
||||
: 'Radio is disabling…'
|
||||
? t('Radio is enabling…')
|
||||
: t('Radio is disabling…')
|
||||
: null;
|
||||
const uncertainMessage = uncertain
|
||||
? 'Radio lifecycle is uncertain — use Enable or Disable to reconcile'
|
||||
? t('Radio lifecycle is uncertain — use Enable or Disable to reconcile')
|
||||
: null;
|
||||
this._radioPlaybackState.textContent = `${uncertainMessage || unavailable || lifecycleMessage || state.error || messages[state.audioState] || 'Ready'}${tuningSuffix}${voiceSuffix}${catalogSuffix}${outsideFilter}`;
|
||||
// Directory errors are msg() literals from the radio layer's ingestion.
|
||||
const directoryError = state.error ? t(state.error) : null;
|
||||
this._radioPlaybackState.textContent = `${uncertainMessage || unavailable || lifecycleMessage || directoryError || messages[state.audioState] || t('Ready')}${tuningSuffix}${voiceSuffix}${catalogSuffix}${outsideFilter}`;
|
||||
this._radioPlaybackState.classList.toggle(
|
||||
'error',
|
||||
Boolean(
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { setLocale } from '../i18n/index.js';
|
||||
import { renderRadioState } from './radioPresentation.js';
|
||||
|
||||
function el() {
|
||||
const classes = new Set();
|
||||
return {
|
||||
textContent: '',
|
||||
classList: {
|
||||
toggle(name, on) {
|
||||
on ? classes.add(name) : classes.delete(name);
|
||||
},
|
||||
contains: (name) => classes.has(name),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function render(audioError) {
|
||||
globalThis.document = { getElementById: () => null, activeElement: null };
|
||||
const host = {
|
||||
destroyed: false,
|
||||
_radioPanel: el(),
|
||||
_radioPlaybackState: el(),
|
||||
_syncContextRadioLauncherState() {},
|
||||
actions: {
|
||||
getLifecycle: () => null,
|
||||
preservePanelStateDuringClear: () => false,
|
||||
setPanelCollapsed() {},
|
||||
scheduleLayout() {},
|
||||
},
|
||||
};
|
||||
renderRadioState.call(host, {
|
||||
enabled: true,
|
||||
audioState: 'error',
|
||||
audioError,
|
||||
filteredCount: 1,
|
||||
stationCount: 1,
|
||||
volume: 1,
|
||||
});
|
||||
return host._radioPlaybackState.textContent;
|
||||
}
|
||||
|
||||
const PLAYBACK_ERRORS = [
|
||||
'Playback requires a direct click or tap.',
|
||||
'Broadcaster stream could not be started.',
|
||||
'Broadcaster stream is unavailable or blocked by the browser.',
|
||||
];
|
||||
|
||||
for (const locale of ['es', 'ru']) {
|
||||
test(`radio playback errors are localized in ${locale}`, () => {
|
||||
setLocale(locale);
|
||||
try {
|
||||
for (const message of PLAYBACK_ERRORS) {
|
||||
assert.notEqual(render(message), message, `${locale}: ${message}`);
|
||||
}
|
||||
// Control: the fallback (no audioError) is translated.
|
||||
assert.notEqual(render(null), 'Broadcaster stream unavailable');
|
||||
} finally {
|
||||
setLocale('en');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test('radio playback errors stay English', () => {
|
||||
setLocale('en');
|
||||
for (const message of PLAYBACK_ERRORS) {
|
||||
assert.equal(render(message), message);
|
||||
}
|
||||
assert.equal(render(null), 'Broadcaster stream unavailable');
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { test } from 'node:test';
|
||||
import { renderRadioState } from './radioPresentation.js';
|
||||
|
||||
function el() {
|
||||
const attrs = new Map();
|
||||
return {
|
||||
textContent: '',
|
||||
hidden: false,
|
||||
disabled: false,
|
||||
style: {},
|
||||
dataset: {},
|
||||
classList: { toggle() {}, add() {}, remove() {}, contains: () => false },
|
||||
setAttribute: (k, v) => attrs.set(k, String(v)),
|
||||
getAttribute: (k) => attrs.get(k),
|
||||
attrs,
|
||||
};
|
||||
}
|
||||
|
||||
for (const lifecycleState of ['enabling', 'disabling']) {
|
||||
test(`Radio render survives the ${lifecycleState} transition`, () => {
|
||||
const prior = globalThis.document;
|
||||
globalThis.document = { getElementById: () => null };
|
||||
try {
|
||||
const enable = el();
|
||||
const ctx = {
|
||||
destroyed: false,
|
||||
_radioPanel: el(),
|
||||
_radioEnableBtn: enable,
|
||||
_syncContextRadioLauncherState() {},
|
||||
actions: {
|
||||
getLifecycle: () => ({
|
||||
lifecycleState,
|
||||
enabled: lifecycleState === 'disabling',
|
||||
uncertain: false,
|
||||
}),
|
||||
},
|
||||
};
|
||||
const state = {
|
||||
enabled: false,
|
||||
categories: [],
|
||||
filteredCount: 0,
|
||||
stationCount: 0,
|
||||
audioState: 'idle',
|
||||
};
|
||||
try {
|
||||
renderRadioState.call(ctx, state);
|
||||
} catch (error) {
|
||||
// Anything thrown after the transitional label is a different
|
||||
// missing fixture field, not the bug under test.
|
||||
assert.ok(
|
||||
!(
|
||||
error instanceof ReferenceError &&
|
||||
/lifecycleLabel/.test(error.message)
|
||||
),
|
||||
`render threw: ${error.message}`,
|
||||
);
|
||||
}
|
||||
assert.equal(enable.attrs.get('aria-busy'), 'true');
|
||||
assert.equal(enable.textContent, lifecycleState.toUpperCase());
|
||||
} finally {
|
||||
globalThis.document = prior;
|
||||
}
|
||||
});
|
||||
}
|
||||
+117
-5
@@ -1,5 +1,8 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { syncChipGroup } from './chipGroup.js';
|
||||
import { syncRowList } from './rowList.js';
|
||||
import { formatScaleLabel, unitLabel } from './unitLabels.js';
|
||||
import { createSlider } from './slider.js';
|
||||
|
||||
const set = (node, key, value) => {
|
||||
if (node[key] !== value) node[key] = value;
|
||||
@@ -13,6 +16,13 @@ const order = (parent, nodes) =>
|
||||
parent.insertBefore(node, parent.children[i] || null);
|
||||
});
|
||||
|
||||
// "960 — 1050+ гПа": the unit stays with the last number.
|
||||
const scaleText = (low, high, units) => {
|
||||
const unit = unitLabel(units);
|
||||
const range = `${formatScaleLabel(low)} — ${formatScaleLabel(high)}`;
|
||||
return unit ? `${range}\u00a0${unit}` : range;
|
||||
};
|
||||
|
||||
/** Optional, ordered blocks without disclosure state. All controls are keyed. */
|
||||
export function createRailCardBlocks({ container, cardId, onParams }) {
|
||||
const document = container.ownerDocument;
|
||||
@@ -30,6 +40,7 @@ export function createRailCardBlocks({ container, cardId, onParams }) {
|
||||
};
|
||||
const dispose = (block) => {
|
||||
block.removeClick?.();
|
||||
block.removeInput?.();
|
||||
block.children?.destroy();
|
||||
block.root.remove();
|
||||
};
|
||||
@@ -74,6 +85,65 @@ export function createRailCardBlocks({ container, cardId, onParams }) {
|
||||
);
|
||||
block.chips = make('div', 'rail-card-chips', root);
|
||||
block.chips.setAttribute('role', 'group');
|
||||
block.rangeRow = make('div', 'rail-card-setting-range-row', root);
|
||||
block.rangeLabel = make(
|
||||
'span',
|
||||
'rail-card-setting-range-label',
|
||||
block.rangeRow,
|
||||
);
|
||||
block.rangeInput = createSlider({
|
||||
documentRef: document,
|
||||
className: 'rail-card-setting-range',
|
||||
});
|
||||
block.rangeRow.appendChild(block.rangeInput);
|
||||
block.rangeValue = make(
|
||||
'span',
|
||||
'rail-card-setting-range-value',
|
||||
block.rangeRow,
|
||||
);
|
||||
const rangeParams = () => {
|
||||
const range = block.props.range;
|
||||
const value = Number(block.rangeInput.value);
|
||||
if (
|
||||
!range?.param ||
|
||||
range.disabled ||
|
||||
!Number.isFinite(value) ||
|
||||
value < Number(range.min) ||
|
||||
value > Number(range.max)
|
||||
)
|
||||
return null;
|
||||
return { params: { [range.param]: value } };
|
||||
};
|
||||
const onInput = () => {
|
||||
const range = block.props.range;
|
||||
const value = Number(block.rangeInput.value);
|
||||
const params = rangeParams();
|
||||
if (!params) return;
|
||||
if (range.commitOnChange) block.rangeDraft = { range, value };
|
||||
set(
|
||||
block.rangeValue,
|
||||
'textContent',
|
||||
`${value}${range.unit || ''}`,
|
||||
);
|
||||
attribute(
|
||||
block.rangeInput,
|
||||
'aria-valuetext',
|
||||
`${value}${range.unit || ''}`,
|
||||
);
|
||||
if (!range.commitOnChange) dispatch(params);
|
||||
};
|
||||
const onChange = () => {
|
||||
if (!block.props.range?.commitOnChange) return;
|
||||
const params = rangeParams();
|
||||
block.rangeDraft = null;
|
||||
if (params) dispatch(params);
|
||||
};
|
||||
block.rangeInput.addEventListener('input', onInput);
|
||||
block.rangeInput.addEventListener('change', onChange);
|
||||
block.removeInput = () => {
|
||||
block.rangeInput.removeEventListener('input', onInput);
|
||||
block.rangeInput.removeEventListener('change', onChange);
|
||||
};
|
||||
bind((event) => {
|
||||
const button = event.target?.closest?.('[data-chip-id]');
|
||||
dispatch(
|
||||
@@ -98,8 +168,8 @@ export function createRailCardBlocks({ container, cardId, onParams }) {
|
||||
block.clear.type = 'button';
|
||||
block.clear.dataset.actionId = 'clear';
|
||||
block.clear.textContent = '×';
|
||||
block.clear.setAttribute('aria-label', 'Clear reading');
|
||||
block.clear.title = 'Clear reading';
|
||||
block.clear.setAttribute('aria-label', t('Clear reading'));
|
||||
block.clear.title = t('Clear reading');
|
||||
bind((event) => {
|
||||
if (event.target === block.clear) dispatch(block.props.clear);
|
||||
});
|
||||
@@ -124,17 +194,59 @@ export function createRailCardBlocks({ container, cardId, onParams }) {
|
||||
blocks.set(props.id, block);
|
||||
}
|
||||
block.props = props;
|
||||
if (props.type === 'settings')
|
||||
if (props.type === 'settings') {
|
||||
block.children.update(
|
||||
(props.settings || []).map((setting) => ({
|
||||
...setting,
|
||||
type: 'setting',
|
||||
})),
|
||||
);
|
||||
else if (props.type === 'setting') {
|
||||
} else if (props.type === 'setting') {
|
||||
set(block.label, 'textContent', props.label);
|
||||
attribute(block.chips, 'aria-label', props.label);
|
||||
syncChipGroup(block.chips, props.chips);
|
||||
const range = props.range;
|
||||
set(block.rangeRow, 'hidden', !range);
|
||||
const draft = block.rangeDraft;
|
||||
if (
|
||||
draft &&
|
||||
(!range ||
|
||||
range.disabled ||
|
||||
!range.commitOnChange ||
|
||||
['id', 'param', 'min', 'max', 'step', 'value'].some(
|
||||
(key) => range[key] !== draft.range[key],
|
||||
))
|
||||
)
|
||||
block.rangeDraft = null;
|
||||
if (range) {
|
||||
const min = Number(range.min);
|
||||
const max = Number(range.max);
|
||||
const step = Number(range.step);
|
||||
const candidate = Number(block.rangeDraft?.value ?? range.value);
|
||||
const value = Math.min(
|
||||
max,
|
||||
Math.max(min, Number.isFinite(candidate) ? candidate : min),
|
||||
);
|
||||
set(block.rangeLabel, 'textContent', range.label || '');
|
||||
set(block.rangeLabel, 'hidden', !range.label);
|
||||
set(block.rangeInput.dataset, 'rangeId', range.id || props.id);
|
||||
set(block.rangeInput, 'min', String(min));
|
||||
set(block.rangeInput, 'max', String(max));
|
||||
set(block.rangeInput, 'step', String(step));
|
||||
set(block.rangeInput, 'value', String(value));
|
||||
set(block.rangeInput, 'disabled', Boolean(range.disabled));
|
||||
attribute(
|
||||
block.rangeInput,
|
||||
'aria-label',
|
||||
range.ariaLabel || props.label,
|
||||
);
|
||||
attribute(
|
||||
block.rangeInput,
|
||||
'aria-valuetext',
|
||||
`${value}${range.unit || ''}`,
|
||||
);
|
||||
set(block.rangeValue, 'textContent', `${value}${range.unit || ''}`);
|
||||
}
|
||||
} else if (props.type === 'list') syncRowList(block.root, props.list);
|
||||
else if (props.type === 'result') {
|
||||
set(block.label, 'textContent', props.label);
|
||||
@@ -197,7 +309,7 @@ export function createRailCardBlocks({ container, cardId, onParams }) {
|
||||
block.scale,
|
||||
'textContent',
|
||||
visible
|
||||
? `${legend.labels[0]} — ${legend.labels.at(-1)} ${legend.units || ''}`.trim()
|
||||
? scaleText(legend.labels[0], legend.labels.at(-1), legend.units)
|
||||
: '',
|
||||
);
|
||||
} else if (props.type === 'actions') {
|
||||
|
||||
+11
-7
@@ -1,4 +1,5 @@
|
||||
import { createRailCardBlocks } from './railCardBlocks.js';
|
||||
import { createStatusBadge, updateStatusBadge } from './statusBadge.js';
|
||||
|
||||
const set = (node, key, value) => {
|
||||
if (node[key] !== value) node[key] = value;
|
||||
@@ -53,11 +54,12 @@ export function createRailCards({
|
||||
'rail-card-title rail-card-nowrap',
|
||||
heading,
|
||||
);
|
||||
const badge = make(
|
||||
'span',
|
||||
`rail-card-badge${badgeClassName ? ` ${badgeClassName}` : ''}`,
|
||||
labels,
|
||||
);
|
||||
const badge = createStatusBadge({
|
||||
documentRef: document,
|
||||
appearance: 'plain',
|
||||
className: `rail-card-badge${badgeClassName ? ` ${badgeClassName}` : ''}`,
|
||||
});
|
||||
labels.appendChild(badge);
|
||||
const disclosure = make('span', 'rail-card-disclosure', header);
|
||||
disclosure.setAttribute('aria-hidden', 'true');
|
||||
const compact = make('span', 'rail-card-compact', header);
|
||||
@@ -90,8 +92,10 @@ export function createRailCards({
|
||||
row.title.setAttribute('title', card.title);
|
||||
set(row.icon, 'textContent', card.icon || '');
|
||||
set(row.icon, 'hidden', !card.icon);
|
||||
set(row.badge, 'textContent', card.badge || '');
|
||||
set(row.badge, 'hidden', !card.badge);
|
||||
updateStatusBadge(row.badge, {
|
||||
label: card.badge || '',
|
||||
hidden: !card.badge,
|
||||
});
|
||||
const open = card.open !== false;
|
||||
set(row.element.dataset, 'open', String(open));
|
||||
row.element.classList.toggle('is-open', open);
|
||||
|
||||
@@ -119,6 +119,96 @@ test('footer buttons retain focus and current callbacks; links use safe new tabs
|
||||
button.click();
|
||||
assert.deepEqual(calls, [2]);
|
||||
});
|
||||
test('setting ranges stay below presets and commit expensive filters on release', () => {
|
||||
const f = railFixture();
|
||||
const calls = [];
|
||||
const view = createRailCards({
|
||||
...f,
|
||||
onParams: (...args) => calls.push(args),
|
||||
});
|
||||
const model = (value) => ({
|
||||
...card,
|
||||
blocks: [
|
||||
{
|
||||
id: 'settings',
|
||||
type: 'settings',
|
||||
settings: [
|
||||
{
|
||||
id: 'image',
|
||||
label: 'IMAGE',
|
||||
chips: [
|
||||
{
|
||||
id: 'clouds-only',
|
||||
label: 'Clouds only',
|
||||
params: { infrared: 100 },
|
||||
},
|
||||
{ id: 'full', label: 'Full', params: { infrared: 0 } },
|
||||
],
|
||||
range: {
|
||||
id: 'cloud-filter',
|
||||
param: 'infrared',
|
||||
min: 0,
|
||||
max: 100,
|
||||
step: 1,
|
||||
value,
|
||||
label: 'FILTER',
|
||||
unit: '%',
|
||||
ariaLabel: 'Cloud filter strength',
|
||||
commitOnChange: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
view.update([model(100)]);
|
||||
const setting = f.find((node) => node.dataset.blockId === 'image');
|
||||
assert.equal(setting.children[1].className, 'rail-card-chips');
|
||||
assert.equal(setting.children[2].className, 'rail-card-setting-range-row');
|
||||
assert.equal(setting.children[2].children[0].textContent, 'FILTER');
|
||||
const slider = f.find((node) => node.dataset.rangeId === 'cloud-filter');
|
||||
assert.equal(slider.tagName, 'INPUT');
|
||||
assert.equal(slider.type, 'range');
|
||||
assert.equal(slider.min, '0');
|
||||
assert.equal(slider.max, '100');
|
||||
assert.equal(slider.step, '1');
|
||||
assert.equal(slider.value, '100');
|
||||
assert.equal(slider.getAttribute('aria-label'), 'Cloud filter strength');
|
||||
slider.focus();
|
||||
slider.value = '53';
|
||||
slider.dispatchEvent(new Event('input'));
|
||||
assert.equal(calls.length, 0, 'expensive image work waits until release');
|
||||
assert.equal(
|
||||
f.find((node) => node.className === 'rail-card-setting-range-value')
|
||||
.textContent,
|
||||
'53%',
|
||||
);
|
||||
view.update([model(100)]);
|
||||
assert.equal(slider.value, '53', 'a status refresh retains the pending drag');
|
||||
assert.equal(
|
||||
slider.getAttribute('aria-valuetext'),
|
||||
'53%',
|
||||
'the accessible preview also survives a refresh',
|
||||
);
|
||||
slider.dispatchEvent(new Event('change'));
|
||||
assert.deepEqual(calls.at(-1), ['a', { infrared: 53 }]);
|
||||
view.update([model(53)]);
|
||||
assert.equal(slider.value, '53');
|
||||
assert.equal(f.document.activeElement, slider);
|
||||
slider.value = '41';
|
||||
slider.dispatchEvent(new Event('input'));
|
||||
view.update([model(70)]);
|
||||
assert.equal(
|
||||
slider.value,
|
||||
'70',
|
||||
'an authoritative value supersedes the draft',
|
||||
);
|
||||
view.destroy();
|
||||
slider.value = '41';
|
||||
slider.dispatchEvent(new Event('change'));
|
||||
assert.equal(calls.length, 1, 'destroy removes the range listener');
|
||||
});
|
||||
|
||||
test('legend validates colors, preserves the freezing anchor and ignores CSSOM normalization', () => {
|
||||
let writes = 0;
|
||||
const f = railFixture(() => writes++);
|
||||
|
||||
+33
-17
@@ -1,9 +1,20 @@
|
||||
import { formatUtcDayMonth, t } from '../i18n/index.js';
|
||||
import { createSlider } from './slider.js';
|
||||
const set = (node, key, value) => {
|
||||
if (node[key] !== value) node[key] = value;
|
||||
};
|
||||
/**
|
||||
* "HH:MM UTC" of a time, or '' when it is not one. Computed on its own rather
|
||||
* than cut from the dated readout: the localized day and month vary in length
|
||||
* ("3/9" in Spanish, "09-03" in English).
|
||||
*/
|
||||
export const utcClock = (tick) =>
|
||||
Number.isFinite(Date.parse(tick))
|
||||
? `${new Date(tick).toISOString().slice(11, 16)} UTC`
|
||||
: '';
|
||||
const utc = (tick) =>
|
||||
Number.isFinite(Date.parse(tick))
|
||||
? `${new Date(tick).toISOString().slice(5, 16).replace('T', ' ')} UTC`
|
||||
? `${formatUtcDayMonth(tick)} ${utcClock(tick)}`
|
||||
: '';
|
||||
|
||||
/** Stable native transport with local preview and a coalesced 150 ms drag commit. */
|
||||
@@ -32,27 +43,32 @@ export function createRailTimeline({
|
||||
parent.appendChild(node);
|
||||
return node;
|
||||
};
|
||||
const previous = makeButton('‹', 'Earlier observation', row);
|
||||
const slider = document.createElement('input');
|
||||
slider.type = 'range';
|
||||
slider.className = `gev-quantitative-slider${sliderClassName ? ` ${sliderClassName}` : ''}`;
|
||||
slider.min = '0';
|
||||
slider.max = '0';
|
||||
slider.step = '1';
|
||||
slider.value = '0';
|
||||
slider.setAttribute('aria-label', 'Observed history');
|
||||
const previous = makeButton('‹', t('Earlier observation'), row);
|
||||
const slider = createSlider({
|
||||
documentRef: document,
|
||||
className: sliderClassName,
|
||||
min: '0',
|
||||
max: '0',
|
||||
step: '1',
|
||||
value: '0',
|
||||
ariaLabel: t('Observed history'),
|
||||
});
|
||||
row.appendChild(slider);
|
||||
const next = makeButton('›', 'Later observation', row);
|
||||
const next = makeButton('›', t('Later observation'), row);
|
||||
const controls = document.createElement('div');
|
||||
controls.className = 'rail-timeline-controls';
|
||||
const latest = makeButton('Latest', 'Newest frame per product', controls);
|
||||
const play = makeButton('Play', 'Replay observed history', controls);
|
||||
const latest = makeButton(
|
||||
t('Latest'),
|
||||
t('Newest frame per product'),
|
||||
controls,
|
||||
);
|
||||
const play = makeButton(t('Play'), t('Replay observed history'), controls);
|
||||
const readout = document.createElement('span');
|
||||
readout.className = 'rail-timeline-readout';
|
||||
controls.appendChild(readout);
|
||||
const label = document.createElement('div');
|
||||
label.className = 'panel-title';
|
||||
label.textContent = 'Observed history';
|
||||
label.textContent = t('Observed history');
|
||||
const endpoints = document.createElement('div');
|
||||
endpoints.className = 'rail-timeline-endpoints';
|
||||
const oldest = document.createElement('span');
|
||||
@@ -110,8 +126,8 @@ export function createRailTimeline({
|
||||
String(Math.max(0, Math.min(props.index, ticks.length - 1))),
|
||||
);
|
||||
valueText(ticks[Number(slider.value)]);
|
||||
set(oldest, 'textContent', utc(ticks[0]).slice(6));
|
||||
set(newest, 'textContent', utc(ticks.at(-1)).slice(6));
|
||||
set(oldest, 'textContent', utcClock(ticks[0]));
|
||||
set(newest, 'textContent', utcClock(ticks.at(-1)));
|
||||
set(readout, 'textContent', props.readout || '');
|
||||
}
|
||||
for (const node of [slider, latest, play])
|
||||
@@ -128,7 +144,7 @@ export function createRailTimeline({
|
||||
`data-toggle-chip${props.mode === 'latest' ? ' active' : ''}`,
|
||||
);
|
||||
set(play, 'className', `data-toggle-chip${props.playing ? ' active' : ''}`);
|
||||
set(play, 'textContent', props.playing ? 'Pause' : 'Play');
|
||||
set(play, 'textContent', props.playing ? t('Pause') : t('Play'));
|
||||
for (const [node, active] of [
|
||||
[latest, props.mode === 'latest'],
|
||||
[play, props.playing],
|
||||
|
||||
+253
-142
@@ -8,40 +8,100 @@
|
||||
* strip and selection bar are this adapter's own keyed DOM. Source toggles
|
||||
* live on the data-panel row.
|
||||
*/
|
||||
import { formatNumber, msg, t, tn, translateKnown } from '../i18n/index.js';
|
||||
import { createRailCardBlocks } from './railCardBlocks.js';
|
||||
import { createRailCards } from './railCards.js';
|
||||
import { createImagerySplit } from './imagerySplit.js';
|
||||
import { createSlider } from './slider.js';
|
||||
import { createSegmentedControl } from './segmentedControl.js';
|
||||
import {
|
||||
PRODUCTS,
|
||||
hhmm,
|
||||
shortDay,
|
||||
wvsSnapshotUrl,
|
||||
} from '../layers/recentImagery/model.js';
|
||||
import { displayDay, displayMetres } from '../layers/recentImagery/display.js';
|
||||
import { formatQuantity } from './unitLabels.js';
|
||||
import { pointerOwnerName } from '../data/pointerOwnerNames.js';
|
||||
|
||||
const PANEL_ID = 'recent-imagery-panel';
|
||||
const OVERVIEW_MIN_BOX_KM = 25;
|
||||
const ESRI_NOTE = 'Imagery on Esri · Google 3D returns when cleared';
|
||||
const ESRI_NOTE = msg('Imagery on Esri · Google 3D returns when cleared');
|
||||
|
||||
// The layer keeps its notices and box refusals in English (AI tools read the
|
||||
// same snapshot); translate the ones we write, show anything else as it came.
|
||||
const LAYER_NOTICES = new Set([
|
||||
ESRI_NOTE,
|
||||
msg('Box and images cleared'),
|
||||
msg('Esri map unavailable · no swipe'),
|
||||
msg('Swipe needs a globe map'),
|
||||
msg('Imagery stays on Esri · CLEAR to use Google 3D'),
|
||||
// Box refusals the layer writes itself (layers/recentImagery/index.js).
|
||||
msg('Point the camera at the ground to use the view'),
|
||||
msg('That point cannot anchor a box'),
|
||||
]);
|
||||
// Refusals with a value in them (layers/recentImagery/model.js and
|
||||
// imageryBoxTool.js); fixed refusals there are msg() text for translateKnown.
|
||||
const TOO_LARGE = /^(Box|View) is ([\d,]+) km wide · limit ([\d,]+) km$/;
|
||||
const POLAR = /^Imagery stops at ±([\d.]+)° latitude$/;
|
||||
const POINTER_BUSY = /^(.+) is using the pointer — close it first$/;
|
||||
|
||||
/**
|
||||
* The notice line in the UI language: notices and box refusals arrive in
|
||||
* English. Exported for tests.
|
||||
* @param {string} text
|
||||
* @returns {string}
|
||||
*/
|
||||
export function localizeNotice(text) {
|
||||
if (!text) return '';
|
||||
if (LAYER_NOTICES.has(text)) return t(text);
|
||||
const polar = POLAR.exec(text);
|
||||
if (polar)
|
||||
return t('Imagery stops at ±{limit}° latitude', {
|
||||
limit: formatNumber(Number(polar[1]), {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
}),
|
||||
});
|
||||
const busy = POINTER_BUSY.exec(text);
|
||||
if (busy)
|
||||
return t('{owner} is using the pointer — close it first', {
|
||||
owner: translateKnown(pointerOwnerName(busy[1])),
|
||||
});
|
||||
const tooLarge = TOO_LARGE.exec(text);
|
||||
if (!tooLarge) return translateKnown(text);
|
||||
const values = {
|
||||
size: formatQuantity(Number(tooLarge[2].replace(/,/g, '')), 'km', {
|
||||
useGrouping: true,
|
||||
}),
|
||||
limit: formatQuantity(Number(tooLarge[3].replace(/,/g, '')), 'km', {
|
||||
useGrouping: true,
|
||||
}),
|
||||
};
|
||||
return tooLarge[1] === 'Box'
|
||||
? t('Box is {size} wide · limit {limit}', values)
|
||||
: t('View is {size} wide · limit {limit}', values);
|
||||
}
|
||||
const MODE_LABELS = [
|
||||
['image', 'IMAGE'],
|
||||
['basemap', 'VS BASEMAP'],
|
||||
['ab', 'A / B'],
|
||||
['image', msg('IMAGE')],
|
||||
['basemap', msg('VS BASEMAP')],
|
||||
['ab', msg('A / B')],
|
||||
];
|
||||
const START_HERE_TITLES = {
|
||||
clear: 'Newest low-cloud day for this box · scene cloud, not box cloud',
|
||||
cloudy: 'Newest day covering this box · cloudier than 20%',
|
||||
partial: 'Newest day with imagery for this box · partial coverage',
|
||||
overview: 'Newest daily overview for this box',
|
||||
clear: msg('Newest low-cloud day for this box · scene cloud, not box cloud'),
|
||||
cloudy: msg('Newest day covering this box · cloudier than 20%'),
|
||||
partial: msg('Newest day with imagery for this box · partial coverage'),
|
||||
overview: msg('Newest daily overview for this box'),
|
||||
};
|
||||
const START_HERE_REASONS = {
|
||||
clear: 'newest clear day',
|
||||
cloudy: 'newest day (cloudy)',
|
||||
partial: 'newest day (partial coverage)',
|
||||
overview: 'newest overview',
|
||||
clear: msg('newest clear day'),
|
||||
cloudy: msg('newest day (cloudy)'),
|
||||
partial: msg('newest day (partial coverage)'),
|
||||
overview: msg('newest overview'),
|
||||
};
|
||||
const PLACEHOLDERS = {
|
||||
empty: 'No imagery',
|
||||
error: 'Unavailable',
|
||||
present: 'Loading',
|
||||
empty: msg('No imagery'),
|
||||
error: msg('Unavailable'),
|
||||
present: msg('Loading'),
|
||||
};
|
||||
const KEY_STEPS = {
|
||||
ArrowLeft: (index) => index - 1,
|
||||
@@ -55,48 +115,57 @@ const appearedDocuments = new WeakSet();
|
||||
|
||||
const sensorLine = (product) =>
|
||||
PRODUCTS[product]
|
||||
? `${PRODUCTS[product].name} · ${PRODUCTS[product].resolutionM} m`
|
||||
? `${t(PRODUCTS[product].name)} · ${displayMetres(PRODUCTS[product].resolutionM)}`
|
||||
: product || '';
|
||||
const utcTime = (iso) => (hhmm(iso) ? `${hhmm(iso)}Z` : '');
|
||||
const longerSideKm = (size) =>
|
||||
Math.max(Number(size?.width) || 0, Number(size?.height) || 0);
|
||||
const kmText = (km) =>
|
||||
!Number.isFinite(km)
|
||||
? '?'
|
||||
: km >= 100
|
||||
? Math.round(km).toLocaleString('en-US')
|
||||
: km.toFixed(1);
|
||||
const kmText = (km) => {
|
||||
if (!Number.isFinite(km)) return '?';
|
||||
const digits = km >= 100 ? 0 : 1;
|
||||
return formatNumber(km, {
|
||||
minimumFractionDigits: digits,
|
||||
maximumFractionDigits: digits,
|
||||
});
|
||||
};
|
||||
|
||||
function coverageText(coverage) {
|
||||
if (coverage === 'full') return t('full', { context: 'coverage' });
|
||||
if (coverage === 'partial') return t('partial', { context: 'coverage' });
|
||||
return t('unknown');
|
||||
}
|
||||
|
||||
function cloudText(candidate) {
|
||||
if (candidate.thumbnail?.status === 'empty') return 'no imagery';
|
||||
if (!candidate.cloud) return 'cloud unknown';
|
||||
if (candidate.thumbnail?.status === 'empty') return t('no imagery');
|
||||
if (!candidate.cloud) return t('cloud unknown');
|
||||
const min = Math.round(candidate.cloud.min);
|
||||
const max = Math.round(candidate.cloud.max);
|
||||
return min === max ? `${min}% cloud` : `${min}–${max}% cloud`;
|
||||
return min === max
|
||||
? t('{percent}% cloud', { percent: min })
|
||||
: t('{min}–{max}% cloud', { min, max });
|
||||
}
|
||||
|
||||
function countText(snapshot) {
|
||||
if (!snapshot.box) return 'NO BOX';
|
||||
if (snapshot.searching) return 'SEARCHING';
|
||||
const count = snapshot.candidates.length;
|
||||
return `${count} DAY${count === 1 ? '' : 'S'}`;
|
||||
if (!snapshot.box) return t('NO BOX');
|
||||
if (snapshot.searching) return t('SEARCHING');
|
||||
return tn(snapshot.candidates.length, '{count} DAY', '{count} DAYS');
|
||||
}
|
||||
|
||||
/** The one-line hint under the strip: the next thing to do, per state. */
|
||||
function hintText(snapshot) {
|
||||
if (snapshot.zoomToFit) return 'Zoom in or draw a smaller box';
|
||||
if (!snapshot.box) return 'Select a box or use the view';
|
||||
if (snapshot.searching) return 'Searching the last 30 days';
|
||||
if (!snapshot.candidates.length) return 'No days to show for this box';
|
||||
if (snapshot.zoomToFit) return t('Zoom in or draw a smaller box');
|
||||
if (!snapshot.box) return t('Select a box or use the view');
|
||||
if (snapshot.searching) return t('Searching the last 30 days');
|
||||
if (!snapshot.candidates.length) return t('No days to show for this box');
|
||||
const { mode, pins, shown } = snapshot;
|
||||
if (shown.swipe !== 'none') return 'Drag the divider · SWAP trades sides';
|
||||
if (shown.swipe !== 'none') return t('Drag the divider · SWAP trades sides');
|
||||
if (mode === 'ab') {
|
||||
if (!pins.a.key && !pins.b.key)
|
||||
return '← → preview · A or B pins the focused day';
|
||||
return '← → preview the other side · A or B pins it';
|
||||
return t('← → preview · A or B pins the focused day');
|
||||
return t('← → preview the other side · A or B pins it');
|
||||
}
|
||||
if (pins.a.key) return 'S on another day replaces it · × unpins';
|
||||
return '← → preview · S shows the focused day';
|
||||
if (pins.a.key) return t('S on another day replaces it · × unpins');
|
||||
return t('← → preview · S shows the focused day');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -173,7 +242,7 @@ export function createRecentImageryPanel({
|
||||
|
||||
// ---- build: every block exists from the start, in its final order ----
|
||||
const root = el('section', 'recent-imagery-readout');
|
||||
root.setAttribute('aria-label', 'Recent imagery');
|
||||
root.setAttribute('aria-label', t('Recent imagery'));
|
||||
|
||||
const actionsHost = el('div', 'ri-block ri-actions-row', root);
|
||||
actionsHost.id = 'ri-actions';
|
||||
@@ -191,10 +260,15 @@ export function createRecentImageryPanel({
|
||||
noticeText.id = 'ri-notice-text';
|
||||
noticeText.setAttribute('role', 'status');
|
||||
noticeText.setAttribute('aria-live', 'polite');
|
||||
const zoomIn = el('button', 'data-toggle-chip ri-zoom-in', notice, 'ZOOM IN');
|
||||
const zoomIn = el(
|
||||
'button',
|
||||
'data-toggle-chip ri-zoom-in',
|
||||
notice,
|
||||
t('ZOOM IN'),
|
||||
);
|
||||
zoomIn.id = 'ri-zoom-in';
|
||||
zoomIn.type = 'button';
|
||||
zoomIn.title = 'Fly in until the view fits the 1,000 km limit';
|
||||
zoomIn.title = t('Fly in until the view fits the 1,000 km limit');
|
||||
|
||||
const strip = el('div', 'ri-block ri-strip', root);
|
||||
strip.id = 'ri-strip';
|
||||
@@ -203,7 +277,7 @@ export function createRecentImageryPanel({
|
||||
strip.setAttribute('aria-orientation', 'horizontal');
|
||||
strip.setAttribute(
|
||||
'aria-label',
|
||||
'Imagery days, newest first · arrows move, S or A and B pin',
|
||||
t('Imagery days, newest first · arrows move, S or A and B pin'),
|
||||
);
|
||||
strip.setAttribute('aria-keyshortcuts', 'A B S');
|
||||
const stripEmpty = el('div', 'ri-strip-empty', strip);
|
||||
@@ -213,21 +287,30 @@ export function createRecentImageryPanel({
|
||||
|
||||
const selection = el('section', 'ri-block ri-selection', root);
|
||||
selection.id = 'ri-selection';
|
||||
selection.setAttribute('aria-label', 'On the map');
|
||||
const modeGroup = el('div', 'ri-mode', selection);
|
||||
selection.setAttribute('aria-label', t('On the map'));
|
||||
const modeGroup = el('div', 'gev-segmented ri-mode', selection);
|
||||
modeGroup.id = 'ri-mode';
|
||||
modeGroup.setAttribute('role', 'radiogroup');
|
||||
modeGroup.setAttribute('aria-label', 'Mode');
|
||||
modeGroup.setAttribute('aria-label', t('Mode'));
|
||||
const modeButtons = new Map(
|
||||
MODE_LABELS.map(([mode, label]) => {
|
||||
const node = el('button', 'data-toggle-chip ri-mode-btn', modeGroup);
|
||||
const node = el('button', 'gev-segment ri-mode-btn', modeGroup);
|
||||
node.type = 'button';
|
||||
node.textContent = label;
|
||||
node.textContent = t(label);
|
||||
node.dataset.mode = mode;
|
||||
node.setAttribute('role', 'radio');
|
||||
return [mode, node];
|
||||
}),
|
||||
);
|
||||
const modeControl = createSegmentedControl({
|
||||
buttons: modeButtons.values(),
|
||||
valueOf: (button) => button.dataset.mode,
|
||||
onChange: (mode) => layer.setMode(mode),
|
||||
keyboard: 'arrows',
|
||||
keyTarget: modeGroup,
|
||||
readValue: () => snapshot.mode,
|
||||
listen,
|
||||
});
|
||||
const slotRows = {};
|
||||
for (const slotId of ['a', 'b']) {
|
||||
const row = el('div', 'ri-slot', selection);
|
||||
@@ -244,24 +327,25 @@ export function createRecentImageryPanel({
|
||||
const controls = el('div', 'ri-block ri-controls', root);
|
||||
controls.id = 'ri-controls';
|
||||
const opacityLabel = el('label', 'ri-opacity-label', controls);
|
||||
el('span', '', opacityLabel, 'OPACITY');
|
||||
el('span', '', opacityLabel, t('OPACITY'));
|
||||
const opacityValue = el('span', 'ri-opacity-value', opacityLabel, '100%');
|
||||
const opacity = el('input', 'ri-opacity', controls);
|
||||
opacity.id = 'ri-opacity';
|
||||
Object.assign(opacity, {
|
||||
type: 'range',
|
||||
const opacity = createSlider({
|
||||
documentRef: document,
|
||||
className: 'ri-opacity',
|
||||
min: '0',
|
||||
max: '100',
|
||||
step: '1',
|
||||
value: '100',
|
||||
ariaLabel: t('Imagery opacity'),
|
||||
});
|
||||
opacity.setAttribute('aria-label', 'Imagery opacity');
|
||||
opacity.id = 'ri-opacity';
|
||||
controls.appendChild(opacity);
|
||||
opacityLabel.htmlFor = 'ri-opacity';
|
||||
// Its slot is always there; it is only usable while a swipe is live.
|
||||
const swap = el('button', 'data-toggle-chip ri-swap', controls, 'SWAP');
|
||||
const swap = el('button', 'data-toggle-chip ri-swap', controls, t('SWAP'));
|
||||
swap.id = 'ri-swap';
|
||||
swap.type = 'button';
|
||||
swap.title = 'Trade the two sides of the divider';
|
||||
swap.title = t('Trade the two sides of the divider');
|
||||
const exportHost = el('div', 'ri-exports', controls);
|
||||
const exports = createRailCardBlocks({
|
||||
container: exportHost,
|
||||
@@ -272,7 +356,6 @@ export function createRecentImageryPanel({
|
||||
const detailsHost = el('div', 'ri-details', root);
|
||||
detailsHost.id = 'ri-details';
|
||||
let detailsOpen = false;
|
||||
let detailsShownOpen = false;
|
||||
const details = createRailCards({
|
||||
container: detailsHost,
|
||||
document,
|
||||
@@ -280,6 +363,8 @@ export function createRecentImageryPanel({
|
||||
onOpen: () => {
|
||||
detailsOpen = !detailsOpen;
|
||||
render();
|
||||
// After the render: preserveScroll() puts the old position back.
|
||||
if (detailsOpen) revealCard(container, detailsHost.children[0]);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -318,8 +403,8 @@ export function createRecentImageryPanel({
|
||||
actions: [
|
||||
{
|
||||
id: 'select-box',
|
||||
label: 'SELECT BOX',
|
||||
title: 'Drag a box on the map (Esc cancels)',
|
||||
label: t('SELECT BOX'),
|
||||
title: t('Drag a box on the map (Esc cancels)'),
|
||||
onClick: () => {
|
||||
exportError = null;
|
||||
if (tool?.isActive()) tool.cancel('toggle');
|
||||
@@ -328,8 +413,8 @@ export function createRecentImageryPanel({
|
||||
},
|
||||
{
|
||||
id: 'use-view',
|
||||
label: 'USE VIEW',
|
||||
title: 'Use the current view as the box',
|
||||
label: t('USE VIEW'),
|
||||
title: t('Use the current view as the box'),
|
||||
onClick: () => {
|
||||
exportError = null;
|
||||
layer.useCurrentView(viewer);
|
||||
@@ -337,8 +422,8 @@ export function createRecentImageryPanel({
|
||||
},
|
||||
{
|
||||
id: 'clear',
|
||||
label: 'CLEAR',
|
||||
title: 'Forget the box and its images',
|
||||
label: t('CLEAR', { context: 'action' }),
|
||||
title: t('Forget the box and its images'),
|
||||
disabled: !snapshot.box && !snapshot.boxError,
|
||||
onClick: () => {
|
||||
exportError = null;
|
||||
@@ -365,8 +450,9 @@ export function createRecentImageryPanel({
|
||||
// ---- notice -----------------------------------------------------------
|
||||
function renderNotice() {
|
||||
const warning = snapshot.boxError || snapshot.error || exportError;
|
||||
const text =
|
||||
warning || snapshot.notice || (snapshot.borrowedEsri ? ESRI_NOTE : '');
|
||||
const text = localizeNotice(
|
||||
warning || snapshot.notice || (snapshot.borrowedEsri ? ESRI_NOTE : ''),
|
||||
);
|
||||
set(noticeText, 'textContent', text);
|
||||
attribute(noticeText, 'title', text);
|
||||
toggle(notice, 'warn', Boolean(warning));
|
||||
@@ -388,7 +474,7 @@ export function createRecentImageryPanel({
|
||||
entry.thumb = el('div', 'ri-thumb', card);
|
||||
entry.placeholder = el('span', 'ri-thumb-text', entry.thumb);
|
||||
entry.flag = el('span', 'ri-card-flag', entry.thumb);
|
||||
entry.start = el('span', 'ri-card-start', entry.thumb, 'START HERE');
|
||||
entry.start = el('span', 'ri-card-start', entry.thumb, t('START HERE'));
|
||||
entry.date = el('div', 'ri-card-date', card);
|
||||
entry.sensor = el('div', 'ri-card-sensor', card);
|
||||
entry.cloud = el('div', 'ri-card-cloud', card);
|
||||
@@ -409,7 +495,7 @@ export function createRecentImageryPanel({
|
||||
const entry = cards.get(candidate.key);
|
||||
if (!entry) return;
|
||||
const { card } = entry;
|
||||
const day = shortDay(candidate.day);
|
||||
const day = displayDay(candidate.day);
|
||||
const ab = snapshot.mode === 'ab';
|
||||
set(card, 'id', `ri-card-${index}`);
|
||||
const focused = index === snapshot.focusIndex;
|
||||
@@ -432,13 +518,17 @@ export function createRecentImageryPanel({
|
||||
}
|
||||
if (entry.image) set(entry.image, 'hidden', !shown);
|
||||
set(entry.placeholder, 'hidden', shown);
|
||||
set(entry.placeholder, 'textContent', PLACEHOLDERS[status] || 'Checking');
|
||||
set(
|
||||
entry.placeholder,
|
||||
'textContent',
|
||||
PLACEHOLDERS[status] ? t(PLACEHOLDERS[status]) : t('Checking'),
|
||||
);
|
||||
if (entry.thumb.dataset.status !== status)
|
||||
entry.thumb.dataset.status = status;
|
||||
const flag = candidate.preview
|
||||
? 'PREVIEW'
|
||||
? t('PREVIEW')
|
||||
: candidate.pending
|
||||
? 'LOADING'
|
||||
? t('LOADING')
|
||||
: '';
|
||||
set(entry.flag, 'textContent', flag);
|
||||
set(entry.flag, 'hidden', !flag);
|
||||
@@ -448,8 +538,10 @@ export function createRecentImageryPanel({
|
||||
set(
|
||||
entry.start,
|
||||
'title',
|
||||
START_HERE_TITLES[snapshot.recommended.reason] ||
|
||||
'Newest day with imagery for this box',
|
||||
t(
|
||||
START_HERE_TITLES[snapshot.recommended.reason] ||
|
||||
msg('Newest day with imagery for this box'),
|
||||
),
|
||||
);
|
||||
set(entry.date, 'textContent', day);
|
||||
set(entry.sensor, 'textContent', sensorLine(candidate.product));
|
||||
@@ -459,7 +551,7 @@ export function createRecentImageryPanel({
|
||||
const chip = entry.chips[slotId];
|
||||
const live = slotId === 'a' || ab;
|
||||
const on = candidate.pinned === slotId && live;
|
||||
const label = slotId === 'a' ? (ab ? 'A' : 'SHOW') : 'B';
|
||||
const label = slotId === 'a' ? (ab ? 'A' : t('SHOW')) : 'B';
|
||||
set(chip, 'textContent', label);
|
||||
set(chip, 'disabled', empty || !live);
|
||||
toggle(chip, 'active', on);
|
||||
@@ -469,22 +561,29 @@ export function createRecentImageryPanel({
|
||||
attribute(
|
||||
chip,
|
||||
'aria-label',
|
||||
ab ? `Pin ${day} as ${slotId.toUpperCase()}` : `Show ${day}`,
|
||||
ab
|
||||
? t('Pin {day} as {slot}', { day, slot: slotId.toUpperCase() })
|
||||
: t('Show {day}', { day }),
|
||||
);
|
||||
}
|
||||
const state = candidate.pinned
|
||||
? ab
|
||||
? ` · pinned ${candidate.pinned.toUpperCase()}`
|
||||
? t('pinned {slot}', { slot: candidate.pinned.toUpperCase() })
|
||||
: candidate.pinned === 'a'
|
||||
? ' · shown'
|
||||
? t('shown')
|
||||
: ''
|
||||
: candidate.preview
|
||||
? ' · preview'
|
||||
? t('preview')
|
||||
: '';
|
||||
attribute(
|
||||
card,
|
||||
'aria-label',
|
||||
`${day} · ${sensorLine(candidate.product)} · ${cloudText(candidate)}${recommended ? ' · start here' : ''}${state}`,
|
||||
[
|
||||
day,
|
||||
sensorLine(candidate.product),
|
||||
cloudText(candidate),
|
||||
...[recommended ? t('start here') : '', state].filter(Boolean),
|
||||
].join(' · '),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -512,14 +611,14 @@ export function createRecentImageryPanel({
|
||||
candidates.length
|
||||
? ''
|
||||
: !snapshot.box
|
||||
? 'No box'
|
||||
? t('No box')
|
||||
: snapshot.searching
|
||||
? 'Searching'
|
||||
? t('Searching')
|
||||
: snapshot.hiddenCount
|
||||
? 'Every day is empty here'
|
||||
? t('Every day is empty here')
|
||||
: !snapshot.sources.hls && !snapshot.sources.viirs
|
||||
? 'Sources off'
|
||||
: 'No imagery',
|
||||
? t('Sources off')
|
||||
: t('No imagery'),
|
||||
);
|
||||
set(stripEmpty, 'hidden', candidates.length > 0);
|
||||
if (candidates[snapshot.focusIndex])
|
||||
@@ -581,12 +680,7 @@ export function createRecentImageryPanel({
|
||||
function renderSelection() {
|
||||
const { mode } = snapshot;
|
||||
set(selection.dataset, 'mode', mode);
|
||||
for (const [id, node] of modeButtons) {
|
||||
const on = id === mode;
|
||||
attribute(node, 'aria-checked', String(on));
|
||||
toggle(node, 'active', on);
|
||||
set(node, 'tabIndex', on ? 0 : -1);
|
||||
}
|
||||
modeControl.update(mode, { rovingFocus: true });
|
||||
const ab = mode === 'ab';
|
||||
for (const slotId of ['a', 'b']) {
|
||||
const { row, tag, value, unpin } = slotRows[slotId];
|
||||
@@ -596,18 +690,22 @@ export function createRecentImageryPanel({
|
||||
set(
|
||||
tag,
|
||||
'textContent',
|
||||
ab ? slotId.toUpperCase() : slotId === 'a' ? 'IMAGE' : 'VS',
|
||||
ab ? slotId.toUpperCase() : slotId === 'a' ? t('IMAGE') : t('VS'),
|
||||
);
|
||||
let text = 'Not set';
|
||||
if (basemapRow) text = 'Basemap';
|
||||
let text = t('Not set');
|
||||
if (basemapRow) text = t('Basemap');
|
||||
else if (image?.label)
|
||||
text = `${image.sourceOff ? 'Source off · ' : ''}${image.label}${
|
||||
text = [
|
||||
image.sourceOff ? t('Source off') : '',
|
||||
image.label,
|
||||
image.preview
|
||||
? ' · preview'
|
||||
? t('preview')
|
||||
: image.candidate && !image.drapable && !image.sourceOff
|
||||
? ' · loading'
|
||||
: ''
|
||||
}`;
|
||||
? t('loading')
|
||||
: '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ');
|
||||
set(value, 'textContent', text);
|
||||
attribute(value, 'title', text);
|
||||
const lit = basemapRow
|
||||
@@ -625,7 +723,9 @@ export function createRecentImageryPanel({
|
||||
attribute(
|
||||
unpin,
|
||||
'aria-label',
|
||||
ab ? `Unpin ${slotId.toUpperCase()}` : 'Unpin the image',
|
||||
ab
|
||||
? t('Unpin {slot}', { slot: slotId.toUpperCase() })
|
||||
: t('Unpin the image'),
|
||||
);
|
||||
set(unpin, 'title', unpin.getAttribute('aria-label'));
|
||||
}
|
||||
@@ -658,8 +758,12 @@ export function createRecentImageryPanel({
|
||||
type: 'actions',
|
||||
actions: ['a', 'b'].map((slotId) => ({
|
||||
id: `export-${slotId}`,
|
||||
label: ab ? `EXPORT ${slotId.toUpperCase()}` : 'EXPORT',
|
||||
title: `Download ${ab ? slotId.toUpperCase() : 'the image'} as a PNG`,
|
||||
label: ab
|
||||
? t('EXPORT {slot}', { slot: slotId.toUpperCase() })
|
||||
: t('EXPORT'),
|
||||
title: ab
|
||||
? t('Download {slot} as a PNG', { slot: slotId.toUpperCase() })
|
||||
: t('Download the image as a PNG'),
|
||||
disabled: !exportTarget(slotId) || exporting.has(slotId),
|
||||
onClick: () => void exportImage(slotId),
|
||||
})),
|
||||
@@ -682,7 +786,10 @@ export function createRecentImageryPanel({
|
||||
if (snapshot.box)
|
||||
lines.push({
|
||||
id: 'box',
|
||||
text: `Box ${kmText(snapshot.boxSizeKm?.width)} × ${kmText(snapshot.boxSizeKm?.height)} km`,
|
||||
text: t('Box {width} × {height} km', {
|
||||
width: kmText(snapshot.boxSizeKm?.width),
|
||||
height: kmText(snapshot.boxSizeKm?.height),
|
||||
}),
|
||||
});
|
||||
if (focus) {
|
||||
lines.push({ id: 'readout', text: snapshot.readout || '' });
|
||||
@@ -690,14 +797,24 @@ export function createRecentImageryPanel({
|
||||
if (focus.timeRange?.start) {
|
||||
const start = utcTime(focus.timeRange.start);
|
||||
const end = utcTime(focus.timeRange.end || focus.timeRange.start);
|
||||
times.push(`Acquired ${start === end ? start : `${start}–${end}`}`);
|
||||
times.push(
|
||||
t('Acquired {time}', {
|
||||
time: start === end ? start : `${start}–${end}`,
|
||||
}),
|
||||
);
|
||||
} else if (focus.thumbnail?.acquisitionTime)
|
||||
times.push(`Acquired ${utcTime(focus.thumbnail.acquisitionTime)}`);
|
||||
times.push(`Coverage ${focus.coverage || 'unknown'}`);
|
||||
times.push(
|
||||
t('Acquired {time}', {
|
||||
time: utcTime(focus.thumbnail.acquisitionTime),
|
||||
}),
|
||||
);
|
||||
times.push(
|
||||
t('Coverage {coverage}', { coverage: coverageText(focus.coverage) }),
|
||||
);
|
||||
lines.push({ id: 'acquired', text: times.join(' · ') });
|
||||
(focus.granules || []).forEach((granule, index) => {
|
||||
const cloud = Number.isFinite(granule.cloud)
|
||||
? ` · ${Math.round(granule.cloud)}% cloud`
|
||||
? ` · ${t('{percent}% cloud', { percent: Math.round(granule.cloud) })}`
|
||||
: '';
|
||||
lines.push({
|
||||
id: `granule-${index}`,
|
||||
@@ -707,7 +824,11 @@ export function createRecentImageryPanel({
|
||||
});
|
||||
}
|
||||
const reason = START_HERE_REASONS[snapshot.recommended?.reason];
|
||||
if (reason) lines.push({ id: 'start', text: `START HERE · ${reason}` });
|
||||
if (reason)
|
||||
lines.push({
|
||||
id: 'start',
|
||||
text: t('START HERE · {reason}', { reason: t(reason) }),
|
||||
});
|
||||
for (const [index, note] of snapshot.notes.entries())
|
||||
lines.push({ id: `note-${index}`, text: note, muted: true });
|
||||
if (
|
||||
@@ -718,12 +839,14 @@ export function createRecentImageryPanel({
|
||||
)
|
||||
lines.push({
|
||||
id: 'overview-scale',
|
||||
text: 'Daily overview shows little detail in a box this small',
|
||||
text: t('Daily overview shows little detail in a box this small'),
|
||||
muted: true,
|
||||
});
|
||||
lines.push({
|
||||
id: 'credit',
|
||||
text: 'Imagery: NASA GIBS and Worldview · HLS (Sentinel-2, Landsat 8/9) and VIIRS',
|
||||
text: t(
|
||||
'Imagery: NASA GIBS and Worldview · HLS (Sentinel-2, Landsat 8/9) and VIIRS',
|
||||
),
|
||||
muted: true,
|
||||
});
|
||||
return lines;
|
||||
@@ -735,9 +858,11 @@ export function createRecentImageryPanel({
|
||||
details.update([
|
||||
{
|
||||
id: 'details',
|
||||
title: 'Details',
|
||||
title: t('Details'),
|
||||
open: detailsOpen,
|
||||
compact: snapshot.focus ? snapshot.readout : 'Times, coverage, sources',
|
||||
compact: snapshot.focus
|
||||
? snapshot.readout
|
||||
: t('Times, coverage, sources'),
|
||||
blocks: [
|
||||
{ id: 'lines', type: 'lines', lines: detailLines() },
|
||||
{
|
||||
@@ -747,9 +872,9 @@ export function createRecentImageryPanel({
|
||||
{
|
||||
id: 'toggle-empty',
|
||||
label: showing
|
||||
? 'HIDE EMPTY DAYS'
|
||||
: `SHOW EMPTY DAYS · ${hidden}`,
|
||||
title: 'Days the probe found empty in this box',
|
||||
? t('HIDE EMPTY DAYS')
|
||||
: t('SHOW EMPTY DAYS · {count}', { count: hidden }),
|
||||
title: t('Days the probe found empty in this box'),
|
||||
disabled: !showing && !hidden,
|
||||
onClick: () => layer.setShowUnavailable(!showing),
|
||||
},
|
||||
@@ -758,9 +883,6 @@ export function createRecentImageryPanel({
|
||||
],
|
||||
},
|
||||
]);
|
||||
if (detailsOpen && !detailsShownOpen)
|
||||
revealCard(container, detailsHost.children[0]);
|
||||
detailsShownOpen = detailsOpen;
|
||||
}
|
||||
|
||||
// ---- divider ----------------------------------------------------------
|
||||
@@ -773,8 +895,10 @@ export function createRecentImageryPanel({
|
||||
const describe = (c) => (c ? `${sensorLine(c.product)} · ${c.day}` : '');
|
||||
// The two sides as [label, title, spoken name]; SWAP trades them.
|
||||
const sides = [
|
||||
basemap ? ['IMAGE', describe(a), 'image'] : ['A', describe(a), 'A'],
|
||||
basemap ? ['BASEMAP', 'The basemap', 'basemap'] : ['B', describe(b), 'B'],
|
||||
basemap ? [t('IMAGE'), describe(a), t('image')] : ['A', describe(a), 'A'],
|
||||
basemap
|
||||
? [t('BASEMAP'), t('The basemap'), t('basemap')]
|
||||
: ['B', describe(b), 'B'],
|
||||
];
|
||||
const [before, after] = swapped ? [sides[1], sides[0]] : sides;
|
||||
const signature = live
|
||||
@@ -799,10 +923,15 @@ export function createRecentImageryPanel({
|
||||
beforeTitle: before[1],
|
||||
afterTitle: after[1],
|
||||
ariaLabel: basemap
|
||||
? 'Recent imagery against the basemap divider'
|
||||
: 'Recent imagery A and B divider',
|
||||
? t('Recent imagery against the basemap divider')
|
||||
: t('Recent imagery A and B divider'),
|
||||
formatValueText: (leftPercent, rightPercent) =>
|
||||
`${before[2][0].toUpperCase()}${before[2].slice(1)} ${leftPercent} percent, ${after[2]} ${rightPercent} percent`,
|
||||
t('{before} {left} percent, {after} {right} percent', {
|
||||
before: `${before[2][0].toUpperCase()}${before[2].slice(1)}`,
|
||||
left: leftPercent,
|
||||
after: after[2],
|
||||
right: rightPercent,
|
||||
}),
|
||||
getViewportWidth: () =>
|
||||
Number(viewer?.scene?.canvas?.clientWidth) ||
|
||||
Number(document.documentElement?.clientWidth) ||
|
||||
@@ -895,7 +1024,9 @@ export function createRecentImageryPanel({
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (!destroyed)
|
||||
exportError = `Export failed · ${error?.message || error}`;
|
||||
exportError = t('Export failed · {error}', {
|
||||
error: error?.message || error,
|
||||
});
|
||||
return false;
|
||||
} finally {
|
||||
exporting.delete(slotId);
|
||||
@@ -941,11 +1072,6 @@ export function createRecentImageryPanel({
|
||||
strip.focus({ preventScroll: true });
|
||||
return;
|
||||
}
|
||||
const mode = target?.closest?.('.ri-mode-btn');
|
||||
if (mode) {
|
||||
layer.setMode(mode.dataset.mode);
|
||||
return;
|
||||
}
|
||||
if (target?.closest?.('.ri-swap') && !swap.disabled) {
|
||||
layer.swapSides?.();
|
||||
return;
|
||||
@@ -962,21 +1088,6 @@ export function createRecentImageryPanel({
|
||||
if (event.target === opacity) layer.setAlpha(Number(opacity.value) / 100);
|
||||
});
|
||||
|
||||
listen(modeGroup, 'keydown', (event) => {
|
||||
const order = MODE_LABELS.map(([mode]) => mode);
|
||||
const step =
|
||||
{ ArrowLeft: -1, ArrowUp: -1, ArrowRight: 1, ArrowDown: 1 }[event.key] ||
|
||||
0;
|
||||
if (!step) return;
|
||||
event.preventDefault();
|
||||
const next =
|
||||
order[
|
||||
(order.indexOf(snapshot.mode) + step + order.length) % order.length
|
||||
];
|
||||
layer.setMode(next);
|
||||
modeButtons.get(next)?.focus?.();
|
||||
});
|
||||
|
||||
listen(strip, 'keydown', (event) => {
|
||||
const total = snapshot.candidates.length;
|
||||
const index = snapshot.focusIndex || 0;
|
||||
|
||||
@@ -412,7 +412,7 @@ test('the body is a fixed stack of seven blocks in a fixed order, each with a fi
|
||||
assert.match(rule('.recent-imagery-readout .ri-card'), /height: 112px/);
|
||||
assert.match(
|
||||
rule('.recent-imagery-readout .ri-selection'),
|
||||
/grid-template-rows: 20px 20px 20px/,
|
||||
/grid-template-rows: 26px 20px 20px/,
|
||||
);
|
||||
assert.match(rule('.recent-imagery-readout .ri-slot'), /height: 20px/);
|
||||
assert.match(rule('.recent-imagery-readout .ri-controls'), /height: 22px/);
|
||||
@@ -445,7 +445,7 @@ test('no control changes place in the tree, no block is hidden and every fixed-h
|
||||
/**
|
||||
* Every block that must keep its height: the node carrying the class, that
|
||||
* class, and the rule it gets its height from. The mode row is the first
|
||||
* 20 px track of the selection grid. The details header has no height of
|
||||
* 26 px track of the selection grid. The details header has no height of
|
||||
* its own: it is the last block, so it moves nothing below it, and its
|
||||
* title is held to one line.
|
||||
*/
|
||||
@@ -491,7 +491,7 @@ test('no control changes place in the tree, no block is hidden and every fixed-h
|
||||
mode.parentNode.children[0] === mode ? mode.parentNode : null,
|
||||
'ri-selection',
|
||||
readout('.ri-selection'),
|
||||
/grid-template-rows: 20px 20px 20px/,
|
||||
/grid-template-rows: 26px 20px 20px/,
|
||||
],
|
||||
'ri-slot-a': [
|
||||
f.byId('ri-slot-a'),
|
||||
@@ -646,7 +646,10 @@ test('cards carry thumbnail, date, sensor, cloud, START HERE and PREVIEW; the ch
|
||||
f.layer.focus(1);
|
||||
const s18 = f.card(S18);
|
||||
assert.equal(f.part(s18, 'ri-card-date').textContent, 'Sep 18');
|
||||
assert.equal(f.part(s18, 'ri-card-sensor').textContent, 'Sentinel-2 · 30 m');
|
||||
assert.equal(
|
||||
f.part(s18, 'ri-card-sensor').textContent,
|
||||
'Sentinel-2 · 30\u00a0m',
|
||||
);
|
||||
assert.equal(f.part(s18, 'ri-card-cloud').textContent, '12% cloud');
|
||||
assert.equal(f.part(s18, 'ri-card-start').hidden, false);
|
||||
assert.match(f.part(s18, 'ri-card-start').title, /Newest low-cloud day/);
|
||||
@@ -658,11 +661,11 @@ test('cards carry thumbnail, date, sensor, cloud, START HERE and PREVIEW; the ch
|
||||
assert.equal(f.part(f.card(V21), 'ri-thumb-text').textContent, 'Checking');
|
||||
assert.equal(
|
||||
f.part(f.card(V21), 'ri-card-sensor').textContent,
|
||||
'Daily overview · 250 m',
|
||||
'Daily overview · 250\u00a0m',
|
||||
);
|
||||
assert.equal(
|
||||
f.part(f.card(L16), 'ri-card-sensor').textContent,
|
||||
'Landsat 8/9 · 30 m',
|
||||
'Landsat 8/9 · 30\u00a0m',
|
||||
);
|
||||
// IMAGE: one SHOW chip; the B chip keeps its box but is invisible.
|
||||
const [a, b] = [f.chip(S18, 'a'), f.chip(S18, 'b')];
|
||||
@@ -734,7 +737,10 @@ test('the selection bar reads the mode, both rows and a preview, with × reserve
|
||||
['A / B', 'radio', 'false'],
|
||||
],
|
||||
);
|
||||
assert.equal(rowText(f, 'a'), 'IMAGE | Sep 18 · Sentinel-2 · 30 m · preview');
|
||||
assert.equal(
|
||||
rowText(f, 'a'),
|
||||
'IMAGE | Sep 18 · Sentinel-2 · 30\u00a0m · preview',
|
||||
);
|
||||
assert.equal(f.byId('ri-slot-a').dataset.state, 'preview');
|
||||
assert.equal(rowText(f, 'b'), 'VS | Basemap');
|
||||
assert.equal(f.byId('ri-slot-b').classList.contains('lit'), false, 'dimmed');
|
||||
@@ -748,7 +754,7 @@ test('the selection bar reads the mode, both rows and a preview, with × reserve
|
||||
[true, true, '×'],
|
||||
);
|
||||
f.key('s');
|
||||
assert.equal(rowText(f, 'a'), 'IMAGE | Sep 18 · Sentinel-2 · 30 m');
|
||||
assert.equal(rowText(f, 'a'), 'IMAGE | Sep 18 · Sentinel-2 · 30\u00a0m');
|
||||
assert.equal(f.byId('ri-slot-a').dataset.state, 'pinned');
|
||||
assert.equal(unpinA.disabled, false);
|
||||
assert.equal(unpinA.getAttribute('aria-label'), 'Unpin the image');
|
||||
@@ -757,12 +763,12 @@ test('the selection bar reads the mode, both rows and a preview, with × reserve
|
||||
assert.equal(modes[1].getAttribute('aria-checked'), 'true');
|
||||
assert.equal(f.byId('ri-slot-b').classList.contains('lit'), true, 'lit');
|
||||
modes[2].click();
|
||||
assert.equal(rowText(f, 'a'), 'A | Sep 18 · Sentinel-2 · 30 m');
|
||||
assert.equal(rowText(f, 'a'), 'A | Sep 18 · Sentinel-2 · 30\u00a0m');
|
||||
assert.equal(rowText(f, 'b'), 'B | Not set');
|
||||
assert.equal(f.byId('ri-slot-b').dataset.state, 'empty');
|
||||
assert.equal(f.byId('ri-unpin-b').classList.contains('is-reserved'), true);
|
||||
f.chip(L16, 'b').click();
|
||||
assert.equal(rowText(f, 'b'), 'B | Sep 16 · Landsat 8/9 · 30 m');
|
||||
assert.equal(rowText(f, 'b'), 'B | Sep 16 · Landsat 8/9 · 30\u00a0m');
|
||||
f.byId('ri-unpin-b').click();
|
||||
assert.equal(f.snap().pins.b.key, null);
|
||||
unpinA.click();
|
||||
@@ -879,7 +885,10 @@ test('the notice line shows the refusal, then errors, then CLEAR, then the Esri
|
||||
);
|
||||
assert.equal(notice.classList.contains('info'), true);
|
||||
f.layer.setBox({ west: 0, south: 0, east: 20, north: 20 });
|
||||
assert.equal(noticeText.textContent, 'Box is 2,226 km wide · limit 1,000 km');
|
||||
assert.equal(
|
||||
noticeText.textContent,
|
||||
'Box is 2,226\u00a0km wide · limit 1,000\u00a0km',
|
||||
);
|
||||
assert.equal(notice.classList.contains('warn'), true);
|
||||
assert.equal(hint.textContent, 'Zoom in or draw a smaller box');
|
||||
f.layer.setBox(BOX);
|
||||
@@ -929,7 +938,7 @@ test('an oversized box offers ZOOM IN in a fixed slot at the end of the notice l
|
||||
assert.deepEqual(reserved(), [false, false, 'false', true]);
|
||||
assert.equal(
|
||||
f.byId('ri-notice-text').textContent,
|
||||
'Box is 2,226 km wide · limit 1,000 km',
|
||||
'Box is 2,226\u00a0km wide · limit 1,000\u00a0km',
|
||||
);
|
||||
assert.equal(f.byId('ri-hint').textContent, 'Zoom in or draw a smaller box');
|
||||
assert.equal(zoom.title, 'Fly in until the view fits the 1,000 km limit');
|
||||
@@ -998,7 +1007,10 @@ test('the divider exists only while a swipe is live, labelled A / B or IMAGE / B
|
||||
[split.options.beforeLabel, split.options.afterLabel],
|
||||
['A', 'B'],
|
||||
);
|
||||
assert.equal(split.options.afterTitle, 'Landsat 8/9 · 30 m · 2026-09-16');
|
||||
assert.equal(
|
||||
split.options.afterTitle,
|
||||
'Landsat 8/9 · 30\u00a0m · 2026-09-16',
|
||||
);
|
||||
split.options.onChange(0.3);
|
||||
assert.equal(f.snap().split, 0.3);
|
||||
assert.deepEqual(directions(), ['left', 'right']);
|
||||
@@ -1015,7 +1027,7 @@ test('the divider exists only while a swipe is live, labelled A / B or IMAGE / B
|
||||
assert.deepEqual(labels(), ['B', 'A']);
|
||||
assert.equal(
|
||||
f.splits.at(-1).options.beforeTitle,
|
||||
'Landsat 8/9 · 30 m · 2026-09-16',
|
||||
'Landsat 8/9 · 30\u00a0m · 2026-09-16',
|
||||
);
|
||||
assert.equal(f.splits.at(-1).options.initialValue, 0.3);
|
||||
assert.deepEqual(directions(), ['right', 'left']);
|
||||
@@ -1135,6 +1147,29 @@ test('the body scroll position survives renders even when DOM mutations reset it
|
||||
assert.equal(f.body.scrollTop, 120);
|
||||
});
|
||||
|
||||
test('opening DETAILS scrolls its card into view, and closing it does not scroll', async () => {
|
||||
const f = fixture();
|
||||
await f.ready();
|
||||
// The body is 100 px high and scrolled 40 px; the card opens 150 px down.
|
||||
f.body.scrollTop = 40;
|
||||
f.body.clientHeight = 100;
|
||||
f.body.getBoundingClientRect = () => ({ top: 0 });
|
||||
const header = f
|
||||
.byId('ri-details')
|
||||
.find((node) => node.classList.contains('rail-card-header'));
|
||||
const card = header.parentNode;
|
||||
card.getBoundingClientRect = () => ({
|
||||
top: 150,
|
||||
height: card.dataset.open === 'true' ? 60 : 0,
|
||||
});
|
||||
header.click();
|
||||
assert.equal(card.dataset.open, 'true');
|
||||
assert.equal(f.body.scrollTop, 150);
|
||||
header.click();
|
||||
assert.equal(card.dataset.open, 'false');
|
||||
assert.equal(f.body.scrollTop, 150);
|
||||
});
|
||||
|
||||
test('destroy returns every listener, the divider and the panel state', async () => {
|
||||
const f = fixture();
|
||||
await f.ready();
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
// Box-tool and model refusals on the Recent Imagery notice line are
|
||||
// shown in the UI language; the layer keeps them in English.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import { setLocale } from '../i18n/index.js';
|
||||
import { validateBox } from '../layers/recentImagery/model.js';
|
||||
import { localizeNotice } from './recentImagery.js';
|
||||
|
||||
const REFUSALS = [
|
||||
'Drag to size the box', // imageryBoxTool.js, click without drag
|
||||
'Press on the ground, not the sky', // imageryBoxTool.js
|
||||
'draw is using the pointer — close it first', // imageryBoxTool.js, pointer busy
|
||||
'Point the camera at the ground to use the view', // layers/recentImagery/index.js
|
||||
'That point cannot anchor a box', // layers/recentImagery/index.js
|
||||
...[
|
||||
{ west: 170, south: 10, east: -170, north: 20 }, // dateline
|
||||
{ west: 10, south: 80, east: 20, north: 89 }, // polar
|
||||
{ west: 10, south: 10, east: 10, north: 20 }, // degenerate
|
||||
{ west: 10, south: 10, east: 200, north: 20 }, // longitude range
|
||||
{ west: Number.NaN, south: 10, east: 20, north: 20 }, // not finite
|
||||
].map((box) => {
|
||||
const result = validateBox(box);
|
||||
assert.equal(result.ok, false);
|
||||
return result.message;
|
||||
}),
|
||||
];
|
||||
|
||||
// The pointer-busy refusal names the owner by its internal id; the notice
|
||||
// shows the tool's name instead, in English too.
|
||||
const SHOWN_EN = new Map([
|
||||
[
|
||||
'draw is using the pointer — close it first',
|
||||
'Draw is using the pointer — close it first',
|
||||
],
|
||||
]);
|
||||
|
||||
test('en: refusals stay English', () => {
|
||||
setLocale('en');
|
||||
for (const text of REFUSALS)
|
||||
assert.equal(localizeNotice(text), SHOWN_EN.get(text) ?? text);
|
||||
assert.ok(REFUSALS.includes('Imagery stops at ±85.05° latitude'));
|
||||
});
|
||||
|
||||
test('E3/E12: the pointer owner is named by its tool, never by its id', () => {
|
||||
const owners = {
|
||||
en: {
|
||||
draw: 'Draw',
|
||||
directions: 'Directions',
|
||||
'recent-imagery-box': 'Recent imagery',
|
||||
},
|
||||
ru: {
|
||||
draw: 'Рисование',
|
||||
directions: 'Маршруты',
|
||||
'recent-imagery-box': 'Свежие снимки',
|
||||
},
|
||||
es: {
|
||||
draw: 'Dibujo',
|
||||
directions: 'Indicaciones',
|
||||
'recent-imagery-box': 'Imágenes recientes',
|
||||
},
|
||||
};
|
||||
try {
|
||||
for (const [locale, names] of Object.entries(owners)) {
|
||||
setLocale(locale);
|
||||
for (const [id, name] of Object.entries(names)) {
|
||||
const shown = localizeNotice(
|
||||
`${id} is using the pointer — close it first`,
|
||||
);
|
||||
assert.ok(shown.includes(name), `${locale} ${id}: ${shown}`);
|
||||
assert.ok(!shown.includes(id), `${locale} ${id} leaked: ${shown}`);
|
||||
}
|
||||
}
|
||||
setLocale('en');
|
||||
assert.equal(
|
||||
localizeNotice('measure is using the pointer — close it first'),
|
||||
'measure is using the pointer — close it first',
|
||||
'an unregistered owner falls back to its id',
|
||||
);
|
||||
} finally {
|
||||
setLocale('en');
|
||||
}
|
||||
});
|
||||
|
||||
for (const locale of ['es', 'ru']) {
|
||||
test(`${locale}: box-tool and model refusals are translated`, () => {
|
||||
setLocale(locale);
|
||||
try {
|
||||
for (const text of REFUSALS)
|
||||
assert.notEqual(localizeNotice(text), text, `untranslated: ${text}`);
|
||||
assert.match(
|
||||
localizeNotice('Imagery stops at ±85.05° latitude'),
|
||||
/85,05/,
|
||||
);
|
||||
assert.doesNotMatch(
|
||||
localizeNotice('draw is using the pointer — close it first'),
|
||||
/\bdraw\b/,
|
||||
);
|
||||
} finally {
|
||||
setLocale('en');
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -69,10 +69,17 @@ export function layoutRightPanelRail({
|
||||
// A collapse may schedule one follow-up, which only measures and allocates.
|
||||
const isCollapseRetry = pendingCollapseRetries.delete(stack);
|
||||
|
||||
// A floating (lifted-out) panel is not laid out by the rail.
|
||||
// Other CSS may hide a panel, such as an event view: it is not laid out.
|
||||
// Exclusive presentation hides collapsed panels itself; those stay in the
|
||||
// rail so they can be restored.
|
||||
const hiddenByRail = (panel) =>
|
||||
stack.classList.contains('layout-exclusive') &&
|
||||
panel.classList.contains('collapsed');
|
||||
const panels = [...stack.children].filter(
|
||||
(panel) =>
|
||||
panel.matches('[data-panel-id]:not(.panel-floating)') && !panel.hidden,
|
||||
panel.matches('[data-panel-id]') &&
|
||||
!panel.hidden &&
|
||||
(hiddenByRail(panel) || getComputedStyle(panel).display !== 'none'),
|
||||
);
|
||||
if (!hud.visible || hud.variant !== 'tactical') {
|
||||
for (const panel of panels.filter((item) =>
|
||||
@@ -84,7 +91,9 @@ export function layoutRightPanelRail({
|
||||
}
|
||||
// Normalize restored state and theme entry without overwriting saved panel
|
||||
// preferences. This marker is distinct from Tactical's space-based collapse.
|
||||
if (hud.variant === 'cyber') {
|
||||
// Phones present the rail as tab sheets that show several panels at once.
|
||||
const isMobile = windowRef.matchMedia('(max-width: 720px)').matches;
|
||||
if (hud.variant === 'cyber' && !isMobile) {
|
||||
const expanded = panels.filter(
|
||||
(panel) => !panel.classList.contains('collapsed'),
|
||||
);
|
||||
@@ -104,16 +113,19 @@ export function layoutRightPanelRail({
|
||||
onCollapse(panel);
|
||||
}
|
||||
}
|
||||
const isMobile = windowRef.matchMedia('(max-width: 720px)').matches;
|
||||
const hasExpandedPanel = panels.some(
|
||||
(panel) =>
|
||||
!panel.classList.contains('collapsed') &&
|
||||
(!isMobile || panel.id !== 'pp-toggles'),
|
||||
);
|
||||
const exclusive = shouldHideCollapsedRightPanels({
|
||||
hudVariant: hud.variant,
|
||||
hasExpandedPanel,
|
||||
});
|
||||
// Phones present the rail as tab sheets (mobileShell.js), which choose what
|
||||
// shows; hiding collapsed siblings would empty a sheet and its a11y tree.
|
||||
const exclusive =
|
||||
!isMobile &&
|
||||
shouldHideCollapsedRightPanels({
|
||||
hudVariant: hud.variant,
|
||||
hasExpandedPanel,
|
||||
});
|
||||
stack.classList.toggle('layout-exclusive', exclusive);
|
||||
for (const panel of panels) {
|
||||
if (exclusive && panel.classList.contains('collapsed'))
|
||||
|
||||
+19
-8
@@ -1,4 +1,5 @@
|
||||
/** Own Scene panel listeners and presentation through project reads and actions. */
|
||||
import { t, msg } from '../i18n/index.js';
|
||||
import {
|
||||
sceneElements,
|
||||
renderSceneOptions,
|
||||
@@ -45,7 +46,7 @@ export class SceneControls {
|
||||
this.listen(elements.start, 'click', () =>
|
||||
this.run('start', this.read().selectedSceneId),
|
||||
);
|
||||
this.listen(elements.stop, 'click', () => this.run('stop', 'Stopped'));
|
||||
this.listen(elements.stop, 'click', () => this.run('stop', msg('Stopped')));
|
||||
this.listen(elements.import, 'click', () => elements.file?.click());
|
||||
this.listen(elements.file, 'change', async () => {
|
||||
const file = elements.file?.files?.[0];
|
||||
@@ -57,7 +58,7 @@ export class SceneControls {
|
||||
if (!this.destroyed) elements.file.value = '';
|
||||
});
|
||||
if (!subscribe) {
|
||||
this.updateStatus('Ready');
|
||||
this.updateStatus(t('Ready'));
|
||||
this.setProgress(0);
|
||||
this.setButtons(false);
|
||||
}
|
||||
@@ -123,7 +124,7 @@ export class SceneControls {
|
||||
const generation = ++this.actionGeneration;
|
||||
const failed = () => {
|
||||
if (!this.destroyed && generation === this.actionGeneration)
|
||||
this.updateStatus('Scene action failed');
|
||||
this.updateStatus(t('Scene action failed'));
|
||||
};
|
||||
try {
|
||||
const result = this.actions[action](...args);
|
||||
@@ -140,8 +141,8 @@ export class SceneControls {
|
||||
createScene() {
|
||||
if (this.destroyed) return;
|
||||
const name = window.prompt(
|
||||
'New scene name',
|
||||
`Scene ${this.read().scenes.length + 1}`,
|
||||
t('New scene name'),
|
||||
t('Scene {n}', { n: this.read().scenes.length + 1 }),
|
||||
);
|
||||
if (name) this.run('create', name);
|
||||
}
|
||||
@@ -152,7 +153,12 @@ export class SceneControls {
|
||||
const scene = state.scenes.find(
|
||||
(item) => item.id === state.selectedSceneId,
|
||||
);
|
||||
if (scene && window.confirm(`Delete scene "${scene.title}" and all shots?`))
|
||||
if (
|
||||
scene &&
|
||||
window.confirm(
|
||||
t('Delete scene "{scene}" and all shots?', { scene: scene.title }),
|
||||
)
|
||||
)
|
||||
this.run('deleteScene');
|
||||
}
|
||||
|
||||
@@ -160,7 +166,12 @@ export class SceneControls {
|
||||
if (this.destroyed) return;
|
||||
const scene = this.read().scenes.find((item) => item.id === sceneId);
|
||||
const shot = scene?.shots.find((item) => item.id === shotId);
|
||||
if (shot && window.confirm(`Delete shot "${shot.title}"?`))
|
||||
if (
|
||||
shot &&
|
||||
window.confirm(
|
||||
t('Delete shot "{shot}"?', { shot: shot.displayTitle || shot.title }),
|
||||
)
|
||||
)
|
||||
this.run('deleteShot', sceneId, shotId);
|
||||
}
|
||||
|
||||
@@ -215,7 +226,7 @@ export class SceneControls {
|
||||
} else if (!this.destroyed && !this.playbackKeyRemover) {
|
||||
const onKeyDown = (event) => {
|
||||
if (!this.destroyed && event.key === 'Escape' && this.read().running)
|
||||
this.run('stop', 'Stopped (Esc)');
|
||||
this.run('stop', msg('Stopped (Esc)'));
|
||||
};
|
||||
document.addEventListener('keydown', onKeyDown);
|
||||
this.playbackKeyRemover = () =>
|
||||
|
||||
+63
-14
@@ -1,4 +1,27 @@
|
||||
/** Scene panel elements and text-only project presentation. */
|
||||
import { formatNumber, msg, t } from '../i18n/index.js';
|
||||
import { createActionButton } from './actionButton.js';
|
||||
|
||||
// Labels for what a shot stores; anything else shows as stored. Style names
|
||||
// match STYLE_STATUS_LABELS in visualPresets.js, which this package cannot
|
||||
// import (it pulls in the shaders).
|
||||
const STYLE_LABELS = Object.freeze({
|
||||
normal: msg('NORMAL'),
|
||||
retro: msg('CRT'),
|
||||
surveillance: msg('NVG'),
|
||||
thermal: msg('FLIR'),
|
||||
anime: msg('ANIME'),
|
||||
noir: msg('NOIR'),
|
||||
snow: msg('SNOW'),
|
||||
});
|
||||
|
||||
const DETECTION_MODE_LABELS = Object.freeze({
|
||||
OFF: msg('OFF'),
|
||||
SPARSE: msg('SPARSE'),
|
||||
BALANCED: msg('BALANCED'),
|
||||
DENSE: msg('DENSE'),
|
||||
});
|
||||
|
||||
export function sceneElements(root = document) {
|
||||
const ids = {
|
||||
panel: 'scene-panel',
|
||||
@@ -47,11 +70,16 @@ export function renderSceneShots(
|
||||
if (!scene || scene.shots.length === 0) {
|
||||
const empty = document.createElement('div');
|
||||
empty.className = 'scene-shot-empty';
|
||||
empty.textContent = 'No shots yet. Use CAPTURE SHOT to save current look.';
|
||||
empty.textContent = t(
|
||||
'No shots yet. Use CAPTURE SHOT to save current look.',
|
||||
);
|
||||
element.appendChild(empty);
|
||||
return;
|
||||
}
|
||||
for (const shot of scene.shots) {
|
||||
// Built-in titles arrive localized as displayTitle; the stored title
|
||||
// stays English, so a rename happens only when the shown text changes.
|
||||
const shownTitle = shot.displayTitle || shot.title;
|
||||
const row = document.createElement('div');
|
||||
row.className = 'scene-shot-row';
|
||||
row.dataset.sceneShotId = shot.id;
|
||||
@@ -60,23 +88,23 @@ export function renderSceneShots(
|
||||
top.className = 'scene-shot-top';
|
||||
const label = document.createElement('div');
|
||||
label.className = 'scene-shot-label';
|
||||
label.textContent = shot.title;
|
||||
label.title = 'Double-click to rename';
|
||||
label.textContent = shownTitle;
|
||||
label.title = t('Double-click to rename');
|
||||
listen(label, 'click', () => select(shot.id));
|
||||
listen(label, 'dblclick', () => {
|
||||
if (label.children.length) return;
|
||||
const input = document.createElement('input');
|
||||
input.type = 'text';
|
||||
input.className = 'scene-shot-rename';
|
||||
input.setAttribute('aria-label', 'Shot name');
|
||||
input.value = shot.title;
|
||||
input.setAttribute('aria-label', t('Shot name'));
|
||||
input.value = shownTitle;
|
||||
let finished = false;
|
||||
const finish = (save) => {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
const title = input.value.trim();
|
||||
label.textContent = shot.title;
|
||||
if (save && title && title !== shot.title)
|
||||
label.textContent = shownTitle;
|
||||
if (save && title && title !== shownTitle)
|
||||
rename(scene.id, shot.id, title);
|
||||
};
|
||||
listen(input, 'keydown', (event) => {
|
||||
@@ -94,13 +122,18 @@ export function renderSceneShots(
|
||||
});
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'scene-shot-actions';
|
||||
const loadButton = document.createElement('button');
|
||||
loadButton.className = 'scene-shot-btn';
|
||||
loadButton.textContent = 'LOAD';
|
||||
const loadButton = createActionButton({
|
||||
label: t('LOAD'),
|
||||
className: 'scene-shot-btn',
|
||||
size: 'compact',
|
||||
});
|
||||
listen(loadButton, 'click', () => load(scene.id, shot.id));
|
||||
const deleteButton = document.createElement('button');
|
||||
deleteButton.className = 'scene-shot-btn scene-shot-danger';
|
||||
deleteButton.textContent = 'DEL';
|
||||
const deleteButton = createActionButton({
|
||||
label: t('DEL'),
|
||||
className: 'scene-shot-btn scene-shot-danger',
|
||||
size: 'compact',
|
||||
variant: 'danger',
|
||||
});
|
||||
listen(deleteButton, 'click', () => remove(scene.id, shot.id));
|
||||
actions.appendChild(loadButton);
|
||||
actions.appendChild(deleteButton);
|
||||
@@ -110,7 +143,23 @@ export function renderSceneShots(
|
||||
meta.className = 'scene-shot-meta';
|
||||
const mode = shot.visual?.detection?.mode || 'OFF';
|
||||
const style = shot.visual?.style || 'normal';
|
||||
meta.textContent = `${style.toUpperCase()} · ${mode} · ${shot.durationSec.toFixed(1)}s + ${shot.holdSec.toFixed(1)}s`;
|
||||
const styleLabel = STYLE_LABELS[style]
|
||||
? t(STYLE_LABELS[style])
|
||||
: style.toUpperCase();
|
||||
const modeLabel = DETECTION_MODE_LABELS[mode]
|
||||
? t(DETECTION_MODE_LABELS[mode])
|
||||
: mode;
|
||||
const seconds = (value) =>
|
||||
formatNumber(value, {
|
||||
minimumFractionDigits: 1,
|
||||
maximumFractionDigits: 1,
|
||||
});
|
||||
// English keeps its compact "4.0s + 0.9s"; other languages space the unit.
|
||||
const timing = t('{duration}s + {hold}s', {
|
||||
duration: seconds(shot.durationSec),
|
||||
hold: seconds(shot.holdSec),
|
||||
});
|
||||
meta.textContent = `${styleLabel} · ${modeLabel} · ${timing}`;
|
||||
row.appendChild(top);
|
||||
row.appendChild(meta);
|
||||
element.appendChild(row);
|
||||
|
||||
+69
-7
@@ -1,3 +1,6 @@
|
||||
import { t, tn } from '../i18n/index.js';
|
||||
import { createActionButton } from './actionButton.js';
|
||||
|
||||
/** Small owned modal for scene authoring and import review; text never becomes markup. */
|
||||
export function createSceneDialog(title, onClose) {
|
||||
const dialog = document.createElement('dialog');
|
||||
@@ -79,10 +82,72 @@ export function createSceneDialog(title, onClose) {
|
||||
});
|
||||
if (multiline) node.rows = 9;
|
||||
wrapper.append(node);
|
||||
if (type === 'file') fileChooser(wrapper, node);
|
||||
body.append(wrapper);
|
||||
return node;
|
||||
}
|
||||
button('Cancel', onClose);
|
||||
/**
|
||||
* The browser draws a file input's button and "no file" text in its own
|
||||
* language. Stretch the native input, transparent, over the whole row (so
|
||||
* click, focus and drops stay native) and draw translated text under it.
|
||||
*/
|
||||
function fileChooser(wrapper, node) {
|
||||
wrapper.style.position = 'relative';
|
||||
Object.assign(node.style, {
|
||||
position: 'absolute',
|
||||
inset: '0',
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
margin: '0',
|
||||
padding: '0',
|
||||
border: '0',
|
||||
opacity: '0',
|
||||
cursor: 'pointer',
|
||||
zIndex: '1',
|
||||
});
|
||||
const row = document.createElement('span');
|
||||
row.setAttribute('aria-hidden', 'true');
|
||||
Object.assign(row.style, {
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: '10px',
|
||||
margin: '6px 0 14px',
|
||||
padding: '7px',
|
||||
background: '#10242e',
|
||||
border: '1px solid #397080',
|
||||
});
|
||||
const chooser = document.createElement('span');
|
||||
chooser.textContent = t('Choose files');
|
||||
Object.assign(chooser.style, {
|
||||
padding: '3px 9px',
|
||||
border: '1px solid #397080',
|
||||
borderRadius: '3px',
|
||||
background: '#08141e',
|
||||
cursor: 'pointer',
|
||||
});
|
||||
const chosen = document.createElement('span');
|
||||
const showChosen = () => {
|
||||
const count = node.files?.length || 0;
|
||||
// One file shows its name, like the browser's own picker did.
|
||||
chosen.textContent =
|
||||
count === 1
|
||||
? node.files[0].name
|
||||
: count
|
||||
? tn(count, '{count} file selected', '{count} files selected')
|
||||
: t('No file chosen');
|
||||
};
|
||||
showChosen();
|
||||
row.append(chooser, chosen);
|
||||
wrapper.append(row);
|
||||
listen(node, 'change', showChosen);
|
||||
listen(node, 'focus', () => {
|
||||
chooser.style.outline = '2px solid #e3faff';
|
||||
});
|
||||
listen(node, 'blur', () => {
|
||||
chooser.style.outline = '';
|
||||
});
|
||||
}
|
||||
button(t('Cancel'), onClose);
|
||||
listen(dialog, 'cancel', (event) => {
|
||||
event.preventDefault();
|
||||
onClose();
|
||||
@@ -116,15 +181,12 @@ export function mountSceneSharing(
|
||||
bar.dataset.directorAuthoring = '';
|
||||
bar.className = 'scene-controls';
|
||||
const entries = [
|
||||
['EDIT DETAILS', edit],
|
||||
['SHARE SCENE', share],
|
||||
[t('EDIT DETAILS'), edit],
|
||||
[t('SHARE SCENE'), share],
|
||||
];
|
||||
const removers = [];
|
||||
for (const [text, fn] of entries) {
|
||||
const b = document.createElement('button');
|
||||
b.type = 'button';
|
||||
b.textContent = text;
|
||||
b.className = 'scene-btn';
|
||||
const b = createActionButton({ label: text, className: 'scene-btn' });
|
||||
b.addEventListener('click', fn);
|
||||
removers.push(() => b.removeEventListener('click', fn));
|
||||
bar.append(b);
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
const STEPS = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 };
|
||||
|
||||
/** Pure value navigation, also usable by a future template-based view. */
|
||||
export function nextSegmentValue(values, value, key, { homeEnd = true } = {}) {
|
||||
if (!values.length) return undefined;
|
||||
if (homeEnd && key === 'Home') return values[0];
|
||||
if (homeEnd && key === 'End') return values.at(-1);
|
||||
const step = STEPS[key];
|
||||
if (!step) return undefined;
|
||||
return values[(values.indexOf(value) + step + values.length) % values.length];
|
||||
}
|
||||
|
||||
/** Paint controlled selection without emitting changes or moving focus. */
|
||||
export function syncSegmentedControl(
|
||||
buttons,
|
||||
value,
|
||||
{ valueOf, activeClass = 'active', rovingFocus = false } = {},
|
||||
) {
|
||||
for (const button of buttons || []) {
|
||||
if (!button) continue;
|
||||
const selected = valueOf(button) === value;
|
||||
if (button.classList.contains(activeClass) !== selected)
|
||||
button.classList.toggle(activeClass, selected);
|
||||
const set = (name, content) => {
|
||||
if (button.getAttribute?.(name) !== content)
|
||||
button.setAttribute(name, content);
|
||||
};
|
||||
set('aria-checked', String(selected));
|
||||
if (rovingFocus) set('tabindex', selected ? '0' : '-1');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Controlled segmented-selector DOM adapter. Feature owners supply values and
|
||||
* receive changes; rendering a restored value never triggers the callback.
|
||||
* `keyboard` retains each existing group's policy: none, arrows, or radio
|
||||
* (arrows plus Home/End). Pointer and native Enter/Space share the click path.
|
||||
* An injected listener owner keeps the feature's existing teardown boundary.
|
||||
* @param {object} options
|
||||
* @param {Iterable<HTMLButtonElement>} options.buttons
|
||||
* @param {Function} options.valueOf Maps a button to the feature's value.
|
||||
* @param {Function} options.onChange Receives value and originating button.
|
||||
* @param {'none'|'arrows'|'radio'} [options.keyboard]
|
||||
* @param {HTMLElement} [options.keyTarget] Delegated keyboard target, if any.
|
||||
* @param {Function} [options.readValue] Current controlled value for delegation.
|
||||
* @param {Function} [options.listen] Feature-owned event registration.
|
||||
* @returns {{ update: Function, destroy: Function }}
|
||||
*/
|
||||
export function createSegmentedControl({
|
||||
buttons,
|
||||
valueOf,
|
||||
onChange,
|
||||
keyboard = 'none',
|
||||
keyTarget,
|
||||
readValue,
|
||||
listen,
|
||||
}) {
|
||||
const options = [...buttons].filter(Boolean);
|
||||
const removers = [];
|
||||
let destroyed = false;
|
||||
const bind = (target, type, handler) => {
|
||||
const owned = (event) => {
|
||||
if (!destroyed) handler(event);
|
||||
};
|
||||
if (listen) listen(target, type, owned);
|
||||
else {
|
||||
target.addEventListener(type, owned);
|
||||
removers.push(() => target.removeEventListener(type, owned));
|
||||
}
|
||||
};
|
||||
for (const button of options)
|
||||
bind(button, 'click', () => {
|
||||
if (!button.disabled) onChange(valueOf(button), button);
|
||||
});
|
||||
const navigate = (event, from) => {
|
||||
const enabled = options.filter((button) => !button.disabled);
|
||||
const values = enabled.map(valueOf);
|
||||
const next = nextSegmentValue(values, from, event.key, {
|
||||
homeEnd: keyboard === 'radio',
|
||||
});
|
||||
if (next === undefined) return;
|
||||
const button = enabled.find((option) => valueOf(option) === next);
|
||||
event.preventDefault();
|
||||
if (keyTarget) {
|
||||
button.click();
|
||||
button.focus();
|
||||
} else {
|
||||
button.focus();
|
||||
if (next !== from) button.click();
|
||||
}
|
||||
};
|
||||
if (keyboard !== 'none') {
|
||||
if (keyTarget)
|
||||
bind(keyTarget, 'keydown', (event) => navigate(event, readValue()));
|
||||
else
|
||||
for (const button of options)
|
||||
bind(button, 'keydown', (event) => navigate(event, valueOf(button)));
|
||||
}
|
||||
return {
|
||||
update(value, presentation) {
|
||||
if (!destroyed)
|
||||
syncSegmentedControl(options, value, { valueOf, ...presentation });
|
||||
},
|
||||
destroy() {
|
||||
destroyed = true;
|
||||
for (const remove of removers.splice(0)) remove();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { railFixture } from './railTestFixture.mjs';
|
||||
import {
|
||||
createSegmentedControl,
|
||||
nextSegmentValue,
|
||||
} from './segmentedControl.js';
|
||||
|
||||
function fixture(options = {}) {
|
||||
let writes = 0;
|
||||
const f = railFixture(() => writes++);
|
||||
const buttons = ['a', 'b', 'c'].map((value) => {
|
||||
const button = f.document.createElement('button');
|
||||
button.dataset.value = value;
|
||||
f.container.appendChild(button);
|
||||
return button;
|
||||
});
|
||||
const calls = [];
|
||||
const control = createSegmentedControl({
|
||||
buttons,
|
||||
valueOf: (button) => button.dataset.value,
|
||||
onChange: (value) => calls.push(value),
|
||||
...options,
|
||||
});
|
||||
const key = (target, value) => {
|
||||
const event = new Event('keydown', { cancelable: true });
|
||||
Object.defineProperty(event, 'key', { value });
|
||||
target.dispatchEvent(event);
|
||||
return event.defaultPrevented;
|
||||
};
|
||||
return { ...f, buttons, calls, control, key, writes: () => writes };
|
||||
}
|
||||
|
||||
test('controlled restoration updates selection without emitting or stealing focus', () => {
|
||||
const f = fixture();
|
||||
f.buttons[0].focus();
|
||||
f.control.update('b', { rovingFocus: true });
|
||||
assert.deepEqual(f.calls, []);
|
||||
assert.equal(f.document.activeElement, f.buttons[0]);
|
||||
assert.deepEqual(
|
||||
f.buttons.map((b) => b.getAttribute('aria-checked')),
|
||||
['false', 'true', 'false'],
|
||||
);
|
||||
assert.deepEqual(
|
||||
f.buttons.map((b) => b.getAttribute('tabindex')),
|
||||
['-1', '0', '-1'],
|
||||
);
|
||||
const before = f.writes();
|
||||
f.control.update('b', { rovingFocus: true });
|
||||
assert.equal(
|
||||
f.writes(),
|
||||
before,
|
||||
'unchanged renders must not retrigger rail observers',
|
||||
);
|
||||
f.control.destroy();
|
||||
});
|
||||
|
||||
test('clicks emit current values once, including reselection; disabled controls do not emit', () => {
|
||||
const f = fixture();
|
||||
f.control.update('a');
|
||||
f.buttons[0].click();
|
||||
f.buttons[0].click();
|
||||
f.buttons[1].dataset.value = 'renamed';
|
||||
f.buttons[1].click();
|
||||
f.buttons[2].disabled = true;
|
||||
f.buttons[2].dispatchEvent(new Event('click'));
|
||||
assert.deepEqual(f.calls, ['a', 'a', 'renamed']);
|
||||
assert.equal(
|
||||
f.buttons[0].getAttribute('aria-checked'),
|
||||
'true',
|
||||
'the owner controls selection',
|
||||
);
|
||||
f.control.destroy();
|
||||
});
|
||||
|
||||
test('radio navigation wraps, skips disabled choices, and retains Home/End semantics', () => {
|
||||
const f = fixture({ keyboard: 'radio' });
|
||||
f.buttons[1].disabled = true;
|
||||
assert.equal(f.key(f.buttons[0], 'ArrowRight'), true);
|
||||
assert.equal(f.document.activeElement, f.buttons[2]);
|
||||
assert.deepEqual(f.calls, ['c']);
|
||||
f.key(f.buttons[2], 'ArrowDown');
|
||||
assert.equal(f.document.activeElement, f.buttons[0]);
|
||||
f.key(f.buttons[0], 'Home');
|
||||
assert.deepEqual(
|
||||
f.calls,
|
||||
['c', 'a'],
|
||||
'Home on the first button does not reselect it',
|
||||
);
|
||||
f.key(f.buttons[0], 'End');
|
||||
assert.equal(f.document.activeElement, f.buttons[2]);
|
||||
assert.deepEqual(f.calls, ['c', 'a', 'c']);
|
||||
f.control.destroy();
|
||||
});
|
||||
|
||||
test('legacy click-only groups leave arrows and tab order to their existing owner', () => {
|
||||
const f = fixture();
|
||||
f.control.update('b');
|
||||
assert.equal(f.key(f.buttons[0], 'ArrowRight'), false);
|
||||
assert.equal(f.key(f.buttons[0], 'Home'), false);
|
||||
assert.deepEqual(f.calls, []);
|
||||
assert.ok(
|
||||
f.buttons.every((button) => button.getAttribute('tabindex') === null),
|
||||
);
|
||||
f.control.destroy();
|
||||
});
|
||||
|
||||
test('delegated imagery keys navigate from the controlled value, not stale focus', () => {
|
||||
const f = railFixture();
|
||||
const buttons = ['a', 'b', 'c'].map((value) => {
|
||||
const button = f.document.createElement('button');
|
||||
button.dataset.value = value;
|
||||
f.container.appendChild(button);
|
||||
return button;
|
||||
});
|
||||
let selected = 'c';
|
||||
const calls = [];
|
||||
const control = createSegmentedControl({
|
||||
buttons,
|
||||
valueOf: (b) => b.dataset.value,
|
||||
onChange: (value) => {
|
||||
calls.push(value);
|
||||
selected = value;
|
||||
},
|
||||
keyboard: 'arrows',
|
||||
keyTarget: f.container,
|
||||
readValue: () => selected,
|
||||
});
|
||||
const event = new Event('keydown', { cancelable: true });
|
||||
Object.defineProperty(event, 'key', { value: 'ArrowRight' });
|
||||
f.container.dispatchEvent(event);
|
||||
assert.deepEqual(calls, ['a']);
|
||||
assert.equal(f.document.activeElement, buttons[0]);
|
||||
const home = new Event('keydown', { cancelable: true });
|
||||
Object.defineProperty(home, 'key', { value: 'Home' });
|
||||
f.container.dispatchEvent(home);
|
||||
assert.equal(home.defaultPrevented, false);
|
||||
assert.deepEqual(calls, ['a']);
|
||||
control.destroy();
|
||||
});
|
||||
|
||||
test('disposal revokes detached controls and replacement subscriptions fire once', () => {
|
||||
const f = fixture({ keyboard: 'radio' });
|
||||
f.control.destroy();
|
||||
const next = [];
|
||||
const replacement = createSegmentedControl({
|
||||
buttons: f.buttons,
|
||||
valueOf: (b) => b.dataset.value,
|
||||
onChange: (value) => next.push(value),
|
||||
keyboard: 'radio',
|
||||
});
|
||||
f.buttons[0].click();
|
||||
f.key(f.buttons[0], 'End');
|
||||
assert.deepEqual(f.calls, []);
|
||||
assert.deepEqual(next, ['a', 'c']);
|
||||
replacement.destroy();
|
||||
replacement.destroy();
|
||||
f.buttons[1].click();
|
||||
f.key(f.buttons[0], 'End');
|
||||
assert.deepEqual(next, ['a', 'c']);
|
||||
});
|
||||
|
||||
test('pure value navigation can be reused without a DOM', () => {
|
||||
assert.equal(nextSegmentValue(['fit', 'fill'], 'fill', 'ArrowRight'), 'fit');
|
||||
assert.equal(nextSegmentValue(['fit', 'fill'], 'fit', 'ArrowUp'), 'fill');
|
||||
assert.equal(nextSegmentValue(['fit', 'fill'], 'fill', 'Home'), 'fit');
|
||||
assert.equal(nextSegmentValue(['fit', 'fill'], 'fit', 'End'), 'fill');
|
||||
assert.equal(
|
||||
nextSegmentValue(['fit', 'fill'], 'fit', 'Home', { homeEnd: false }),
|
||||
undefined,
|
||||
);
|
||||
assert.equal(nextSegmentValue([], 'fit', 'ArrowRight'), undefined);
|
||||
assert.equal(nextSegmentValue(['fit'], 'fit', 'Escape'), undefined);
|
||||
});
|
||||
@@ -0,0 +1,160 @@
|
||||
// The share button copies by default; a host's `services.shareLink` shares the
|
||||
// link its own way and reports how it went.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { StyleManager } from './applicationShell.js';
|
||||
import { ShareLinkManager } from '../sharelink.js';
|
||||
import { parseSharePath } from '../share/shareLinkPath.js';
|
||||
import { decodeShareView } from '../share/viewCodec.js';
|
||||
|
||||
/** The decoded view of a `/share/<code>` link. */
|
||||
const sharedState = (href) =>
|
||||
decodeShareView(parseSharePath(new URL(href).pathname).code).state;
|
||||
const SHARE_LINK = /^https:\/\/gev\.example\/share\/[A-Za-z0-9_-]+$/;
|
||||
|
||||
function makeManager(href, { positioned = true } = {}) {
|
||||
globalThis.window = { location: { href, hash: new URL(href).hash } };
|
||||
globalThis.history = { replaceState() {} };
|
||||
const viewer = {
|
||||
camera: {
|
||||
changed: { addEventListener() {} },
|
||||
positionCartographic: positioned
|
||||
? { latitude: 0, longitude: 0, height: 1000 }
|
||||
: undefined,
|
||||
heading: 0,
|
||||
pitch: -Math.PI / 2,
|
||||
roll: 0,
|
||||
},
|
||||
};
|
||||
return new ShareLinkManager(viewer);
|
||||
}
|
||||
|
||||
function installClipboard(writeText) {
|
||||
Object.defineProperty(globalThis, 'navigator', {
|
||||
configurable: true,
|
||||
value: { clipboard: { writeText } },
|
||||
});
|
||||
}
|
||||
|
||||
/** Wire the real share button handler onto a minimal shell; return a click. */
|
||||
function shell({ manager, services = {} }) {
|
||||
const toasts = [];
|
||||
let click;
|
||||
const owner = {
|
||||
services,
|
||||
shareLinkManager: manager,
|
||||
_shareBtn: {},
|
||||
_disposed: false,
|
||||
_lifetime: { listen: (_el, _type, handler) => (click = handler) },
|
||||
_showToast: (message) => toasts.push(message),
|
||||
};
|
||||
StyleManager.prototype._initShareButton.call(owner);
|
||||
return { toasts, click: () => click() };
|
||||
}
|
||||
|
||||
test('buildLink is a /share link stamped with its creation time, without ?lang', () => {
|
||||
const manager = makeManager('https://gev.example/?lang=ru#v=2&lat=10&lon=20');
|
||||
const href = manager.buildLink({ nowMs: 5_000_000 });
|
||||
assert.match(href, SHARE_LINK);
|
||||
const link = new URL(href);
|
||||
assert.equal(link.searchParams.get('lang'), null);
|
||||
assert.equal(link.hash, '');
|
||||
assert.equal(sharedState(href).sharedAtMs, 5_000_000);
|
||||
// The camera is the live one, not the address bar's.
|
||||
assert.equal(sharedState(href).lat, 0);
|
||||
assert.equal(
|
||||
makeManager('https://gev.example/', { positioned: false }).buildLink(),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('copyLink copies exactly what buildLink builds', async () => {
|
||||
let copied = null;
|
||||
installClipboard(async (url) => {
|
||||
copied = url;
|
||||
});
|
||||
const manager = makeManager('https://gev.example/#v=2');
|
||||
assert.equal(await manager.copyLink({ nowMs: 7_000_000 }), true);
|
||||
assert.equal(copied, manager.buildLink({ nowMs: 7_000_000 }));
|
||||
});
|
||||
|
||||
test('without a host hook the button copies the link', async () => {
|
||||
let copied = null;
|
||||
installClipboard(async (url) => {
|
||||
copied = url;
|
||||
});
|
||||
const { toasts, click } = shell({
|
||||
manager: makeManager('https://gev.example/#v=2'),
|
||||
});
|
||||
await click();
|
||||
assert.match(copied, SHARE_LINK);
|
||||
assert.deepEqual(toasts, ['Link copied!']);
|
||||
|
||||
installClipboard(async () => {
|
||||
throw new Error('denied');
|
||||
});
|
||||
await click();
|
||||
assert.deepEqual(toasts, ['Link copied!', 'Copy failed']);
|
||||
});
|
||||
|
||||
test('a host hook receives the link and its result picks the toast', async () => {
|
||||
installClipboard(async () => assert.fail('the host shares instead'));
|
||||
const shared = [];
|
||||
const results = ['shared', 'copied', 'cancelled', false];
|
||||
const { toasts, click } = shell({
|
||||
manager: makeManager('https://gev.example/#v=2'),
|
||||
services: {
|
||||
shareLink: async (url) => {
|
||||
shared.push(url);
|
||||
return results.shift();
|
||||
},
|
||||
},
|
||||
});
|
||||
for (let i = 0; i < 4; i++) await click();
|
||||
assert.equal(shared.length, 4);
|
||||
assert.match(shared[0], SHARE_LINK);
|
||||
// 'cancelled' (the user closed the sheet) shows nothing.
|
||||
assert.deepEqual(toasts, ['Link shared', 'Link copied!', 'Copy failed']);
|
||||
});
|
||||
|
||||
test('a failing host hook, or no camera position, reports a failure', async () => {
|
||||
const failing = shell({
|
||||
manager: makeManager('https://gev.example/#v=2'),
|
||||
services: { shareLink: async () => Promise.reject(new Error('no sheet')) },
|
||||
});
|
||||
await failing.click();
|
||||
assert.deepEqual(failing.toasts, ['Copy failed']);
|
||||
|
||||
let called = false;
|
||||
const unpositioned = shell({
|
||||
manager: makeManager('https://gev.example/', { positioned: false }),
|
||||
services: {
|
||||
shareLink: async () => {
|
||||
called = true;
|
||||
return 'shared';
|
||||
},
|
||||
},
|
||||
});
|
||||
await unpositioned.click();
|
||||
assert.equal(called, false);
|
||||
assert.deepEqual(unpositioned.toasts, ['Copy failed']);
|
||||
});
|
||||
|
||||
test('a host hook that answers without a promise, or throws, still gets a toast', async () => {
|
||||
for (const [shareLink, toast] of [
|
||||
[() => 'shared', 'Link shared'],
|
||||
[
|
||||
() => {
|
||||
throw new Error('no sheet');
|
||||
},
|
||||
'Copy failed',
|
||||
],
|
||||
]) {
|
||||
const { toasts, click } = shell({
|
||||
manager: makeManager('https://gev.example/#v=2'),
|
||||
services: { shareLink },
|
||||
});
|
||||
await click();
|
||||
assert.deepEqual(toasts, [toast]);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,190 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { trackedDisplayPositionForCamera } from '../data/trackedCamera.js';
|
||||
import {
|
||||
SHARE_VIEW_ENTITY_KINDS,
|
||||
followOffsetFromEnu,
|
||||
followOffsetToEnu,
|
||||
} from '../share/follow.js';
|
||||
|
||||
/**
|
||||
* The bridge between the camera following an entity and a share link's thing
|
||||
* view: what the camera follows now, in the share format's terms, and the
|
||||
* stored follow offset applied to an entity the camera has started to follow.
|
||||
*/
|
||||
|
||||
const KIND_BY_LAYER = new Map(
|
||||
SHARE_VIEW_ENTITY_KINDS.map((entry) => [entry.layerId, entry.kind]),
|
||||
);
|
||||
const MAX_FRAMES = 120;
|
||||
|
||||
/** `position`'s local east/north/up offset from `origin`, in metres. */
|
||||
function enuOffset(origin, position) {
|
||||
const frame = Cesium.Transforms.eastNorthUpToFixedFrame(origin);
|
||||
const local = Cesium.Matrix4.multiplyByPoint(
|
||||
Cesium.Matrix4.inverseTransformation(frame, new Cesium.Matrix4()),
|
||||
position,
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
return { east: local.x, north: local.y, up: local.z };
|
||||
}
|
||||
|
||||
/**
|
||||
* The entity the camera follows as `{ kind, id, offset, lastKnown }`, with
|
||||
* the camera's offset from it and its displayed position as of `nowMs`; null
|
||||
* when the camera follows nothing a share link can name. A selected vessel is
|
||||
* not followed (the camera stays where the user puts it), so a link made then
|
||||
* keeps its own camera.
|
||||
*/
|
||||
export function readShareFollowSubject({ viewer, nowMs = Date.now() }) {
|
||||
const cameraPosition = viewer?.camera?.positionWC;
|
||||
if (!cameraPosition) return null;
|
||||
const tracked = viewer.trackedEntity;
|
||||
const trackedId = String(tracked?.gevTrackedId || '');
|
||||
const separator = trackedId.indexOf(':');
|
||||
if (separator <= 0) return null;
|
||||
const kind = KIND_BY_LAYER.get(trackedId.slice(0, separator));
|
||||
const id = trackedId.slice(separator + 1);
|
||||
const target = kind
|
||||
? trackedDisplayPositionForCamera(
|
||||
tracked,
|
||||
viewer.clock.currentTime,
|
||||
new Cesium.Cartesian3(),
|
||||
)
|
||||
: null;
|
||||
if (!kind || !id || !target) return null;
|
||||
const offset = followOffsetFromEnu(enuOffset(target, cameraPosition));
|
||||
const fix = Cesium.Cartographic.fromCartesian(target);
|
||||
if (!offset || !fix) return null;
|
||||
return {
|
||||
kind,
|
||||
id,
|
||||
offset,
|
||||
lastKnown: {
|
||||
lat: Cesium.Math.toDegrees(fix.latitude),
|
||||
lon: Cesium.Math.toDegrees(fix.longitude),
|
||||
alt: fix.height,
|
||||
observedAtMs: nowMs,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Largest turn, in radians, the camera makes around the entity per frame. */
|
||||
const MAX_TURN_PER_FRAME = Math.PI / 3;
|
||||
|
||||
/**
|
||||
* Put the camera at a shared follow offset from `entity` once following it
|
||||
* has framed the camera. Cesium keeps the offset afterwards, as it keeps one
|
||||
* the user orbits to. The camera swings round the entity at most 60° a frame:
|
||||
* the follow's own guard treats a jump to the far side as the camera crossing
|
||||
* through the entity and puts it back. Returns a disposer.
|
||||
*/
|
||||
export function applyShareFollowOffset(viewer, entity, offset) {
|
||||
if (!viewer?.scene?.preUpdate || !entity || !(offset?.range > 0))
|
||||
return () => {};
|
||||
const local = followOffsetToEnu(offset);
|
||||
let frames = 0;
|
||||
let remove = null;
|
||||
const stop = () => {
|
||||
remove?.();
|
||||
remove = null;
|
||||
};
|
||||
remove = viewer.scene.preUpdate.addEventListener(() => {
|
||||
if (viewer.isDestroyed?.() || viewer.trackedEntity !== entity) {
|
||||
stop();
|
||||
return;
|
||||
}
|
||||
frames += 1;
|
||||
const camera = viewer.camera;
|
||||
// Let the follow frame the camera first (its first frame), then move it.
|
||||
const framed =
|
||||
frames > 1 &&
|
||||
!Cesium.Matrix4.equals(camera.transform, Cesium.Matrix4.IDENTITY);
|
||||
const target = framed
|
||||
? trackedDisplayPositionForCamera(
|
||||
entity,
|
||||
viewer.clock.currentTime,
|
||||
new Cesium.Cartesian3(),
|
||||
)
|
||||
: null;
|
||||
if (!target) {
|
||||
if (frames >= MAX_FRAMES) stop();
|
||||
return;
|
||||
}
|
||||
// The offset is east/north/up at the entity; the follow's own frame may
|
||||
// differ, so place the camera in world space and re-express it there.
|
||||
const world = Cesium.Matrix4.multiplyByPoint(
|
||||
Cesium.Transforms.eastNorthUpToFixedFrame(target),
|
||||
new Cesium.Cartesian3(local.east, local.north, local.up),
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
const goal = Cesium.Matrix4.multiplyByPoint(
|
||||
Cesium.Matrix4.inverseTransformation(
|
||||
camera.transform,
|
||||
new Cesium.Matrix4(),
|
||||
),
|
||||
world,
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
const from = Cesium.Cartesian3.clone(
|
||||
camera.position,
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
const angle =
|
||||
Cesium.Cartesian3.magnitude(from) > 0
|
||||
? Cesium.Cartesian3.angleBetween(from, goal)
|
||||
: 0;
|
||||
const done = !(angle > MAX_TURN_PER_FRAME);
|
||||
const next = done ? goal : turnToward(from, goal, MAX_TURN_PER_FRAME);
|
||||
camera.lookAtTransform(camera.transform, next);
|
||||
viewer.scene.requestRender?.();
|
||||
if (done) stop();
|
||||
});
|
||||
return stop;
|
||||
}
|
||||
|
||||
/**
|
||||
* `from` turned `step` radians toward `to`, with its length moved the same
|
||||
* fraction of the way: one frame of the swing round the entity.
|
||||
*/
|
||||
function turnToward(from, to, step) {
|
||||
const angle = Cesium.Cartesian3.angleBetween(from, to);
|
||||
const unitFrom = Cesium.Cartesian3.normalize(from, new Cesium.Cartesian3());
|
||||
// The direction perpendicular to `from` in the plane toward `to` (or any
|
||||
// perpendicular when they are opposite).
|
||||
let toward = Cesium.Cartesian3.subtract(
|
||||
Cesium.Cartesian3.normalize(to, new Cesium.Cartesian3()),
|
||||
Cesium.Cartesian3.multiplyByScalar(
|
||||
unitFrom,
|
||||
Math.cos(angle),
|
||||
new Cesium.Cartesian3(),
|
||||
),
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
if (Cesium.Cartesian3.magnitude(toward) < 1e-9)
|
||||
toward = Cesium.Cartesian3.cross(
|
||||
unitFrom,
|
||||
Math.abs(unitFrom.z) < 0.9
|
||||
? Cesium.Cartesian3.UNIT_Z
|
||||
: Cesium.Cartesian3.UNIT_X,
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
Cesium.Cartesian3.normalize(toward, toward);
|
||||
const length =
|
||||
Cesium.Cartesian3.magnitude(from) +
|
||||
(Cesium.Cartesian3.magnitude(to) - Cesium.Cartesian3.magnitude(from)) *
|
||||
(step / angle);
|
||||
const direction = Cesium.Cartesian3.add(
|
||||
Cesium.Cartesian3.multiplyByScalar(
|
||||
unitFrom,
|
||||
Math.cos(step),
|
||||
new Cesium.Cartesian3(),
|
||||
),
|
||||
Cesium.Cartesian3.multiplyByScalar(
|
||||
toward,
|
||||
Math.sin(step),
|
||||
new Cesium.Cartesian3(),
|
||||
),
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
return Cesium.Cartesian3.multiplyByScalar(direction, length, direction);
|
||||
}
|
||||
@@ -0,0 +1,554 @@
|
||||
// Short share links: `/share/<code>` opens through the start-up restore
|
||||
// pipeline, the address then follows the live view, and the share button
|
||||
// makes `/share/<code>` links (following an entity when the camera does).
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { ShareLinkManager } from '../sharelink.js';
|
||||
import { ShareRestoration, sharedFixNotice } from './shareRestoration.js';
|
||||
import {
|
||||
applyShareFollowOffset,
|
||||
readShareFollowSubject,
|
||||
} from './shareFollow.js';
|
||||
import { createDefaultLayerState } from '../data/layerState.js';
|
||||
import { parseSharePath, shareLinkUrl } from '../share/shareLinkPath.js';
|
||||
import {
|
||||
decodeShareView,
|
||||
encodeShareView,
|
||||
followCameraFor,
|
||||
followOffsetToEnu,
|
||||
} from '../share/viewCodec.js';
|
||||
|
||||
const NOW_MS = Date.now();
|
||||
const FIX = { lat: 37.6213, lon: -122.379, alt: 3200 };
|
||||
const OFFSET = { range: 5800, heading: 0, pitch: -35 };
|
||||
|
||||
const PLACE_CODE = encodeShareView({
|
||||
lat: 48.8584,
|
||||
lon: 2.2945,
|
||||
alt: 1200,
|
||||
heading: 120,
|
||||
pitch: -25,
|
||||
style: 'noir',
|
||||
panelState: { specs: [{ id: 'data-panel', collapsed: false }] },
|
||||
sharedAtMs: NOW_MS - 60_000,
|
||||
});
|
||||
|
||||
function aircraftCode() {
|
||||
const layerState = createDefaultLayerState();
|
||||
layerState.enabledLayerIds = ['flights'];
|
||||
return encodeShareView({
|
||||
view: {
|
||||
kind: 'thing',
|
||||
entity: { kind: 'aircraft', id: 'a1b2c3' },
|
||||
offset: OFFSET,
|
||||
lastKnown: { ...FIX, observedAtMs: NOW_MS - 120_000 },
|
||||
},
|
||||
layerState,
|
||||
sharedAtMs: NOW_MS - 120_000,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A page at `href`. `history.replaceState` rewrites the address in place and
|
||||
* is counted; `pushState` (a new history entry) is counted too.
|
||||
*/
|
||||
function installPage(t, href) {
|
||||
const prior = { window: globalThis.window, history: globalThis.history };
|
||||
const target = new EventTarget();
|
||||
const location = new URL(href);
|
||||
target.location = location;
|
||||
globalThis.window = target;
|
||||
const writes = { replaced: 0, pushed: 0 };
|
||||
globalThis.history = {
|
||||
replaceState(_state, _title, next) {
|
||||
writes.replaced += 1;
|
||||
location.href = new URL(next, location.href).href;
|
||||
},
|
||||
pushState() {
|
||||
writes.pushed += 1;
|
||||
},
|
||||
};
|
||||
t.after(() => Object.assign(globalThis, prior));
|
||||
return { location, writes, target };
|
||||
}
|
||||
|
||||
function installManualTimers(t) {
|
||||
const prior = {
|
||||
setTimeout: globalThis.setTimeout,
|
||||
clearTimeout: globalThis.clearTimeout,
|
||||
};
|
||||
const timers = new Map();
|
||||
let timerId = 0;
|
||||
globalThis.setTimeout = (fn) => {
|
||||
timers.set(++timerId, fn);
|
||||
return timerId;
|
||||
};
|
||||
globalThis.clearTimeout = (id) => timers.delete(id);
|
||||
t.after(() => Object.assign(globalThis, prior));
|
||||
return {
|
||||
timers,
|
||||
runAll() {
|
||||
for (const [id, fn] of [...timers]) {
|
||||
timers.delete(id);
|
||||
fn();
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** A viewer whose camera flights land at once. */
|
||||
function fakeViewer() {
|
||||
const flights = [];
|
||||
return {
|
||||
flights,
|
||||
canvas: new EventTarget(),
|
||||
camera: {
|
||||
changed: { addEventListener: () => () => {} },
|
||||
positionCartographic: { latitude: 0, longitude: 0, height: 1000 },
|
||||
heading: 0,
|
||||
pitch: -Math.PI / 2,
|
||||
roll: 0,
|
||||
flyTo(options) {
|
||||
flights.push(options);
|
||||
options.complete?.();
|
||||
},
|
||||
setView() {},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const flush = () => new Promise((resolve) => setImmediate(resolve));
|
||||
|
||||
/** A ShareRestoration over a real ShareLinkManager, as the shell wires them. */
|
||||
function openPage(t, href, { managerOptions = {}, tracking = null } = {}) {
|
||||
const page = installPage(t, href);
|
||||
const clock = installManualTimers(t);
|
||||
const viewer = fakeViewer();
|
||||
const restores = [];
|
||||
const manager = new ShareLinkManager(viewer, {
|
||||
onRestore: async (state) => restores.push(state),
|
||||
isNavigationCurrent: () => true,
|
||||
...managerOptions,
|
||||
});
|
||||
const notices = [];
|
||||
let generation = 0;
|
||||
const owner = new ShareRestoration({
|
||||
viewer,
|
||||
navigation: {
|
||||
_beginDeferredNavigation: () => ++generation,
|
||||
_reassertNavigationHandoff: () => true,
|
||||
_stampNavigation() {},
|
||||
},
|
||||
syncShareState() {},
|
||||
syncModels3d() {},
|
||||
showStatus() {},
|
||||
feedback: {},
|
||||
updateFeedback() {},
|
||||
applyFollowOffset: (entity, offset) =>
|
||||
applyShareFollowOffset(viewer, entity, offset),
|
||||
});
|
||||
// Notices are checked by message; their start-up-cover timing is not.
|
||||
owner._presentAfterStartupCover = (message) => notices.push(message);
|
||||
owner.attachLinks(manager);
|
||||
owner._layerStateCoordinator = {
|
||||
applyShareLayerState: () => Promise.resolve([]),
|
||||
getDurableState: () => null,
|
||||
cancelPendingShareTracking: () => false,
|
||||
restoreShareTrackingSelection: async () => tracking?.(owner) ?? null,
|
||||
destroy() {},
|
||||
};
|
||||
owner.start();
|
||||
t.after(() => owner.destroy());
|
||||
return { ...page, ...clock, viewer, manager, owner, restores, notices };
|
||||
}
|
||||
|
||||
/** Run the delayed start-up restore and let it settle. */
|
||||
async function restore(page) {
|
||||
page.runAll();
|
||||
const result = await page.owner.initialRestorePromise;
|
||||
await flush();
|
||||
return result;
|
||||
}
|
||||
|
||||
test('a /share/<code> address opens its place view through the start-up restore', async (t) => {
|
||||
const page = openPage(t, `http://localhost/share/${PLACE_CODE}`);
|
||||
assert.equal(page.timers.size, 1, 'the restore waits for its delayed flight');
|
||||
assert.equal(page.manager._initialRestorePending, true);
|
||||
const result = await restore(page);
|
||||
assert.equal(result.status, 'settled');
|
||||
assert.equal(result.share.camera, 'applied');
|
||||
assert.equal(page.restores[0].style, 'noir');
|
||||
assert.deepEqual(page.restores[0].panelState.specs, [
|
||||
{ id: 'data-panel', collapsed: false, pinned: null },
|
||||
]);
|
||||
const destination = Cesium.Cartographic.fromCartesian(
|
||||
page.viewer.flights[0].destination,
|
||||
);
|
||||
assert.ok(
|
||||
Math.abs(Cesium.Math.toDegrees(destination.latitude) - 48.8584) < 1e-6,
|
||||
);
|
||||
assert.equal(page.manager._initialRestorePending, false);
|
||||
assert.deepEqual(page.notices, []);
|
||||
});
|
||||
|
||||
test('after a restore the address becomes the app root and the long hash, with no new history entry', async (t) => {
|
||||
for (const [href, root] of [
|
||||
[`http://localhost/share/${PLACE_CODE}`, 'http://localhost/'],
|
||||
[
|
||||
`http://localhost:4173/gev/share/${PLACE_CODE}`,
|
||||
'http://localhost:4173/gev/',
|
||||
],
|
||||
]) {
|
||||
const page = openPage(t, href);
|
||||
await restore(page);
|
||||
page.manager._updateHash();
|
||||
assert.equal(`${page.location.origin}${page.location.pathname}`, root);
|
||||
// The live view's long form, as written for any other page.
|
||||
const params = new URLSearchParams(page.location.hash.slice(1));
|
||||
assert.equal(params.get('v'), '2');
|
||||
assert.ok(params.has('lat') && params.has('style'));
|
||||
assert.equal(page.writes.pushed, 0);
|
||||
assert.equal(page.writes.replaced, 1);
|
||||
page.manager.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
test('a host can pass the share code instead of the address', async (t) => {
|
||||
const page = openPage(t, 'http://localhost/', {
|
||||
managerOptions: { initialShareCode: PLACE_CODE },
|
||||
});
|
||||
await restore(page);
|
||||
assert.equal(page.restores[0].style, 'noir');
|
||||
});
|
||||
|
||||
test('a code that fails its check restores nothing and says so', async (t) => {
|
||||
// One character changed: the check byte no longer matches.
|
||||
const last = PLACE_CODE.at(-2) === 'A' ? 'B' : 'A';
|
||||
const typo = `${PLACE_CODE.slice(0, -2)}${last}${PLACE_CODE.at(-1)}`;
|
||||
const page = openPage(t, `http://localhost/share/${typo}`);
|
||||
assert.equal(page.manager.rejectedShareCode, 'checksum');
|
||||
assert.notEqual(page.owner._hasShareState, true);
|
||||
assert.equal(page.timers.size, 0, 'nothing to restore');
|
||||
assert.equal(
|
||||
(await page.owner.initialRestorePromise).status,
|
||||
'not-requested',
|
||||
);
|
||||
assert.deepEqual(page.notices, ["This share link can't be opened"]);
|
||||
// The default start's first address write leaves the bad link behind.
|
||||
page.manager._updateHash();
|
||||
assert.equal(page.location.pathname, '/');
|
||||
});
|
||||
|
||||
test('a thing view turns its layer on, follows by id and frames the shared offset', async (t) => {
|
||||
let entity = null;
|
||||
const page = openPage(t, `http://localhost/share/${aircraftCode()}`, {
|
||||
tracking: (owner) => {
|
||||
// What the coordinator does when the aircraft is in the feed.
|
||||
owner.viewer.trackedEntity = entity;
|
||||
owner._handleShareTrackingRestoreStatus({
|
||||
layerId: 'flights',
|
||||
targetId: 'a1b2c3',
|
||||
classification: 'followed',
|
||||
});
|
||||
return { classification: 'followed' };
|
||||
},
|
||||
});
|
||||
const target = Cesium.Cartesian3.fromDegrees(FIX.lon, FIX.lat, FIX.alt);
|
||||
const listeners = [];
|
||||
const looks = [];
|
||||
Object.assign(page.viewer, {
|
||||
clock: { currentTime: Cesium.JulianDate.now() },
|
||||
scene: {
|
||||
preUpdate: {
|
||||
addEventListener(fn) {
|
||||
listeners.push(fn);
|
||||
return () => listeners.splice(listeners.indexOf(fn), 1);
|
||||
},
|
||||
},
|
||||
},
|
||||
isDestroyed: () => false,
|
||||
});
|
||||
Object.assign(page.viewer.camera, {
|
||||
transform: Cesium.Transforms.eastNorthUpToFixedFrame(target),
|
||||
// The app's own follow framing: south of the aircraft and above it.
|
||||
position: new Cesium.Cartesian3(0, -4800, 3300),
|
||||
lookAtTransform(transform, offset) {
|
||||
looks.push(offset);
|
||||
this.position = Cesium.Cartesian3.clone(offset);
|
||||
},
|
||||
});
|
||||
entity = {
|
||||
gevTrackedId: 'flights:a1b2c3',
|
||||
gevDisplayPosition: () => target,
|
||||
};
|
||||
|
||||
const parsed = page.manager._parseShareCode(aircraftCode());
|
||||
assert.deepEqual(parsed.layerState.enabledLayerIds, ['flights']);
|
||||
assert.equal(
|
||||
parsed.layerState.options.flights.selectedFlightsTrackingId,
|
||||
'a1b2c3',
|
||||
);
|
||||
await restore(page);
|
||||
// The opening flight goes where following the fix puts the camera.
|
||||
const camera = followCameraFor(FIX, OFFSET);
|
||||
const destination = Cesium.Cartographic.fromCartesian(
|
||||
page.viewer.flights[0].destination,
|
||||
);
|
||||
assert.ok(
|
||||
Math.abs(Cesium.Math.toDegrees(destination.latitude) - camera.lat) < 1e-3,
|
||||
);
|
||||
assert.ok(
|
||||
Math.abs(Cesium.Math.toDegrees(destination.longitude) - camera.lon) < 1e-3,
|
||||
);
|
||||
// Once followed, the camera takes the shared offset after the follow's
|
||||
// own first frame.
|
||||
assert.equal(listeners.length, 1);
|
||||
listeners[0]();
|
||||
assert.equal(looks.length, 0);
|
||||
listeners[0]?.();
|
||||
assert.equal(looks.length, 1);
|
||||
const expected = followOffsetToEnu(OFFSET);
|
||||
assert.ok(Math.abs(looks[0].x - expected.east) < 1);
|
||||
assert.ok(Math.abs(looks[0].y - expected.north) < 1);
|
||||
assert.ok(Math.abs(looks[0].z - expected.up) < 1);
|
||||
assert.equal(listeners.length, 0, 'the offset is applied once');
|
||||
assert.deepEqual(page.notices, []);
|
||||
});
|
||||
|
||||
test('a thing that is not reporting leaves the view at its last-known fix, with a notice', async (t) => {
|
||||
const page = openPage(t, `http://localhost/share/${aircraftCode()}`, {
|
||||
tracking: (owner) => {
|
||||
// The coordinator's verdict once the follow window has passed.
|
||||
const result = {
|
||||
layerId: 'flights',
|
||||
targetId: 'a1b2c3',
|
||||
label: 'flight',
|
||||
classification: 'expired',
|
||||
};
|
||||
owner._handleShareTrackingRestoreStatus(result);
|
||||
return result;
|
||||
},
|
||||
});
|
||||
await restore(page);
|
||||
await flush();
|
||||
assert.equal(page.notices.length, 1);
|
||||
assert.match(
|
||||
page.notices[0],
|
||||
/^A1B2C3 isn't reporting now — showing where it was at .+/,
|
||||
);
|
||||
// A long link names no fix and keeps the existing notice.
|
||||
page.owner._initialShareState = { shareView: null };
|
||||
page.owner._handleShareTrackingRestoreStatus({
|
||||
layerId: 'flights',
|
||||
targetId: 'a1b2c3',
|
||||
label: 'flight',
|
||||
classification: 'expired',
|
||||
});
|
||||
assert.equal(page.notices[1], 'Shared flight follow expired');
|
||||
});
|
||||
|
||||
test('the not-reporting notice names the id and the time of the fix', () => {
|
||||
const at = new Date(2026, 9, 26, 14, 5).getTime();
|
||||
assert.match(
|
||||
sharedFixNotice({ kind: 'aircraft', id: 'a1b2c3' }, at, at + 60_000),
|
||||
/^A1B2C3 isn't reporting now — showing where it was at .*05/,
|
||||
);
|
||||
assert.equal(
|
||||
sharedFixNotice({ kind: 'vessel', id: '366999712' }, null),
|
||||
"366999712 isn't reporting now — showing where it was last seen",
|
||||
);
|
||||
});
|
||||
|
||||
test('a shared vessel is selected once the vessel feed has it', async (t) => {
|
||||
t.mock.timers.enable({ apis: ['Date'], now: NOW_MS });
|
||||
const page = openPage(t, 'http://localhost/');
|
||||
const selected = [];
|
||||
let present = false;
|
||||
page.owner._dataManager = {
|
||||
layers: new Map([
|
||||
[
|
||||
'ais-live-vessels',
|
||||
{
|
||||
module: {
|
||||
hasContact: (id) => present && id === '366999712',
|
||||
selectById: (id) => selected.push(id) > 0,
|
||||
},
|
||||
},
|
||||
],
|
||||
]),
|
||||
};
|
||||
const view = {
|
||||
kind: 'thing',
|
||||
entity: { kind: 'vessel', id: '366999712' },
|
||||
lastKnown: { lat: 1, lon: 2, alt: 0, observedAtMs: NOW_MS - 30_000 },
|
||||
};
|
||||
const found = page.owner._restoreSharedVessel(view, () => true);
|
||||
await flush();
|
||||
present = true;
|
||||
page.runAll();
|
||||
assert.equal(await found, true);
|
||||
assert.deepEqual(selected, ['366999712']);
|
||||
|
||||
present = false;
|
||||
const missing = page.owner._restoreSharedVessel(view, () => true);
|
||||
for (let i = 0; i < 61; i += 1) {
|
||||
await flush();
|
||||
t.mock.timers.tick(2_000);
|
||||
page.runAll();
|
||||
}
|
||||
assert.equal(await missing, false);
|
||||
assert.match(page.notices.at(-1), /^366999712 isn't reporting now/);
|
||||
});
|
||||
|
||||
test('the share button links to /share/<code>, following the followed entity', (t) => {
|
||||
installPage(t, 'https://gev.example/?lang=ru#v=2&lat=1&lon=2');
|
||||
const manager = new ShareLinkManager(fakeViewer());
|
||||
// A fresh session's look, as the app reports it at start-up.
|
||||
manager.onToggleChange(false, true, {
|
||||
hudVisible: true,
|
||||
detectionMode: 'DENSE',
|
||||
detectionDensity: 75,
|
||||
});
|
||||
// No entity: a place view at the live camera.
|
||||
const place = manager.buildLink({ nowMs: NOW_MS });
|
||||
assert.match(place, /^https:\/\/gev\.example\/share\/[A-Za-z0-9_-]+$/);
|
||||
assert.equal(
|
||||
decodeShareView(parseSharePath(new URL(place).pathname).code).state.view
|
||||
.kind,
|
||||
'place',
|
||||
);
|
||||
|
||||
manager.setFollowSubjectProvider(() => ({
|
||||
kind: 'aircraft',
|
||||
id: 'a1b2c3',
|
||||
offset: OFFSET,
|
||||
lastKnown: { ...FIX, observedAtMs: NOW_MS },
|
||||
}));
|
||||
const href = manager.buildLink({ nowMs: NOW_MS });
|
||||
const code = parseSharePath(new URL(href).pathname).code;
|
||||
const { state } = decodeShareView(code, { nowMs: NOW_MS });
|
||||
assert.deepEqual(state.view, {
|
||||
kind: 'thing',
|
||||
entity: { kind: 'aircraft', id: 'a1b2c3' },
|
||||
offset: OFFSET,
|
||||
lastKnown: { ...FIX, observedAtMs: Math.floor(NOW_MS / 1000) * 1000 },
|
||||
});
|
||||
// The followed aircraft's layer is implied; the camera is derived.
|
||||
assert.ok(code.length <= 45, `${code.length} characters`);
|
||||
assert.equal(href, shareLinkUrl(code, 'https://gev.example/'));
|
||||
manager.destroy();
|
||||
});
|
||||
|
||||
test('the followed entity is read in the share format, and its offset round-trips', () => {
|
||||
const target = Cesium.Cartesian3.fromDegrees(FIX.lon, FIX.lat, FIX.alt);
|
||||
const offset = { range: 2400, heading: 30, pitch: -20 };
|
||||
const local = followOffsetToEnu(offset);
|
||||
const cameraPosition = Cesium.Matrix4.multiplyByPoint(
|
||||
Cesium.Transforms.eastNorthUpToFixedFrame(target),
|
||||
new Cesium.Cartesian3(local.east, local.north, local.up),
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
const viewer = {
|
||||
camera: { positionWC: cameraPosition },
|
||||
clock: { currentTime: Cesium.JulianDate.now() },
|
||||
trackedEntity: {
|
||||
gevTrackedId: 'military:ae1234',
|
||||
gevDisplayPosition: () => target,
|
||||
},
|
||||
};
|
||||
const subject = readShareFollowSubject({ viewer, nowMs: NOW_MS });
|
||||
assert.equal(subject.kind, 'military_aircraft');
|
||||
assert.equal(subject.id, 'ae1234');
|
||||
assert.deepEqual(subject.offset, offset);
|
||||
assert.ok(Math.abs(subject.lastKnown.lat - FIX.lat) < 1e-9);
|
||||
assert.ok(Math.abs(subject.lastKnown.alt - FIX.alt) < 1e-3);
|
||||
// A followed entity the share format has no kind for is not a thing view.
|
||||
viewer.trackedEntity.gevTrackedId = 'local-adsb:abc';
|
||||
assert.equal(readShareFollowSubject({ viewer }), null);
|
||||
// Nor is a camera that follows nothing (a selected vessel is not followed).
|
||||
viewer.trackedEntity = undefined;
|
||||
assert.equal(readShareFollowSubject({ viewer }), null);
|
||||
});
|
||||
|
||||
test('a shared offset on the far side swings round, never jumping through the entity', () => {
|
||||
const target = Cesium.Cartesian3.fromDegrees(FIX.lon, FIX.lat, FIX.alt);
|
||||
const listeners = [];
|
||||
const looks = [];
|
||||
const entity = { gevDisplayPosition: () => target };
|
||||
const viewer = {
|
||||
clock: { currentTime: Cesium.JulianDate.now() },
|
||||
scene: {
|
||||
preUpdate: {
|
||||
addEventListener(fn) {
|
||||
listeners.push(fn);
|
||||
return () => listeners.splice(listeners.indexOf(fn), 1);
|
||||
},
|
||||
},
|
||||
},
|
||||
trackedEntity: entity,
|
||||
camera: {
|
||||
transform: Cesium.Transforms.eastNorthUpToFixedFrame(target),
|
||||
position: new Cesium.Cartesian3(0, -4800, 3300),
|
||||
lookAtTransform(transform, offset) {
|
||||
looks.push(Cesium.Cartesian3.clone(offset));
|
||||
this.position = Cesium.Cartesian3.clone(offset);
|
||||
},
|
||||
},
|
||||
};
|
||||
// Looking south at the nose: the opposite side of the app's framing.
|
||||
const offset = { range: 5800, heading: 180, pitch: -35 };
|
||||
applyShareFollowOffset(viewer, entity, offset);
|
||||
let previous = viewer.camera.position;
|
||||
for (let frame = 0; frame < 10 && listeners.length; frame += 1) {
|
||||
listeners[0]();
|
||||
const now = viewer.camera.position;
|
||||
// The follow's guard treats a turn of 90° or more as a crossing.
|
||||
assert.ok(Cesium.Cartesian3.angleBetween(previous, now) < Math.PI / 2);
|
||||
previous = now;
|
||||
}
|
||||
assert.equal(listeners.length, 0, 'it arrives');
|
||||
assert.ok(looks.length >= 2, `${looks.length} steps`);
|
||||
const expected = followOffsetToEnu(offset);
|
||||
const last = looks.at(-1);
|
||||
assert.ok(Math.abs(last.x - expected.east) < 1);
|
||||
assert.ok(Math.abs(last.y - expected.north) < 1);
|
||||
assert.ok(Math.abs(last.z - expected.up) < 1);
|
||||
});
|
||||
|
||||
test('applying a follow offset gives up when the follow ends', () => {
|
||||
const listeners = [];
|
||||
const viewer = {
|
||||
scene: {
|
||||
preUpdate: {
|
||||
addEventListener(fn) {
|
||||
listeners.push(fn);
|
||||
return () => listeners.splice(listeners.indexOf(fn), 1);
|
||||
},
|
||||
},
|
||||
},
|
||||
trackedEntity: null,
|
||||
};
|
||||
applyShareFollowOffset(viewer, {}, OFFSET);
|
||||
listeners[0]();
|
||||
assert.equal(listeners.length, 0);
|
||||
});
|
||||
|
||||
test('long links and hash navigation are unaffected by a share code start', async (t) => {
|
||||
// A long link still opens from the hash.
|
||||
const long = openPage(t, 'http://localhost/#v=2&lat=10&lon=20&style=nvg');
|
||||
await restore(long);
|
||||
assert.equal(long.restores[0].style, 'surveillance');
|
||||
assert.equal(long.restores[0].shareView, undefined);
|
||||
long.manager._updateHash();
|
||||
assert.equal(long.location.pathname, '/');
|
||||
|
||||
// After a /share start, navigating to a long link restores it (#1416).
|
||||
const page = openPage(t, `http://localhost/share/${PLACE_CODE}`);
|
||||
await restore(page);
|
||||
page.location.hash = 'v=2&lat=1.0000&lon=2.0000&style=normal';
|
||||
page.target.dispatchEvent(new Event('hashchange'));
|
||||
await flush();
|
||||
assert.equal(page.restores.length, 2);
|
||||
assert.equal(page.restores[1].style, 'normal');
|
||||
});
|
||||
Loaded 100 of 1387 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user