mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-20 02:02:21 +00:00
Merge branch 'main' into fix/shortcuts-modifier-keys
This commit is contained in:
1214 files changed
+37676
-9143
No files matched your search
+45
-25
@@ -30,7 +30,7 @@ import { LocationNavigation } from './locationNavigation.js';
|
||||
import { bindCameraOrientationControls } from './cameraOrientationControls.js';
|
||||
import { createMapSourceControls } from './mapSource.js';
|
||||
import { STYLES } from './effects.js';
|
||||
import { isHudLayout } from '../hudLayouts.js';
|
||||
import { isHudLayout, isLegacySonarHudLayout } from '../hudLayouts.js';
|
||||
import {
|
||||
getCyberSonarControlState,
|
||||
setCyberSonarControls,
|
||||
@@ -62,6 +62,8 @@ import { applyLocaleChoice } from './localePicker.js';
|
||||
import { PanelNavigation } from './panelNavigation.js';
|
||||
import { applicationPinia, createUiRuntime } from './vueRuntime.js';
|
||||
import { useContextStore } from './stores/context.js';
|
||||
import { useSpaceMissionsStore } from './stores/spaceMissions.js';
|
||||
import { SpaceMissionsControls } from './spaceMissionsControls.js';
|
||||
import { useMissionReplayStore } from './stores/missionReplay.js';
|
||||
import { useCelestialRingStore } from './stores/celestialRing.js';
|
||||
import { icrfToFixedAxes } from '../sky/icrf.js';
|
||||
@@ -78,6 +80,12 @@ import { useCockpitStore } from './stores/cockpit.js';
|
||||
import { useGlobeActionsStore } from './stores/globeActions.js';
|
||||
import { useRecordingStore } from './stores/recording.js';
|
||||
import { onPlacePacksLoadingChange } from '../data/placeBelow.js';
|
||||
import {
|
||||
hideOsmCredit,
|
||||
registerDynamicCredit,
|
||||
showOsmCredit,
|
||||
WIKIDATA_PLACES_CREDIT,
|
||||
} from '../data/dataCredits.js';
|
||||
import { withPlacePacks } from './placePacksLoading.js';
|
||||
import { preloadOwnerFlags } from './ownerFlag.js';
|
||||
|
||||
@@ -182,6 +190,14 @@ export class StyleManager extends ShellFacade {
|
||||
layers: () => this._dataManager?.getAll?.() || [],
|
||||
setLayer: (id, enabled) =>
|
||||
this._dataManager?.setEnabled(id, enabled, { origin: 'user' }),
|
||||
// The Omnibar shows names from the bundled Wikidata packs.
|
||||
creditPlaces: () =>
|
||||
registerDynamicCredit(this.viewer, WIKIDATA_PLACES_CREDIT),
|
||||
// Photon's suggestions are OpenStreetMap data: credited while shown.
|
||||
creditSuggestions: (shown) =>
|
||||
shown
|
||||
? showOsmCredit(this.viewer, 'omnibar')
|
||||
: hideOsmCredit(this.viewer, 'omnibar'),
|
||||
});
|
||||
// Scrolling at a screen edge steps through that side's rail panels.
|
||||
this._removeRailEdgeScroll = installRailEdgeScroll();
|
||||
@@ -203,7 +219,6 @@ export class StyleManager extends ShellFacade {
|
||||
pinia: applicationPinia(),
|
||||
pickWorld: services.pickWorldFromScreen,
|
||||
regionalBrief: services.fetchRegionalBrief,
|
||||
overlayHit: services.hitTestWorldOverlay,
|
||||
});
|
||||
this.mapStackController = mapStackController;
|
||||
this.placeSearch = placeSearch;
|
||||
@@ -312,6 +327,7 @@ export class StyleManager extends ShellFacade {
|
||||
readControls: () => ({
|
||||
hud: this.hud,
|
||||
_contextControls: this._contextControls,
|
||||
_spaceMissionsControls: this._spaceMissionsControls,
|
||||
_cctvControls: this._cctvControls,
|
||||
_radioControls: this._radioControls,
|
||||
_streetLevelControls: this._streetLevelControls,
|
||||
@@ -676,6 +692,7 @@ export class StyleManager extends ShellFacade {
|
||||
this._initStreetLevelPanel();
|
||||
this._initWildlifeSightingCard();
|
||||
this._initGlobalContextPanel();
|
||||
this._initSpaceMissionsPanel();
|
||||
this._initLocationBar();
|
||||
this._initMobileShell();
|
||||
this._initShareButton();
|
||||
@@ -1012,17 +1029,12 @@ export class StyleManager extends ShellFacade {
|
||||
}
|
||||
|
||||
_initGlobalContextPanel() {
|
||||
const {
|
||||
radioLayer,
|
||||
militaryInstallationsLayer,
|
||||
militaryAwarenessLayer,
|
||||
rocketLaunchesLayer,
|
||||
} = this.services;
|
||||
const { radioLayer, militaryInstallationsLayer, militaryAwarenessLayer } =
|
||||
this.services;
|
||||
const contextStore = useContextStore(applicationPinia());
|
||||
this._contextControls = new ContextControls({
|
||||
elements: {
|
||||
_globalContextFlightsBtn: this._globalContextFlightsBtn,
|
||||
_globalContextMissionsBtn: this._globalContextMissionsBtn,
|
||||
_installationsSearchBtn: this._installationsSearchBtn,
|
||||
},
|
||||
installations: militaryInstallationsLayer,
|
||||
@@ -1058,13 +1070,24 @@ export class StyleManager extends ShellFacade {
|
||||
militaryAwarenessLayer?.subscribeDirectionOverlay?.((view) =>
|
||||
awarenessDirectionStore.publish(view),
|
||||
);
|
||||
}
|
||||
|
||||
_initSpaceMissionsPanel() {
|
||||
const { rocketLaunchesLayer } = this.services;
|
||||
// The Space Missions layer publishes its roster and selected mission.
|
||||
contextStore.connectMissions(rocketLaunchesLayer);
|
||||
this._missionsPanelUnsubscribe?.();
|
||||
contextStore.publishMissions(null);
|
||||
this._missionsPanelUnsubscribe = rocketLaunchesLayer?.subscribePanel?.(
|
||||
(view) => contextStore.publishMissions(view),
|
||||
);
|
||||
this._spaceMissionsControls?.destroy();
|
||||
this._spaceMissionsControls = new SpaceMissionsControls({
|
||||
layer: rocketLaunchesLayer,
|
||||
store: useSpaceMissionsStore(applicationPinia()),
|
||||
actions: {
|
||||
setPanelCollapsed: (...args) => this.setPanelCollapsed(...args),
|
||||
isCockpitActive: () => Boolean(this.cockpitView?.active),
|
||||
// After the panel has rendered as shown: the phone shell will not
|
||||
// open the Missions sheet over a hidden panel.
|
||||
revealPanel: () =>
|
||||
nextTick(() => this.revealPanel('space-missions-panel')),
|
||||
},
|
||||
});
|
||||
// And its replay vehicle overlay, which the scene chrome renders.
|
||||
const missionReplayStore = useMissionReplayStore(applicationPinia());
|
||||
this._missionReplayUnsubscribe?.();
|
||||
@@ -1377,17 +1400,18 @@ export class StyleManager extends ShellFacade {
|
||||
}
|
||||
|
||||
/**
|
||||
* Switches the HUD layout variant.
|
||||
* Switches the HUD layout variant. The removed Cyber layout is accepted
|
||||
* as an alias: it opens Tactical with the Sonar style on.
|
||||
* @param {'tactical'|'minimal'|'cyber'} variantName - Layout variant.
|
||||
* @returns {{ok: boolean, layout?: string, visible?: boolean, error?: string}}
|
||||
*/
|
||||
setHudLayout(variantName) {
|
||||
const variant = String(variantName ?? '').toLowerCase();
|
||||
if (!isHudLayout(variant)) {
|
||||
if (!isHudLayout(variant) && !isLegacySonarHudLayout(variant)) {
|
||||
return { ok: false, error: `Unknown HUD layout: ${variantName}` };
|
||||
}
|
||||
this.shareLinkManager?.claimRestoreLane?.('visual');
|
||||
this._setHudVariant(variant, { applyVisualDefaults: true });
|
||||
this._setHudVariant(variant);
|
||||
return {
|
||||
ok: true,
|
||||
layout: this.hud.getVariant(),
|
||||
@@ -1506,7 +1530,7 @@ export class StyleManager extends ShellFacade {
|
||||
};
|
||||
}
|
||||
|
||||
/** Apply Cyber-only sonar settings through the shared visual controls. */
|
||||
/** Apply sonar visual-style settings through the shared visual controls. */
|
||||
setCyberSonar(settings) {
|
||||
return setCyberSonarControls(this, settings);
|
||||
}
|
||||
@@ -1642,8 +1666,6 @@ export class StyleManager extends ShellFacade {
|
||||
* @param {string} styleName - Target style ('normal'|'retro'|'surveillance'|'thermal'|'anime'|'noir').
|
||||
* @param {object} [options]
|
||||
* @param {boolean} [options.applyPreset=true] - Whether to apply STYLE_PRESET_DEFAULTS for the new style.
|
||||
* @param {boolean} [options.userInitiated=false] - Whether a direct user preset choice owns the Cyber exit style.
|
||||
* @param {boolean} [options.preserveCyberRestore=false] - Whether an automatic style update keeps the Cyber entry snapshot.
|
||||
* @returns {void}
|
||||
*/
|
||||
setStyle(
|
||||
@@ -1943,16 +1965,14 @@ export class StyleManager extends ShellFacade {
|
||||
this._awarenessDirectionUnsubscribe?.();
|
||||
this._awarenessDirectionUnsubscribe = null;
|
||||
useAwarenessDirectionStore(applicationPinia()).publish(null);
|
||||
this._missionsPanelUnsubscribe?.();
|
||||
this._missionsPanelUnsubscribe = null;
|
||||
this._spaceMissionsControls?.destroy();
|
||||
this._spaceMissionsControls = null;
|
||||
this._missionReplayUnsubscribe?.();
|
||||
this._missionReplayUnsubscribe = null;
|
||||
useMissionReplayStore(applicationPinia()).publish(null);
|
||||
const contextStore = useContextStore(applicationPinia());
|
||||
contextStore.connectAwareness(null);
|
||||
contextStore.publishAwareness(null);
|
||||
contextStore.connectMissions(null);
|
||||
contextStore.publishMissions(null);
|
||||
this._cockpitCoordinator.stop();
|
||||
this._visualSettings.stop();
|
||||
this.shareLinkManager?.destroy();
|
||||
|
||||
+31
-9
@@ -336,7 +336,7 @@ function updateVessel(nowMs) {
|
||||
* gives none) and slew toward its heading. A frame that is null, malformed or
|
||||
* for another subject ends the view, as an aircraft tracked meanwhile does.
|
||||
* The update runs on the provider's `cameraIntervalMs` (0: every frame), and
|
||||
* its rates advance by the time that interval spans (cockpitSubjectStepSec).
|
||||
* its rates advance by the time since the last update (cockpitSubjectStepSec).
|
||||
*/
|
||||
function updateSubject(nowMs) {
|
||||
const provider = this.subjectProvider;
|
||||
@@ -357,6 +357,7 @@ function updateSubject(nowMs) {
|
||||
}
|
||||
this.lastSubjectFrame = frame;
|
||||
let heightM = frame.heightM;
|
||||
let held = false;
|
||||
if (heightM === null) {
|
||||
this.services.warmGroundFloor?.([
|
||||
{ lat: frame.latitude, lon: frame.longitude },
|
||||
@@ -366,8 +367,10 @@ function updateSubject(nowMs) {
|
||||
frame.longitude,
|
||||
);
|
||||
// A frame with no height stands on the shared floor; while that is cold
|
||||
// it keeps the height it last stood at.
|
||||
heightM = Number.isFinite(floorM) ? floorM : this.subjectHeightM;
|
||||
// the eye keeps the last height it stood at (a frame's or the floor's),
|
||||
// at first the entry frame's.
|
||||
held = !Number.isFinite(floorM);
|
||||
heightM = held ? this.subjectHeightM : floorM;
|
||||
}
|
||||
if (!Number.isFinite(heightM)) {
|
||||
// Nothing to stand on yet, from the first frame: the camera stays where
|
||||
@@ -399,6 +402,21 @@ function updateSubject(nowMs) {
|
||||
}
|
||||
this.surfaceWaitStartedMs = 0;
|
||||
this.surfaceAcquiring = false;
|
||||
if (!held) {
|
||||
// The first height to replace the entry frame's is the anchor's at once
|
||||
// (an inertial anchor would close on it only at the horizontal
|
||||
// correction's rate); where the anchor stands, it stays.
|
||||
if (
|
||||
this.subjectHeightFromEntry &&
|
||||
this.cockpitAnchorValid &&
|
||||
heightM !== this.subjectHeightM
|
||||
) {
|
||||
const anchor = toCartographicRadians(this.cockpitAnchor);
|
||||
if (anchor)
|
||||
this.cockpitAnchor = fromRadians(anchor.lon, anchor.lat, heightM);
|
||||
}
|
||||
this.subjectHeightFromEntry = false;
|
||||
}
|
||||
this.subjectHeightM = heightM;
|
||||
const target = fromDegrees(frame.longitude, frame.latitude, heightM);
|
||||
const dtSec = cockpitSubjectStepSec(nowMs - this.lastFrameMs, intervalMs);
|
||||
@@ -411,7 +429,9 @@ function updateSubject(nowMs) {
|
||||
: slewHeading(
|
||||
this.heading ?? frame.headingDeg,
|
||||
frame.headingDeg,
|
||||
rate * dtSec,
|
||||
// At most half a turn, which reaches any heading: a huge rate times
|
||||
// the step must not overflow to Infinity and stop the turn.
|
||||
Math.min(rate * dtSec, 180),
|
||||
);
|
||||
}
|
||||
let look = null;
|
||||
@@ -459,8 +479,10 @@ function updateSubject(nowMs) {
|
||||
* Aircraft pass none and look along the heading at the profile pitch.
|
||||
*/
|
||||
function placeCamera(target, info, nowMs, dtSec, profile, look = null) {
|
||||
if (!this.cockpitAnchorValid) {
|
||||
this.cockpitAnchor = clone(target);
|
||||
// The update that first sets the anchor stands it on the target: the time
|
||||
// before it (an entry, a floor wait) moved nothing, so it has no step.
|
||||
const anchoring = !this.cockpitAnchorValid;
|
||||
if (anchoring) {
|
||||
this.cockpitAnchorValid = true;
|
||||
this.subjectLiftM = null;
|
||||
}
|
||||
@@ -485,7 +507,7 @@ function placeCamera(target, info, nowMs, dtSec, profile, look = null) {
|
||||
: 0;
|
||||
|
||||
const groundClamp = info.groundClamp !== false;
|
||||
if (info.stale || info.anchor === 'exact') {
|
||||
if (anchoring || info.stale || info.anchor === 'exact') {
|
||||
// A feed backoff has no authoritative velocity epoch to advance from.
|
||||
// Hold the cockpit on the exact layer-rendered position so the camera
|
||||
// cannot coast away while the icon correctly remains fixed.
|
||||
@@ -503,8 +525,8 @@ function placeCamera(target, info, nowMs, dtSec, profile, look = null) {
|
||||
);
|
||||
const correction = sub(target, this.cockpitAnchor);
|
||||
const correctionDistanceM = magnitude(correction);
|
||||
// An application subject's step is already bounded by its own update
|
||||
// interval (cockpitSubjectStepSec); the built-in views keep the 0.1 s.
|
||||
// An application subject's step is already bounded (cockpitSubjectStepSec);
|
||||
// the built-in views keep the 0.1 s.
|
||||
const correctionStepM = cockpitAnchorCorrectionStep(
|
||||
correctionDistanceM,
|
||||
speedMps,
|
||||
|
||||
@@ -194,8 +194,10 @@ export class CockpitViewController {
|
||||
this.surfaceWaitStartedMs = 0;
|
||||
this.surfaceAcquiring = false;
|
||||
this.surfaceFallback = false;
|
||||
/** The height an application subject's frame last stood at (m). */
|
||||
/** The height an application subject's eye last stood at (m). */
|
||||
this.subjectHeightM = null;
|
||||
/** Whether `subjectHeightM` is still the one its entry frame gave. */
|
||||
this.subjectHeightFromEntry = false;
|
||||
/** The ground clamp's eased lift under that subject's eye (m). */
|
||||
this.subjectLiftM = null;
|
||||
/**
|
||||
@@ -735,8 +737,16 @@ export class CockpitViewController {
|
||||
publishCockpitSignals() {
|
||||
return publishCockpitSignals.call(this);
|
||||
}
|
||||
pushCockpitSignal(key, tone, title, detail, target) {
|
||||
return pushCockpitSignal.call(this, key, tone, title, detail, target);
|
||||
pushCockpitSignal(key, tone, title, detail, target, options) {
|
||||
return pushCockpitSignal.call(
|
||||
this,
|
||||
key,
|
||||
tone,
|
||||
title,
|
||||
detail,
|
||||
target,
|
||||
options,
|
||||
);
|
||||
}
|
||||
dropCockpitSignal(key) {
|
||||
return dropCockpitSignal.call(this, key);
|
||||
|
||||
@@ -444,10 +444,10 @@ test('Cockpit places the eye at its aircraft as the Cesium maths did', async ()
|
||||
latitude: 30.19,
|
||||
longitude: -97.67,
|
||||
onGround: false,
|
||||
stale: true,
|
||||
stale: false,
|
||||
};
|
||||
const { owner, views } = cockpitOver({ info, target });
|
||||
// Held on the target while the feed is stale.
|
||||
// The first update stands the anchor on the target.
|
||||
owner.update();
|
||||
let expected = cesiumCockpitEye(Cesium, {
|
||||
target,
|
||||
@@ -456,13 +456,12 @@ test('Cockpit places the eye at its aircraft as the Cesium maths did', async ()
|
||||
dtSec: 0,
|
||||
liftM: 0,
|
||||
});
|
||||
near(views[0].destination, expected.eye, 1e-6, 'stale eye');
|
||||
near(views[0].destination, expected.eye, 1e-6, 'first eye');
|
||||
near(views[0].orientation.direction, expected.forward, 1e-12, 'direction');
|
||||
near(views[0].orientation.up, expected.up, 1e-12, 'up');
|
||||
|
||||
// Live: the anchor coasts 80 ms along the heading and is pulled toward
|
||||
// where the layer now shows the aircraft.
|
||||
info.stale = false;
|
||||
const anchor = Cesium.Cartesian3.clone(expected.anchor);
|
||||
const moved = Cesium.Cartesian3.fromDegrees(-97.6698, 30.1901, 1210);
|
||||
owner.trackedFollow.position = () => moved;
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { displayPanelScroller } from './displayPanelScroll.js';
|
||||
|
||||
/**
|
||||
* Show the existing Display groups in Cockpit's Display popover while Cockpit
|
||||
* is on. The portal publishes the popover's slots; the Display panel
|
||||
@@ -37,16 +35,13 @@ export class CockpitDisplayPortal {
|
||||
this.slots = Object.freeze(
|
||||
Object.fromEntries(this.records.map(({ name, slot }) => [name, slot])),
|
||||
);
|
||||
this.standardScrollTop =
|
||||
displayPanelScroller(standardPanel)?.scrollTop || 0;
|
||||
this.standardScrollTop = standardPanel?.scrollTop || 0;
|
||||
this.cockpitScrollTop = cockpitPanel?.scrollTop || 0;
|
||||
const options = { passive: true, signal: this.listeners.signal };
|
||||
standardPanel?.addEventListener(
|
||||
'scroll',
|
||||
() => {
|
||||
if (!this.active)
|
||||
this.standardScrollTop =
|
||||
displayPanelScroller(standardPanel).scrollTop;
|
||||
if (!this.active) this.standardScrollTop = standardPanel.scrollTop;
|
||||
},
|
||||
{ ...options, capture: true },
|
||||
);
|
||||
@@ -98,8 +93,7 @@ export class CockpitDisplayPortal {
|
||||
if (nextActive && this.cockpitPanel)
|
||||
this.cockpitPanel.scrollTop = this.cockpitScrollTop;
|
||||
if (!nextActive && this.standardPanel)
|
||||
displayPanelScroller(this.standardPanel).scrollTop =
|
||||
this.standardScrollTop;
|
||||
this.standardPanel.scrollTop = this.standardScrollTop;
|
||||
};
|
||||
if (!settle) {
|
||||
this.afterRender(() => {
|
||||
@@ -146,8 +140,7 @@ export class CockpitDisplayPortal {
|
||||
this.publish(null);
|
||||
const { standardPanel, standardScrollTop } = this;
|
||||
this.afterRender(() => {
|
||||
if (standardPanel)
|
||||
displayPanelScroller(standardPanel).scrollTop = standardScrollTop;
|
||||
if (standardPanel) standardPanel.scrollTop = standardScrollTop;
|
||||
});
|
||||
this.records = [];
|
||||
this.restoreOwner = null;
|
||||
|
||||
@@ -256,20 +256,21 @@ function updateSubjectHud(info, nowMs, forceContext) {
|
||||
this.updateLocalPosition(info);
|
||||
this.maybeRefreshRegionalBrief(info);
|
||||
this.showContextCard(false);
|
||||
const keys = new Set();
|
||||
for (const signal of hud.signals) {
|
||||
const key = `subject:${signal.id}`;
|
||||
keys.add(key);
|
||||
this.pushCockpitSignal(
|
||||
key,
|
||||
SUBJECT_SIGNAL_TONES[signal.tone] ?? 'info',
|
||||
signal.title,
|
||||
signal.detail || signal.title,
|
||||
);
|
||||
}
|
||||
const keys = new Set(hud.signals.map(({ id }) => `subject:${id}`));
|
||||
// Rows the view no longer lists leave first, so new ones take their
|
||||
// places rather than push a listed one (or TRACK ACQUIRED) off.
|
||||
for (const key of this.subjectSignalKeys ?? [])
|
||||
if (!keys.has(key)) this.dropCockpitSignal(key);
|
||||
this.subjectSignalKeys = keys;
|
||||
for (const signal of hud.signals)
|
||||
this.pushCockpitSignal(
|
||||
`subject:${signal.id}`,
|
||||
SUBJECT_SIGNAL_TONES[signal.tone] ?? 'info',
|
||||
signal.title,
|
||||
signal.detail || signal.title,
|
||||
null,
|
||||
{ inPlace: true },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+3
-135
@@ -2,7 +2,6 @@
|
||||
import {
|
||||
resolveCockpitUtilityAnchor,
|
||||
resolveCockpitUtilityLayout,
|
||||
resolveCyberCockpitPanelLane,
|
||||
} from '../cockpitUtilityLayout.js';
|
||||
import {
|
||||
COCKPIT_UTILITY_REC_GAP_PX,
|
||||
@@ -67,8 +66,6 @@ export function syncContextLayout() {
|
||||
if (window.matchMedia('(max-width: 760px)').matches) {
|
||||
this.context.dataset.layoutMode = 'compact-bottom';
|
||||
this.context.style.removeProperty('--cockpit-context-left');
|
||||
this.context.style.removeProperty('--cockpit-context-top');
|
||||
this.context.style.removeProperty('--cockpit-context-max-height');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -78,56 +75,6 @@ export function syncContextLayout() {
|
||||
'--cockpit-context-left',
|
||||
`${desktopInset.toFixed(1)}px`,
|
||||
);
|
||||
if (document.documentElement.dataset.uiTheme !== 'cyber') {
|
||||
this.context.style.removeProperty('--cockpit-context-top');
|
||||
this.context.style.removeProperty('--cockpit-context-max-height');
|
||||
return;
|
||||
}
|
||||
const defaultTop = Math.max(255, Math.min(300, window.innerHeight * 0.28));
|
||||
// An open left panel Cockpit keeps (Data Layers or Utilities).
|
||||
const dataPanel = document.querySelector(
|
||||
'#left-panel-stack > :is(#data-panel, #utilities-panel):not(.collapsed)',
|
||||
);
|
||||
let desiredTop = defaultTop;
|
||||
if (this.contextCollapsed && dataPanel) {
|
||||
desiredTop = Math.max(
|
||||
desiredTop,
|
||||
dataPanel.getBoundingClientRect().bottom + 8,
|
||||
);
|
||||
}
|
||||
const contextBounds = this.context.getBoundingClientRect();
|
||||
let safeBottom = window.innerHeight - 24;
|
||||
for (const selector of [
|
||||
'#cesium-credits',
|
||||
'#gev-credits',
|
||||
'#command-dock',
|
||||
'#view-switcher',
|
||||
]) {
|
||||
const obstacle = document.querySelector(selector);
|
||||
if (!obstacle) continue;
|
||||
const style = window.getComputedStyle(obstacle);
|
||||
if (
|
||||
style.display === 'none' ||
|
||||
style.visibility === 'hidden' ||
|
||||
Number(style.opacity) === 0
|
||||
)
|
||||
continue;
|
||||
const bounds = obstacle.getBoundingClientRect();
|
||||
const overlapsHorizontally =
|
||||
bounds.right > contextBounds.left && bounds.left < contextBounds.right;
|
||||
if (overlapsHorizontally && bounds.top > desiredTop) {
|
||||
safeBottom = Math.min(safeBottom, bounds.top - 8);
|
||||
}
|
||||
}
|
||||
const boundedTop = Math.max(
|
||||
defaultTop,
|
||||
Math.min(desiredTop, safeBottom - contextBounds.height),
|
||||
);
|
||||
this.context.style.setProperty(
|
||||
'--cockpit-context-top',
|
||||
`${boundedTop.toFixed(1)}px`,
|
||||
);
|
||||
this.context.style.removeProperty('--cockpit-context-max-height');
|
||||
}
|
||||
|
||||
export function syncSignalLayout() {
|
||||
@@ -138,8 +85,6 @@ export function syncSignalLayout() {
|
||||
// The compact strip shows only an expanded control.
|
||||
this.publishUtilityLayout(utilityLayoutView({ hideCollapsed: true }));
|
||||
this.signalStream.style.removeProperty('--cockpit-signal-right');
|
||||
this.signalStream.style.removeProperty('--cockpit-signal-top');
|
||||
this.signalStream.style.removeProperty('--cockpit-signal-max-height');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -149,36 +94,6 @@ export function syncSignalLayout() {
|
||||
'--cockpit-signal-right',
|
||||
`${desktopInset.toFixed(1)}px`,
|
||||
);
|
||||
this.signalStream.style.removeProperty('--cockpit-signal-top');
|
||||
this.signalStream.style.removeProperty('--cockpit-signal-max-height');
|
||||
const cyber = document.documentElement.dataset.uiTheme === 'cyber';
|
||||
const leftPanel = cyber
|
||||
? document.querySelector('#left-panel-stack > #data-panel')
|
||||
: null;
|
||||
const alignedTop = isRenderedOnScreen(leftPanel)
|
||||
? leftPanel.getBoundingClientRect().top
|
||||
: null;
|
||||
// Cyber's two rails share a top edge. Move the briefing below the collapsed
|
||||
// strip rather than pulling the right rail upward to avoid it.
|
||||
if (alignedTop !== null && utilityControls) {
|
||||
const expanded = utilityControls.querySelector(
|
||||
'.cockpit-utility-control.is-expanded',
|
||||
);
|
||||
if (!expanded) {
|
||||
const signalTop = Math.max(
|
||||
Math.max(255, Math.min(300, window.innerHeight * 0.28)),
|
||||
alignedTop + utilityControls.getBoundingClientRect().height + 28,
|
||||
);
|
||||
this.signalStream.style.setProperty(
|
||||
'--cockpit-signal-top',
|
||||
`${signalTop.toFixed(1)}px`,
|
||||
);
|
||||
this.signalStream.style.setProperty(
|
||||
'--cockpit-signal-max-height',
|
||||
`${Math.max(44, window.innerHeight - signalTop - 80).toFixed(1)}px`,
|
||||
);
|
||||
}
|
||||
}
|
||||
const signalBounds = this.signalStream.getBoundingClientRect();
|
||||
const utilityBounds = utilityControls?.getBoundingClientRect();
|
||||
if (utilityBounds) {
|
||||
@@ -203,42 +118,7 @@ export function syncSignalLayout() {
|
||||
collapsedLauncher.scrollHeight,
|
||||
)
|
||||
: 0;
|
||||
if (alignedTop !== null) {
|
||||
const lane = resolveCyberCockpitPanelLane({
|
||||
viewportHeight: window.innerHeight,
|
||||
top: alignedTop,
|
||||
launcherHeight: Math.max(
|
||||
collapsedHeight,
|
||||
collapsedLauncher?.getBoundingClientRect().height || 60,
|
||||
),
|
||||
signalHeight: this.signalCollapsed ? signalBounds.height : 44,
|
||||
contactHeight:
|
||||
this.contextCollapsed && this.context
|
||||
? this.context.getBoundingClientRect().height
|
||||
: 64,
|
||||
});
|
||||
document.body.style.setProperty(
|
||||
'--cyber-cockpit-panel-height',
|
||||
`${lane.panelHeight.toFixed(2)}px`,
|
||||
);
|
||||
this.publishUtilityLayout(
|
||||
utilityLayoutView({
|
||||
top: `${alignedTop.toFixed(2)}px`,
|
||||
maxHeight: `${lane.utilityHeight.toFixed(2)}px`,
|
||||
expandedMaxHeight: `${lane.panelHeight.toFixed(2)}px`,
|
||||
}),
|
||||
);
|
||||
if (expandedControl) {
|
||||
this.signalStream.style.setProperty(
|
||||
'--cockpit-signal-top',
|
||||
`${lane.signalTop.toFixed(2)}px`,
|
||||
);
|
||||
}
|
||||
this.syncContextLayout();
|
||||
return;
|
||||
}
|
||||
// Non-Cyber themes retain their independent REC/briefing corridor. Cyber
|
||||
// uses the rendered Data Layers top after reserving briefing space above.
|
||||
// The REC readout and the briefing card bound the utility corridor.
|
||||
// The readout only anchors the strip while it is genuinely on screen:
|
||||
// the Minimal variant drops it with `display:none`, but HUD Off hides the
|
||||
// whole Intel HUD with `visibility`/`opacity`, which keeps its rect.
|
||||
@@ -254,20 +134,8 @@ export function syncSignalLayout() {
|
||||
collapsedHeight,
|
||||
recGap: COCKPIT_UTILITY_REC_GAP_PX,
|
||||
signalGap: COCKPIT_UTILITY_SIGNAL_GAP_PX,
|
||||
minTopFloor: alignedTop ?? COCKPIT_UTILITY_MIN_TOP_PX,
|
||||
minTopRatio: alignedTop !== null ? 0 : COCKPIT_UTILITY_MIN_TOP_RATIO,
|
||||
signalCollapsed: this.signalCollapsed,
|
||||
utilityExpanded: Boolean(expandedControl),
|
||||
// Only Cyber relocates its collapsed briefing below the utility lane.
|
||||
// Other themes keep the measured visible card as the lower boundary.
|
||||
reserveViewportLane: document.documentElement.dataset.uiTheme === 'cyber',
|
||||
// Cyber keeps the collapsed briefing reachable below the utility instead
|
||||
// of hiding it. Reserve its actual height, including wrapped headings.
|
||||
signalHeight:
|
||||
document.documentElement.dataset.uiTheme === 'cyber' &&
|
||||
this.signalCollapsed
|
||||
? signalBounds.height
|
||||
: 0,
|
||||
minTopFloor: COCKPIT_UTILITY_MIN_TOP_PX,
|
||||
minTopRatio: COCKPIT_UTILITY_MIN_TOP_RATIO,
|
||||
});
|
||||
const availableHeight = utilityAnchor.maxHeight;
|
||||
const utilityLayout =
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
*/
|
||||
import { fromDegrees } from '../geo/ellipsoid.js';
|
||||
import { inputFor } from '../input/dispatcher.js';
|
||||
import { isUnderOtherCard } from '../data/pickRegistry.js';
|
||||
import { findQuery } from '../render/rendererOf.js';
|
||||
import { clampOrbitalLook, easeLook } from '../cockpitLook.js';
|
||||
import { ORBITAL_EARTH_RADIUS_M } from '../cockpitOrbital.js';
|
||||
@@ -286,7 +287,12 @@ export function routeSceneClick() {
|
||||
// A viewer with no input (headless tools, partial stubs) has no clicks.
|
||||
return () => {};
|
||||
}
|
||||
return input.onClick((event) => this.onOrbitalClick(event?.position));
|
||||
return input.onClick((event) => {
|
||||
// Another layer's card or label painted on top takes the click: the site
|
||||
// under it does not focus, and the click does not end a held focus.
|
||||
if (isUnderOtherCard(event)) return;
|
||||
this.onOrbitalClick(event?.position);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -31,6 +31,7 @@ import CockpitView from './views/CockpitView.vue';
|
||||
import ContextView from './views/ContextView.vue';
|
||||
import IntelHudView from './views/IntelHudView.vue';
|
||||
import { claimPointer, releasePointer } from '../data/inputOwnership.js';
|
||||
import { setClickCardHitTest } from '../data/pickRegistry.js';
|
||||
import { ORBITAL_FOCUS_EASE_TAU_MS } from '../cockpitOrbitalFocus.js';
|
||||
import { ORBITAL_HOP_MS } from '../cockpitOrbitalSatellites.js';
|
||||
|
||||
@@ -648,6 +649,23 @@ test('a click a tool owns is left alone', async (t) => {
|
||||
assert.equal(scene.cockpit.orbital.focus.key, SITES.alpha.id, 'kept while drawing');
|
||||
});
|
||||
|
||||
// The card or label painted on top takes the click: a site under another
|
||||
// layer's card does not focus, and a click there does not end a held focus.
|
||||
test('another layer\'s card over the orbital view keeps the click', async (t) => {
|
||||
const scene = await inOrbit(t);
|
||||
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
setClickCardHitTest(() => top);
|
||||
t.after(() => setClickCardHitTest(null));
|
||||
scene.click(SITES.alpha.at);
|
||||
assert.equal(scene.cockpit.orbital.focus ?? null, null, 'covered: no focus');
|
||||
top = null;
|
||||
scene.click(SITES.alpha.at);
|
||||
assert.equal(scene.cockpit.orbital.focus.key, SITES.alpha.id);
|
||||
top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
scene.click(EMPTY_GROUND);
|
||||
assert.equal(scene.cockpit.orbital.focus.key, SITES.alpha.id, 'covered: kept');
|
||||
});
|
||||
|
||||
test('a double-click on a site focuses it and keeps the orbital view', async (t) => {
|
||||
const scene = await inOrbit(t);
|
||||
const { cockpit, viewer, handler } = scene;
|
||||
|
||||
@@ -39,17 +39,42 @@ export function publishCockpitSignals() {
|
||||
this.scheduleContextLayout();
|
||||
}
|
||||
|
||||
export function pushCockpitSignal(key, tone, title, detail, target = null) {
|
||||
/**
|
||||
* Log a signal as the newest row, unless its key last said the same.
|
||||
* @param {{inPlace?: boolean}} [options] `inPlace`: a status row, such as a
|
||||
* provider's, that changes where it stands rather than log a new row, so a
|
||||
* changing ETA never pushes a steady warning off the list; it keeps its
|
||||
* time while it stays listed, and one pushed off comes back as the newest
|
||||
* row.
|
||||
*/
|
||||
export function pushCockpitSignal(
|
||||
key,
|
||||
tone,
|
||||
title,
|
||||
detail,
|
||||
target = null,
|
||||
{ inPlace = false } = {},
|
||||
) {
|
||||
if (!title || !detail) return;
|
||||
const signature = `${title}|${detail}|${target?.layerId || ''}|${target?.id || ''}`;
|
||||
if (this.signalSignatures.get(key) === signature) return;
|
||||
this.signalSignatures.set(key, signature);
|
||||
// JSON, not a joined string, so a separator inside a title or detail cannot
|
||||
// make two rows match. An in-place row also changes with its tone alone.
|
||||
const signature = JSON.stringify([
|
||||
title,
|
||||
detail,
|
||||
target?.layerId || '',
|
||||
target?.id || '',
|
||||
inPlace ? tone : '',
|
||||
]);
|
||||
// A locale change words the signal again where it stands.
|
||||
const shown = this.rewordingSignals
|
||||
? this.signalItems.find((item) => item.key === key)
|
||||
: null;
|
||||
const shown =
|
||||
this.rewordingSignals || inPlace
|
||||
? this.signalItems.find((item) => item.key === key)
|
||||
: null;
|
||||
if (this.signalSignatures.get(key) === signature && (!inPlace || shown))
|
||||
return;
|
||||
this.signalSignatures.set(key, signature);
|
||||
if (shown) {
|
||||
Object.assign(shown, { title, detail });
|
||||
Object.assign(shown, { tone, title, detail });
|
||||
this.publishCockpitSignals();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -27,6 +27,10 @@ import { fakeScenePorts } from '../testSupport/fakeCesiumScene.mjs';
|
||||
const LAT = 47;
|
||||
const LON = 8;
|
||||
const FLOOR_M = 400;
|
||||
/** Metres in a degree of longitude at LAT. */
|
||||
const M_PER_DEG_LON = 111_320 * Math.cos(Cesium.Math.toRadians(LAT));
|
||||
/** The longitude `m` metres east of LON. */
|
||||
const eastM = (m) => LON + m / M_PER_DEG_LON;
|
||||
|
||||
/** A HUD view model as a provider words it. */
|
||||
const HUD = Object.freeze({
|
||||
@@ -123,7 +127,10 @@ function subjectProvider(overrides = {}) {
|
||||
return { definition, subject, calls };
|
||||
}
|
||||
|
||||
function fixture(t, { providers = [], vessel = null, layerOn = true } = {}) {
|
||||
function fixture(
|
||||
t,
|
||||
{ providers = [], vessel = null, layerOn = true, realSignals = false } = {},
|
||||
) {
|
||||
document.body.replaceChildren();
|
||||
const host = document.body.appendChild(document.createElement('div'));
|
||||
const pinia = createPinia();
|
||||
@@ -204,6 +211,7 @@ function fixture(t, { providers = [], vessel = null, layerOn = true } = {}) {
|
||||
instruments: (view) => store.publishInstruments(view),
|
||||
route: (view) => store.publishRoute(view),
|
||||
radar: (view) => store.publishRadar(view),
|
||||
signals: realSignals ? (view) => store.publishSignals(view) : undefined,
|
||||
},
|
||||
});
|
||||
Object.assign(cockpit, {
|
||||
@@ -211,17 +219,20 @@ function fixture(t, { providers = [], vessel = null, layerOn = true } = {}) {
|
||||
showBriefPage() {},
|
||||
startBriefRotation() {},
|
||||
stopBriefRotation() {},
|
||||
pushCockpitSignal(key, tone, title, detail) {
|
||||
signals.push({ key, tone, title, detail });
|
||||
},
|
||||
dropCockpitSignal(key) {
|
||||
dropped.push(key);
|
||||
},
|
||||
scheduleContextLayout() {},
|
||||
updateLocalPosition() {},
|
||||
maybeRefreshRegionalBrief() {},
|
||||
showContextCard() {},
|
||||
});
|
||||
if (!realSignals)
|
||||
Object.assign(cockpit, {
|
||||
pushCockpitSignal(key, tone, title, detail) {
|
||||
signals.push({ key, tone, title, detail });
|
||||
},
|
||||
dropCockpitSignal(key) {
|
||||
dropped.push(key);
|
||||
},
|
||||
});
|
||||
t.after(() => {
|
||||
cockpit.stop();
|
||||
app.unmount();
|
||||
@@ -281,6 +292,25 @@ async function settle() {
|
||||
/** The provider's last release call. */
|
||||
const lastRelease = (calls) => calls.findLast(([name]) => name === 'release');
|
||||
|
||||
/**
|
||||
* Move `ride`'s subject east at `speedMps` from `startMs` (the manual clock's
|
||||
* start) on an inertial anchor, its frame otherwise as it was with `extra`
|
||||
* on top; returns a function giving its longitude now.
|
||||
*/
|
||||
function movingEast(ride, startMs, speedMps, extra = {}) {
|
||||
const eastNow = () =>
|
||||
eastM((speedMps * (performance.now() - startMs)) / 1000);
|
||||
const base = ride.subject.frame;
|
||||
ride.subject.frame = () => ({
|
||||
...base,
|
||||
longitude: eastNow(),
|
||||
speedMps,
|
||||
anchor: 'inertial',
|
||||
...extra,
|
||||
});
|
||||
return eastNow;
|
||||
}
|
||||
|
||||
/** The camera's height above the ellipsoid in its last shot (m). */
|
||||
const shotHeight = (shots) =>
|
||||
Cesium.Cartographic.fromCartesian(shots.at(-1).destination).height;
|
||||
@@ -560,7 +590,7 @@ test('a subject updated every 500 ms turns, eases and closes on its target at it
|
||||
ride.subject.frame = {
|
||||
...ride.subject.frame,
|
||||
headingDeg: 180,
|
||||
longitude: LON + 100 / (111_320 * Math.cos(Cesium.Math.toRadians(LAT))),
|
||||
longitude: eastM(100),
|
||||
};
|
||||
setFloor(FLOOR_M + 3.5);
|
||||
clock.advance(500);
|
||||
@@ -585,7 +615,78 @@ test('a subject updated every 500 ms turns, eases and closes on its target at it
|
||||
// A long stall (a hidden tab) moves it as one late update would.
|
||||
clock.advance(60_000);
|
||||
cockpit.update();
|
||||
assert.ok(Math.abs(cockpit.heading - 101) < 1e-6, 'at most 0.6 s');
|
||||
assert.ok(Math.abs(cockpit.heading - 110) < 1e-6, 'at most 1.5 s');
|
||||
});
|
||||
|
||||
test('a subject turning at the largest finite rate reaches its heading after a late update', async (t) => {
|
||||
const clock = manualClock(t, 10_000);
|
||||
const ride = subjectProvider({
|
||||
cameraIntervalMs: 500,
|
||||
headingSlewDps: Number.MAX_VALUE,
|
||||
});
|
||||
const { cockpit } = fixture(t, { providers: [ride] });
|
||||
cockpit.syncEntry();
|
||||
assert.equal(cockpit.enter(), true);
|
||||
clock.advance(500);
|
||||
cockpit.update();
|
||||
ride.subject.frame = { ...ride.subject.frame, headingDeg: 180 };
|
||||
// A 1.5 s step: the rate times it overflows to Infinity.
|
||||
clock.advance(1500);
|
||||
cockpit.update();
|
||||
assert.equal(cockpit.heading, 180);
|
||||
});
|
||||
|
||||
test('an inertial subject drawn at 5 frames a second stays near its target', async (t) => {
|
||||
const startMs = 10_000;
|
||||
const clock = manualClock(t, startMs);
|
||||
const ride = subjectProvider();
|
||||
const eastNow = movingEast(ride, startMs, 30);
|
||||
const { cockpit, shots } = fixture(t, { providers: [ride] });
|
||||
cockpit.syncEntry();
|
||||
assert.equal(cockpit.enter(), true);
|
||||
for (let i = 0; i < 300; i += 1) {
|
||||
clock.advance(200);
|
||||
cockpit.update();
|
||||
}
|
||||
const target = Cesium.Cartesian3.fromDegrees(eastNow(), LAT, FLOOR_M + 3.5);
|
||||
const gapM = Cesium.Cartesian3.distance(shots.at(-1).destination, target);
|
||||
assert.ok(
|
||||
gapM < 50,
|
||||
`after 60 s the camera is ${gapM.toFixed(0)} m from the subject`,
|
||||
);
|
||||
});
|
||||
|
||||
test("an inertial subject's first camera update after a floor wait longer than its step stands on it", async (t) => {
|
||||
const startMs = 10_000;
|
||||
const clock = manualClock(t, startMs);
|
||||
const intervalMs = 500;
|
||||
const ride = subjectProvider({ cameraIntervalMs: intervalMs });
|
||||
const eastNow = movingEast(ride, startMs, 30, { heightM: null });
|
||||
const { cockpit, shots, setFloor } = fixture(t, { providers: [ride] });
|
||||
setFloor(undefined);
|
||||
cockpit.syncEntry();
|
||||
assert.equal(cockpit.enter(), true);
|
||||
const before = shots.length;
|
||||
// 2 s cold: longer than the 1.5 s an update may step.
|
||||
for (let waited = intervalMs; waited < 2000; waited += intervalMs) {
|
||||
clock.advance(intervalMs);
|
||||
cockpit.update();
|
||||
}
|
||||
assert.equal(
|
||||
shots.length,
|
||||
before,
|
||||
'no camera update while the floor is cold',
|
||||
);
|
||||
setFloor(FLOOR_M);
|
||||
clock.advance(intervalMs);
|
||||
cockpit.update();
|
||||
const shot = Cesium.Cartographic.fromCartesian(shots[before].destination);
|
||||
const leadM =
|
||||
(Cesium.Math.toDegrees(shot.longitude) - eastNow()) * M_PER_DEG_LON;
|
||||
assert.ok(
|
||||
Math.abs(leadM) < 1,
|
||||
`the first camera update leads the subject by ${leadM.toFixed(2)} m`,
|
||||
);
|
||||
});
|
||||
|
||||
test('an exact anchor sits on the subject, wherever the frame moves it', async (t) => {
|
||||
@@ -863,6 +964,47 @@ test('a floor that never comes ends the view after the bounded wait, releasing t
|
||||
assert.deepEqual(lastRelease(ride.calls), ['release', 'a1', false]);
|
||||
});
|
||||
|
||||
for (const entryHeightM of [0, FLOOR_M]) {
|
||||
test(`a height the entry frame gave (${entryHeightM} m) holds while later frames give none and the floor is cold`, async (t) => {
|
||||
const clock = manualClock(t, 10_000);
|
||||
const ride = subjectProvider();
|
||||
ride.subject.frame = { ...ride.subject.frame, heightM: entryHeightM };
|
||||
const { cockpit, shots, setFloor } = fixture(t, { providers: [ride] });
|
||||
setFloor(undefined);
|
||||
cockpit.syncEntry();
|
||||
assert.equal(cockpit.enter(), true);
|
||||
ride.subject.frame = { ...ride.subject.frame, heightM: null };
|
||||
const waitPastTimeout = () => {
|
||||
for (
|
||||
let elapsed = 0;
|
||||
elapsed < COCKPIT_GROUND_WAIT_TIMEOUT_MS + 1000;
|
||||
elapsed += 100
|
||||
) {
|
||||
clock.advance(100);
|
||||
cockpit.update();
|
||||
}
|
||||
};
|
||||
waitPastTimeout();
|
||||
assert.equal(
|
||||
cockpit.active,
|
||||
true,
|
||||
'the view keeps the height its entry frame gave',
|
||||
);
|
||||
assert.ok(shots.length > 0, 'the camera is placed');
|
||||
assert.ok(Math.abs(shotHeight(shots) - (entryHeightM + 3.5)) < 0.01);
|
||||
// A floor that comes takes over, and is kept once it is cold again.
|
||||
const floorM = FLOOR_M - 100;
|
||||
setFloor(floorM);
|
||||
clock.advance(100);
|
||||
cockpit.update();
|
||||
assert.ok(Math.abs(shotHeight(shots) - (floorM + 3.5)) < 0.01);
|
||||
setFloor(undefined);
|
||||
waitPastTimeout();
|
||||
assert.equal(cockpit.active, true);
|
||||
assert.ok(Math.abs(shotHeight(shots) - (floorM + 3.5)) < 0.01);
|
||||
});
|
||||
}
|
||||
|
||||
test('an asynchronous hold that lands after entry was refused is released again', async (t) => {
|
||||
let heldId = null;
|
||||
const releases = [];
|
||||
@@ -942,6 +1084,30 @@ test('a provider’s labels, entry face and look follow a change of language', a
|
||||
);
|
||||
});
|
||||
|
||||
test('a provider whose labels throw after registration enters with no HUD kicker', async (t) => {
|
||||
manualClock(t, 10_000);
|
||||
let read = false;
|
||||
const ride = subjectProvider({
|
||||
labels() {
|
||||
if (read) throw new Error('word bundle unloaded');
|
||||
read = true;
|
||||
return {
|
||||
view: 'Tram view',
|
||||
exit: 'Exit tram view',
|
||||
exitText: 'EXIT TRAM',
|
||||
kicker: 'TRAM 4',
|
||||
};
|
||||
},
|
||||
});
|
||||
ride.subject.hud = { title: 'Example 12' };
|
||||
const { $, cockpit } = fixture(t, { providers: [ride] });
|
||||
cockpit.syncEntry();
|
||||
assert.equal(cockpit.enter(), true);
|
||||
await settle();
|
||||
// The kicker checked at registration stands in for the HUD view's.
|
||||
assert.equal($('.cockpit-kicker').textContent, 'TRAM 4');
|
||||
});
|
||||
|
||||
test('a read that throws ends the view once; a hud that throws keeps the last', async (t) => {
|
||||
const clock = manualClock(t, 10_000);
|
||||
const ride = subjectProvider();
|
||||
@@ -1122,26 +1288,78 @@ test('a subject first seen together with a built-in one comes after it', async (
|
||||
assert.equal(store.presence.entryKind, 'vessel');
|
||||
});
|
||||
|
||||
/**
|
||||
* Every world position projects to (x, y): the scene query port projects
|
||||
* through Cesium.SceneTransforms.
|
||||
*/
|
||||
function everythingAt(t, x, y) {
|
||||
t.mock.method(
|
||||
Cesium.SceneTransforms,
|
||||
'worldToWindowCoordinates',
|
||||
(_scene, _position, result = new Cesium.Cartesian2()) =>
|
||||
Object.assign(result, { x, y }),
|
||||
);
|
||||
}
|
||||
|
||||
test("a double-click on the selected vessel does not enter an application's subject", async (t) => {
|
||||
const clock = manualClock(t, 10_000);
|
||||
const ride = subjectProvider();
|
||||
ride.subject.candidate = null;
|
||||
const { cockpit, store, viewer } = fixture(t, {
|
||||
const { cockpit, store } = fixture(t, {
|
||||
providers: [ride],
|
||||
vessel: VESSEL,
|
||||
});
|
||||
everythingAt(t, 100, 100);
|
||||
cockpit.syncEntry();
|
||||
assert.equal(store.presence.entryKind, 'vessel');
|
||||
// The first press of the double-click notes where the vessel is drawn.
|
||||
cockpit.onScenePointerDown();
|
||||
// The application's subject is selected after the vessel: it takes entry.
|
||||
clock.advance(500);
|
||||
ride.subject.candidate = { id: 'a1', name: 'Example 12', selectedAt: 1 };
|
||||
cockpit.syncEntry();
|
||||
assert.equal(cockpit.resolveEntryKind(), 'example-kind');
|
||||
// Every world position lands under the pointer, the vessel's sprite too.
|
||||
viewer.scene.cartesianToCanvasCoordinates = (_position, result = {}) =>
|
||||
Object.assign(result, { x: 400, y: 300 });
|
||||
assert.equal(cockpit.onSceneDoubleClick({ x: 400, y: 300 }), false);
|
||||
assert.equal(store.presence.entryKind, 'example-kind');
|
||||
// The user double-clicks the vessel, still selected.
|
||||
assert.equal(cockpit.onSceneDoubleClick({ x: 100, y: 100 }), false);
|
||||
await settle();
|
||||
assert.notEqual(store.presence.active, true);
|
||||
assert.equal(
|
||||
cockpit.subjectProvider ?? null,
|
||||
null,
|
||||
'no provider view entered from a double-click on the vessel',
|
||||
);
|
||||
assert.equal(
|
||||
ride.calls.some(([name]) => name === 'hold'),
|
||||
false,
|
||||
'the provider subject was not held',
|
||||
);
|
||||
});
|
||||
|
||||
test('the same double-click on the vessel alone enters its bridge', async (t) => {
|
||||
manualClock(t, 10_000);
|
||||
const { cockpit, store } = fixture(t, { vessel: VESSEL });
|
||||
everythingAt(t, 100, 100);
|
||||
cockpit.syncEntry();
|
||||
assert.equal(store.presence.entryKind, 'vessel');
|
||||
assert.equal(cockpit.onSceneDoubleClick({ x: 100, y: 100 }), true);
|
||||
await settle();
|
||||
assert.equal(store.presence.active, true, 'the bridge is entered');
|
||||
assert.equal(cockpit.subjectKind, 'vessel');
|
||||
});
|
||||
|
||||
test("a moving vessel's first bridge update after entry stands the anchor on its fix", async (t) => {
|
||||
const clock = manualClock(t, 10_000);
|
||||
const { cockpit } = fixture(t, { vessel: VESSEL });
|
||||
cockpit.syncEntry();
|
||||
assert.equal(cockpit.enter(), true);
|
||||
clock.advance(1000);
|
||||
cockpit.update();
|
||||
const anchor = Cesium.Cartographic.fromCartesian(cockpit.cockpitAnchor);
|
||||
const fix = cockpit.vesselFix;
|
||||
const gapM = Cesium.Cartesian3.distance(
|
||||
Cesium.Cartesian3.fromRadians(anchor.longitude, anchor.latitude, 0),
|
||||
Cesium.Cartesian3.fromDegrees(fix.longitude, fix.latitude, 0),
|
||||
);
|
||||
assert.ok(gapM < 0.01, `the anchor is ${gapM.toFixed(2)} m from the fix`);
|
||||
});
|
||||
|
||||
test('a provider view with look turns with the arrow keys and words its readout', async (t) => {
|
||||
@@ -1188,3 +1406,238 @@ test('rows a HUD view no longer lists leave Live Signals', async (t) => {
|
||||
cockpit.update();
|
||||
assert.ok(dropped.includes('subject:note'));
|
||||
});
|
||||
|
||||
test('a signal still listed stays in Live Signals while another one changes', async (t) => {
|
||||
const clock = manualClock(t, 10_000);
|
||||
const ride = subjectProvider();
|
||||
const { cockpit } = fixture(t, { providers: [ride], realSignals: true });
|
||||
// The ETA is logged first, so it stands below the warning.
|
||||
const hudWith = (minutes) => ({
|
||||
...HUD,
|
||||
signals: [
|
||||
{ id: 'eta', title: 'NEXT', detail: `Central in ${minutes} min` },
|
||||
{
|
||||
id: 'doors',
|
||||
tone: 'warning',
|
||||
title: 'DOORS',
|
||||
detail: 'door fault, car 2',
|
||||
},
|
||||
],
|
||||
});
|
||||
const etaRow = () =>
|
||||
cockpit.signalItems.find((row) => row.key === 'subject:eta');
|
||||
ride.subject.hud = hudWith(10);
|
||||
cockpit.syncEntry();
|
||||
assert.equal(cockpit.enter(), true);
|
||||
const keysAtEntry = cockpit.signalItems.map((row) => row.key);
|
||||
const etaFirstSeen = etaRow().timestamp;
|
||||
for (let minutes = 9; minutes >= 2; minutes -= 1) {
|
||||
ride.subject.hud = hudWith(minutes);
|
||||
clock.advance(1000);
|
||||
cockpit.update();
|
||||
}
|
||||
const keys = cockpit.signalItems.map((row) => row.key);
|
||||
// Each row keeps its place, and the ETA the time it first appeared.
|
||||
assert.deepEqual(keys, keysAtEntry);
|
||||
assert.equal(etaRow().timestamp, etaFirstSeen);
|
||||
assert.ok(
|
||||
keys.includes('subject:doors'),
|
||||
`the warning the HUD still lists is shown (rows: ${keys.join(', ')})`,
|
||||
);
|
||||
// The changing one is one row, worded as it reads now.
|
||||
const etas = cockpit.signalItems.filter((row) => row.key === 'subject:eta');
|
||||
assert.deepEqual(
|
||||
etas.map((row) => row.detail),
|
||||
['Central in 2 min'],
|
||||
);
|
||||
// Rows pushed off the list by newer ones come back while still listed.
|
||||
for (let i = 0; i < 5; i += 1)
|
||||
cockpit.pushCockpitSignal(`other-${i}`, 'info', 'OTHER', `row ${i}`);
|
||||
assert.equal(
|
||||
cockpit.signalItems.some((row) => row.key.startsWith('subject:')),
|
||||
false,
|
||||
);
|
||||
clock.advance(1000);
|
||||
cockpit.update();
|
||||
assert.deepEqual(
|
||||
cockpit.signalItems
|
||||
.map((row) => row.key)
|
||||
.filter((key) => key.startsWith('subject:'))
|
||||
.sort(),
|
||||
['subject:doors', 'subject:eta'],
|
||||
);
|
||||
});
|
||||
|
||||
test('a Live Signals row whose tone alone changes takes the new tone', async (t) => {
|
||||
const clock = manualClock(t, 10_000);
|
||||
const ride = subjectProvider();
|
||||
const { cockpit, store } = fixture(t, {
|
||||
providers: [ride],
|
||||
realSignals: true,
|
||||
});
|
||||
const hudWith = (tone) => ({
|
||||
...HUD,
|
||||
signals: [
|
||||
{ id: 'doors', tone, title: 'DOORS', detail: 'door fault, car 2' },
|
||||
],
|
||||
});
|
||||
// The class of the row Live Signals shows.
|
||||
const doorsTone = () =>
|
||||
store.signals.find((row) => row.title === 'DOORS').className;
|
||||
ride.subject.hud = hudWith('normal');
|
||||
cockpit.syncEntry();
|
||||
assert.equal(cockpit.enter(), true);
|
||||
const tones = [doorsTone()];
|
||||
for (const tone of ['warning', 'normal']) {
|
||||
ride.subject.hud = hudWith(tone);
|
||||
clock.advance(1000);
|
||||
cockpit.update();
|
||||
tones.push(doorsTone());
|
||||
}
|
||||
assert.deepEqual(tones, ['info', 'warning', 'info']);
|
||||
});
|
||||
|
||||
test('rows a HUD view replaces leave before new ones push a listed one off', async (t) => {
|
||||
const clock = manualClock(t, 10_000);
|
||||
const ride = subjectProvider();
|
||||
const { cockpit } = fixture(t, { providers: [ride], realSignals: true });
|
||||
const row = (id, tone) => ({
|
||||
id,
|
||||
tone,
|
||||
title: id.toUpperCase(),
|
||||
detail: `row ${id}`,
|
||||
});
|
||||
ride.subject.hud = {
|
||||
...HUD,
|
||||
signals: [row('w', 'warning'), row('a'), row('b'), row('c')],
|
||||
};
|
||||
cockpit.syncEntry();
|
||||
assert.equal(cockpit.enter(), true);
|
||||
assert.ok(cockpit.signalItems.some((item) => item.key === 'track'));
|
||||
ride.subject.hud = {
|
||||
...HUD,
|
||||
signals: [row('w', 'warning'), row('a'), row('d'), row('e')],
|
||||
};
|
||||
clock.advance(1000);
|
||||
cockpit.update();
|
||||
const keys = cockpit.signalItems.map((item) => item.key);
|
||||
assert.deepEqual(
|
||||
[...keys].sort(),
|
||||
['subject:a', 'subject:d', 'subject:e', 'subject:w', 'track'],
|
||||
`rows right after the change: ${keys.join(', ')}`,
|
||||
);
|
||||
});
|
||||
|
||||
// An inertial subject placed at its entry frame's height while the floor was
|
||||
// cold stands on the floor as soon as it warms, as an exact anchor does.
|
||||
test('an inertial subject placed at its entry height stands on the floor once it warms', async (t) => {
|
||||
const clock = manualClock(t, 10_000);
|
||||
const ride = subjectProvider();
|
||||
ride.subject.frame = {
|
||||
...ride.subject.frame,
|
||||
heightM: FLOOR_M,
|
||||
speedMps: 0,
|
||||
anchor: 'inertial',
|
||||
eye: { ...ride.subject.frame.eye, forwardM: 0 },
|
||||
};
|
||||
const { cockpit, shots, setFloor } = fixture(t, { providers: [ride] });
|
||||
setFloor(undefined);
|
||||
cockpit.syncEntry();
|
||||
assert.equal(cockpit.enter(), true);
|
||||
ride.subject.frame = { ...ride.subject.frame, heightM: null };
|
||||
clock.advance(100);
|
||||
cockpit.update();
|
||||
assert.ok(Math.abs(shotHeight(shots) - (FLOOR_M + 3.5)) < 0.01);
|
||||
const floorM = FLOOR_M - 100;
|
||||
setFloor(floorM);
|
||||
for (let i = 0; i < 10; i += 1) {
|
||||
clock.advance(100);
|
||||
cockpit.update();
|
||||
}
|
||||
const heightM = shotHeight(shots);
|
||||
assert.ok(
|
||||
Math.abs(heightM - (floorM + 3.5)) < 1,
|
||||
`1 s after the floor came the eye is at ${heightM.toFixed(2)} m, not ${floorM + 3.5} m`,
|
||||
);
|
||||
});
|
||||
|
||||
/** How far east of LON the camera's last shot is (m). */
|
||||
const shotEastM = (shots) =>
|
||||
(Cesium.Math.toDegrees(
|
||||
Cesium.Cartographic.fromCartesian(shots.at(-1).destination).longitude,
|
||||
) -
|
||||
LON) *
|
||||
M_PER_DEG_LON;
|
||||
|
||||
test('the first floor after an entry height moves an inertial anchor as a cold floor does', async (t) => {
|
||||
// The provider corrects its subject 100 m east as the floor arrives.
|
||||
const run = (warm) => {
|
||||
const clock = manualClock(t, 10_000);
|
||||
const ride = subjectProvider();
|
||||
ride.subject.frame = {
|
||||
...ride.subject.frame,
|
||||
heightM: FLOOR_M,
|
||||
speedMps: 0,
|
||||
anchor: 'inertial',
|
||||
groundClamp: false,
|
||||
};
|
||||
const { cockpit, shots, setFloor } = fixture(t, { providers: [ride] });
|
||||
setFloor(undefined);
|
||||
cockpit.syncEntry();
|
||||
assert.equal(cockpit.enter(), true);
|
||||
ride.subject.frame = { ...ride.subject.frame, heightM: null };
|
||||
clock.advance(100);
|
||||
cockpit.update();
|
||||
const beforeM = shotEastM(shots);
|
||||
ride.subject.frame = { ...ride.subject.frame, longitude: eastM(100) };
|
||||
if (warm) setFloor(FLOOR_M + 0.1);
|
||||
clock.advance(100);
|
||||
cockpit.update();
|
||||
const stepM = shotEastM(shots) - beforeM;
|
||||
const heightM = shotHeight(shots);
|
||||
cockpit.stop();
|
||||
return { stepM, heightM };
|
||||
};
|
||||
const cold = run(false);
|
||||
const warm = run(true);
|
||||
assert.ok(
|
||||
Math.abs(warm.stepM - cold.stepM) < 0.02,
|
||||
`east step ${warm.stepM.toFixed(3)} m with the floor arriving, ${cold.stepM.toFixed(3)} m with it cold`,
|
||||
);
|
||||
assert.ok(Math.abs(warm.heightM - (FLOOR_M + 0.1 + 3.5)) < 0.02);
|
||||
});
|
||||
|
||||
test('the first floor after an entry height never steps an inertial anchor back to a held fix', async (t) => {
|
||||
const startMs = 10_000;
|
||||
const clock = manualClock(t, startMs);
|
||||
const ride = subjectProvider();
|
||||
const base = {
|
||||
...ride.subject.frame,
|
||||
heightM: FLOOR_M,
|
||||
speedMps: 30,
|
||||
anchor: 'inertial',
|
||||
groundClamp: false,
|
||||
};
|
||||
ride.subject.frame = base;
|
||||
const { cockpit, shots, setFloor } = fixture(t, { providers: [ride] });
|
||||
setFloor(undefined);
|
||||
cockpit.syncEntry();
|
||||
assert.equal(cockpit.enter(), true);
|
||||
// Telemetry that gives a new fix once a second, 30 m on each time.
|
||||
ride.subject.frame = () => ({
|
||||
...base,
|
||||
heightM: null,
|
||||
longitude: eastM(30 * Math.floor((performance.now() - startMs) / 1000)),
|
||||
});
|
||||
for (let i = 0; i < 17; i += 1) {
|
||||
clock.advance(100);
|
||||
cockpit.update();
|
||||
}
|
||||
const beforeM = shotEastM(shots);
|
||||
// The floor arrives 1 cm off the entry height, between two fixes.
|
||||
setFloor(FLOOR_M + 0.01);
|
||||
clock.advance(100);
|
||||
cockpit.update();
|
||||
const stepM = shotEastM(shots) - beforeM;
|
||||
assert.ok(stepM > 0, `the eye stepped ${stepM.toFixed(2)} m east`);
|
||||
});
|
||||
@@ -516,7 +516,10 @@ function enterSubject(provider) {
|
||||
this.surfaceAcquiring = false;
|
||||
this.surfaceFallback = false;
|
||||
this.cockpitAnchorValid = false;
|
||||
this.subjectHeightM = null;
|
||||
// The entry frame's height, if any, stands in for a cold floor
|
||||
// (updateSubject).
|
||||
this.subjectHeightM = frame.heightM;
|
||||
this.subjectHeightFromEntry = true;
|
||||
this.lookRestPitchDeg = provider.look?.restPitchDeg ?? null;
|
||||
this.resetLook({ immediate: true });
|
||||
this.active = true;
|
||||
|
||||
@@ -379,7 +379,7 @@ test('the layout pass’s measured fit hides the collapsed control and marks the
|
||||
app.unmount();
|
||||
});
|
||||
|
||||
test('the real layout pass drives the mounted controls: compact hides the collapsed sibling, Cyber shows both', async (t) => {
|
||||
test('the real layout pass drives the mounted controls: compact hides the collapsed sibling, desktop shows both', async (t) => {
|
||||
document.body.replaceChildren();
|
||||
const host = document.body.appendChild(document.createElement('div'));
|
||||
const pinia = createPinia();
|
||||
@@ -403,9 +403,6 @@ test('the real layout pass drives the mounted controls: compact hides the collap
|
||||
window.matchMedia = (query) => ({ matches: compact, media: query });
|
||||
t.after(() => {
|
||||
window.matchMedia = originalMatchMedia;
|
||||
delete document.documentElement.dataset.uiTheme;
|
||||
document.body.style.removeProperty('opacity');
|
||||
document.documentElement.style.removeProperty('opacity');
|
||||
app.unmount();
|
||||
});
|
||||
const strip = document.getElementById('cockpit-utility-controls');
|
||||
@@ -421,34 +418,13 @@ test('the real layout pass drives the mounted controls: compact hides the collap
|
||||
assert.equal(cockpit.utilityLayout.top, null);
|
||||
// Compact hides the sibling without marking the strip primary-only.
|
||||
assert.equal(strip.classList.contains('layout-primary-only'), false);
|
||||
// Cyber aligns the strip with the Data panel and keeps both controls.
|
||||
// The desktop pass anchors the strip in its own corridor and keeps both.
|
||||
compact = false;
|
||||
document.documentElement.dataset.uiTheme = 'cyber';
|
||||
const stack = document.body.appendChild(document.createElement('div'));
|
||||
stack.id = 'left-panel-stack';
|
||||
const dataPanel = stack.appendChild(document.createElement('section'));
|
||||
dataPanel.id = 'data-panel';
|
||||
for (const node of [
|
||||
dataPanel,
|
||||
stack,
|
||||
document.body,
|
||||
document.documentElement,
|
||||
])
|
||||
node.style.opacity = '1';
|
||||
dataPanel.getBoundingClientRect = () => ({
|
||||
top: 120,
|
||||
bottom: 400,
|
||||
left: 0,
|
||||
right: 200,
|
||||
width: 200,
|
||||
height: 280,
|
||||
});
|
||||
syncSignalLayout.call(owner);
|
||||
await nextTick();
|
||||
assert.equal(display.getAttribute('aria-hidden'), 'false');
|
||||
assert.equal(radioControl.getAttribute('aria-hidden'), 'false');
|
||||
assert.equal(cockpit.utilityLayout.top, '120.00px');
|
||||
assert.equal(strip.classList.contains('layout-primary-only'), false);
|
||||
assert.match(cockpit.utilityLayout.top, /^\d+(\.\d+)?px$/);
|
||||
});
|
||||
|
||||
test('the rail opens one panel at a time and reads as a disclosure', async (t) => {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -4,19 +4,6 @@ import {
|
||||
contextModeWord,
|
||||
} from '../contextModePolicy.js';
|
||||
|
||||
/** Why a Space Missions entry failed: its mission index never loaded, and
|
||||
* the error is no older than `since` (an earlier attempt's is not the cause). */
|
||||
export function spaceMissionsIndexFailure(dataManager, since = 0) {
|
||||
const stats = dataManager?.layers
|
||||
?.get('rocket-launches')
|
||||
?.module?.getStats?.();
|
||||
return stats?.error && stats.lastUpdate == null && stats.errorAt >= since
|
||||
? t(
|
||||
'Space Missions unavailable: the mission index could not load. Try again later.',
|
||||
)
|
||||
: null;
|
||||
}
|
||||
|
||||
export async function _runUserFacingContextAction(
|
||||
operation,
|
||||
message = t('Context could not restore every layer; try again'),
|
||||
@@ -71,7 +58,6 @@ export function getContextModeState() {
|
||||
changing: Boolean(this._contextModeChanging),
|
||||
entering: this._contextModeEntering || null,
|
||||
canContact: !this._contextMode || this._contextMode === 'flights',
|
||||
canMission: !this._contextMode || this._contextMode === 'space-missions',
|
||||
snapshotCaptured: Boolean(this._contextSessionSnapshot),
|
||||
};
|
||||
}
|
||||
@@ -127,7 +113,7 @@ export async function setContextMode(
|
||||
};
|
||||
}
|
||||
const canonical = mode === 'contacts' ? 'flights' : mode;
|
||||
if (!['flights', 'space-missions'].includes(canonical)) {
|
||||
if (canonical !== 'flights') {
|
||||
return {
|
||||
ok: false,
|
||||
action: 'set_context_mode',
|
||||
@@ -222,8 +208,6 @@ export function clearSelectedLayers() {
|
||||
this._contextModeChanging = true;
|
||||
this._contextMode = null;
|
||||
this._contextModeEntering = null;
|
||||
this._contextModeEntryIntent = null;
|
||||
this._contextModeReplacementIntent = null;
|
||||
this._contextSessionSnapshot = null;
|
||||
this._contextRestoreState = null;
|
||||
this._preservePanelStateDuringLayerClear = true;
|
||||
|
||||
@@ -1,28 +1,8 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { spaceMissionsIndexFailure } from './contextActions.js';
|
||||
import { translateStatusMessage } from './statusText.js';
|
||||
import { shouldExpandGlobalContextPanel } from '../rightRailPolicy.js';
|
||||
|
||||
export function _initGlobalContextPanel() {
|
||||
const contextTabs = [
|
||||
this._globalContextFlightsBtn,
|
||||
this._globalContextMissionsBtn,
|
||||
].filter(Boolean);
|
||||
contextTabs.forEach((tab, index) =>
|
||||
this.listen(tab, 'keydown', (event) => {
|
||||
let nextIndex = null;
|
||||
if (event.key === 'ArrowRight')
|
||||
nextIndex = (index + 1) % contextTabs.length;
|
||||
else if (event.key === 'ArrowLeft')
|
||||
nextIndex = (index - 1 + contextTabs.length) % contextTabs.length;
|
||||
else if (event.key === 'Home') nextIndex = 0;
|
||||
else if (event.key === 'End') nextIndex = contextTabs.length - 1;
|
||||
if (nextIndex === null) return;
|
||||
event.preventDefault();
|
||||
contextTabs[nextIndex].focus({ preventScroll: true });
|
||||
contextTabs[nextIndex].click();
|
||||
}),
|
||||
);
|
||||
this.listen(this._globalContextFlightsBtn, 'click', () => {
|
||||
if (
|
||||
this.destroyed ||
|
||||
@@ -51,40 +31,6 @@ export function _initGlobalContextPanel() {
|
||||
});
|
||||
});
|
||||
});
|
||||
this.listen(this._globalContextMissionsBtn, 'click', () => {
|
||||
if (
|
||||
this.destroyed ||
|
||||
this._contextModeChanging ||
|
||||
this._clearSelectedLayersPromise
|
||||
)
|
||||
return;
|
||||
const nextMode =
|
||||
this._contextMode === 'space-missions' ? null : 'space-missions';
|
||||
this._claimContextVisualAuthority();
|
||||
const startedAt = Date.now();
|
||||
void this._runUserFacingContextAction(
|
||||
(notificationToken) =>
|
||||
this._selectContextMode(nextMode, { notificationToken }),
|
||||
() =>
|
||||
(nextMode && spaceMissionsIndexFailure(this._dataManager, startedAt)) ||
|
||||
t(
|
||||
'Space Missions could not complete the requested transition; try again',
|
||||
),
|
||||
).then((succeeded) => {
|
||||
if (
|
||||
!this.destroyed &&
|
||||
nextMode &&
|
||||
shouldExpandGlobalContextPanel({
|
||||
action: 'space-missions',
|
||||
explicitUserAction: true,
|
||||
succeeded: succeeded === true,
|
||||
})
|
||||
)
|
||||
this.actions.setPanelCollapsed('global-context-panel', false, {
|
||||
explicit: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
this.listen(this._installationsSearchBtn, 'click', () => {
|
||||
if (
|
||||
this.destroyed ||
|
||||
|
||||
@@ -44,9 +44,6 @@ export class ContextControls {
|
||||
this._contextModeChanging = false;
|
||||
this._contextModeGeneration = 0;
|
||||
this._contextModeEntering = null;
|
||||
this._contextModeEntryIntent = null;
|
||||
this._contextModeReplacementIntent = null;
|
||||
this._contextModeDeferredEntryIntent = null;
|
||||
this._contextSessionSnapshot = null;
|
||||
this._contextRestoreState = null;
|
||||
this._contextLayerReactionPromises = new Set();
|
||||
|
||||
@@ -48,7 +48,6 @@ test('Context starts with an explicit idle snapshot', (t) => {
|
||||
changing: false,
|
||||
entering: null,
|
||||
canContact: true,
|
||||
canMission: true,
|
||||
snapshotCaptured: false,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,10 +2,6 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { setLocale } from '../i18n/index.js';
|
||||
import {
|
||||
contextLayerEnableBlockReason,
|
||||
parseContextLayerBlockReason,
|
||||
} from '../contextModePolicy.js';
|
||||
import {
|
||||
_handleContextLayerChange,
|
||||
localizeVisibilityBlockReason,
|
||||
@@ -18,7 +14,7 @@ function fakeShell() {
|
||||
_userFacingContextNotificationTokens: new Set(),
|
||||
_contextSessionSnapshot: null,
|
||||
_contextModeChanging: false,
|
||||
_contextMode: 'space-missions',
|
||||
_contextMode: null,
|
||||
_contextModeEntering: null,
|
||||
_syncContextModeButtons() {},
|
||||
showToast(message) {
|
||||
@@ -28,41 +24,19 @@ function fakeShell() {
|
||||
};
|
||||
}
|
||||
|
||||
const ENGLISH_GUARD =
|
||||
'Space Missions isolates replay data. Exit the mode to enable Live Flights.';
|
||||
|
||||
test.afterEach(() => setLocale('en'));
|
||||
|
||||
test('the guard reason is English data and parses back to its layer name', () => {
|
||||
const reason = contextLayerEnableBlockReason({
|
||||
contextMode: 'space-missions',
|
||||
change: { layerId: 'flights', enabled: true, origin: 'user' },
|
||||
layerName: 'Live Flights',
|
||||
});
|
||||
assert.equal(reason, ENGLISH_GUARD);
|
||||
assert.deepEqual(parseContextLayerBlockReason(reason), {
|
||||
layer: 'Live Flights',
|
||||
});
|
||||
assert.equal(parseContextLayerBlockReason('Data source unavailable'), null);
|
||||
assert.equal(
|
||||
parseContextLayerBlockReason(
|
||||
'Space Missions isolates replay data. Exit the mode to enable .',
|
||||
),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('en: the toast shows the reason unchanged', () => {
|
||||
setLocale('en');
|
||||
const shell = fakeShell();
|
||||
_handleContextLayerChange.call(shell, {
|
||||
type: 'visibility-blocked',
|
||||
layerId: 'flights',
|
||||
layerId: 'street-level',
|
||||
enabled: true,
|
||||
origin: 'user',
|
||||
reason: ENGLISH_GUARD,
|
||||
reason: 'Data source unavailable',
|
||||
});
|
||||
assert.deepEqual(shell.toasts, [ENGLISH_GUARD]);
|
||||
assert.deepEqual(shell.toasts, ['Data source unavailable']);
|
||||
assert.equal(
|
||||
localizeVisibilityBlockReason('Overpass returned HTTP 503'),
|
||||
'Overpass returned HTTP 503',
|
||||
@@ -70,27 +44,6 @@ test('en: the toast shows the reason unchanged', () => {
|
||||
});
|
||||
|
||||
for (const locale of ['es', 'ru']) {
|
||||
test(`${locale}: the Space Missions block toast is localized with the layer name`, () => {
|
||||
setLocale(locale);
|
||||
const reason = contextLayerEnableBlockReason({
|
||||
contextMode: 'space-missions',
|
||||
change: { layerId: 'flights', enabled: true, origin: 'user' },
|
||||
layerName: 'Live Flights',
|
||||
});
|
||||
const shell = fakeShell();
|
||||
_handleContextLayerChange.call(shell, {
|
||||
type: 'visibility-blocked',
|
||||
layerId: 'flights',
|
||||
enabled: true,
|
||||
origin: 'user',
|
||||
reason,
|
||||
});
|
||||
assert.equal(shell.toasts.length, 1);
|
||||
assert.notEqual(shell.toasts[0], ENGLISH_GUARD, 'toast must be localized');
|
||||
assert.doesNotMatch(shell.toasts[0], /Space Missions isolates/);
|
||||
assert.doesNotMatch(shell.toasts[0], /Live Flights/);
|
||||
});
|
||||
|
||||
test(`${locale}: a known lifecycle reason is looked up in the catalog`, () => {
|
||||
setLocale(locale);
|
||||
const shell = fakeShell();
|
||||
|
||||
+21
-109
@@ -1,28 +1,16 @@
|
||||
import { t, translateKnown } from '../i18n/index.js';
|
||||
import {
|
||||
SPACE_MISSIONS_LAYER_BLOCK_REASON,
|
||||
isExplicitUserIntentOrigin,
|
||||
parseContextLayerBlockReason,
|
||||
recordContextRestoreExplicitChange,
|
||||
recordContextSessionUserChange,
|
||||
shouldExitContextForLayerChange,
|
||||
spaceMissionEntryCancellationDisposition,
|
||||
} from '../contextModePolicy.js';
|
||||
import { localizeLayerName } from './layerNames.js';
|
||||
import { spaceMissionsIndexFailure } from './contextActions.js';
|
||||
|
||||
/**
|
||||
* A blocked-visibility reason in the UI language. Reasons stay English (voice
|
||||
* and tools read them): the Space Missions refusal is rebuilt with the layer
|
||||
* name localized, a known sentence is looked up, anything else passes.
|
||||
* and tools read them): a known sentence is looked up, anything else passes.
|
||||
*/
|
||||
export function localizeVisibilityBlockReason(reason) {
|
||||
if (typeof reason !== 'string' || !reason) return reason;
|
||||
const blocked = parseContextLayerBlockReason(reason);
|
||||
if (blocked)
|
||||
return t(SPACE_MISSIONS_LAYER_BLOCK_REASON, {
|
||||
layer: localizeLayerName(blocked.layer),
|
||||
});
|
||||
return translateKnown(reason);
|
||||
}
|
||||
|
||||
@@ -40,74 +28,12 @@ export function _handleContextLayerChange(change) {
|
||||
this.actions.refreshRadio();
|
||||
}
|
||||
if (change?.type === 'visibility-transition') return;
|
||||
// The effective mode must be read BEFORE the entering flag is cleared:
|
||||
// the entry layer's own enable event is the one that clears it, and the
|
||||
// session bookkeeping below needs to know a mode was being entered.
|
||||
// A mode still being entered counts for the session bookkeeping below.
|
||||
const effectiveContextMode = this._contextModeEntering || this._contextMode;
|
||||
if (change?.type === 'visibility-cancelled') {
|
||||
const cancellationDisposition = spaceMissionEntryCancellationDisposition({
|
||||
change,
|
||||
});
|
||||
if (
|
||||
this._contextModeDeferredEntryIntent?.layerId === change.layerId &&
|
||||
this._contextModeDeferredEntryIntent.intentEpoch === change.intentEpoch
|
||||
) {
|
||||
if (cancellationDisposition !== 'replacement') {
|
||||
this._contextModeDeferredEntryIntent = null;
|
||||
}
|
||||
}
|
||||
if (cancellationDisposition === 'replacement') {
|
||||
this._contextModeEntering = 'space-missions';
|
||||
const entryIntent = this._contextModeEntryIntent;
|
||||
if (
|
||||
entryIntent?.generation === this._contextModeGeneration &&
|
||||
entryIntent.layerId === change.layerId &&
|
||||
entryIntent.intentEpoch === change.intentEpoch
|
||||
) {
|
||||
this._contextModeReplacementIntent = {
|
||||
generation: entryIntent.generation,
|
||||
layerId: change.layerId,
|
||||
intentEpoch: change.successorIntentEpoch,
|
||||
};
|
||||
}
|
||||
} else if (cancellationDisposition === 'restore') {
|
||||
this._contextModeEntering = null;
|
||||
this._contextModeEntryIntent = null;
|
||||
this._contextModeReplacementIntent = null;
|
||||
if (this._contextSessionSnapshot && !this._contextModeChanging) {
|
||||
this._contextMode = null;
|
||||
void this._trackContextLayerReaction(
|
||||
this._runUserFacingContextAction(
|
||||
async (notificationToken) => {
|
||||
await this._restoreContextSessionAfterLayerSettles(
|
||||
change.layerId,
|
||||
{
|
||||
notificationToken,
|
||||
},
|
||||
);
|
||||
return true;
|
||||
},
|
||||
'Space Missions cancellation could not restore the previous layer state', // i18n-ignore: English message; the toast shows localizedMessage
|
||||
{
|
||||
localizedMessage: t(
|
||||
'Space Missions cancellation could not restore the previous layer state',
|
||||
),
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
this._syncContextModeButtons();
|
||||
return;
|
||||
}
|
||||
if (
|
||||
change?.layerId === 'rocket-launches' &&
|
||||
['visibility', 'visibility-blocked', 'visibility-failed'].includes(
|
||||
change.type,
|
||||
)
|
||||
) {
|
||||
this._contextModeEntering = null;
|
||||
}
|
||||
if (change?.type === 'visibility-blocked') {
|
||||
if (
|
||||
!this._userFacingContextNotificationTokens.has(change.notificationToken)
|
||||
@@ -121,10 +47,13 @@ export function _handleContextLayerChange(change) {
|
||||
return;
|
||||
}
|
||||
if (change?.type === 'visibility-failed') {
|
||||
// A layer may name why its own start failed (Space Missions: the
|
||||
// mission index never loaded).
|
||||
const failureMessage =
|
||||
(change.layerId === 'rocket-launches' &&
|
||||
change.enabled &&
|
||||
spaceMissionsIndexFailure(this._dataManager)) ||
|
||||
(change.enabled &&
|
||||
this._dataManager?.layers
|
||||
?.get(change.layerId)
|
||||
?.module?.enableFailureMessage?.()) ||
|
||||
t('{layerId} could not {action} cleanly', {
|
||||
layerId: change.layerId,
|
||||
action: change.enabled ? t('start') : t('stop'),
|
||||
@@ -134,7 +63,7 @@ export function _handleContextLayerChange(change) {
|
||||
// notification for this queue to settle, then reconcile the complete
|
||||
// snapshot, including an uncertain failed shell.
|
||||
const needsDeferredShellRestore =
|
||||
['military-awareness', 'rocket-launches'].includes(change.layerId) &&
|
||||
change.layerId === 'military-awareness' &&
|
||||
change.enabled &&
|
||||
this._contextSessionSnapshot &&
|
||||
!this._contextModeChanging;
|
||||
@@ -212,26 +141,6 @@ export function _handleContextLayerChange(change) {
|
||||
),
|
||||
);
|
||||
}
|
||||
} else if (change.layerId === 'rocket-launches') {
|
||||
const ownsContextEntry =
|
||||
isExplicitUserIntentOrigin(change.origin, change.layerId) ||
|
||||
this._contextMode === 'space-missions' ||
|
||||
effectiveContextMode === 'space-missions';
|
||||
if (!ownsContextEntry) return;
|
||||
this._contextMode = change.enabled
|
||||
? 'space-missions'
|
||||
: this._contextMode === 'space-missions'
|
||||
? null
|
||||
: this._contextMode;
|
||||
if (change.enabled) {
|
||||
this._syncContextModeButtons();
|
||||
} else if (this._contextSessionSnapshot) {
|
||||
void this._trackContextLayerReaction(
|
||||
this._runUserFacingContextAction((notificationToken) =>
|
||||
this._deactivateContextForLayerChange({ notificationToken }),
|
||||
),
|
||||
);
|
||||
}
|
||||
} else if (
|
||||
this._contextMode === 'flights' &&
|
||||
[
|
||||
@@ -254,23 +163,26 @@ export function _handleContextLayerChange(change) {
|
||||
change.enabled &&
|
||||
change.origin === 'user' &&
|
||||
!this.cockpitView?.active &&
|
||||
(change.layerId === 'radio' || change.layerId === 'rocket-launches')
|
||||
change.layerId === 'radio'
|
||||
) {
|
||||
// Context's panel shows its main tab for them (ContextView listens).
|
||||
globalThis.dispatchEvent?.(new Event('gev:context-show-view'));
|
||||
this.actions.setPanelCollapsed('global-context-panel', false, {
|
||||
explicit: true,
|
||||
});
|
||||
if (change.layerId === 'radio')
|
||||
this.actions.setPanelCollapsed('radio-panel', false, { explicit: true });
|
||||
this.actions.setPanelCollapsed('radio-panel', false, { explicit: true });
|
||||
}
|
||||
finishContextLayerChange(this);
|
||||
}
|
||||
|
||||
/** The checks every settled layer change ends with. */
|
||||
function finishContextLayerChange(controls) {
|
||||
// Turning off the layer the view rides ends it; every other layer may be
|
||||
// turned on or off freely during a session.
|
||||
const riddenLayerId = this.cockpitView?.active
|
||||
? this.cockpitView.readSubjectLayerId?.()
|
||||
const riddenLayerId = controls.cockpitView?.active
|
||||
? controls.cockpitView.readSubjectLayerId?.()
|
||||
: null;
|
||||
if (riddenLayerId && !this._dataManager?.isEnabled(riddenLayerId)) {
|
||||
this.cockpitView.exit({ restoreTracking: false });
|
||||
if (riddenLayerId && !controls._dataManager?.isEnabled(riddenLayerId)) {
|
||||
controls.cockpitView.exit({ restoreTracking: false });
|
||||
}
|
||||
this._syncContextModeButtons();
|
||||
controls._syncContextModeButtons();
|
||||
}
|
||||
@@ -22,7 +22,6 @@ function fixture(t) {
|
||||
const controls = new ContextControls({
|
||||
elements: {
|
||||
_globalContextFlightsBtn: $('global-context-flights-btn'),
|
||||
_globalContextMissionsBtn: $('global-context-missions-btn'),
|
||||
_installationsSearchBtn: $('installations-search-btn'),
|
||||
},
|
||||
installations: {},
|
||||
@@ -58,61 +57,41 @@ test('before ContextControls renders, the switch shows its initial markup', (t)
|
||||
'ui-panel panel-collapsible collapsed ui-panel--collapsed',
|
||||
);
|
||||
assert.equal(panel.hasAttribute('data-context-mode'), false);
|
||||
for (const id of [
|
||||
'global-context-flights-btn',
|
||||
'global-context-missions-btn',
|
||||
]) {
|
||||
const tab = $(id);
|
||||
assert.equal(tab.className, 'context-mode-button');
|
||||
assert.equal(tab.getAttribute('aria-selected'), 'false');
|
||||
assert.equal(tab.getAttribute('tabindex'), '0');
|
||||
assert.equal(tab.hasAttribute('aria-busy'), false);
|
||||
}
|
||||
const tab = $('global-context-flights-btn');
|
||||
assert.equal(tab.className, 'context-mode-button');
|
||||
assert.equal(tab.getAttribute('aria-selected'), 'false');
|
||||
assert.equal(tab.getAttribute('tabindex'), '0');
|
||||
assert.equal(tab.hasAttribute('aria-busy'), false);
|
||||
assert.equal($('context-mode-standby').hidden, false);
|
||||
assert.equal($('context-flights-view').hidden, true);
|
||||
assert.equal($('context-missions-view').hidden, true);
|
||||
assert.equal($('global-context-missions-btn'), null);
|
||||
assert.equal($('context-missions-view'), null);
|
||||
assert.equal($('installations-search-btn').hasAttribute('aria-busy'), false);
|
||||
});
|
||||
|
||||
test('a transition keeps focus and Tab on both tabs until it settles', async (t) => {
|
||||
test('a Contacts transition keeps the tab focusable until it settles', async (t) => {
|
||||
const { $, controls, sync } = fixture(t);
|
||||
const contacts = $('global-context-flights-btn');
|
||||
const missions = $('global-context-missions-btn');
|
||||
missions.focus();
|
||||
contacts.focus();
|
||||
controls._contextModeChanging = true;
|
||||
await sync();
|
||||
assert.equal(
|
||||
document.activeElement === missions,
|
||||
true,
|
||||
'busy render keeps focus',
|
||||
);
|
||||
for (const tab of [contacts, missions]) {
|
||||
assert.equal(tab.disabled, false);
|
||||
assert.equal(tab.getAttribute('tabindex'), '0');
|
||||
assert.equal(tab.getAttribute('aria-disabled'), 'true');
|
||||
assert.equal(tab.getAttribute('aria-busy'), 'true');
|
||||
}
|
||||
assert.equal(document.activeElement, contacts);
|
||||
assert.equal(contacts.disabled, false);
|
||||
assert.equal(contacts.getAttribute('tabindex'), '0');
|
||||
assert.equal(contacts.getAttribute('aria-disabled'), 'true');
|
||||
assert.equal(contacts.getAttribute('aria-busy'), 'true');
|
||||
|
||||
controls._contextModeChanging = false;
|
||||
controls._contextMode = 'space-missions';
|
||||
controls._contextMode = 'flights';
|
||||
await sync();
|
||||
assert.equal(
|
||||
document.activeElement === missions,
|
||||
true,
|
||||
'settled render keeps focus',
|
||||
);
|
||||
for (const tab of [contacts, missions]) {
|
||||
assert.equal(tab.disabled, false);
|
||||
assert.equal(tab.getAttribute('aria-disabled'), 'false');
|
||||
assert.equal(tab.getAttribute('aria-busy'), 'false');
|
||||
}
|
||||
assert.equal(missions.classList.contains('active'), true);
|
||||
assert.equal(missions.getAttribute('aria-selected'), 'true');
|
||||
assert.equal(contacts.classList.contains('active'), false);
|
||||
assert.equal(contacts.getAttribute('aria-selected'), 'false');
|
||||
assert.equal(document.activeElement, contacts);
|
||||
assert.equal(contacts.disabled, false);
|
||||
assert.equal(contacts.getAttribute('aria-disabled'), 'false');
|
||||
assert.equal(contacts.getAttribute('aria-busy'), 'false');
|
||||
assert.equal(contacts.classList.contains('active'), true);
|
||||
assert.equal(contacts.getAttribute('aria-selected'), 'true');
|
||||
assert.equal($('context-mode-standby').hidden, true);
|
||||
assert.equal($('context-flights-view').hidden, true);
|
||||
assert.equal($('context-missions-view').hidden, false);
|
||||
assert.equal($('context-flights-view').hidden, false);
|
||||
});
|
||||
|
||||
test('the panel carries the mode beside the classes its chrome writes', async (t) => {
|
||||
|
||||
@@ -12,17 +12,10 @@ export function _syncContextModeButtons() {
|
||||
export function _presentContext() {
|
||||
if (this.destroyed) return;
|
||||
const flightsActive = this._contextMode === 'flights';
|
||||
const missionsActive = this._contextMode === 'space-missions';
|
||||
// Both Context choices stay in the ordinary Tab sequence and are never
|
||||
// native-disabled. Arrow keys still provide tablist navigation, but must
|
||||
// not be the only way to reach Space Missions from the keyboard. Semantic
|
||||
// busy state keeps them perceivable while synchronous click guards prevent
|
||||
// a second transition.
|
||||
this.publish({
|
||||
mode: this._contextMode || 'none',
|
||||
enabled: flightsActive || missionsActive,
|
||||
enabled: flightsActive,
|
||||
flightsActive,
|
||||
missionsActive,
|
||||
busy: Boolean(this._contextModeChanging),
|
||||
installationsBusy: this._installationsSearchBusy,
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
CONTEXT_INDEPENDENT_LAYER_IDS,
|
||||
contextRestoreLayerIds,
|
||||
contextSnapshotLayerIds,
|
||||
mergeContextTransitionErrors,
|
||||
@@ -24,7 +25,8 @@ export async function _waitForContextLayerSettlement() {
|
||||
export function _captureContextSessionSnapshot({ excludeLayerIds = [] } = {}) {
|
||||
if (!this._dataManager || this._contextSessionSnapshot) return;
|
||||
const params = {};
|
||||
for (const layerId of ['military-awareness', 'satellites']) {
|
||||
// Satellites is not Context's: the mission controller owns its parameters.
|
||||
for (const layerId of ['military-awareness']) {
|
||||
const value = this._dataManager.getLayerParams(layerId);
|
||||
if (value) params[layerId] = value;
|
||||
}
|
||||
@@ -93,9 +95,11 @@ export async function _restoreContextSession({
|
||||
restoreState.enabledLayerIds,
|
||||
{
|
||||
origin: 'context-restore',
|
||||
excludeLayerIds: settleContactsCoordinator
|
||||
? [...excludeLayerIds, contactsCoordinatorId]
|
||||
: excludeLayerIds,
|
||||
excludeLayerIds: [
|
||||
...excludeLayerIds,
|
||||
...CONTEXT_INDEPENDENT_LAYER_IDS,
|
||||
...(settleContactsCoordinator ? [contactsCoordinatorId] : []),
|
||||
],
|
||||
notificationToken,
|
||||
...(restoreSignal ? { signal: restoreSignal } : {}),
|
||||
},
|
||||
|
||||
+38
-104
@@ -1,11 +1,8 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import {
|
||||
contextLayerEnableBlockReason,
|
||||
isExplicitUserIntentOrigin,
|
||||
runWithContextModeChanging,
|
||||
settleContextModeChange,
|
||||
shouldCaptureContextSession,
|
||||
shouldDeferContextEntryDuringClear,
|
||||
} from '../contextModePolicy.js';
|
||||
|
||||
export function connectContextManager(manager) {
|
||||
@@ -28,31 +25,6 @@ export function connectContextManager(manager) {
|
||||
this._captureContextSessionSnapshot({
|
||||
excludeLayerIds: [change.layerId],
|
||||
});
|
||||
if (
|
||||
shouldDeferContextEntryDuringClear({
|
||||
change,
|
||||
clearInFlight: Boolean(this._clearSelectedLayersPromise),
|
||||
})
|
||||
) {
|
||||
this._contextModeDeferredEntryIntent = {
|
||||
layerId: change.layerId,
|
||||
intentEpoch: change.intentEpoch,
|
||||
origin: change.origin,
|
||||
};
|
||||
this._contextModeEntering = 'space-missions';
|
||||
this._syncContextModeButtons();
|
||||
}
|
||||
} else if (
|
||||
change?.layerId === 'rocket-launches' &&
|
||||
change.enabled === false &&
|
||||
isExplicitUserIntentOrigin(change.origin, change.layerId)
|
||||
) {
|
||||
this._contextModeDeferredEntryIntent = null;
|
||||
if (this._clearSelectedLayersPromise) {
|
||||
this._contextSessionSnapshot = null;
|
||||
this._contextModeEntering = null;
|
||||
this._syncContextModeButtons();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -60,88 +32,50 @@ export function connectContextManager(manager) {
|
||||
this._dataManagerVisibilityGuardUnsubscribe =
|
||||
this._dataManager.addVisibilityGuard(async (change) => {
|
||||
if (this.destroyed) return null;
|
||||
const layerName =
|
||||
this._dataManager?.layers?.get(change.layerId)?.module?.name ||
|
||||
change.layerId;
|
||||
const reason = contextLayerEnableBlockReason({
|
||||
contextMode: this._contextModeEntering || this._contextMode,
|
||||
change,
|
||||
layerName,
|
||||
});
|
||||
if (reason) return reason;
|
||||
// A direct Contacts start (the coordinator layer itself, not the
|
||||
// Context chooser) isolates its dependencies like the chooser does.
|
||||
if (
|
||||
change.enabled &&
|
||||
['military-awareness', 'rocket-launches'].includes(change.layerId) &&
|
||||
shouldCaptureContextSession(change) &&
|
||||
(!this._contextModeChanging ||
|
||||
(change.layerId === 'rocket-launches' &&
|
||||
this._contextModeDeferredEntryIntent?.intentEpoch ===
|
||||
change.intentEpoch))
|
||||
) {
|
||||
const entryMode =
|
||||
change.layerId === 'rocket-launches' ? 'space-missions' : null;
|
||||
const deferredClearEntry =
|
||||
this._contextModeDeferredEntryIntent?.intentEpoch ===
|
||||
change.intentEpoch;
|
||||
// A deferred entry owns the state after Clear settles. Restoring
|
||||
// Clear's transient busy flag here would leave Context stuck.
|
||||
const priorChanging = deferredClearEntry
|
||||
? false
|
||||
: this._contextModeChanging;
|
||||
const notificationToken =
|
||||
change.notificationToken || Symbol('direct-context-shell-entry');
|
||||
const ownsNotificationToken = !change.notificationToken;
|
||||
if (ownsNotificationToken) {
|
||||
this._userFacingContextNotificationTokens.add(notificationToken);
|
||||
}
|
||||
this._contextModeEntering = entryMode;
|
||||
this._contextModeChanging = true;
|
||||
!change.enabled ||
|
||||
change.layerId !== 'military-awareness' ||
|
||||
!shouldCaptureContextSession(change) ||
|
||||
this._contextModeChanging
|
||||
)
|
||||
return null;
|
||||
const notificationToken =
|
||||
change.notificationToken || Symbol('direct-context-shell-entry');
|
||||
const ownsNotificationToken = !change.notificationToken;
|
||||
if (ownsNotificationToken) {
|
||||
this._userFacingContextNotificationTokens.add(notificationToken);
|
||||
}
|
||||
this._contextModeEntering = null;
|
||||
this._contextModeChanging = true;
|
||||
try {
|
||||
await this._clearLayersOutsideContextMode(null, {
|
||||
notificationToken,
|
||||
});
|
||||
if (this.destroyed) return false;
|
||||
} catch (error) {
|
||||
console.warn(`[Context] ${change.layerId} isolation failed`, error);
|
||||
try {
|
||||
if (deferredClearEntry) {
|
||||
await this._clearSelectedLayersManagerPromise;
|
||||
if (this.destroyed) return false;
|
||||
if (
|
||||
this._contextModeDeferredEntryIntent?.intentEpoch !==
|
||||
change.intentEpoch
|
||||
)
|
||||
return false;
|
||||
this._contextModeDeferredEntryIntent = null;
|
||||
}
|
||||
await this._clearLayersOutsideContextMode(entryMode, {
|
||||
await this._restoreContextSession({
|
||||
excludeLayerIds: [change.layerId],
|
||||
notificationToken,
|
||||
});
|
||||
if (this.destroyed) return false;
|
||||
} catch (error) {
|
||||
this._contextModeEntering = null;
|
||||
console.warn(`[Context] ${change.layerId} isolation failed`, error);
|
||||
try {
|
||||
await this._restoreContextSession({
|
||||
excludeLayerIds: [change.layerId],
|
||||
notificationToken,
|
||||
});
|
||||
} catch (restoreError) {
|
||||
console.warn(
|
||||
`[Context] ${change.layerId} rollback failed`,
|
||||
restoreError,
|
||||
);
|
||||
}
|
||||
return t(
|
||||
'{mode} could not start because another layer did not stop cleanly',
|
||||
{
|
||||
mode:
|
||||
entryMode === 'space-missions'
|
||||
? t('Space Missions')
|
||||
: t('Context'),
|
||||
},
|
||||
} catch (restoreError) {
|
||||
console.warn(
|
||||
`[Context] ${change.layerId} rollback failed`,
|
||||
restoreError,
|
||||
);
|
||||
} finally {
|
||||
if (ownsNotificationToken) {
|
||||
this._userFacingContextNotificationTokens.delete(
|
||||
notificationToken,
|
||||
);
|
||||
}
|
||||
if (!this.destroyed) settleContextModeChange(this, priorChanging);
|
||||
}
|
||||
return t(
|
||||
'{mode} could not start because another layer did not stop cleanly',
|
||||
{ mode: t('Context') },
|
||||
);
|
||||
} finally {
|
||||
if (ownsNotificationToken) {
|
||||
this._userFacingContextNotificationTokens.delete(notificationToken);
|
||||
}
|
||||
if (!this.destroyed) settleContextModeChange(this, false);
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
@@ -13,8 +13,6 @@ export async function _selectContextMode(
|
||||
const generation = ++this._contextModeGeneration;
|
||||
const isCurrent = () =>
|
||||
!this.destroyed && generation === this._contextModeGeneration;
|
||||
this._contextModeEntryIntent = null;
|
||||
this._contextModeReplacementIntent = null;
|
||||
this._contextModeChanging = true;
|
||||
this._syncContextModeButtons();
|
||||
try {
|
||||
@@ -47,9 +45,6 @@ export async function _selectContextMode(
|
||||
this._captureContextSessionSnapshot();
|
||||
this._contextMode = mode;
|
||||
this._syncContextModeButtons();
|
||||
// Replay isolation must settle before Space Missions starts. Contacts
|
||||
// keeps its non-dependency teardown in the background so slow source
|
||||
// shutdown does not delay cockpit entry.
|
||||
try {
|
||||
await this._clearLayersOutsideContextMode(mode, {
|
||||
notificationToken,
|
||||
@@ -82,13 +77,8 @@ export async function _selectContextMode(
|
||||
// Entry is one transaction: isolation succeeded above, so a failed mode
|
||||
// activation must roll the cleared layers back instead of stranding the
|
||||
// user in a half-entered mode with an orphaned snapshot.
|
||||
const entryLayerId =
|
||||
mode === 'flights' ? 'military-awareness' : 'rocket-launches';
|
||||
if (mode === 'flights') {
|
||||
this._dataManager.setLayerParams('military-awareness', {
|
||||
passive: false,
|
||||
});
|
||||
}
|
||||
const entryLayerId = 'military-awareness';
|
||||
this._dataManager.setLayerParams(entryLayerId, { passive: false });
|
||||
let activated = false;
|
||||
let activationError = null;
|
||||
let activationIntent = null;
|
||||
@@ -99,11 +89,6 @@ export async function _selectContextMode(
|
||||
true,
|
||||
{ notificationToken, ...(signal ? { signal } : {}) },
|
||||
);
|
||||
this._contextModeEntryIntent = {
|
||||
generation,
|
||||
layerId: entryLayerId,
|
||||
intentEpoch: activationIntent.intentEpoch,
|
||||
};
|
||||
activated = await activationIntent.promise;
|
||||
terminalIntentOutcome =
|
||||
await this._dataManager._waitForVisibilityIntent?.(
|
||||
@@ -114,46 +99,6 @@ export async function _selectContextMode(
|
||||
activationError = error;
|
||||
}
|
||||
if (!isCurrent()) return false;
|
||||
let replacementIntent =
|
||||
mode === 'space-missions' &&
|
||||
this._contextModeReplacementIntent?.generation === generation &&
|
||||
this._contextModeReplacementIntent.layerId === entryLayerId
|
||||
? this._contextModeReplacementIntent
|
||||
: null;
|
||||
while (replacementIntent) {
|
||||
const outcome = await this._dataManager._waitForVisibilityIntent?.(
|
||||
entryLayerId,
|
||||
replacementIntent.intentEpoch,
|
||||
);
|
||||
terminalIntentOutcome = outcome;
|
||||
if (!isCurrent()) return false;
|
||||
const replacementOwnsMode =
|
||||
outcome?.intentEpoch === replacementIntent.intentEpoch &&
|
||||
outcome.enabled === true &&
|
||||
outcome.succeeded === true;
|
||||
if (replacementOwnsMode) {
|
||||
this._contextModeEntering = null;
|
||||
this._contextModeEntryIntent = null;
|
||||
this._contextModeReplacementIntent = null;
|
||||
this._syncContextModeButtons();
|
||||
return true;
|
||||
}
|
||||
const successorEpoch =
|
||||
outcome?.cancellationReason === 'superseded' &&
|
||||
outcome.successorEnabled === true &&
|
||||
Number.isInteger(outcome.successorIntentEpoch) &&
|
||||
outcome.successorIntentEpoch > replacementIntent.intentEpoch
|
||||
? outcome.successorIntentEpoch
|
||||
: null;
|
||||
replacementIntent =
|
||||
successorEpoch === null
|
||||
? null
|
||||
: {
|
||||
generation,
|
||||
layerId: entryLayerId,
|
||||
intentEpoch: successorEpoch,
|
||||
};
|
||||
}
|
||||
if (
|
||||
activationError ||
|
||||
activated === false ||
|
||||
@@ -182,8 +127,6 @@ export async function _selectContextMode(
|
||||
);
|
||||
}
|
||||
this._contextMode = null;
|
||||
this._contextModeEntryIntent = null;
|
||||
this._contextModeReplacementIntent = null;
|
||||
this._syncContextModeButtons();
|
||||
try {
|
||||
await this._restoreContextSession({
|
||||
@@ -205,7 +148,6 @@ export async function _selectContextMode(
|
||||
// while callers still require literal `true` before expanding Context.
|
||||
return cancelledAndSettled ? null : false;
|
||||
}
|
||||
this._contextModeEntryIntent = null;
|
||||
return true;
|
||||
} finally {
|
||||
if (isCurrent()) {
|
||||
@@ -221,8 +163,6 @@ export async function _deactivateContextForLayerChange({
|
||||
this._contextModeGeneration += 1;
|
||||
this._contextModeChanging = true;
|
||||
this._contextMode = null;
|
||||
this._contextModeEntryIntent = null;
|
||||
this._contextModeReplacementIntent = null;
|
||||
// A layer turned off ends Contacts but not the Cockpit: the view ends only
|
||||
// when the layer it rides goes off (see _handleContextLayerChange).
|
||||
this._syncContextModeButtons();
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* @module ui/creditLineHeight
|
||||
* @description Keeps `--credit-line-height` on the page's root at the
|
||||
* height of the attribution line at the bottom of the screen, so what sits
|
||||
* above it (the HUD's bottom corners) clears it when it wraps onto more
|
||||
* lines. The line is the application's own (`#gev-credits`) or the one a
|
||||
* renderer draws inside `#cesium-credits`.
|
||||
*/
|
||||
|
||||
const LINES = ['#gev-credits', '#cesium-credits .cesium-widget-credits'];
|
||||
|
||||
/**
|
||||
* Follow the attribution line's height in `--credit-line-height`.
|
||||
* @param {Document} [doc]
|
||||
* @returns {() => void} Stops following it and clears the property.
|
||||
*/
|
||||
export function trackCreditLineHeight(doc = globalThis.document) {
|
||||
const Observer = doc?.defaultView?.ResizeObserver;
|
||||
if (!doc?.documentElement || typeof Observer !== 'function') return () => {};
|
||||
const root = doc.documentElement;
|
||||
const lines = LINES.map((selector) => doc.querySelector(selector)).filter(
|
||||
Boolean,
|
||||
);
|
||||
if (!lines.length) return () => {};
|
||||
const update = () => {
|
||||
const height = Math.max(
|
||||
0,
|
||||
...lines.map((line) => line.getBoundingClientRect().height),
|
||||
);
|
||||
if (height > 0)
|
||||
root.style.setProperty('--credit-line-height', `${Math.ceil(height)}px`);
|
||||
else root.style.removeProperty('--credit-line-height');
|
||||
};
|
||||
const observer = new Observer(update);
|
||||
for (const line of lines) observer.observe(line);
|
||||
update();
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
root.style.removeProperty('--credit-line-height');
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import '../testSupport/registerDom.mjs';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { trackCreditLineHeight } from './creditLineHeight.js';
|
||||
|
||||
/** A ResizeObserver the test drives, with each line's height set by hand. */
|
||||
function fakeResizing() {
|
||||
const observers = [];
|
||||
const window = document.defaultView;
|
||||
const original = window.ResizeObserver;
|
||||
window.ResizeObserver = class {
|
||||
constructor(callback) {
|
||||
this.callback = callback;
|
||||
this.targets = new Set();
|
||||
observers.push(this);
|
||||
}
|
||||
observe(target) {
|
||||
this.targets.add(target);
|
||||
}
|
||||
disconnect() {
|
||||
this.targets.clear();
|
||||
}
|
||||
};
|
||||
return {
|
||||
resize(element, height) {
|
||||
element.getBoundingClientRect = () => ({ height });
|
||||
for (const observer of observers)
|
||||
if (observer.targets.has(element)) observer.callback([]);
|
||||
},
|
||||
restore() {
|
||||
window.ResizeObserver = original;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("the credit line's height follows it as it wraps, for either renderer's line", () => {
|
||||
const resizing = fakeResizing();
|
||||
try {
|
||||
for (const markup of [
|
||||
'<div id="gev-credits"></div>',
|
||||
'<div id="cesium-credits"><div class="cesium-widget-credits"></div></div>',
|
||||
]) {
|
||||
document.body.innerHTML = markup;
|
||||
const line = document.querySelector(
|
||||
'#gev-credits, #cesium-credits .cesium-widget-credits',
|
||||
);
|
||||
line.getBoundingClientRect = () => ({ height: 28 });
|
||||
const stop = trackCreditLineHeight(document);
|
||||
const root = document.documentElement.style;
|
||||
assert.equal(root.getPropertyValue('--credit-line-height'), '28px');
|
||||
resizing.resize(line, 66.4);
|
||||
assert.equal(root.getPropertyValue('--credit-line-height'), '67px');
|
||||
// Hidden, it holds no room.
|
||||
resizing.resize(line, 0);
|
||||
assert.equal(root.getPropertyValue('--credit-line-height'), '');
|
||||
resizing.resize(line, 28);
|
||||
stop();
|
||||
assert.equal(root.getPropertyValue('--credit-line-height'), '');
|
||||
}
|
||||
} finally {
|
||||
resizing.restore();
|
||||
document.body.replaceChildren();
|
||||
}
|
||||
});
|
||||
|
||||
test('without a credit line nothing is followed', () => {
|
||||
const resizing = fakeResizing();
|
||||
try {
|
||||
document.body.replaceChildren();
|
||||
const stop = trackCreditLineHeight(document);
|
||||
assert.equal(
|
||||
document.documentElement.style.getPropertyValue('--credit-line-height'),
|
||||
'',
|
||||
);
|
||||
stop();
|
||||
} finally {
|
||||
resizing.restore();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
<script setup>
|
||||
import { computed } from 'vue';
|
||||
import {
|
||||
LINK_SCHEMES,
|
||||
LOGO_SCHEMES,
|
||||
safeUrl,
|
||||
splitLink,
|
||||
} from '../../render/creditMarkup.js';
|
||||
|
||||
// One credit: its logo or its text, linked when it has a link. A credit is
|
||||
// plain data (`src/render/contract/credits.d.ts`): its text is set as text,
|
||||
// and a link or logo is kept only for a safe scheme.
|
||||
const props = defineProps({
|
||||
credit: { type: Object, required: true },
|
||||
});
|
||||
|
||||
const href = computed(() =>
|
||||
props.credit.href ? safeUrl(props.credit.href, LINK_SCHEMES) : null,
|
||||
);
|
||||
// A logo is drawn in place of the text, which names it (its alt text).
|
||||
const logo = computed(() =>
|
||||
props.credit.logoUrl ? safeUrl(props.credit.logoUrl, LOGO_SCHEMES) : null,
|
||||
);
|
||||
// Only the credit's linked words are the link, as the source wrote it.
|
||||
const parts = computed(() =>
|
||||
href.value && !logo.value && props.credit.linkText
|
||||
? splitLink(props.credit)
|
||||
: null,
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span v-if="parts" class="gev-credit"
|
||||
>{{ parts[0]
|
||||
}}<a :href="href" target="_blank" rel="noopener noreferrer">{{
|
||||
parts[1]
|
||||
}}</a
|
||||
>{{ parts[2] }}</span
|
||||
><component
|
||||
:is="href ? 'a' : 'span'"
|
||||
v-else
|
||||
class="gev-credit"
|
||||
:href="href || undefined"
|
||||
:target="href ? '_blank' : undefined"
|
||||
:rel="href ? 'noopener noreferrer' : undefined"
|
||||
><img
|
||||
v-if="logo"
|
||||
class="gev-credit-logo"
|
||||
:src="logo"
|
||||
:alt="credit.text"
|
||||
/><template v-else>{{ credit.text }}</template></component
|
||||
>
|
||||
</template>
|
||||
@@ -0,0 +1,82 @@
|
||||
<script setup>
|
||||
import { t } from '../../i18n/index.js';
|
||||
import UiCloseButton from '../kit/UiCloseButton.vue';
|
||||
import CreditItem from './CreditItem.vue';
|
||||
|
||||
// The attribution line at the bottom left and the "Data attribution" list it
|
||||
// opens, both at the end of `to` (the page's body), where the page's rules
|
||||
// place them. The owner (src/ui/creditsView.js) computes the credits shown,
|
||||
// keeps the list's open state and its focus, and takes the clicks and keys;
|
||||
// `elements` receives the line's, the button's and the list's elements for
|
||||
// it.
|
||||
const props = defineProps({
|
||||
to: { type: Object, required: true },
|
||||
panelId: { type: String, required: true },
|
||||
/** The credits on the line, once each. */
|
||||
inline: { type: Array, required: true },
|
||||
/** The credits in the list, once each. */
|
||||
listed: { type: Array, required: true },
|
||||
open: { type: Boolean, default: false },
|
||||
/**
|
||||
* The locale its words are in: a change words them again. The template
|
||||
* never reads it; `t()` is not reactive, so a new value is what makes the
|
||||
* view render again in the new language.
|
||||
*/
|
||||
locale: { type: String, default: '' },
|
||||
elements: { type: Object, required: true },
|
||||
onExpand: { type: Function, default: () => {} },
|
||||
onClose: { type: Function, default: () => {} },
|
||||
onKeydown: { type: Function, default: () => {} },
|
||||
});
|
||||
|
||||
/** Between the line's credits, and before the list's button. */
|
||||
const SEPARATOR = ' · ';
|
||||
/** A credit's key: the same text and link are one credit. */
|
||||
const key = (credit) => `${credit.text}\u0000${credit.href ?? ''}`;
|
||||
/** Keep `name`'s element for the owner. */
|
||||
const keep = (name) => (element) => {
|
||||
props.elements[name] = element?.$el ?? element;
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport :to="props.to"
|
||||
><div id="gev-credits" :ref="keep('bar')" class="gev-credits" tabindex="-1"
|
||||
><span :ref="keep('line')" class="gev-credits-line"
|
||||
><template v-for="(credit, i) in props.inline" :key="key(credit)"
|
||||
>{{ i ? SEPARATOR : '' }}<CreditItem :credit="credit" /></template
|
||||
>{{ props.inline.length && props.listed.length ? SEPARATOR : '' }}</span
|
||||
><button
|
||||
:ref="keep('expand')"
|
||||
type="button"
|
||||
class="gev-credits-expand"
|
||||
aria-haspopup="dialog"
|
||||
:aria-controls="props.panelId"
|
||||
:aria-expanded="String(props.open)"
|
||||
:hidden="props.listed.length === 0"
|
||||
@click="props.onExpand()"
|
||||
>{{ t('Data attribution') }}</button
|
||||
></div
|
||||
><div
|
||||
:id="props.panelId"
|
||||
:ref="keep('panel')"
|
||||
class="gev-credits-panel"
|
||||
role="dialog"
|
||||
:aria-labelledby="`${props.panelId}-title`"
|
||||
:hidden="!props.open"
|
||||
@keydown="props.onKeydown($event)"
|
||||
><div class="gev-credits-header"
|
||||
><span class="gev-credits-title" :id="`${props.panelId}-title`">{{
|
||||
t('Data provided by:')
|
||||
}}</span
|
||||
><UiCloseButton
|
||||
:ref="keep('close')"
|
||||
class="gev-credits-close"
|
||||
bare
|
||||
:label="t('Close data attribution')"
|
||||
@click="props.onClose()" /></div
|
||||
><ul class="gev-credits-list"
|
||||
><li v-for="credit in props.listed" :key="key(credit)"
|
||||
><CreditItem :credit="credit" /></li></ul></div
|
||||
></Teleport>
|
||||
</template>
|
||||
+55
-122
@@ -6,16 +6,14 @@
|
||||
* credits). Inline credits are shown on the line at the bottom left; the
|
||||
* rest are in the "Data attribution" list it opens. A credit is plain data
|
||||
* (`src/render/contract/credits.d.ts`): its text is set as text, and a link
|
||||
* or logo is kept only for a safe scheme.
|
||||
* or logo is kept only for a safe scheme. `CreditsView` renders the line and
|
||||
* the list; this owner keeps the credits shown, the list's open state and
|
||||
* its focus.
|
||||
*/
|
||||
import { h, render as renderVue } from 'vue';
|
||||
import { findCredits } from '../render/rendererOf.js';
|
||||
import {
|
||||
LINK_SCHEMES,
|
||||
LOGO_SCHEMES,
|
||||
safeUrl,
|
||||
splitLink,
|
||||
} from '../render/creditMarkup.js';
|
||||
import { onLocaleChange, t } from '../i18n/index.js';
|
||||
import { getLocale, onLocaleChange } from '../i18n/index.js';
|
||||
import CreditsView from './credits/CreditsView.vue';
|
||||
|
||||
const PANEL_ID = 'gev-credits-panel';
|
||||
|
||||
@@ -30,42 +28,6 @@ function distinct(list) {
|
||||
});
|
||||
}
|
||||
|
||||
/** One credit as DOM: its logo or its text, linked when it has a link. */
|
||||
function creditElement(doc, credit) {
|
||||
const href = credit.href ? safeUrl(credit.href, LINK_SCHEMES) : null;
|
||||
const logoUrl = credit.logoUrl ? safeUrl(credit.logoUrl, LOGO_SCHEMES) : null;
|
||||
// Only the credit's linked words are the link, as the source wrote it.
|
||||
if (href && !logoUrl && credit.linkText) {
|
||||
const [before, words, after] = splitLink(credit);
|
||||
const element = doc.createElement('span');
|
||||
element.className = 'gev-credit';
|
||||
const link = doc.createElement('a');
|
||||
link.href = href;
|
||||
link.target = '_blank';
|
||||
link.rel = 'noopener noreferrer';
|
||||
link.textContent = words;
|
||||
element.append(before, link, after);
|
||||
return element;
|
||||
}
|
||||
const element = doc.createElement(href ? 'a' : 'span');
|
||||
element.className = 'gev-credit';
|
||||
if (href) {
|
||||
element.href = href;
|
||||
element.target = '_blank';
|
||||
element.rel = 'noopener noreferrer';
|
||||
}
|
||||
// A logo is drawn in place of the text, which names it (its alt text).
|
||||
const logo = credit.logoUrl ? safeUrl(credit.logoUrl, LOGO_SCHEMES) : null;
|
||||
if (logo) {
|
||||
const image = doc.createElement('img');
|
||||
image.className = 'gev-credit-logo';
|
||||
image.src = logo;
|
||||
image.alt = credit.text;
|
||||
element.append(image);
|
||||
} else element.textContent = credit.text;
|
||||
return element;
|
||||
}
|
||||
|
||||
/**
|
||||
* Show `viewer`'s renderer credits at the bottom left of `root`'s page.
|
||||
* @param {object} viewer The scene object, bound to its renderer.
|
||||
@@ -76,106 +38,77 @@ export function mountCreditsView(viewer, { root = document.body } = {}) {
|
||||
const credits = findCredits(viewer);
|
||||
if (!credits || !root) return () => {};
|
||||
const doc = root.ownerDocument;
|
||||
const bar = doc.createElement('div');
|
||||
bar.id = 'gev-credits';
|
||||
bar.className = 'gev-credits';
|
||||
// Takes focus back from an emptied list when the line has no link.
|
||||
bar.tabIndex = -1;
|
||||
const line = doc.createElement('span');
|
||||
line.className = 'gev-credits-line';
|
||||
const expand = doc.createElement('button');
|
||||
expand.type = 'button';
|
||||
expand.className = 'gev-credits-expand';
|
||||
expand.setAttribute('aria-haspopup', 'dialog');
|
||||
expand.setAttribute('aria-controls', PANEL_ID);
|
||||
expand.setAttribute('aria-expanded', 'false');
|
||||
// The view teleports the line and the list to the end of `root`; this
|
||||
// host, never in the page, holds only its place.
|
||||
const host = doc.createElement('div');
|
||||
const elements = {};
|
||||
let inline = [];
|
||||
let listed = [];
|
||||
let open = false;
|
||||
|
||||
const panel = doc.createElement('div');
|
||||
panel.id = PANEL_ID;
|
||||
panel.className = 'gev-credits-panel';
|
||||
panel.setAttribute('role', 'dialog');
|
||||
panel.hidden = true;
|
||||
const header = doc.createElement('div');
|
||||
header.className = 'gev-credits-header';
|
||||
const title = doc.createElement('span');
|
||||
title.className = 'gev-credits-title';
|
||||
title.id = `${PANEL_ID}-title`;
|
||||
panel.setAttribute('aria-labelledby', title.id);
|
||||
const close = doc.createElement('button');
|
||||
close.type = 'button';
|
||||
close.className = 'gev-credits-close';
|
||||
close.textContent = '×';
|
||||
header.append(title, close);
|
||||
const list = doc.createElement('ul');
|
||||
list.className = 'gev-credits-list';
|
||||
panel.append(header, list);
|
||||
bar.append(line, expand);
|
||||
root.append(bar, panel);
|
||||
// The view patches synchronously, so focus can move once it returns.
|
||||
const paint = () =>
|
||||
renderVue(
|
||||
h(CreditsView, {
|
||||
to: root,
|
||||
panelId: PANEL_ID,
|
||||
inline,
|
||||
listed,
|
||||
open,
|
||||
locale: getLocale(),
|
||||
elements,
|
||||
onExpand,
|
||||
onClose,
|
||||
onKeydown,
|
||||
}),
|
||||
host,
|
||||
);
|
||||
|
||||
const label = () => {
|
||||
expand.textContent = t('Data attribution');
|
||||
title.textContent = t('Data provided by:');
|
||||
close.setAttribute('aria-label', t('Close data attribution'));
|
||||
};
|
||||
|
||||
const setOpen = (open, { focus = false } = {}) => {
|
||||
panel.hidden = !open;
|
||||
expand.setAttribute('aria-expanded', String(open));
|
||||
if (open) close.focus();
|
||||
else if (focus) expand.focus();
|
||||
const setOpen = (next, { focus = false } = {}) => {
|
||||
open = next;
|
||||
paint();
|
||||
if (open) elements.close.focus();
|
||||
else if (focus) elements.expand.focus();
|
||||
};
|
||||
|
||||
const render = (all) => {
|
||||
const { bar, line, panel } = elements;
|
||||
const focused = panel.contains(doc.activeElement);
|
||||
const shown = distinct(Array.isArray(all) ? all : []);
|
||||
const inline = shown.filter((credit) => credit.inline);
|
||||
const listed = shown.filter((credit) => !credit.inline);
|
||||
line.replaceChildren();
|
||||
inline.forEach((credit, i) => {
|
||||
if (i) line.append(doc.createTextNode(' · '));
|
||||
line.append(creditElement(doc, credit));
|
||||
});
|
||||
if (inline.length && listed.length) line.append(doc.createTextNode(' · '));
|
||||
list.replaceChildren(
|
||||
...listed.map((credit) => {
|
||||
const item = doc.createElement('li');
|
||||
item.append(creditElement(doc, credit));
|
||||
return item;
|
||||
}),
|
||||
);
|
||||
expand.hidden = listed.length === 0;
|
||||
if (expand.hidden && !panel.hidden) {
|
||||
inline = shown.filter((credit) => credit.inline);
|
||||
listed = shown.filter((credit) => !credit.inline);
|
||||
paint();
|
||||
if (listed.length === 0 && open) {
|
||||
// Focus in the list goes back to the line, not to the page.
|
||||
setOpen(false);
|
||||
if (focused) (line.querySelector('a') ?? bar).focus();
|
||||
} else if (focused && !panel.contains(doc.activeElement)) {
|
||||
// A link that focus was on was redrawn: focus stays in the list.
|
||||
close.focus();
|
||||
elements.close.focus();
|
||||
}
|
||||
};
|
||||
|
||||
const onExpand = () => setOpen(panel.hidden);
|
||||
const onClose = () => setOpen(false, { focus: true });
|
||||
function onExpand() {
|
||||
setOpen(!open);
|
||||
}
|
||||
function onClose() {
|
||||
setOpen(false, { focus: true });
|
||||
}
|
||||
// Escape in the open list closes it (it takes focus as it opens).
|
||||
const onKey = (event) => {
|
||||
if (event.key !== 'Escape' || panel.hidden) return;
|
||||
function onKeydown(event) {
|
||||
if (event.key !== 'Escape' || !open) return;
|
||||
event.preventDefault();
|
||||
setOpen(false, { focus: true });
|
||||
};
|
||||
expand.addEventListener('click', onExpand);
|
||||
close.addEventListener('click', onClose);
|
||||
panel.addEventListener('keydown', onKey);
|
||||
label();
|
||||
}
|
||||
|
||||
paint();
|
||||
render(credits.list());
|
||||
const offChange = credits.on('change', render);
|
||||
const offLocale = onLocaleChange(label);
|
||||
// The view words its text again in the new locale, as it renders.
|
||||
const offLocale = onLocaleChange(paint);
|
||||
return () => {
|
||||
offChange();
|
||||
offLocale();
|
||||
expand.removeEventListener('click', onExpand);
|
||||
close.removeEventListener('click', onClose);
|
||||
panel.removeEventListener('keydown', onKey);
|
||||
bar.remove();
|
||||
panel.remove();
|
||||
renderVue(null, host);
|
||||
};
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import assert from 'node:assert/strict';
|
||||
import { mountCreditsView } from './creditsView.js';
|
||||
import { bindRenderer } from '../render/rendererOf.js';
|
||||
import { createStubRenderer } from '../render/stub/index.js';
|
||||
import { setLocale } from '../i18n/index.js';
|
||||
|
||||
function scene() {
|
||||
document.body.replaceChildren();
|
||||
@@ -118,10 +119,12 @@ test('focus in the list stays in it as it redraws, and goes to the line as it em
|
||||
const off = mountCreditsView(viewer);
|
||||
const panel = document.getElementById('gev-credits-panel');
|
||||
document.querySelector('.gev-credits-expand').click();
|
||||
panel.querySelector('li a').focus();
|
||||
const link = panel.querySelector('li a');
|
||||
link.focus();
|
||||
const removeOther = renderer.credits.addStatic({ text: 'NOAA' });
|
||||
assert.equal(panel.hidden, false);
|
||||
assert.ok(panel.contains(document.activeElement), 'still in the list');
|
||||
assert.equal(document.activeElement, link, 'the focused link keeps it');
|
||||
remove();
|
||||
removeOther();
|
||||
assert.equal(panel.hidden, true);
|
||||
@@ -152,3 +155,55 @@ test('a credit with linked words links only those words', () => {
|
||||
);
|
||||
off();
|
||||
});
|
||||
|
||||
test('the line and its list follow the locale', () => {
|
||||
const { viewer, renderer } = scene();
|
||||
renderer.credits.addStatic({ text: 'NOAA' });
|
||||
const off = mountCreditsView(viewer);
|
||||
const expand = document.querySelector('.gev-credits-expand');
|
||||
const close = document.querySelector('.gev-credits-close');
|
||||
try {
|
||||
setLocale('fr');
|
||||
assert.equal(expand.textContent, 'Attribution des données');
|
||||
assert.equal(
|
||||
document.getElementById('gev-credits-panel-title').textContent,
|
||||
'Données fournies par\u202f:',
|
||||
);
|
||||
assert.equal(
|
||||
close.getAttribute('aria-label'),
|
||||
"Fermer l'attribution des données",
|
||||
);
|
||||
} finally {
|
||||
setLocale('en');
|
||||
}
|
||||
assert.equal(expand.textContent, 'Data attribution');
|
||||
off();
|
||||
});
|
||||
|
||||
test('the line and its list are the last of the body, and its close button is the kit’s', () => {
|
||||
const { viewer, renderer } = scene();
|
||||
document.body.append(document.createElement('main'));
|
||||
renderer.credits.addStatic({ text: 'NOAA' });
|
||||
const off = mountCreditsView(viewer);
|
||||
const children = [...document.body.children];
|
||||
assert.deepEqual(
|
||||
children.slice(-2).map((element) => element.id),
|
||||
['gev-credits', 'gev-credits-panel'],
|
||||
'the page’s rules select them as children of the body',
|
||||
);
|
||||
const close = document.querySelector('.gev-credits-close');
|
||||
assert.ok(close.classList.contains('ui-button'), 'a UiCloseButton');
|
||||
assert.equal(close.type, 'button');
|
||||
assert.equal(close.textContent, '×');
|
||||
assert.equal(close.hasAttribute('title'), false, 'no tip');
|
||||
assert.equal(
|
||||
close.classList.contains('ui-close-button'),
|
||||
false,
|
||||
'bare: it keeps the browser’s padding',
|
||||
);
|
||||
off();
|
||||
assert.deepEqual(
|
||||
[...document.body.children].map((element) => element.tagName),
|
||||
['MAIN'],
|
||||
);
|
||||
});
|
||||
@@ -9,9 +9,8 @@ import { fileURLToPath } from 'node:url';
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
const STYLES = path.join(HERE, 'styles');
|
||||
const LOCALES = path.join(HERE, '..', 'i18n', 'locales');
|
||||
// cyber.css carries decorative theme strings (LOC / GRID, SYS 06 // ...);
|
||||
// street-level.css ' · ESC' is a key cap. Neither is UI copy.
|
||||
const DECORATIVE = new Set(['cyber.css', 'street-level.css']);
|
||||
// street-level.css ' · ESC' is a key cap, not UI copy.
|
||||
const DECORATIVE = new Set(['street-level.css']);
|
||||
|
||||
test('no user-visible text in CSS content: outside decorative themes', () => {
|
||||
const hits = [];
|
||||
|
||||
@@ -38,7 +38,6 @@ export function getCyberSonarControlState(
|
||||
intensityPct: settings.intensity,
|
||||
opacityPct: settings.opacity,
|
||||
sectorDeg: settings.sector,
|
||||
cyberSelected: root?.dataset?.uiTheme === 'cyber',
|
||||
mapSweepActive: isCyberSonarActive(options),
|
||||
contactSweepActive:
|
||||
root?.dataset?.cyberSonarGpu === 'supported' &&
|
||||
@@ -59,10 +58,10 @@ export function setCyberSonarControls(
|
||||
sonar: getCyberSonarControlState(doc, { hudActive: owner?.hud?.visible }),
|
||||
});
|
||||
if (!request || typeof request !== 'object' || Array.isArray(request)) {
|
||||
return fail('Provide Cyber sonar settings as an object.');
|
||||
return fail('Provide sonar settings as an object.');
|
||||
}
|
||||
const fields = Object.keys(request);
|
||||
if (!fields.length) return fail('Provide at least one Cyber sonar setting.');
|
||||
if (!fields.length) return fail('Provide at least one sonar setting.');
|
||||
for (const field of fields) {
|
||||
const value = request[field];
|
||||
if (field === 'enabled') {
|
||||
@@ -70,19 +69,14 @@ export function setCyberSonarControls(
|
||||
continue;
|
||||
}
|
||||
if (!Object.hasOwn(SETTING_FIELDS, field)) {
|
||||
return fail('Unknown Cyber sonar setting.');
|
||||
return fail('Unknown sonar setting.');
|
||||
}
|
||||
const [, min, max] = SETTING_FIELDS[field];
|
||||
if (!Number.isInteger(value) || value < min || value > max) {
|
||||
return fail(`${field} must be an integer from ${min} to ${max}.`);
|
||||
}
|
||||
}
|
||||
if (
|
||||
owner.hud?.getVariant?.() !== 'cyber' ||
|
||||
doc?.documentElement?.dataset?.uiTheme !== 'cyber'
|
||||
) {
|
||||
return fail('Cyber sonar controls require the Cyber HUD layout.');
|
||||
}
|
||||
owner.shareLinkManager?.claimRestoreLane?.('visual');
|
||||
for (const [field, [setting]] of Object.entries(SETTING_FIELDS)) {
|
||||
if (Object.hasOwn(request, field)) {
|
||||
owner._setCyberSonarSetting(setting, request[field]);
|
||||
|
||||
@@ -11,9 +11,9 @@ import { StyleManager } from './applicationShell.js';
|
||||
import { VisualSettings } from './visualSettings.js';
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
function fixture(theme = 'cyber') {
|
||||
function fixture(layout = 'tactical') {
|
||||
const root = {
|
||||
dataset: { uiTheme: theme, cyberSonarGpu: 'supported' },
|
||||
dataset: { cyberSonarGpu: 'supported' },
|
||||
style: { setProperty() {} },
|
||||
};
|
||||
const flags = new Set();
|
||||
@@ -27,7 +27,7 @@ function fixture(theme = 'cyber') {
|
||||
};
|
||||
const calls = [];
|
||||
const owner = {
|
||||
hud: { getVariant: () => theme },
|
||||
hud: { getVariant: () => layout },
|
||||
_setCyberSonarSetting(name, value) {
|
||||
calls.push([name, value]);
|
||||
const suffix = name[0].toUpperCase() + name.slice(1);
|
||||
@@ -50,8 +50,15 @@ test('real runner and facade use visual settings, preserve visibility and return
|
||||
visual.services = { governorRequestRender: (reason) => renders.push(reason) };
|
||||
// No Display panel here: the controls' render is not under test.
|
||||
visual._publishDisplay = () => {};
|
||||
// The shell's share sync; a sonar change keeps the link current.
|
||||
const shares = [];
|
||||
visual._syncShareState = () => shares.push(true);
|
||||
const owner = Object.create(StyleManager.prototype);
|
||||
owner._visualSettings = visual;
|
||||
const claims = [];
|
||||
Object.defineProperty(owner, 'shareLinkManager', { value: {
|
||||
claimRestoreLane: (lane) => claims.push({ lane, renders: renders.length }),
|
||||
} });
|
||||
Object.defineProperty(owner, 'hud', { value: f.owner.hud });
|
||||
const viewer = {
|
||||
camera: { moveEnd: { addEventListener() {} } },
|
||||
@@ -65,19 +72,23 @@ test('real runner and facade use visual settings, preserve visibility and return
|
||||
const runner = createGevActionRunner({ styleManager: owner, viewer, dataManager: {} });
|
||||
const result = await runner('set_cyber_sonar', { enabled: false, intensityPct: 73, sectorDeg: 9 });
|
||||
assert.equal(result.ok, true);
|
||||
assert.deepEqual(claims, [{ lane: 'visual', renders: 0 }]);
|
||||
assert.equal(result.sonar.intensityPct, 73);
|
||||
assert.equal(result.sonar.sectorDeg, 9);
|
||||
assert.equal(result.sonar.enabled, false);
|
||||
assert.equal(f.root.dataset.uiTheme, 'cyber');
|
||||
assert.equal(f.owner.hud.getVariant(), 'tactical');
|
||||
assert.equal(f.hudFlags.has('active'), true);
|
||||
assert.equal(renders.length, 3);
|
||||
assert.equal(shares.length, 1);
|
||||
const before = getCyberSonarControlState();
|
||||
const invalid = await runner('set_cyber_sonar', { rings: 6, opacityPct: 0 });
|
||||
assert.equal(invalid.ok, false);
|
||||
assert.deepEqual(claims, [{ lane: 'visual', renders: 0 }], 'invalid requests claim no authority');
|
||||
assert.deepEqual(getCyberSonarControlState(), before);
|
||||
assert.equal(renders.length, 3);
|
||||
const zero = await runner('set_cyber_sonar', { intensityPct: 0 });
|
||||
assert.equal(zero.sonar.intensityPct, 0);
|
||||
assert.deepEqual(claims.map(({ lane }) => lane), ['visual', 'visual']);
|
||||
assert.equal(zero.sonar.enabled, false);
|
||||
const unavailable = createGevActionRunner({ styleManager: {}, viewer, dataManager: {} });
|
||||
assert.equal((await unavailable('set_cyber_sonar', { enabled: true })).ok, false);
|
||||
@@ -136,11 +147,11 @@ test('rejects the whole invalid request before any mutation', () => {
|
||||
}
|
||||
});
|
||||
|
||||
test('requires Cyber and preserves off state and every omitted setting', () => {
|
||||
for (const theme of ['tactical', 'minimal']) {
|
||||
const f = fixture(theme);
|
||||
assert.equal(setCyberSonarControls(f.owner, { enabled: true }, f.doc).ok, false);
|
||||
assert.deepEqual(f.calls, []);
|
||||
test('works under every HUD layout and preserves off state and every omitted setting', () => {
|
||||
for (const layout of ['tactical', 'minimal']) {
|
||||
const f = fixture(layout);
|
||||
assert.equal(setCyberSonarControls(f.owner, { enabled: true }, f.doc).ok, true);
|
||||
assert.deepEqual(f.calls, [['enabled', true]]);
|
||||
}
|
||||
const f = fixture();
|
||||
f.root.dataset.cyberSonar = 'off';
|
||||
|
||||
@@ -1,950 +0,0 @@
|
||||
import {
|
||||
getScopeMaskFeather,
|
||||
getScopeMaskOpacity,
|
||||
isScopeMaskEnabled,
|
||||
setScopeMaskEnabled,
|
||||
setScopeMaskFeather,
|
||||
setScopeMaskOpacity,
|
||||
} from '../scopeMask.js';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
applyHudUiTheme,
|
||||
CYBER_VISUAL_DEFAULTS,
|
||||
cyberVisualDefaultsForHudTransition,
|
||||
HUD_LAYOUTS,
|
||||
normalizeHudLayout,
|
||||
} from '../hudLayouts.js';
|
||||
import { GEV_ACTION_SCHEMAS } from '../voice/actionSchemas.js';
|
||||
import { createGevActionRunner } from '../voice/gevActions.js';
|
||||
import { StyleManager } from './applicationShell.js';
|
||||
import { createPinia } from 'pinia';
|
||||
import { useDisplayStore } from './stores/display.js';
|
||||
import { VisualSettings } from './visualSettings.js';
|
||||
import { STYLES } from './visualPresets.js';
|
||||
|
||||
test('CCTV and Context keep their headers outside Cyber-only scroll bodies', () => {
|
||||
for (const file of ['panels/CctvPanel.vue', 'ContextView.vue']) {
|
||||
const markup = readFileSync(
|
||||
new URL(`./views/${file}`, import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
// The body wears the shared scrollbar skin where Cyber makes it scroll.
|
||||
assert.match(
|
||||
markup,
|
||||
/class="cyber-panel-body ui-scroll" data-rail-scroller/,
|
||||
);
|
||||
assert.ok(
|
||||
// The header is RailPanel's; the body is its first content.
|
||||
markup.indexOf('<RailPanel ') > -1 &&
|
||||
markup.indexOf('<RailPanel ') <
|
||||
markup.indexOf('class="cyber-panel-body ui-scroll"'),
|
||||
);
|
||||
}
|
||||
const shared = readFileSync(
|
||||
new URL('./styles/controls.css', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
const cyber = readFileSync(
|
||||
new URL('./styles/cyber.css', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
assert.match(shared, /\.cyber-panel-body\s*\{\s*display: contents;/);
|
||||
assert.match(
|
||||
cyber,
|
||||
/:root\[data-ui-theme='cyber'\] \.cyber-panel-body\s*\{[^}]*overflow-y: auto;[^}]*overscroll-behavior: contain;/,
|
||||
);
|
||||
});
|
||||
|
||||
function styleOwner(t, initialVariant = 'cyber') {
|
||||
const previous = { document: globalThis.document, window: globalThis.window };
|
||||
const root = { dataset: {} };
|
||||
globalThis.document = { documentElement: root, querySelectorAll: () => [] };
|
||||
globalThis.window = { dispatchEvent() {} };
|
||||
t.after(() => Object.assign(globalThis, previous));
|
||||
let variant = initialVariant;
|
||||
const calls = [];
|
||||
const hud = {
|
||||
getVariant: () => variant,
|
||||
setVariant: (value) => {
|
||||
// Normalize like the real HUD so retired layouts fall back.
|
||||
variant = normalizeHudLayout(value);
|
||||
applyHudUiTheme(root, variant);
|
||||
},
|
||||
setMode: (value) => calls.push(['mode', value]),
|
||||
onStyleChange: (value) => calls.push(['style', value]),
|
||||
};
|
||||
hud.setVariant(initialVariant);
|
||||
const owner = Object.create(VisualSettings.prototype);
|
||||
Object.assign(owner, {
|
||||
activeStyle: 'normal',
|
||||
store: { publish() {} },
|
||||
readHud: () => hud,
|
||||
readShareLinks: () => ({ onStyleChange() {} }),
|
||||
_visualEffects: {
|
||||
stages: Object.fromEntries(
|
||||
Object.entries(STYLES).map(([name, config]) => [
|
||||
name,
|
||||
{ uniforms: { ...config.uniforms, intensity: 0 } },
|
||||
]),
|
||||
),
|
||||
},
|
||||
services: { governorRequestRender() {}, setDetectionStyle() {} },
|
||||
_setBloomEnabled: (value) => calls.push(['bloom', value]),
|
||||
_setSharpenEnabled: (value) => calls.push(['sharpen', value]),
|
||||
_applyDetectionPreset: (value) => calls.push(['detection', value]),
|
||||
_syncShareState: () => calls.push(['share', variant]),
|
||||
});
|
||||
for (const name of [
|
||||
'setCelestialRingEnabled',
|
||||
'_startTransition',
|
||||
'_publishActiveStyle',
|
||||
'_updateSliderPanel',
|
||||
'_updateHudButtonState',
|
||||
'_syncIrBoost',
|
||||
'_syncCockpitInheritedStyle',
|
||||
'_syncCyberSonarControl',
|
||||
'_scheduleAdaptivePanelLayout',
|
||||
'_setDetectionFade',
|
||||
// Intensities: the fixture has no post-process stages to drive.
|
||||
'_setBloomIntensity',
|
||||
'_setSharpenIntensity',
|
||||
])
|
||||
owner[name] = () => {};
|
||||
return { owner, hud, root, calls };
|
||||
}
|
||||
|
||||
test('visual styles retain Cyber through real preset application without dropping other defaults', (t) => {
|
||||
const { owner, hud, root, calls } = styleOwner(t);
|
||||
for (const style of [
|
||||
'surveillance',
|
||||
'normal',
|
||||
'noir',
|
||||
'anime',
|
||||
'thermal',
|
||||
'retro',
|
||||
]) {
|
||||
owner.setStyle(style);
|
||||
assert.equal(owner.activeStyle, style);
|
||||
assert.equal(hud.getVariant(), 'cyber');
|
||||
assert.equal(root.dataset.uiTheme, 'cyber');
|
||||
assert.deepEqual(calls.at(-1), ['share', 'cyber']);
|
||||
}
|
||||
assert.equal(owner.stages.thermal.uniforms.sensitivity, 0.85);
|
||||
assert.equal(calls.filter(([name]) => name === 'detection').length, 3);
|
||||
assert.equal(
|
||||
calls.filter(([name, value]) => name === 'bloom' && value === false).length,
|
||||
3,
|
||||
);
|
||||
assert.equal(
|
||||
calls.filter(([name, value]) => name === 'sharpen' && value === true)
|
||||
.length,
|
||||
3,
|
||||
);
|
||||
});
|
||||
|
||||
test('non-Cyber style presets and explicit HUD choices remain authoritative', (t) => {
|
||||
const { owner, hud, root } = styleOwner(t);
|
||||
for (const variant of ['tactical', 'minimal']) {
|
||||
owner._setHudVariant(variant);
|
||||
assert.equal(hud.getVariant(), variant);
|
||||
assert.equal(root.dataset.uiTheme, undefined);
|
||||
owner.setStyle('normal');
|
||||
owner.setStyle('surveillance');
|
||||
assert.equal(hud.getVariant(), 'tactical');
|
||||
}
|
||||
});
|
||||
|
||||
test('leaving Cyber without a preset choice restores the prior visual preset', (t) => {
|
||||
const { owner, hud } = styleOwner(t, 'tactical');
|
||||
owner.setStyle('noir');
|
||||
|
||||
owner._setHudVariant('cyber', { applyVisualDefaults: true });
|
||||
assert.equal(owner.activeStyle, 'thermal');
|
||||
assert.equal(owner._preCyberStyle, 'noir');
|
||||
assert.equal(owner._cyberStyleUserSelected, false);
|
||||
|
||||
owner._setHudVariant('minimal', { applyVisualDefaults: true });
|
||||
assert.equal(hud.getVariant(), 'minimal');
|
||||
assert.equal(owner.activeStyle, 'noir');
|
||||
assert.equal(owner._preCyberStyle, null);
|
||||
assert.equal(owner._cyberStyleUserSelected, false);
|
||||
});
|
||||
|
||||
test('a preset explicitly selected in Cyber survives exit and resets for re-entry', (t) => {
|
||||
const { owner, hud } = styleOwner(t, 'tactical');
|
||||
owner.setStyle('noir');
|
||||
|
||||
owner._setHudVariant('cyber', { applyVisualDefaults: true });
|
||||
owner.setStyle('anime', { userInitiated: true });
|
||||
assert.equal(owner.activeStyle, 'anime');
|
||||
assert.equal(owner._preCyberStyle, 'noir');
|
||||
assert.equal(owner._cyberStyleUserSelected, true);
|
||||
|
||||
// Reselecting the active mode must not erase the user's preset intent.
|
||||
owner._setHudVariant('cyber', { applyVisualDefaults: true });
|
||||
assert.equal(owner._preCyberStyle, 'noir');
|
||||
owner._setHudVariant('minimal', { applyVisualDefaults: true });
|
||||
assert.equal(hud.getVariant(), 'minimal');
|
||||
assert.equal(owner.activeStyle, 'anime');
|
||||
assert.equal(owner._preCyberStyle, null);
|
||||
assert.equal(owner._cyberStyleUserSelected, false);
|
||||
|
||||
// A later untouched Cyber round trip restores the new pre-Cyber preset.
|
||||
owner._setHudVariant('cyber', { applyVisualDefaults: true });
|
||||
assert.equal(owner.activeStyle, 'thermal');
|
||||
assert.equal(owner._preCyberStyle, 'anime');
|
||||
owner._setHudVariant('minimal', { applyVisualDefaults: true });
|
||||
assert.equal(owner.activeStyle, 'anime');
|
||||
});
|
||||
|
||||
test('an explicit same-value FLIR choice is preserved on Cyber exit', (t) => {
|
||||
const { owner } = styleOwner(t, 'tactical');
|
||||
owner.setStyle('noir');
|
||||
owner._setHudVariant('cyber', { applyVisualDefaults: true });
|
||||
|
||||
owner.setStyle('thermal', { userInitiated: true });
|
||||
assert.equal(owner.activeStyle, 'thermal');
|
||||
assert.equal(owner._cyberStyleUserSelected, true);
|
||||
owner._setHudVariant('minimal', { applyVisualDefaults: true });
|
||||
assert.equal(owner.activeStyle, 'thermal');
|
||||
});
|
||||
|
||||
test('an authoritative same-Cyber reset clears local preset ownership', (t) => {
|
||||
const { owner } = styleOwner(t, 'tactical');
|
||||
owner.setStyle('noir');
|
||||
owner._setHudVariant('cyber', { applyVisualDefaults: true });
|
||||
owner.setStyle('anime', { userInitiated: true });
|
||||
assert.equal(owner._cyberStyleUserSelected, true);
|
||||
|
||||
owner._setHudVariant('cyber');
|
||||
assert.equal(owner.activeStyle, 'anime');
|
||||
assert.equal(owner._preCyberStyle, null);
|
||||
assert.equal(owner._cyberStyleUserSelected, false);
|
||||
owner._setHudVariant('minimal', { applyVisualDefaults: true });
|
||||
assert.equal(owner.activeStyle, 'anime');
|
||||
});
|
||||
|
||||
test('Display and voice HUD routes preserve explicit Cyber entry and exit authority', async (t) => {
|
||||
const makeOwner = () => {
|
||||
const { owner, hud } = styleOwner(t, 'tactical');
|
||||
owner.setStyle('noir');
|
||||
owner.setHudLayout = (...args) =>
|
||||
StyleManager.prototype.setHudLayout.call(owner, ...args);
|
||||
owner.getControlState = () => ({
|
||||
hud: { layout: hud.getVariant(), visible: true },
|
||||
});
|
||||
return { owner, hud };
|
||||
};
|
||||
|
||||
const display = makeOwner();
|
||||
// The Display panel's layout select and the dock's style buttons call
|
||||
// these actions through the display store.
|
||||
const store = useDisplayStore(createPinia());
|
||||
const token = store.connect({
|
||||
setHudLayout: (value) => display.owner.setHudLayout(value),
|
||||
setStyle: (value) => display.owner.setStyle(value, { userInitiated: true }),
|
||||
});
|
||||
store.act('setHudLayout', 'cyber');
|
||||
assert.equal(display.hud.getVariant(), 'cyber');
|
||||
assert.equal(display.owner.activeStyle, 'thermal');
|
||||
store.act('setStyle', 'anime');
|
||||
assert.equal(display.owner.activeStyle, 'anime');
|
||||
store.act('setHudLayout', 'minimal');
|
||||
assert.equal(display.hud.getVariant(), 'minimal');
|
||||
assert.equal(display.owner.activeStyle, 'anime');
|
||||
store.detach(token);
|
||||
|
||||
const voice = makeOwner();
|
||||
const eventSource = { addEventListener() {}, removeEventListener() {} };
|
||||
const viewer = {
|
||||
camera: { moveEnd: { addEventListener() {} } },
|
||||
clock: { onTick: { addEventListener: () => () => {} } },
|
||||
canvas: eventSource,
|
||||
scene: { canvas: eventSource },
|
||||
};
|
||||
const runVoiceAction = createGevActionRunner({
|
||||
viewer,
|
||||
styleManager: voice.owner,
|
||||
dataManager: {},
|
||||
});
|
||||
const entered = await runVoiceAction('set_hud', { layout: 'cyber' });
|
||||
assert.equal(entered.ok, true);
|
||||
assert.equal(voice.hud.getVariant(), 'cyber');
|
||||
assert.equal(voice.owner.activeStyle, 'thermal');
|
||||
const selected = await runVoiceAction('set_visual_style', { style: 'anime' });
|
||||
assert.equal(selected.ok, true);
|
||||
assert.equal(voice.owner.activeStyle, 'anime');
|
||||
const exited = await runVoiceAction('set_hud', { layout: 'minimal' });
|
||||
assert.equal(exited.ok, true);
|
||||
assert.equal(voice.hud.getVariant(), 'minimal');
|
||||
assert.equal(voice.owner.activeStyle, 'anime');
|
||||
});
|
||||
|
||||
test('scope choice and expanded feather survive every HUD layout and both restore paths', async (t) => {
|
||||
const { owner } = styleOwner(t, 'tactical');
|
||||
const previous = { enabled: isScopeMaskEnabled(), feather: getScopeMaskFeather() };
|
||||
t.after(() => { setScopeMaskEnabled(previous.enabled); setScopeMaskFeather(previous.feather); });
|
||||
Object.assign(owner.services, { setScopeMaskEnabled, setScopeMaskFeather });
|
||||
let shown = null;
|
||||
owner.store = { publish: (view) => (shown = view.scope) };
|
||||
await owner.restoreShareState({ scopeEnabled: false, scopeFeatherPct: 200 });
|
||||
assert.deepEqual(shown, { enabled: false, featherPct: 200, opacityPct: 100 });
|
||||
for (const layout of ['minimal', 'cyber', 'tactical']) {
|
||||
owner._setHudVariant(layout, { applyVisualDefaults: true });
|
||||
assert.equal(isScopeMaskEnabled(), false, layout);
|
||||
assert.equal(getScopeMaskFeather(), 2, layout);
|
||||
assert.equal(shown.enabled, false, layout);
|
||||
}
|
||||
await owner.applyVisualState({ scope: { enabled: true, featherPct: 175 } });
|
||||
assert.equal(isScopeMaskEnabled(), true);
|
||||
assert.equal(getScopeMaskFeather(), 1.75);
|
||||
assert.deepEqual(shown, { enabled: true, featherPct: 175, opacityPct: 100 });
|
||||
await owner.applyVisualState({ scope: { featherPct: 500 } });
|
||||
assert.equal(getScopeMaskFeather(), 2);
|
||||
assert.deepEqual(shown, { enabled: true, featherPct: 200, opacityPct: 100 });
|
||||
});
|
||||
|
||||
test('a shared scope opacity is restored and rides in the next share state', async (t) => {
|
||||
const { owner } = styleOwner(t, 'tactical');
|
||||
const previous = getScopeMaskOpacity();
|
||||
t.after(() => setScopeMaskOpacity(previous));
|
||||
Object.assign(owner.services, {
|
||||
setScopeMaskEnabled() {},
|
||||
setScopeMaskFeather() {},
|
||||
setScopeMaskOpacity,
|
||||
});
|
||||
let shown = null;
|
||||
owner.store = { publish: (view) => (shown = view.scope) };
|
||||
await owner.restoreShareState({ scopeOpacityPct: 60 });
|
||||
assert.equal(getScopeMaskOpacity(), 0.6);
|
||||
assert.equal(shown.opacityPct, 60);
|
||||
// A state without it leaves the opacity alone.
|
||||
await owner.restoreShareState({ scopeFeatherPct: 80 });
|
||||
assert.equal(getScopeMaskOpacity(), 0.6);
|
||||
assert.equal(shown.opacityPct, 60);
|
||||
Object.assign(owner.services, {
|
||||
getDetectionTuning: () => ({ allocationStrategy: 'ELASTIC' }),
|
||||
getDetectionMode: () => 'OFF',
|
||||
isScopeMaskEnabled: () => true,
|
||||
getScopeMaskFeather: () => 0.8,
|
||||
getScopeMaskOpacity,
|
||||
getScopeTerminusOverride: () => null,
|
||||
});
|
||||
owner.readCelestialRing = () => null;
|
||||
assert.equal(owner._readShareState().options.scopeOpacityPct, 60);
|
||||
// A link asking for less than the floor opens at the floor, and says so.
|
||||
await owner.restoreShareState({ scopeOpacityPct: 20 });
|
||||
assert.equal(getScopeMaskOpacity(), 0.5);
|
||||
assert.equal(owner._readShareState().options.scopeOpacityPct, 50);
|
||||
});
|
||||
|
||||
test('a scene shot saved with the retired Snow style plays on Normal', async (t) => {
|
||||
const { owner } = styleOwner(t, 'tactical');
|
||||
owner.setStyle('noir');
|
||||
await owner.applyVisualState({ style: 'snow' });
|
||||
assert.equal(owner.activeStyle, 'normal');
|
||||
});
|
||||
|
||||
test('scene and share HUD transitions do not restore a local pre-Cyber preset', async (t) => {
|
||||
const { owner, hud } = styleOwner(t, 'tactical');
|
||||
owner.setStyle('noir');
|
||||
owner._setHudVariant('cyber', { applyVisualDefaults: true });
|
||||
owner.setStyle('anime', { userInitiated: true });
|
||||
assert.equal(owner._cyberStyleUserSelected, true);
|
||||
|
||||
await owner.applyVisualState({ style: 'retro', hud: { variant: 'cyber' } });
|
||||
assert.equal(hud.getVariant(), 'cyber');
|
||||
assert.equal(owner.activeStyle, 'retro');
|
||||
assert.equal(owner._preCyberStyle, null);
|
||||
assert.equal(owner._cyberStyleUserSelected, false);
|
||||
owner._setHudVariant('minimal', { applyVisualDefaults: true });
|
||||
assert.equal(owner.activeStyle, 'retro');
|
||||
|
||||
owner.setStyle('surveillance');
|
||||
owner._setHudVariant('cyber', { applyVisualDefaults: true });
|
||||
assert.equal(owner._preCyberStyle, 'surveillance');
|
||||
owner.setStyle('anime', { userInitiated: true });
|
||||
await owner.restoreShareState({
|
||||
style: 'thermal',
|
||||
hudVariant: 'cyber',
|
||||
});
|
||||
assert.equal(hud.getVariant(), 'cyber');
|
||||
assert.equal(owner.activeStyle, 'thermal');
|
||||
assert.equal(owner._preCyberStyle, null);
|
||||
assert.equal(owner._cyberStyleUserSelected, false);
|
||||
owner._setHudVariant('tactical', { applyVisualDefaults: true });
|
||||
assert.equal(owner.activeStyle, 'thermal');
|
||||
assert.equal(owner._preCyberStyle, null);
|
||||
});
|
||||
|
||||
test('scene and share restoration override Cyber and preserve restored Cyber parameters', async (t) => {
|
||||
const { owner, hud } = styleOwner(t);
|
||||
await owner.applyVisualState({ style: 'retro', hud: { variant: 'minimal' } });
|
||||
assert.equal(hud.getVariant(), 'minimal');
|
||||
owner._setHudVariant('cyber');
|
||||
await owner.restoreShareState({
|
||||
style: 'surveillance',
|
||||
hudVariant: 'operator',
|
||||
});
|
||||
// A link saved with the retired Operator layout restores as Tactical.
|
||||
assert.equal(hud.getVariant(), 'tactical');
|
||||
await owner.restoreShareState({
|
||||
style: 'thermal',
|
||||
hudVariant: 'cyber',
|
||||
styleParams: { palette: 0.73 },
|
||||
});
|
||||
assert.equal(hud.getVariant(), 'cyber');
|
||||
assert.equal(owner.activeStyle, 'thermal');
|
||||
assert.equal(owner.stages.thermal.uniforms.palette, 0.73);
|
||||
owner._setHudVariant('cyber', { applyVisualDefaults: true });
|
||||
assert.equal(owner.stages.thermal.uniforms.palette, 0.73);
|
||||
owner._setHudVariant('tactical');
|
||||
owner._setHudVariant('cyber', { applyVisualDefaults: true });
|
||||
assert.equal(owner.stages.thermal.uniforms.palette, 0.42);
|
||||
});
|
||||
|
||||
const read = (relative) =>
|
||||
readFileSync(new URL(relative, import.meta.url), 'utf8');
|
||||
|
||||
test('Cyber setup uses a compact toolbar icon and highlights the north-up letter', () => {
|
||||
const css = read('./styles/cyber.css');
|
||||
assert.match(
|
||||
css,
|
||||
/#top-center-actions #key-setup-chip\s*\{[^}]*inset: auto;[^}]*width: 36px;/,
|
||||
);
|
||||
assert.match(css, /#key-setup-chip\[hidden\]\s*\{\s*display: none;/);
|
||||
assert.match(
|
||||
css,
|
||||
/#north-up-view\[data-north-up='true'\]\s+\.camera-compass-n\s*\{[^}]*color: var\(--cyber-red-bright\)/,
|
||||
);
|
||||
});
|
||||
const cyberStyles = read('./styles/cyber.css');
|
||||
|
||||
// Source guards supplement rendered popup/hit-target checks. Inspect one rule
|
||||
// at a time so a safe declaration on a child cannot excuse a clipped ancestor.
|
||||
function cssRuleBody(styles, selector) {
|
||||
const match = styles.match(new RegExp(`${selector.source}\\s*\\{([^}]+)\\}`));
|
||||
assert.ok(match, `Missing CSS rule: ${selector.source}`);
|
||||
return match[1];
|
||||
}
|
||||
|
||||
test('Cyber Voice clips its decoration without clipping descendant help and errors', () => {
|
||||
const owner = cssRuleBody(
|
||||
cyberStyles,
|
||||
/:root\[data-ui-theme='cyber'\] #command-dock > #gev-voice-control/,
|
||||
);
|
||||
assert.match(owner, /isolation:\s*isolate;/);
|
||||
assert.match(owner, /overflow:\s*visible;/);
|
||||
assert.match(owner, /clip-path:\s*none;/);
|
||||
|
||||
const decoration = cssRuleBody(
|
||||
cyberStyles,
|
||||
/:root\[data-ui-theme='cyber'\] #command-dock > #gev-voice-control::before/,
|
||||
);
|
||||
assert.match(decoration, /clip-path:\s*polygon\(/);
|
||||
assert.match(decoration, /pointer-events:\s*none;/);
|
||||
assert.match(decoration, /inset:\s*0;/);
|
||||
assert.match(decoration, /z-index:\s*-1;/);
|
||||
});
|
||||
|
||||
test('Cyber dock pins escape the tray mask and its decoration overrides the legacy arrow geometry', () => {
|
||||
const owner = cssRuleBody(
|
||||
cyberStyles,
|
||||
/:root\[data-ui-theme='cyber'\] #command-dock \.dock-popover-content/,
|
||||
);
|
||||
assert.match(owner, /clip-path:\s*none;/);
|
||||
assert.match(owner, /isolation:\s*isolate;/);
|
||||
|
||||
// Including the tray owners beats #control-panel's more specific old
|
||||
// ::after arrow positioning. Otherwise left:auto can collapse the frame.
|
||||
const decoration = cssRuleBody(
|
||||
cyberStyles,
|
||||
/:root\[data-ui-theme='cyber'\]\s+#command-dock\s+:is\(#location-bar, #control-panel\)\s+\.dock-popover-content::after/,
|
||||
);
|
||||
assert.match(decoration, /inset:\s*0;/);
|
||||
assert.match(decoration, /width:\s*auto;/);
|
||||
assert.match(decoration, /height:\s*auto;/);
|
||||
assert.match(decoration, /transform:\s*none;/);
|
||||
assert.match(decoration, /clip-path:\s*var\(--cyber-panel-frame\);/);
|
||||
assert.match(decoration, /pointer-events:\s*none;/);
|
||||
});
|
||||
|
||||
test('Cyber lower-left telemetry tracks the credit anchor with clearance for its logo row', () => {
|
||||
const telemetry = cssRuleBody(
|
||||
cyberStyles,
|
||||
/#intel-hud\[data-variant='cyber'\] \.hud-bottom-left/,
|
||||
);
|
||||
const offset = telemetry.match(/bottom:\s*calc\(2vh \+ ([\d.]+)rem \+ var\(--world-timeline-lift, 0px\)\);/);
|
||||
assert.ok(offset, 'telemetry must retain the attribution viewport anchor');
|
||||
const credits = read('./styles/command-dock-trays.css');
|
||||
const creditOffsets = [
|
||||
...credits.matchAll(
|
||||
/#cesium-credits\s*\{[^}]*bottom:\s*calc\(2vh \+ ([\d.]+)rem \+ var\(--world-timeline-lift, 0px\)\);/g,
|
||||
),
|
||||
];
|
||||
assert.ok(creditOffsets.length > 0);
|
||||
for (const credit of creditOffsets) {
|
||||
assert.ok(
|
||||
Number(offset[1]) - Number(credit[1]) >= 2.75,
|
||||
'reserve the 28px logo row, baseline descent and 12px clearance at the 16px root size',
|
||||
);
|
||||
}
|
||||
assert.doesNotMatch(cyberStyles, /\.hud-bottom-left\s*\{\s*bottom:\s*60px;/);
|
||||
});
|
||||
|
||||
test('shared panel hooks affect only opted-in rail surfaces without overriding disclosure and concealment', () => {
|
||||
const styles = read('./styles/panel-surfaces.css');
|
||||
const rail = cssRuleBody(
|
||||
styles,
|
||||
/:is\(#left-panel-stack, #right-context-rail\)\s+> \[data-panel-id\]:has\(> \[data-panel-surface\]\)/,
|
||||
);
|
||||
assert.match(rail, /pointer-events:\s*auto;/);
|
||||
assert.doesNotMatch(rail, /(?:display|visibility):/);
|
||||
assert.doesNotMatch(
|
||||
styles,
|
||||
/:is\(#left-panel-stack, #right-context-rail\)\s*> \[data-panel-id\]\s*\{/,
|
||||
);
|
||||
assert.match(
|
||||
styles,
|
||||
/\[data-panel-surface\]:not\(\[hidden\]\):not\(dialog:not\(\[open\]\)\)\s*\{\s*display: flex;/,
|
||||
);
|
||||
assert.match(
|
||||
styles,
|
||||
/dialog\[data-panel-surface\]:not\(\[open\]\)\s*\{\s*display: none !important;/,
|
||||
);
|
||||
assert.match(
|
||||
styles,
|
||||
/body:is\(\.ui-clean-view, \.recording-mode\)[^{]+\{[^}]*visibility: hidden !important;[^}]*pointer-events: none !important;/,
|
||||
);
|
||||
});
|
||||
|
||||
test('Cyber clipped expand controls retain an inset keyboard-focus outline in map and cockpit', () => {
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/:root\[data-ui-theme='cyber'\]\s+:is\(\s*\.panel-collapse-btn,\s*body\.cockpit-mode \.cockpit-utility-glyph\s*\):focus-visible\s*\{[^}]*outline: 2px solid var\(--cyber-red-bright\) !important;[^}]*outline-offset: -3px;[^}]*box-shadow: none;/,
|
||||
);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/:root\[data-ui-theme='cyber'\]\s+:is\(\.panel-collapse-btn, body\.cockpit-mode \.cockpit-utility-glyph\):is\(\s*:hover,\s*:focus-visible\s*\)\s*\{[^}]*border-color: var\(--cyber-red-bright\);/,
|
||||
);
|
||||
});
|
||||
|
||||
test('Cyber Radio retains upstream nested Context ownership', () => {
|
||||
assert.doesNotMatch(cyberStyles, /#right-context-rail\s*>\s*#radio-panel/);
|
||||
});
|
||||
|
||||
test('Cyber cockpit launchers share Data Layers frame and expand-control treatment', () => {
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/:is\(\.panel-collapse-btn, body\.cockpit-mode \.cockpit-utility-glyph\)/,
|
||||
);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/body\.cockpit-mode \.cockpit-utility-launcher \{[^}]*width: var\(--cyber-panel-width\);[^}]*min-height: 60px;[^}]*clip-path: var\(--cyber-panel-frame\);/,
|
||||
);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/\.cockpit-utility-glyph::after \{\s*content: '\+';/,
|
||||
);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/\.cockpit-utility-glyph\[aria-expanded='true'\]::after \{\s*content: '−';/,
|
||||
);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/\.cockpit-utility-control\.is-expanded\s+\.cockpit-utility-launcher \{[^}]*width: 100%;[^}]*clip-path: none;/,
|
||||
);
|
||||
});
|
||||
|
||||
test('Cyber side panels share one width and one framed surface material', () => {
|
||||
assert.match(cyberStyles, /--cyber-panel-width: 272px;/);
|
||||
assert.match(cyberStyles, /--cyber-right-panel-width: 312px;/);
|
||||
assert.match(cyberStyles, /--cyber-panel-collapsed-width: 200px;/);
|
||||
assert.match(cyberStyles, /--cyber-panel-control-size: 30px;/);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/--cyber-panel-surface: rgba\(18, 24, 27, 0\.92\);/,
|
||||
);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/\.cockpit-utility-control\.is-expanded \{[\s\S]*?width: var\(--cyber-right-panel-width\);[\s\S]*?background-color: var\(--cyber-panel-surface\);[\s\S]*?background-image: var\(--cyber-panel-surface-detail\);[\s\S]*?clip-path: var\(--cyber-panel-frame\);/,
|
||||
);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/\.cockpit-utility-control\.is-expanded::after \{[\s\S]*?width: 36px;[\s\S]*?border-top: 1px solid rgba\(225, 102, 102, 0\.84\);/,
|
||||
);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/#global-context-panel #radio-panel\.collapsed \{\s*width: 100%;/,
|
||||
);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/#left-panel-stack\s*> :is\(#data-panel, #utilities-panel, #scene-panel\)\.collapsed \{\s*width: var\(--cyber-panel-collapsed-width\);/,
|
||||
);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/:is\(#data-panel, #utilities-panel, #scene-panel\)\.collapsed\s+:is\(\.data-panel-inner, \.utilities-panel-inner, \.scene-panel-inner\) \{[\s\S]*?height: 50px;[\s\S]*?min-height: 50px;/,
|
||||
);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/\.cockpit-utility-control:not\(\.is-expanded\)\s+\.cockpit-utility-launcher \{\s*width: var\(--cyber-panel-collapsed-width\);/,
|
||||
);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/#pp-toggles\s*> \.pp-header-row\s+\.pp-collapse-btn \{[\s\S]*?width: var\(--cyber-panel-control-size\);[\s\S]*?height: var\(--cyber-panel-control-size\);/,
|
||||
);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/#right-context-rail\s+:is\(\s*\.cctv-panel-inner,\s*\.weather-panel-inner,\s*\.recent-imagery-panel-inner,\s*\.street-level-panel-inner,\s*\.global-context-panel-inner\s*\) \{\s*padding-inline-end: 8px;/,
|
||||
);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/#right-context-rail[\s\S]*?:is\(\s*#cctv-panel,\s*#weather-panel,\s*#recent-imagery-panel,\s*#street-level-panel,\s*#global-context-panel\s*\)\.collapsed[\s\S]*?> \.panel-header \{[\s\S]*?height: 48px;[\s\S]*?padding: 0 10px 0 14px;/,
|
||||
);
|
||||
assert.doesNotMatch(
|
||||
cyberStyles,
|
||||
/\.cockpit-utility-control\.is-expanded\s*\{[^}]*order:/,
|
||||
'expanded Cockpit utilities must retain Display-then-Radio DOM order',
|
||||
);
|
||||
});
|
||||
|
||||
test('Cyber is a canonical HUD layout with a safe Tactical fallback', () => {
|
||||
assert.deepEqual(HUD_LAYOUTS, ['tactical', 'minimal', 'cyber']);
|
||||
assert.equal(normalizeHudLayout('CYBER'), 'cyber');
|
||||
assert.equal(normalizeHudLayout('operator'), 'tactical');
|
||||
assert.equal(normalizeHudLayout('unknown'), 'tactical');
|
||||
});
|
||||
|
||||
test('the Cyber HUD owns the global shell skin and leaving it restores defaults', () => {
|
||||
const root = { dataset: { unrelated: 'preserved' } };
|
||||
assert.equal(applyHudUiTheme(root, 'cyber'), 'cyber');
|
||||
assert.equal(root.dataset.uiTheme, 'cyber');
|
||||
assert.equal(applyHudUiTheme(root, 'minimal'), null);
|
||||
assert.equal(root.dataset.uiTheme, undefined);
|
||||
assert.equal(root.dataset.unrelated, 'preserved');
|
||||
});
|
||||
|
||||
test('an explicit transition into Cyber selects FLIR with Ironbow 0.42 once', () => {
|
||||
assert.deepEqual(CYBER_VISUAL_DEFAULTS, {
|
||||
style: 'thermal',
|
||||
ironbow: 0.42,
|
||||
});
|
||||
assert.equal(
|
||||
cyberVisualDefaultsForHudTransition('tactical', 'cyber', {
|
||||
explicit: true,
|
||||
}),
|
||||
CYBER_VISUAL_DEFAULTS,
|
||||
);
|
||||
assert.equal(
|
||||
cyberVisualDefaultsForHudTransition('cyber', 'cyber', {
|
||||
explicit: true,
|
||||
}),
|
||||
null,
|
||||
);
|
||||
assert.equal(cyberVisualDefaultsForHudTransition('tactical', 'cyber'), null);
|
||||
assert.equal(
|
||||
cyberVisualDefaultsForHudTransition('cyber', 'minimal', {
|
||||
explicit: true,
|
||||
}),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('Cyber visual defaults update the style, thermal palette and render state', () => {
|
||||
const calls = [];
|
||||
const owner = {
|
||||
stages: { thermal: { uniforms: { palette: 0 } } },
|
||||
services: {
|
||||
governorRequestRender: (reason) => calls.push(['render', reason]),
|
||||
},
|
||||
setStyle: (style, options) => calls.push(['style', style, options]),
|
||||
_updateSliderPanel: (style, options) =>
|
||||
calls.push(['sliders', style, options]),
|
||||
};
|
||||
|
||||
VisualSettings.prototype._applyCyberVisualDefaults.call(
|
||||
owner,
|
||||
CYBER_VISUAL_DEFAULTS,
|
||||
);
|
||||
|
||||
assert.equal(owner.stages.thermal.uniforms.palette, 0.42);
|
||||
assert.deepEqual(calls, [
|
||||
[
|
||||
'style',
|
||||
'thermal',
|
||||
{
|
||||
applyPreset: false,
|
||||
revealParameters: false,
|
||||
preserveCyberRestore: true,
|
||||
},
|
||||
],
|
||||
['sliders', 'thermal', { reveal: false }],
|
||||
['render', 'cyber-visual-defaults'],
|
||||
]);
|
||||
});
|
||||
|
||||
test('the Display selector, voice schema and final stylesheet expose Cyber', () => {
|
||||
const display = read('./views/panels/DisplayPanel.vue');
|
||||
const stylesheet = read('../../style.css');
|
||||
const rightRail = read('./rightPanelRail.js');
|
||||
const hud = read('../hud.js');
|
||||
const hudView = read('./views/IntelHudView.vue');
|
||||
const detection = read('../data/detection.js');
|
||||
const aircraftModels = read('../data/aircraftModelLayer.js');
|
||||
const setHud = GEV_ACTION_SCHEMAS.find((schema) => schema.name === 'set_hud');
|
||||
|
||||
assert.match(display, /<option value="cyber">\{\{ t\('Cyber'\) \}\}<\/option>/);
|
||||
assert.match(display, /id="cyber-sonar-toggle"/);
|
||||
assert.match(
|
||||
display,
|
||||
/id="cyber-sonar-opacity"[^>]*:model-value="sonar\?\.opacity \?\? 84" :aria-label="t\('Cyber contact and label opacity'\)"/,
|
||||
);
|
||||
assert.match(display, /id="cyber-sonar-sector"/);
|
||||
assert.deepEqual(setHud.parameters.properties.layout.enum, HUD_LAYOUTS);
|
||||
assert.match(stylesheet, /@import '\.\/src\/ui\/styles\/cyber\.css';\s*$/);
|
||||
assert.match(cyberStyles, /:root\[data-ui-theme='cyber'\]/);
|
||||
assert.match(cyberStyles, /\.material-symbols-outlined/);
|
||||
assert.match(cyberStyles, /\.pp-label/);
|
||||
assert.match(cyberStyles, /#intel-hud\[data-variant='cyber'\]/);
|
||||
assert.match(cyberStyles, /#left-panel-stack/);
|
||||
assert.match(cyberStyles, /#right-context-rail/);
|
||||
assert.match(cyberStyles, /#command-dock/);
|
||||
assert.match(cyberStyles, /--cyber-panel-frame: polygon/);
|
||||
assert.match(cyberStyles, /\.data-panel-inner,/);
|
||||
assert.match(cyberStyles, /#pp-toggles\.collapsed > \.pp-header-row/);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/\.panel-collapsible:not\(#location-bar\):not\(#control-panel\)::after/,
|
||||
);
|
||||
assert.match(cyberStyles, /clip-path: var\(--cyber-panel-frame\);/);
|
||||
assert.match(hudView, /class="hud-sonar" aria-hidden="true"/);
|
||||
assert.match(cyberStyles, /\.hud-sonar::before/);
|
||||
assert.match(cyberStyles, /\.hud-sonar::after/);
|
||||
assert.match(cyberStyles, /@keyframes cyber-sonar-sweep/);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/animation-delay:\s*var\(--cyber-sonar-phase-delay, 0ms\)/,
|
||||
);
|
||||
assert.doesNotMatch(cyberStyles, /--cyber-sonar-angle/);
|
||||
assert.match(cyberStyles, /prefers-reduced-motion: reduce/);
|
||||
assert.match(detection, /candidate\.sonarFactor \?\? 1/);
|
||||
assert.match(detection, /sonarActive && !obj\.skipLabel/);
|
||||
assert.match(detection, /const bracketAlpha = admissionAlpha \* sonarFactor/);
|
||||
assert.match(detection, /sonarSampler\.label\(sonarFactor\)/);
|
||||
assert.match(detection, /createCyberSonarSampler\(width, height, now\)/);
|
||||
assert.match(cyberStyles, /data-cyber-sonar='off'/);
|
||||
assert.match(detection, /governorRequestRender\('cyber-sonar-cadence'\)/);
|
||||
assert.match(
|
||||
detection,
|
||||
/const animatingCount = countAnimatingRenderEntries\(renderEntries\);/,
|
||||
);
|
||||
assert.doesNotMatch(detection, /sonarActive \? 1 : 0/);
|
||||
assert.match(
|
||||
aircraftModels,
|
||||
/alpha: state\._irBoost\s*\?\s*1\s*:\s*aircraftTreatmentAlpha\(/,
|
||||
);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/#title-bar \.title-logo #globe \{[\s\S]*?fill: var\(--cyber-red\);[\s\S]*?stroke: var\(--cyber-red-bright\);/,
|
||||
);
|
||||
assert.match(cyberStyles, /#title-bar \.title-logo #globe_cage/);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/#top-center-actions button\s*\{[\s\S]*?border-radius:\s*0;[\s\S]*?clip-path:\s*polygon\(\s*29% 0,\s*71% 0,[\s\S]*?0 29%\s*\);/,
|
||||
);
|
||||
assert.match(cyberStyles, /#top-center-actions button::before/);
|
||||
assert.match(cyberStyles, /\.hud-top-left/);
|
||||
assert.match(cyberStyles, /transparent 0 min\(40vw, 52vh\)/);
|
||||
assert.match(cyberStyles, /\.hud-bottom-bar \{\s*display: none;/);
|
||||
assert.doesNotMatch(cyberStyles, /\.hud-top-bar/);
|
||||
// Cyber shares the measured rail/credit keep-out rather than overriding it.
|
||||
assert.doesNotMatch(
|
||||
cyberStyles,
|
||||
/#right-context-rail\s*\{[^}]*\b(?:top|bottom|height|max-height):/,
|
||||
);
|
||||
assert.match(cyberStyles, /--cyber-hud-card-top: max\(100px, 10\.25vh\);/);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/--cyber-left-rail-top: max\([\s\S]*?220px,[\s\S]*?calc\(var\(--cyber-hud-card-top\) \+ 120px\)/,
|
||||
);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/\.hud-top-left \{[\s\S]*?top: var\(--cyber-hud-card-top\);/,
|
||||
);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/#left-panel-stack \{[\s\S]*?top: var\(--cyber-left-rail-top\) !important;[\s\S]*?bottom: calc\(2vh \+ 13rem \+ var\(--world-timeline-lift, 0px\)\);/,
|
||||
);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/\.hud-left-edge \{\s*top: calc\(var\(--cyber-left-rail-top\) - 18px\);\s*left: 14px;/,
|
||||
);
|
||||
assert.match(
|
||||
rightRail,
|
||||
/const leftStackTop = settledLeftRailTop\([\s\S]*?const alignedTop = Number\.isFinite\(leftStackTop\)[\s\S]*?baseTop: alignedTop,/,
|
||||
);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/--right-display-collapsed-width: var\(--cyber-panel-collapsed-width\);/,
|
||||
);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/clip-path: polygon\([\s\S]*?12px 0,[\s\S]*?0 12px/,
|
||||
);
|
||||
assert.match(cyberStyles, /\.hud-corner::before/);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/--cyber-telemetry-fill: rgba\(13, 20, 23, 0\.985\);/,
|
||||
);
|
||||
assert.match(cyberStyles, /var\(--cyber-telemetry-fill\)/);
|
||||
assert.match(cyberStyles, />\s*\.panel-header\s+\.panel-title::before/);
|
||||
assert.match(cyberStyles, /\.panel-collapsible\.collapsed::after/);
|
||||
assert.match(cyberStyles, /\.panel-collapsible:not\(\.collapsed\)::after/);
|
||||
assert.match(cyberStyles, /\.context-mode-standby:not\(\[hidden\]\)/);
|
||||
// The base standby is borderless plain text, so the focus card must name its
|
||||
// own frame width and centring rather than inherit them.
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/\.context-mode-standby:not\(\[hidden\]\) \{[^}]*place-content: center;[^}]*border: 1px solid[^}]*text-align: center;/,
|
||||
);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/:root\[data-ui-theme='cyber'\] \.global-context-modes \{[^}]*border: 0;/,
|
||||
);
|
||||
assert.match(cyberStyles, /mask-image: linear-gradient\(/);
|
||||
assert.match(cyberStyles, /flex: 1 1 auto;/);
|
||||
assert.match(cyberStyles, /#left-panel-stack:has/);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/inset-inline-start: calc\(54px \+ var\(--panel-rail-clearance\)\);/,
|
||||
);
|
||||
assert.match(cyberStyles, /right: calc\(51px \+ var\(--panel-rail-clearance\)\);/);
|
||||
// Each side's edge line shows only beside an open panel.
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/#left-panel-stack:has\(> \[data-panel-id\]:not\(\.collapsed, \[hidden\]\)\) \{\s*border-inline-start-color:/,
|
||||
);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/#right-context-rail:has\(> \[data-panel-id\]:not\(\.collapsed, \[hidden\]\)\) \{\s*border-inline-end-color:/,
|
||||
);
|
||||
assert.match(cyberStyles, /bottom: calc\(2vh \+ 13rem \+ var\(--world-timeline-lift, 0px\)\);/);
|
||||
assert.doesNotMatch(cyberStyles, /NAV 01 \/\/ COMMAND BUS \/\/ VIS 03/);
|
||||
assert.match(cyberStyles, /data-layer-id='satellites'/);
|
||||
assert.match(cyberStyles, /#search-toggle::before/);
|
||||
assert.match(cyberStyles, /VISUAL MATRIX \/\/ 03/);
|
||||
assert.match(cyberStyles, /body\.cockpit-mode #cockpit-hud/);
|
||||
assert.match(cyberStyles, /TARGET SCANNING \/\/ LIVE VECTOR/);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/body\.cockpit-mode #global-loading-status \{[\s\S]*?top: 60px;[\s\S]*?z-index: 146;/,
|
||||
);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/body\.cockpit-mode #global-loading-detail \{[\s\S]*?color: var\(--cockpit-accent\);/,
|
||||
);
|
||||
assert.match(cyberStyles, /body\.cockpit-mode \.cockpit-visor-shell::before/);
|
||||
assert.match(cyberStyles, /body\.cockpit-mode \.cockpit-scan-array/);
|
||||
assert.match(cyberStyles, /body\.cockpit-mode \.cockpit-target-side-arcs/);
|
||||
assert.match(cyberStyles, /body\.cockpit-mode \.cockpit-target-ticks/);
|
||||
assert.match(cyberStyles, /body\.cockpit-mode \.cockpit-target-core/);
|
||||
assert.match(cyberStyles, /width: min\(48vw, 60vh\);/);
|
||||
assert.match(cyberStyles, /body\.cockpit-mode \.cockpit-context-window/);
|
||||
assert.match(cyberStyles, /body\.cockpit-mode \.cockpit-signal-window/);
|
||||
assert.match(cyberStyles, /body\.cockpit-mode #intel-hud\.active/);
|
||||
});
|
||||
|
||||
test('Cyber voice telemetry renders a live scan scope without replacing audio ownership', () => {
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/#gev-voice-control\s*\{[\s\S]*?--cyber-voice-wave:/,
|
||||
);
|
||||
assert.match(cyberStyles, /\.gev-voice-visualizer::before/);
|
||||
assert.match(cyberStyles, /\.gev-voice-visualizer::after/);
|
||||
assert.match(cyberStyles, /@keyframes gev-cyber-voice-scan/);
|
||||
assert.match(cyberStyles, /@keyframes gev-cyber-voice-lock/);
|
||||
assert.match(cyberStyles, /\[data-speaker='user'\]/);
|
||||
assert.match(cyberStyles, /\[data-speaker='ai'\]/);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/prefers-reduced-motion: reduce[\s\S]*?gev-voice-visualizer::after[\s\S]*?animation: none/,
|
||||
);
|
||||
});
|
||||
|
||||
test('Cyber Cockpit Display uses the released briefing lane instead of the legacy viewport cap', () => {
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/body\.cockpit-mode\s+#cockpit-display-panel\s*\{[\s\S]*?max-height:\s*calc\(var\(--cockpit-utility-expanded-max-height, 72vh\) - 62px\)/,
|
||||
);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/#cockpit-hud:has\(\.cockpit-utility-control\.is-expanded\)[\s\S]*?\.cockpit-signal-window\[data-collapsed='true'\][\s\S]*?bottom: 80px;[\s\S]*?visibility:\s*visible/,
|
||||
);
|
||||
});
|
||||
|
||||
test('Cyber Cockpit keeps Data Layers inside its bounded rail', () => {
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/body:not\(\.cockpit-mode\)\s+#left-panel-stack:has\([\s\S]*?max-height:\s*none;/,
|
||||
);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/body\.cockpit-mode\s+#left-panel-stack\s+> :is\(#data-panel, #utilities-panel\) \{[\s\S]*?max-height: min\(64vh, 610px\);/,
|
||||
);
|
||||
});
|
||||
|
||||
test('Cyber desktop cockpit collapsed utility frames match the 50px Data Layers frame', () => {
|
||||
const desktop = cyberStyles.slice(
|
||||
cyberStyles.indexOf('@media (min-width: 961px) and (min-height: 650px)'),
|
||||
cyberStyles.indexOf('@media (max-width: 720px)'),
|
||||
);
|
||||
assert.match(
|
||||
desktop,
|
||||
/:root\[data-ui-theme='cyber'\]\s+body\.cockpit-mode\s+\.cockpit-utility-control:not\(\.is-expanded\)\s+\.cockpit-utility-launcher\s*\{\s*height: 50px;\s*min-height: 50px;\s*padding: 9px 18px 9px 24px;/,
|
||||
);
|
||||
assert.match(
|
||||
desktop,
|
||||
/\.cockpit-utility-control:not\(\.is-expanded\)\s+\.cockpit-utility-launcher::after\s*\{\s*bottom: 6px;/,
|
||||
);
|
||||
});
|
||||
|
||||
test('Cyber right panels preserve intrinsic sizing and the shared rail allocation', () => {
|
||||
assert.doesNotMatch(
|
||||
cyberStyles.slice(cyberStyles.indexOf(":root[data-ui-theme='cyber'] {")),
|
||||
/#right-context-rail\s*>[^{}]+\{[^{}]*\b(?:flex|height|max-height):/,
|
||||
);
|
||||
});
|
||||
|
||||
test('Cyber panels retain clean edges without the added footer band', () => {
|
||||
assert.doesNotMatch(cyberStyles, /--cyber-panel-foot-/);
|
||||
assert.doesNotMatch(cyberStyles, /border-bottom: 24px solid transparent/);
|
||||
});
|
||||
|
||||
test('Cyber keeps Sonar on/off without the removed CSS effect switch or dimmer', () => {
|
||||
const template = readFileSync(
|
||||
new URL('./views/panels/DisplayPanel.vue', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
assert.match(template, /id="cyber-sonar-toggle"/);
|
||||
assert.doesNotMatch(template, /data-sonar-mode|cyber-sonar-mode-row/);
|
||||
assert.doesNotMatch(cyberStyles, /cyber-scene-dimmer|data-cyber-sonar-mode/);
|
||||
});
|
||||
|
||||
test('Cyber Display uses a red title without a panel-specific center tab', () => {
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/#pp-toggles \.pp-header-label\s*\{\s*color: var\(--cyber-red-bright\);/,
|
||||
);
|
||||
assert.doesNotMatch(cyberStyles, /#pp-toggles[^,{]*::after\s*\{/);
|
||||
assert.match(cyberStyles, /isolation: isolate;\s*clip-path: none;/);
|
||||
assert.match(cyberStyles, /#pp-toggles:not\(\.collapsed\)::before/);
|
||||
});
|
||||
|
||||
test('Cyber omits only the fictional classification and system header lines', () => {
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
/#intel-hud\[data-variant='cyber'\] \.hud-top-left \.hud-classification,\s*#intel-hud\[data-variant='cyber'\] \.hud-top-left \.hud-system\s*\{\s*display: none;\s*\}/,
|
||||
);
|
||||
});
|
||||
@@ -54,7 +54,7 @@ export class DisplayBindings {
|
||||
documentRef: document,
|
||||
searchInput: this._locationSearch,
|
||||
actions: {
|
||||
setStyle: (style) => this.setStyle(style, { userInitiated: true }),
|
||||
setStyle: (style) => this.setStyle(style),
|
||||
dismissSearch: () => this._closeLocationSearch?.({ ifOpen: true }),
|
||||
toggleHud: () => {
|
||||
this.shareLinkManager?.claimRestoreLane?.('visual');
|
||||
@@ -82,7 +82,7 @@ export class DisplayBindings {
|
||||
this._detachDisplayControls?.();
|
||||
const store = this.displayStore ?? useDisplayStore(applicationPinia());
|
||||
const token = store.connect({
|
||||
setStyle: (style) => this.setStyle(style, { userInitiated: true }),
|
||||
setStyle: (style) => this.setStyle(style),
|
||||
toggleBloom: () => {
|
||||
this.shareLinkManager?.claimRestoreLane?.('visual');
|
||||
this._setBloomEnabled(!this.bloomEnabled);
|
||||
@@ -116,7 +116,7 @@ export class DisplayBindings {
|
||||
},
|
||||
setHudLayout: (value) => {
|
||||
this.shareLinkManager?.claimRestoreLane?.('visual');
|
||||
this._setHudVariant(value, { applyVisualDefaults: true });
|
||||
this._setHudVariant(value);
|
||||
},
|
||||
toggleCleanView: () => this.toggleCleanView(),
|
||||
exitCleanView: () => this.toggleCleanView(false),
|
||||
@@ -155,7 +155,10 @@ export class DisplayBindings {
|
||||
this._updateHudButtonState();
|
||||
this._syncShareState();
|
||||
},
|
||||
toggleSonar: () => this._setCyberSonarEnabled(),
|
||||
toggleSonar: () => {
|
||||
this.shareLinkManager?.claimRestoreLane?.('visual');
|
||||
this._setCyberSonarEnabled();
|
||||
},
|
||||
setSonarRings: (value) => this._setCyberSonarSetting('rings', value),
|
||||
setSonarRange: (value) => this._setCyberSonarSetting('range', value),
|
||||
setSonarIntensity: (value) =>
|
||||
@@ -178,9 +181,8 @@ export class DisplayBindings {
|
||||
// feather and opacity, 3D aircraft on in Proximity.
|
||||
resetVisual: () => {
|
||||
this.shareLinkManager?.claimRestoreLane?.('visual');
|
||||
this.setStyle('normal', { userInitiated: true });
|
||||
// The HUD layout follows the Normal style, as choosing it does: the
|
||||
// Cyber HUD stays Cyber.
|
||||
this.setStyle('normal');
|
||||
// The HUD layout and the Sonar style stay as the viewer set them.
|
||||
this._applyGlobalPostDefaults({ keepHudVariant: true });
|
||||
this._setDetectionAllocation('ELASTIC');
|
||||
this._setScope({ enabled: true, featherPct: 100, opacityPct: 100 });
|
||||
|
||||
@@ -238,20 +238,29 @@ test('the HUD and Sonar controls render what VisualSettings shows', async (t) =>
|
||||
getVariant: () => variant,
|
||||
});
|
||||
owner._scheduleAdaptivePanelLayout = () => {};
|
||||
assert.equal($('cyber-sonar-toggle').textContent, 'ON');
|
||||
assert.equal($('cyber-sonar-toggle').getAttribute('aria-pressed'), 'true');
|
||||
// Sonar is opt-in: OFF until the viewer turns it on.
|
||||
assert.equal($('cyber-sonar-toggle').textContent, 'OFF');
|
||||
assert.equal($('cyber-sonar-toggle').getAttribute('aria-pressed'), 'false');
|
||||
assert.equal(
|
||||
[...$('hud-layout-select').options].map((option) => option.value).join(),
|
||||
'tactical,minimal',
|
||||
);
|
||||
|
||||
owner._syncHudControls();
|
||||
await nextTick();
|
||||
assert.equal($('hud-toggle').classList.contains('active'), true);
|
||||
assert.equal($('hud-layout-row').classList.contains('visible'), true);
|
||||
assert.equal($('hud-layout-select').value, 'minimal');
|
||||
// The toggle shows with the HUD; its sliders wait for Sonar ON.
|
||||
assert.equal($('cyber-sonar-row').classList.contains('visible'), true);
|
||||
assert.equal($('cyber-sonar-rings-row').classList.contains('visible'), false);
|
||||
|
||||
visible = false;
|
||||
owner._updateHudButtonState();
|
||||
await nextTick();
|
||||
assert.equal($('hud-toggle').classList.contains('active'), false);
|
||||
assert.equal($('hud-layout-row').classList.contains('visible'), false);
|
||||
assert.equal($('cyber-sonar-row').classList.contains('visible'), false);
|
||||
|
||||
owner._sonarShown = {
|
||||
enabled: false,
|
||||
@@ -272,6 +281,19 @@ test('the HUD and Sonar controls render what VisualSettings shows', async (t) =>
|
||||
assert.equal($('cyber-sonar-range-value').textContent, '90%');
|
||||
assert.equal($('cyber-sonar-sector').value, '30');
|
||||
assert.equal($('cyber-sonar-sector-value').textContent, '30°');
|
||||
|
||||
visible = true;
|
||||
owner._updateHudButtonState();
|
||||
owner._sonarShown = { ...owner._sonarShown, enabled: true };
|
||||
owner._publishDisplay();
|
||||
await nextTick();
|
||||
assert.equal(toggle.textContent, 'ON');
|
||||
for (const name of ['rings', 'range', 'intensity', 'opacity', 'sector'])
|
||||
assert.equal(
|
||||
$(`cyber-sonar-${name}-row`).classList.contains('visible'),
|
||||
true,
|
||||
name,
|
||||
);
|
||||
});
|
||||
|
||||
test('Scope and Celestial render what VisualSettings shows', async (t) => {
|
||||
|
||||
@@ -321,7 +321,7 @@ test('DisplayBindings sets the scope opacity and resets Visual to its defaults',
|
||||
document.querySelector('#pp-toggles .pp-reset-btn').click();
|
||||
assert.deepEqual(calls, [
|
||||
['claim', 'visual'],
|
||||
['style', 'normal', { userInitiated: true }],
|
||||
['style', 'normal', undefined],
|
||||
['postDefaults', { keepHudVariant: true }],
|
||||
['allocation', 'ELASTIC'],
|
||||
['scope', { enabled: true, featherPct: 100, opacityPct: 100 }],
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
/** Cyber keeps the frame fixed; other layouts retain their existing scroller. */
|
||||
export function displayPanelScroller(panel) {
|
||||
return panel?.ownerDocument?.documentElement?.dataset.uiTheme === 'cyber'
|
||||
? panel.querySelector('.pp-panel-body') || panel
|
||||
: panel;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { resolvePickedContext } from '../data/pickedContext.js';
|
||||
import { clickCard } from '../data/pickRegistry.js';
|
||||
import { followedOf, onFollowChanged } from '../data/followed.js';
|
||||
import { fromDegreesInto } from '../geo/ellipsoid.js';
|
||||
import { inputFor } from '../input/dispatcher.js';
|
||||
@@ -45,8 +46,6 @@ const FOLLOWABLE = new Set(['flights', 'military', 'satellites']);
|
||||
* to the point under the camera without it.
|
||||
* @param {(lat: number, lon: number) => Promise<object>} [options.regionalBrief]
|
||||
* The app's regional brief service, for the weather and news Context shows.
|
||||
* @param {(x: number, y: number) => object|null} [options.overlayHit]
|
||||
* The overlay card under a screen point, if any (a vessel's, a fire's).
|
||||
* @returns {() => void} disconnects
|
||||
*/
|
||||
export function installEntityContext({
|
||||
@@ -55,14 +54,13 @@ export function installEntityContext({
|
||||
pinia,
|
||||
pickWorld,
|
||||
regionalBrief,
|
||||
overlayHit,
|
||||
}) {
|
||||
const store = useEntityCardStore(pinia);
|
||||
const omnibar = useOmnibarStore(pinia);
|
||||
const voice = useVoiceStore(pinia);
|
||||
const cockpitStore = useCockpitStore(pinia);
|
||||
const chrome = usePanelChromeStore(pinia);
|
||||
/** Whether Context is open; a closed panel reads nothing. */
|
||||
/** Whether Context is open. (readView also reads while the Omnibar is focused.) */
|
||||
const isOpen = () =>
|
||||
chrome.panels['global-context-panel']?.collapsed === false;
|
||||
const doc = globalThis.document;
|
||||
@@ -223,7 +221,8 @@ export function installEntityContext({
|
||||
// the height. Read when the camera settles, not every frame.
|
||||
const readView = () => {
|
||||
const port = camera();
|
||||
if (!port || !isOpen()) return;
|
||||
if (!port || (!isOpen() && doc?.activeElement?.id !== 'gev-omnibar-input'))
|
||||
return;
|
||||
const pose = port.pose();
|
||||
if (![pose.lat, pose.lon, pose.height].every(Number.isFinite)) return;
|
||||
const middle = pickWorld?.(viewer, 0.5, 0.5);
|
||||
@@ -272,6 +271,12 @@ export function installEntityContext({
|
||||
listen();
|
||||
readView();
|
||||
}, 0);
|
||||
// The Omnibar's nearby suggestions also need a fresh center even with
|
||||
// Context closed. Its focus event requests one camera read.
|
||||
const onSearchFocus = (event) => {
|
||||
if (event.target?.id === 'gev-omnibar-input') readView();
|
||||
};
|
||||
doc?.addEventListener('focusin', onSearchFocus);
|
||||
// Opening the panel describes the view as it is now.
|
||||
let wasOpen = isOpen();
|
||||
const offChrome = chrome.$subscribe(() => {
|
||||
@@ -311,6 +316,10 @@ export function installEntityContext({
|
||||
// Cockpit has its own picks, and Context is hidden while it runs. A
|
||||
// camera drag never selects, even if it ends over something.
|
||||
if (inCockpit() || !isTrackingSelectionGesture(event.gesture)) return;
|
||||
// A card or label painted on top is its layer's click, read once per
|
||||
// click so every layer agrees: Context names nothing under it and keeps
|
||||
// its own card as it is.
|
||||
if (clickCard(event)) return;
|
||||
const identity = resolvePickedContext(event.hit, {
|
||||
dataManager: getDataManager(),
|
||||
});
|
||||
@@ -324,14 +333,8 @@ export function installEntityContext({
|
||||
// A click on open ground, sea or sky lets go of what was selected. A
|
||||
// click on something else Context cannot describe (a label, a trail)
|
||||
// leaves the card as it is.
|
||||
// Only a clean click lets go, as the layers' own clicks do; a card
|
||||
// painted on the overlay (a vessel's, a fire's) is not open map.
|
||||
if (
|
||||
event.surface &&
|
||||
isTrackingClickGesture(event.gesture) &&
|
||||
!overlayHit?.(event.screenPosition?.x, event.screenPosition?.y)
|
||||
)
|
||||
store.clear();
|
||||
// Only a clean click lets go, as the layers' own clicks do.
|
||||
if (event.surface && isTrackingClickGesture(event.gesture)) store.clear();
|
||||
});
|
||||
|
||||
// Layers that select through the context store (GeoJSON sites, fires,
|
||||
@@ -356,6 +359,7 @@ export function installEntityContext({
|
||||
clearTimeout(trailing);
|
||||
offFollow();
|
||||
offChrome();
|
||||
doc?.removeEventListener('focusin', onSearchFocus);
|
||||
clearTimeout(followCheck);
|
||||
globalThis.removeEventListener?.('gev:entity-selected', onSelected);
|
||||
store.connect(null);
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createPinia } from 'pinia';
|
||||
import { installEntityContext } from './entityContextBridge.js';
|
||||
import { useEntityCardStore } from './stores/entityCard.js';
|
||||
import { fakeInput } from '../input/testDoubles.mjs';
|
||||
import {
|
||||
registerPickOwner,
|
||||
setClickCardHitTest,
|
||||
unregisterPickOwner,
|
||||
} from '../data/pickRegistry.js';
|
||||
|
||||
// The card or label painted on top takes the click: Context names nothing
|
||||
// under it, exact or nearby, an acting owner's item or a passive one, and
|
||||
// keeps its own card. On open map it names what the click found.
|
||||
test('Context names nothing under a card painted on top, and keeps its card', (t) => {
|
||||
const previous = globalThis.matchMedia;
|
||||
globalThis.matchMedia = () => ({ matches: true });
|
||||
t.after(() => {
|
||||
if (previous) globalThis.matchMedia = previous;
|
||||
else delete globalThis.matchMedia;
|
||||
});
|
||||
const fire = { set: 'test-fires:1', id: 'fire:1' };
|
||||
const plane = { set: 'test-planes:1', id: 'plane:1' };
|
||||
const route = { set: 'test-route:1', id: 'route:line' };
|
||||
registerPickOwner('test-fires', (id) => id === fire.id);
|
||||
registerPickOwner('test-planes', (id) => id === plane.id);
|
||||
registerPickOwner('test-route', (id) => id.startsWith('route:'));
|
||||
let cardOnTop = false;
|
||||
// The card on top at a click, as the host answers the pick registry.
|
||||
setClickCardHitTest(() =>
|
||||
cardOnTop ? { sourceId: 'earthquake-card', entryId: 'q' } : null,
|
||||
);
|
||||
t.after(() => {
|
||||
setClickCardHitTest(null);
|
||||
unregisterPickOwner('test-fires');
|
||||
unregisterPickOwner('test-planes');
|
||||
unregisterPickOwner('test-route');
|
||||
});
|
||||
let exact = null;
|
||||
let near = null;
|
||||
const viewer = {
|
||||
scene: {
|
||||
pick: () => (exact ? { id: exact } : null),
|
||||
drillPick: () => (near ? [{ id: near }] : []),
|
||||
},
|
||||
};
|
||||
const input = fakeInput(viewer);
|
||||
const pinia = createPinia();
|
||||
const disconnect = installEntityContext({
|
||||
viewer,
|
||||
getDataManager: () => ({
|
||||
isEnabled: () => true,
|
||||
layers: new Map(),
|
||||
getAll: () => [],
|
||||
}),
|
||||
pinia,
|
||||
});
|
||||
t.after(() => {
|
||||
disconnect();
|
||||
input.destroy();
|
||||
});
|
||||
const store = useEntityCardStore(pinia);
|
||||
const named = [];
|
||||
let clears = 0;
|
||||
store.select = (identity) => named.push(identity.id);
|
||||
store.clear = () => clears++;
|
||||
const tap = (hitExact, hitNear) => {
|
||||
exact = hitExact;
|
||||
near = hitNear;
|
||||
named.length = 0;
|
||||
input.click();
|
||||
return [...named];
|
||||
};
|
||||
assert.deepEqual(tap(null, fire), ['fire:1'], 'open map: a near fire');
|
||||
assert.deepEqual(tap(route, null), ['route:line'], 'open map: a route');
|
||||
cardOnTop = true;
|
||||
assert.deepEqual(tap(null, fire), [], 'under a card: a near fire');
|
||||
assert.deepEqual(tap(fire, fire), [], 'under a card: an exact fire');
|
||||
assert.deepEqual(tap(plane, plane), [], 'under a card: an aircraft');
|
||||
assert.deepEqual(tap(route, null), [], 'under a card: a route');
|
||||
const cleared = clears;
|
||||
tap(null, null);
|
||||
assert.equal(clears, cleared, 'a card over open map is not open map');
|
||||
});
|
||||
@@ -0,0 +1,787 @@
|
||||
import {
|
||||
getScopeMaskFeather,
|
||||
getScopeMaskOpacity,
|
||||
isScopeMaskEnabled,
|
||||
setScopeMaskEnabled,
|
||||
setScopeMaskFeather,
|
||||
setScopeMaskOpacity,
|
||||
} from '../scopeMask.js';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readdirSync, readFileSync } from 'node:fs';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
HUD_LAYOUTS,
|
||||
isLegacySonarHudLayout,
|
||||
LEGACY_SONAR_HUD_LAYOUTS,
|
||||
normalizeHudLayout,
|
||||
} from '../hudLayouts.js';
|
||||
import {
|
||||
isCyberMapThemeActive,
|
||||
isCyberSonarActive,
|
||||
isCyberSonarEnabled,
|
||||
setCyberSonarEnabled,
|
||||
} from '../cyberSonar.js';
|
||||
import { GEV_ACTION_SCHEMAS } from '../voice/actionSchemas.js';
|
||||
import { createGevActionRunner } from '../voice/gevActions.js';
|
||||
import { StyleManager } from './applicationShell.js';
|
||||
import { setCyberSonarControls } from './cyberSonarControls.js';
|
||||
import { createPinia } from 'pinia';
|
||||
import { useDisplayStore } from './stores/display.js';
|
||||
import { VisualSettings } from './visualSettings.js';
|
||||
import { normalizeShot } from '../scenes/project.js';
|
||||
import {
|
||||
SCENE_DOCUMENT_VERSION,
|
||||
validateSceneDocument,
|
||||
} from '../director/document.js';
|
||||
import { decodeShareView, encodeShareView } from '../share/viewCodec.js';
|
||||
import { toLegacyShareState } from '../share/legacyShareState.js';
|
||||
import { STYLES } from './visualPresets.js';
|
||||
|
||||
const read = (relative) =>
|
||||
readFileSync(new URL(relative, import.meta.url), 'utf8');
|
||||
|
||||
function cssRuleBody(styles, selector) {
|
||||
const match = styles.match(new RegExp(`${selector.source}\\s*\\{([^}]+)\\}`));
|
||||
assert.ok(match, `Missing CSS rule: ${selector.source}`);
|
||||
return match[1];
|
||||
}
|
||||
|
||||
function styleOwner(t, initialVariant = 'tactical') {
|
||||
const previous = { document: globalThis.document, window: globalThis.window };
|
||||
const root = { dataset: {} };
|
||||
globalThis.document = { documentElement: root, querySelectorAll: () => [] };
|
||||
globalThis.window = { dispatchEvent() {} };
|
||||
t.after(() => Object.assign(globalThis, previous));
|
||||
let variant = initialVariant;
|
||||
const calls = [];
|
||||
const hud = {
|
||||
getVariant: () => variant,
|
||||
// Normalize like the real HUD so removed layouts fall back.
|
||||
setVariant: (value) => (variant = normalizeHudLayout(value)),
|
||||
setMode: (value) => calls.push(['mode', value]),
|
||||
onStyleChange: (value) => calls.push(['style', value]),
|
||||
visible: true,
|
||||
};
|
||||
hud.setVariant(initialVariant);
|
||||
const owner = Object.create(VisualSettings.prototype);
|
||||
Object.assign(owner, {
|
||||
activeStyle: 'normal',
|
||||
store: { publish() {} },
|
||||
readHud: () => hud,
|
||||
readShareLinks: () => ({ onStyleChange() {} }),
|
||||
_visualEffects: {
|
||||
stages: Object.fromEntries(
|
||||
Object.entries(STYLES).map(([name, config]) => [
|
||||
name,
|
||||
{ uniforms: { ...config.uniforms, intensity: 0 } },
|
||||
]),
|
||||
),
|
||||
},
|
||||
services: {
|
||||
governorRequestRender: (reason) => calls.push(['render', reason]),
|
||||
setDetectionStyle() {},
|
||||
},
|
||||
_setBloomEnabled: (value) => calls.push(['bloom', value]),
|
||||
_setSharpenEnabled: (value) => calls.push(['sharpen', value]),
|
||||
_applyDetectionPreset: (value) => calls.push(['detection', value]),
|
||||
_syncShareState: () => calls.push(['share', variant]),
|
||||
});
|
||||
for (const name of [
|
||||
'setCelestialRingEnabled',
|
||||
'_startTransition',
|
||||
'_publishActiveStyle',
|
||||
'_updateSliderPanel',
|
||||
'_updateHudButtonState',
|
||||
'_syncIrBoost',
|
||||
'_syncCockpitInheritedStyle',
|
||||
'_syncCyberSonarControl',
|
||||
'_scheduleAdaptivePanelLayout',
|
||||
'_setDetectionFade',
|
||||
// Intensities: the fixture has no post-process stages to drive.
|
||||
'_setBloomIntensity',
|
||||
'_setSharpenIntensity',
|
||||
])
|
||||
owner[name] = () => {};
|
||||
return { owner, hud, root, calls };
|
||||
}
|
||||
|
||||
test('Tactical and Minimal are the HUD layouts; Cyber is only a Sonar alias', () => {
|
||||
assert.deepEqual(HUD_LAYOUTS, ['tactical', 'minimal']);
|
||||
assert.deepEqual(LEGACY_SONAR_HUD_LAYOUTS, ['cyber']);
|
||||
assert.equal(normalizeHudLayout('cyber'), 'tactical');
|
||||
assert.equal(normalizeHudLayout('CYBER'), 'tactical');
|
||||
assert.equal(normalizeHudLayout('operator'), 'tactical');
|
||||
assert.equal(normalizeHudLayout('Minimal'), 'minimal');
|
||||
assert.equal(isLegacySonarHudLayout('Cyber'), true);
|
||||
assert.equal(isLegacySonarHudLayout('operator'), false);
|
||||
assert.equal(isLegacySonarHudLayout('tactical'), false);
|
||||
});
|
||||
|
||||
test('a share link, scene or saved view naming Cyber opens Tactical with Sonar on', async (t) => {
|
||||
const { owner, hud, root, calls } = styleOwner(t, 'minimal');
|
||||
assert.equal(isCyberSonarEnabled(root), false);
|
||||
await owner.restoreShareState({ hudVariant: 'cyber' });
|
||||
assert.equal(hud.getVariant(), 'tactical');
|
||||
assert.equal(root.dataset.cyberSonar, 'on');
|
||||
assert.equal(root.dataset.uiTheme, undefined);
|
||||
// Turning it on asks for a frame, so a parked map starts the sweep.
|
||||
assert.ok(
|
||||
calls.some(
|
||||
([name, reason]) => name === 'render' && reason === 'cyber-sonar-toggle',
|
||||
),
|
||||
);
|
||||
// The viewer's own layout choice afterwards leaves the Sonar style alone.
|
||||
owner._setHudVariant('minimal');
|
||||
assert.equal(hud.getVariant(), 'minimal');
|
||||
assert.equal(isCyberSonarEnabled(root), true);
|
||||
// A restored state is authoritative: one that does not name Cyber turns
|
||||
// Sonar off, whether from a link or a scene shot.
|
||||
await owner.restoreShareState({ hudVariant: 'tactical' });
|
||||
assert.equal(isCyberSonarEnabled(root), false);
|
||||
setCyberSonarEnabled(true, root);
|
||||
await owner.applyVisualState({ hud: { variant: 'minimal' } });
|
||||
assert.equal(hud.getVariant(), 'minimal');
|
||||
assert.equal(isCyberSonarEnabled(root), false);
|
||||
await owner.applyVisualState({ hud: { variant: 'cyber' } });
|
||||
assert.equal(hud.getVariant(), 'tactical');
|
||||
assert.equal(isCyberSonarEnabled(root), true);
|
||||
});
|
||||
|
||||
/** A styleOwner that can also read its share state and scene shot. */
|
||||
function sharingOwner(t, initialVariant) {
|
||||
const fixture = styleOwner(t, initialVariant);
|
||||
Object.assign(fixture.owner.services, {
|
||||
getDetectionTuning: () => ({ allocationStrategy: 'ELASTIC' }),
|
||||
getDetectionMode: () => 'OFF',
|
||||
isScopeMaskEnabled: () => true,
|
||||
getScopeMaskFeather: () => 1,
|
||||
getScopeMaskOpacity: () => 1,
|
||||
getScopeTerminusOverride: () => null,
|
||||
});
|
||||
fixture.owner.readCelestialRing = () => null;
|
||||
return fixture;
|
||||
}
|
||||
|
||||
test('links and scene shots record Tactical with Sonar as the Cyber code, and only that', (t) => {
|
||||
const { owner, root } = sharingOwner(t, 'tactical');
|
||||
const shared = () => {
|
||||
const { hudVariant, hudSonar } = owner._readShareState().options;
|
||||
return [hudVariant, hudSonar];
|
||||
};
|
||||
const shot = () => owner.getVisualState().hud;
|
||||
assert.deepEqual(shared(), ['tactical', false]);
|
||||
assert.deepEqual(shot(), { visible: true, variant: 'tactical' });
|
||||
owner._setCyberSonarEnabled(true);
|
||||
// Tactical with Sonar is the Cyber code alone, as older readers expect.
|
||||
assert.deepEqual(shared(), ['cyber', false]);
|
||||
assert.deepEqual(shot(), { visible: true, variant: 'cyber' });
|
||||
// Minimal has no such code, so Sonar is carried beside it.
|
||||
owner._setHudVariant('minimal');
|
||||
assert.deepEqual(shared(), ['minimal', true]);
|
||||
assert.deepEqual(shot(), { visible: true, variant: 'minimal', sonar: true });
|
||||
owner._setCyberSonarEnabled(false);
|
||||
assert.deepEqual(shared(), ['minimal', false]);
|
||||
assert.deepEqual(shot(), { visible: true, variant: 'minimal' });
|
||||
owner._setHudVariant('tactical');
|
||||
assert.deepEqual(shared(), ['tactical', false]);
|
||||
assert.equal(isCyberSonarEnabled(root), false);
|
||||
});
|
||||
|
||||
test('Minimal with Sonar round-trips through a compact link and a scene shot', async (t) => {
|
||||
const { owner, hud, root } = sharingOwner(t, 'minimal');
|
||||
owner._setCyberSonarEnabled(true);
|
||||
const options = owner._readShareState().options;
|
||||
const shot = normalizeShot(
|
||||
JSON.parse(JSON.stringify({ visual: owner.getVisualState() })),
|
||||
);
|
||||
validateSceneDocument({
|
||||
version: SCENE_DOCUMENT_VERSION,
|
||||
scenes: [{ id: 'scene', title: 'Scene', shots: [shot] }],
|
||||
});
|
||||
const code = encodeShareView({
|
||||
hudVariant: options.hudVariant,
|
||||
hudSonar: options.hudSonar,
|
||||
});
|
||||
const link = decodeShareView(code, { nowMs: Date.now() }).state;
|
||||
|
||||
// The viewer is elsewhere: Tactical, Sonar off.
|
||||
owner._setHudVariant('tactical');
|
||||
owner._setCyberSonarEnabled(false);
|
||||
// The HUD fields of the parsed link (the fixture drives no detection).
|
||||
const { hudVariant, hudSonar } = toLegacyShareState(link);
|
||||
assert.deepEqual([hudVariant, hudSonar], ['minimal', true]);
|
||||
await owner.restoreShareState({ hudVariant, hudSonar });
|
||||
assert.equal(hud.getVariant(), 'minimal');
|
||||
assert.equal(isCyberSonarEnabled(root), true);
|
||||
|
||||
owner._setHudVariant('tactical');
|
||||
owner._setCyberSonarEnabled(false);
|
||||
// The saved shot's HUD, as the editor normalized and validated it.
|
||||
assert.deepEqual(shot.visual.hud, {
|
||||
visible: true,
|
||||
variant: 'minimal',
|
||||
sonar: true,
|
||||
});
|
||||
await owner.applyVisualState({ hud: shot.visual.hud });
|
||||
assert.equal(hud.getVariant(), 'minimal');
|
||||
assert.equal(isCyberSonarEnabled(root), true);
|
||||
});
|
||||
|
||||
test('a link or scene shot that does not mention Sonar restores as before', async (t) => {
|
||||
const { owner, hud, root } = sharingOwner(t, 'minimal');
|
||||
// Made before Sonar was carried: Minimal turns the viewer's Sonar off...
|
||||
setCyberSonarEnabled(true, root);
|
||||
await owner.restoreShareState({ hudVariant: 'minimal' });
|
||||
assert.equal(isCyberSonarEnabled(root), false);
|
||||
setCyberSonarEnabled(true, root);
|
||||
await owner.applyVisualState({ hud: { variant: 'minimal' } });
|
||||
assert.equal(isCyberSonarEnabled(root), false);
|
||||
// ...and Cyber still opens Tactical with Sonar on.
|
||||
await owner.restoreShareState({ hudVariant: 'cyber', hudSonar: false });
|
||||
assert.equal(hud.getVariant(), 'tactical');
|
||||
assert.equal(isCyberSonarEnabled(root), true);
|
||||
owner._setCyberSonarEnabled(false);
|
||||
await owner.applyVisualState({ hud: { variant: 'cyber' } });
|
||||
assert.equal(isCyberSonarEnabled(root), true);
|
||||
// Sonar beside a layout counts only in a restore, not a layout choice.
|
||||
owner._setCyberSonarEnabled(false);
|
||||
owner._setHudVariant('minimal', { sonar: true });
|
||||
assert.equal(isCyberSonarEnabled(root), false);
|
||||
});
|
||||
|
||||
test('Sonar is opt-in and gated on its toggle, the HUD, Cockpit and motion, not a theme', () => {
|
||||
const classes = new Set();
|
||||
const root = { dataset: {} };
|
||||
const body = { classList: { contains: (name) => classes.has(name) } };
|
||||
const gate = (extra = {}) => ({
|
||||
root,
|
||||
body,
|
||||
hudActive: true,
|
||||
reducedMotion: false,
|
||||
...extra,
|
||||
});
|
||||
assert.equal(isCyberSonarEnabled(root), false);
|
||||
assert.equal(isCyberSonarActive(gate()), false);
|
||||
assert.equal(isCyberMapThemeActive(gate()), false);
|
||||
// The removed Cyber theme attribute no longer enables anything.
|
||||
root.dataset.uiTheme = 'cyber';
|
||||
assert.equal(isCyberSonarActive(gate()), false);
|
||||
delete root.dataset.uiTheme;
|
||||
|
||||
assert.equal(setCyberSonarEnabled(true, root), true);
|
||||
assert.equal(root.dataset.cyberSonar, 'on');
|
||||
assert.equal(isCyberSonarActive(gate()), true);
|
||||
assert.equal(isCyberMapThemeActive(gate()), true);
|
||||
assert.equal(isCyberSonarActive(gate({ hudActive: false })), false);
|
||||
assert.equal(isCyberMapThemeActive(gate({ hudActive: false })), false);
|
||||
// Reduced motion keeps the static treatment and stops the sweep.
|
||||
assert.equal(isCyberSonarActive(gate({ reducedMotion: true })), false);
|
||||
assert.equal(isCyberMapThemeActive(gate({ reducedMotion: true })), true);
|
||||
classes.add('cockpit-mode');
|
||||
assert.equal(isCyberSonarActive(gate()), false);
|
||||
assert.equal(isCyberMapThemeActive(gate()), false);
|
||||
classes.delete('cockpit-mode');
|
||||
|
||||
assert.equal(setCyberSonarEnabled(false, root), false);
|
||||
assert.equal(root.dataset.cyberSonar, 'off');
|
||||
assert.equal(isCyberSonarActive(gate()), false);
|
||||
assert.equal(isCyberMapThemeActive(gate()), false);
|
||||
});
|
||||
|
||||
test('Sonar controls apply under Tactical and Minimal and still validate input', () => {
|
||||
for (const layout of ['tactical', 'minimal']) {
|
||||
const root = { dataset: {} };
|
||||
const doc = {
|
||||
documentElement: root,
|
||||
body: { classList: { contains: () => false } },
|
||||
getElementById: () => null,
|
||||
};
|
||||
const calls = [];
|
||||
const owner = {
|
||||
hud: { getVariant: () => layout, visible: true },
|
||||
_setCyberSonarSetting: (name, value) => calls.push([name, value]),
|
||||
_setCyberSonarEnabled: (value) => {
|
||||
calls.push(['enabled', value]);
|
||||
setCyberSonarEnabled(value, root);
|
||||
},
|
||||
};
|
||||
const applied = setCyberSonarControls(
|
||||
owner,
|
||||
{ enabled: true, rings: 6, sectorDeg: 30 },
|
||||
doc,
|
||||
);
|
||||
assert.equal(applied.ok, true, layout);
|
||||
assert.equal(applied.sonar.enabled, true);
|
||||
assert.equal('cyberSelected' in applied.sonar, false);
|
||||
assert.deepEqual(calls, [
|
||||
['rings', 6],
|
||||
['sector', 30],
|
||||
['enabled', true],
|
||||
]);
|
||||
assert.equal(
|
||||
setCyberSonarControls(owner, { enabled: 'yes' }, doc).error,
|
||||
'enabled must be a boolean.',
|
||||
);
|
||||
assert.equal(
|
||||
setCyberSonarControls(owner, { pulse: 3 }, doc).error,
|
||||
'Unknown sonar setting.',
|
||||
);
|
||||
assert.equal(
|
||||
setCyberSonarControls(owner, { rings: 13 }, doc).error,
|
||||
'rings must be an integer from 3 to 12.',
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('Display and voice HUD routes offer Tactical and Minimal, and Cyber turns Sonar on', async (t) => {
|
||||
const makeOwner = () => {
|
||||
const { owner, hud, root } = styleOwner(t, 'tactical');
|
||||
owner.setStyle('noir');
|
||||
owner.setHudLayout = (...args) =>
|
||||
StyleManager.prototype.setHudLayout.call(owner, ...args);
|
||||
owner.getControlState = () => ({
|
||||
hud: { layout: hud.getVariant(), visible: true },
|
||||
});
|
||||
return { owner, hud, root };
|
||||
};
|
||||
|
||||
const display = makeOwner();
|
||||
const store = useDisplayStore(createPinia());
|
||||
const token = store.connect({
|
||||
setHudLayout: (value) => display.owner.setHudLayout(value),
|
||||
setStyle: (value) => display.owner.setStyle(value),
|
||||
});
|
||||
store.act('setHudLayout', 'minimal');
|
||||
assert.equal(display.hud.getVariant(), 'minimal');
|
||||
// Switching layouts never changes the visual preset.
|
||||
assert.equal(display.owner.activeStyle, 'noir');
|
||||
store.act('setStyle', 'anime');
|
||||
assert.equal(display.owner.activeStyle, 'anime');
|
||||
store.detach(token);
|
||||
|
||||
const setHud = GEV_ACTION_SCHEMAS.find((tool) => tool.name === 'set_hud');
|
||||
assert.deepEqual(setHud.parameters.properties.layout.enum, HUD_LAYOUTS);
|
||||
|
||||
const voice = makeOwner();
|
||||
const eventSource = { addEventListener() {}, removeEventListener() {} };
|
||||
const viewer = {
|
||||
camera: { moveEnd: { addEventListener() {} } },
|
||||
clock: { onTick: { addEventListener: () => () => {} } },
|
||||
canvas: eventSource,
|
||||
scene: { canvas: eventSource },
|
||||
};
|
||||
const runVoiceAction = createGevActionRunner({
|
||||
viewer,
|
||||
styleManager: voice.owner,
|
||||
dataManager: {},
|
||||
});
|
||||
const minimal = await runVoiceAction('set_hud', { layout: 'minimal' });
|
||||
assert.equal(minimal.ok, true);
|
||||
assert.equal(voice.hud.getVariant(), 'minimal');
|
||||
assert.equal(isCyberSonarEnabled(voice.root), false);
|
||||
const legacy = await runVoiceAction('set_hud', { layout: 'cyber' });
|
||||
assert.equal(legacy.ok, true);
|
||||
assert.equal(legacy.layout, 'tactical');
|
||||
assert.equal(voice.hud.getVariant(), 'tactical');
|
||||
assert.equal(isCyberSonarEnabled(voice.root), true);
|
||||
assert.equal(voice.owner.activeStyle, 'noir');
|
||||
const unknown = await runVoiceAction('set_hud', { layout: 'operator' });
|
||||
assert.equal(unknown.ok, false);
|
||||
});
|
||||
|
||||
test('style presets keep their own HUD layout and never touch Sonar', (t) => {
|
||||
const { owner, hud, root } = styleOwner(t);
|
||||
setCyberSonarEnabled(true, root);
|
||||
for (const variant of ['tactical', 'minimal']) {
|
||||
owner._setHudVariant(variant);
|
||||
assert.equal(hud.getVariant(), variant);
|
||||
owner.setStyle('normal');
|
||||
owner.setStyle('surveillance');
|
||||
assert.equal(hud.getVariant(), 'tactical');
|
||||
assert.equal(isCyberSonarEnabled(root), true);
|
||||
}
|
||||
});
|
||||
|
||||
test('the Display panel offers Sonar as an opt-in toggle under the HUD layout', () => {
|
||||
const view = read('./views/panels/DisplayPanel.vue');
|
||||
assert.doesNotMatch(view, /value="cyber"/);
|
||||
assert.match(view, /<option value="tactical">/);
|
||||
assert.match(view, /<option value="minimal">/);
|
||||
assert.match(
|
||||
view,
|
||||
/const sonarOn = computed\(\(\) => sonar\.value\?\.enabled \?\? false\);/,
|
||||
);
|
||||
// The toggle shows with the HUD; its sliders only once Sonar is on.
|
||||
assert.match(
|
||||
view,
|
||||
/cyber-sonar-toggle-row" :class="\{ visible: hud\?\.visible \}" id="cyber-sonar-row"/,
|
||||
);
|
||||
assert.equal(
|
||||
view.match(
|
||||
/cyber-sonar-setting" :class="\{ visible: hud\?\.visible && sonarOn \}"/g,
|
||||
)?.length,
|
||||
5,
|
||||
);
|
||||
assert.match(view, /:aria-label="t\('Sonar contact scanner'\)"/);
|
||||
// Its renderer status speaks only for a Sonar the viewer turned on.
|
||||
assert.match(
|
||||
view,
|
||||
/<output id="cyber-sonar-status"[^>]*:hidden="!\(hud\?\.visible && sonarOn\)"/,
|
||||
);
|
||||
assert.doesNotMatch(view, /t\('Cyber/);
|
||||
});
|
||||
|
||||
test('stylesheets carry no Cyber theme and show the sweep only while Sonar is on', () => {
|
||||
const entry = readFileSync(
|
||||
new URL('../../style.css', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
assert.match(entry, /@import '\.\/src\/ui\/styles\/sonar\.css';/);
|
||||
assert.doesNotMatch(entry, /cyber\.css/);
|
||||
const dir = new URL('./styles/', import.meta.url);
|
||||
for (const name of readdirSync(dir).filter((file) => file.endsWith('.css')))
|
||||
assert.doesNotMatch(
|
||||
readFileSync(new URL(name, dir), 'utf8'),
|
||||
/data-ui-theme/,
|
||||
name,
|
||||
);
|
||||
|
||||
const sonar = read('./styles/sonar.css');
|
||||
assert.match(cssRuleBody(sonar, /\n\.hud-sonar/), /display: none;/);
|
||||
assert.match(
|
||||
cssRuleBody(
|
||||
sonar,
|
||||
/\n:root\[data-cyber-sonar='on'\] #intel-hud \.hud-sonar/,
|
||||
),
|
||||
/display: block;/,
|
||||
);
|
||||
// Cockpit and a hidden HUD keep no sweep, not even an invisible one.
|
||||
assert.match(
|
||||
cssRuleBody(
|
||||
sonar,
|
||||
/:root\[data-cyber-sonar='on'\] body\.cockpit-mode #intel-hud \.hud-sonar,\s*:root\[data-cyber-sonar='on'\] #intel-hud:not\(\.active\) \.hud-sonar/,
|
||||
),
|
||||
/display: none;/,
|
||||
);
|
||||
assert.match(
|
||||
sonar,
|
||||
/@media \(prefers-reduced-motion: reduce\)\s*\{\s*:root\[data-cyber-sonar='on'\] #intel-hud \.hud-sonar::after\s*\{\s*display: none;\s*animation: none;/,
|
||||
);
|
||||
// The Vue bindings own the Sonar rows' visibility now.
|
||||
const controls = read('./styles/controls.css');
|
||||
assert.doesNotMatch(controls, /\.cyber-sonar-control\s*\{\s*display: none/);
|
||||
assert.doesNotMatch(controls, /data-cyber-sonar='off'/);
|
||||
});
|
||||
|
||||
test('the desktop bottom row: credits on the Power Up baseline, the dock lifted, the corners level', () => {
|
||||
const rem = 16;
|
||||
const lift = 'var\\(--world-timeline-lift, 0px\\)';
|
||||
const value = (text, pattern) => {
|
||||
const match = text.match(pattern);
|
||||
assert.ok(match, pattern.source);
|
||||
return Number(match[1]);
|
||||
};
|
||||
const block = (text, header) => {
|
||||
const start = text.indexOf(header);
|
||||
assert.ok(start >= 0, header);
|
||||
let depth = 0;
|
||||
for (let i = text.indexOf('{', start); i < text.length; i += 1) {
|
||||
if (text[i] === '{') depth += 1;
|
||||
else if (text[i] === '}' && --depth === 0)
|
||||
return text.slice(start, i + 1);
|
||||
}
|
||||
assert.fail(`unclosed ${header}`);
|
||||
};
|
||||
// Measured constants: the Power Up / language row is 32px tall, 14px up
|
||||
// and about 20rem wide in English; the attribution logo line is 28px; the
|
||||
// single-row dock is 62px; the bottom-right readout is one 26px line
|
||||
// taller than the coordinates.
|
||||
const POWER_UP = { bottom: 14, height: 32 };
|
||||
const CREDIT_HEIGHT = 28;
|
||||
const DOCK_HEIGHT = 62;
|
||||
const timeline = read('./styles/world-timeline.css');
|
||||
const timelineLift = value(
|
||||
timeline,
|
||||
/body:has\(#world-timeline\) \{\s*--world-timeline-lift: (\d+)px;/,
|
||||
);
|
||||
|
||||
// From 1200px the dock and the World Timeline leave the bottom 74px; below
|
||||
// it they return to the bottom edge, where the dock spans the corners.
|
||||
const dock = read('./styles/command-dock.css');
|
||||
const dockFloor = value(
|
||||
dock,
|
||||
new RegExp(
|
||||
`\\n#command-dock \\{[^}]*bottom: calc\\((\\d+)px \\+ ${lift}\\)`,
|
||||
),
|
||||
);
|
||||
assert.match(
|
||||
block(dock, '@media (max-width: 1199px)'),
|
||||
new RegExp(`#command-dock \\{\\s*bottom: calc\\(2vh \\+ ${lift}\\);`),
|
||||
);
|
||||
assert.equal(
|
||||
value(timeline, /\n#world-timeline \{[^}]*bottom: (\d+)px;/),
|
||||
dockFloor,
|
||||
);
|
||||
assert.match(
|
||||
block(timeline, '@media (max-width: 1199px)'),
|
||||
/#world-timeline \{\s*bottom: 2vh;/,
|
||||
);
|
||||
assert.ok(dockFloor >= POWER_UP.bottom + POWER_UP.height + 8);
|
||||
|
||||
// Both credit renderers share Power Up's row, centred on it, below the
|
||||
// dock, and stop short of the corner row instead of running under it:
|
||||
// GEV's own line on its anchor, Cesium's on the absolutely placed box it
|
||||
// draws inside its empty anchor.
|
||||
const trays = read('./styles/command-dock-trays.css');
|
||||
const trayWide = block(trays, '@media (min-width: 1200px)');
|
||||
const caps = {
|
||||
'gev-credits': trays.match(
|
||||
/#gev-credits \{\s*right: auto;\s*bottom: ([\d.]+)rem;\s*left: 1\.5rem;\s*width: max-content !important;\s*max-width: calc\(100vw - 1\.5rem - ([\d.]+)rem\);\s*white-space: normal;/,
|
||||
),
|
||||
'cesium-credits': (() => {
|
||||
const anchor = trays.match(
|
||||
/#cesium-credits \{\s*right: auto;\s*bottom: ([\d.]+)rem;\s*left: 1\.5rem;/,
|
||||
);
|
||||
// From 1200px, and in the Omnibar layout at every width: a long line
|
||||
// wraps rather than running under the corner row.
|
||||
const box = trayWide.match(
|
||||
/\n\s*#cesium-credits \.cesium-widget-credits \{\s*width: max-content;\s*max-width: calc\(100vw - 1\.5rem - ([\d.]+)rem\);\s*white-space: normal;/,
|
||||
);
|
||||
assert.match(
|
||||
trays,
|
||||
/:has\(#command-dock > #gev-voice-control\)\s*\)\s*#cesium-credits\s*\.cesium-widget-credits \{\s*width: max-content;\s*max-width: calc\(100vw - 1\.5rem - 26rem\);/,
|
||||
);
|
||||
return anchor && box && [null, anchor[1], box[1]];
|
||||
})(),
|
||||
};
|
||||
for (const [id, match] of Object.entries(caps)) {
|
||||
assert.ok(match, id);
|
||||
const creditsBottom = Number(match[1]) * rem;
|
||||
assert.equal(
|
||||
creditsBottom + CREDIT_HEIGHT / 2,
|
||||
POWER_UP.bottom + POWER_UP.height / 2,
|
||||
);
|
||||
assert.ok(creditsBottom + CREDIT_HEIGHT + 8 <= dockFloor);
|
||||
assert.ok(Number(match[2]) >= 20 + 1.5, `${id} leaves the corner row room`);
|
||||
}
|
||||
// Below 1200px the row returns above the bottom-edge dock, on one line.
|
||||
const narrow = block(trays, '@media (max-width: 1199px)');
|
||||
for (const id of ['cesium-credits', 'gev-credits'])
|
||||
assert.match(narrow, new RegExp(`#${id}[,\\s]`));
|
||||
assert.match(
|
||||
narrow,
|
||||
new RegExp(
|
||||
`\\{\\s*bottom: calc\\(2vh \\+ 5rem \\+ ${lift}\\);\\s*width: auto !important;\\s*max-width: calc\\(100vw - 3rem\\);\\s*white-space: nowrap;`,
|
||||
),
|
||||
);
|
||||
// Right to left the corner row is at the bottom left, so the row moves
|
||||
// right, with the Minimal HUD too (its placement names #intel-hud).
|
||||
assert.match(
|
||||
trayWide,
|
||||
/html\[dir='rtl'\]\s*body:not\(\.context-docked\):not\(\.ui-clean-view\):not\(\.recording-mode\)\s*:is\(#cesium-credits, #gev-credits\),\s*html\[dir='rtl'\]\s*body:not\(\.context-docked\):not\(\.ui-clean-view\):not\(\.recording-mode\):has\(\s*#intel-hud\[data-variant='minimal'\]\.active\s*\)\s*:is\(#cesium-credits, #gev-credits\) \{\s*right: 1\.5rem;\s*left: auto;/,
|
||||
);
|
||||
// Its box hangs from the anchor's right edge there, and in the Omnibar
|
||||
// layout at every width; never in clean view or recording, where the
|
||||
// anchor stays on the left.
|
||||
assert.match(
|
||||
trayWide,
|
||||
/body:not\(\.context-docked\):not\(\.ui-clean-view\):not\(\.recording-mode\)\s*#cesium-credits\s*\.cesium-widget-credits \{\s*right: 0;\s*left: auto;/,
|
||||
);
|
||||
assert.match(
|
||||
trays,
|
||||
/html\[dir='rtl'\]\s*body:not\(\.mobile-shell\)[^{]*:not\(\.recording-mode\):not\(\.context-docked\)[^{]*#cesium-credits\s*\.cesium-widget-credits \{\s*right: 0;\s*left: auto;/,
|
||||
);
|
||||
// There the readout clears the row under it, however many lines it wraps
|
||||
// onto (--credit-line-height).
|
||||
assert.match(
|
||||
read('./styles/omnibar-dock.css'),
|
||||
/html\[dir='rtl'\] \*\):not\(\.context-docked\)\s*#intel-hud\[data-variant='tactical'\]\s*\.hud-bottom-right \{\s*bottom: max\(3\.375rem, var\(--omnibar-credits-clear\)\);/,
|
||||
);
|
||||
const locale = read('./styles/locale-picker.css');
|
||||
assert.match(locale, /#corner-actions \{[^}]*inset-inline-end: 0\.9rem;/);
|
||||
|
||||
// From 1200px the readout keeps 8px above Power Up and the coordinates
|
||||
// start level with it. The World Timeline sits between the corners, so they
|
||||
// do not move while it shows.
|
||||
const split = read('./styles/rail-split.css');
|
||||
const wide = block(split, '@media (min-width: 1200px)');
|
||||
const readoutWide =
|
||||
value(
|
||||
wide,
|
||||
/\n #intel-hud\[data-variant='tactical'\] \.hud-bottom-right \{\s*bottom: ([\d.]+)rem;/,
|
||||
) * rem;
|
||||
assert.equal(readoutWide, POWER_UP.bottom + POWER_UP.height + 8);
|
||||
assert.equal(
|
||||
value(wide, /\.hud-bottom-left \{\s*bottom: calc\(([\d.]+)rem \+ 26px\);/) *
|
||||
rem,
|
||||
readoutWide,
|
||||
);
|
||||
assert.doesNotMatch(
|
||||
wide,
|
||||
/hud-bottom-(left|right) \{[^}]*world-timeline-lift/,
|
||||
);
|
||||
// Corners: coordinates ~302px from 36px, readout ~292px to 36px from the
|
||||
// right edge; the bar keeps 12px from each at every width from 1200px.
|
||||
const gutter =
|
||||
value(
|
||||
wide,
|
||||
/#world-timeline \{\s*width: min\(820px, calc\(100vw - ([\d.]+)rem\)\);/,
|
||||
) * rem;
|
||||
assert.ok(gutter / 2 >= 36 + 302 + 12);
|
||||
assert.ok(timelineLift > 0);
|
||||
// Toasts keep 12px above the raised dock.
|
||||
assert.equal(
|
||||
value(
|
||||
wide,
|
||||
new RegExp(`#toast \\{\\s*bottom: calc\\((\\d+)px \\+ ${lift}\\);`),
|
||||
),
|
||||
dockFloor + DOCK_HEIGHT + 12,
|
||||
);
|
||||
// The dock's panels lose the dock's rise from their height budgets.
|
||||
assert.match(
|
||||
wide,
|
||||
/\.gev-voice-panel \{[^}]*calc\(100dvh - 12rem - 74px \+ 2vh - var\(--gev-provider-lift, 0px\)\)/,
|
||||
);
|
||||
assert.match(
|
||||
block(read('./styles/ai-chat.css'), '@media (min-width: 1200px)'),
|
||||
/#gev-chat-panel \{\s*max-height: min\(34rem, calc\(100dvh - 10rem - 74px \+ 2vh\)\);/,
|
||||
);
|
||||
|
||||
// Below 1200px the corners keep the committed layout: the coordinates clear
|
||||
// the raised credit row's logo line by 6px.
|
||||
assert.ok(
|
||||
value(
|
||||
trays.slice(
|
||||
trays.indexOf(
|
||||
'/* The coordinate readout shares the bottom-left corner',
|
||||
),
|
||||
),
|
||||
new RegExp(
|
||||
`\\.hud-bottom-left \\{\\s*bottom: calc\\(2vh \\+ ([\\d.]+)rem \\+ ${lift}\\);`,
|
||||
),
|
||||
) *
|
||||
rem >=
|
||||
5 * rem + CREDIT_HEIGHT + 6,
|
||||
);
|
||||
// The desktop Omnibar layout outranks these rules; its readout keeps the
|
||||
// same 8px above Power Up.
|
||||
const omnibarReadout = value(
|
||||
read('./styles/omnibar-dock.css'),
|
||||
/#intel-hud\[data-variant='tactical'\] \.hud-bottom-right \{\s*bottom: ([\d.]+)rem;/,
|
||||
);
|
||||
assert.equal(omnibarReadout * rem, POWER_UP.bottom + POWER_UP.height + 8);
|
||||
});
|
||||
|
||||
test('scope choice and expanded feather survive every HUD layout and both restore paths', async (t) => {
|
||||
const { owner } = styleOwner(t, 'tactical');
|
||||
const previous = {
|
||||
enabled: isScopeMaskEnabled(),
|
||||
feather: getScopeMaskFeather(),
|
||||
};
|
||||
t.after(() => {
|
||||
setScopeMaskEnabled(previous.enabled);
|
||||
setScopeMaskFeather(previous.feather);
|
||||
});
|
||||
Object.assign(owner.services, { setScopeMaskEnabled, setScopeMaskFeather });
|
||||
let shown = null;
|
||||
owner.store = { publish: (view) => (shown = view.scope) };
|
||||
await owner.restoreShareState({ scopeEnabled: false, scopeFeatherPct: 200 });
|
||||
assert.deepEqual(shown, { enabled: false, featherPct: 200, opacityPct: 100 });
|
||||
for (const layout of ['minimal', 'cyber', 'tactical']) {
|
||||
owner._setHudVariant(layout);
|
||||
assert.equal(isScopeMaskEnabled(), false, layout);
|
||||
assert.equal(getScopeMaskFeather(), 2, layout);
|
||||
assert.equal(shown.enabled, false, layout);
|
||||
}
|
||||
await owner.applyVisualState({ scope: { enabled: true, featherPct: 175 } });
|
||||
assert.equal(isScopeMaskEnabled(), true);
|
||||
assert.equal(getScopeMaskFeather(), 1.75);
|
||||
assert.deepEqual(shown, { enabled: true, featherPct: 175, opacityPct: 100 });
|
||||
await owner.applyVisualState({ scope: { featherPct: 500 } });
|
||||
assert.equal(getScopeMaskFeather(), 2);
|
||||
assert.deepEqual(shown, { enabled: true, featherPct: 200, opacityPct: 100 });
|
||||
});
|
||||
|
||||
test('a shared scope opacity is restored and rides in the next share state', async (t) => {
|
||||
const { owner } = styleOwner(t, 'tactical');
|
||||
const previous = getScopeMaskOpacity();
|
||||
t.after(() => setScopeMaskOpacity(previous));
|
||||
Object.assign(owner.services, {
|
||||
setScopeMaskEnabled() {},
|
||||
setScopeMaskFeather() {},
|
||||
setScopeMaskOpacity,
|
||||
});
|
||||
let shown = null;
|
||||
owner.store = { publish: (view) => (shown = view.scope) };
|
||||
await owner.restoreShareState({ scopeOpacityPct: 60 });
|
||||
assert.equal(getScopeMaskOpacity(), 0.6);
|
||||
assert.equal(shown.opacityPct, 60);
|
||||
// A state without it leaves the opacity alone.
|
||||
await owner.restoreShareState({ scopeFeatherPct: 80 });
|
||||
assert.equal(getScopeMaskOpacity(), 0.6);
|
||||
assert.equal(shown.opacityPct, 60);
|
||||
Object.assign(owner.services, {
|
||||
getDetectionTuning: () => ({ allocationStrategy: 'ELASTIC' }),
|
||||
getDetectionMode: () => 'OFF',
|
||||
isScopeMaskEnabled: () => true,
|
||||
getScopeMaskFeather: () => 0.8,
|
||||
getScopeMaskOpacity,
|
||||
getScopeTerminusOverride: () => null,
|
||||
});
|
||||
owner.readCelestialRing = () => null;
|
||||
assert.equal(owner._readShareState().options.scopeOpacityPct, 60);
|
||||
// A link asking for less than the floor opens at the floor, and says so.
|
||||
await owner.restoreShareState({ scopeOpacityPct: 20 });
|
||||
assert.equal(getScopeMaskOpacity(), 0.5);
|
||||
assert.equal(owner._readShareState().options.scopeOpacityPct, 50);
|
||||
});
|
||||
|
||||
test('a scene shot saved with the retired Snow style plays on Normal', async (t) => {
|
||||
const { owner } = styleOwner(t, 'tactical');
|
||||
owner.setStyle('noir');
|
||||
await owner.applyVisualState({ style: 'snow' });
|
||||
assert.equal(owner.activeStyle, 'normal');
|
||||
});
|
||||
|
||||
test('shared panel hooks affect only opted-in rail surfaces without overriding disclosure and concealment', () => {
|
||||
const styles = read('./styles/panel-surfaces.css');
|
||||
const rail = cssRuleBody(
|
||||
styles,
|
||||
/:is\(#left-panel-stack, #right-context-rail\)\s+> \[data-panel-id\]:has\(> \[data-panel-surface\]\)/,
|
||||
);
|
||||
assert.match(rail, /pointer-events:\s*auto;/);
|
||||
assert.doesNotMatch(rail, /(?:display|visibility):/);
|
||||
assert.doesNotMatch(
|
||||
styles,
|
||||
/:is\(#left-panel-stack, #right-context-rail\)\s*> \[data-panel-id\]\s*\{/,
|
||||
);
|
||||
assert.match(
|
||||
styles,
|
||||
/\[data-panel-surface\]:not\(\[hidden\]\):not\(dialog:not\(\[open\]\)\)\s*\{\s*display: flex;/,
|
||||
);
|
||||
assert.match(
|
||||
styles,
|
||||
/dialog\[data-panel-surface\]:not\(\[open\]\)\s*\{\s*display: none !important;/,
|
||||
);
|
||||
assert.match(
|
||||
styles,
|
||||
/body:is\(\.ui-clean-view, \.recording-mode\)[^{]+\{[^}]*visibility: hidden !important;[^}]*pointer-events: none !important;/,
|
||||
);
|
||||
});
|
||||
|
||||
test('narrow Omnibar corners clear the World Timeline over the dock', () => {
|
||||
const css = read('./styles/omnibar-dock.css');
|
||||
const timeline = css.match(
|
||||
/#world-timeline \{\s*bottom: calc\(var\(--omnibar-dock-bottom\) \+ (\d+)px\);/,
|
||||
);
|
||||
const height = read('./styles/world-timeline.css').match(
|
||||
/#world-timeline \{[^}]*\n {2}height: (\d+)px;/,
|
||||
);
|
||||
const corners = css.match(
|
||||
/&:has\(#world-timeline\) \{\s*--omnibar-coordinates-bottom: max\(\s*calc\(var\(--omnibar-dock-bottom\) \+ (\d+)px \+ (\d+)px \+ (\d+)px\)/,
|
||||
);
|
||||
assert.ok(timeline && height && corners);
|
||||
assert.equal(Number(corners[1]), Number(timeline[1]));
|
||||
assert.equal(Number(corners[2]), Number(height[1]));
|
||||
assert.ok(Number(corners[3]) >= 6);
|
||||
});
|
||||
@@ -1,8 +1,10 @@
|
||||
<script setup>
|
||||
// Core's read-only badge, with a `tone` and the kit's classes. It carries Core's `gev-status-badge` class, and
|
||||
// callers add its density variants (`gev-status-badge--box`, `--plain`) and
|
||||
// the feature classes that colour it; the kit classes carry no Core styles
|
||||
// yet. Not mirrored yet: pulse, busy, the tone glyphs and the clipped title.
|
||||
// Core's read-only badge, with a `tone` and the kit's classes. `ui-badge`
|
||||
// wears Core's badge (status-badge.css) beside Core's `gev-status-badge`
|
||||
// class; callers add its density variants (`gev-status-badge--box`,
|
||||
// `--plain`) and the feature classes that colour it. The tone classes carry
|
||||
// no style yet. Not mirrored yet: pulse, busy, the tone glyphs and the
|
||||
// clipped title.
|
||||
defineProps({
|
||||
tone: { type: String, default: 'neutral' },
|
||||
});
|
||||
|
||||
@@ -100,3 +100,50 @@ test('server-rendered markup carries the pressed classes', async () => {
|
||||
assert.match(html, /<button[^>]*class="[^"]*\bactive\b[^"]*"/);
|
||||
assert.match(html, /aria-pressed="true"/);
|
||||
});
|
||||
|
||||
const LOOKS = [
|
||||
'ui-button--action',
|
||||
'ui-button--primary',
|
||||
'ui-button--icon',
|
||||
'ui-button--compact',
|
||||
];
|
||||
|
||||
test('a ghost button, the default, carries no look of the kit’s', () => {
|
||||
const wrapper = mountButton({}, { class: 'pp-toggle-btn' });
|
||||
const classes = wrapper.get('button').classes();
|
||||
assert.ok(classes.includes('ui-button--ghost'));
|
||||
for (const look of LOOKS) assert.equal(classes.includes(look), false, look);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
test('the variant, tone and size render their kit classes', async () => {
|
||||
const wrapper = mountButton({ variant: 'action', tone: 'danger' });
|
||||
const button = wrapper.get('button');
|
||||
assert.ok(button.classes().includes('ui-button--action'));
|
||||
assert.ok(button.classes().includes('ui-button--danger'));
|
||||
assert.equal(button.classes().includes('ui-button--compact'), false);
|
||||
await wrapper.setProps({ size: 'compact' });
|
||||
assert.ok(button.classes().includes('ui-button--compact'));
|
||||
for (const variant of ['primary', 'icon']) {
|
||||
await wrapper.setProps({ variant });
|
||||
assert.ok(button.classes().includes(`ui-button--${variant}`));
|
||||
assert.equal(button.classes().includes('ui-button--action'), false);
|
||||
}
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
test('a styled variant still presses', async () => {
|
||||
const wrapper = mountButton({
|
||||
variant: 'action',
|
||||
pressed: false,
|
||||
pressedClass: 'active',
|
||||
});
|
||||
const button = wrapper.get('button');
|
||||
assert.equal(button.attributes('aria-pressed'), 'false');
|
||||
await wrapper.setProps({ pressed: true });
|
||||
assert.equal(button.attributes('aria-pressed'), 'true');
|
||||
assert.ok(button.classes().includes('ui-button--pressed'));
|
||||
assert.ok(button.classes().includes('ui-button--action'));
|
||||
assert.ok(button.classes().includes('active'));
|
||||
wrapper.unmount();
|
||||
});
|
||||
+39
-6
@@ -4,9 +4,22 @@ import { vClassToggle } from '../rail/classToggle.js';
|
||||
|
||||
// Core's button and its attribute contract: the button is always the root,
|
||||
// attributes passed in win over its own (a `title` replaces the label's), and
|
||||
// `pressed` renders aria-pressed only when it is passed. Core styles the
|
||||
// button through the classes its callers pass; the kit classes carry no Core
|
||||
// styles yet. Core adds `pressedClass`, its class on a pressed button (most
|
||||
// `pressed` renders aria-pressed only when it is passed. The variant picks
|
||||
// the look:
|
||||
// - `ghost` (the default) carries no style; the caller's classes style it.
|
||||
// - `action` wears Core's action surface (action-button.css), with
|
||||
// `tone="danger"` for a red hover and `size="compact"` for the smaller
|
||||
// shot-row footprint.
|
||||
// - `primary` is that surface with the accent emphasis of a group's one main
|
||||
// action (action-button.css).
|
||||
// - `icon` is the 22px square glyph button of a panel's collapse toggle
|
||||
// (controls.css).
|
||||
// A pressed action, primary or icon button looks as a hovered regular one
|
||||
// does (a compact action's quieter hover is for an unpressed button); a
|
||||
// disabled one dims and ignores hover and press. `size` styles the action
|
||||
// variant only. Each
|
||||
// resting rule selects one kit class, so a feature class loaded later still
|
||||
// wins. Core adds `pressedClass`, its class on a pressed button (most
|
||||
// toggles use `active`). The pressed classes toggle through `classList`, so
|
||||
// classes other code adds to the button (a voice highlight) survive a press.
|
||||
// Not mirrored yet: icon, loading, disabledReason and the missing-label
|
||||
@@ -14,8 +27,24 @@ import { vClassToggle } from '../rail/classToggle.js';
|
||||
defineOptions({ inheritAttrs: false });
|
||||
|
||||
const props = defineProps({
|
||||
variant: { type: String, default: 'ghost' },
|
||||
tone: { type: String, default: 'accent' },
|
||||
variant: {
|
||||
type: String,
|
||||
default: 'ghost',
|
||||
validator: (value) =>
|
||||
['ghost', 'action', 'primary', 'icon'].includes(value),
|
||||
},
|
||||
/** `accent`, or `danger` for an action that destroys or stops. */
|
||||
tone: {
|
||||
type: String,
|
||||
default: 'accent',
|
||||
validator: (value) => ['accent', 'danger'].includes(value),
|
||||
},
|
||||
/** `compact` for an action's smaller footprint. */
|
||||
size: {
|
||||
type: String,
|
||||
default: 'regular',
|
||||
validator: (value) => ['regular', 'compact'].includes(value),
|
||||
},
|
||||
/** The accessible name (aria-label) and, with nativeTitle, the tip. */
|
||||
label: { type: String, default: undefined },
|
||||
pressed: { type: Boolean, default: undefined },
|
||||
@@ -53,7 +82,11 @@ const vPressedClasses = {
|
||||
:type="props.type"
|
||||
:form="props.form"
|
||||
class="ui-button ui-focus"
|
||||
:class="[`ui-button--${props.variant}`, `ui-button--${props.tone}`]"
|
||||
:class="[
|
||||
`ui-button--${props.variant}`,
|
||||
`ui-button--${props.tone}`,
|
||||
{ 'ui-button--compact': props.size === 'compact' },
|
||||
]"
|
||||
:aria-label="props.label"
|
||||
:title="props.nativeTitle ? props.label : undefined"
|
||||
:aria-pressed="
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
import { after, before, test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { installVueDom } from '../../testSupport/vueDom.mjs';
|
||||
|
||||
let mount;
|
||||
let nextTick;
|
||||
let UiCheckbox;
|
||||
let uninstall;
|
||||
before(async () => {
|
||||
uninstall = installVueDom();
|
||||
({ mount } = await import('@vue/test-utils'));
|
||||
({ nextTick } = await import('vue'));
|
||||
UiCheckbox = (await import('./UiCheckbox.vue')).default;
|
||||
});
|
||||
after(() => uninstall());
|
||||
|
||||
/** A checkbox whose v-model writes back into its props, as a parent's would. */
|
||||
function bound(props = {}, attrs = {}) {
|
||||
const wrapper = mount(UiCheckbox, {
|
||||
attachTo: document.body,
|
||||
props: {
|
||||
modelValue: false,
|
||||
...props,
|
||||
'onUpdate:modelValue': (value) => wrapper.setProps({ modelValue: value }),
|
||||
},
|
||||
attrs,
|
||||
slots: { default: '<span class="words">Scope</span>' },
|
||||
});
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
/** Tick the box as a person does: flip it, then the change event. */
|
||||
async function tick(input) {
|
||||
input.element.checked = !input.element.checked;
|
||||
await input.trigger('change');
|
||||
}
|
||||
|
||||
test('a checkbox is a label wrapping a native box, then its words', () => {
|
||||
const wrapper = bound();
|
||||
const root = wrapper.get('label');
|
||||
assert.ok(root.classes().includes('ui-checkbox'));
|
||||
const input = wrapper.get('input');
|
||||
assert.equal(input.attributes('type'), 'checkbox');
|
||||
assert.ok(input.classes().includes('ui-checkbox__input'));
|
||||
assert.equal(input.attributes('id'), undefined);
|
||||
const elements = [...root.element.children];
|
||||
assert.deepEqual(
|
||||
elements.map((el) => el.tagName),
|
||||
['INPUT', 'SPAN'],
|
||||
);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
test('trailing puts the box after its words', () => {
|
||||
const wrapper = bound({ trailing: true });
|
||||
assert.deepEqual(
|
||||
[...wrapper.get('label').element.children].map((el) => el.tagName),
|
||||
['SPAN', 'INPUT'],
|
||||
);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
test('attributes and classes go to the label; inputId and inputAttrs to the box', () => {
|
||||
const wrapper = bound(
|
||||
{
|
||||
inputId: 'scope-toggle',
|
||||
inputAttrs: { 'aria-describedby': 'note', 'data-hook': '' },
|
||||
},
|
||||
{ class: 'pp-scope-toggle', title: 'Scope', id: 'scope-row' },
|
||||
);
|
||||
const root = wrapper.get('label');
|
||||
assert.ok(root.classes().includes('pp-scope-toggle'));
|
||||
assert.equal(root.attributes('title'), 'Scope');
|
||||
assert.equal(root.attributes('id'), 'scope-row');
|
||||
const input = wrapper.get('input');
|
||||
assert.equal(input.attributes('id'), 'scope-toggle');
|
||||
assert.equal(input.attributes('aria-describedby'), 'note');
|
||||
assert.equal(input.attributes('data-hook'), '');
|
||||
assert.equal(input.attributes('title'), undefined);
|
||||
assert.ok(!input.classes().includes('pp-scope-toggle'));
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
test('v-model shows the value and reports each change', async () => {
|
||||
const wrapper = bound({ modelValue: true });
|
||||
const input = wrapper.get('input');
|
||||
assert.equal(input.element.checked, true);
|
||||
await tick(input);
|
||||
assert.deepEqual(wrapper.emitted('update:modelValue').at(-1), [false]);
|
||||
assert.equal(wrapper.emitted('change').at(-1)[0].target, input.element);
|
||||
assert.equal(input.element.checked, false);
|
||||
await tick(input);
|
||||
assert.deepEqual(wrapper.emitted('update:modelValue').at(-1), [true]);
|
||||
// A parent that resets its value resets the box.
|
||||
await wrapper.setProps({ modelValue: false });
|
||||
assert.equal(input.element.checked, false);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
test('without restore a change the owner ignores stays ticked, as :checked did', async () => {
|
||||
const wrapper = mount(UiCheckbox, { props: { modelValue: false } });
|
||||
const input = wrapper.get('input');
|
||||
await tick(input);
|
||||
await nextTick();
|
||||
assert.deepEqual(wrapper.emitted('update:modelValue'), [[true]]);
|
||||
assert.equal(input.element.checked, true);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
test('restore puts a refused change back and keeps an accepted one', async () => {
|
||||
// Refused: the owner keeps its value.
|
||||
const refused = mount(UiCheckbox, {
|
||||
props: { modelValue: true, restore: true },
|
||||
});
|
||||
const box = refused.get('input');
|
||||
await tick(box);
|
||||
assert.deepEqual(refused.emitted('update:modelValue'), [[false]]);
|
||||
await nextTick();
|
||||
assert.equal(box.element.checked, true);
|
||||
refused.unmount();
|
||||
// Accepted: the owner takes the change before the box is checked again.
|
||||
const accepted = bound({ modelValue: true, restore: true });
|
||||
const input = accepted.get('input');
|
||||
await tick(input);
|
||||
await nextTick();
|
||||
assert.equal(input.element.checked, false);
|
||||
assert.equal(accepted.props('modelValue'), false);
|
||||
accepted.unmount();
|
||||
});
|
||||
|
||||
test('without a modelValue the box is the browser’s own', async () => {
|
||||
const wrapper = mount(UiCheckbox, {
|
||||
props: { inputAttrs: { 'data-first-run-suppress': '' } },
|
||||
});
|
||||
const input = wrapper.get('input');
|
||||
assert.equal(input.element.checked, false);
|
||||
await tick(input);
|
||||
assert.equal(input.element.checked, true);
|
||||
assert.equal(wrapper.emitted('change').length, 1);
|
||||
// Rendering again leaves what was ticked alone.
|
||||
await wrapper.setProps({ inputId: 'suppress' });
|
||||
assert.equal(input.attributes('id'), 'suppress');
|
||||
assert.equal(input.element.checked, true);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
test('a change listener sees the box as the event’s current target', async () => {
|
||||
let seen = null;
|
||||
const wrapper = mount(UiCheckbox, {
|
||||
attrs: {
|
||||
onChange: (event) => {
|
||||
seen = event.currentTarget;
|
||||
},
|
||||
},
|
||||
});
|
||||
const input = wrapper.get('input');
|
||||
await tick(input);
|
||||
assert.equal(seen, input.element);
|
||||
// The label itself does not hear the box's change a second time.
|
||||
assert.equal(wrapper.emitted('change').length, 1);
|
||||
wrapper.unmount();
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
<script setup>
|
||||
import { nextTick, ref } from 'vue';
|
||||
|
||||
// Core's checkbox: a `<label>` wrapping a native `<input type="checkbox">`
|
||||
// and the default slot, which names it. The box comes first, or after the
|
||||
// slot with `trailing`. Attributes and classes pass through to the label, so
|
||||
// each site keeps its feature class and tip; the input takes `inputId` and
|
||||
// `inputAttrs` (other attributes it needs, such as aria-describedby or a
|
||||
// data hook). With v-model the box shows `modelValue` and a change emits the
|
||||
// checked state; `change` is emitted with the event too. Without a
|
||||
// modelValue the box is the browser's own and keeps whatever is ticked.
|
||||
// `restore` puts the box back to `modelValue` after a change its owner did
|
||||
// not take, so a refused preference shows the applied value again. The kit
|
||||
// classes `ui-checkbox` and `ui-checkbox__input` (checkbox.css) are the
|
||||
// label's centred flex row and the box, which keeps each skin's look.
|
||||
const props = defineProps({
|
||||
modelValue: { type: Boolean, default: undefined },
|
||||
inputId: { type: String, default: undefined },
|
||||
inputAttrs: { type: Object, default: undefined },
|
||||
trailing: { type: Boolean, default: false },
|
||||
restore: { type: Boolean, default: false },
|
||||
});
|
||||
const emit = defineEmits(['update:modelValue', 'change']);
|
||||
const input = ref(null);
|
||||
|
||||
function onChange(event) {
|
||||
emit('update:modelValue', event.target.checked);
|
||||
emit('change', event);
|
||||
if (!props.restore) return;
|
||||
// The owner has answered once the update it caused has rendered.
|
||||
nextTick(() => {
|
||||
const box = input.value;
|
||||
if (
|
||||
box &&
|
||||
props.modelValue !== undefined &&
|
||||
box.checked !== props.modelValue
|
||||
)
|
||||
box.checked = props.modelValue;
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<label class="ui-checkbox">
|
||||
<slot v-if="props.trailing" />
|
||||
<input
|
||||
ref="input"
|
||||
type="checkbox"
|
||||
:id="props.inputId"
|
||||
class="ui-checkbox__input"
|
||||
v-bind="props.inputAttrs"
|
||||
:checked="props.modelValue"
|
||||
@change="onChange"
|
||||
/>
|
||||
<slot v-if="!props.trailing" />
|
||||
</label>
|
||||
</template>
|
||||
@@ -1,7 +1,8 @@
|
||||
<script setup>
|
||||
// Core's chip: a label that says what something is, never a control.
|
||||
// Core styles it through the classes its callers pass; the kit classes carry
|
||||
// no Core styles yet. A chip that presses is a UiButton with pressedClass.
|
||||
// Core's chip: a label that says what something is, never a control. It
|
||||
// wears Core's read-only chip (chip.css: a pill of small uppercase mono
|
||||
// text), and `selected` its accent; feature classes the caller passes
|
||||
// restyle it. A chip that presses is a UiButton with pressedClass.
|
||||
defineProps({
|
||||
selected: { type: Boolean, default: false },
|
||||
mono: { type: Boolean, default: false },
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import { after, before, test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { installVueDom } from '../../testSupport/vueDom.mjs';
|
||||
|
||||
let mount;
|
||||
let UiCloseButton;
|
||||
let uninstall;
|
||||
before(async () => {
|
||||
uninstall = installVueDom();
|
||||
({ mount } = await import('@vue/test-utils'));
|
||||
UiCloseButton = (await import('./UiCloseButton.vue')).default;
|
||||
});
|
||||
after(() => uninstall());
|
||||
|
||||
function mountClose(props = {}, attrs = {}) {
|
||||
return mount(UiCloseButton, {
|
||||
attachTo: document.body,
|
||||
props: { label: 'Close card', ...props },
|
||||
attrs,
|
||||
});
|
||||
}
|
||||
|
||||
test('a close button is a button named by its label, with no tip of its own', () => {
|
||||
const wrapper = mountClose();
|
||||
const button = wrapper.get('button');
|
||||
assert.equal(button.attributes('type'), 'button');
|
||||
assert.equal(button.attributes('aria-label'), 'Close card');
|
||||
assert.equal(button.attributes('title'), undefined);
|
||||
assert.ok(button.classes().includes('ui-close-button'));
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
test('glyph="times" draws the × character', () => {
|
||||
const wrapper = mountClose();
|
||||
const button = wrapper.get('button');
|
||||
assert.equal(button.element.innerHTML, '×');
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
test('glyph="icon" draws the Material close symbol, sized by the stylesheet', () => {
|
||||
const wrapper = mountClose({ glyph: 'icon' });
|
||||
const icon = wrapper.get('button > span');
|
||||
assert.equal(wrapper.get('button').element.children.length, 1);
|
||||
assert.equal(icon.text(), 'close');
|
||||
assert.ok(icon.classes().includes('material-symbols-outlined'));
|
||||
assert.equal(icon.attributes('aria-hidden'), 'true');
|
||||
assert.equal(icon.attributes('style'), undefined);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
test('attributes and classes pass through to the button', () => {
|
||||
const wrapper = mountClose(
|
||||
{},
|
||||
{
|
||||
id: 'gev-chat-close',
|
||||
class: 'data-toggle-chip',
|
||||
title: 'Clear reading',
|
||||
'data-action-id': 'clear',
|
||||
'aria-hidden': 'true',
|
||||
disabled: true,
|
||||
hidden: true,
|
||||
},
|
||||
);
|
||||
const button = wrapper.get('button');
|
||||
assert.equal(button.attributes('id'), 'gev-chat-close');
|
||||
assert.ok(button.classes().includes('data-toggle-chip'));
|
||||
assert.ok(button.classes().includes('ui-close-button'));
|
||||
assert.equal(button.attributes('title'), 'Clear reading');
|
||||
assert.equal(button.attributes('data-action-id'), 'clear');
|
||||
assert.equal(button.attributes('aria-hidden'), 'true');
|
||||
assert.equal(button.element.disabled, true);
|
||||
assert.equal(button.element.hidden, true);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
test('bare leaves the kit look off', () => {
|
||||
const wrapper = mountClose({ bare: true }, { class: 'sl-viewer-x' });
|
||||
const classes = wrapper.get('button').classes();
|
||||
assert.ok(classes.includes('sl-viewer-x'));
|
||||
assert.equal(classes.includes('ui-close-button'), false);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
test('a click is emitted with its event', async () => {
|
||||
const wrapper = mountClose();
|
||||
await wrapper.get('button').trigger('click');
|
||||
const clicks = wrapper.emitted('click');
|
||||
assert.equal(clicks.length, 1);
|
||||
assert.ok(clicks[0][0] instanceof Event);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
test('a disabled close button emits no click', async () => {
|
||||
const wrapper = mountClose({}, { disabled: true });
|
||||
await wrapper.get('button').trigger('click');
|
||||
assert.equal(wrapper.emitted('click'), undefined);
|
||||
wrapper.unmount();
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
<script setup>
|
||||
import UiButton from './UiButton.vue';
|
||||
import UiIcon from './UiIcon.vue';
|
||||
|
||||
// Core's close, dismiss and clear button: a UiButton with a fixed glyph and
|
||||
// a required accessible name. `glyph` is `times` (the × character) or `icon`
|
||||
// (the Material `close` symbol, sized by the caller's stylesheet). Attributes
|
||||
// and classes pass through to the button, so each site keeps its id, its
|
||||
// feature class and its look; a `title` passed in is its tip, and without
|
||||
// one it has none. The kit class `ui-close-button` (close-button.css) is
|
||||
// Core's common look, a bare glyph: no padding, border or background of its
|
||||
// own, and a pointer. Its rule selects one class and loads before the
|
||||
// feature stylesheets, so a feature rule still sets the size, colour, hover
|
||||
// and any surface. `bare` leaves the kit look off, for a button whose own
|
||||
// skin sets its padding and border.
|
||||
const props = defineProps({
|
||||
/** The accessible name (aria-label). */
|
||||
label: { type: String, required: true },
|
||||
glyph: {
|
||||
type: String,
|
||||
default: 'times',
|
||||
validator: (value) => ['times', 'icon'].includes(value),
|
||||
},
|
||||
bare: { type: Boolean, default: false },
|
||||
});
|
||||
const emit = defineEmits(['click']);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<UiButton
|
||||
:class="{ 'ui-close-button': !props.bare }"
|
||||
:label="props.label"
|
||||
:native-title="false"
|
||||
@click="emit('click', $event)"
|
||||
><UiIcon v-if="props.glyph === 'icon'" name="close" :size="null" /><template
|
||||
v-else
|
||||
>×</template
|
||||
></UiButton
|
||||
>
|
||||
</template>
|
||||
@@ -0,0 +1,200 @@
|
||||
import { after, before, test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { installVueDom } from '../../testSupport/vueDom.mjs';
|
||||
|
||||
let mount;
|
||||
let nextTick;
|
||||
let UiDialog;
|
||||
let uninstall;
|
||||
before(async () => {
|
||||
uninstall = installVueDom();
|
||||
({ mount } = await import('@vue/test-utils'));
|
||||
({ nextTick } = await import('vue'));
|
||||
UiDialog = (await import('./UiDialog.vue')).default;
|
||||
});
|
||||
after(() => uninstall());
|
||||
|
||||
/**
|
||||
* A dialog that records what it emits, each with whether the dialog was open
|
||||
* then; its content is a paragraph. One is mounted at a time.
|
||||
*/
|
||||
function dialog(props = {}, attrs = {}) {
|
||||
const events = [];
|
||||
const record = (name) => () =>
|
||||
events.push(
|
||||
name,
|
||||
document.querySelector('dialog').open ? 'shown' : 'hidden',
|
||||
);
|
||||
const wrapper = mount(UiDialog, {
|
||||
attachTo: document.body,
|
||||
props: {
|
||||
...props,
|
||||
onDismiss: record('dismiss'),
|
||||
onBrowserClose: record('browserClose'),
|
||||
onOpened: record('opened'),
|
||||
onClosed: record('closed'),
|
||||
},
|
||||
attrs,
|
||||
slots: { default: '<p class="content">Words</p>' },
|
||||
});
|
||||
return { wrapper, events };
|
||||
}
|
||||
|
||||
test('a dialog mounted closed stays closed until open', async () => {
|
||||
const { wrapper, events } = dialog();
|
||||
const element = wrapper.element;
|
||||
assert.equal(element.tagName, 'DIALOG');
|
||||
assert.equal(element.open, false);
|
||||
assert.equal(wrapper.vm.element, element, 'element is exposed');
|
||||
await wrapper.setProps({ open: true });
|
||||
assert.equal(element.open, true);
|
||||
assert.deepEqual(events, ['opened', 'shown']);
|
||||
await wrapper.setProps({ open: false });
|
||||
assert.equal(element.open, false);
|
||||
assert.deepEqual(events, ['opened', 'shown', 'closed', 'hidden']);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
test('a dialog mounted open opens modal on mount; unmounting closes it', async () => {
|
||||
const modal = [];
|
||||
const showModal = HTMLDialogElement.prototype.showModal;
|
||||
HTMLDialogElement.prototype.showModal = function () {
|
||||
modal.push(this);
|
||||
return showModal.call(this);
|
||||
};
|
||||
try {
|
||||
const { wrapper, events } = dialog({ open: true });
|
||||
const element = wrapper.element;
|
||||
assert.deepEqual(modal, [element]);
|
||||
assert.equal(element.open, true);
|
||||
assert.deepEqual(events, ['opened', 'shown']);
|
||||
wrapper.unmount();
|
||||
assert.equal(element.open, false);
|
||||
assert.deepEqual(events, ['opened', 'shown'], 'no dismiss on unmount');
|
||||
} finally {
|
||||
HTMLDialogElement.prototype.showModal = showModal;
|
||||
}
|
||||
});
|
||||
|
||||
test('the open state follows the content: opened comes after it renders', async () => {
|
||||
// The content changes in the same update that opens the dialog, so an
|
||||
// opened emitted before that update renders would see the old words.
|
||||
const { h } = await import('vue');
|
||||
let seen;
|
||||
const Host = {
|
||||
props: { open: Boolean, words: String },
|
||||
setup(props) {
|
||||
return () =>
|
||||
h(
|
||||
UiDialog,
|
||||
{
|
||||
open: props.open,
|
||||
onOpened: () => {
|
||||
seen = document.querySelector('dialog .content')?.textContent;
|
||||
},
|
||||
},
|
||||
() => h('p', { class: 'content' }, props.words),
|
||||
);
|
||||
},
|
||||
};
|
||||
const wrapper = mount(Host, {
|
||||
attachTo: document.body,
|
||||
props: { open: false, words: 'Before' },
|
||||
});
|
||||
await wrapper.setProps({ open: true, words: 'After' });
|
||||
assert.equal(seen, 'After');
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
test('Escape is prevented and emitted as dismiss; the owner decides', async () => {
|
||||
const { wrapper, events } = dialog({ open: true });
|
||||
events.length = 0;
|
||||
const cancel = new Event('cancel', { cancelable: true });
|
||||
wrapper.element.dispatchEvent(cancel);
|
||||
assert.equal(cancel.defaultPrevented, true);
|
||||
assert.equal(wrapper.element.open, true);
|
||||
assert.deepEqual(events, ['dismiss', 'shown']);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
test('a close the browser made while open is reported once; the owner’s is not', async () => {
|
||||
const { wrapper, events } = dialog({ open: true });
|
||||
events.length = 0;
|
||||
wrapper.element.close();
|
||||
assert.deepEqual(events, ['browserClose', 'hidden']);
|
||||
events.length = 0;
|
||||
// The owner then closes it too: nothing to close, closed is still emitted.
|
||||
await wrapper.setProps({ open: false });
|
||||
assert.deepEqual(events, ['closed', 'hidden']);
|
||||
await wrapper.setProps({ open: true });
|
||||
events.length = 0;
|
||||
await wrapper.setProps({ open: false });
|
||||
assert.deepEqual(events, ['closed', 'hidden'], 'no browserClose');
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
test('a late close event from an earlier close is not reported once open again', async () => {
|
||||
const { wrapper, events } = dialog({ open: true });
|
||||
await wrapper.setProps({ open: false });
|
||||
await wrapper.setProps({ open: true });
|
||||
events.length = 0;
|
||||
// The browser's queued close event from the first close lands now.
|
||||
wrapper.element.dispatchEvent(new Event('close'));
|
||||
assert.deepEqual(events, [], 'no browserClose');
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
test('a backdrop click dismisses only when asked, and only on the dialog', async () => {
|
||||
const plain = dialog({ open: true });
|
||||
plain.events.length = 0;
|
||||
plain.wrapper.element.click();
|
||||
assert.deepEqual(plain.events, []);
|
||||
plain.wrapper.unmount();
|
||||
|
||||
const backdrop = dialog({ open: true, backdropDismiss: true });
|
||||
backdrop.events.length = 0;
|
||||
backdrop.wrapper.get('.content').element.click();
|
||||
assert.deepEqual(backdrop.events, [], 'a click inside is content');
|
||||
backdrop.wrapper.element.click();
|
||||
assert.deepEqual(backdrop.events, ['dismiss', 'shown']);
|
||||
backdrop.wrapper.unmount();
|
||||
});
|
||||
|
||||
test('attributes, classes, styles and listeners pass through to the dialog', async () => {
|
||||
const clicks = [];
|
||||
const { wrapper } = dialog(
|
||||
{},
|
||||
{
|
||||
id: 'library',
|
||||
class: 'library-dialog',
|
||||
style: { width: '40px' },
|
||||
'aria-label': 'Library',
|
||||
'data-panel-surface': '',
|
||||
onClick: () => clicks.push('click'),
|
||||
},
|
||||
);
|
||||
const element = wrapper.element;
|
||||
assert.equal(element.id, 'library');
|
||||
assert.ok(element.classList.contains('library-dialog'));
|
||||
assert.equal(element.style.width, '40px');
|
||||
assert.equal(element.getAttribute('aria-label'), 'Library');
|
||||
assert.equal(element.getAttribute('data-panel-surface'), '');
|
||||
element.click();
|
||||
assert.deepEqual(clicks, ['click']);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
test('a DOM without showModal leaves the dialog closed rather than failing', async () => {
|
||||
const showModal = HTMLDialogElement.prototype.showModal;
|
||||
HTMLDialogElement.prototype.showModal = undefined;
|
||||
try {
|
||||
const { wrapper, events } = dialog({ open: true });
|
||||
assert.equal(wrapper.element.open, false);
|
||||
assert.deepEqual(events, ['opened', 'hidden']);
|
||||
await wrapper.setProps({ open: false });
|
||||
await nextTick();
|
||||
wrapper.unmount();
|
||||
} finally {
|
||||
HTMLDialogElement.prototype.showModal = showModal;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
<script setup>
|
||||
import { onBeforeUnmount, onMounted, useTemplateRef, watch } from 'vue';
|
||||
|
||||
// Core's modal dialog: a native `<dialog>` the owner opens and closes with
|
||||
// `open`. True opens it with showModal() (once mounted, so a dialog mounted
|
||||
// open opens straight away), false closes it, and unmounting closes it.
|
||||
// Each change is applied after the content has rendered and is then emitted
|
||||
// (`opened`, `closed`), so the owner can move focus into the content it
|
||||
// shows or back to the control that opened it. Escape's `cancel` is
|
||||
// prevented and emitted as `dismiss`, so the owner decides; with
|
||||
// `backdropDismiss`, a click on the backdrop (the dialog element itself,
|
||||
// outside its content) is a `dismiss` too. When the browser closes the
|
||||
// dialog on its own while `open` is still true (an Escape it does not let
|
||||
// the page cancel), `browserClose` tells the owner. A DOM without
|
||||
// showModal() (a test's) leaves the dialog closed rather than failing.
|
||||
// Attributes, classes, styles and listeners pass through to the dialog; the
|
||||
// content is the default slot. `element` is the dialog element.
|
||||
const props = defineProps({
|
||||
open: { type: Boolean, default: false },
|
||||
backdropDismiss: { type: Boolean, default: false },
|
||||
});
|
||||
const emit = defineEmits(['dismiss', 'browserClose', 'opened', 'closed']);
|
||||
const element = useTemplateRef('element');
|
||||
let unmounting = false;
|
||||
|
||||
function show() {
|
||||
const dialog = element.value;
|
||||
if (!dialog) return;
|
||||
if (!dialog.open) dialog.showModal?.();
|
||||
emit('opened');
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
if (props.open) show();
|
||||
});
|
||||
watch(
|
||||
() => props.open,
|
||||
(open) => {
|
||||
if (open) return show();
|
||||
const dialog = element.value;
|
||||
if (!dialog) return;
|
||||
// The browser may already have closed it.
|
||||
if (dialog.open) dialog.close();
|
||||
emit('closed');
|
||||
},
|
||||
{ flush: 'post' },
|
||||
);
|
||||
onBeforeUnmount(() => {
|
||||
unmounting = true;
|
||||
if (element.value?.open) element.value.close();
|
||||
});
|
||||
|
||||
function onCancel(event) {
|
||||
event.preventDefault();
|
||||
emit('dismiss');
|
||||
}
|
||||
// The browser queues its close event, so one from an earlier close can land
|
||||
// after the dialog has been opened again; only a dialog still shut reports it.
|
||||
function onClose() {
|
||||
if (!unmounting && props.open && !element.value?.open) emit('browserClose');
|
||||
}
|
||||
function onClick(event) {
|
||||
if (props.backdropDismiss && event.target === event.currentTarget)
|
||||
emit('dismiss');
|
||||
}
|
||||
|
||||
defineExpose({ element });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<dialog ref="element" @cancel="onCancel" @close="onClose" @click="onClick">
|
||||
<slot />
|
||||
</dialog>
|
||||
</template>
|
||||
@@ -1,8 +1,9 @@
|
||||
<script setup>
|
||||
// Core's empty state, with a `title` and `hint`. Core's empty states are one
|
||||
// line, so the title is the text itself rather than a bold heading; a hint
|
||||
// follows it. Core
|
||||
// styles it through the classes its callers pass. Not mirrored yet: icon.
|
||||
// follows it on a line of its own. It wears Core's empty line
|
||||
// (empty-state.css: dim 10px mono text); feature classes the caller passes
|
||||
// restyle it. Not mirrored yet: icon.
|
||||
defineProps({
|
||||
title: { type: String, required: true },
|
||||
hint: { type: String, default: undefined },
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
<script setup>
|
||||
/** A Material Symbols glyph; the name must be in index.html's `icon_names`. */
|
||||
/**
|
||||
* A Material Symbols glyph; the name must be in index.html's `icon_names`.
|
||||
* `size` is its font size in pixels; null leaves the size to the stylesheet.
|
||||
*/
|
||||
defineProps({
|
||||
name: { type: String, required: true },
|
||||
size: { type: Number, default: 18 },
|
||||
@@ -9,7 +12,7 @@ defineProps({
|
||||
<template>
|
||||
<span
|
||||
class="ui-icon material-symbols-outlined"
|
||||
:style="{ fontSize: `${size}px` }"
|
||||
:style="size == null ? undefined : { fontSize: `${size}px` }"
|
||||
aria-hidden="true"
|
||||
>{{ name }}</span
|
||||
>
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import { after, before, test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { installVueDom } from '../../testSupport/vueDom.mjs';
|
||||
|
||||
let mount;
|
||||
let UiSearchField;
|
||||
let uninstall;
|
||||
before(async () => {
|
||||
uninstall = installVueDom();
|
||||
({ mount } = await import('@vue/test-utils'));
|
||||
UiSearchField = (await import('./UiSearchField.vue')).default;
|
||||
});
|
||||
after(() => uninstall());
|
||||
|
||||
/** A field whose v-model writes back into its props, as a parent's would. */
|
||||
function bound(props = {}, attrs = {}) {
|
||||
const wrapper = mount(UiSearchField, {
|
||||
attachTo: document.body,
|
||||
props: {
|
||||
label: 'Search layers',
|
||||
modelValue: '',
|
||||
...props,
|
||||
'onUpdate:modelValue': (value) => wrapper.setProps({ modelValue: value }),
|
||||
},
|
||||
attrs,
|
||||
});
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
test('a search field is the search glyph and a search input named by its label', () => {
|
||||
const wrapper = bound({ placeholder: 'Search layers…' });
|
||||
const root = wrapper.get('div');
|
||||
assert.ok(root.classes().includes('ui-search-field'));
|
||||
const icon = wrapper.get('span');
|
||||
assert.equal(icon.text(), 'search');
|
||||
assert.ok(icon.classes().includes('material-symbols-outlined'));
|
||||
assert.equal(icon.attributes('aria-hidden'), 'true');
|
||||
const input = wrapper.get('input');
|
||||
assert.equal(input.attributes('type'), 'search');
|
||||
assert.ok(input.classes().includes('ui-search-field__input'));
|
||||
assert.equal(input.attributes('aria-label'), 'Search layers');
|
||||
assert.equal(input.attributes('placeholder'), 'Search layers…');
|
||||
for (const name of ['id', 'autocomplete', 'spellcheck'])
|
||||
assert.equal(input.attributes(name), undefined, name);
|
||||
assert.equal(wrapper.find('button').exists(), false);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
test('v-model shows the text and updates it as typed', async () => {
|
||||
const wrapper = bound({ modelValue: 'radar' });
|
||||
const input = wrapper.get('input');
|
||||
assert.equal(input.element.value, 'radar');
|
||||
await input.setValue('rain');
|
||||
assert.deepEqual(wrapper.emitted('update:modelValue').at(-1), ['rain']);
|
||||
assert.equal(wrapper.props('modelValue'), 'rain');
|
||||
// A parent that empties its value, as closing a search does, empties the input.
|
||||
await wrapper.setProps({ modelValue: '' });
|
||||
assert.equal(input.element.value, '');
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
test('the clear button shows only while text is typed, clears and refocuses', async () => {
|
||||
const wrapper = bound({
|
||||
clearLabel: 'Clear search',
|
||||
clearClass: 'context-search__clear',
|
||||
});
|
||||
assert.equal(wrapper.find('button').exists(), false);
|
||||
await wrapper.setProps({ modelValue: 'rain' });
|
||||
const clear = wrapper.get('button');
|
||||
assert.equal(clear.attributes('aria-label'), 'Clear search');
|
||||
assert.equal(clear.attributes('title'), 'Clear search');
|
||||
assert.ok(clear.classes().includes('context-search__clear'));
|
||||
assert.ok(clear.classes().includes('ui-close-button'));
|
||||
assert.equal(clear.get('span').text(), 'close');
|
||||
await clear.trigger('click');
|
||||
assert.deepEqual(wrapper.emitted('update:modelValue').at(-1), ['']);
|
||||
assert.equal(document.activeElement, wrapper.get('input').element);
|
||||
assert.equal(wrapper.find('button').exists(), false);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
test('Escape is emitted with its event and stops at the input', async () => {
|
||||
const wrapper = bound();
|
||||
let bubbled = 0;
|
||||
const onKey = () => bubbled++;
|
||||
wrapper.element.addEventListener('keydown', onKey);
|
||||
await wrapper.get('input').trigger('keydown', { key: 'Escape' });
|
||||
const escapes = wrapper.emitted('escape');
|
||||
assert.equal(escapes.length, 1);
|
||||
assert.ok(escapes[0][0] instanceof Event);
|
||||
assert.equal(escapes[0][0].defaultPrevented, false);
|
||||
assert.equal(bubbled, 0);
|
||||
await wrapper.get('input').trigger('keydown', { key: 'a' });
|
||||
assert.equal(wrapper.emitted('escape').length, 1);
|
||||
assert.equal(bubbled, 1);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
test('tag="label" frames the input in a label', () => {
|
||||
const wrapper = bound({ tag: 'label' });
|
||||
assert.equal(wrapper.element.tagName, 'LABEL');
|
||||
assert.ok(wrapper.element.contains(wrapper.get('input').element));
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
test('attributes and classes pass through to the frame; the input takes its own', () => {
|
||||
const wrapper = bound(
|
||||
{
|
||||
inputId: 'layer-finder-input',
|
||||
inputClass: 'context-search__input',
|
||||
autocomplete: 'off',
|
||||
spellcheck: 'false',
|
||||
},
|
||||
{ class: 'context-search', role: 'search', 'data-x': '1' },
|
||||
);
|
||||
const root = wrapper.get('div');
|
||||
assert.ok(root.classes().includes('context-search'));
|
||||
assert.ok(root.classes().includes('ui-search-field'));
|
||||
assert.equal(root.attributes('role'), 'search');
|
||||
assert.equal(root.attributes('data-x'), '1');
|
||||
const input = wrapper.get('input');
|
||||
assert.equal(input.attributes('id'), 'layer-finder-input');
|
||||
assert.ok(input.classes().includes('context-search__input'));
|
||||
assert.ok(input.classes().includes('ui-search-field__input'));
|
||||
assert.equal(input.attributes('autocomplete'), 'off');
|
||||
assert.equal(input.attributes('spellcheck'), 'false');
|
||||
assert.equal(input.attributes('role'), undefined);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
test('focus() focuses the input', () => {
|
||||
const wrapper = bound();
|
||||
wrapper.vm.focus();
|
||||
assert.equal(document.activeElement, wrapper.get('input').element);
|
||||
wrapper.unmount();
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
<script setup>
|
||||
import { computed, ref } from 'vue';
|
||||
import UiCloseButton from './UiCloseButton.vue';
|
||||
|
||||
// Core's search field: the Material `search` glyph, then an
|
||||
// `<input type="search">` bound with v-model, and, when `clearLabel` is set,
|
||||
// a UiCloseButton (the `close` symbol, its label as its tip) shown while
|
||||
// text is typed, which empties the field and focuses the input again. `tag`
|
||||
// is the frame: a `div` (give it role="search") or a `label`, which names
|
||||
// the input by wrapping it. Attributes and classes pass through to the frame,
|
||||
// so each site keeps its feature class; the input takes `inputId`,
|
||||
// `inputClass`, `autocomplete` and `spellcheck`, and the clear button
|
||||
// `clearClass`. Escape, pressed in the input, stops there and is emitted
|
||||
// with its event, so a caller that also prevents the browser's own Escape
|
||||
// does so. `focus()` focuses the input. The kit classes `ui-search-field`
|
||||
// and `ui-search-field__input` (search-field.css) are the frame's flex row
|
||||
// and the bare input; the browser's own cancel button is left as it is.
|
||||
const props = defineProps({
|
||||
modelValue: { type: String, default: '' },
|
||||
/** The input's accessible name (aria-label). */
|
||||
label: { type: String, required: true },
|
||||
placeholder: { type: String, default: undefined },
|
||||
tag: {
|
||||
type: String,
|
||||
default: 'div',
|
||||
validator: (value) => ['div', 'label'].includes(value),
|
||||
},
|
||||
inputId: { type: String, default: undefined },
|
||||
inputClass: { type: String, default: undefined },
|
||||
autocomplete: { type: String, default: undefined },
|
||||
spellcheck: { type: String, default: undefined },
|
||||
/** The clear button's accessible name and tip; none without it. */
|
||||
clearLabel: { type: String, default: undefined },
|
||||
clearClass: { type: String, default: undefined },
|
||||
});
|
||||
const emit = defineEmits(['update:modelValue', 'escape']);
|
||||
const input = ref(null);
|
||||
// The input keeps Vue's native v-model, as both fields had.
|
||||
const text = computed({
|
||||
get: () => props.modelValue,
|
||||
set: (value) => emit('update:modelValue', value),
|
||||
});
|
||||
|
||||
function focus() {
|
||||
input.value?.focus();
|
||||
}
|
||||
|
||||
function clear() {
|
||||
emit('update:modelValue', '');
|
||||
focus();
|
||||
}
|
||||
|
||||
defineExpose({ focus });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<component :is="props.tag" class="ui-search-field">
|
||||
<span class="material-symbols-outlined" aria-hidden="true">search</span>
|
||||
<input
|
||||
:id="props.inputId"
|
||||
ref="input"
|
||||
v-model="text"
|
||||
type="search"
|
||||
class="ui-search-field__input"
|
||||
:class="props.inputClass"
|
||||
:placeholder="props.placeholder"
|
||||
:aria-label="props.label"
|
||||
:autocomplete="props.autocomplete"
|
||||
:spellcheck="props.spellcheck"
|
||||
@keydown.esc.stop="emit('escape', $event)"
|
||||
/>
|
||||
<UiCloseButton
|
||||
v-if="props.clearLabel && props.modelValue"
|
||||
:class="props.clearClass"
|
||||
glyph="icon"
|
||||
:label="props.clearLabel"
|
||||
:title="props.clearLabel"
|
||||
@click="clear"
|
||||
/>
|
||||
</component>
|
||||
</template>
|
||||
@@ -7,7 +7,9 @@ import { computed } from 'vue';
|
||||
// stop that arrows move) or `radio` (arrows plus Home and
|
||||
// End). Each option may carry `attrs` (an id, data attributes, a tip), and
|
||||
// Core's classes sit beside the kit's: `gev-segmented`, `gev-segment` and the
|
||||
// selected option's `activeClass`. An option with an `icon` shows the glyph,
|
||||
// selected option's `activeClass`. The kit's classes wear Core's segmented
|
||||
// skin (segmented-control.css) as Core's do; `stacked` carries no style yet.
|
||||
// An option with an `icon` shows the glyph,
|
||||
// and its label becomes the button's accessible name and tooltip, unless its
|
||||
// `attrs` carry a tip of their own.
|
||||
const props = defineProps({
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
// Every checkbox in a Vue view is a UiCheckbox: no SFC template hand-writes
|
||||
// `<input type="checkbox">`. Story Explore's filters are not converted yet.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync, readdirSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const SRC_ROOT = fileURLToPath(new URL('../../', import.meta.url));
|
||||
const REPO_ROOT = path.resolve(SRC_ROOT, '..');
|
||||
const NOT_YET = new Set([
|
||||
'src/ui/kit/UiCheckbox.vue',
|
||||
'src/ui/views/stories/ExploreScreen.vue',
|
||||
]);
|
||||
|
||||
/** Every SFC under src. */
|
||||
function sfcFiles(directory = SRC_ROOT) {
|
||||
const files = [];
|
||||
for (const entry of readdirSync(directory, { withFileTypes: true })) {
|
||||
const absolute = path.join(directory, entry.name);
|
||||
if (entry.isDirectory()) files.push(...sfcFiles(absolute));
|
||||
else if (entry.isFile() && entry.name.endsWith('.vue'))
|
||||
files.push(absolute);
|
||||
}
|
||||
return files.sort();
|
||||
}
|
||||
|
||||
/** The template block: everything outside script and style. */
|
||||
function template(source) {
|
||||
return source.replace(/<(script|style)\b[\s\S]*?<\/\1\s*>/g, '');
|
||||
}
|
||||
|
||||
// An opening tag's attributes, quoted values may hold `>` (`() => x`).
|
||||
const ATTRS = String.raw`(?:[^>"']|"[^"]*"|'[^']*')*`;
|
||||
const HAND_WRITTEN_CHECKBOX = new RegExp(
|
||||
String.raw`<input\b${ATTRS}\btype="checkbox"${ATTRS}>`,
|
||||
'gi',
|
||||
);
|
||||
|
||||
/** Hand-written checkboxes in an SFC's template. */
|
||||
function handWrittenCheckboxes(source) {
|
||||
return [...template(source).matchAll(HAND_WRITTEN_CHECKBOX)].map((m) =>
|
||||
m[0].replace(/\s+/g, ' '),
|
||||
);
|
||||
}
|
||||
|
||||
test('the scan finds each hand-written checkbox', () => {
|
||||
for (const markup of [
|
||||
'<template><input type="checkbox" id="x" @change="on" /></template>',
|
||||
'<template><input\n :checked="a > b"\n type="checkbox"\n/></template>',
|
||||
])
|
||||
assert.equal(handWrittenCheckboxes(markup).length, 1, markup);
|
||||
for (const markup of [
|
||||
'<template><UiCheckbox input-id="x" v-model="on">On</UiCheckbox></template>',
|
||||
'<template><input type="search" /></template>',
|
||||
'<script>const html = \'<input type="checkbox">\';</script><template><p /></template>',
|
||||
])
|
||||
assert.equal(handWrittenCheckboxes(markup).length, 0, markup);
|
||||
});
|
||||
|
||||
test('no SFC hand-writes a checkbox; each is a UiCheckbox', () => {
|
||||
const found = [];
|
||||
for (const file of sfcFiles()) {
|
||||
const relative = path.relative(REPO_ROOT, file).split(path.sep).join('/');
|
||||
if (NOT_YET.has(relative)) continue;
|
||||
for (const markup of handWrittenCheckboxes(readFileSync(file, 'utf8')))
|
||||
found.push(`${relative}: ${markup}`);
|
||||
}
|
||||
assert.deepEqual(found, []);
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
// Every close, dismiss and clear button in a Vue view is a UiCloseButton: no
|
||||
// SFC template hand-writes a button whose only content is × or the Material
|
||||
// `close` symbol. Buttons built in script are not read here.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync, readdirSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const SRC_ROOT = fileURLToPath(new URL('../../', import.meta.url));
|
||||
const REPO_ROOT = path.resolve(SRC_ROOT, '..');
|
||||
|
||||
/** Every SFC under src. */
|
||||
function sfcFiles(directory = SRC_ROOT) {
|
||||
const files = [];
|
||||
for (const entry of readdirSync(directory, { withFileTypes: true })) {
|
||||
const absolute = path.join(directory, entry.name);
|
||||
if (entry.isDirectory()) files.push(...sfcFiles(absolute));
|
||||
else if (entry.isFile() && entry.name.endsWith('.vue'))
|
||||
files.push(absolute);
|
||||
}
|
||||
return files.sort();
|
||||
}
|
||||
|
||||
/** The template block: everything outside script and style. */
|
||||
function template(source) {
|
||||
return source.replace(/<(script|style)\b[\s\S]*?<\/\1\s*>/g, '');
|
||||
}
|
||||
|
||||
// An opening tag's attributes, quoted values may hold `>` (`() => x`).
|
||||
const ATTRS = String.raw`(?:[^>"']|"[^"]*"|'[^']*')*`;
|
||||
const BUTTON = String.raw`(button|UiButton)`;
|
||||
const CLOSE_GLYPH = [
|
||||
String.raw`×|×|×|×`,
|
||||
String.raw`<span\b[^>]*\bmaterial-symbols-outlined\b[^>]*>\s*close\s*</span\s*>`,
|
||||
String.raw`<UiIcon${ATTRS}\bname="close"${ATTRS}/>`,
|
||||
].join('|');
|
||||
const HAND_WRITTEN_CLOSE = new RegExp(
|
||||
String.raw`<${BUTTON}\b${ATTRS}>\s*(?:${CLOSE_GLYPH})\s*</\1\s*>`,
|
||||
'gi',
|
||||
);
|
||||
|
||||
/** Hand-written close buttons in an SFC's template. */
|
||||
function handWrittenCloses(source) {
|
||||
return [...template(source).matchAll(HAND_WRITTEN_CLOSE)].map((m) =>
|
||||
m[0].replace(/\s+/g, ' '),
|
||||
);
|
||||
}
|
||||
|
||||
test('the scan finds each hand-written close glyph', () => {
|
||||
for (const markup of [
|
||||
'<template><button type="button" @click="emit(\'close\')">×</button></template>',
|
||||
'<template><button\n class="x"\n :title="a > b ? 1 : 2"\n >×</button\n></template>',
|
||||
'<template><UiButton class="x" :label="l">×</UiButton></template>',
|
||||
'<template><button type="button" class="x">\n <span class="material-symbols-outlined" aria-hidden="true">close</span>\n</button></template>',
|
||||
'<template><UiButton class="x"><UiIcon name="close" :size="14" /></UiButton></template>',
|
||||
])
|
||||
assert.equal(handWrittenCloses(markup).length, 1, markup);
|
||||
for (const markup of [
|
||||
'<template><UiCloseButton class="x" :label="l" /></template>',
|
||||
'<template><button type="button">{{ name }} ×</button></template>',
|
||||
'<template><button type="button">On<span class="material-symbols-outlined">close</span></button></template>',
|
||||
'<template><button type="button"><span class="material-symbols-outlined">close_fullscreen</span></button></template>',
|
||||
])
|
||||
assert.equal(handWrittenCloses(markup).length, 0, markup);
|
||||
});
|
||||
|
||||
test('no SFC hand-writes a close button; each is a UiCloseButton', () => {
|
||||
const found = [];
|
||||
for (const file of sfcFiles()) {
|
||||
const relative = path.relative(REPO_ROOT, file).split(path.sep).join('/');
|
||||
for (const markup of handWrittenCloses(readFileSync(file, 'utf8')))
|
||||
found.push(`${relative}: ${markup}`);
|
||||
}
|
||||
assert.deepEqual(found, []);
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
// Every modal dialog in a Vue view is a UiDialog: no SFC template hand-writes
|
||||
// `<dialog>`. Panels drawn as `role="dialog"` (key setup, the welcome
|
||||
// launcher, the CCTV popup, Story Explore's filter) and the render failure's
|
||||
// `alertdialog` are other controls.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync, readdirSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const SRC_ROOT = fileURLToPath(new URL('../../', import.meta.url));
|
||||
const REPO_ROOT = path.resolve(SRC_ROOT, '..');
|
||||
const KIT = 'src/ui/kit/UiDialog.vue';
|
||||
|
||||
/** Every SFC under src. */
|
||||
function sfcFiles(directory = SRC_ROOT) {
|
||||
const files = [];
|
||||
for (const entry of readdirSync(directory, { withFileTypes: true })) {
|
||||
const absolute = path.join(directory, entry.name);
|
||||
if (entry.isDirectory()) files.push(...sfcFiles(absolute));
|
||||
else if (entry.isFile() && entry.name.endsWith('.vue'))
|
||||
files.push(absolute);
|
||||
}
|
||||
return files.sort();
|
||||
}
|
||||
|
||||
/** The template block: everything outside script and style. */
|
||||
function template(source) {
|
||||
return source.replace(/<(script|style)\b[\s\S]*?<\/\1\s*>/g, '');
|
||||
}
|
||||
|
||||
// An opening tag's attributes, quoted values may hold `>` (`() => x`).
|
||||
const ATTRS = String.raw`(?:[^>"']|"[^"]*"|'[^']*')*`;
|
||||
const HAND_WRITTEN_DIALOG = new RegExp(String.raw`<dialog\b${ATTRS}>`, 'gi');
|
||||
|
||||
/** Hand-written dialogs in an SFC's template. */
|
||||
function handWrittenDialogs(source) {
|
||||
return [...template(source).matchAll(HAND_WRITTEN_DIALOG)].map((m) =>
|
||||
m[0].replace(/\s+/g, ' '),
|
||||
);
|
||||
}
|
||||
|
||||
test('the scan finds each hand-written dialog', () => {
|
||||
for (const markup of [
|
||||
'<template><dialog id="x" @cancel.prevent="on"><p /></dialog></template>',
|
||||
'<template><dialog\n :open="a > b"\n class="x"\n>…</dialog></template>',
|
||||
])
|
||||
assert.equal(handWrittenDialogs(markup).length, 1, markup);
|
||||
for (const markup of [
|
||||
'<template><UiDialog :open="on" @dismiss="off"><p /></UiDialog></template>',
|
||||
'<template><div role="dialog" aria-modal="true" /></template>',
|
||||
"<script>const html = '<dialog open>';</script><template><p /></template>",
|
||||
])
|
||||
assert.equal(handWrittenDialogs(markup).length, 0, markup);
|
||||
});
|
||||
|
||||
test('no SFC hand-writes a dialog; each is a UiDialog', () => {
|
||||
const found = [];
|
||||
for (const file of sfcFiles()) {
|
||||
const relative = path.relative(REPO_ROOT, file).split(path.sep).join('/');
|
||||
if (relative === KIT) continue;
|
||||
for (const markup of handWrittenDialogs(readFileSync(file, 'utf8')))
|
||||
found.push(`${relative}: ${markup}`);
|
||||
}
|
||||
assert.deepEqual(found, []);
|
||||
});
|
||||
@@ -0,0 +1,266 @@
|
||||
// The kit's classes wear Core's standard looks: each shares one selector list
|
||||
// with the Core skin it comes from, so the rules are never copied, and the
|
||||
// default ghost button carries none.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readStylesheet } from '../../testSupport/readStylesheet.mjs';
|
||||
|
||||
const css = readStylesheet(new URL('../../../style.css', import.meta.url));
|
||||
|
||||
/** Each rule's selectors, outside @media and other at-rule preludes. */
|
||||
function rules(source) {
|
||||
const out = [];
|
||||
const re = /([^{}]+)\{([^{}]*)\}/g;
|
||||
const bare = source.replace(/\/\*[\s\S]*?\*\//g, '');
|
||||
let match;
|
||||
while ((match = re.exec(bare))) {
|
||||
const prelude = match[1].split('}').pop().trim();
|
||||
if (prelude.startsWith('@')) continue;
|
||||
out.push({
|
||||
selectors: prelude
|
||||
.split(',')
|
||||
.map((s) =>
|
||||
s
|
||||
.replace(/\s+/g, ' ')
|
||||
.replace(/\( /g, '(')
|
||||
.replace(/ \)/g, ')')
|
||||
.trim(),
|
||||
),
|
||||
body: match[2],
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
const all = rules(css);
|
||||
|
||||
/** The rule that lists exactly `selector`, which must exist. */
|
||||
function ruleWith(selector) {
|
||||
const found = all.filter((rule) => rule.selectors.includes(selector));
|
||||
assert.equal(found.length, 1, `one rule lists ${selector}`);
|
||||
return found[0];
|
||||
}
|
||||
|
||||
/** `kit` and `core` share one rule, so the kit wears Core's skin unchanged. */
|
||||
function shares(kit, core) {
|
||||
const rule = ruleWith(kit);
|
||||
assert.ok(rule.selectors.includes(core), `${kit} shares ${core}'s rule`);
|
||||
return rule;
|
||||
}
|
||||
|
||||
test('UiButton variants wear Core’s action and icon skins', () => {
|
||||
shares('.ui-button--action', '.gev-action-button');
|
||||
shares('.ui-button--primary', '.gev-action-button');
|
||||
shares(
|
||||
'.ui-button--action:hover:not(:disabled)',
|
||||
'.gev-action-button:hover:not(:disabled)',
|
||||
);
|
||||
shares('.ui-button--action:disabled', '.gev-action-button:disabled');
|
||||
shares(
|
||||
'.ui-button--action.ui-button--danger:hover:not(:disabled)',
|
||||
'.gev-action-button--danger:hover:not(:disabled)',
|
||||
);
|
||||
shares(
|
||||
'.ui-button--primary:where(:not(:disabled))',
|
||||
'#scene-panel .scene-btn-primary:not(:disabled)',
|
||||
);
|
||||
shares(
|
||||
'.ui-button--compact:where(.ui-button--action)',
|
||||
'.gev-action-button--compact',
|
||||
);
|
||||
shares(
|
||||
'.ui-button--compact:where(.ui-button--action):hover:not(:disabled):not(.ui-button--pressed)',
|
||||
'.gev-action-button--compact:hover:not(:disabled)',
|
||||
);
|
||||
shares(
|
||||
'.ui-button--compact.ui-button--danger:where(.ui-button--action):hover:not(:disabled)',
|
||||
'.gev-action-button--compact.gev-action-button--danger:hover:not(:disabled)',
|
||||
);
|
||||
shares('.ui-button--icon', '.panel-collapse-btn');
|
||||
shares('.ui-button--icon:hover:not(:disabled)', '.panel-collapse-btn:hover');
|
||||
assert.match(ruleWith('.ui-button--icon:disabled').body, /opacity:\s*0\.45/);
|
||||
});
|
||||
|
||||
test('a pressed styled button looks as a hovered one does', () => {
|
||||
shares(
|
||||
'.ui-button--action.ui-button--pressed:not(:disabled)',
|
||||
'.gev-action-button:hover:not(:disabled)',
|
||||
);
|
||||
shares(
|
||||
'.ui-button--primary.ui-button--pressed:not(:disabled)',
|
||||
'.gev-action-button:hover:not(:disabled)',
|
||||
);
|
||||
shares(
|
||||
'.ui-button--action.ui-button--danger.ui-button--pressed:not(:disabled)',
|
||||
'.gev-action-button--danger:hover:not(:disabled)',
|
||||
);
|
||||
shares(
|
||||
'.ui-button--icon.ui-button--pressed:not(:disabled)',
|
||||
'.panel-collapse-btn:hover',
|
||||
);
|
||||
});
|
||||
|
||||
test('a ghost button, the tones and the size alone carry no style', () => {
|
||||
const kitButton =
|
||||
/\.ui-button(?:--(?:ghost|accent|danger|pressed|compact))?(?![\w-])/;
|
||||
// size="compact" styles the action variant only.
|
||||
const look = /\.ui-button--(?:action|primary|icon)(?![\w-])/;
|
||||
for (const rule of all)
|
||||
for (const selector of rule.selectors)
|
||||
assert.ok(
|
||||
!kitButton.test(selector) || look.test(selector),
|
||||
`${selector} styles a kit button without a look`,
|
||||
);
|
||||
});
|
||||
|
||||
test('UiChip, UiEmpty, UiBadge and UiSegmented wear Core’s skins', () => {
|
||||
shares('.ui-chip', '.news-chip');
|
||||
shares('.ui-chip--selected', '.news-chip--official');
|
||||
shares('.ui-empty', '.news-readout__empty');
|
||||
assert.match(ruleWith('.ui-empty__hint').body, /display:\s*block/);
|
||||
shares('.ui-badge', '.gev-status-badge');
|
||||
shares('.ui-badge[hidden]', '.gev-status-badge[hidden]');
|
||||
shares('.ui-segmented', '.gev-segmented');
|
||||
shares('.ui-segmented[hidden]', '.gev-segmented[hidden]');
|
||||
shares('.ui-segmented__item', '.gev-segment');
|
||||
shares(
|
||||
'.ui-segmented__item + .ui-segmented__item',
|
||||
'.gev-segment + .gev-segment',
|
||||
);
|
||||
shares(
|
||||
".ui-segmented__item[aria-checked='true']",
|
||||
".gev-segment[aria-checked='true']",
|
||||
);
|
||||
shares(
|
||||
'.ui-segmented__item:hover:not(:disabled)',
|
||||
'.gev-segment:hover:not(:disabled)',
|
||||
);
|
||||
shares('.ui-segmented__item:focus-visible', '.gev-segment:focus-visible');
|
||||
shares('.ui-segmented__item:disabled', '.gev-segment:disabled');
|
||||
});
|
||||
|
||||
test('UiCloseButton wears the bare glyph look the guide’s close shares', () => {
|
||||
const rule = shares('.ui-close-button', '.gev-guide-close');
|
||||
for (const declaration of [
|
||||
/padding:\s*0;/,
|
||||
/border:\s*0;/,
|
||||
/background:\s*none;/,
|
||||
/cursor:\s*pointer;/,
|
||||
])
|
||||
assert.match(rule.body, declaration);
|
||||
});
|
||||
|
||||
test('UiSearchField owns the row and bare input both search skins drew', () => {
|
||||
const frame = ruleWith('.ui-search-field');
|
||||
assert.deepEqual(frame.selectors, ['.ui-search-field']);
|
||||
assert.match(frame.body, /display:\s*flex;/);
|
||||
assert.match(frame.body, /align-items:\s*center;/);
|
||||
const input = ruleWith('.ui-search-field__input');
|
||||
assert.deepEqual(input.selectors, ['.ui-search-field__input']);
|
||||
for (const declaration of [
|
||||
/min-width:\s*0;/,
|
||||
/background:\s*none;/,
|
||||
/border:\s*0;/,
|
||||
])
|
||||
assert.match(input.body, declaration);
|
||||
// The browser's cancel button is each skin's own: Context hides it, the
|
||||
// Layer Finder keeps it.
|
||||
assert.ok(
|
||||
!all.some((rule) =>
|
||||
rule.selectors.some((s) =>
|
||||
s.startsWith('.ui-search-field__input::-webkit-search-cancel-button'),
|
||||
),
|
||||
),
|
||||
);
|
||||
// Each declaration lives once, in the kit's rule.
|
||||
for (const [selector, kit] of [
|
||||
['.context-search', frame],
|
||||
['.layer-finder__field', frame],
|
||||
['.context-search__input', input],
|
||||
['.layer-finder__field input', input],
|
||||
]) {
|
||||
const feature = ruleWith(selector);
|
||||
for (const property of kit.body.match(/[\w-]+(?=:)/g))
|
||||
assert.doesNotMatch(
|
||||
feature.body,
|
||||
new RegExp(`(^|[\\s;])${property}:`),
|
||||
`${selector} leaves ${property} to the kit`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('UiCheckbox owns the centred row the checkbox-only labels drew', () => {
|
||||
const label = ruleWith('.ui-checkbox');
|
||||
assert.deepEqual(label.selectors, ['.ui-checkbox']);
|
||||
assert.match(label.body, /display:\s*flex;/);
|
||||
assert.match(label.body, /align-items:\s*center;/);
|
||||
// The box keeps each skin's size, margin and accent colour.
|
||||
assert.ok(
|
||||
!all.some((rule) =>
|
||||
rule.selectors.some((s) => s.startsWith('.ui-checkbox__input')),
|
||||
),
|
||||
);
|
||||
// Labels that hold only a checkbox leave the row to the kit; the Visual
|
||||
// and voice rows share their classes with buttons and other labels, so
|
||||
// theirs stay.
|
||||
for (const selector of ['.first-run-suppress', '.data-library-check']) {
|
||||
const feature = ruleWith(selector);
|
||||
for (const property of ['display', 'align-items'])
|
||||
assert.doesNotMatch(
|
||||
feature.body,
|
||||
new RegExp(`(^|[\\s;])${property}:`),
|
||||
`${selector} leaves ${property} to the kit`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('the kit’s skins load before the feature stylesheets that restyle them', () => {
|
||||
const at = (selector) => css.indexOf(selector);
|
||||
for (const [kit, feature] of [
|
||||
['.ui-chip,', '.gev-voice-card-chip {'],
|
||||
['.ui-empty,', '.scene-shot-empty {'],
|
||||
['.ui-empty,', '.recent-imagery-readout .ri-strip-empty {'],
|
||||
['.ui-empty,', '#space-mission-panel-host .space-mission-roster-empty {'],
|
||||
['.ui-button--icon,', '#command-dock .panel-collapse-btn'],
|
||||
['.ui-close-button,', '.data-toggle-chip {'],
|
||||
['.ui-close-button,', '.geo-import-action {'],
|
||||
['.ui-close-button,', '.panel-surface-control {'],
|
||||
['.ui-close-button,', '.gev-voice-card-dismiss {'],
|
||||
['.ui-close-button,', '.bhote-event-icon-btn {'],
|
||||
['.ui-close-button,', '.entity-card__close {'],
|
||||
['.ui-close-button,', '.context-search__clear {'],
|
||||
['.ui-close-button,', '.key-setup-close {'],
|
||||
['.ui-close-button,', '.cctv-popup__close {'],
|
||||
['.ui-close-button,', '.view-context__live-off {'],
|
||||
['.ui-close-button,', '.gev-guide-close {'],
|
||||
['.ui-search-field {', '.context-search {'],
|
||||
['.ui-search-field {', '.layer-finder__field {'],
|
||||
['.ui-search-field__input {', '.context-search__input {'],
|
||||
['.ui-search-field__input {', '.layer-finder__field input {'],
|
||||
['.ui-checkbox {', '.pp-toggle-btn {'],
|
||||
['.ui-checkbox {', '.gev-voice-preference {'],
|
||||
['.ui-checkbox {', '.data-library-check {'],
|
||||
['.ui-checkbox {', '.first-run-suppress {'],
|
||||
]) {
|
||||
assert.ok(
|
||||
at(kit) >= 0 && at(feature) > at(kit),
|
||||
`${kit} loads before ${feature}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('feature rules over a kit skin keep the type they inherit', () => {
|
||||
// The chip and empty skins set a font and colour; these feature surfaces
|
||||
// inherit theirs from the card or strip around them.
|
||||
for (const [selector, property] of [
|
||||
['.gev-voice-card-chip', /font:\s*inherit/],
|
||||
['.scene-shot-empty', /font:\s*inherit/],
|
||||
['.recent-imagery-readout .ri-strip-empty', /font:\s*inherit/],
|
||||
['.recent-imagery-readout .ri-strip-empty', /color:\s*inherit/],
|
||||
])
|
||||
assert.ok(
|
||||
all.some(
|
||||
(rule) => rule.selectors.includes(selector) && property.test(rule.body),
|
||||
),
|
||||
`${selector} keeps ${property}`,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
// The Omnibar's buttons and Material glyphs are the kit's: its template
|
||||
// hand-writes no <button> and no Material Symbols span. Its two inline SVG
|
||||
// glyphs (the mic and the chat row's bubble) are not Material symbols the
|
||||
// page loads, so they stay as they are drawn.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
const source = readFileSync(
|
||||
new URL('../views/panels/Omnibar.vue', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
/** The template block: everything outside script and style. */
|
||||
const template = source.replace(/<(script|style)\b[\s\S]*?<\/\1\s*>/g, '');
|
||||
|
||||
test('the Omnibar hand-writes no button; each is a UiButton', () => {
|
||||
assert.deepEqual(template.match(/<button\b/gi) ?? [], []);
|
||||
assert.equal(template.match(/<UiButton\b/g)?.length, 2);
|
||||
});
|
||||
|
||||
test('the Omnibar hand-writes no Material glyph; each is a UiIcon', () => {
|
||||
assert.deepEqual(template.match(/material-symbols-outlined/g) ?? [], []);
|
||||
const icons = template.match(/<UiIcon\b[^>]*>/g) ?? [];
|
||||
assert.equal(icons.length, 3);
|
||||
// Without it the kit writes an 18px size that beats the Omnibar's own rules.
|
||||
for (const icon of icons) assert.match(icon, /:size="null"/);
|
||||
});
|
||||
|
||||
test('the only inline SVG glyphs are the mic and the chat row bubble', () => {
|
||||
const svgs = [...template.matchAll(/<svg\b[\s\S]*?<\/svg\s*>/g)].map(
|
||||
(m) => m[0],
|
||||
);
|
||||
assert.equal(svgs.length, 2);
|
||||
assert.match(svgs[0], /<rect x="9" y="3" width="6" height="11" rx="3" \/>/);
|
||||
assert.match(svgs[1], /class="omnibar-item-icon"/);
|
||||
assert.match(svgs[1], /<path d="M4 5h16v11H9l-5 4z" \/>/);
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
// The welcome card's buttons and Material glyphs are the kit's: its template
|
||||
// hand-writes no <button> and no Material Symbols span, and its one box is a
|
||||
// UiCheckbox. Its two inline SVGs (God mode's globe and its callouts) are
|
||||
// drawings, not glyphs, and its outbound links stay links.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
const source = readFileSync(
|
||||
new URL('../views/WelcomeView.vue', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
/** The template block: everything outside script and style. */
|
||||
const template = source.replace(/<(script|style)\b[\s\S]*?<\/\1\s*>/g, '');
|
||||
|
||||
test('the welcome card hand-writes no button; each is a UiButton', () => {
|
||||
assert.deepEqual(template.match(/<button\b/gi) ?? [], []);
|
||||
// SKIP, the three start tiles, BROWSE STORIES, BACK and the main action.
|
||||
assert.equal(template.match(/<UiButton\b/g)?.length, 7);
|
||||
assert.equal(template.match(/<UiCheckbox\b/g)?.length, 1);
|
||||
});
|
||||
|
||||
test('the welcome card hand-writes no Material glyph; each is a UiIcon', () => {
|
||||
assert.deepEqual(template.match(/material-symbols-outlined/g) ?? [], []);
|
||||
const icons = template.match(/<UiIcon\b[^>]*>/g) ?? [];
|
||||
// The three tiles, the three tips, the Stories card and the main arrow.
|
||||
assert.equal(icons.length, 8);
|
||||
// Without it the kit writes an 18px size that beats first-run.css's rules.
|
||||
for (const icon of icons) assert.match(icon, /:size="null"/);
|
||||
});
|
||||
|
||||
test('the only inline SVGs are God mode preview drawings', () => {
|
||||
const svgs = [...template.matchAll(/<svg\b[^>]*>/g)].map((m) => m[0]);
|
||||
assert.equal(svgs.length, 2);
|
||||
assert.match(svgs[0], /class="first-run-globe"/);
|
||||
assert.match(svgs[1], /class="first-run-callouts"/);
|
||||
});
|
||||
@@ -50,6 +50,9 @@ export class LayerBindings {
|
||||
get _contextControls() {
|
||||
return this.readControls()._contextControls;
|
||||
}
|
||||
get _spaceMissionsControls() {
|
||||
return this.readControls()._spaceMissionsControls;
|
||||
}
|
||||
get _cctvControls() {
|
||||
return this.readControls()._cctvControls;
|
||||
}
|
||||
@@ -254,6 +257,7 @@ export class LayerBindings {
|
||||
this._dataManagerUnsubscribe = null;
|
||||
}
|
||||
this._contextControls.connect(this._dataManager);
|
||||
this._spaceMissionsControls?.connect(this._dataManager);
|
||||
if (typeof this._dataManager?.subscribe === 'function') {
|
||||
this._dataManagerUnsubscribe = this._dataManager.subscribe((change) => {
|
||||
this._feedback._loadingFeedbackEvent = change;
|
||||
@@ -319,6 +323,7 @@ export class LayerBindings {
|
||||
this._directionsShellModule?.attachShellServices?.(null);
|
||||
this._directionsShellModule = null;
|
||||
this._dataManager = null;
|
||||
this._spaceMissionsControls?.connect(null);
|
||||
this._connectWeatherCamera();
|
||||
}
|
||||
}
|
||||
+72
-15
@@ -5,8 +5,30 @@ import {
|
||||
resolvePanelStackCorridor,
|
||||
} from '../panelStackLayout.js';
|
||||
import { measurePanelNaturalHeight } from './panelMeasurement.js';
|
||||
import { bandBesideMidpointObstacles } from './panelRailGeometry.js';
|
||||
import { settleSideAccordion } from './panelAccordion.js';
|
||||
|
||||
/**
|
||||
* Whether the desktop Omnibar dock is laid out, by the condition
|
||||
* omnibar-dock.css lays it out by: the bar and the voice control in the
|
||||
* dock, outside the phone layout, the cockpit, playback, clean view and
|
||||
* recording.
|
||||
*/
|
||||
const DOCK_OFF = [
|
||||
'mobile-shell',
|
||||
'cockpit-mode',
|
||||
'scene-playback-mode',
|
||||
'ui-clean-view',
|
||||
'recording-mode',
|
||||
];
|
||||
function desktopOmnibarDock(documentRef) {
|
||||
if (!documentRef?.getElementById?.('gev-omnibar')) return false;
|
||||
const body = documentRef.body;
|
||||
if (DOCK_OFF.some((name) => body?.classList?.contains?.(name))) return false;
|
||||
const voice = documentRef.getElementById('gev-voice-control');
|
||||
return Boolean(voice) && voice.parentElement?.id === 'command-dock';
|
||||
}
|
||||
|
||||
/**
|
||||
* Measure and place the left panel rail for one synchronous layout pass.
|
||||
* The caller owns scheduling, obstacle selection, disclosure preferences and
|
||||
@@ -93,10 +115,12 @@ export function layoutLeftPanelRail({
|
||||
const baseTop = viewportHeight * 0.26;
|
||||
const baseBottomInset = viewportHeight * 0.04;
|
||||
const safeGap = viewportHeight * 0.012;
|
||||
let obstacleSafeTop = viewportHeight * 0.04;
|
||||
const topInset = viewportHeight * 0.04;
|
||||
let obstacleSafeTop = topInset;
|
||||
let safeTop = baseTop;
|
||||
let safeBottom = viewportHeight - baseBottomInset;
|
||||
const bottomObstacles = [];
|
||||
const inLane = [];
|
||||
|
||||
for (const obstacle of obstacles) {
|
||||
if (stack.contains(obstacle)) continue;
|
||||
@@ -115,10 +139,18 @@ export function layoutLeftPanelRail({
|
||||
if (hiddenByAncestor) continue;
|
||||
const rect = obstacle.getBoundingClientRect();
|
||||
if (rect.width <= 0 || rect.height <= 0) continue;
|
||||
const overlapsHorizontally =
|
||||
rect.right > stackRect.left && rect.left < stackRect.right;
|
||||
// The centered controls can enter the stack's transparent outer gutter.
|
||||
// Only constrain the lane if they reach an expanded panel itself, whose
|
||||
// actual bounds also include the edge-rail offset.
|
||||
const lanes = ['world-timeline', 'gev-voice-control'].includes(obstacle.id)
|
||||
? laidOutPanels.map((panel) => panel.getBoundingClientRect())
|
||||
: [stackRect];
|
||||
const overlapsHorizontally = lanes.some(
|
||||
(lane) => rect.right > lane.left && rect.left < lane.right,
|
||||
);
|
||||
if (!overlapsHorizontally) continue;
|
||||
|
||||
inLane.push(rect);
|
||||
if (rect.top < baseTop && rect.bottom <= viewportHeight * 0.5) {
|
||||
const obstacleBottom = rect.bottom + safeGap;
|
||||
obstacleSafeTop = Math.max(obstacleSafeTop, obstacleBottom);
|
||||
@@ -127,6 +159,25 @@ export function layoutLeftPanelRail({
|
||||
bottomObstacles.push({ top: rect.top });
|
||||
}
|
||||
}
|
||||
// Obstacles across the midpoint (common in short windows) put the panels
|
||||
// on whichever side of them has more room, and the panels may use all of
|
||||
// it, above the corridor's usual top too; with no room on either side the
|
||||
// obstacles are read as before.
|
||||
const beside = bandBesideMidpointObstacles({
|
||||
midpoint: viewportHeight * 0.5,
|
||||
top: topInset,
|
||||
bottom: safeBottom,
|
||||
obstacles: inLane,
|
||||
gap: safeGap,
|
||||
// A side thinner than this holds no usable panel.
|
||||
minimum: viewportHeight * 0.08,
|
||||
});
|
||||
if (beside) {
|
||||
obstacleSafeTop = beside.top;
|
||||
safeTop = beside.top;
|
||||
bottomObstacles.length = 0;
|
||||
bottomObstacles.push({ top: beside.bottom + safeGap });
|
||||
}
|
||||
safeBottom = resolveLeftStackBottomBoundary({
|
||||
baseBottom: safeBottom,
|
||||
obstacles: bottomObstacles,
|
||||
@@ -220,11 +271,20 @@ export function layoutLeftPanelRail({
|
||||
const tailLayoutBottom = tailLayoutTop + tailRequiredHeight;
|
||||
const tailAvailableHeight = Math.max(0, obstacleSafeBottom - obstacleSafeTop);
|
||||
const tailTolerance = wasTail ? stabilityBand : -stabilityBand;
|
||||
// Data Layers has a scrollable list and a fixed footer. Give it the full
|
||||
// desktop lane while short control panels keep their natural height.
|
||||
const fillDataLayers =
|
||||
exclusive &&
|
||||
expandedPanels.length === 1 &&
|
||||
expandedPanels[0].id === 'data-panel' &&
|
||||
desktopOmnibarDock(documentRef);
|
||||
const shouldTail =
|
||||
!fillDataLayers &&
|
||||
expandedPanels.length > 0 &&
|
||||
tailLayoutTop >= obstacleSafeTop - tailTolerance &&
|
||||
tailLayoutBottom <= obstacleSafeBottom + tailTolerance;
|
||||
const shouldFocus = exceedsCenteredCorridor && !shouldTail;
|
||||
const shouldFocus =
|
||||
fillDataLayers || (exceedsCenteredCorridor && !shouldTail);
|
||||
// Focus mode owns the lane, so let every expanded panel share the full
|
||||
// obstacle-safe corridor. Tail/normal layouts keep the balanced
|
||||
// viewport centering used for compact accordion stacks.
|
||||
@@ -250,10 +310,12 @@ export function layoutLeftPanelRail({
|
||||
rowGap * Math.max(0, expandedPanels.length - 1),
|
||||
)
|
||||
: naturalExpandedHeight;
|
||||
const allocatedExpandedHeights = allocatePanelStackHeights({
|
||||
naturalHeights: naturalExpandedHeights,
|
||||
availableHeight: expandedAvailableHeight,
|
||||
});
|
||||
const allocatedExpandedHeights = fillDataLayers
|
||||
? [expandedAvailableHeight]
|
||||
: allocatePanelStackHeights({
|
||||
naturalHeights: naturalExpandedHeights,
|
||||
availableHeight: expandedAvailableHeight,
|
||||
});
|
||||
const autoCollapseIndices = hud.visible
|
||||
? panelStackAutoCollapseIndices({
|
||||
naturalHeights: naturalExpandedHeights,
|
||||
@@ -278,21 +340,16 @@ export function layoutLeftPanelRail({
|
||||
stack.style.setProperty('--left-stack-safe-bottom', bottomValue);
|
||||
}
|
||||
// The rail stays where the resting stack puts it; only the panels move.
|
||||
// A theme that pins the stack's top (Cyber) leaves nothing to offset.
|
||||
const topPinned =
|
||||
getComputedStyle(stack)
|
||||
.getPropertyValue?.('--panel-stack-top-pinned')
|
||||
?.trim() === '1';
|
||||
// The stack itself rises by the lift below, by a different amount for a
|
||||
// tall panel than at rest; the rail takes up the difference.
|
||||
const lift = (top) => Math.min(0, obstacleSafeTop - top);
|
||||
const railOffset = `${(topPinned ? 0 : safeTop + lift(safeTop) - layoutTop - lift(layoutTop)).toFixed(1)}px`;
|
||||
const railOffset = `${(safeTop + lift(safeTop) - layoutTop - lift(layoutTop)).toFixed(1)}px`;
|
||||
if (stack.style.getPropertyValue('--panel-rail-offset') !== railOffset) {
|
||||
stack.style.setProperty('--panel-rail-offset', railOffset);
|
||||
}
|
||||
// How far the column can rise before it meets the HUD readout, so the rail
|
||||
// and any open panel sit just under it, whether or not a panel is open.
|
||||
const railLift = `${(topPinned ? 0 : lift(layoutTop)).toFixed(1)}px`;
|
||||
const railLift = `${lift(layoutTop).toFixed(1)}px`;
|
||||
if (stack.style.getPropertyValue('--panel-rail-lift') !== railLift) {
|
||||
stack.style.setProperty('--panel-rail-lift', railLift);
|
||||
}
|
||||
|
||||
@@ -46,6 +46,7 @@ export class LocationControls {
|
||||
onCity,
|
||||
onPoi,
|
||||
onSearch,
|
||||
onSearchEdit,
|
||||
onReset,
|
||||
publish,
|
||||
doc,
|
||||
@@ -74,6 +75,7 @@ export class LocationControls {
|
||||
poi: t('Landmark: --'),
|
||||
};
|
||||
this.searchError = null;
|
||||
this.searchOrigin = 'dock';
|
||||
// The search field: whether it is open, and whether a lookup runs.
|
||||
this.searchExpanded = Boolean(searchExpanded);
|
||||
this.searching = false;
|
||||
@@ -96,12 +98,16 @@ export class LocationControls {
|
||||
onPoi(cityId, index);
|
||||
});
|
||||
this.bind(elements.search, 'keydown', (event) => {
|
||||
if (event.key === 'Enter') void onSearch(elements.search.value);
|
||||
if (event.key === 'Enter')
|
||||
void this.search(elements.search.value, { origin: 'dock' });
|
||||
});
|
||||
// Typing corrects a failed query; closing the field (which empties it) drops its error.
|
||||
this.bind(elements.search, 'input', () => onSearchEdit?.());
|
||||
this.bind(elements.search, 'input', () => {
|
||||
if (this.searchOrigin === 'dock') onSearchEdit?.();
|
||||
});
|
||||
this.bind(elements.search, 'blur', () => {
|
||||
if (!elements.search.value) onSearchEdit?.();
|
||||
if (this.searchOrigin === 'dock' && !elements.search.value)
|
||||
onSearchEdit?.();
|
||||
});
|
||||
this.present();
|
||||
}
|
||||
@@ -138,9 +144,29 @@ export class LocationControls {
|
||||
searchError: this.searchError,
|
||||
searchExpanded: this.searchExpanded,
|
||||
searching: this.searching,
|
||||
searchOrigin: this.searchOrigin,
|
||||
orbit: this.orbit && { ...this.orbit },
|
||||
};
|
||||
}
|
||||
/** Search through the same lifecycle as the location field. */
|
||||
search(query, { origin = 'omnibar' } = {}) {
|
||||
if (this.destroyed || !String(query || '').trim()) return false;
|
||||
this._requestedSearchOrigin = origin;
|
||||
// Beginning navigation synchronously settles the previous lookup. That
|
||||
// handoff must not clear or blur the draft just submitted by either field.
|
||||
this._startingSearch = true;
|
||||
try {
|
||||
return this.onSearch(query);
|
||||
} finally {
|
||||
this._startingSearch = false;
|
||||
this._requestedSearchOrigin = null;
|
||||
}
|
||||
}
|
||||
/** Editing an external query clears its prior lookup error. */
|
||||
editSearch() {
|
||||
if (!this.destroyed && this.searchOrigin === 'omnibar')
|
||||
this.onSearchEdit?.();
|
||||
}
|
||||
/** A city pill was clicked. */
|
||||
chooseCity(id) {
|
||||
if (!this.destroyed) this.onCity(id);
|
||||
@@ -233,6 +259,8 @@ export class LocationControls {
|
||||
/** Mark the search field while a lookup runs. */
|
||||
setSearching(active) {
|
||||
if (this.destroyed) return;
|
||||
if (active && this._requestedSearchOrigin)
|
||||
this.searchOrigin = this._requestedSearchOrigin;
|
||||
this.searching = Boolean(active);
|
||||
this.present();
|
||||
}
|
||||
@@ -243,6 +271,10 @@ export class LocationControls {
|
||||
settleSearch({ keepQuery = false } = {}) {
|
||||
if (this.destroyed) return;
|
||||
this.searching = false;
|
||||
if (this._startingSearch || this.searchOrigin === 'omnibar') {
|
||||
this.present();
|
||||
return;
|
||||
}
|
||||
if (!keepQuery) {
|
||||
this.closeSearch();
|
||||
return;
|
||||
|
||||
@@ -108,6 +108,7 @@ test('the tray presents its cities, empty status and no landmarks at first', ()
|
||||
searchError: null,
|
||||
searchExpanded: false,
|
||||
searching: false,
|
||||
searchOrigin: 'dock',
|
||||
orbit: null,
|
||||
});
|
||||
f.controls.highlightCity('b');
|
||||
|
||||
@@ -101,6 +101,8 @@ export class LocationSearch {
|
||||
destination: { ...destination },
|
||||
};
|
||||
this.channel.publish(change('found'));
|
||||
// Found and still the current search: a plan may go on.
|
||||
return current() && !controller.signal.aborted;
|
||||
} else {
|
||||
this.onMissing?.();
|
||||
if (!current() || controller.signal.aborted) return;
|
||||
|
||||
@@ -6,14 +6,14 @@ import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createPinia } from 'pinia';
|
||||
import { createApp, h, nextTick } from 'vue';
|
||||
import { useContextStore } from './stores/context.js';
|
||||
import { useSpaceMissionsStore } from './stores/spaceMissions.js';
|
||||
import MissionDetail from './views/panels/MissionDetail.vue';
|
||||
import MissionRoster from './views/panels/MissionRoster.vue';
|
||||
|
||||
function fixture(t) {
|
||||
document.body.replaceChildren();
|
||||
const scroller = document.body.appendChild(document.createElement('div'));
|
||||
scroller.className = 'global-context-panel-inner';
|
||||
scroller.className = 'space-missions-panel-inner';
|
||||
const host = scroller.appendChild(document.createElement('div'));
|
||||
const pinia = createPinia();
|
||||
const app = createApp({
|
||||
@@ -21,13 +21,13 @@ function fixture(t) {
|
||||
}).use(pinia);
|
||||
app.mount(host);
|
||||
t.after(() => app.unmount());
|
||||
const store = useContextStore(pinia);
|
||||
const store = useSpaceMissionsStore(pinia);
|
||||
const calls = [];
|
||||
const record =
|
||||
(name) =>
|
||||
(...args) =>
|
||||
calls.push([name, ...args]);
|
||||
store.connectMissions({
|
||||
store.connect({
|
||||
selectMissionAt: record('select'),
|
||||
selectPreviousMission: record('previous'),
|
||||
selectNextMission: record('next'),
|
||||
@@ -44,7 +44,7 @@ function fixture(t) {
|
||||
});
|
||||
const $ = (selector) => document.querySelector(selector);
|
||||
const publish = async (view) => {
|
||||
store.publishMissions(view);
|
||||
store.publish(view);
|
||||
await nextTick();
|
||||
await nextTick();
|
||||
};
|
||||
@@ -325,7 +325,7 @@ test('the replay controls follow the layer and call its commands', async (t) =>
|
||||
]);
|
||||
});
|
||||
|
||||
test('each newly presented selection returns the Context panel to the top', async (t) => {
|
||||
test('each newly presented selection returns the Space Missions panel to the top', async (t) => {
|
||||
const { publish, scroller } = fixture(t);
|
||||
scroller.scrollTop = 120;
|
||||
await publish({ roster: null, mission: mission({ scrollRequest: 4 }) });
|
||||
|
||||
+23
-2
@@ -30,6 +30,7 @@ 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']),
|
||||
missions: Object.freeze(['space-missions-panel']),
|
||||
search: Object.freeze(['location-bar']),
|
||||
more: Object.freeze(['control-panel', 'pp-toggles']),
|
||||
});
|
||||
@@ -38,6 +39,11 @@ 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: 'missions',
|
||||
label: msg('Space Missions'),
|
||||
icon: 'rocket_launch',
|
||||
}),
|
||||
Object.freeze({ sheet: 'search', label: msg('Search'), icon: 'search' }),
|
||||
Object.freeze({ sheet: 'more', label: msg('More'), icon: 'more_horiz' }),
|
||||
]);
|
||||
@@ -142,6 +148,7 @@ export function initMobileShell({
|
||||
.map(element)
|
||||
.filter(Boolean);
|
||||
const dock = element('command-dock');
|
||||
const missionsPanel = element('space-missions-panel');
|
||||
const shown = (node) =>
|
||||
node && globalThis.getComputedStyle?.(node).display !== 'none';
|
||||
|
||||
@@ -254,7 +261,9 @@ export function initMobileShell({
|
||||
const setSheet = (requested) => {
|
||||
swipe = null;
|
||||
if (!body.classList.contains(MOBILE_SHELL_CLASS)) return;
|
||||
const sheet = sheetBlocked(body) ? null : requested;
|
||||
const unavailableMissions =
|
||||
requested === 'missions' && missionsPanel?.hidden;
|
||||
const sheet = sheetBlocked(body) || unavailableMissions ? null : requested;
|
||||
const previous = currentSheetOf(body);
|
||||
if (previous === sheet) return;
|
||||
if (!previous) {
|
||||
@@ -487,9 +496,21 @@ export function initMobileShell({
|
||||
|
||||
if (typeof MutationObserverImpl === 'function') {
|
||||
const observer = new MutationObserverImpl(() => {
|
||||
if (currentSheetOf(body) && sheetBlocked(body)) setSheet(null);
|
||||
const sheet = currentSheetOf(body);
|
||||
if (!sheet) return;
|
||||
if (sheet === 'missions' && missionsPanel?.hidden) {
|
||||
returnFocus = tabFor('layers') ?? returnFocus;
|
||||
setSheet(null);
|
||||
} else if (sheetBlocked(body)) {
|
||||
setSheet(null);
|
||||
}
|
||||
});
|
||||
observer.observe(body, { attributes: true, attributeFilter: ['class'] });
|
||||
if (missionsPanel)
|
||||
observer.observe(missionsPanel, {
|
||||
attributes: true,
|
||||
attributeFilter: ['hidden'],
|
||||
});
|
||||
removers.push(() => observer.disconnect());
|
||||
}
|
||||
|
||||
|
||||
@@ -903,12 +903,11 @@ test('manual Context opens the existing transaction without disabling the tracke
|
||||
}
|
||||
});
|
||||
|
||||
test('manual Context respects Space Missions, busy transitions, missing tracks and disposal', async () => {
|
||||
test('manual Context respects an active mode, busy transitions, missing tracks and disposal', async () => {
|
||||
for (const state of [
|
||||
{ mode: 'space-missions' },
|
||||
{ mode: 'flights' },
|
||||
{ changing: true },
|
||||
{ entering: 'space-missions' },
|
||||
{ entering: 'flights' },
|
||||
{ noTrack: true },
|
||||
{ disposed: true },
|
||||
{ sheet: 'layers' },
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
// What Enter does in the Omnibar before a row is chosen with the keyboard:
|
||||
// the one rule, in one place. The rows come from src/ui/omnibarRows.js; the
|
||||
// text this rule reads is the line after readLine (omnibarRows.js).
|
||||
//
|
||||
// Enter performs an action (a plan, a layer switch, a command, Ask GEV) only
|
||||
// when the line asks for it outright:
|
||||
// (a) the action's own clause starts with a verb from ACTION_VERB (one
|
||||
// list, in omnibarIntent.js): "show flights", "play radio in Tokyo",
|
||||
// "go to Austin and show flights". A verb inside a place's name asks
|
||||
// for nothing ("radio near Clear Lake");
|
||||
// (b) or the line is a command's exact label, alone or after ">" ("North
|
||||
// up", "> Clear all layers"); a command row runs on nothing else;
|
||||
// (c) or, for Ask GEV, it is a real question (isRealQuestion).
|
||||
// A whole layer name with a place after near, in, around, over, across or
|
||||
// above ("flights near Tokyo"; not "of" or "at": "Planes of Fame") asks
|
||||
// outright too. Keywords without a verb ask for nothing, however many
|
||||
// clauses they fill ("Fire and Rain", "noir and cctv near austin"). Otherwise
|
||||
// the place row is the default, and any plan or command is offered after
|
||||
// it. A guide found by forgiving a typo, or on a line written as a title
|
||||
// ("How To Train Your Dragon"), is offered, never run. Some actions need
|
||||
// more:
|
||||
// - sound (the Radio layer and radio steps), clearing the map, closing
|
||||
// panels and the cockpit need (a) or (b);
|
||||
// - the microphone, sharing the view, resetting it and the globe view
|
||||
// need (b);
|
||||
// - a layer row runs only when the line names that layer before any
|
||||
// other (the row's `best`): "show flights" with Flights already on
|
||||
// offers Flights, never Military Flights.
|
||||
// Only the first row can be the default, and the pointer never makes one:
|
||||
// a hovered row is chosen by a click, and the arrow keys choose any row.
|
||||
|
||||
import { hasActionVerb, isRealQuestion } from './omnibarIntent.js';
|
||||
|
||||
/**
|
||||
* Words that are both the name of a bundled place (wikidata_cities or
|
||||
* wikidata_places) and, alone, a command, style or layer word. Typed alone
|
||||
* they search the place first and offer the switch second. Found by sweeping
|
||||
* every bundled name through the Omnibar (see docs/CURRENT-STATE.md); a test
|
||||
* checks each is still a bundled name.
|
||||
*/
|
||||
export const PLACE_WORDS = new Set([
|
||||
'bike',
|
||||
'hurricane',
|
||||
'normal',
|
||||
'rain',
|
||||
'ski',
|
||||
'street',
|
||||
'thermal',
|
||||
]);
|
||||
|
||||
/** Whether the whole line is one of PLACE_WORDS, in any case. */
|
||||
export function isPlaceWord(text) {
|
||||
return PLACE_WORDS.has(
|
||||
String(text || '')
|
||||
.trim()
|
||||
.toLowerCase(),
|
||||
);
|
||||
}
|
||||
|
||||
/** Layers whose switching on starts sound. */
|
||||
export const SOUND_LAYERS = new Set(['radio']);
|
||||
/** Camera moves that only their exact label asks for (b). */
|
||||
const NAMED_ONLY = new Set(['share', 'reset', 'zoom_to_globe']);
|
||||
|
||||
/**
|
||||
* Whether a plan's steps ask for themselves. Verbs are read per clause: the
|
||||
* parser marks each step whose own clause had one (`parsed.asked`), so a verb
|
||||
* inside a place's name ("radio near Clear Lake") asks for nothing.
|
||||
* @param {Array<object>} steps
|
||||
* @param {{named: boolean, parsed: object}} line
|
||||
*/
|
||||
function planAsked(steps, { named, parsed }) {
|
||||
if (named) return true;
|
||||
const asked = parsed?.asked || new Set();
|
||||
const requests = steps.filter((step) => step.kind !== 'place');
|
||||
for (const step of requests) {
|
||||
if (step.kind === 'camera' && NAMED_ONLY.has(step.act || step.name))
|
||||
return false;
|
||||
const needsVerb =
|
||||
(step.kind === 'camera' && step.act === 'clear') ||
|
||||
(step.kind === 'panel' && step.action === 'close') ||
|
||||
step.kind === 'cockpit' ||
|
||||
step.kind === 'radio' ||
|
||||
(step.kind === 'layer' && SOUND_LAYERS.has(step.layer.id));
|
||||
if (needsVerb && !asked.has(step)) return false;
|
||||
}
|
||||
if (!requests.length) return false;
|
||||
// Every request asked for by a verb in its own clause. Keywords alone ask
|
||||
// for nothing, however many clauses they fill ("Fire and Rain", "Noir
|
||||
// and Thermal", "New York City noir").
|
||||
if (requests.every((step) => asked.has(step))) return true;
|
||||
// "flights near Tokyo": a whole layer name, and a place after near/in.
|
||||
const [only] = requests;
|
||||
// Only that one request: a bare keyword beside it ("flights near Austin
|
||||
// and noir") is not asked for.
|
||||
return (
|
||||
requests.length === 1 &&
|
||||
only.kind === 'layer' &&
|
||||
only.layer.exact !== false &&
|
||||
parsed?.placeFrom === 'near'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether Enter may run this row without it being chosen.
|
||||
* @param {object} item A row.
|
||||
* @param {string} text The typed line.
|
||||
* @param {object} parsed The line as parseOmnibar read it.
|
||||
* @param {{named: boolean}} context `named`: the line is a command's exact
|
||||
* label.
|
||||
*/
|
||||
export function mayRunOnEnter(item, text, parsed, context) {
|
||||
const verb = hasActionVerb(text);
|
||||
switch (item?.kind) {
|
||||
case 'guide':
|
||||
// A walk found by a typo, or a line written as a title ("How To Train
|
||||
// Your Dragon"), is offered, never run.
|
||||
return !item.loose && !item.titled;
|
||||
case 'place':
|
||||
// A row only for picking ("Search … anyway") never runs on Enter.
|
||||
return !item.explicit;
|
||||
case 'count-show':
|
||||
case 'entity':
|
||||
case 'view-ask':
|
||||
case 'sel-fly':
|
||||
case 'sel-follow':
|
||||
case 'sel-cockpit':
|
||||
case 'sel-ask':
|
||||
case 'sel-close':
|
||||
return true;
|
||||
case 'ask':
|
||||
return isRealQuestion(text);
|
||||
case 'layer':
|
||||
return (
|
||||
Boolean(item.best) &&
|
||||
(!SOUND_LAYERS.has(item.id) || !item.enabled || verb || context.named)
|
||||
);
|
||||
case 'mic':
|
||||
return Boolean(item.named);
|
||||
case 'open-draw':
|
||||
return verb;
|
||||
case 'plan':
|
||||
// A plan the whole line asked for in so many words ("hide everything
|
||||
// except flights") runs.
|
||||
if (item.asked) return true;
|
||||
// A command row runs on its exact label only; a verb that merely
|
||||
// lists it ("hide", "turn off") offers it.
|
||||
if (item.command) return Boolean(item.named);
|
||||
return planAsked(item.steps || [], { named: context.named, parsed });
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The rows in the order shown: when the first may not run on Enter, the
|
||||
* first place row moves ahead of it, so Enter searches the place.
|
||||
*/
|
||||
export function orderForEnter(items, text, parsed, context) {
|
||||
const first = items[0];
|
||||
// A question without "?" still offers a place first when there is one.
|
||||
const askFirst = first?.kind === 'ask' && !String(text).includes('?');
|
||||
if (!first || (!askFirst && mayRunOnEnter(first, text, parsed, context)))
|
||||
return items;
|
||||
const place = items.findIndex((item) => item.kind === 'place');
|
||||
if (place <= 0) return items;
|
||||
return [items[place], ...items.slice(0, place), ...items.slice(place + 1)];
|
||||
}
|
||||
|
||||
/** The row Enter runs before one is chosen with the keyboard, or -1. */
|
||||
export function enterDefault(items, text, parsed, context) {
|
||||
const line = String(text || '').trim();
|
||||
if (!line || /^>\s*$/.test(line)) return -1;
|
||||
return items.length && mayRunOnEnter(items[0], line, parsed, context)
|
||||
? 0
|
||||
: -1;
|
||||
}
|
||||
@@ -0,0 +1,718 @@
|
||||
// "Show me how": a short guided walk through the real controls. Each step
|
||||
// spotlights the control to press, explains it in one line, and waits until
|
||||
// the visitor presses it (or the step is already done), then moves on. It
|
||||
// does not press the controls the walk is about. A layer walk clears
|
||||
// layer-list filter chips only when they would hide the row it is about;
|
||||
// steps scroll their target into view.
|
||||
//
|
||||
// The callout is a non-modal dialog: focus moves to it when a walk starts,
|
||||
// the rest of the page stays usable (the walk is about pressing it), Escape
|
||||
// ends the walk and no other key is taken.
|
||||
//
|
||||
// Recipes are data: any data layer gets one from its id, and the main
|
||||
// features (styles, HUD, compass, tilt, globe view, share, clear) have their
|
||||
// own. The walk works the same for all of them.
|
||||
|
||||
import { h, render as renderVue } from 'vue';
|
||||
import { t } from '../i18n/index.js';
|
||||
import { EXCLUSIVE_SURFACE_CLASSES } from '../exclusiveSurfaces.js';
|
||||
import { LABEL_LAYERS } from './contextLayerTabs.js';
|
||||
import OmnibarGuide from './views/panels/OmnibarGuide.vue';
|
||||
|
||||
const LEFT_RAIL = '.ui-rail--left .ui-rail__item';
|
||||
const RIGHT_RAIL = '.ui-rail--right .ui-rail__item';
|
||||
const MOBILE_PANELS = {
|
||||
'data-panel': 'layers',
|
||||
'pp-toggles': 'more',
|
||||
'global-context-panel': 'context',
|
||||
};
|
||||
const SEARCH_BUTTON = '#layer-finder-search-btn';
|
||||
const SEARCH_INPUT = '#layer-finder-input';
|
||||
const FILTER_BUTTON = '#data-panel .layer-finder__filter button';
|
||||
const AIRCRAFT_LAYERS = new Set(['flights', 'military', 'local-adsb']);
|
||||
/** Above this altitude (metres) the camera already shows the globe. */
|
||||
const GLOBE_ALTITUDE = 2_500_000;
|
||||
/**
|
||||
* Layers spread wider than a street-level view, and the camera altitude
|
||||
* (metres) from which enough of them are in frame. Traffic layers spread over
|
||||
* a region: aircraft cruise kilometres up across hundreds of kilometres, so
|
||||
* from a low, tilted camera almost none are in view. Global layers read best
|
||||
* from the globe view.
|
||||
*/
|
||||
const VIEW_ALTITUDE = Object.freeze({
|
||||
flights: 150_000,
|
||||
military: 400_000,
|
||||
'local-adsb': 60_000,
|
||||
'ais-live-vessels': 120_000,
|
||||
satellites: GLOBE_ALTITUDE,
|
||||
'rocket-launches': GLOBE_ALTITUDE,
|
||||
'weather-cyclones': GLOBE_ALTITUDE,
|
||||
'telegeography-submarine-cables': GLOBE_ALTITUDE,
|
||||
earthquakes: GLOBE_ALTITUDE,
|
||||
'local-firms': GLOBE_ALTITUDE,
|
||||
'weather-satellite': GLOBE_ALTITUDE,
|
||||
});
|
||||
|
||||
const $ = (selector, doc = globalThis.document) => doc?.querySelector(selector);
|
||||
|
||||
/** The camera altitude from the share hash, the app's own record of it. */
|
||||
function cameraAltitude() {
|
||||
const alt = Number(
|
||||
new URLSearchParams(globalThis.location?.hash.slice(1) || '').get('alt'),
|
||||
);
|
||||
return Number.isFinite(alt) ? alt : 0;
|
||||
}
|
||||
|
||||
const pressed = (selector) =>
|
||||
$(selector)?.getAttribute('aria-pressed') === 'true';
|
||||
const screenIsOwned = (doc) =>
|
||||
EXCLUSIVE_SURFACE_CLASSES.some((name) => doc.body.classList.contains(name));
|
||||
|
||||
/** Steps that open a side panel from its rail, unless it is already open. */
|
||||
function openPanelSteps(rail, item, label) {
|
||||
const button = () =>
|
||||
MOBILE_PANELS[item] &&
|
||||
globalThis.document?.body.classList.contains('mobile-shell')
|
||||
? $(`#mobile-tab-bar [data-mobile-sheet="${MOBILE_PANELS[item]}"]`)
|
||||
: $(`${rail}[data-rail-item="${item}"]`);
|
||||
return [
|
||||
{
|
||||
targets: () => [button()],
|
||||
text: () => t('Open {panel}', { panel: label }),
|
||||
done: () =>
|
||||
button()?.getAttribute('aria-pressed') === 'true' ||
|
||||
button()?.getAttribute('aria-expanded') === 'true',
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/** Steps that open the Visual panel from the left rail. */
|
||||
function openVisualSteps() {
|
||||
return openPanelSteps(LEFT_RAIL, 'pp-toggles', t('Visual'));
|
||||
}
|
||||
|
||||
/** Steps that bring up a section of Context's Properties tab. */
|
||||
function propertiesSteps(section, text) {
|
||||
const pane = `#context-tab-${section}`;
|
||||
const tab = () => $('#context-tab-btn-props');
|
||||
return [
|
||||
...openPanelSteps(RIGHT_RAIL, 'global-context-panel', t('Context')),
|
||||
{
|
||||
targets: () => [tab()],
|
||||
text: () => t('Open Properties: settings for the layers that are on'),
|
||||
skip: () => !tab(),
|
||||
done: () => tab()?.getAttribute('aria-selected') === 'true',
|
||||
},
|
||||
{
|
||||
prepare: () => $(pane)?.scrollIntoView?.({ block: 'center' }),
|
||||
targets: () => [$(pane)?.closest('.context-props__section') || $(pane)],
|
||||
text,
|
||||
skip: () => !$(pane)?.offsetParent,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const rowHidden = (selector) =>
|
||||
Boolean($(selector)?.classList.contains('is-filtered'));
|
||||
const hasSearchQuery = () => Boolean($(SEARCH_INPUT)?.value.trim());
|
||||
|
||||
/**
|
||||
* The settings that change what a layer shows: its own option chips in the
|
||||
* Data layers row, then, where they apply, the Display panel's detection
|
||||
* labels and how dense they are.
|
||||
* @param {{id: string, shown: string}} layer
|
||||
*/
|
||||
export function layerSettingsGuide(layer) {
|
||||
const rowSelector = `[data-layer-id="${layer.id}"]`;
|
||||
const controls = `${rowSelector} .data-toggle-controls`;
|
||||
const chipNames = () =>
|
||||
[...(globalThis.document?.querySelectorAll(`${controls} button`) || [])]
|
||||
.map((chip) => {
|
||||
const name = chip.textContent.trim();
|
||||
const what = chip.getAttribute('title');
|
||||
// The title as translated: lowering its first letter is wrong in
|
||||
// German and other languages.
|
||||
return what ? `${name}: ${what}` : name;
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join(' · ');
|
||||
return [
|
||||
...openPanelSteps(LEFT_RAIL, 'data-panel', t('Data layers')),
|
||||
{
|
||||
prepare: () => $(rowSelector)?.scrollIntoView?.({ block: 'center' }),
|
||||
targets: () => [$(controls)],
|
||||
text: () =>
|
||||
chipNames()
|
||||
? t('{layer} options. {options}', {
|
||||
layer: layer.shown,
|
||||
options: chipNames(),
|
||||
})
|
||||
: t('{layer} options appear here once it has loaded.', {
|
||||
layer: layer.shown,
|
||||
}),
|
||||
skip: () => !$(controls),
|
||||
},
|
||||
// Labels and 3D models now sit in Context's Properties while their
|
||||
// layers are on.
|
||||
...(LABEL_LAYERS.has(layer.id)
|
||||
? propertiesSteps('labels', () =>
|
||||
t(
|
||||
'Labels tag {layer} on the map. Density sets how many are labelled; Fade and Outside set how they thin out beyond the scope.',
|
||||
{
|
||||
layer: layer.shown,
|
||||
},
|
||||
),
|
||||
)
|
||||
: []),
|
||||
...(AIRCRAFT_LAYERS.has(layer.id)
|
||||
? propertiesSteps('aircraft', () =>
|
||||
t(
|
||||
'3D models: Proximity shows them up close only, All shows every aircraft as a model.',
|
||||
),
|
||||
)
|
||||
: []),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* The walk for one data layer.
|
||||
* @param {{id: string, shown: string}} layer
|
||||
* @param {(id: string) => boolean} isEnabled
|
||||
* @param {{readAltitude?: () => number}} [options] Current camera altitude in metres.
|
||||
*/
|
||||
export function layerGuide(
|
||||
layer,
|
||||
isEnabled,
|
||||
{ readAltitude = cameraAltitude } = {},
|
||||
) {
|
||||
const rowSelector = `[data-layer-id="${layer.id}"]`;
|
||||
return [
|
||||
// The walk asks for Data layers to be opened (or skips that when it is
|
||||
// open); it closes no panel the visitor has open.
|
||||
...openPanelSteps(LEFT_RAIL, 'data-panel', t('Data layers')),
|
||||
{
|
||||
// A filter left on from before could hide the row; start from the full list.
|
||||
prepare: () => {
|
||||
if (rowHidden(rowSelector) && !hasSearchQuery()) {
|
||||
for (const chip of globalThis.document.querySelectorAll(
|
||||
'#data-panel .layer-finder__chip',
|
||||
))
|
||||
chip.click();
|
||||
}
|
||||
},
|
||||
targets: () => [$(SEARCH_BUTTON)],
|
||||
text: () =>
|
||||
t('Press search to find {layer} in the list', { layer: layer.shown }),
|
||||
skip: () => isEnabled(layer.id) || !$(SEARCH_BUTTON),
|
||||
done: () => pressed(SEARCH_BUTTON),
|
||||
},
|
||||
{
|
||||
targets: () => [$(SEARCH_INPUT)],
|
||||
text: () => t('Type {layer}', { layer: layer.shown }),
|
||||
skip: () => isEnabled(layer.id) || !$(SEARCH_INPUT),
|
||||
done: () => hasSearchQuery() && !rowHidden(rowSelector),
|
||||
},
|
||||
{
|
||||
prepare: () => $(rowSelector)?.scrollIntoView?.({ block: 'center' }),
|
||||
targets: () => [$(rowSelector), $(`${rowSelector} .data-toggle-btn`)],
|
||||
text: () => t('Turn on {layer} with its switch', { layer: layer.shown }),
|
||||
skip: () => isEnabled(layer.id),
|
||||
done: () => isEnabled(layer.id),
|
||||
},
|
||||
{
|
||||
// Too close to see them: zoom out (any way) or press the globe view.
|
||||
targets: () => [$('#reset-globe-view')],
|
||||
text: () =>
|
||||
VIEW_ALTITUDE[layer.id] >= GLOBE_ALTITUDE
|
||||
? t('{layer} are easiest to see from the globe view', {
|
||||
layer: layer.shown,
|
||||
})
|
||||
: t(
|
||||
'{layer} spread over a wide area, so few are in view this close. Zoom out, or press the globe view.',
|
||||
{
|
||||
layer: layer.shown,
|
||||
},
|
||||
),
|
||||
skip: () =>
|
||||
!VIEW_ALTITUDE[layer.id] || readAltitude() >= VIEW_ALTITUDE[layer.id],
|
||||
done: () => readAltitude() >= VIEW_ALTITUDE[layer.id],
|
||||
},
|
||||
{
|
||||
// The end: offer the settings that shape this layer.
|
||||
text: () =>
|
||||
t('{layer} is on. Want to fine-tune what it shows?', {
|
||||
layer: layer.shown,
|
||||
}),
|
||||
offer: {
|
||||
label: () => t('Show settings'),
|
||||
steps: () => layerSettingsGuide(layer),
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/** Walks for features, keyed like the omnibar's commands. */
|
||||
export const FEATURE_GUIDES = Object.freeze({
|
||||
styles: () => [
|
||||
...openVisualSteps(),
|
||||
{
|
||||
prepare: () =>
|
||||
$('.visual-presets__grid')?.scrollIntoView?.({ block: 'center' }),
|
||||
targets: () => [$('.visual-presets__grid')],
|
||||
text: () =>
|
||||
t('Pick a look: Normal, CRT, NVG, FLIR, Anime or Noir (keys 1–6)'),
|
||||
},
|
||||
],
|
||||
'map-source': () => [
|
||||
...openVisualSteps(),
|
||||
{
|
||||
prepare: () =>
|
||||
$('#pp-toggles .visual-presets')?.scrollIntoView?.({ block: 'start' }),
|
||||
targets: () => [$('#pp-toggles .visual-presets')],
|
||||
text: () =>
|
||||
t(
|
||||
'Under Map source, pick the map underneath: Google 3D, Bing, Esri or OpenStreetMap',
|
||||
),
|
||||
},
|
||||
],
|
||||
hud: () => [
|
||||
...openVisualSteps(),
|
||||
{
|
||||
prepare: () => $('#hud-toggle')?.scrollIntoView?.({ block: 'center' }),
|
||||
targets: () => [$('#hud-toggle')],
|
||||
text: () =>
|
||||
t('Switch the HUD on or off here; Layout picks Tactical or Minimal'),
|
||||
},
|
||||
],
|
||||
scope: () => [
|
||||
...openVisualSteps(),
|
||||
{
|
||||
prepare: () => $('#scope-toggle')?.scrollIntoView?.({ block: 'center' }),
|
||||
targets: () => [$('#scope-toggle')?.closest('.pp-toggle-group')],
|
||||
text: () =>
|
||||
t(
|
||||
'Scope frames the view in a circle. Feather softens its edge, Opacity sets how dark it shades outside.',
|
||||
),
|
||||
},
|
||||
],
|
||||
clean: () => [
|
||||
...openVisualSteps(),
|
||||
{
|
||||
prepare: () =>
|
||||
$('#clean-view-toggle')?.scrollIntoView?.({ block: 'center' }),
|
||||
targets: () => [$('#clean-view-toggle')],
|
||||
text: () => t('Clean UI hides the panels and readouts for a clear view'),
|
||||
},
|
||||
],
|
||||
'find-layer': () => [
|
||||
...openPanelSteps(LEFT_RAIL, 'data-panel', t('Data layers')),
|
||||
{
|
||||
targets: () => [$(SEARCH_BUTTON)],
|
||||
text: () => t('Press search, then type part of a layer name or source'),
|
||||
done: () => pressed(SEARCH_BUTTON),
|
||||
},
|
||||
{
|
||||
targets: () => [$(SEARCH_INPUT)],
|
||||
text: () => t('Type to narrow the list; Esc clears it'),
|
||||
done: hasSearchQuery,
|
||||
},
|
||||
{
|
||||
targets: () => [$(FILTER_BUTTON)],
|
||||
text: () =>
|
||||
t('Filter shows only layers that are on or off, or one category'),
|
||||
},
|
||||
],
|
||||
'filter-layers': () => [
|
||||
...openPanelSteps(LEFT_RAIL, 'data-panel', t('Data layers')),
|
||||
{
|
||||
targets: () => [$(FILTER_BUTTON)],
|
||||
text: () => t('Open the filter'),
|
||||
done: () => $(FILTER_BUTTON)?.getAttribute('aria-expanded') === 'true',
|
||||
},
|
||||
{
|
||||
targets: () => [$('.layer-finder__menu')],
|
||||
text: () =>
|
||||
t(
|
||||
'Pick a status (On, Off) and a category; each shows as a chip you can clear',
|
||||
),
|
||||
},
|
||||
],
|
||||
'section-index': () => [
|
||||
...openPanelSteps(LEFT_RAIL, 'data-panel', t('Data layers')),
|
||||
{
|
||||
targets: () => [$('.layer-section-index')],
|
||||
text: () => t('Hover a tick to see its group; click to jump there'),
|
||||
},
|
||||
],
|
||||
preferences: () => [
|
||||
{
|
||||
targets: () => [$('#corner-actions')],
|
||||
text: () => t('Add provider keys with Power Up, or change the language'),
|
||||
},
|
||||
],
|
||||
edge: () => [
|
||||
...openPanelSteps(LEFT_RAIL, 'data-panel', t('Data layers')),
|
||||
{
|
||||
targets: () => [$('#data-panel .ui-panel-edge')],
|
||||
text: () =>
|
||||
t(
|
||||
'Press this to slide panels over the rail to the screen edge; press again to bring them back',
|
||||
),
|
||||
},
|
||||
],
|
||||
context: () => [
|
||||
...openPanelSteps(RIGHT_RAIL, 'global-context-panel', t('Context')),
|
||||
{
|
||||
targets: () => [$('#global-context-panel .cyber-panel-body')],
|
||||
text: () =>
|
||||
t(
|
||||
'Context describes the view: weather, hazards, what your layers have nearby, and whatever you pick on the map',
|
||||
),
|
||||
},
|
||||
],
|
||||
properties: () =>
|
||||
propertiesSteps('labels', () =>
|
||||
t(
|
||||
'Properties holds the settings for the layers that are on, each layer marked by a coloured dot',
|
||||
),
|
||||
),
|
||||
north: () => [
|
||||
{
|
||||
targets: () => [$('#north-up-view')],
|
||||
text: () => t('Press the compass to face north'),
|
||||
},
|
||||
],
|
||||
tilt: () => [
|
||||
{
|
||||
targets: () => [$('#tilt-map-view')],
|
||||
text: () => t('Tilt the camera for a 3D view'),
|
||||
},
|
||||
],
|
||||
globe: () => [
|
||||
{
|
||||
targets: () => [$('#reset-globe-view')],
|
||||
text: () => t('Zoom out to the whole globe'),
|
||||
},
|
||||
],
|
||||
share: () => [
|
||||
{
|
||||
targets: () => [$('#share-btn')],
|
||||
text: () => t('Copy a link to exactly this view'),
|
||||
},
|
||||
],
|
||||
clear: () => [
|
||||
{
|
||||
targets: () => [$('#clear-selected-layers')],
|
||||
text: () => t('Turn off every layer at once'),
|
||||
},
|
||||
],
|
||||
// Drawing, and measuring with it: a line shows its length and an area its
|
||||
// size while it is drawn (src/annotations/drawMode.js).
|
||||
draw: () => [
|
||||
...openPanelSteps(LEFT_RAIL, 'utilities-panel', t('Utilities')),
|
||||
{
|
||||
prepare: () => $('#draw-group')?.scrollIntoView?.({ block: 'center' }),
|
||||
targets: () => [$('#draw-toggle')],
|
||||
text: () => t('Press Draw to start drawing on the map'),
|
||||
skip: () => pressed('#draw-toggle'),
|
||||
done: () => pressed('#draw-toggle'),
|
||||
},
|
||||
{
|
||||
targets: () => [$('#draw-mode-row')],
|
||||
text: () =>
|
||||
t(
|
||||
'Pick Line to measure a distance or Area for its size, then click points on the map; double-click or Enter finishes',
|
||||
),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
/** The omnibar command ids that have a feature walk. */
|
||||
export function featureGuideFor(commandId) {
|
||||
if (commandId.startsWith('style-')) return 'styles';
|
||||
if (commandId.startsWith('map-')) return 'map-source';
|
||||
if (commandId.startsWith('hud-')) return 'hud';
|
||||
if (commandId === 'reset') return 'globe';
|
||||
return FEATURE_GUIDES[commandId] ? commandId : null;
|
||||
}
|
||||
|
||||
let active = null;
|
||||
|
||||
/**
|
||||
* Run a walk. Starting another ends the one in progress.
|
||||
* @param {Array<object>} steps
|
||||
* @param {{title?: string}} [options]
|
||||
*/
|
||||
export function startGuide(steps, { title = '' } = {}) {
|
||||
active?.stop();
|
||||
const doc = globalThis.document;
|
||||
if (!doc?.body || screenIsOwned(doc) || !steps?.length) return;
|
||||
// What the view renders: the owner writes it for each step, then paints.
|
||||
// The view never binds what is set on the elements: the guide's `visible`
|
||||
// class, the callout's entrance replay, place and side, and the rings'
|
||||
// boxes, set per frame.
|
||||
const endLabel = t('End guide');
|
||||
const view = {
|
||||
title: title ? t('Guide · {topic}', { topic: title }) : t('Guide'),
|
||||
endLabel,
|
||||
count: '',
|
||||
step: 0,
|
||||
progress: [],
|
||||
text: '',
|
||||
hint: t('Press the highlighted control'),
|
||||
hintHidden: false,
|
||||
// i18n-ignore: the Escape keycap, matching the keyboard shortcut.
|
||||
keyCap: 'Esc',
|
||||
keyText: t('to end'),
|
||||
keysHidden: false,
|
||||
skipLabel: '',
|
||||
skipHidden: true,
|
||||
offerLabel: '',
|
||||
offerHidden: true,
|
||||
nextLabel: t('Next'),
|
||||
nextHidden: false,
|
||||
nextQuiet: false,
|
||||
// Announces each step once; the dialog itself is not a live region, so
|
||||
// its buttons and progress are not read out on every change.
|
||||
status: '',
|
||||
};
|
||||
const host = doc.createElement('div');
|
||||
const handlers = {
|
||||
onClose: () => stop(),
|
||||
onSkip: () => stop(),
|
||||
// Taking the offer carries the walk on with its steps.
|
||||
onOffer() {
|
||||
if (!current?.offer) return;
|
||||
const extra = current.offer.steps() || [];
|
||||
live.splice(index + 1, live.length, ...extra.filter(Boolean));
|
||||
next();
|
||||
},
|
||||
onNext() {
|
||||
if (current) next();
|
||||
},
|
||||
};
|
||||
let mounted = true;
|
||||
/** Render the view now: the guide goes to the end of the body. */
|
||||
function paint() {
|
||||
if (!mounted) return null;
|
||||
const vnode = h(OmnibarGuide, {
|
||||
to: doc.body,
|
||||
view: { ...view },
|
||||
...handlers,
|
||||
});
|
||||
renderVue(vnode, host);
|
||||
return vnode;
|
||||
}
|
||||
// Focus returns where it was when the walk ends, if that is still there.
|
||||
const returnFocus = doc.activeElement;
|
||||
// The elements come from the rendered tree, which is in place as soon as the
|
||||
// render returns; template refs are filled after it, and later still when
|
||||
// the walk starts inside one of Vue's own post-render updates.
|
||||
const root = paint().component.subTree.children[0].el;
|
||||
const ring = root.querySelector(':scope > .gev-guide-ring');
|
||||
const callout = root.querySelector(':scope > .gev-guide-callout');
|
||||
const subRings = [];
|
||||
|
||||
const live = steps.filter(Boolean);
|
||||
let index = -1;
|
||||
let frame = 0;
|
||||
let advanceTimer = 0;
|
||||
let stopped = false;
|
||||
let current = null;
|
||||
let shown = 0;
|
||||
|
||||
const stop = () => {
|
||||
if (stopped) return;
|
||||
stopped = true;
|
||||
cancelAnimationFrame(frame);
|
||||
clearInterval(poll);
|
||||
clearTimeout(advanceTimer);
|
||||
resizeObserver?.disconnect();
|
||||
globalThis.removeEventListener?.('resize', schedule);
|
||||
doc.removeEventListener('scroll', schedule, true);
|
||||
doc.removeEventListener('click', onClick, true);
|
||||
doc.removeEventListener('keydown', onKey, true);
|
||||
const hadFocus = root.contains(doc.activeElement);
|
||||
mounted = false;
|
||||
renderVue(null, host);
|
||||
if (hadFocus && returnFocus?.isConnected) returnFocus.focus?.();
|
||||
if (active?.stop === stop) active = null;
|
||||
};
|
||||
const next = () => {
|
||||
clearTimeout(advanceTimer);
|
||||
advanceTimer = 0;
|
||||
void run(index + 1);
|
||||
};
|
||||
|
||||
const advance = () => {
|
||||
if (advanceTimer) return;
|
||||
advanceTimer = setTimeout(next, 350);
|
||||
};
|
||||
|
||||
async function run(at) {
|
||||
if (stopped) return;
|
||||
if (screenIsOwned(doc)) return stop();
|
||||
current = null;
|
||||
index = at;
|
||||
const step = live[index];
|
||||
if (!step) return stop();
|
||||
await step.prepare?.();
|
||||
if (stopped || at !== index) return;
|
||||
if (step.skip?.() || step.done?.()) return run(index + 1);
|
||||
current = step;
|
||||
shown += 1;
|
||||
// The total is what is shown so far plus the steps still to come that
|
||||
// would not be skipped as things stand.
|
||||
const total =
|
||||
shown + live.slice(index + 1).filter((later) => !later.skip?.()).length;
|
||||
view.count = `${shown} / ${total}`;
|
||||
view.step = shown;
|
||||
view.progress = Array.from({ length: total }, (_, i) =>
|
||||
i < shown - 1 ? 'done' : i === shown - 1 ? 'current' : null,
|
||||
);
|
||||
const text = step.text();
|
||||
view.text = text;
|
||||
view.status = `${shown} / ${total}: ${text}`;
|
||||
// Steps that point at a control wait for it to be pressed; say so.
|
||||
const waits = Boolean(step.targets) && !step.offer;
|
||||
view.hintHidden = !waits;
|
||||
view.offerHidden = !step.offer;
|
||||
view.skipHidden = !step.offer;
|
||||
view.keysHidden = Boolean(step.offer);
|
||||
if (step.offer) {
|
||||
view.offerLabel = step.offer.label();
|
||||
view.skipLabel = t('Not now');
|
||||
}
|
||||
const last = index === live.length - 1;
|
||||
view.nextHidden = Boolean(step.offer);
|
||||
view.nextLabel = last ? t('Finish') : waits ? t('Skip step') : t('Next');
|
||||
view.nextQuiet = waits && !last;
|
||||
paint();
|
||||
// Replay the entrance so each step reads as new.
|
||||
callout.classList.remove('swap');
|
||||
void callout.offsetWidth;
|
||||
callout.classList.add('swap');
|
||||
root.classList.add('visible');
|
||||
schedule();
|
||||
}
|
||||
|
||||
// The visitor pressed the spotlit control: give the app a moment to react,
|
||||
// then move on (or let `done` decide, for steps that wait on a state).
|
||||
function onClick(event) {
|
||||
if (!current || callout.contains(event.target)) return;
|
||||
const [target] = current.targets?.() || [];
|
||||
if (target?.contains(event.target) && !current.done) advance();
|
||||
}
|
||||
// Only Escape is the walk's: it ends the walk and nothing else (the
|
||||
// Omnibar or a panel behind it stays as it is). Every other key goes on to
|
||||
// the page untouched.
|
||||
function onKey(event) {
|
||||
if (screenIsOwned(doc)) {
|
||||
stop();
|
||||
return;
|
||||
}
|
||||
if (event.key !== 'Escape' || event.isComposing) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
stop();
|
||||
}
|
||||
doc.addEventListener('click', onClick, true);
|
||||
doc.addEventListener('keydown', onKey, true);
|
||||
|
||||
// Follow the targets as panels open and scroll, and notice when a step's
|
||||
// goal is reached however it happened: on resize and scroll, when the page
|
||||
// changes size, and otherwise four times a second (panels slide open
|
||||
// without an event to follow). Each is at most one frame's work.
|
||||
let poll = 0;
|
||||
let resizeObserver = null;
|
||||
function schedule() {
|
||||
if (stopped || frame) return;
|
||||
frame = requestAnimationFrame(() => {
|
||||
frame = 0;
|
||||
place();
|
||||
});
|
||||
}
|
||||
const place = () => {
|
||||
if (screenIsOwned(doc)) return stop();
|
||||
if (!current) return;
|
||||
if (current.done?.()) advance();
|
||||
const targets = (current.targets?.() || []).filter(Boolean);
|
||||
const [main, ...rest] = targets.map((element) =>
|
||||
element.getBoundingClientRect(),
|
||||
);
|
||||
if (!main || !main.width) {
|
||||
// Nothing to point at (the closing offer): centre the callout.
|
||||
ring.style.opacity = '0';
|
||||
subRings.forEach((sub) => (sub.style.opacity = '0'));
|
||||
callout.dataset.side = 'none';
|
||||
callout.style.left = `${(innerWidth - (callout.offsetWidth || 280)) / 2}px`;
|
||||
callout.style.top = `${innerHeight * 0.32}px`;
|
||||
return;
|
||||
}
|
||||
const pad = 6;
|
||||
Object.assign(ring.style, {
|
||||
opacity: '1',
|
||||
left: `${main.left - pad}px`,
|
||||
top: `${main.top - pad}px`,
|
||||
width: `${main.width + pad * 2}px`,
|
||||
height: `${main.height + pad * 2}px`,
|
||||
});
|
||||
while (subRings.length < rest.length) {
|
||||
const sub = doc.createElement('div');
|
||||
sub.className = 'gev-guide-ring gev-guide-ring--sub';
|
||||
root.append(sub);
|
||||
subRings.push(sub);
|
||||
}
|
||||
subRings.forEach((sub, i) => {
|
||||
const box = rest[i];
|
||||
Object.assign(
|
||||
sub.style,
|
||||
box?.width
|
||||
? {
|
||||
opacity: '1',
|
||||
left: `${box.left - 4}px`,
|
||||
top: `${box.top - 4}px`,
|
||||
width: `${box.width + 8}px`,
|
||||
height: `${box.height + 8}px`,
|
||||
}
|
||||
: { opacity: '0' },
|
||||
);
|
||||
});
|
||||
// The callout sits beside the target, on whichever side has room.
|
||||
const width = callout.offsetWidth || 280;
|
||||
const height = callout.offsetHeight || 120;
|
||||
const gap = 18;
|
||||
const right = main.right + pad + gap;
|
||||
const onRight = right + width < innerWidth - 12;
|
||||
const left = onRight ? right : Math.max(12, main.left - pad - gap - width);
|
||||
const centre = main.top + main.height / 2;
|
||||
const top = Math.max(
|
||||
12,
|
||||
Math.min(innerHeight - height - 12, centre - height / 2),
|
||||
);
|
||||
// The arrow points at the target's middle, kept inside the callout.
|
||||
callout.dataset.side = onRight ? 'right' : 'left';
|
||||
callout.style.setProperty(
|
||||
'--gev-guide-arrow-y',
|
||||
`${Math.min(height - 18, Math.max(18, centre - top))}px`,
|
||||
);
|
||||
callout.style.left = `${left}px`;
|
||||
callout.style.top = `${top}px`;
|
||||
};
|
||||
globalThis.addEventListener?.('resize', schedule);
|
||||
doc.addEventListener('scroll', schedule, true);
|
||||
if (typeof ResizeObserver === 'function') {
|
||||
resizeObserver = new ResizeObserver(schedule);
|
||||
resizeObserver.observe(doc.body);
|
||||
}
|
||||
// A hidden tab has nothing to follow: the poll rests until it is shown.
|
||||
poll = setInterval(() => {
|
||||
if (!doc.hidden) schedule();
|
||||
}, 250);
|
||||
schedule();
|
||||
callout.focus({ preventScroll: true });
|
||||
|
||||
active = { stop };
|
||||
void run(0);
|
||||
return stop;
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
// The guided walk's callout, rendered by startGuide() over happy-dom.
|
||||
import '../testSupport/registerDom.mjs';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createApp, h, onMounted } from 'vue';
|
||||
import { startGuide } from './omnibarGuide.js';
|
||||
|
||||
const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
|
||||
const $ = (selector) => document.querySelector(selector);
|
||||
|
||||
function fixture(t) {
|
||||
document.body.replaceChildren();
|
||||
const target = document.body.appendChild(document.createElement('button'));
|
||||
const field = document.body.appendChild(document.createElement('input'));
|
||||
field.focus();
|
||||
t.after(() => $('.gev-guide-close')?.click());
|
||||
return { target, field };
|
||||
}
|
||||
|
||||
test('the walk is the last of the body, takes focus and gives it back', async (t) => {
|
||||
const { target, field } = fixture(t);
|
||||
startGuide([{ targets: () => [target], text: () => 'Press it' }], {
|
||||
title: 'Flights',
|
||||
});
|
||||
await settle();
|
||||
const guide = $('.gev-guide');
|
||||
assert.equal(document.body.lastElementChild, guide);
|
||||
assert.equal(guide.parentElement, document.body);
|
||||
assert.ok(guide.classList.contains('visible'));
|
||||
const callout = $('.gev-guide-callout');
|
||||
assert.equal(document.activeElement, callout);
|
||||
assert.equal(callout.getAttribute('role'), 'dialog');
|
||||
assert.equal(callout.getAttribute('aria-modal'), 'false');
|
||||
assert.equal(callout.getAttribute('tabindex'), '-1');
|
||||
assert.equal($('.gev-guide-title').textContent, 'Guide · Flights');
|
||||
const close = $('.gev-guide-close');
|
||||
assert.equal(close.getAttribute('type'), 'button');
|
||||
assert.equal(close.getAttribute('aria-label'), 'End guide');
|
||||
assert.equal(close.getAttribute('title'), 'End guide');
|
||||
assert.ok(close.classList.contains('ui-close-button'));
|
||||
close.focus();
|
||||
close.click();
|
||||
assert.equal($('.gev-guide'), null);
|
||||
assert.equal(document.activeElement, field);
|
||||
});
|
||||
|
||||
test('the status line says each step once, and each step draws new progress', async (t) => {
|
||||
const { target } = fixture(t);
|
||||
startGuide([
|
||||
{ targets: () => [target], text: () => 'Press it' },
|
||||
{ text: () => 'Then this' },
|
||||
{
|
||||
text: () => 'More?',
|
||||
offer: { label: () => 'Show more', steps: () => [] },
|
||||
},
|
||||
]);
|
||||
const status = $('.gev-guide-status');
|
||||
const said = [];
|
||||
// One change per step: its text replaced once, never cleared first.
|
||||
const observer = new MutationObserver(() => said.push(status.textContent));
|
||||
observer.observe(status, {
|
||||
childList: true,
|
||||
characterData: true,
|
||||
subtree: true,
|
||||
});
|
||||
t.after(() => observer.disconnect());
|
||||
await settle();
|
||||
const firstDots = [...document.querySelectorAll('.gev-guide-progress li')];
|
||||
assert.deepEqual(
|
||||
firstDots.map((dot) => dot.getAttribute('class')),
|
||||
['current', null, null],
|
||||
);
|
||||
const next = $('.gev-guide-next');
|
||||
assert.equal(next.textContent, 'Skip step');
|
||||
assert.ok(next.classList.contains('quiet'));
|
||||
assert.equal($('.gev-guide-hint').hidden, false);
|
||||
next.click();
|
||||
await settle();
|
||||
const secondDots = [...document.querySelectorAll('.gev-guide-progress li')];
|
||||
assert.deepEqual(
|
||||
secondDots.map((dot) => dot.getAttribute('class')),
|
||||
['done', 'current', null],
|
||||
);
|
||||
assert.ok(secondDots.every((dot) => !firstDots.includes(dot)));
|
||||
assert.equal(next.textContent, 'Next');
|
||||
assert.equal(next.classList.contains('quiet'), false);
|
||||
assert.equal($('.gev-guide-hint').hidden, true);
|
||||
next.click();
|
||||
await settle();
|
||||
// The closing offer: its two buttons, no Esc hint and no Next.
|
||||
assert.equal($('.gev-guide-keys').hidden, true);
|
||||
assert.equal(next.hidden, true);
|
||||
assert.equal($('.gev-guide-skip').hidden, false);
|
||||
assert.equal($('.gev-guide-skip').textContent, 'Not now');
|
||||
assert.equal($('.gev-guide-offer').textContent, 'Show more');
|
||||
assert.deepEqual(said, [
|
||||
'1 / 3: Press it',
|
||||
'2 / 3: Then this',
|
||||
'3 / 3: More?',
|
||||
]);
|
||||
$('.gev-guide-skip').click();
|
||||
assert.equal($('.gev-guide'), null);
|
||||
});
|
||||
|
||||
test('starting another walk ends the one in progress', async (t) => {
|
||||
fixture(t);
|
||||
startGuide([{ text: () => 'First' }]);
|
||||
startGuide([{ text: () => 'Second' }]);
|
||||
await settle();
|
||||
assert.equal(document.querySelectorAll('.gev-guide').length, 1);
|
||||
assert.equal($('.gev-guide-text').textContent, 'Second');
|
||||
});
|
||||
|
||||
test('a walk started while Vue mounts something else still starts and ends', async (t) => {
|
||||
const { target, field } = fixture(t);
|
||||
let stop = null;
|
||||
const app = createApp({
|
||||
setup() {
|
||||
onMounted(() => {
|
||||
stop = startGuide([
|
||||
{ targets: () => [target], text: () => 'Press it' },
|
||||
]);
|
||||
});
|
||||
return () => h('span');
|
||||
},
|
||||
});
|
||||
app.mount(document.body.appendChild(document.createElement('div')));
|
||||
t.after(() => app.unmount());
|
||||
await settle();
|
||||
assert.equal(typeof stop, 'function');
|
||||
assert.equal(document.activeElement, $('.gev-guide-callout'));
|
||||
assert.ok($('.gev-guide').classList.contains('visible'));
|
||||
stop();
|
||||
assert.equal($('.gev-guide'), null);
|
||||
assert.equal(document.activeElement, field);
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,442 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { isPanelText, magnitudeFloor, parseOmnibar } from './omnibarIntent.js';
|
||||
|
||||
const matchLayers = (term) =>
|
||||
['flights', 'ships'].includes(term) ? [{ id: term, score: 2 }] : [];
|
||||
|
||||
test('place lookup retains comma qualifiers in standalone and combined requests', () => {
|
||||
assert.deepEqual(
|
||||
[...parseOmnibar(' Paris, Texas ', matchLayers).steps],
|
||||
[{ kind: 'place', place: 'Paris, Texas' }],
|
||||
);
|
||||
const { steps } = parseOmnibar(
|
||||
'north up, flights near Paris, Texas, follow AAL123',
|
||||
matchLayers,
|
||||
);
|
||||
assert.deepEqual(
|
||||
steps.map(({ kind }) => kind),
|
||||
['place', 'camera', 'layer', 'follow'],
|
||||
);
|
||||
assert.equal(steps[0].place, 'paris, texas');
|
||||
});
|
||||
|
||||
test('named layer removals and orbit stop preserve the requested action', () => {
|
||||
const { steps } = parseOmnibar(
|
||||
'hide all flights and ships, stop orbit',
|
||||
matchLayers,
|
||||
);
|
||||
assert.deepEqual(
|
||||
[...steps],
|
||||
[
|
||||
{ kind: 'layer', layer: { id: 'flights', score: 2 }, enabled: false },
|
||||
{ kind: 'layer', layer: { id: 'ships', score: 2 }, enabled: false },
|
||||
{ kind: 'camera', name: 'move_camera', args: { motion: 'stop' } },
|
||||
],
|
||||
);
|
||||
assert.deepEqual(
|
||||
[...parseOmnibar('turn off all layers', matchLayers).steps],
|
||||
[{ kind: 'camera', act: 'clear' }],
|
||||
);
|
||||
});
|
||||
|
||||
const layersOf = (steps) =>
|
||||
[...steps].map((step) =>
|
||||
step.kind === 'layer'
|
||||
? { kind: 'layer', id: step.layer.id, enabled: step.enabled }
|
||||
: step,
|
||||
);
|
||||
|
||||
test('turning the radio off is a radio step, and its verb is never a place', () => {
|
||||
assert.deepEqual(
|
||||
layersOf(parseOmnibar('tokyo and turn off the radio', matchLayers).steps),
|
||||
[
|
||||
{ kind: 'place', place: 'tokyo' },
|
||||
{ kind: 'radio', action: 'disable' },
|
||||
],
|
||||
);
|
||||
assert.deepEqual(
|
||||
layersOf(
|
||||
parseOmnibar('show flights and stop the radio', matchLayers).steps,
|
||||
),
|
||||
[
|
||||
{ kind: 'layer', id: 'flights', enabled: true },
|
||||
{ kind: 'radio', action: 'disable' },
|
||||
],
|
||||
);
|
||||
assert.deepEqual(
|
||||
layersOf(parseOmnibar('go to austin, mute radio', matchLayers).steps),
|
||||
[
|
||||
{ kind: 'place', place: 'austin' },
|
||||
{ kind: 'radio', action: 'disable' },
|
||||
],
|
||||
);
|
||||
assert.deepEqual(
|
||||
layersOf(parseOmnibar('play radio in tokyo', matchLayers).steps),
|
||||
[
|
||||
{ kind: 'place', place: 'tokyo' },
|
||||
{ kind: 'radio', action: 'enable' },
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
// Layers as the Omnibar matches them: whole names are `exact`, a name's
|
||||
// start is not.
|
||||
const LAYERS = {
|
||||
flights: ['flights'],
|
||||
earthquakes: ['earthquakes', 'quakes'],
|
||||
'local-firms': ['fires'],
|
||||
'rocket-launches': ['rockets', 'launches'],
|
||||
traffic: ['traffic'],
|
||||
radio: ['radio'],
|
||||
};
|
||||
const matchNamed = (term) => {
|
||||
const needle = term.trim().toLowerCase();
|
||||
if (!needle) return [];
|
||||
return Object.entries(LAYERS)
|
||||
.filter(([, words]) =>
|
||||
words.some((word) => needle.length >= 3 && word.startsWith(needle)),
|
||||
)
|
||||
.map(([id, words]) => ({
|
||||
id,
|
||||
score: 2,
|
||||
exact: words.includes(needle) || words.includes(`${needle}s`),
|
||||
}));
|
||||
};
|
||||
|
||||
test('near-miss lines read as people mean them', () => {
|
||||
const read = (text) => layersOf(parseOmnibar(text, matchNamed).steps);
|
||||
const clear = [{ kind: 'camera', act: 'clear' }];
|
||||
assert.deepEqual(read('hide everything'), clear);
|
||||
assert.deepEqual(read('remove everything'), clear);
|
||||
assert.equal(isPanelText('hide everything'), false);
|
||||
assert.equal(isPanelText('close all panels'), true);
|
||||
assert.deepEqual(read('track flights near austin'), [
|
||||
{ kind: 'place', place: 'austin' },
|
||||
{ kind: 'layer', id: 'flights', enabled: true },
|
||||
]);
|
||||
assert.deepEqual(read('follow AAL123'), [
|
||||
{ kind: 'follow', query: 'aal123' },
|
||||
]);
|
||||
assert.deepEqual(read('show earthquake data layer'), [
|
||||
{ kind: 'layer', id: 'earthquakes', enabled: true },
|
||||
]);
|
||||
assert.equal(isPanelText('show earthquake data layer'), false);
|
||||
assert.equal(read('open data layers')[0].item, 'data-panel');
|
||||
assert.equal(
|
||||
read('open space missions panel')[0].item,
|
||||
'space-missions-panel',
|
||||
);
|
||||
assert.equal(
|
||||
read('close the missions panel')[0].item,
|
||||
'space-missions-panel',
|
||||
);
|
||||
// Without "panel" it is the layer, not its panel.
|
||||
assert.equal(isPanelText('show space missions'), false);
|
||||
assert.deepEqual(read('go to trinidad and tobago and show flights'), [
|
||||
{ kind: 'place', place: 'trinidad and tobago' },
|
||||
{ kind: 'layer', id: 'flights', enabled: true },
|
||||
]);
|
||||
// "fire" is a whole layer word, so "Fire Island" is ambiguous: the whole
|
||||
// line is offered as a place first (see the Omnibar test).
|
||||
assert.equal(parseOmnibar('Fire Island', matchNamed).ambiguous, true);
|
||||
assert.deepEqual(read('Show Low, AZ'), [
|
||||
{ kind: 'place', place: 'Show Low, AZ' },
|
||||
]);
|
||||
// Words that also start place names ask only in a longer line.
|
||||
for (const place of ['Can Tho', 'Tell City']) {
|
||||
const { steps, question } = parseOmnibar(place, matchNamed);
|
||||
assert.equal(question, false, place);
|
||||
assert.deepEqual([...steps], [{ kind: 'place', place }]);
|
||||
}
|
||||
assert.equal(parseOmnibar('can you show me', matchNamed).question, true);
|
||||
assert.equal(parseOmnibar('Can Tho?', matchNamed).question, true);
|
||||
assert.equal(parseOmnibar('what is here', matchNamed).question, true);
|
||||
});
|
||||
|
||||
test('a magnitude floor is read for earthquakes only', () => {
|
||||
assert.deepEqual(magnitudeFloor('quakes above m5 in japan', matchNamed), {
|
||||
text: 'quakes in japan',
|
||||
minMagnitude: 5,
|
||||
});
|
||||
assert.deepEqual(magnitudeFloor('earthquakes m4.5+ near tokyo', matchNamed), {
|
||||
text: 'earthquakes near tokyo',
|
||||
minMagnitude: 4.5,
|
||||
});
|
||||
assert.deepEqual(magnitudeFloor('flights over m25', matchNamed), {
|
||||
text: 'flights over m25',
|
||||
minMagnitude: null,
|
||||
});
|
||||
assert.deepEqual(magnitudeFloor('flights near austin', matchNamed), {
|
||||
text: 'flights near austin',
|
||||
minMagnitude: null,
|
||||
});
|
||||
});
|
||||
|
||||
test('place names holding a command word are places, or ambiguous at most', () => {
|
||||
const read = (text) => parseOmnibar(text, matchNamed);
|
||||
// The cockpit and the radio need a verb.
|
||||
for (const text of [
|
||||
'Cockpit Country, Jamaica',
|
||||
'cockpit',
|
||||
'cockpit view',
|
||||
'Rock and Roll Hall of Fame',
|
||||
]) {
|
||||
const { steps } = read(text);
|
||||
assert.deepEqual([...steps], [{ kind: 'place', place: text }], text);
|
||||
}
|
||||
assert.deepEqual([...read('enter cockpit').steps], [{ kind: 'cockpit' }]);
|
||||
assert.equal(
|
||||
read('Radio City Music Hall').steps.some((step) => step.kind === 'radio'),
|
||||
false,
|
||||
);
|
||||
// One keyword without a verb beside the rest of a name: the whole line is
|
||||
// offered as a place ahead of the plan.
|
||||
for (const text of [
|
||||
'Radio City Music Hall',
|
||||
'Radio Free Europe',
|
||||
'Thermal, California',
|
||||
'Tilt Cove',
|
||||
'Hud Valley',
|
||||
'tokyo traffic',
|
||||
])
|
||||
assert.equal(read(text).ambiguous, true, text);
|
||||
// A verb, a joining "and" or "near" makes it a plan.
|
||||
// Keywords nobody asked for, joined to the rest of a name, leave the
|
||||
// whole line a place first too ("Storm Lake and Spencer").
|
||||
assert.equal(read('noir and tokyo').ambiguous, true);
|
||||
for (const text of [
|
||||
'flights near austin',
|
||||
'show traffic in tokyo',
|
||||
'tilt and go to cove',
|
||||
'show noir and tokyo',
|
||||
])
|
||||
assert.equal(read(text).ambiguous, false, text);
|
||||
});
|
||||
|
||||
test('nearest to, several places, and what can be followed', () => {
|
||||
const read = (text) => layersOf(parseOmnibar(text, matchNamed).steps);
|
||||
assert.deepEqual(read('nearest plane to Heathrow'), [
|
||||
{ kind: 'place', place: 'heathrow' },
|
||||
{ kind: 'nearest' },
|
||||
]);
|
||||
const both = parseOmnibar('flights near New York and Paris', matchNamed);
|
||||
assert.equal(both.steps[0].place, 'new york');
|
||||
assert.deepEqual(both.extraPlaces, ['paris']);
|
||||
assert.deepEqual(read('Follow Me Bar'), [
|
||||
{ kind: 'place', place: 'Follow Me Bar' },
|
||||
]);
|
||||
// A name without a digit is followed only when it is loaded on the map.
|
||||
assert.deepEqual(
|
||||
layersOf(
|
||||
parseOmnibar('follow the iss', matchNamed, {
|
||||
isEntity: (name) => name === 'iss',
|
||||
}).steps,
|
||||
),
|
||||
[{ kind: 'follow', query: 'iss' }],
|
||||
);
|
||||
assert.deepEqual(read('Track Hill'), [
|
||||
{ kind: 'place', place: 'Track Hill' },
|
||||
]);
|
||||
assert.deepEqual(read('follow UAL 123'), [
|
||||
{ kind: 'follow', query: 'ual 123' },
|
||||
]);
|
||||
});
|
||||
|
||||
test('a magnitude floor is no part of the place', () => {
|
||||
const { text, minMagnitude } = magnitudeFloor(
|
||||
'show me earthquakes above m5 in japan',
|
||||
matchNamed,
|
||||
);
|
||||
assert.equal(minMagnitude, 5);
|
||||
assert.deepEqual(layersOf(parseOmnibar(text, matchNamed).steps), [
|
||||
{ kind: 'place', place: 'japan' },
|
||||
{ kind: 'layer', id: 'earthquakes', enabled: true },
|
||||
]);
|
||||
});
|
||||
|
||||
test('ar and he mark every Omnibar string alike with a right-to-left mark', async () => {
|
||||
const { readFile } = await import('node:fs/promises');
|
||||
// Every message the Omnibar's code passes to t(), msg() or tn(): after a
|
||||
// colon or comma, before a placeholder or Latin text, both catalogs put
|
||||
// U+200F, so the punctuation stays with the right-to-left text before it.
|
||||
const sources = await Promise.all(
|
||||
[
|
||||
'./views/panels/Omnibar.vue',
|
||||
'./views/panels/VoiceVisualizer.vue',
|
||||
'./omnibarIntent.js',
|
||||
'./omnibarRows.js',
|
||||
'./omnibarGuide.js',
|
||||
'./leftPanelRail.js',
|
||||
].map((file) => readFile(new URL(file, import.meta.url), 'utf8')),
|
||||
);
|
||||
const code = sources.join('\n');
|
||||
// Single- or double-quoted, as t('…') / msg("…") / tn(n, '…', "…").
|
||||
const STRING = String.raw`'((?:\\.|[^'\\])*)'|"((?:\\.|[^"\\])*)"`;
|
||||
const literal = (match, from) => match[from] ?? match[from + 1];
|
||||
const keys = new Set([
|
||||
...[
|
||||
...code.matchAll(
|
||||
new RegExp(String.raw`\b(?:t|msg)\(\s*(?:${STRING})`, 'g'),
|
||||
),
|
||||
].map((match) => literal(match, 1)),
|
||||
...[
|
||||
...code.matchAll(
|
||||
new RegExp(
|
||||
String.raw`\btn\([^,]+,\s*(?:'(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"),\s*(?:${STRING})`,
|
||||
'g',
|
||||
),
|
||||
),
|
||||
].map((match) => literal(match, 1)),
|
||||
]);
|
||||
assert.ok(keys.size > 100, `${keys.size} Omnibar messages`);
|
||||
const unmarked = /[:\u060c,] (?!\u200f)(?=[{A-Za-z\u00ab\u05f4"])/;
|
||||
for (const locale of ['ar', 'he']) {
|
||||
const catalog = JSON.parse(
|
||||
await readFile(
|
||||
new URL(`../i18n/locales/${locale}.json`, import.meta.url),
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
for (const key of keys) {
|
||||
const entry = catalog[key];
|
||||
assert.ok(entry, `${locale} has ${key}`);
|
||||
for (const text of typeof entry === 'string'
|
||||
? [entry]
|
||||
: Object.values(entry))
|
||||
assert.doesNotMatch(text, unmarked, `${locale}: ${key}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('a "go to" clause is all place, and radio verbs apply to the radio', () => {
|
||||
const read = (text) => layersOf(parseOmnibar(text, matchNamed).steps);
|
||||
for (const [text, place] of [
|
||||
['go to cockpit country', 'cockpit country'],
|
||||
['go to Thermal, California', 'Thermal, California'],
|
||||
['fly to Tilt Cove', 'Tilt Cove'],
|
||||
['go to Night Vision Way', 'Night Vision Way'],
|
||||
['go to Whole Earth Provision', 'Whole Earth Provision'],
|
||||
])
|
||||
assert.deepEqual(read(text), [{ kind: 'place', place }], text);
|
||||
assert.deepEqual(read('go to austin, clear everything'), [
|
||||
{ kind: 'place', place: 'austin' },
|
||||
{ kind: 'camera', act: 'clear' },
|
||||
]);
|
||||
assert.deepEqual(read('go to'), []);
|
||||
assert.deepEqual(read('play radio in Kill Devil Hills'), [
|
||||
{ kind: 'place', place: 'kill devil hills' },
|
||||
{ kind: 'radio', action: 'enable' },
|
||||
]);
|
||||
assert.deepEqual(read('enter the cockpit view'), [{ kind: 'cockpit' }]);
|
||||
// Only a real question asks GEV by default; small talk goes there too.
|
||||
assert.equal(parseOmnibar('hi', matchNamed).asks, false);
|
||||
// Small talk is no question: it may be a place, with Ask GEV after it.
|
||||
assert.equal(parseOmnibar('hi', matchNamed).question, false);
|
||||
assert.equal(parseOmnibar('what is here', matchNamed).asks, true);
|
||||
// A long line is not split word by word into a layer and a place.
|
||||
let asked = 0;
|
||||
parseOmnibar('a b c d e f g h i j k l m n o p', (term) => {
|
||||
asked++;
|
||||
return matchNamed(term);
|
||||
});
|
||||
assert.ok(asked <= 2, `${asked} layer lookups`);
|
||||
});
|
||||
|
||||
test('a request ending a "go to" clause is peeled off, and the line is ambiguous', () => {
|
||||
const read = (text) => parseOmnibar(text, matchNamed);
|
||||
for (const [text, place, step] of [
|
||||
['go to tokyo in noir', 'tokyo', { kind: 'style', style: 'noir' }],
|
||||
['go to tokyo, noir', 'tokyo', { kind: 'style', style: 'noir' }],
|
||||
['go to Tokyo, north up', 'tokyo', { kind: 'camera', act: 'northUp' }],
|
||||
[
|
||||
'take me to Austin in thermal',
|
||||
'austin',
|
||||
{ kind: 'style', style: 'thermal' },
|
||||
],
|
||||
[
|
||||
'go to London with flights',
|
||||
'london',
|
||||
{ kind: 'layer', id: 'flights', enabled: true },
|
||||
],
|
||||
[
|
||||
'go to tokyo show flights',
|
||||
'tokyo',
|
||||
{ kind: 'layer', id: 'flights', enabled: true },
|
||||
],
|
||||
]) {
|
||||
const parsed = read(text);
|
||||
assert.equal(parsed.ambiguous, true, text);
|
||||
assert.equal(parsed.peeled, true, text);
|
||||
assert.deepEqual(
|
||||
layersOf(parsed.steps),
|
||||
[{ kind: 'place', place }, step],
|
||||
text,
|
||||
);
|
||||
}
|
||||
for (const text of [
|
||||
'go to Thermal, California',
|
||||
'fly to Tilt Cove',
|
||||
'go to Night Vision Way',
|
||||
'go to cockpit country',
|
||||
])
|
||||
assert.equal(read(text).steps.length, 1, text);
|
||||
// A joining word left alone names no place.
|
||||
assert.deepEqual(
|
||||
layersOf(read('go to Austin and show flights in noir').steps),
|
||||
[
|
||||
{ kind: 'place', place: 'austin' },
|
||||
{ kind: 'style', style: 'noir' },
|
||||
{ kind: 'layer', id: 'flights', enabled: true },
|
||||
],
|
||||
);
|
||||
// A named layer without a verb may be a name: "Hurricane, Utah".
|
||||
assert.equal(read('fires, utah').ambiguous, true);
|
||||
assert.equal(read('flights near austin').placeFrom, 'near');
|
||||
// A comma line without "?" is never a question.
|
||||
for (const text of ['Why, Arizona', 'What Cheer, Iowa', 'Can Tho, Vietnam'])
|
||||
assert.equal(read(text).question, false, text);
|
||||
assert.equal(read('why, arizona?').question, true);
|
||||
});
|
||||
|
||||
test('the one verb test reads any letter case', async () => {
|
||||
const { hasActionVerb } = await import('./omnibarIntent.js');
|
||||
for (const text of [
|
||||
'Turn on the radio',
|
||||
'Turn On Radio',
|
||||
'Draw',
|
||||
'CLEAR THE MAP',
|
||||
])
|
||||
assert.equal(hasActionVerb(text), true, text);
|
||||
for (const text of [
|
||||
'Kill Devil Hills',
|
||||
'Show',
|
||||
'See',
|
||||
'Clear Lake',
|
||||
'Tilt Cove',
|
||||
])
|
||||
assert.equal(hasActionVerb(text), text === 'Show', text);
|
||||
});
|
||||
|
||||
test('every place word is still a bundled place name', async () => {
|
||||
const { readFile, readdir } = await import('node:fs/promises');
|
||||
const { PLACE_WORDS } = await import('./omnibarEnter.js');
|
||||
const names = new Set();
|
||||
const cities = JSON.parse(
|
||||
await readFile(
|
||||
new URL(
|
||||
'../data/local_data/wikidata_cities/cities.json',
|
||||
import.meta.url,
|
||||
),
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
for (const row of cities.rows) names.add(row[0].toLowerCase());
|
||||
const dir = new URL('../data/local_data/wikidata_places/', import.meta.url);
|
||||
for (const file of await readdir(dir))
|
||||
if (/^-?\d+_-?\d+\.json$/.test(file))
|
||||
for (const row of JSON.parse(await readFile(new URL(file, dir), 'utf8'))
|
||||
.rows)
|
||||
names.add(row[0].toLowerCase());
|
||||
for (const word of PLACE_WORDS) assert.ok(names.has(word), word);
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,887 @@
|
||||
// src/ui/omnibarRows.test.mjs — the Omnibar's one pipeline from typed text
|
||||
// to rows, read without the DOM: what Enter runs for a line before any row is
|
||||
// chosen, what may go to the place service, and the rows themselves.
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createOmnibar, readLine } from './omnibarRows.js';
|
||||
import { normalizeLine } from './omnibarIntent.js';
|
||||
|
||||
const LAYERS = [
|
||||
{ id: 'flights', name: 'Live Flights', enabled: false },
|
||||
{ id: 'military', name: 'Military Flights', enabled: false },
|
||||
{ id: 'radio', name: 'Radio', enabled: false },
|
||||
{ id: 'cctv', name: 'CCTV', enabled: false },
|
||||
{ id: 'earthquakes', name: 'Earthquakes', enabled: false },
|
||||
{ id: 'traffic', name: 'Traffic', enabled: false },
|
||||
{ id: 'weather-radar', name: 'Weather radar', enabled: false },
|
||||
];
|
||||
const layers = (on = []) =>
|
||||
LAYERS.map((layer) => ({ ...layer, enabled: on.includes(layer.id) }));
|
||||
|
||||
/** One step of a plan, as the table writes it. */
|
||||
function stepOutcome(step) {
|
||||
switch (step.kind) {
|
||||
case 'place':
|
||||
return `fly(${step.place})`;
|
||||
case 'layer':
|
||||
return `layer(${step.layer.id},${step.enabled ? 'on' : 'off'})`;
|
||||
case 'style':
|
||||
return `style(${step.style})`;
|
||||
case 'stack':
|
||||
return `map(${step.stack})`;
|
||||
case 'camera':
|
||||
return `camera(${step.act || step.args?.motion || step.args?.direction || step.name})`;
|
||||
case 'hud':
|
||||
return `hud(${step.visible})`;
|
||||
case 'panel':
|
||||
return `panel(${step.action} ${step.item || step.side})`;
|
||||
case 'radio':
|
||||
return `radio(${step.action || 'enable'})`;
|
||||
case 'follow':
|
||||
return `follow(${step.query})`;
|
||||
default:
|
||||
return step.kind;
|
||||
}
|
||||
}
|
||||
|
||||
/** What Enter runs for a line before any row is chosen. */
|
||||
function outcome(text, { on = [], places = [] } = {}) {
|
||||
const omnibar = createOmnibar({ layers: layers(on) });
|
||||
const { rows, defaultIndex } = omnibar.rows(text, { places });
|
||||
const row = rows[defaultIndex];
|
||||
if (!row) return 'nothing';
|
||||
switch (row.kind) {
|
||||
case 'place':
|
||||
return `search(${row.place})`;
|
||||
case 'layer':
|
||||
return `layer(${row.id},${row.enabled ? 'on' : 'off'})`;
|
||||
case 'ask':
|
||||
return `ask(${row.query})`;
|
||||
case 'plan':
|
||||
return row.steps.map(stepOutcome).join(' + ');
|
||||
default:
|
||||
return row.kind;
|
||||
}
|
||||
}
|
||||
|
||||
// Every line is read with no row chosen. `search(q)` is the place search,
|
||||
// `nothing` means Enter runs nothing.
|
||||
const OUTCOMES = [
|
||||
// A switch after what it switches is a switch, never a place.
|
||||
['noir off', 'style(normal)'],
|
||||
['Noir off', 'style(normal)'],
|
||||
['noir on', 'style(noir)'],
|
||||
['turn off noir', 'style(normal)'],
|
||||
['thermal off', 'style(normal)'],
|
||||
['night vision off', 'style(normal)'],
|
||||
['orbit off', 'camera(stop)'],
|
||||
['osm off', 'nothing'],
|
||||
['hud off', 'hud(off)'],
|
||||
['radio off', 'radio(disable)'],
|
||||
['cctv off', 'layer(cctv,off)'],
|
||||
['Bath on', 'search(Bath on)'],
|
||||
// A verb ends at a space: hyphenated names are names.
|
||||
['Hide-A-Way Lake noir', 'search(Hide-A-Way Lake noir)'],
|
||||
['Hide-A-Way Lake', 'search(Hide-A-Way Lake)'],
|
||||
['Show-Me Lake radio', 'search(Show-Me Lake radio)'],
|
||||
// A closing full stop, curly apostrophes and "please".
|
||||
['Show flights.', 'layer(flights,on)'],
|
||||
['show flights!', 'layer(flights,on)'],
|
||||
['please show flights', 'layer(flights,on)'],
|
||||
['Please, show flights', 'layer(flights,on)'],
|
||||
['show flights please', 'layer(flights,on)'],
|
||||
['North up.', 'camera(northUp)'],
|
||||
['please north up', 'camera(northUp)'],
|
||||
['Clear all layers!', 'camera(clear)'],
|
||||
['what’s here', 'ask(what’s here)'],
|
||||
['what’s here?', 'ask(what’s here?)'],
|
||||
['Paris, Texas.', 'search(Paris, Texas.)'],
|
||||
['Washington D.C.', 'search(Washington D.C.)'],
|
||||
['please', 'search(please)'],
|
||||
// Ask GEV (a billed call) needs a question, not a name.
|
||||
['Do it Best Hardware', 'search(Do it Best Hardware)'],
|
||||
['Can You Imagine', 'search(Can You Imagine)'],
|
||||
['Is This It', 'search(Is This It)'],
|
||||
['Where Is My Mind', 'search(Where Is My Mind)'],
|
||||
['can you show me', 'nothing'],
|
||||
['is it raining in tokyo', 'nothing'],
|
||||
['is it raining in tokyo?', 'ask(is it raining in tokyo?)'],
|
||||
['where is my mind', 'ask(where is my mind)'],
|
||||
['how far is paris', 'ask(how far is paris)'],
|
||||
['Can Tho City', 'search(Can Tho City)'],
|
||||
['Is there', 'search(Is there)'],
|
||||
// Pasted sentences are no place, and words about a layer are no place.
|
||||
['Show radio stations', 'layer(radio,on)'],
|
||||
['show radio station', 'layer(radio,on)'],
|
||||
['show flights here', 'layer(flights,on)'],
|
||||
['flights here', 'search(flights here)'],
|
||||
['I went to the store yesterday and it was really great', 'nothing'],
|
||||
['the quick brown fox jumps over the lazy dog', 'nothing'],
|
||||
['we saw so many flights over the city and it was loud', 'nothing'],
|
||||
['go to Austin and show flights', 'fly(austin) + layer(flights,on)'],
|
||||
// keywords without a verb ask for nothing,
|
||||
// however many clauses they fill, and names keep their words.
|
||||
['Fire and Rain', 'search(Fire and Rain)'],
|
||||
['Rain, Thermal', 'search(Rain, Thermal)'],
|
||||
['Weather and Traffic', 'search(Weather and Traffic)'],
|
||||
// Each word alone is a command that runs ("orbit", "tilt").
|
||||
['Orbit and Tilt', 'camera(orbit) + camera(tilt)'],
|
||||
['Noir and Thermal', 'search(Noir and Thermal)'],
|
||||
['Trains and Boats and Planes', 'search(Trains and Boats and Planes)'],
|
||||
['Storm Lake and Spencer', 'search(Storm Lake and Spencer)'],
|
||||
['Fire Island and Ocean Beach', 'search(Fire Island and Ocean Beach)'],
|
||||
['Thermal and Indio', 'search(Thermal and Indio)'],
|
||||
['Please Touch Museum', 'search(Please Touch Museum)'],
|
||||
['Kindly Lane', 'search(Kindly Lane)'],
|
||||
['Pretty Please', 'search(Pretty Please)'],
|
||||
['Yahoo!', 'search(Yahoo!)'],
|
||||
['Draw Bridge', 'search(Draw Bridge)'],
|
||||
['draw well', 'search(draw well)'],
|
||||
['draw a line', 'open-draw'],
|
||||
['How To Train Your Dragon', 'nothing'],
|
||||
['how to see satelites', 'ask(how to see satelites)'],
|
||||
['Train Station', 'search(Train Station)'],
|
||||
['Traffic Status', 'search(Traffic Status)'],
|
||||
['Remove Island', 'search(Remove Island)'],
|
||||
['Toggle Inn', 'search(Toggle Inn)'],
|
||||
['Disable Canyon', 'search(Disable Canyon)'],
|
||||
['remove island', 'nothing'],
|
||||
['show noir and show cctv', 'style(noir) + layer(cctv,on)'],
|
||||
// a name with "?" is offered to GEV,
|
||||
// never sent; a question's form is.
|
||||
['New York?', 'nothing'],
|
||||
['Truth or Consequences?', 'nothing'],
|
||||
['Ho Chi Minh City?', 'nothing'],
|
||||
['Santa Cruz de la Sierra?', 'nothing'],
|
||||
['東京都?', 'nothing'],
|
||||
['東京はどこ?', 'ask(東京はどこ?)'],
|
||||
['is it far?', 'ask(is it far?)'],
|
||||
['how about the weather in paris today?', 'nothing'],
|
||||
['123–45–6789', 'nothing'],
|
||||
['what is 4111–1111–1111–1111?', 'nothing'],
|
||||
// a switch with its place after "in" asks;
|
||||
// a vague "how do I" runs no walk; names with "senha" or "xox" in them
|
||||
// and addresses with numbers are places.
|
||||
['turn on radio in tokyo', 'fly(tokyo) + radio(enable)'],
|
||||
['enable radio in tokyo', 'fly(tokyo) + radio(enable)'],
|
||||
['turn on noir in tokyo', 'fly(tokyo) + style(noir)'],
|
||||
['how do I share', 'guide'],
|
||||
['how do I sha', 'nothing'],
|
||||
['Sachsenhausen', 'search(Sachsenhausen)'],
|
||||
['Xoxocotla', 'search(Xoxocotla)'],
|
||||
['Meguro Honmachi 2-chome', 'search(Meguro Honmachi 2-chome)'],
|
||||
[
|
||||
'1600 Pennsylvania Ave NW Washington DC 20500',
|
||||
'search(1600 Pennsylvania Ave NW Washington DC 20500)',
|
||||
],
|
||||
// A long comma address beside a layer word is a sentence; a verb that
|
||||
// starts a name asks for nothing; small talk asks no question.
|
||||
['San Jose, Santa Clara County, California, USA flights', 'nothing'],
|
||||
['Start Point noir', 'search(Start Point noir)'],
|
||||
['Track Hill noir', 'search(Track Hill noir)'],
|
||||
['Open Bay north up', 'search(Open Bay north up)'],
|
||||
['show noir', 'style(noir)'],
|
||||
['play radio tokyo', 'fly(tokyo) + radio(enable)'],
|
||||
["what's up", "search(what's up)"],
|
||||
["how's it going", "search(how's it going)"],
|
||||
["what's the weather in paris", "ask(what's the weather in paris)"],
|
||||
['Hauptstrasse 12 10115 Berlin', 'search(Hauptstrasse 12 10115 Berlin)'],
|
||||
// "of" and "at" may join the words of a name; CJK addresses and
|
||||
// postcodes are places.
|
||||
['Planes of Fame Air Museum', 'search(Planes of Fame Air Museum)'],
|
||||
['Boats at Sea', 'search(Boats at Sea)'],
|
||||
['flights over texas', 'fly(texas) + layer(flights,on)'],
|
||||
['北京市朝阳区建国路88号', 'search(北京市朝阳区建国路88号)'],
|
||||
['東京都港区六本木6丁目', 'search(東京都港区六本木6丁目)'],
|
||||
['Washington DC 20500-0003', 'search(Washington DC 20500-0003)'],
|
||||
['Calle 100 # 19-61 Bogota', 'search(Calle 100 # 19-61 Bogota)'],
|
||||
// Addresses that look like numbers to keep, and long names, are offered
|
||||
// to search on purpose; Enter runs nothing. "Track 7" and "Nearest Plane
|
||||
// Crash Site" are names.
|
||||
['Tverskaya 13 125009 Moscow', 'search(Tverskaya 13 125009 Moscow)'],
|
||||
['Москва, ул. Тверская, д. 13, 125009', 'nothing'],
|
||||
['San Miguel de las Piedras Primera Sección', 'nothing'],
|
||||
['Goto', 'search(Goto)'],
|
||||
['goto tokyo', 'search(tokyo)'],
|
||||
['Track 7', 'search(Track 7)'],
|
||||
['Track 29', 'search(Track 29)'],
|
||||
['Nearest Plane Crash Site', 'search(Nearest Plane Crash Site)'],
|
||||
['nearest plane', 'nearest'],
|
||||
// Lines the mounted Enter table pins too, read through the module.
|
||||
['tokyo traffic', 'search(tokyo traffic)'],
|
||||
['flights near tokyo', 'fly(tokyo) + layer(flights,on)'],
|
||||
['radio near Clear Lake', 'search(clear lake)'],
|
||||
['Thermal', 'search(Thermal)'],
|
||||
['Thermal, California', 'search(Thermal, California)'],
|
||||
['radio', 'search(radio)'],
|
||||
['share', 'nothing'],
|
||||
['hide', 'nothing'],
|
||||
['Turn on the radio', 'layer(radio,on)'],
|
||||
];
|
||||
|
||||
for (const [text, expected] of OUTCOMES)
|
||||
test(`Enter on ${JSON.stringify(text)} runs ${expected}`, () => {
|
||||
assert.equal(outcome(text), expected);
|
||||
});
|
||||
|
||||
test('"show flights" with Live Flights on offers Live Flights, not Military Flights', () => {
|
||||
assert.equal(
|
||||
outcome('show flights', { on: ['flights'] }),
|
||||
'layer(flights,on)',
|
||||
);
|
||||
assert.equal(
|
||||
outcome('turn on flights', { on: ['flights'] }),
|
||||
'layer(flights,on)',
|
||||
);
|
||||
const { rows, defaultIndex } = createOmnibar({
|
||||
layers: layers(['flights']),
|
||||
}).rows('show flights');
|
||||
// Nothing to switch on the default row; Military Flights is offered after.
|
||||
assert.equal(rows[defaultIndex].hint, 'Layer');
|
||||
assert.ok(rows.some((row) => row.id === 'military'));
|
||||
assert.equal(outcome('hide flights', { on: [] }), 'layer(flights,off)');
|
||||
// "military" names Military Flights, never Live Flights.
|
||||
assert.equal(outcome('show military'), 'layer(military,on)');
|
||||
});
|
||||
|
||||
test('a layer near a place cannot admit an unrelated bare style step', () => {
|
||||
assert.doesNotMatch(outcome('flights near Austin and noir'), /style\(noir\)/);
|
||||
assert.equal(
|
||||
outcome('flights near Austin'),
|
||||
'fly(austin) + layer(flights,on)',
|
||||
);
|
||||
});
|
||||
|
||||
test('private text never reaches the place service, the search or GEV', () => {
|
||||
const omnibar = createOmnibar({ layers: layers() });
|
||||
for (const text of [
|
||||
'123 45 6789',
|
||||
'123456789',
|
||||
'123-45-6789',
|
||||
'4111 1111',
|
||||
'١٢٣٤, ٥٦٧٨',
|
||||
'what is my pass\u200bword: violet?',
|
||||
'4111-1111-1111-1111',
|
||||
'+1 415 555',
|
||||
'415 555 0',
|
||||
'415.555.0100',
|
||||
'hunter22',
|
||||
'letmein1',
|
||||
'Tr0ub4dor&3',
|
||||
'pa$$w0rd',
|
||||
'token: abc',
|
||||
'api key=xyz',
|
||||
'password hunter2',
|
||||
'[email protected]',
|
||||
'4111 1111 1111 1111',
|
||||
'john@example.com',
|
||||
'sk_live_abc',
|
||||
'٤١١١ ١١١١ ١١١١ ١١١١',
|
||||
'४१११ ११११ ११११ ११११',
|
||||
'4111.1111.1111.1111',
|
||||
'what is 4111.1111.1111.1111',
|
||||
'where is john@example.com',
|
||||
'card ٤١١١١١١١١١١١١١١١ valid?',
|
||||
'123–45–6789',
|
||||
'415‐555‐0100',
|
||||
'415−555−0100',
|
||||
'4111:1111:1111:1111',
|
||||
'4111|1111|1111|1111',
|
||||
'4111\u200b1111\u200b1111\u200b1111',
|
||||
'contraseña: hunter',
|
||||
'Passwort: geheim',
|
||||
'mot de passe: chat',
|
||||
'пароль qwerty',
|
||||
'api key abcdefgh',
|
||||
]) {
|
||||
assert.equal(omnibar.placeQuery(text), null, text);
|
||||
assert.equal(omnibar.countRequest(text), null, text);
|
||||
const { rows, defaultIndex } = omnibar.rows(text);
|
||||
// Only a row to search it as a place on purpose, never by Enter.
|
||||
assert.ok(
|
||||
rows.every((row) => row.kind === 'place' && row.explicit),
|
||||
text,
|
||||
);
|
||||
assert.equal(defaultIndex, -1, text);
|
||||
}
|
||||
// Callsigns, postcodes, coordinates and street numbers are not secrets.
|
||||
assert.equal(omnibar.placeQuery('SW1A 1AA'), 'SW1A 1AA');
|
||||
assert.equal(omnibar.placeQuery('10 Downing Street'), '10 Downing Street');
|
||||
assert.equal(omnibar.placeQuery('Route 66'), 'Route 66');
|
||||
for (const callsign of ['UAL2110', 'BAW15K', 'N123AB'])
|
||||
assert.equal(omnibar.placeQuery(callsign), null, callsign);
|
||||
for (const text of ['30.2672, -97.7431', '14R PU 2090 4906']) {
|
||||
const { rows, defaultIndex } = omnibar.rows(text);
|
||||
assert.equal(rows[defaultIndex].kind, 'place', text);
|
||||
assert.ok(rows[defaultIndex].coords, text);
|
||||
}
|
||||
});
|
||||
|
||||
test('private text still finds things already on the map, locally', () => {
|
||||
const omnibar = createOmnibar({ layers: layers() });
|
||||
const found = [];
|
||||
const { rows } = omnibar.rows('366123456', {
|
||||
entities: (text) => {
|
||||
found.push(text);
|
||||
return [
|
||||
{
|
||||
key: 'v1',
|
||||
icon: 'directions_boat',
|
||||
identity: 'v1',
|
||||
title: '366123456',
|
||||
layerName: 'Vessels',
|
||||
},
|
||||
];
|
||||
},
|
||||
});
|
||||
assert.deepEqual(found, ['366123456']);
|
||||
assert.deepEqual(
|
||||
rows.map((row) => row.kind),
|
||||
['entity'],
|
||||
);
|
||||
});
|
||||
|
||||
test('a map item named like a place follows the place; a callsign leads', () => {
|
||||
const omnibar = createOmnibar({ layers: layers() });
|
||||
const entities = (text) =>
|
||||
[
|
||||
{
|
||||
key: 's1',
|
||||
icon: 'directions_boat',
|
||||
identity: 's1',
|
||||
title: 'HAMBURG',
|
||||
layerName: 'Vessels',
|
||||
},
|
||||
{
|
||||
key: 'f1',
|
||||
icon: 'flight',
|
||||
identity: 'f1',
|
||||
title: 'UAL123',
|
||||
layerName: 'Flights',
|
||||
},
|
||||
].filter((item) => item.title.toLowerCase().startsWith(text.toLowerCase()));
|
||||
const hamburg = omnibar.rows('Hamburg', { entities });
|
||||
assert.equal(hamburg.rows[hamburg.defaultIndex].kind, 'place');
|
||||
assert.equal(hamburg.rows[1].kind, 'entity');
|
||||
const callsign = omnibar.rows('UAL123', { entities });
|
||||
assert.equal(callsign.rows[callsign.defaultIndex].kind, 'entity');
|
||||
});
|
||||
|
||||
test('a long name or an address that looks private can be searched on purpose', () => {
|
||||
const omnibar = createOmnibar({ layers: layers() });
|
||||
for (const text of [
|
||||
'Москва, ул. Тверская, д. 13, 125009',
|
||||
'San Miguel de las Piedras Primera Sección',
|
||||
]) {
|
||||
const { rows, defaultIndex } = omnibar.rows(text);
|
||||
assert.equal(defaultIndex, -1, text);
|
||||
const row = rows.find((each) => each.explicit);
|
||||
assert.equal(row?.place, text, text);
|
||||
assert.equal(omnibar.placeQuery(text), null, text);
|
||||
}
|
||||
// A bare number names no place.
|
||||
assert.deepEqual(omnibar.rows('4111 1111 1111 1111').rows, []);
|
||||
});
|
||||
|
||||
test('a pasted sentence is never sent to the place service', () => {
|
||||
const omnibar = createOmnibar({ layers: layers() });
|
||||
for (const text of [
|
||||
'I went to the store yesterday and it was really great',
|
||||
'we saw so many flights over the city and it was loud',
|
||||
'Show radio stations',
|
||||
'noir off',
|
||||
'can you show me',
|
||||
])
|
||||
assert.equal(omnibar.placeQuery(text), null, text);
|
||||
assert.equal(omnibar.placeQuery('Tokyo traffic'), 'Tokyo traffic');
|
||||
assert.equal(omnibar.placeQuery('flights near Tokyo.'), 'tokyo');
|
||||
assert.equal(omnibar.placeQuery('Paris, Texas.'), 'Paris, Texas.');
|
||||
assert.equal(omnibar.placeQuery('go to Paris, noir'), 'paris');
|
||||
assert.equal(omnibar.placeQuery('turn on radio in tokyo'), 'tokyo');
|
||||
assert.equal(omnibar.placeQuery('Sachsenhausen'), 'Sachsenhausen');
|
||||
});
|
||||
|
||||
// The wording people use reaches each feature's own walk, and Enter starts
|
||||
// it.
|
||||
const GUIDE_PHRASES = [
|
||||
['how do i change the map style', 'styles'],
|
||||
['how to change the visual style', 'styles'],
|
||||
['show me how to use night vision', 'styles'],
|
||||
['how do i turn on the hud', 'hud'],
|
||||
['how do i hide the hud', 'hud'],
|
||||
['how do i tilt', 'tilt'],
|
||||
['how do i tilt the map', 'tilt'],
|
||||
['how to tilt the camera', 'tilt'],
|
||||
['how to share this view', 'share'],
|
||||
['how do i share a link', 'share'],
|
||||
['how do i reset', 'globe'],
|
||||
['how do i get back to the globe', 'globe'],
|
||||
['how do i see the whole globe', 'globe'],
|
||||
['how do i point north', 'north'],
|
||||
['how do i use the compass', 'north'],
|
||||
['how do i clear all layers', 'clear'],
|
||||
['how to turn off all layers', 'clear'],
|
||||
['how do i change the map', 'map-source'],
|
||||
['how do i switch to openstreetmap', 'map-source'],
|
||||
['how to measure distance', 'draw'],
|
||||
['how do i draw', 'draw'],
|
||||
['how do i draw a line', 'draw'],
|
||||
['how do i measure an area', 'draw'],
|
||||
['how do i search layers', 'find-layer'],
|
||||
['how do i change language', 'preferences'],
|
||||
];
|
||||
for (const [text, feature] of GUIDE_PHRASES)
|
||||
test(`${JSON.stringify(text)} starts the ${feature} walk`, () => {
|
||||
const { rows, defaultIndex } = createOmnibar({ layers: layers() }).rows(
|
||||
text,
|
||||
);
|
||||
assert.equal(rows[defaultIndex]?.kind, 'guide', text);
|
||||
assert.equal(rows[defaultIndex].guide.feature, feature, text);
|
||||
});
|
||||
|
||||
test('a layer named in full leads a feature topic its words also hold', () => {
|
||||
const all = createOmnibar({
|
||||
layers: [
|
||||
...layers(),
|
||||
{ id: 'recent-imagery', name: 'Recent Imagery', enabled: false },
|
||||
{ id: 'weather-lightning', name: 'Lightning density', enabled: false },
|
||||
],
|
||||
});
|
||||
for (const [text, id] of [
|
||||
['how do I see recent imagery', 'recent-imagery'],
|
||||
['how do I see lightning density', 'weather-lightning'],
|
||||
]) {
|
||||
const { rows, defaultIndex } = all.rows(text);
|
||||
assert.equal(rows[defaultIndex].guide.layer?.id, id, text);
|
||||
}
|
||||
// The Context panel's walk stays first beside a layer named Global
|
||||
// Context.
|
||||
const context = createOmnibar({
|
||||
layers: [
|
||||
{ id: 'military-awareness', name: 'Global Context', enabled: false },
|
||||
],
|
||||
}).rows('how do I open global context');
|
||||
assert.equal(context.rows[context.defaultIndex].guide.feature, 'context');
|
||||
});
|
||||
|
||||
test('only an address that looks like a number may be searched anyway', () => {
|
||||
const omnibar = createOmnibar({ layers: layers() });
|
||||
for (const text of [
|
||||
'password hunter2',
|
||||
'[email protected]',
|
||||
'hunter22',
|
||||
'sk-abc123def',
|
||||
'DE89 3704 0044 0532 0130 00',
|
||||
'pin 1234567',
|
||||
'door code 4421',
|
||||
// A number beside a word that says what it is, or one too long for an
|
||||
// address.
|
||||
'code 12345678 Berlin',
|
||||
'token 12345678 Berlin',
|
||||
'user john pass 12345678',
|
||||
'card 4111 1111 1111 1111 please',
|
||||
'my card is 4111111111111111',
|
||||
'routing 021000021 New York',
|
||||
'phone +1 415 555 0100 office',
|
||||
'BSN 123456782 Utrecht',
|
||||
'medicare 1234567890 Sydney',
|
||||
// Digits and words read as they fold: superscript, circled, full-width
|
||||
// or split by a zero-width space; card and phone words in other
|
||||
// languages.
|
||||
'Berlin ⁴¹¹¹¹¹¹¹¹¹¹¹¹¹¹¹',
|
||||
'Berlin ①②③④⑤⑥⑦⑧⑨⑩',
|
||||
'Main St 12 ¹²³⁴⁵⁶⁷⁸⁹¹²³⁴⁵⁶ Berlin',
|
||||
'card 4111 1111 Berlin',
|
||||
'ca\u200brd 4111 1111 Berlin',
|
||||
'Visa 4111 1111 Berlin',
|
||||
'Kreditkarte 4111 1111 Berlin',
|
||||
'Telefon 912 34 567',
|
||||
])
|
||||
assert.deepEqual(omnibar.rows(text).rows, [], text);
|
||||
for (const text of [
|
||||
'Москва, ул. Тверская, д. 13, 125009',
|
||||
'Jl. Jend. Sudirman No. 52-53, 12190 Jakarta',
|
||||
])
|
||||
assert.ok(
|
||||
omnibar.rows(text).rows.some((row) => row.explicit),
|
||||
text,
|
||||
);
|
||||
});
|
||||
|
||||
test("a line naming a layer still starts that layer's walk", () => {
|
||||
const { rows, defaultIndex } = createOmnibar({ layers: layers() }).rows(
|
||||
'how to turn on flights',
|
||||
);
|
||||
assert.equal(rows[defaultIndex].guide.layer.id, 'flights');
|
||||
});
|
||||
|
||||
test('every feature the words name has a walk', async () => {
|
||||
const { FEATURE_GUIDES } = await import('./omnibarGuide.js');
|
||||
const omnibar = createOmnibar({ layers: layers() });
|
||||
for (const [text] of GUIDE_PHRASES) {
|
||||
const { rows, defaultIndex } = omnibar.rows(text);
|
||||
const feature = rows[defaultIndex].guide.feature;
|
||||
assert.equal(typeof FEATURE_GUIDES[feature], 'function', feature);
|
||||
}
|
||||
});
|
||||
|
||||
test('the line is normalised once, in one place', () => {
|
||||
assert.equal(normalizeLine(' Show flights. '), 'Show flights');
|
||||
// "please" goes only around a request; in a name it stays.
|
||||
assert.equal(readLine('please, north up!'), 'north up');
|
||||
assert.equal(readLine('please show flights'), 'show flights');
|
||||
assert.equal(readLine('Please Touch Museum'), 'Please Touch Museum');
|
||||
assert.equal(readLine('Kindly Lane'), 'Kindly Lane');
|
||||
assert.equal(readLine('Pretty Please'), 'Pretty Please');
|
||||
assert.equal(normalizeLine('please, north up!'), 'please, north up');
|
||||
assert.equal(normalizeLine('what’s here'), "what's here");
|
||||
assert.equal(normalizeLine('東京?'), '東京?');
|
||||
assert.equal(normalizeLine('Tokyo'), 'Tokyo');
|
||||
assert.equal(normalizeLine('Washington D.C.'), 'Washington D.C.');
|
||||
assert.equal(normalizeLine('St. Louis.'), 'St. Louis');
|
||||
assert.equal(normalizeLine('please'), 'please');
|
||||
});
|
||||
|
||||
test('the rows the parser and the Enter rule agree on come from one place', () => {
|
||||
// A command named exactly is the default; one merely begun only follows.
|
||||
const omnibar = createOmnibar({ layers: layers() });
|
||||
assert.equal(outcome('North up'), 'camera(northUp)');
|
||||
assert.equal(outcome('> North up'), 'camera(northUp)');
|
||||
const begun = omnibar.rows('> nort');
|
||||
assert.equal(begun.defaultIndex, -1);
|
||||
assert.equal(begun.rows[0].command, 'north');
|
||||
// A Photon place counts for the credit.
|
||||
const { rows } = omnibar.rows('Shibuya', {
|
||||
places: [
|
||||
{
|
||||
name: 'Shibuya',
|
||||
detail: 'Tokyo, Japan',
|
||||
latitude: 35.66,
|
||||
longitude: 139.7,
|
||||
},
|
||||
],
|
||||
});
|
||||
assert.equal(rows[0].source, 'photon');
|
||||
});
|
||||
|
||||
test('coordinates named as the place are flown to, never refused or looked up', () => {
|
||||
const omnibar = createOmnibar({ layers: layers() });
|
||||
for (const text of [
|
||||
'go to 30.27, -97.74',
|
||||
'go to 48.85 2.35',
|
||||
'go to 14R PU 2090 4906',
|
||||
]) {
|
||||
const { rows, defaultIndex } = omnibar.rows(text);
|
||||
assert.equal(rows[defaultIndex]?.kind, 'place', text);
|
||||
assert.match(rows[defaultIndex].label, /°[NS] .*°[EW]/, text);
|
||||
assert.equal(omnibar.placeQuery(text), null, text);
|
||||
}
|
||||
const { rows, defaultIndex } = omnibar.rows(
|
||||
'show flights near 30.27, -97.74',
|
||||
);
|
||||
assert.equal(rows[defaultIndex].kind, 'plan');
|
||||
assert.equal(omnibar.placeQuery('show flights near 30.27, -97.74'), null);
|
||||
// A card number is still no spot.
|
||||
assert.equal(omnibar.rows('go to 4111 1111 1111 1111').defaultIndex, -1);
|
||||
assert.equal(omnibar.placeQuery('go to ,'), null);
|
||||
});
|
||||
|
||||
test('only a layer in or near a place is counted, never a name', () => {
|
||||
const omnibar = createOmnibar({
|
||||
layers: [...layers(), { id: 'ships', name: 'Ships', enabled: false }],
|
||||
});
|
||||
assert.ok(omnibar.countRequest('flights over Texas'));
|
||||
assert.ok(omnibar.countRequest('quakes above M5 in Japan'));
|
||||
for (const text of [
|
||||
'Ship Bottom',
|
||||
'Radio City Music Hall',
|
||||
'radio settings',
|
||||
'show me how to turn off flights',
|
||||
])
|
||||
assert.equal(omnibar.countRequest(text), null, text);
|
||||
});
|
||||
|
||||
test('a place named Left or Right is no panel to close', () => {
|
||||
const omnibar = createOmnibar({ layers: layers(['flights']) });
|
||||
const { rows, defaultIndex } = omnibar.rows(
|
||||
'hide flights near Left Bank, Paris',
|
||||
);
|
||||
assert.equal(rows[defaultIndex].kind, 'plan');
|
||||
assert.ok(rows[defaultIndex].steps.every((step) => step.kind !== 'panel'));
|
||||
for (const text of ['hide the left panel', 'close right side']) {
|
||||
const read = omnibar.rows(text);
|
||||
assert.ok(
|
||||
read.rows[read.defaultIndex].steps.some((step) => step.kind === 'panel'),
|
||||
text,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('the place service gets the whole place, however it is asked', () => {
|
||||
const omnibar = createOmnibar({ layers: layers() });
|
||||
assert.equal(
|
||||
omnibar.placeQuery('flights near Trinidad and Tobago'),
|
||||
'trinidad and tobago',
|
||||
);
|
||||
assert.equal(
|
||||
omnibar.placeQuery('take me to New York City NY'),
|
||||
'New York City NY',
|
||||
);
|
||||
// A signed longitude or a semicolon stays inside the coordinates.
|
||||
for (const text of [
|
||||
'show flights near 30.27, +97.74',
|
||||
'go to 30.27; -97.74',
|
||||
]) {
|
||||
const { rows, defaultIndex } = omnibar.rows(text);
|
||||
assert.ok(defaultIndex >= 0, text);
|
||||
assert.equal(omnibar.placeQuery(text), null, text);
|
||||
assert.notEqual(rows[defaultIndex].kind, 'none', text);
|
||||
}
|
||||
});
|
||||
|
||||
test('several switches in one line are one plan', () => {
|
||||
const omnibar = createOmnibar({ layers: layers(['flights']) });
|
||||
for (const text of ['hide flights, show radio', 'hide flights; show radio']) {
|
||||
const { rows, defaultIndex } = omnibar.rows(text);
|
||||
assert.equal(rows[defaultIndex].kind, 'plan', text);
|
||||
}
|
||||
});
|
||||
|
||||
test('a place named with "and" stays whole, and a place keeps how it was typed', () => {
|
||||
const omnibar = createOmnibar({
|
||||
layers: [{ id: 'flights', name: 'Live Flights', enabled: false }],
|
||||
});
|
||||
const first = (text) => omnibar.rows(text, { places: [] }).rows[0];
|
||||
const plan = first('flights near Trinidad and Tobago');
|
||||
assert.equal(plan.kind, 'plan');
|
||||
assert.equal(plan.steps[0].place, 'trinidad and tobago');
|
||||
assert.equal(
|
||||
first('flights near Bosnia & Herzegovina').steps[0].place,
|
||||
'bosnia and herzegovina',
|
||||
);
|
||||
assert.equal(
|
||||
first('flights near Saint Vincent and the Grenadines').steps[0].place,
|
||||
'saint vincent and the grenadines',
|
||||
);
|
||||
// Two places joined by "and" are still two.
|
||||
assert.equal(
|
||||
first('flights near Austin and Dallas').steps[0].place,
|
||||
'austin',
|
||||
);
|
||||
// "İstanbul" is searched without a stray combining dot, and labelled as typed.
|
||||
const istanbul = first('show flights in İstanbul');
|
||||
assert.equal(istanbul.steps[0].place, 'istanbul');
|
||||
assert.match(istanbul.label, /^İstanbul /);
|
||||
assert.equal(first('iPhone store').label, 'Go to iPhone store');
|
||||
});
|
||||
|
||||
test('"everything except" keeps the layers named and switches off the rest', () => {
|
||||
const omnibar = createOmnibar({
|
||||
layers: layers(['flights', 'radio', 'cctv']),
|
||||
});
|
||||
const first = (text) => omnibar.rows(text, { places: [] }).rows[0];
|
||||
for (const text of [
|
||||
'hide everything except flights',
|
||||
'turn off all but live flights',
|
||||
'clear everything other than flights',
|
||||
]) {
|
||||
const plan = first(text);
|
||||
assert.equal(plan.kind, 'plan', text);
|
||||
assert.deepEqual(
|
||||
plan.steps.map(stepOutcome),
|
||||
['layer(radio,off)', 'layer(cctv,off)'],
|
||||
text,
|
||||
);
|
||||
}
|
||||
assert.deepEqual(
|
||||
first('hide everything except flights and the cctv').steps.map(stepOutcome),
|
||||
['layer(radio,off)'],
|
||||
);
|
||||
// Enter runs it: the line asked for it in so many words.
|
||||
assert.equal(
|
||||
outcome('hide everything except flights', { on: ['flights', 'radio'] }),
|
||||
'layer(radio,off)',
|
||||
);
|
||||
// A layer to keep that is not read switches nothing off.
|
||||
const unread = omnibar.rows('hide everything except flights and the fog', {
|
||||
places: [],
|
||||
});
|
||||
assert.deepEqual(
|
||||
unread.rows.map((row) => row.kind),
|
||||
['ask'],
|
||||
);
|
||||
assert.equal(unread.defaultIndex, -1);
|
||||
const alone = createOmnibar({ layers: layers(['flights']) });
|
||||
assert.equal(
|
||||
alone.rows('hide everything except flights').rows[0].kind,
|
||||
'none',
|
||||
);
|
||||
// Naming no layer to keep is not this reading.
|
||||
assert.notEqual(first('hide everything except the coast').kind, 'plan');
|
||||
});
|
||||
|
||||
test('"from the map" and a doubled verb do not change the request', () => {
|
||||
assert.equal(
|
||||
outcome('remove flights from the map', { on: ['flights'] }),
|
||||
'layer(flights,off)',
|
||||
);
|
||||
assert.equal(
|
||||
outcome('hide flights off the globe', { on: ['flights'] }),
|
||||
'layer(flights,off)',
|
||||
);
|
||||
assert.equal(normalizeLine('show show flights'), 'show flights');
|
||||
assert.equal(normalizeLine('turn off turn off flights'), 'turn off flights');
|
||||
});
|
||||
|
||||
test('a grid reference after "near" is the place', () => {
|
||||
const omnibar = createOmnibar({ layers: layers() });
|
||||
const plan = omnibar.rows('flights near 14R PU 2090 4906', { places: [] })
|
||||
.rows[0];
|
||||
assert.equal(plan.kind, 'plan');
|
||||
assert.equal(plan.steps[0].kind, 'place');
|
||||
assert.match(plan.steps[0].place, /^14R PU 2090 4906$/i);
|
||||
});
|
||||
|
||||
test('a keyword that begins a name offers no plan to the rest of it', () => {
|
||||
const omnibar = createOmnibar({ layers: layers() });
|
||||
for (const text of ['Radio City', 'Traffic Island', 'radio island']) {
|
||||
const { rows } = omnibar.rows(text, { places: [] });
|
||||
assert.equal(rows[0].kind, 'place', text);
|
||||
assert.ok(!rows.some((row) => row.kind === 'plan'), text);
|
||||
assert.ok(
|
||||
rows.some((row) => row.kind === 'layer'),
|
||||
text,
|
||||
);
|
||||
}
|
||||
// A keyword after the place, or before a place that is no name's
|
||||
// fragment, still offers its plan.
|
||||
for (const text of [
|
||||
'tokyo traffic',
|
||||
'earthquakes japan',
|
||||
'radio London',
|
||||
'traffic city hall',
|
||||
'traffic county cork',
|
||||
'earthquakes valley forge',
|
||||
'traffic road to hana',
|
||||
]) {
|
||||
const { rows } = omnibar.rows(text, { places: [] });
|
||||
assert.ok(
|
||||
rows.some((row) => row.kind === 'plan'),
|
||||
text,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('"except" keeps a layer and the one it shows through together', () => {
|
||||
const omnibar = createOmnibar({
|
||||
layers: [
|
||||
{ id: 'flights', name: 'Live Flights', enabled: true },
|
||||
{ id: 'satellites', name: 'Satellites', enabled: true },
|
||||
{ id: 'rocket-launches', name: 'Space Missions', enabled: true },
|
||||
],
|
||||
});
|
||||
for (const text of [
|
||||
'hide everything except space missions',
|
||||
'hide everything except satellites',
|
||||
])
|
||||
assert.deepEqual(
|
||||
omnibar.rows(text, { places: [] }).rows[0].steps.map(stepOutcome),
|
||||
['layer(flights,off)'],
|
||||
text,
|
||||
);
|
||||
});
|
||||
|
||||
test('"except" leaves Satellites to switch off with Space Missions off', () => {
|
||||
const omnibar = createOmnibar({
|
||||
layers: [
|
||||
{ id: 'flights', name: 'Live Flights', enabled: true },
|
||||
{ id: 'satellites', name: 'Satellites', enabled: true },
|
||||
{ id: 'rocket-launches', name: 'Space Missions', enabled: false },
|
||||
],
|
||||
});
|
||||
assert.deepEqual(
|
||||
omnibar
|
||||
.rows('hide everything except space missions', { places: [] })
|
||||
.rows[0].steps.map(stepOutcome),
|
||||
['layer(flights,off)', 'layer(satellites,off)'],
|
||||
);
|
||||
for (const text of [
|
||||
'hide everything except flights from the map',
|
||||
'clear everything except flights from the map',
|
||||
'please clear everything except flights from the map',
|
||||
'hide everything except flights from the map, please',
|
||||
])
|
||||
assert.deepEqual(
|
||||
omnibar.rows(text, { places: [] }).rows[0].steps.map(stepOutcome),
|
||||
['layer(satellites,off)'],
|
||||
text,
|
||||
);
|
||||
// "clear" takes the ending off only for the whole map: "clear flights
|
||||
// from the map" never offers to turn Flights on.
|
||||
for (const text of [
|
||||
'clear flights from the map',
|
||||
'clear all flights from the map',
|
||||
'clear all flights except ships from the map',
|
||||
])
|
||||
assert.ok(
|
||||
!omnibar
|
||||
.rows(text, { places: [] })
|
||||
.rows.some((row) =>
|
||||
(row.steps || []).some(
|
||||
(step) => step.kind === 'layer' && step.enabled,
|
||||
),
|
||||
),
|
||||
);
|
||||
// After "show" the ending is part of what is asked.
|
||||
assert.equal(
|
||||
omnibar.rows('show me the view from the map', { places: [] }).defaultIndex,
|
||||
-1,
|
||||
);
|
||||
// The whole map cleared "from the map" is the same plan, not a place.
|
||||
for (const text of [
|
||||
'hide everything from the map',
|
||||
'remove all layers from the map',
|
||||
'clear the layers from the map',
|
||||
]) {
|
||||
const { rows } = omnibar.rows(text, { places: [] });
|
||||
assert.equal(rows[0].kind, 'plan', text);
|
||||
assert.ok(!rows.some((row) => row.kind === 'place'), text);
|
||||
}
|
||||
});
|
||||
|
||||
test('"turn off the screen" is no layer switch and no place', () => {
|
||||
for (const text of ['turn off the screen', 'switch off the map'])
|
||||
assert.equal(outcome(text, { on: ['flights'] }), 'nothing', text);
|
||||
});
|
||||
|
||||
test('a place after a compound country is another place', () => {
|
||||
const omnibar = createOmnibar({ layers: layers() });
|
||||
const places = (text) =>
|
||||
omnibar
|
||||
.rows(text, { places: [] })
|
||||
.rows.filter((row) => row.kind === 'place')
|
||||
.map((row) => row.place.toLowerCase());
|
||||
assert.deepEqual(places('flights near trinidad and tobago and barbados'), [
|
||||
'trinidad and tobago',
|
||||
'barbados',
|
||||
]);
|
||||
assert.deepEqual(places('flights near Paris and Trinidad and Tobago'), [
|
||||
'paris',
|
||||
'trinidad and tobago',
|
||||
]);
|
||||
});
|
||||
|
||||
test('a kind of place written before its name keeps the plan', () => {
|
||||
const omnibar = createOmnibar({ layers: layers() });
|
||||
for (const text of [
|
||||
'earthquakes lake tahoe',
|
||||
'earthquakes mount fuji',
|
||||
'traffic tower bridge',
|
||||
]) {
|
||||
const { rows } = omnibar.rows(text, { places: [] });
|
||||
assert.ok(
|
||||
rows.some((row) => row.kind === 'plan'),
|
||||
text,
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -2,7 +2,6 @@ import { UiLifetime } from './uiLifetime.js';
|
||||
import { prefersCollapsed, readPanelState } from './rail/panelState.js';
|
||||
import { usePanelChromeStore } from './stores/panelChrome.js';
|
||||
import { applicationPinia } from './vueRuntime.js';
|
||||
import { displayPanelScroller } from './displayPanelScroll.js';
|
||||
import { PanelPositionControls } from './panelPositionControls.js';
|
||||
import { PanelLayoutController } from './panelLayoutController.js';
|
||||
import {
|
||||
@@ -23,6 +22,7 @@ const SHARE_PANEL_STATE_SPECS = Object.freeze([
|
||||
{ id: 'radio-panel' },
|
||||
{ id: 'scene-panel' },
|
||||
{ id: 'global-context-panel' },
|
||||
{ id: 'space-missions-panel' },
|
||||
{ id: 'pp-toggles' },
|
||||
{ id: 'param-slider-panel' },
|
||||
]);
|
||||
@@ -49,6 +49,7 @@ const COCKPIT_ENTRY_COLLAPSE_PANEL_IDS = Object.freeze([
|
||||
'utilities-panel',
|
||||
'pp-toggles',
|
||||
'global-context-panel',
|
||||
'space-missions-panel',
|
||||
'radio-panel',
|
||||
]);
|
||||
|
||||
@@ -121,7 +122,7 @@ export class PanelChrome {
|
||||
readDisplayScrollTop: () =>
|
||||
this._displayPortalScrollRestoreOwner === 'standard'
|
||||
? this._standardDisplayScrollTop
|
||||
: displayPanelScroller(this._ppToggles)?.scrollTop || 0,
|
||||
: this._ppToggles?.scrollTop || 0,
|
||||
});
|
||||
}
|
||||
get hud() {
|
||||
|
||||
@@ -429,6 +429,31 @@ test('destroying the chrome inside Cockpit puts back the panels its entry closed
|
||||
assert.equal(data.classList.contains('collapsed'), false);
|
||||
});
|
||||
|
||||
test('Cockpit entry folds the Space Missions panel away and exit brings it back', () => {
|
||||
document.body.innerHTML = `<div id="space-missions-panel"></div>`;
|
||||
const store = usePanelChromeStore(createPinia());
|
||||
const chrome = panelChrome(store);
|
||||
const missions = document.getElementById('space-missions-panel');
|
||||
followPanelState(store, 'space-missions-panel', missions);
|
||||
chrome.enterCockpit();
|
||||
assert.equal(missions.classList.contains('collapsed'), true);
|
||||
chrome.exitCockpit();
|
||||
assert.equal(missions.classList.contains('collapsed'), false);
|
||||
chrome.destroy();
|
||||
});
|
||||
|
||||
test('a share link records whether the Space Missions panel is open', () => {
|
||||
document.body.innerHTML = `<div id="space-missions-panel"></div>`;
|
||||
const store = usePanelChromeStore(createPinia());
|
||||
const chrome = panelChrome(store);
|
||||
const state = chrome._buildSharePanelState();
|
||||
assert.deepEqual(
|
||||
state.specs.filter((spec) => spec.id === 'space-missions-panel'),
|
||||
[{ id: 'space-missions-panel', collapsed: false }],
|
||||
);
|
||||
chrome.destroy();
|
||||
});
|
||||
|
||||
test('the accordion closes peers through the real store, and opens them again', () => {
|
||||
document.body.innerHTML = `
|
||||
<div id="data-panel" data-panel-id="data-panel"></div>
|
||||
|
||||
@@ -57,6 +57,9 @@ const RIGHT_STACK_OBSTACLE_SELECTOR = [
|
||||
'#intel-hud .hud-right-edge',
|
||||
'#cockpit-context',
|
||||
'#cockpit-signal-stream',
|
||||
// The "NEW: GEV Stories" card under the Stories button: panels start below
|
||||
// it while it is up, so its buttons never sit over a panel's controls.
|
||||
'#hPop',
|
||||
'#cesium-credits .cesium-credit-logoContainer',
|
||||
'#cesium-credits .cesium-credit-textContainer',
|
||||
'#gev-credits',
|
||||
@@ -64,6 +67,29 @@ const RIGHT_STACK_OBSTACLE_SELECTOR = [
|
||||
'#gev-voice-control',
|
||||
'#world-timeline',
|
||||
].join(', ');
|
||||
/** The body class the welcome sets while BROWSE STORIES loads. */
|
||||
const OPENING_STORIES = 'first-run-opening-stories';
|
||||
/**
|
||||
* True when a mutation can show or hide the Stories card (`#hPop`): the card
|
||||
* itself coming or going, or the welcome that hides it (`#first-run-launcher`,
|
||||
* and the body class it sets while BROWSE STORIES loads) ending.
|
||||
*/
|
||||
export function movesStoriesCard(record) {
|
||||
if (record.type === 'attributes')
|
||||
return (
|
||||
(record.oldValue || '').split(/\s+/).includes(OPENING_STORIES) !==
|
||||
record.target.classList.contains(OPENING_STORIES)
|
||||
);
|
||||
for (const list of [record.addedNodes, record.removedNodes])
|
||||
for (const node of list)
|
||||
if (
|
||||
['hPop', 'first-run-launcher'].includes(node.id) ||
|
||||
node.querySelector?.('#hPop, #first-run-launcher')
|
||||
)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
export class PanelLayoutController {
|
||||
constructor({
|
||||
readHud,
|
||||
@@ -92,6 +118,9 @@ export class PanelLayoutController {
|
||||
this._rightStackPreferredPanelId = null;
|
||||
this._rightStackReconsiderAutoCollapse = false;
|
||||
this._rightStackResizeObserver = null;
|
||||
this._storiesCardObserver = null;
|
||||
this._storiesCardShownHandler = null;
|
||||
this._storiesHost = null;
|
||||
this._cockpitLayoutFrame = null;
|
||||
this._cockpitLayoutTimer = null;
|
||||
this._leftPanelStack = document.getElementById('left-panel-stack');
|
||||
@@ -223,6 +252,7 @@ export class PanelLayoutController {
|
||||
this._recentImageryPanel,
|
||||
this._streetLevelPanel,
|
||||
globalContextPanel,
|
||||
document.getElementById('space-missions-panel'),
|
||||
document.getElementById('radio-panel'),
|
||||
]) {
|
||||
if (panel) this._rightStackResizeObserver.observe(panel);
|
||||
@@ -246,6 +276,41 @@ export class PanelLayoutController {
|
||||
attributes: true,
|
||||
attributeFilter: ['class', 'hidden', 'data-variant'],
|
||||
});
|
||||
// The Stories card comes and goes inside the Stories view; only its
|
||||
// arrival or departure moves the rail, not the view's other changes.
|
||||
// It fades in from transparent, which the layout skips, so the end of
|
||||
// that fade (also replayed when the card is shown again after being
|
||||
// hidden) lays the rail out once more.
|
||||
const storiesHost = document.getElementById('gev-stories-host');
|
||||
if (storiesHost) {
|
||||
this._storiesHost = storiesHost;
|
||||
this._storiesCardObserver = new MutationObserver((records) => {
|
||||
if (records.some(movesStoriesCard)) this._scheduleRightPanelLayout();
|
||||
});
|
||||
this._storiesCardObserver.observe(storiesHost, {
|
||||
subtree: true,
|
||||
childList: true,
|
||||
});
|
||||
const welcomeHost = document.querySelector('[data-gev-view="welcome"]');
|
||||
if (welcomeHost)
|
||||
this._storiesCardObserver.observe(welcomeHost, {
|
||||
subtree: true,
|
||||
childList: true,
|
||||
});
|
||||
if (document.body)
|
||||
this._storiesCardObserver.observe(document.body, {
|
||||
attributes: true,
|
||||
attributeFilter: ['class'],
|
||||
attributeOldValue: true,
|
||||
});
|
||||
this._storiesCardShownHandler = (event) => {
|
||||
if (event.target?.id === 'hPop') this._scheduleRightPanelLayout();
|
||||
};
|
||||
storiesHost.addEventListener(
|
||||
'animationend',
|
||||
this._storiesCardShownHandler,
|
||||
);
|
||||
}
|
||||
const hud = document.getElementById('intel-hud');
|
||||
if (hud) {
|
||||
this._rightStackMutationObserver.observe(hud, {
|
||||
@@ -464,10 +529,16 @@ export class PanelLayoutController {
|
||||
'_leftStackMutationObserver',
|
||||
'_rightStackResizeObserver',
|
||||
'_rightStackMutationObserver',
|
||||
'_storiesCardObserver',
|
||||
]) {
|
||||
this[field]?.disconnect();
|
||||
this[field] = null;
|
||||
}
|
||||
this._storiesHost?.removeEventListener(
|
||||
'animationend',
|
||||
this._storiesCardShownHandler,
|
||||
);
|
||||
this._storiesHost = this._storiesCardShownHandler = null;
|
||||
for (const field of [
|
||||
'_leftStackHudTransitionHandler',
|
||||
'_rightStackHudTransitionHandler',
|
||||
|
||||
@@ -26,6 +26,10 @@ export const PANEL_RAIL_ITEMS = Object.freeze({
|
||||
},
|
||||
'street-level-panel': { icon: 'streetview', label: msg('STREET LEVEL') },
|
||||
'global-context-panel': { icon: 'radar', label: msg('CONTEXT') },
|
||||
'space-missions-panel': {
|
||||
icon: 'rocket_launch',
|
||||
label: msg('Space Missions'),
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
/**
|
||||
* Resolve a vertically centered panel slot inside a HUD rail while respecting
|
||||
* live rectangles that intersect that rail above or below the viewport center.
|
||||
* live rectangles that intersect that rail. A rectangle above the viewport
|
||||
* center lowers the top and one below it raises the bottom. Rectangles across
|
||||
* the center put the band beside them (bandBesideMidpointObstacles); with no
|
||||
* room on either side they are left out, as before.
|
||||
*/
|
||||
export function resolveHudRailLayout({
|
||||
viewportHeight,
|
||||
@@ -29,6 +32,7 @@ export function resolveHudRailLayout({
|
||||
const midpoint = viewportHeight * 0.5;
|
||||
let safeTop = Math.max(0, baseTop);
|
||||
let safeBottom = Math.min(viewportHeight, baseBottom);
|
||||
const inLane = [];
|
||||
|
||||
for (const rect of obstacles) {
|
||||
if (
|
||||
@@ -41,10 +45,21 @@ export function resolveHudRailLayout({
|
||||
rect.bottom <= rect.top
|
||||
)
|
||||
continue;
|
||||
inLane.push(rect);
|
||||
if (rect.bottom <= midpoint) safeTop = Math.max(safeTop, rect.bottom + gap);
|
||||
else if (rect.top >= midpoint)
|
||||
safeBottom = Math.min(safeBottom, rect.top - gap);
|
||||
}
|
||||
const beside = bandBesideMidpointObstacles({
|
||||
midpoint,
|
||||
top: Math.max(0, baseTop),
|
||||
bottom: Math.min(viewportHeight, baseBottom),
|
||||
obstacles: inLane,
|
||||
gap,
|
||||
// A side thinner than this holds no usable panel.
|
||||
minimum: viewportHeight * 0.08,
|
||||
});
|
||||
if (beside) ({ top: safeTop, bottom: safeBottom } = beside);
|
||||
|
||||
safeBottom = Math.max(safeTop, safeBottom);
|
||||
const availableHeight = Math.max(0, safeBottom - safeTop);
|
||||
@@ -61,6 +76,74 @@ export function resolveHudRailLayout({
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a rail's band goes when obstacles cross the viewport midpoint, as in
|
||||
* short windows. Those obstacles, and any other that leaves no band between
|
||||
* itself and them, form one block; the band takes whichever side of the block
|
||||
* has more room between it and the next obstacle or the band's own edge,
|
||||
* above on a tie.
|
||||
* @param {object} input
|
||||
* @param {number} input.midpoint The viewport's vertical midpoint.
|
||||
* @param {number} input.top The band's highest top.
|
||||
* @param {number} input.bottom The band's lowest bottom.
|
||||
* @param {Array<{top: number, bottom: number}>} input.obstacles Rectangles that reach the rail.
|
||||
* @param {number} input.gap Space kept between the band and an obstacle.
|
||||
* @param {number} [input.minimum=0] The least room a side needs to count;
|
||||
* a thinner side is no room at all.
|
||||
* @returns {{side: 'above' | 'below', top: number, bottom: number} | null}
|
||||
* Null when nothing crosses the midpoint or neither side has room.
|
||||
*/
|
||||
export function bandBesideMidpointObstacles({
|
||||
midpoint,
|
||||
top,
|
||||
bottom,
|
||||
obstacles,
|
||||
gap,
|
||||
minimum = 0,
|
||||
}) {
|
||||
const crossing = obstacles.filter(
|
||||
(rect) => rect.top < midpoint && rect.bottom > midpoint,
|
||||
);
|
||||
if (!crossing.length) return null;
|
||||
let blockTop = Math.min(...crossing.map((rect) => rect.top));
|
||||
let blockBottom = Math.max(...crossing.map((rect) => rect.bottom));
|
||||
for (let grown = true; grown;) {
|
||||
grown = false;
|
||||
for (const rect of obstacles) {
|
||||
const touches =
|
||||
rect.top <= blockBottom + 2 * gap && rect.bottom >= blockTop - 2 * gap;
|
||||
if (touches && (rect.top < blockTop || rect.bottom > blockBottom)) {
|
||||
blockTop = Math.min(blockTop, rect.top);
|
||||
blockBottom = Math.max(blockBottom, rect.bottom);
|
||||
grown = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
let aboveTop = top;
|
||||
let belowBottom = bottom;
|
||||
for (const rect of obstacles) {
|
||||
if (rect.bottom <= blockTop)
|
||||
aboveTop = Math.max(aboveTop, rect.bottom + gap);
|
||||
else if (rect.top >= blockBottom)
|
||||
belowBottom = Math.min(belowBottom, rect.top - gap);
|
||||
}
|
||||
const above = {
|
||||
side: 'above',
|
||||
top: aboveTop,
|
||||
bottom: Math.min(bottom, blockTop - gap),
|
||||
};
|
||||
const below = {
|
||||
side: 'below',
|
||||
top: Math.max(top, blockBottom + gap),
|
||||
bottom: belowBottom,
|
||||
};
|
||||
const roomAbove = above.bottom - above.top;
|
||||
const roomBelow = below.bottom - below.top;
|
||||
const fits = (room) => room > 0 && room >= minimum;
|
||||
if (roomBelow > roomAbove && fits(roomBelow)) return below;
|
||||
return fits(roomAbove) ? above : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the Tactical layout hid collapsed right panels beside an expanded
|
||||
* one. The rail now enforces one open panel per side in every layout; this
|
||||
|
||||
+157
-22
@@ -1,5 +1,4 @@
|
||||
import { readStylesheet } from '../testSupport/readStylesheet.mjs';
|
||||
import { displayPanelScroller } from './displayPanelScroll.js';
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
@@ -9,21 +8,9 @@ import {
|
||||
} from './panelRails.js';
|
||||
import { applyPanelState, readPanelState } from './rail/panelState.js';
|
||||
|
||||
test('Display uses an inner scroll body only in Cyber', () => {
|
||||
const body = { scrollTop: 95 };
|
||||
const panel = {
|
||||
ownerDocument: { documentElement: { dataset: { uiTheme: 'cyber' } } },
|
||||
querySelector: () => body,
|
||||
};
|
||||
assert.equal(displayPanelScroller(panel), body);
|
||||
panel.ownerDocument.documentElement.dataset.uiTheme = 'tactical';
|
||||
assert.equal(displayPanelScroller(panel), panel);
|
||||
assert.equal(displayPanelScroller(null), null);
|
||||
});
|
||||
|
||||
for (const side of ['left', 'right']) {
|
||||
test(`${side} desktop rail keeps one expanded owner in every HUD layout`, () => {
|
||||
for (const variant of ['tactical', 'minimal', 'cyber']) {
|
||||
for (const variant of ['tactical', 'minimal']) {
|
||||
const f = fixture(side, { hud: { visible: true, variant } });
|
||||
f.expand(f.first, 250);
|
||||
f.expand(f.second, 250);
|
||||
@@ -232,6 +219,121 @@ test('left corridor respects a lower obstacle but ignores an obstacle hidden by
|
||||
assert.equal(Number(f.stack.dataset.safeBottomPct), 65.47);
|
||||
});
|
||||
|
||||
test('in a short window the left corridor stays clear of an obstacle across the midpoint', () => {
|
||||
// 480px window, midpoint 240.
|
||||
const f = fixture('left');
|
||||
f.options.windowRef.innerHeight = 480;
|
||||
f.options.obstacles = [element('card', { top: 100, height: 200 })];
|
||||
f.run();
|
||||
// More room below the card than above it: the corridor starts under it.
|
||||
assert(Number(f.stack.dataset.safeTopPct) * 4.8 >= 300);
|
||||
|
||||
// A card starting below the corridor's usual top (26%, 124.8px) that
|
||||
// crosses the midpoint counts the same way: more room below it.
|
||||
f.options.obstacles = [element('card', { top: 130, height: 120 })];
|
||||
f.run();
|
||||
assert(Number(f.stack.dataset.safeTopPct) * 4.8 >= 250);
|
||||
|
||||
// More room above it: the corridor ends over it.
|
||||
f.options.obstacles = [element('card', { top: 200, height: 250 })];
|
||||
f.run();
|
||||
assert(Number(f.stack.dataset.safeBottomPct) * 4.8 <= 200);
|
||||
});
|
||||
|
||||
test('several cards across the midpoint give the left corridor the same room in any order', () => {
|
||||
const f = fixture('left');
|
||||
f.options.windowRef.innerHeight = 480;
|
||||
const a = element('card', { top: 100, height: 160 });
|
||||
const b = element('card', { top: 110, height: 360 });
|
||||
f.options.obstacles = [a, b];
|
||||
f.run();
|
||||
const first = [f.stack.dataset.safeTopPct, f.stack.dataset.safeBottomPct];
|
||||
f.options.obstacles = [b, a];
|
||||
f.run();
|
||||
assert.deepEqual(
|
||||
[f.stack.dataset.safeTopPct, f.stack.dataset.safeBottomPct],
|
||||
first,
|
||||
);
|
||||
// Together they cover 100 to 470: the corridor ends above them.
|
||||
assert(Number(first[1]) * 4.8 <= 100);
|
||||
});
|
||||
|
||||
test('the left corridor counts cards beside those across the midpoint', () => {
|
||||
const f = fixture('left');
|
||||
f.options.windowRef.innerHeight = 480;
|
||||
// A card inside the span below the midpoint: more room below both.
|
||||
f.options.obstacles = [
|
||||
element('card', { top: 100, height: 200 }),
|
||||
element('card', { top: 250, height: 30 }),
|
||||
];
|
||||
f.run();
|
||||
assert(Number(f.stack.dataset.safeTopPct) * 4.8 >= 300);
|
||||
// About 25px above the cards is under the least usable room (8% of the
|
||||
// window): they are read as before, the upper card pushing the corridor
|
||||
// down past it rather than into a sliver at the top.
|
||||
f.options.obstacles = [
|
||||
element('card', { top: 50, height: 150 }),
|
||||
element('card', { top: 150, height: 320 }),
|
||||
];
|
||||
f.run();
|
||||
assert(Number(f.stack.dataset.safeTopPct) * 4.8 >= 200);
|
||||
// The room above a card is all the panels' to use, above the corridor's
|
||||
// usual top (26%) too: 700px window, card 300 to 420, about 263px above
|
||||
// against 244 below.
|
||||
f.options.windowRef.innerHeight = 700;
|
||||
f.options.obstacles = [element('card', { top: 300, height: 120 })];
|
||||
f.run();
|
||||
assert(Number(f.stack.dataset.safeBottomPct) * 7 <= 300);
|
||||
assert(Number(f.stack.dataset.safeTopPct) * 7 <= 30);
|
||||
// No room on either side: the card is read as before.
|
||||
f.options.windowRef.innerHeight = 480;
|
||||
f.options.obstacles = [element('card', { top: 0, height: 480 })];
|
||||
f.run();
|
||||
assert.equal(Number(f.stack.dataset.safeTopPct), 26);
|
||||
});
|
||||
|
||||
test('a centered timeline only shortens the corridor when it reaches a laid-out panel', () => {
|
||||
const f = fixture('left');
|
||||
f.stack.rect.width = 360;
|
||||
f.stack.rect.right = f.stack.rect.left + 360;
|
||||
f.expand(f.first, 850);
|
||||
const timeline = element('world-timeline', { top: 650, left: 320 });
|
||||
f.options.obstacles = [timeline];
|
||||
f.run();
|
||||
const clear = Number(f.stack.dataset.safeBottomPct);
|
||||
timeline.rect.left = 280;
|
||||
f.run();
|
||||
assert(clear > 85);
|
||||
assert(Number(f.stack.dataset.safeBottomPct) < 73);
|
||||
// Any other obstacle in the same gutter still bounds the corridor.
|
||||
const blocker = element('blocker', { top: 650, left: 320 });
|
||||
f.options.obstacles = [blocker];
|
||||
f.run();
|
||||
assert(Number(f.stack.dataset.safeBottomPct) < 73);
|
||||
});
|
||||
|
||||
test('Data Layers extends to the HUD even if its list is currently short', () => {
|
||||
const f = fixture('left');
|
||||
f.first.id = 'data-panel';
|
||||
const dock = { id: 'command-dock' };
|
||||
f.options.documentRef.getElementById = (id) =>
|
||||
id === 'gev-omnibar'
|
||||
? {}
|
||||
: id === 'gev-voice-control'
|
||||
? { parentElement: dock }
|
||||
: null;
|
||||
f.expand(f.first, 250);
|
||||
f.options.obstacles = [element('hud', { top: 760, height: 45 })];
|
||||
f.run();
|
||||
assert.equal(f.stack.dataset.layoutMode, 'focus');
|
||||
assert(Number(f.stack.dataset.safeBottomPct) > 80);
|
||||
assert(
|
||||
parseFloat(
|
||||
f.first.style.getPropertyValue('--left-panel-allocated-height'),
|
||||
) > 500,
|
||||
);
|
||||
});
|
||||
|
||||
for (const side of ['left', 'right']) {
|
||||
test(`${side} mobile layout releases desktop height/position styles and labels`, () => {
|
||||
const f = fixture(side, { mobile: true });
|
||||
@@ -376,12 +478,6 @@ test('left rail buttons hold still whether the open panel is short or tall', ()
|
||||
assert.equal(f.stack.dataset.layoutMode, 'focus');
|
||||
assert.notEqual(short.stack.dataset.layoutMode, 'focus');
|
||||
assert.ok(Math.abs(railTop(f.stack) - railTop(short.stack)) < 0.2);
|
||||
|
||||
// A theme that pins the stack's top (Cyber) leaves nothing to offset.
|
||||
f.stack.computed.getPropertyValue = (name) =>
|
||||
name === '--panel-stack-top-pinned' ? ' 1' : '';
|
||||
f.run();
|
||||
assert.equal(f.stack.style.getPropertyValue('--panel-rail-offset'), '0.0px');
|
||||
});
|
||||
|
||||
// The left rail's `top` animates after the right pass runs, and nothing
|
||||
@@ -422,9 +518,9 @@ test('right rail falls back to the committed left target when the transition end
|
||||
});
|
||||
|
||||
test('right rail follows a settled left rail whose CSS overrides the committed target', () => {
|
||||
// Cyber pins the left rail with `top: ... !important`, so the committed
|
||||
// A stylesheet that pins the left rail's `top` means the committed
|
||||
// percentage is not where it renders and no `top` transition runs.
|
||||
const f = fixture('right', { hud: { visible: true, variant: 'cyber' } });
|
||||
const f = fixture('right', { hud: { visible: true, variant: 'minimal' } });
|
||||
f.options.leftStack.rect.top = 220;
|
||||
f.options.leftStack.dataset.safeTopPct = '26.00';
|
||||
f.options.leftStack.getAnimations = () => [];
|
||||
@@ -855,3 +951,42 @@ test('left rail keeps collapsed panels shown beside Cockpit, still one open', ()
|
||||
assert.equal(f.stack.classList.contains('layout-exclusive'), false);
|
||||
assert.equal(f.first.getAttribute('aria-hidden'), undefined);
|
||||
});
|
||||
|
||||
test('the right rail is laid out again when the Stories card can appear or go', async () => {
|
||||
const { movesStoriesCard } = await import('./panelLayoutController.js');
|
||||
const node = (id, inner = null) => ({
|
||||
id,
|
||||
querySelector: (selector) =>
|
||||
inner && selector.split(', ').includes(`#${inner}`) ? {} : null,
|
||||
});
|
||||
const childList = (added = [], removed = []) => ({
|
||||
type: 'childList',
|
||||
addedNodes: added,
|
||||
removedNodes: removed,
|
||||
});
|
||||
const bodyClass = (oldValue, now) => ({
|
||||
type: 'attributes',
|
||||
oldValue,
|
||||
target: { classList: { contains: (name) => now.includes(name) } },
|
||||
});
|
||||
// The card itself, or a wrapper holding it, comes or goes.
|
||||
assert.equal(movesStoriesCard(childList([node('hPop')])), true);
|
||||
assert.equal(movesStoriesCard(childList([], [node('', 'hPop')])), true);
|
||||
// The welcome, which hides the card, is removed.
|
||||
assert.equal(
|
||||
movesStoriesCard(childList([], [node('first-run-launcher')])),
|
||||
true,
|
||||
);
|
||||
// Story playback's own changes do not lay the rail out.
|
||||
assert.equal(movesStoriesCard(childList([node('story-frame')])), false);
|
||||
// Only the welcome's loading class coming or going counts.
|
||||
assert.equal(
|
||||
movesStoriesCard(bodyClass('first-run-opening-stories', ['stories-mode'])),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
movesStoriesCard(bodyClass('', ['first-run-opening-stories'])),
|
||||
true,
|
||||
);
|
||||
assert.equal(movesStoriesCard(bodyClass('a', ['b'])), false);
|
||||
});
|
||||
@@ -329,18 +329,14 @@ test('while the OAuth check runs, the toggle is busy and repeat presses are igno
|
||||
localStorage.removeItem(CLOUD_VOICE_AUTH_STORAGE_KEY);
|
||||
});
|
||||
|
||||
test('Cyber moves the chip into the top toolbar and other themes return it to the corner', async (t) => {
|
||||
test('the chip stays first in the corner row whatever the HUD layout', async (t) => {
|
||||
const { $, toolbar } = await fixture(t);
|
||||
const corner = $('#corner-actions');
|
||||
assert.equal(corner.firstElementChild?.id, 'key-setup-chip');
|
||||
// The removed Cyber skin no longer moves it into the top toolbar.
|
||||
document.documentElement.dataset.uiTheme = 'cyber';
|
||||
await wait();
|
||||
await nextTick();
|
||||
assert.equal(toolbar.lastElementChild?.id, 'key-setup-chip');
|
||||
assert.equal(corner.querySelector('#key-setup-chip') === null, true);
|
||||
document.documentElement.dataset.uiTheme = 'tactical';
|
||||
await wait();
|
||||
await nextTick();
|
||||
assert.equal(corner.firstElementChild?.id, 'key-setup-chip');
|
||||
assert.equal(toolbar.querySelector('#key-setup-chip') === null, true);
|
||||
delete document.documentElement.dataset.uiTheme;
|
||||
|
||||
+133
-163
@@ -1,3 +1,4 @@
|
||||
import { h, render as renderVue } from 'vue';
|
||||
import { fromDegrees } from '../geo/ellipsoid.js';
|
||||
import { horizonFrom } from '../geo/horizon.js';
|
||||
import { distance } from '../geo/vector.js';
|
||||
@@ -8,6 +9,7 @@ import {
|
||||
findQuery,
|
||||
} from '../render/rendererOf.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
import QuebecCctvOverlay from './views/panels/QuebecCctvOverlay.vue';
|
||||
|
||||
function isQuebecCamera(camera) {
|
||||
return String(camera?.sourceKind || '').startsWith('quebec-');
|
||||
@@ -77,72 +79,77 @@ function mediaRefreshUrl(value) {
|
||||
* Attach the active Québec source to a floating browser player and map
|
||||
* preview. The browser contacts Québec 511 only after the viewer presses Play
|
||||
* for that camera; selecting it (by click, auto-hop, a scene or voice) only
|
||||
* shows its details and the play control.
|
||||
* shows its details and the play control. The panel and marker are the
|
||||
* `QuebecCctvOverlay` view, rendered synchronously on each change.
|
||||
*/
|
||||
export function createQuebecCctvOverlay(viewer) {
|
||||
if (!viewer || typeof document === 'undefined') return null;
|
||||
|
||||
const controller = new AbortController();
|
||||
const { signal } = controller;
|
||||
const panel = document.createElement('section');
|
||||
panel.className = 'qci-panel';
|
||||
panel.hidden = true;
|
||||
panel.setAttribute('role', 'region');
|
||||
panel.setAttribute('aria-label', t('CCTV camera'));
|
||||
|
||||
const header = document.createElement('header');
|
||||
header.className = 'qci-header';
|
||||
const title = document.createElement('strong');
|
||||
const close = document.createElement('button');
|
||||
close.type = 'button';
|
||||
close.textContent = '×';
|
||||
close.setAttribute('aria-label', t('Close camera preview'));
|
||||
header.append(title, close);
|
||||
|
||||
const coordinates = document.createElement('p');
|
||||
coordinates.className = 'qci-coordinates';
|
||||
const credit = document.createElement('p');
|
||||
credit.className = 'qci-credit';
|
||||
const live = document.createElement('video');
|
||||
live.className = 'qci-live';
|
||||
live.controls = true;
|
||||
live.muted = true;
|
||||
live.autoplay = true;
|
||||
live.loop = true;
|
||||
live.playsInline = true;
|
||||
live.setAttribute('aria-label', t('CCTV camera'));
|
||||
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'qci-actions';
|
||||
const play = document.createElement('button');
|
||||
play.type = 'button';
|
||||
play.className = 'qci-play';
|
||||
play.textContent = t('Play');
|
||||
const refresh = document.createElement('button');
|
||||
refresh.type = 'button';
|
||||
refresh.textContent = t('Refresh map still');
|
||||
actions.append(play, refresh);
|
||||
const note = document.createElement('p');
|
||||
note.className = 'qci-note';
|
||||
const sourceLink = document.createElement('a');
|
||||
sourceLink.target = '_blank';
|
||||
sourceLink.rel = 'noopener noreferrer';
|
||||
sourceLink.textContent = t("Open this image on the provider's site");
|
||||
panel.append(header, coordinates, credit, live, actions, note, sourceLink);
|
||||
|
||||
const marker = document.createElement('div');
|
||||
marker.className = 'qci-marker';
|
||||
marker.hidden = true;
|
||||
const still = document.createElement('video');
|
||||
still.className = 'qci-marker-still';
|
||||
still.muted = true;
|
||||
still.playsInline = true;
|
||||
still.preload = 'none';
|
||||
still.setAttribute('aria-hidden', 'true');
|
||||
const markerLabel = document.createElement('span');
|
||||
markerLabel.className = 'qci-marker-label';
|
||||
marker.append(still, markerLabel);
|
||||
document.body.append(panel, marker);
|
||||
// What the view renders. The owner writes it where it used to write the
|
||||
// elements, then paints; the view never binds the media sources, the
|
||||
// panel's dragged position or the marker's per-frame visibility and place.
|
||||
const view = {
|
||||
panelHidden: true,
|
||||
title: '',
|
||||
coordinates: '',
|
||||
credit: '',
|
||||
creditHidden: false,
|
||||
liveHidden: false,
|
||||
actionsHidden: false,
|
||||
playHidden: false,
|
||||
refreshHidden: false,
|
||||
note: '',
|
||||
noteHidden: false,
|
||||
sourceHref: null,
|
||||
sourceHidden: false,
|
||||
markerLinkOnly: false,
|
||||
stillHidden: false,
|
||||
markerLabel: '',
|
||||
};
|
||||
const host = document.createElement('div');
|
||||
let disposed = false;
|
||||
const handlers = {
|
||||
onClose: closeWindow,
|
||||
onPlay: startPlayback,
|
||||
onRefresh: refreshStill,
|
||||
onKeydown(event) {
|
||||
if (event.key === 'Escape') close.click();
|
||||
},
|
||||
onHeaderPointerdown: startDrag,
|
||||
onLiveError: markLiveUnavailable,
|
||||
onLiveLoadeddata() {
|
||||
liveUnavailable = false;
|
||||
view.note = t(
|
||||
'The map still uses a separate request and may show a different moment.',
|
||||
);
|
||||
view.noteHidden = false;
|
||||
paint();
|
||||
},
|
||||
onStillError: markStillUnavailable,
|
||||
onStillLoadeddata() {
|
||||
stillUnavailable = false;
|
||||
if (selected)
|
||||
view.markerLabel = markerLabelText(selected, Boolean(selectedMediaUrl));
|
||||
paint();
|
||||
still.pause();
|
||||
},
|
||||
};
|
||||
/** Render the view now: the panel and marker go to the end of the body. */
|
||||
function paint() {
|
||||
if (disposed) return null;
|
||||
const vnode = h(QuebecCctvOverlay, { view: { ...view }, ...handlers });
|
||||
renderVue(vnode, host);
|
||||
return vnode.component.exposed;
|
||||
}
|
||||
const elements = paint();
|
||||
const panel = elements.panel.value;
|
||||
const header = elements.header.value;
|
||||
const close = elements.close.value.$el;
|
||||
const live = elements.live.value;
|
||||
const marker = elements.marker.value;
|
||||
const still = elements.still.value;
|
||||
|
||||
let selected = null;
|
||||
let selectedPosition = null;
|
||||
@@ -166,13 +173,15 @@ export function createQuebecCctvOverlay(viewer) {
|
||||
|
||||
function markLiveUnavailable() {
|
||||
liveUnavailable = true;
|
||||
note.textContent = t('Source unavailable');
|
||||
note.hidden = false;
|
||||
view.note = t('Source unavailable');
|
||||
view.noteHidden = false;
|
||||
paint();
|
||||
}
|
||||
|
||||
function markStillUnavailable() {
|
||||
stillUnavailable = true;
|
||||
markerLabel.textContent = t('Source unavailable');
|
||||
view.markerLabel = t('Source unavailable');
|
||||
paint();
|
||||
}
|
||||
|
||||
function startRender() {
|
||||
@@ -218,16 +227,17 @@ export function createQuebecCctvOverlay(viewer) {
|
||||
playingCameraId = selected.id;
|
||||
liveUnavailable = false;
|
||||
stillUnavailable = false;
|
||||
play.hidden = true;
|
||||
refresh.hidden = false;
|
||||
live.hidden = false;
|
||||
still.hidden = false;
|
||||
marker.classList.remove('qci-marker-link-only');
|
||||
note.textContent = t(
|
||||
view.playHidden = true;
|
||||
view.refreshHidden = false;
|
||||
view.liveHidden = false;
|
||||
view.stillHidden = false;
|
||||
view.markerLinkOnly = false;
|
||||
view.note = t(
|
||||
'The map still uses a separate request and may show a different moment.',
|
||||
);
|
||||
note.hidden = false;
|
||||
markerLabel.textContent = markerLabelText(selected, true);
|
||||
view.noteHidden = false;
|
||||
view.markerLabel = markerLabelText(selected, true);
|
||||
paint();
|
||||
setMedia(live, selectedMediaUrl);
|
||||
setMedia(still, selectedMediaUrl);
|
||||
void live.play().catch(onPlayFailure(markLiveUnavailable));
|
||||
@@ -246,7 +256,8 @@ export function createQuebecCctvOverlay(viewer) {
|
||||
stillUnavailable = false;
|
||||
stopMediaRefresh();
|
||||
stopRender();
|
||||
panel.hidden = true;
|
||||
view.panelHidden = true;
|
||||
paint();
|
||||
marker.hidden = true;
|
||||
setMedia(live, '');
|
||||
setMedia(still, '');
|
||||
@@ -263,7 +274,8 @@ export function createQuebecCctvOverlay(viewer) {
|
||||
Number(camera.elevationM) || 10,
|
||||
);
|
||||
if (closedWindowCameraId === camera.id && !reselected) {
|
||||
panel.hidden = true;
|
||||
view.panelHidden = true;
|
||||
paint();
|
||||
updateMarker();
|
||||
return;
|
||||
}
|
||||
@@ -276,8 +288,8 @@ export function createQuebecCctvOverlay(viewer) {
|
||||
playingCameraId = null;
|
||||
}
|
||||
const playing = Boolean(mediaUrl) && playingCameraId === camera.id;
|
||||
title.textContent = camera.name || t('CCTV camera');
|
||||
coordinates.textContent = [
|
||||
view.title = camera.name || t('CCTV camera');
|
||||
view.coordinates = [
|
||||
`${Number(camera.lat).toFixed(5)}, ${Number(camera.lon).toFixed(5)}`,
|
||||
Number.isFinite(camera.accuracyM) && camera.accuracyM > 0
|
||||
? `±${Math.round(camera.accuracyM)} m`
|
||||
@@ -286,14 +298,13 @@ export function createQuebecCctvOverlay(viewer) {
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ');
|
||||
credit.textContent = camera.credit || camera.provider || '';
|
||||
credit.hidden = !credit.textContent;
|
||||
live.hidden = !playing;
|
||||
play.hidden = !mediaUrl || playing;
|
||||
refresh.hidden = !playing;
|
||||
actions.hidden = !mediaUrl;
|
||||
note.hidden = !mediaUrl;
|
||||
note.textContent = mediaUrl
|
||||
view.credit = camera.credit || camera.provider || '';
|
||||
view.creditHidden = !view.credit;
|
||||
view.liveHidden = !playing;
|
||||
view.playHidden = !mediaUrl || playing;
|
||||
view.refreshHidden = !playing;
|
||||
view.actionsHidden = !mediaUrl;
|
||||
view.note = mediaUrl
|
||||
? !playing
|
||||
? t('Video plays from Québec 511, which sees your IP address.')
|
||||
: liveUnavailable
|
||||
@@ -304,15 +315,16 @@ export function createQuebecCctvOverlay(viewer) {
|
||||
: sourceUrl
|
||||
? ''
|
||||
: t('Source unavailable');
|
||||
note.hidden = !note.textContent;
|
||||
sourceLink.href = sourceUrl || '#';
|
||||
sourceLink.hidden = !sourceUrl;
|
||||
markerLabel.textContent = stillUnavailable
|
||||
view.noteHidden = !view.note;
|
||||
view.sourceHref = sourceUrl || '#';
|
||||
view.sourceHidden = !sourceUrl;
|
||||
view.markerLabel = stillUnavailable
|
||||
? t('Source unavailable')
|
||||
: markerLabelText(camera, playing);
|
||||
marker.classList.toggle('qci-marker-link-only', !playing);
|
||||
still.hidden = !playing;
|
||||
panel.hidden = false;
|
||||
view.markerLinkOnly = !playing;
|
||||
view.stillHidden = !playing;
|
||||
view.panelHidden = false;
|
||||
paint();
|
||||
|
||||
if (changed || mediaUrl !== selectedMediaUrl) {
|
||||
selectedMediaUrl = mediaUrl;
|
||||
@@ -366,34 +378,6 @@ export function createQuebecCctvOverlay(viewer) {
|
||||
);
|
||||
}
|
||||
|
||||
still.addEventListener(
|
||||
'loadeddata',
|
||||
() => {
|
||||
stillUnavailable = false;
|
||||
if (selected)
|
||||
markerLabel.textContent = markerLabelText(
|
||||
selected,
|
||||
Boolean(selectedMediaUrl),
|
||||
);
|
||||
still.pause();
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
still.addEventListener('error', markStillUnavailable, { signal });
|
||||
live.addEventListener('error', markLiveUnavailable, { signal });
|
||||
live.addEventListener(
|
||||
'loadeddata',
|
||||
() => {
|
||||
liveUnavailable = false;
|
||||
note.textContent = t(
|
||||
'The map still uses a separate request and may show a different moment.',
|
||||
);
|
||||
note.hidden = false;
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
refresh.addEventListener('click', refreshStill, { signal });
|
||||
play.addEventListener('click', startPlayback, { signal });
|
||||
const resetCanvasRect = () => {
|
||||
canvasRect = null;
|
||||
};
|
||||
@@ -403,49 +387,35 @@ export function createQuebecCctvOverlay(viewer) {
|
||||
capture: true,
|
||||
passive: true,
|
||||
});
|
||||
panel.addEventListener(
|
||||
'keydown',
|
||||
(event) => {
|
||||
if (event.key === 'Escape') close.click();
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
close.addEventListener(
|
||||
'click',
|
||||
() => {
|
||||
closedWindowCameraId = selected?.id || null;
|
||||
panel.hidden = true;
|
||||
live.pause();
|
||||
stopMediaRefresh();
|
||||
// The floating player closes independently; keep the paused map still.
|
||||
updateMarker();
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
header.addEventListener(
|
||||
'pointerdown',
|
||||
(event) => {
|
||||
if (event.target.closest('button')) return;
|
||||
const rect = panel.getBoundingClientRect();
|
||||
const offsetX = event.clientX - rect.left;
|
||||
const offsetY = event.clientY - rect.top;
|
||||
header.setPointerCapture(event.pointerId);
|
||||
const move = (moveEvent) => {
|
||||
panel.style.left = `${Math.max(0, Math.min(window.innerWidth - panel.offsetWidth, moveEvent.clientX - offsetX))}px`;
|
||||
panel.style.top = `${Math.max(0, Math.min(window.innerHeight - panel.offsetHeight, moveEvent.clientY - offsetY))}px`;
|
||||
panel.style.right = 'auto';
|
||||
};
|
||||
const stop = () => {
|
||||
header.removeEventListener('pointermove', move);
|
||||
header.removeEventListener('pointerup', stop);
|
||||
header.removeEventListener('pointercancel', stop);
|
||||
};
|
||||
header.addEventListener('pointermove', move, { signal });
|
||||
header.addEventListener('pointerup', stop, { once: true, signal });
|
||||
header.addEventListener('pointercancel', stop, { once: true, signal });
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
function closeWindow() {
|
||||
closedWindowCameraId = selected?.id || null;
|
||||
view.panelHidden = true;
|
||||
paint();
|
||||
live.pause();
|
||||
stopMediaRefresh();
|
||||
// The floating player closes independently; keep the paused map still.
|
||||
updateMarker();
|
||||
}
|
||||
function startDrag(event) {
|
||||
if (event.target.closest('button')) return;
|
||||
const rect = panel.getBoundingClientRect();
|
||||
const offsetX = event.clientX - rect.left;
|
||||
const offsetY = event.clientY - rect.top;
|
||||
header.setPointerCapture(event.pointerId);
|
||||
const move = (moveEvent) => {
|
||||
panel.style.left = `${Math.max(0, Math.min(window.innerWidth - panel.offsetWidth, moveEvent.clientX - offsetX))}px`;
|
||||
panel.style.top = `${Math.max(0, Math.min(window.innerHeight - panel.offsetHeight, moveEvent.clientY - offsetY))}px`;
|
||||
panel.style.right = 'auto';
|
||||
};
|
||||
const stop = () => {
|
||||
header.removeEventListener('pointermove', move);
|
||||
header.removeEventListener('pointerup', stop);
|
||||
header.removeEventListener('pointercancel', stop);
|
||||
};
|
||||
header.addEventListener('pointermove', move, { signal });
|
||||
header.addEventListener('pointerup', stop, { once: true, signal });
|
||||
header.addEventListener('pointercancel', stop, { once: true, signal });
|
||||
}
|
||||
document.addEventListener(
|
||||
'visibilitychange',
|
||||
() => {
|
||||
@@ -469,8 +439,8 @@ export function createQuebecCctvOverlay(viewer) {
|
||||
stopRender();
|
||||
setMedia(live, '');
|
||||
setMedia(still, '');
|
||||
panel.remove();
|
||||
marker.remove();
|
||||
disposed = true;
|
||||
renderVue(null, host);
|
||||
selected = null;
|
||||
selectedPosition = null;
|
||||
},
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import '../testSupport/registerDom.mjs';
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { Window } from 'happy-dom';
|
||||
import { fromDegrees } from '../geo/ellipsoid.js';
|
||||
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
|
||||
import { fakeCameraPort } from '../testSupport/fakeCameraPort.mjs';
|
||||
@@ -22,23 +22,36 @@ const CAMERA = Object.freeze({
|
||||
});
|
||||
|
||||
/**
|
||||
* Mount the overlay in a happy-dom window with recorded media loads, timers
|
||||
* and postRender listeners. `play` decides what each play() returns.
|
||||
* Mount the overlay in the registered happy-dom window (Vue binds the
|
||||
* document it loads with) with recorded media loads, timers and postRender
|
||||
* listeners. `play` decides what each play() returns.
|
||||
*/
|
||||
function mountOverlay(t, { play = () => Promise.resolve() } = {}) {
|
||||
const window = new Window({ url: 'http://localhost:4173/' });
|
||||
const previousWindow = globalThis.window;
|
||||
const previousDocument = globalThis.document;
|
||||
globalThis.window = window;
|
||||
globalThis.document = window.document;
|
||||
const { window } = globalThis;
|
||||
const media = window.HTMLMediaElement.prototype;
|
||||
const previous = {
|
||||
load: media.load,
|
||||
play: media.play,
|
||||
pause: media.pause,
|
||||
setInterval: window.setInterval,
|
||||
clearInterval: window.clearInterval,
|
||||
};
|
||||
t.after(() => {
|
||||
media.load = previous.load;
|
||||
media.play = previous.play;
|
||||
media.pause = previous.pause;
|
||||
window.setInterval = previous.setInterval;
|
||||
window.clearInterval = previous.clearInterval;
|
||||
delete window.document.hidden;
|
||||
});
|
||||
const loads = [];
|
||||
window.HTMLMediaElement.prototype.load = function () {
|
||||
media.load = function () {
|
||||
if (this.getAttribute('src')) loads.push(this.getAttribute('src'));
|
||||
};
|
||||
window.HTMLMediaElement.prototype.play = function () {
|
||||
media.play = function () {
|
||||
return play(this);
|
||||
};
|
||||
window.HTMLMediaElement.prototype.pause = function () {};
|
||||
media.pause = function () {};
|
||||
const intervals = new Map();
|
||||
let nextTimer = 1;
|
||||
window.setInterval = (fn) => {
|
||||
@@ -65,12 +78,7 @@ function mountOverlay(t, { play = () => Promise.resolve() } = {}) {
|
||||
});
|
||||
t.after(unbind);
|
||||
const overlay = createQuebecCctvOverlay(viewer);
|
||||
t.after(() => {
|
||||
overlay?.dispose();
|
||||
globalThis.window = previousWindow;
|
||||
globalThis.document = previousDocument;
|
||||
window.close();
|
||||
});
|
||||
t.after(() => overlay?.dispose());
|
||||
const [live, still] = window.document.querySelectorAll('video');
|
||||
return {
|
||||
window,
|
||||
@@ -203,3 +211,21 @@ test('the refresh timer reloads with a cache-buster, skips hidden tabs, and stop
|
||||
assert.equal(ui.renderListeners.size, 0);
|
||||
assert.equal(ui.window.document.querySelector('.qci-panel') === null, true);
|
||||
});
|
||||
|
||||
test('Escape in the window closes it and stops the refresh until the camera is picked again', (t) => {
|
||||
const ui = mountOverlay(t);
|
||||
ui.overlay.setCamera(CAMERA);
|
||||
ui.playButton().click();
|
||||
const panel = ui.window.document.querySelector('.qci-panel');
|
||||
panel.dispatchEvent(
|
||||
new ui.window.KeyboardEvent('keydown', { key: 'Escape', bubbles: true }),
|
||||
);
|
||||
assert.equal(panel.hidden, true);
|
||||
assert.equal(ui.intervals.size, 0);
|
||||
|
||||
ui.overlay.setCamera({ ...CAMERA });
|
||||
assert.equal(panel.hidden, true, 'a routine update keeps it closed');
|
||||
ui.overlay.setCamera({ ...CAMERA }, { reselected: true });
|
||||
assert.equal(panel.hidden, false, 'picking the camera again reopens it');
|
||||
assert.equal(ui.intervals.size, 1);
|
||||
});
|
||||
@@ -91,10 +91,7 @@ export class RadioControls {
|
||||
*/
|
||||
async _revealRadioControlsAfterExplicitEnable(trigger) {
|
||||
const contextPanel = document.getElementById('global-context-panel');
|
||||
const scroller =
|
||||
(document.documentElement?.dataset.uiTheme === 'cyber' &&
|
||||
contextPanel?.querySelector('.cyber-panel-body')) ||
|
||||
contextPanel?.querySelector('.global-context-panel-inner');
|
||||
const scroller = contextPanel?.querySelector('.global-context-panel-inner');
|
||||
const directory = this._radioPanel?.querySelector('.radio-directory-row');
|
||||
const transport = this._radioPanel?.querySelector('.radio-transport');
|
||||
if (
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { onBeforeUnmount } from 'vue';
|
||||
import { t } from '../../i18n/index.js';
|
||||
import { formatScaleRange } from '../unitLabels.js';
|
||||
import UiCloseButton from '../kit/UiCloseButton.vue';
|
||||
import RailCardSetting from './RailCardSetting.vue';
|
||||
import RailChips from './RailChips.vue';
|
||||
import RailRowList from './RailRowList.vue';
|
||||
@@ -100,16 +101,13 @@ function legendView(legend) {
|
||||
/><template v-else-if="block.type === 'result'"
|
||||
><div class="rail-card-result-header"
|
||||
><span class="panel-title">{{ block.label }}</span
|
||||
><button
|
||||
><UiCloseButton
|
||||
class="data-toggle-chip"
|
||||
type="button"
|
||||
data-action-id="clear"
|
||||
:aria-label="t('Clear reading')"
|
||||
:label="t('Clear reading')"
|
||||
:title="t('Clear reading')"
|
||||
:hidden="!block.clear"
|
||||
@click="dispatch(block.clear, block)"
|
||||
>×</button
|
||||
></div
|
||||
@click="dispatch(block.clear, block)" /></div
|
||||
><div class="rail-card-result-lines"
|
||||
><RailCardBlocks
|
||||
:blocks="[
|
||||
|
||||
@@ -130,8 +130,9 @@ test('a collapsed launcher drops its divider so English titles fit whole', () =>
|
||||
/margin-left:\s*auto/,
|
||||
'the launcher toggle',
|
||||
);
|
||||
const button = rules.find(
|
||||
({ selector }) => selector === '.panel-collapse-btn',
|
||||
// The kit's icon button shares the toggle's rule.
|
||||
const button = rules.find(({ selector }) =>
|
||||
selector.split(', ').includes('.panel-collapse-btn'),
|
||||
);
|
||||
assert.match(
|
||||
button?.body || '',
|
||||
@@ -140,7 +141,7 @@ test('a collapsed launcher drops its divider so English titles fit whole', () =>
|
||||
);
|
||||
});
|
||||
|
||||
test('the default theme geometry change leaves cyber gutters alone', () => {
|
||||
test('the default theme geometry change leaves the base gutters alone', () => {
|
||||
for (const surface of [
|
||||
'.data-panel-inner',
|
||||
'.utilities-panel-inner',
|
||||
@@ -164,6 +165,17 @@ test('the default theme geometry change leaves cyber gutters alone', () => {
|
||||
assert.match(display?.body || '', /font-size:\s*12px/);
|
||||
});
|
||||
|
||||
test('Data Layers, Context and Space Missions share the 14px side gutters', () => {
|
||||
const gutters = rules.find(
|
||||
({ selector, body }) =>
|
||||
/:is\(\s*\.data-panel-inner,\s*\.global-context-panel-inner,\s*\.space-missions-panel-inner\s*\)$/.test(
|
||||
selector,
|
||||
) && /padding-left:\s*14px/.test(body),
|
||||
);
|
||||
assert.ok(gutters, 'one rule sets the shared gutters');
|
||||
assert.match(gutters.body, /padding-right:\s*14px/);
|
||||
});
|
||||
|
||||
test('rail titles and dock labels share one set of label tokens', () => {
|
||||
// command-dock-trays.css sets the dock's label type; earlier dock rules
|
||||
// for the same selector are overridden by it.
|
||||
@@ -193,39 +205,6 @@ test('rail titles and dock labels share one set of label tokens', () => {
|
||||
);
|
||||
});
|
||||
|
||||
test('default theme overrides never reach the cyber theme', () => {
|
||||
const notCyber = ":root:not([data-ui-theme='cyber'])";
|
||||
const padding = rules.find(
|
||||
({ selector, body }) =>
|
||||
selector.endsWith(
|
||||
':is(.data-panel-inner, .global-context-panel-inner)',
|
||||
) && /padding-left:\s*14px/.test(body),
|
||||
);
|
||||
assert.ok(
|
||||
padding?.selector.startsWith(notCyber),
|
||||
'the 14px gutters must skip cyber',
|
||||
);
|
||||
const display = rules.find(
|
||||
({ selector, body }) =>
|
||||
selector.endsWith('#pp-toggles > .pp-header-row .pp-collapse-btn') &&
|
||||
/font-size:\s*13px/.test(body),
|
||||
);
|
||||
assert.ok(
|
||||
display?.selector.startsWith(notCyber),
|
||||
"Display's 22px toggle must skip cyber",
|
||||
);
|
||||
// Cyber draws its title marker at left: -8px; a clip on the title would cut it.
|
||||
for (const { selector, body } of rules) {
|
||||
if (!/\.panel-title/.test(selector) || !/overflow:\s*hidden/.test(body))
|
||||
continue;
|
||||
if (!/#left-panel-stack|#right-context-rail/.test(selector)) continue;
|
||||
assert.ok(
|
||||
selector.startsWith(notCyber),
|
||||
`${selector} clips the cyber title marker`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('launcher compaction and header colour stay on the rail panels themselves', () => {
|
||||
// The divider, gap and toggle rules; the translated type rule is checked
|
||||
// above.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script setup>
|
||||
import { computed } from 'vue';
|
||||
import { t } from '../../i18n/index.js';
|
||||
import UiCloseButton from '../kit/UiCloseButton.vue';
|
||||
import UiSegmented from '../kit/UiSegmented.vue';
|
||||
import RailCardBlocks from '../rail/RailCardBlocks.vue';
|
||||
import RailCards from '../rail/RailCards.vue';
|
||||
@@ -99,8 +100,7 @@ const modeOptions = computed(() =>
|
||||
:label="t('Mode')"
|
||||
:options="modeOptions"
|
||||
:model-value="view.mode"
|
||||
@update:model-value="onSetMode"
|
||||
/><div
|
||||
@update:model-value="onSetMode" /><div
|
||||
v-for="slot in view.slots"
|
||||
:id="`ri-slot-${slot.id}`"
|
||||
:key="slot.id"
|
||||
@@ -108,21 +108,17 @@ const modeOptions = computed(() =>
|
||||
:data-state="slot.state"
|
||||
><span class="ri-slot-tag">{{ slot.tag }}</span
|
||||
><span class="ri-slot-value" :title="slot.text">{{ slot.text }}</span
|
||||
><button
|
||||
><UiCloseButton
|
||||
:id="`ri-unpin-${slot.id}`"
|
||||
:class="[
|
||||
'data-toggle-chip ri-unpin',
|
||||
{ 'is-reserved': !slot.pinned },
|
||||
]"
|
||||
type="button"
|
||||
:data-unpin="slot.id"
|
||||
:disabled="!slot.pinned"
|
||||
:aria-hidden="String(!slot.pinned)"
|
||||
:aria-label="slot.unpinLabel"
|
||||
:title="slot.unpinLabel"
|
||||
>×</button
|
||||
></div
|
||||
></section
|
||||
:label="slot.unpinLabel"
|
||||
:title="slot.unpinLabel" /></div></section
|
||||
><div id="ri-controls" class="ri-block ri-controls"
|
||||
><label class="ri-opacity-label" for="ri-opacity"
|
||||
><span>{{ t('OPACITY') }}</span
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
} from '../panelStackLayout.js';
|
||||
import { resolveHudRailLayout } from './panelRailGeometry.js';
|
||||
|
||||
import { displayPanelScroller } from './displayPanelScroll.js';
|
||||
import { settleSideAccordion } from './panelAccordion.js';
|
||||
|
||||
const pendingCollapseRetries = new WeakSet();
|
||||
@@ -356,7 +355,7 @@ export function layoutRightPanelRail({
|
||||
stack.dataset.expandedCount = String(expandedPanels.length);
|
||||
|
||||
if (displayPanel && expandedPanels.includes(displayPanel)) {
|
||||
const scroller = displayPanelScroller(displayPanel);
|
||||
const scroller = displayPanel;
|
||||
const maxScrollTop = Math.max(
|
||||
0,
|
||||
scroller.scrollHeight - scroller.clientHeight,
|
||||
|
||||
@@ -52,18 +52,6 @@ test('the dock trays open from their own wing in right-to-left', () => {
|
||||
);
|
||||
});
|
||||
|
||||
test('the Cyber cockpit keeps Data Layers on the left edge in every language', () => {
|
||||
const body = ruleBody(
|
||||
sheet('cyber.css'),
|
||||
":root[data-ui-theme='cyber'] body.cockpit-mode #left-panel-stack",
|
||||
);
|
||||
// inset-inline-start would become right: 30px in Arabic and beat
|
||||
// rtl.css's reset, landing the stack on the utility controls.
|
||||
assert.doesNotMatch(body, /inset-inline-start/);
|
||||
assert.match(body, /left: 30px;/);
|
||||
assert.match(body, /right: auto;/);
|
||||
});
|
||||
|
||||
test('the panel rails stay on the outer side of their stacks in right-to-left', () => {
|
||||
const layers = sheet('layers.css');
|
||||
// Each rail is placed by its screen-side edge; a physical side would put
|
||||
@@ -90,11 +78,6 @@ test('the panel rails stay on the outer side of their stacks in right-to-left',
|
||||
ruleBody(kit, '.ui-tooltip__tip--left'),
|
||||
/inset-inline-end: calc\(100% \+ 10px\);/,
|
||||
);
|
||||
// Cyber's right stack keeps its rail clearance on the left edge.
|
||||
assert.match(
|
||||
sheet('rtl.css'),
|
||||
/html\[dir='rtl'\]\[data-ui-theme='cyber'\] #right-context-rail \{\s*right: auto;\s*left: calc\(51px \+ var\(--panel-rail-clearance\)\);/,
|
||||
);
|
||||
});
|
||||
|
||||
test('phone top-bar actions mirror with the logo', () => {
|
||||
|
||||
@@ -178,12 +178,31 @@ test('Cancel and Escape close through the owner; dispose removes the dialog', as
|
||||
$('dialog').dispatchEvent(cancel);
|
||||
assert.equal(cancel.defaultPrevented, true);
|
||||
assert.equal(closes, 2);
|
||||
const root = $('dialog');
|
||||
assert.equal(root.open, true, 'Escape leaves closing to the owner');
|
||||
dialog.dispose();
|
||||
await nextTick();
|
||||
assert.equal($('dialog'), null);
|
||||
assert.equal(root.open, false, 'the removed dialog is closed');
|
||||
assert.equal(store.controls, null);
|
||||
});
|
||||
|
||||
test('a close the browser makes on its own also closes through the owner', async (t) => {
|
||||
// A repeated Escape can close a modal without a cancel the page may stop.
|
||||
const { store } = fixture(t);
|
||||
let closes = 0;
|
||||
const dialog = createSceneDialog(
|
||||
'Share selected scene',
|
||||
() => closes++,
|
||||
store,
|
||||
);
|
||||
await nextTick();
|
||||
$('dialog').close();
|
||||
assert.equal(closes, 1);
|
||||
dialog.dispose();
|
||||
await nextTick();
|
||||
});
|
||||
|
||||
test('a replaced dialog opens fresh and its late dispose leaves the new one', async (t) => {
|
||||
const { store } = fixture(t);
|
||||
opened.length = 0;
|
||||
|
||||
@@ -35,9 +35,6 @@ export function readShellElements(document = globalThis.document) {
|
||||
_globalContextFlightsBtn: document.getElementById(
|
||||
'global-context-flights-btn',
|
||||
),
|
||||
_globalContextMissionsBtn: document.getElementById(
|
||||
'global-context-missions-btn',
|
||||
),
|
||||
_installationsSearchBtn: document.getElementById(
|
||||
'installations-search-btn',
|
||||
),
|
||||
|
||||
@@ -1038,15 +1038,16 @@ export class ShellFacade {
|
||||
|
||||
/**
|
||||
* Reads global context mode state for voice/state-sync consumers.
|
||||
* @returns {{mode: 'flights'|'space-missions'|null, active: boolean, changing: boolean, entering: 'flights'|'space-missions'|null, snapshotCaptured: boolean}}
|
||||
* @returns {{mode: 'flights'|null, active: boolean, changing: boolean, entering: 'flights'|null, snapshotCaptured: boolean}}
|
||||
*/
|
||||
getContextModeState(...args) {
|
||||
return this._contextControls?.getContextModeState(...args);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets global context mode (Contacts / Space Missions / off) for voice.
|
||||
* @param {'contacts'|'space-missions'|'off'|null} mode - Requested context target.
|
||||
* Sets global context mode (Contacts / off) for voice. Space Missions is
|
||||
* an ordinary layer, not a Context mode.
|
||||
* @param {'contacts'|'off'|null} mode - Requested context target.
|
||||
* @param {object} [options]
|
||||
* @param {string|Symbol|null} [options.notificationToken]
|
||||
* @param {AbortSignal|null} [options.signal]
|
||||
@@ -1056,7 +1057,7 @@ export class ShellFacade {
|
||||
* lane. Cockpit choreography calls this facade INTERNALLY for its own
|
||||
* enter/rollback steps; those transitions are not a Context request by the
|
||||
* operator and must stay inert, so they pass `false`.
|
||||
* @returns {Promise<{ok:boolean, mode:'flights'|'space-missions'|null, active:boolean, action:string, error?:string}>}
|
||||
* @returns {Promise<{ok:boolean, mode:'flights'|null, active:boolean, action:string, error?:string}>}
|
||||
*/
|
||||
setContextMode(...args) {
|
||||
return this._contextControls?.setContextMode(...args);
|
||||
|
||||
@@ -4,7 +4,7 @@ import { PanelChrome } from './panelChrome.js';
|
||||
import { presentPanelLocally } from '../testSupport/panelState.mjs';
|
||||
import { readPanelState } from './rail/panelState.js';
|
||||
|
||||
function fixture(theme = 'cyber') {
|
||||
function fixture(theme = 'tactical') {
|
||||
const nodes = new Map();
|
||||
const node = (id, collapsed = true) => {
|
||||
const classes = new Set(collapsed ? ['collapsed'] : []);
|
||||
@@ -27,7 +27,8 @@ function fixture(theme = 'cyber') {
|
||||
for (const panel of left.children) panel.parentElement = left;
|
||||
const rail = node('rail');
|
||||
const display = node('pp-toggles'), context = node('global-context-panel'), cctv = node('cctv-panel'), radio = node('radio-panel');
|
||||
rail.children = [display, context, cctv];
|
||||
const missions = node('space-missions-panel');
|
||||
rail.children = [display, context, missions, cctv];
|
||||
for (const panel of rail.children) panel.parentElement = rail;
|
||||
context.children = [radio];
|
||||
radio.parentElement = context;
|
||||
@@ -43,13 +44,13 @@ function fixture(theme = 'cyber') {
|
||||
shareLinkManager: { claimRestoreLane: (...args) => claimed.push(args), onPanelStateChange() {} },
|
||||
};
|
||||
owner.setPanelCollapsed = PanelChrome.prototype.setPanelCollapsed.bind(owner);
|
||||
return { layers, scenes, display, context, cctv, radio, owner, saved, claimed,
|
||||
return { layers, scenes, display, context, missions, cctv, radio, owner, saved, claimed,
|
||||
doc: { documentElement: { dataset: { uiTheme: theme } }, getElementById: (id) => nodes.get(id) },
|
||||
};
|
||||
}
|
||||
|
||||
test('explicit opening collapses side peers and claims their restoration lanes in every theme', () => {
|
||||
for (const theme of ['tactical', 'minimal', 'cyber']) {
|
||||
for (const theme of ['tactical', 'minimal']) {
|
||||
const f = fixture(theme), prior = globalThis.document;
|
||||
globalThis.document = f.doc;
|
||||
try {
|
||||
@@ -71,6 +72,25 @@ test('explicit opening collapses side peers and claims their restoration lanes i
|
||||
}
|
||||
});
|
||||
|
||||
test('the Context and Space Missions panels close each other on desktop', () => {
|
||||
const f = fixture('tactical'), prior = globalThis.document;
|
||||
globalThis.document = f.doc;
|
||||
try {
|
||||
f.owner.setPanelCollapsed('global-context-panel', false, { explicit: true });
|
||||
f.owner.setPanelCollapsed('space-missions-panel', false, { explicit: true });
|
||||
assert.equal(f.missions.classList.contains('collapsed'), false);
|
||||
assert.equal(f.context.classList.contains('collapsed'), true, 'opening Space Missions closes Context');
|
||||
f.owner.setPanelCollapsed('global-context-panel', false, { explicit: true });
|
||||
assert.equal(f.context.classList.contains('collapsed'), false);
|
||||
assert.equal(f.missions.classList.contains('collapsed'), true, 'opening Context closes Space Missions');
|
||||
// Radio lives inside Context, so opening it closes Space Missions too.
|
||||
f.owner.setPanelCollapsed('space-missions-panel', false, { explicit: true });
|
||||
f.owner.setPanelCollapsed('radio-panel', false, { explicit: true });
|
||||
assert.equal(f.context.classList.contains('collapsed'), false);
|
||||
assert.equal(f.missions.classList.contains('collapsed'), true);
|
||||
} finally { globalThis.document = prior; }
|
||||
});
|
||||
|
||||
test('opening already-expanded Radio reveals Context and closes Display', () => {
|
||||
const f = fixture('tactical'), prior = globalThis.document;
|
||||
globalThis.document = f.doc;
|
||||
@@ -86,7 +106,7 @@ test('opening already-expanded Radio reveals Context and closes Display', () =>
|
||||
});
|
||||
|
||||
test('restored preferences keep every saved panel open for the layout to normalize', () => {
|
||||
for (const theme of ['tactical', 'minimal', 'cyber']) {
|
||||
for (const theme of ['tactical', 'minimal']) {
|
||||
const f = fixture(theme), prior = globalThis.document;
|
||||
globalThis.document = f.doc;
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
const LAYER_ID = 'rocket-launches';
|
||||
const PANEL_ID = 'space-missions-panel';
|
||||
|
||||
/**
|
||||
* The Space Missions panel's wiring. Space Missions is an ordinary layer: the
|
||||
* layer owns its data and Satellites dependency, and this connects it to its
|
||||
* panel. The panel shows while the layer is on, and opens when the person
|
||||
* turns the layer on (by hand or by voice) or picks a mission on the globe. Opening it closes the
|
||||
* other right-side panels, Context among them (see setPanelCollapsed).
|
||||
*/
|
||||
export class SpaceMissionsControls {
|
||||
/**
|
||||
* @param {object} options
|
||||
* @param {?object} options.layer The Space Missions layer.
|
||||
* @param {object} options.store The Space Missions store.
|
||||
* @param {object} options.actions
|
||||
* @param {(panelId: string, collapsed: boolean, options?: object) => void} options.actions.setPanelCollapsed
|
||||
* @param {() => boolean} options.actions.isCockpitActive
|
||||
* @param {() => void} [options.actions.revealPanel] Opens the phone sheet that
|
||||
* holds the panel; does nothing on desktop.
|
||||
*/
|
||||
constructor({ layer, store, actions }) {
|
||||
this._layer = layer || null;
|
||||
this._store = store;
|
||||
this._actions = actions;
|
||||
this._manager = null;
|
||||
this._unsubscribeManager = null;
|
||||
this.destroyed = false;
|
||||
store.connect(this._layer);
|
||||
store.publish(null);
|
||||
store.setEnabled(false);
|
||||
this._unsubscribePanel =
|
||||
this._layer?.subscribePanel?.((view) => store.publish(view)) ?? null;
|
||||
this._unsubscribeGlobePick =
|
||||
this._layer?.subscribeGlobePick?.(() => this._reveal()) ?? null;
|
||||
}
|
||||
|
||||
/** Follow a data manager's Space Missions visibility; null disconnects. */
|
||||
connect(manager) {
|
||||
this._unsubscribeManager?.();
|
||||
this._unsubscribeManager = null;
|
||||
this._manager = manager || null;
|
||||
if (this.destroyed) return;
|
||||
this._syncEnabled();
|
||||
this._unsubscribeManager =
|
||||
this._manager?.subscribe?.((change) => this._handleChange(change)) ??
|
||||
null;
|
||||
}
|
||||
|
||||
_syncEnabled() {
|
||||
this._store.setEnabled(Boolean(this._manager?.isEnabled?.(LAYER_ID)));
|
||||
}
|
||||
|
||||
_handleChange(change) {
|
||||
if (this.destroyed || change?.layerId !== LAYER_ID) return;
|
||||
if (!String(change.type || '').startsWith('visibility')) return;
|
||||
this._syncEnabled();
|
||||
if (
|
||||
change.type === 'visibility' &&
|
||||
change.enabled &&
|
||||
(change.origin === 'user' || change.origin === 'voice')
|
||||
)
|
||||
this._reveal();
|
||||
}
|
||||
|
||||
/** Open the panel, unless the Cockpit owns the screen. */
|
||||
_reveal() {
|
||||
if (this.destroyed || this._actions.isCockpitActive?.()) return;
|
||||
this._actions.setPanelCollapsed(PANEL_ID, false, { explicit: true });
|
||||
// A phone shows the rail only as tab sheets: open the Missions sheet too.
|
||||
this._actions.revealPanel?.();
|
||||
}
|
||||
|
||||
destroy() {
|
||||
if (this.destroyed) return;
|
||||
this.destroyed = true;
|
||||
this._unsubscribeManager?.();
|
||||
this._unsubscribeManager = null;
|
||||
this._unsubscribePanel?.();
|
||||
this._unsubscribePanel = null;
|
||||
this._unsubscribeGlobePick?.();
|
||||
this._unsubscribeGlobePick = null;
|
||||
this._store.connect(null);
|
||||
this._store.publish(null);
|
||||
this._store.setEnabled(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
// The Space Missions panel's wiring, apart from Context.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createPinia, setActivePinia } from 'pinia';
|
||||
import { useSpaceMissionsStore } from './stores/spaceMissions.js';
|
||||
import { SpaceMissionsControls } from './spaceMissionsControls.js';
|
||||
|
||||
function layerDouble() {
|
||||
const panelListeners = new Set();
|
||||
const pickListeners = new Set();
|
||||
return {
|
||||
panelListeners,
|
||||
pickListeners,
|
||||
subscribePanel(listener) {
|
||||
panelListeners.add(listener);
|
||||
return () => panelListeners.delete(listener);
|
||||
},
|
||||
subscribeGlobePick(listener) {
|
||||
pickListeners.add(listener);
|
||||
return () => pickListeners.delete(listener);
|
||||
},
|
||||
publish(view) {
|
||||
for (const listener of panelListeners) listener(view);
|
||||
},
|
||||
pick(id) {
|
||||
for (const listener of pickListeners) listener(id);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function managerDouble() {
|
||||
const listeners = new Set();
|
||||
const enabled = new Set();
|
||||
return {
|
||||
listeners,
|
||||
enabled,
|
||||
isEnabled: (id) => enabled.has(id),
|
||||
subscribe(listener) {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
},
|
||||
emit(change) {
|
||||
if (change.type === 'visibility') {
|
||||
if (change.enabled) enabled.add(change.layerId);
|
||||
else enabled.delete(change.layerId);
|
||||
}
|
||||
for (const listener of listeners) listener(change);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function rig({ cockpit = false } = {}) {
|
||||
setActivePinia(createPinia());
|
||||
const store = useSpaceMissionsStore();
|
||||
const layer = layerDouble();
|
||||
const manager = managerDouble();
|
||||
const reveals = [];
|
||||
const sheets = [];
|
||||
const state = { cockpit };
|
||||
const controls = new SpaceMissionsControls({
|
||||
layer,
|
||||
store,
|
||||
actions: {
|
||||
setPanelCollapsed: (...args) => reveals.push(args),
|
||||
isCockpitActive: () => state.cockpit,
|
||||
revealPanel: () => sheets.push('space-missions-panel'),
|
||||
},
|
||||
});
|
||||
controls.connect(manager);
|
||||
return { controls, store, layer, manager, reveals, sheets, state };
|
||||
}
|
||||
|
||||
const userOn = {
|
||||
type: 'visibility',
|
||||
layerId: 'rocket-launches',
|
||||
enabled: true,
|
||||
origin: 'user',
|
||||
};
|
||||
|
||||
test('the layer publishes its roster and mission to its own store', () => {
|
||||
const r = rig();
|
||||
assert.equal(r.store.layer, r.layer);
|
||||
assert.equal(r.store.roster, null);
|
||||
const view = { roster: { entries: [] }, mission: { id: 'L1' } };
|
||||
r.layer.publish(view);
|
||||
assert.equal(r.store.roster, view.roster);
|
||||
assert.equal(r.store.mission, view.mission);
|
||||
});
|
||||
|
||||
test('the panel shows while the layer is on', () => {
|
||||
const r = rig();
|
||||
assert.equal(r.store.enabled, false);
|
||||
r.manager.emit({ ...userOn, origin: 'programmatic' });
|
||||
assert.equal(r.store.enabled, true);
|
||||
r.manager.emit({ ...userOn, enabled: false });
|
||||
assert.equal(r.store.enabled, false);
|
||||
// Another layer's change says nothing about Space Missions.
|
||||
r.manager.enabled.add('rocket-launches');
|
||||
r.manager.emit({ ...userOn, layerId: 'satellites' });
|
||||
assert.equal(r.store.enabled, false);
|
||||
});
|
||||
|
||||
test('a person switching the layer on opens its panel; a restore does not', () => {
|
||||
const r = rig();
|
||||
r.manager.emit({ ...userOn, origin: 'share-restore' });
|
||||
r.manager.emit({ ...userOn, type: 'visibility-requested' });
|
||||
assert.deepEqual(r.reveals, []);
|
||||
r.manager.emit(userOn);
|
||||
assert.deepEqual(r.reveals, [
|
||||
['space-missions-panel', false, { explicit: true }],
|
||||
]);
|
||||
// On a phone the rail shows only as tab sheets: the Missions sheet opens too.
|
||||
assert.deepEqual(r.sheets, ['space-missions-panel']);
|
||||
});
|
||||
|
||||
test('a mission picked on the globe opens the panel', () => {
|
||||
const r = rig();
|
||||
r.layer.pick('L1');
|
||||
assert.deepEqual(r.reveals, [
|
||||
['space-missions-panel', false, { explicit: true }],
|
||||
]);
|
||||
assert.deepEqual(r.sheets, ['space-missions-panel']);
|
||||
});
|
||||
|
||||
test('the Cockpit keeps the screen: no reveal while it is on', () => {
|
||||
const r = rig({ cockpit: true });
|
||||
r.layer.pick('L1');
|
||||
r.manager.emit(userOn);
|
||||
r.manager.emit({ ...userOn, origin: 'voice' });
|
||||
assert.deepEqual(r.reveals, []);
|
||||
assert.deepEqual(r.sheets, [], 'no phone sheet over the Cockpit either');
|
||||
r.state.cockpit = false;
|
||||
r.layer.pick('L1');
|
||||
assert.equal(r.reveals.length, 1);
|
||||
});
|
||||
|
||||
test('reconnecting and destroy release every subscription and clear the store', () => {
|
||||
const r = rig();
|
||||
r.controls.connect(r.manager);
|
||||
assert.equal(r.manager.listeners.size, 1, 'no duplicate subscription');
|
||||
r.layer.publish({ roster: { entries: [] }, mission: null });
|
||||
r.manager.emit(userOn);
|
||||
r.controls.destroy();
|
||||
assert.equal(r.manager.listeners.size, 0);
|
||||
assert.equal(r.layer.panelListeners.size, 0);
|
||||
assert.equal(r.layer.pickListeners.size, 0);
|
||||
assert.equal(r.store.layer, null);
|
||||
assert.equal(r.store.roster, null);
|
||||
assert.equal(r.store.enabled, false);
|
||||
r.layer.pick('L1');
|
||||
assert.equal(r.reveals.length, 1, 'a destroyed control reveals nothing');
|
||||
});
|
||||
@@ -5,9 +5,9 @@ import { markRaw, shallowRef } from 'vue';
|
||||
* The Context panel's mode switch as its view renders it. ContextControls
|
||||
* presents the selected mode, the transition busy state and the nearby
|
||||
* sites search (`_presentContext()`) and publishes them here; it
|
||||
* keeps its listeners and transactions. The Contacts and Space Missions
|
||||
* layers publish their panels beside it, and the app connects each layer's
|
||||
* commands.
|
||||
* keeps its listeners and transactions. The Contacts layer publishes its
|
||||
* panel beside it, and the app connects the layer's commands. Space Missions
|
||||
* has its own store (stores/spaceMissions.js).
|
||||
*/
|
||||
export const useContextStore = defineStore('gev-context', () => {
|
||||
/** The presented mode switch; null until the controls first render. */
|
||||
@@ -37,29 +37,6 @@ export const useContextStore = defineStore('gev-context', () => {
|
||||
awarenessLayer.value = layer && markRaw(layer);
|
||||
}
|
||||
|
||||
/** The Space Missions roster; null until the layer first presents it. */
|
||||
const missionRoster = shallowRef(null);
|
||||
|
||||
/** The selected space mission; null while none is selected. */
|
||||
const mission = shallowRef(null);
|
||||
|
||||
/**
|
||||
* @param {?{roster: ?object, mission: ?object}} next The layer's view. The
|
||||
* layer keeps an unchanged roster's object, which re-renders nothing.
|
||||
*/
|
||||
function publishMissions(next) {
|
||||
missionRoster.value = next?.roster ? markRaw(next.roster) : null;
|
||||
mission.value = next?.mission ? markRaw(next.mission) : null;
|
||||
}
|
||||
|
||||
/** The Space Missions layer whose panel commands the components call. */
|
||||
const missionsLayer = shallowRef(null);
|
||||
|
||||
/** @param {?object} layer The Space Missions layer, or null to disconnect. */
|
||||
function connectMissions(layer) {
|
||||
missionsLayer.value = layer && markRaw(layer);
|
||||
}
|
||||
|
||||
return {
|
||||
view,
|
||||
publish,
|
||||
@@ -67,10 +44,5 @@ export const useContextStore = defineStore('gev-context', () => {
|
||||
publishAwareness,
|
||||
awarenessLayer,
|
||||
connectAwareness,
|
||||
missionRoster,
|
||||
mission,
|
||||
publishMissions,
|
||||
missionsLayer,
|
||||
connectMissions,
|
||||
};
|
||||
});
|
||||
Loaded 100 of 1214 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user