Merge origin/main into byrdit/cctv-visible-only-fetch

This commit is contained in:
German Khokhlov committed 2026-11-19 18:33:29 +04:00
commit d19ae89630
445 files changed
+27359 -9232

No files matched your search

+46 -25
View File
@@ -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,
@@ -621,6 +637,7 @@ export class StyleManager extends ShellFacade {
_toggleOrbit: (...args) => this._toggleOrbit(...args),
toggleCleanView: (...args) => this.toggleCleanView(...args),
_toggleCctvEnabled: (...args) => this._toggleCctvEnabled(...args),
_togglePanel: (panelId) => this._panelChrome._togglePanel(panelId),
_setBloomEnabled: (...args) => this._setBloomEnabled(...args),
_setBloomIntensity: (...args) => this._setBloomIntensity(...args),
_setSharpenEnabled: (...args) => this._setSharpenEnabled(...args),
@@ -675,6 +692,7 @@ export class StyleManager extends ShellFacade {
this._initStreetLevelPanel();
this._initWildlifeSightingCard();
this._initGlobalContextPanel();
this._initSpaceMissionsPanel();
this._initLocationBar();
this._initMobileShell();
this._initShareButton();
@@ -1011,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,
@@ -1057,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?.();
@@ -1376,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(),
@@ -1505,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);
}
@@ -1641,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(
@@ -1942,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();
+4 -11
View File
@@ -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;
+3 -135
View File
@@ -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 =
+7 -1
View File
@@ -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);
});
}
/**
+18
View File
@@ -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;
+3 -27
View File
@@ -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
+1 -17
View File
@@ -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;
-54
View File
@@ -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 ||
-3
View File
@@ -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();
-1
View File
@@ -48,7 +48,6 @@ test('Context starts with an explicit idle snapshot', (t) => {
changing: false,
entering: null,
canContact: true,
canMission: true,
snapshotCaptured: false,
});
});
+4 -51
View File
@@ -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
View File
@@ -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 -43
View File
@@ -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) => {
+1 -8
View File
@@ -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,
});
+8 -4
View File
@@ -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
View File
@@ -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;
});
+2 -62
View File
@@ -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();
+41
View File
@@ -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');
};
}
+79
View File
@@ -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();
}
});
+53
View File
@@ -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>
+82
View File
@@ -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
View File
@@ -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);
};
}
+56 -1
View File
@@ -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'],
);
});
+2 -3
View File
@@ -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 = [];
+4 -10
View File
@@ -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]);
+20 -9
View File
@@ -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';
-950
View File
@@ -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*\}/,
);
});
+11 -9
View File
@@ -54,7 +54,7 @@ export class DisplayBindings {
documentRef: document,
searchInput: this._locationSearch,
actions: {
setStyle: (style) => this.setStyle(style, { userInitiated: true }),
setStyle: (style) => this.setStyle(style),
dismissSearch: () => this._closeLocationSearch?.({ ifOpen: true }),
toggleHud: () => {
this.shareLinkManager?.claimRestoreLane?.('visual');
@@ -64,8 +64,8 @@ export class DisplayBindings {
},
toggleOrbit: () => this._toggleOrbit(),
toggleCleanView: () => this.toggleCleanView(),
toggleLayers: () =>
document.getElementById('data-panel').classList.toggle('active'),
// Same collapse as the panel's own button, so its rail entry stays.
toggleLayers: () => this._togglePanel('data-panel'),
cycleDetection: () => {
this.shareLinkManager?.claimRestoreLane?.('visual');
this.claimDetection();
@@ -82,7 +82,7 @@ export class DisplayBindings {
this._detachDisplayControls?.();
const store = this.displayStore ?? useDisplayStore(applicationPinia());
const token = store.connect({
setStyle: (style) => this.setStyle(style, { userInitiated: true }),
setStyle: (style) => this.setStyle(style),
toggleBloom: () => {
this.shareLinkManager?.claimRestoreLane?.('visual');
this._setBloomEnabled(!this.bloomEnabled);
@@ -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 });
+29 -3
View File
@@ -72,7 +72,11 @@ function settings(store) {
test('before VisualSettings renders, the panel shows its initial markup', (t) => {
const { $ } = fixture(t);
assert.equal($('bloom-toggle').className, 'pp-toggle-btn');
// Beside the kit's ui-* classes, the toggle carries only its own.
assert.deepEqual(
[...$('bloom-toggle').classList].filter((name) => !name.startsWith('ui-')),
['pp-toggle-btn'],
);
assert.equal($('bloom-slider-row').className, 'pp-slider-row');
assert.equal($('bloom-intensity-slider').value, '0');
assert.equal($('bloom-intensity-value').textContent, '0%');
@@ -238,20 +242,29 @@ test('the HUD and Sonar controls render what VisualSettings shows', async (t) =>
getVariant: () => variant,
});
owner._scheduleAdaptivePanelLayout = () => {};
assert.equal($('cyber-sonar-toggle').textContent, 'ON');
assert.equal($('cyber-sonar-toggle').getAttribute('aria-pressed'), 'true');
// Sonar is opt-in: OFF until the viewer turns it on.
assert.equal($('cyber-sonar-toggle').textContent, 'OFF');
assert.equal($('cyber-sonar-toggle').getAttribute('aria-pressed'), 'false');
assert.equal(
[...$('hud-layout-select').options].map((option) => option.value).join(),
'tactical,minimal',
);
owner._syncHudControls();
await nextTick();
assert.equal($('hud-toggle').classList.contains('active'), true);
assert.equal($('hud-layout-row').classList.contains('visible'), true);
assert.equal($('hud-layout-select').value, 'minimal');
// The toggle shows with the HUD; its sliders wait for Sonar ON.
assert.equal($('cyber-sonar-row').classList.contains('visible'), true);
assert.equal($('cyber-sonar-rings-row').classList.contains('visible'), false);
visible = false;
owner._updateHudButtonState();
await nextTick();
assert.equal($('hud-toggle').classList.contains('active'), false);
assert.equal($('hud-layout-row').classList.contains('visible'), false);
assert.equal($('cyber-sonar-row').classList.contains('visible'), false);
owner._sonarShown = {
enabled: false,
@@ -272,6 +285,19 @@ test('the HUD and Sonar controls render what VisualSettings shows', async (t) =>
assert.equal($('cyber-sonar-range-value').textContent, '90%');
assert.equal($('cyber-sonar-sector').value, '30');
assert.equal($('cyber-sonar-sector-value').textContent, '30°');
visible = true;
owner._updateHudButtonState();
owner._sonarShown = { ...owner._sonarShown, enabled: true };
owner._publishDisplay();
await nextTick();
assert.equal(toggle.textContent, 'ON');
for (const name of ['rings', 'range', 'intensity', 'opacity', 'sector'])
assert.equal(
$(`cyber-sonar-${name}-row`).classList.contains('visible'),
true,
name,
);
});
test('Scope and Celestial render what VisualSettings shows', async (t) => {
+1 -1
View File
@@ -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 }],
-6
View File
@@ -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;
}
+17 -13
View File
@@ -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);
+85
View File
@@ -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');
});
+787
View File
@@ -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);
});
+6 -4
View File
@@ -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' },
});
+47
View File
@@ -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
View File
@@ -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="
+162
View File
@@ -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();
});
+57
View File
@@ -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>
+4 -3
View File
@@ -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 },
+98
View File
@@ -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();
});
+40
View File
@@ -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>
+200
View File
@@ -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;
}
});
+74
View File
@@ -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>
+3 -2
View File
@@ -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 },
+5 -2
View File
@@ -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
>
+136
View File
@@ -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();
});
+81
View File
@@ -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>
+3 -1
View File
@@ -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({
+67
View File
@@ -0,0 +1,67 @@
// Every checkbox in a Vue view is a UiCheckbox: no SFC template hand-writes
// `<input type="checkbox">`.
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']);
/** 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, []);
});
+76
View File
@@ -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`×|&times;|&#215;|&#xd7;`,
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">&times;</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, []);
});
+66
View File
@@ -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, []);
});
+84
View File
@@ -0,0 +1,84 @@
// The entity card's buttons and Material glyphs are the kit's: neither its
// template nor the camera preview and nearby lists it renders hand-writes a
// <button> or a Material Symbols span. The Ask GEV button's chat bubble is
// not a Material symbol the page loads, so it stays drawn as inline SVG; the
// hero views (model, route globe, cockpit view, ground view, graphs) draw
// their own pictures and have no controls.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
/** A view's template block: everything outside script and style. */
function template(file) {
const source = readFileSync(
new URL(`../views/panels/${file}`, import.meta.url),
'utf8',
);
return source.replace(/<(script|style)\b[\s\S]*?<\/\1\s*>/g, '');
}
const card = template('EntityCard.vue');
const camera = template('CctvPreview.vue');
const nearby = template('SpotConditions.vue');
const heroViews = [
'AircraftModelHero.vue',
'RouteGlobe.vue',
'FlightCockpitView.vue',
'SatelliteGroundView.vue',
'PreviewHud.vue',
'AltitudeGraph.vue',
].map(template);
test('the entity card hand-writes no button; each is a UiButton', () => {
for (const markup of [card, camera, nearby, ...heroViews])
assert.deepEqual(markup.match(/<button\b/gi) ?? [], []);
// Photos, Route, 3D, Cockpit view, the cockpit entry, Fly to, Follow and
// Ask GEV.
assert.equal(card.match(/<UiButton\b/g)?.length, 8);
assert.equal(card.match(/<UiCloseButton\b/g)?.length, 1);
// A camera's bigger view and More info; its popup closes with a UiCloseButton.
assert.equal(camera.match(/<UiButton\b/g)?.length, 2);
assert.equal(camera.match(/<UiCloseButton\b/g)?.length, 1);
// The traffic, hazard, alert and other nearby rows.
assert.equal(nearby.match(/<UiButton\b/g)?.length, 4);
});
test('the preview switch and Follow are pressed toggles with their classes', () => {
const previews = card.match(/<UiButton v-if="\w+" :pressed[^>]*>/g) ?? [];
assert.equal(previews.length, 4);
for (const button of previews) {
assert.match(button, /pressed-class="active"/);
assert.doesNotMatch(button, /aria-pressed|:class=/);
}
assert.match(
card,
/<UiButton v-if="store\.canFollow\(\)" class="entity-card__action" :pressed="Boolean\(store\.isFollowing\(\)\)" pressed-class="entity-card__action--on"/,
);
});
test('the entity card hand-writes no Material glyph; each is a UiIcon', () => {
for (const markup of [card, camera, nearby, ...heroViews])
assert.deepEqual(markup.match(/material-symbols-outlined/g) ?? [], []);
const counts = [
// The preview switch's three, the hero glyph, the header icon, the
// warning, the route's plane, the route note and the three actions.
[card, 11],
// Bigger view, the popup's camera and More info.
[camera, 3],
// The two weather glyphs, five headings and three row glyphs.
[nearby, 10],
];
for (const [markup, count] of counts) {
const icons = markup.match(/<UiIcon\b[^>]*>/g) ?? [];
assert.equal(icons.length, count);
// Without it the kit writes an 18px size that beats the card's own rules.
for (const icon of icons) assert.match(icon, /:size="null"/);
}
});
test('the only inline SVG glyph is the Ask GEV chat bubble', () => {
const svgs = [...card.matchAll(/<svg\b[\s\S]*?<\/svg\s*>/g)].map((m) => m[0]);
assert.equal(svgs.length, 1);
assert.match(svgs[0], /<path d="M4 5h16v11H9l-5 4z" \/>/);
for (const markup of [camera, nearby])
assert.deepEqual(markup.match(/<svg\b/gi) ?? [], []);
});
+266
View File
@@ -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}`,
);
});
+50
View File
@@ -0,0 +1,50 @@
// The Layer Finder's buttons and Material glyphs are the kit's: its template
// hand-writes no <button>, aria-pressed, Material Symbols span or inline SVG.
// Its search field is a UiSearchField.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
/** A view's template block: everything outside script and style. */
function template(file) {
const source = readFileSync(
new URL(`../views/panels/${file}`, import.meta.url),
'utf8',
);
return source.replace(/<(script|style)\b[\s\S]*?<\/\1\s*>/g, '');
}
const finder = template('LayerFinder.vue');
test('the Layer Finder hand-writes no button; each is a UiButton', () => {
assert.deepEqual(finder.match(/<button\b/gi) ?? [], []);
// Search, Filter, the Status and Category options, and the two chips.
assert.equal(finder.match(/<UiButton\b/g)?.length, 6);
assert.equal(finder.match(/<UiSearchField\b/g)?.length, 1);
});
test('its pressed toggles leave aria-pressed to UiButton', () => {
assert.deepEqual(finder.match(/aria-pressed/g) ?? [], []);
const pressed = finder.match(/<UiButton\b[^>]*:pressed=[^>]*>/g) ?? [];
// Search and the Status and Category options.
assert.equal(pressed.length, 3);
// Only the options' active class follows their pressed state; Search's
// also stays on while a query is typed, so it keeps its own binding.
assert.equal(
pressed.filter((tag) => tag.includes('pressed-class="active"')).length,
2,
);
assert.match(
finder,
/id="layer-finder-search-btn"[^>]*:class="\{ active: searching \|\| query \}"/,
);
});
test('the Layer Finder hand-writes no Material glyph; each is a UiIcon', () => {
assert.deepEqual(finder.match(/material-symbols-outlined/g) ?? [], []);
assert.deepEqual(finder.match(/<svg\b/gi) ?? [], []);
const icons = finder.match(/<UiIcon\b[^>]*>/g) ?? [];
// Search, Filter, the two option radios and the two chips' close.
assert.equal(icons.length, 6);
// Without it the kit writes an 18px size that beats layer-finder.css.
for (const icon of icons) assert.match(icon, /:size="null"/);
});
+37
View File
@@ -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" \/>/);
});
+107
View File
@@ -0,0 +1,107 @@
// The Stories views' buttons and checkboxes are the kit's: neither the
// Stories entry nor any Explore or Story screen hand-writes a <button> or an
// `<input type="checkbox">`. Their glyphs are inline SVG drawn for Stories
// (play, pause, back, filter, search, clear, expand, the GEV eye); no
// Material symbol the page loads draws any of them the same, so they stay
// SVG, and no view hand-writes a Material Symbols span. The two search
// fields keep their own markup rather than UiSearchField, whose Material
// magnifier would replace their SVG one, and their clear buttons stay ghost
// UiButtons with an SVG cross rather than UiCloseButtons, whose glyph is ×
// or the Material `close` symbol.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
/** A view's template block: everything outside script and style. */
function template(file) {
const source = readFileSync(
new URL(`../views/${file}`, import.meta.url),
'utf8',
);
return source.replace(/<(script|style)\b[\s\S]*?<\/\1\s*>/g, '');
}
const views = {
// The Stories entry, the popup's Browse stories and Not now, and the
// toast's Back to story.
'StoriesView.vue': { buttons: 4, svgs: 2 },
// The list grip, Filter, the two search clears, the topic chips (All and
// each topic), the filter's Clear and Show, Clear all, a card's thumbnail
// play and Play story, the map pins and the preview's Play story.
'stories/ExploreScreen.vue': { buttons: 13, svgs: 8 },
// Back, the logo, the breadcrumb's link, search, Share and Back to GEV or
// GEV Stories.
'stories/StoriesHeader.vue': { buttons: 8, svgs: 5 },
// The sheet handle, voice search, the search results, Close, the key
// moments and the related stories.
'stories/StoryContext.vue': { buttons: 6, svgs: 3 },
// Open in GEV and Share.
'stories/StoryRail.vue': { buttons: 2, svgs: 1 },
// A chapter, Minimise, Expand, the card's page dots, the big Play and
// Context.
'stories/StoryScreen.vue': { buttons: 6, svgs: 5 },
// Play, the key moment pips and Expand map.
'stories/StoryTimeline.vue': { buttons: 3, svgs: 2 },
};
// A tag's attributes, read past quoted values so a handler's `=>` does not
// end the tag early.
const ATTRS = String.raw`(?:[^>"']|"[^"]*"|'[^']*')*`;
const tag = (pattern, flags = '') =>
new RegExp(pattern.replaceAll('ATTRS', ATTRS), flags);
const markup = Object.fromEntries(
Object.keys(views).map((file) => [file, template(file)]),
);
test('the Stories views hand-write no button; each is a UiButton', () => {
for (const [file, { buttons }] of Object.entries(views)) {
assert.deepEqual(markup[file].match(/<button\b/gi) ?? [], [], file);
assert.equal(markup[file].match(/<UiButton\b/g)?.length, buttons, file);
}
});
test('the pressed toggles take the kit pressed state', () => {
for (const view of Object.values(markup))
assert.doesNotMatch(view, tag(String.raw`<UiButton\bATTRS\saria-pressed`));
const explore = markup['stories/ExploreScreen.vue'];
// All, each topic and the map pins; the cards are role="button" divs that
// keep their own aria-pressed.
assert.equal(
explore.match(tag(String.raw`<UiButton\bATTRS\s:pressed=`, 'g'))?.length,
3,
);
assert.match(
explore,
tag(String.raw`class="card"\s+role="button"ATTRS\s:aria-pressed=`),
);
assert.match(
markup['stories/StoryScreen.vue'],
tag(String.raw`<UiButton\s+id="btnCtx"ATTRS\s:pressed="ctxOpen"`),
);
assert.match(
markup['stories/StoryTimeline.vue'],
tag(String.raw`<UiButton\s+id="stExpand"ATTRS\s:pressed="expanded"`),
);
});
test("Explore's filter options are UiCheckboxes in their own label", () => {
const explore = markup['stories/ExploreScreen.vue'];
assert.deepEqual(
explore.match(tag(String.raw`<input\bATTRS\stype="checkbox"`, 'g')) ?? [],
[],
);
const boxes = explore.match(tag(String.raw`<UiCheckbox\bATTRS>`, 'g')) ?? [];
assert.equal(boxes.length, 1);
assert.match(boxes[0], /class="fopt"/);
// Controlled, so the box always shows the applied filter.
assert.match(boxes[0], /:model-value="Boolean\(/);
});
test('the glyphs stay inline SVG; no view hand-writes a Material span', () => {
for (const [file, { svgs }] of Object.entries(views)) {
assert.deepEqual(
markup[file].match(/material-symbols-outlined/g) ?? [],
[],
file,
);
assert.equal(markup[file].match(/<svg\b/g)?.length, svgs, file);
}
});
+53
View File
@@ -0,0 +1,53 @@
// The Visual panel's buttons and Material glyphs are the kit's: neither its
// template nor the presets it renders hand-writes a <button>, a Material
// Symbols span or an inline SVG. The toggles' text glyphs (◎ ▣ ✈ □ ✨ 🔍)
// and the presets' style glyphs are characters, not Material symbols, so
// they stay text the panel's rules size.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
/** A view's template block: everything outside script and style. */
function template(file) {
const source = readFileSync(
new URL(`../views/panels/${file}`, import.meta.url),
'utf8',
);
return source.replace(/<(script|style)\b[\s\S]*?<\/\1\s*>/g, '');
}
const panel = template('DisplayPanel.vue');
const presets = template('VisualPresets.vue');
test('the Visual panel hand-writes no button; each is a UiButton', () => {
for (const markup of [panel, presets])
assert.deepEqual(markup.match(/<button\b/gi) ?? [], []);
// HUD, Sonar, Detection, 3D, Clean UI, Celestial, Bloom, Sharpen and
// Reset to default.
assert.equal(panel.match(/<UiButton\b/g)?.length, 9);
// The style presets and the map source chips.
assert.equal(presets.match(/<UiButton\b/g)?.length, 2);
// Scope, the sky rows and the application's toggle rows.
assert.equal(panel.match(/<UiCheckbox\b/g)?.length, 3);
// 3D model coverage and detection label allocation.
assert.equal(panel.match(/<UiSegmented\b/g)?.length, 2);
});
test('the Visual panel hand-writes no Material glyph; each is a UiIcon', () => {
for (const markup of [panel, presets]) {
assert.deepEqual(markup.match(/material-symbols-outlined/g) ?? [], []);
assert.deepEqual(markup.match(/<svg\b/gi) ?? [], []);
}
const icons = panel.match(/<UiIcon\b[^>]*>/g) ?? [];
// Scope, Celestial, the sky rows, the application's rows and Reset.
assert.equal(icons.length, 5);
// Without it the kit writes an 18px size that beats the panel's own rules.
for (const icon of icons) assert.match(icon, /:size="null"/);
});
test('the toggles keep their text glyphs as plain spans', () => {
const glyphs = [...panel.matchAll(/<span class="pp-icon">([^<]*)<\/span>/g)];
assert.deepEqual(
glyphs.map((m) => m[1]),
['&#x25CE;', '&#x25A3;', '&#x2708;', '&#x25A1;', '&#x2728;', '&#x1F50D;'],
);
});
+37
View File
@@ -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"/);
});
+5
View File
@@ -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
View File
@@ -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);
}
+35 -3
View File
@@ -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;
+1
View File
@@ -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');
+2
View File
@@ -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 -6
View File
@@ -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 }) });
+1
View File
@@ -9,6 +9,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']),
});
+22 -2
View File
@@ -36,6 +36,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' }),
]);
@@ -129,6 +134,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';
@@ -241,7 +247,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) {
@@ -474,9 +482,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());
}
+2 -3
View File
@@ -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' },
+3
View File
@@ -140,6 +140,9 @@ export function mayRunOnEnter(item, text, parsed, context) {
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);
+81 -76
View File
@@ -13,9 +13,11 @@
// 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';
@@ -279,9 +281,7 @@ export const FEATURE_GUIDES = Object.freeze({
prepare: () => $('#hud-toggle')?.scrollIntoView?.({ block: 'center' }),
targets: () => [$('#hud-toggle')],
text: () =>
t(
'Switch the HUD on or off here; Layout picks Tactical, Minimal or Cyber',
),
t('Switch the HUD on or off here; Layout picks Tactical or Minimal'),
},
],
scope: () => [
@@ -447,43 +447,71 @@ export function startGuide(steps, { title = '' } = {}) {
active?.stop();
const doc = globalThis.document;
if (!doc?.body || screenIsOwned(doc) || !steps?.length) return;
const root = doc.createElement('div');
root.className = 'gev-guide';
root.innerHTML =
'<div class="gev-guide-ring"><i></i></div>' +
'<div class="gev-guide-callout" role="dialog" aria-modal="false" tabindex="-1" aria-labelledby="gev-guide-title" aria-describedby="gev-guide-text">' +
'<div class="gev-guide-head"><p id="gev-guide-title" class="gev-guide-title"></p>' +
'<p class="gev-guide-count"></p>' +
'<button type="button" class="gev-guide-close"><span aria-hidden="true">×</span></button></div>' +
'<ol class="gev-guide-progress" aria-hidden="true"></ol>' +
'<div class="gev-guide-body"><p id="gev-guide-text" class="gev-guide-text"></p>' +
'<p class="gev-guide-hint"><span class="gev-guide-hint-dot"></span><span></span></p></div>' +
'<div class="gev-guide-actions"><p class="gev-guide-keys"><kbd></kbd><span></span></p>' +
'<span><button type="button" class="gev-guide-skip" hidden></button>' +
'<button type="button" class="gev-guide-offer" hidden></button>' +
'<button type="button" class="gev-guide-next"></button></span></div>' +
// 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.
'<p class="gev-guide-status" role="status" aria-live="polite"></p></div>';
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;
doc.body.append(root);
const ring = root.querySelector('.gev-guide-ring');
const callout = root.querySelector('.gev-guide-callout');
// 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 endLabel = t('End guide');
root.querySelector('.gev-guide-close').setAttribute('aria-label', endLabel);
root.querySelector('.gev-guide-close').title = endLabel;
// i18n-ignore: the Escape keycap, matching the keyboard shortcut.
root.querySelector('.gev-guide-keys kbd').textContent = 'Esc';
root.querySelector('.gev-guide-keys span').textContent = t('to end');
root.querySelector('.gev-guide-title').textContent = title
? t('Guide · {topic}', { topic: title })
: t('Guide');
root.querySelector('.gev-guide-next').textContent = t('Next');
root.querySelector('.gev-guide-hint span:last-child').textContent = t(
'Press the highlighted control',
);
const live = steps.filter(Boolean);
let index = -1;
@@ -505,7 +533,8 @@ export function startGuide(steps, { title = '' } = {}) {
doc.removeEventListener('click', onClick, true);
doc.removeEventListener('keydown', onKey, true);
const hadFocus = root.contains(doc.activeElement);
root.remove();
mounted = false;
renderVue(null, host);
if (hadFocus && returnFocus?.isConnected) returnFocus.focus?.();
if (active?.stop === stop) active = null;
};
@@ -536,41 +565,29 @@ export function startGuide(steps, { title = '' } = {}) {
// would not be skipped as things stand.
const total =
shown + live.slice(index + 1).filter((later) => !later.skip?.()).length;
root.querySelector('.gev-guide-count').textContent = `${shown} / ${total}`;
const progress = root.querySelector('.gev-guide-progress');
progress.replaceChildren(
...Array.from({ length: total }, (_, i) => {
const dot = doc.createElement('li');
if (i < shown - 1) dot.className = 'done';
if (i === shown - 1) dot.className = 'current';
return dot;
}),
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();
root.querySelector('.gev-guide-text').textContent = text;
root.querySelector('.gev-guide-status').textContent =
`${shown} / ${total}: ${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;
root.querySelector('.gev-guide-hint').hidden = !waits;
const offer = root.querySelector('.gev-guide-offer');
const skip = root.querySelector('.gev-guide-skip');
offer.hidden = !step.offer;
skip.hidden = !step.offer;
root.querySelector('.gev-guide-keys').hidden = Boolean(step.offer);
view.hintHidden = !waits;
view.offerHidden = !step.offer;
view.skipHidden = !step.offer;
view.keysHidden = Boolean(step.offer);
if (step.offer) {
offer.textContent = step.offer.label();
skip.textContent = t('Not now');
view.offerLabel = step.offer.label();
view.skipLabel = t('Not now');
}
const last = index === live.length - 1;
const nextButton = root.querySelector('.gev-guide-next');
nextButton.hidden = Boolean(step.offer);
nextButton.textContent = last
? t('Finish')
: waits
? t('Skip step')
: t('Next');
nextButton.classList.toggle('quiet', waits && !last);
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;
@@ -599,18 +616,6 @@ export function startGuide(steps, { title = '' } = {}) {
event.stopPropagation();
stop();
}
root.querySelector('.gev-guide-skip').addEventListener('click', stop);
root.querySelector('.gev-guide-close').addEventListener('click', stop);
root.querySelector('.gev-guide-next').addEventListener('click', () => {
if (current) next();
});
// Taking the offer carries the walk on with its steps.
root.querySelector('.gev-guide-offer').addEventListener('click', () => {
if (!current?.offer) return;
const extra = current.offer.steps() || [];
live.splice(index + 1, live.length, ...extra.filter(Boolean));
next();
});
doc.addEventListener('click', onClick, true);
doc.addEventListener('keydown', onKey, true);
+136
View File
@@ -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);
});
+150 -10
View File
@@ -9,6 +9,7 @@
// entity comes last.
import { msg } from '../i18n/index.js';
import { parseCoordinateQuery } from '../search/coordinateParser.js';
/** Visual styles, by the words people use for them. */
const STYLES = [
@@ -83,6 +84,12 @@ const PANEL_NAMES = [
[/display( panel)?|visual( panel)?/, 'left', 'pp-toggles', msg('Visual')],
[/cctv panel|cameras? panel/, 'right', 'cctv-panel', msg('CCTV')],
[/street ?level panel/, 'right', 'street-level-panel', msg('Street Level')],
[
/(space )?missions? panel/,
'right',
'space-missions-panel',
msg('Space Missions'),
],
[/context( panel)?/, 'right', 'global-context-panel', msg('Context')],
];
const CLOSE = /\b(collapse|close|hide|minimi[sz]e|dismiss|shut|fold)\b/;
@@ -185,8 +192,8 @@ const AUX_FORM =
/**
* Whether a line is a real question, which Ask GEV may answer on Enter (a
* billed call):
* - one ending with "?" that has two words and two letters or more (or
* three Han, Kana or Hangul characters);
* - one ending with "?" that has a question form or two non-Latin words
* with a word of two letters or more, or five Han, Kana or Hangul characters;
* - without "?", only a question word's form ("what is here", "how far is
* paris") with a word about something after it, and not written as a
* name ("Where Is My Mind").
@@ -209,13 +216,12 @@ export function isRealQuestion(text) {
const words = line.replace(/\?+$/, '').split(/\s+/).filter(Boolean);
if (line.endsWith('?'))
// A name with "?" ("New York?", "Truth or Consequences?", "東京都?") is
// offered to GEV, not sent: a question's form, or four words or more
// (five Han, Kana or Hangul characters, written without spaces; two
// words in other non-Latin scripts).
// offered to GEV, not sent: a question's form, or five Han, Kana or
// Hangul characters written without spaces, or two words in other
// non-Latin scripts.
return (
((WH_FORM.test(line) ||
AUX_FORM.test(line) ||
words.length >= 4 ||
// Question words in other scripts are not read: two words do.
(words.length >= 2 && !/\p{Script=Latin}/u.test(line))) &&
words.some((word) => (word.match(/\p{L}/gu) || []).length >= 2)) ||
@@ -281,6 +287,11 @@ export function normalizeLine(text, { isRequest = isPlainRequest } = {}) {
.trim();
const end = /(?<!(?:^|[\s.])\p{L})[.!。]+$/u;
line = line.replace(end, '');
// A verb typed twice ("hide hide everything") is one.
line = line.replace(
/^((?:turn|switch) (?:on|off)|show|hide|remove|enable|disable|clear|go to|fly to)\s+\1\b/i,
'$1',
);
// "please" is dropped only around a request: "Please Touch Museum",
// "Kindly Lane" and "Pretty Please" are names.
const polite = line
@@ -288,7 +299,25 @@ export function normalizeLine(text, { isRequest = isPlainRequest } = {}) {
.replace(/(?:\s*,\s*|\s+)(?:please|pls|plz)$/i, '')
.replace(end, '')
.trim();
return polite !== line && polite && isRequest(polite) ? polite : line;
const read = polite !== line && polite && isRequest(polite) ? polite : line;
// "remove flights from the map", "clear everything except ships from the
// map": the map is where every layer is taken from. Not the verb's own
// "off" ("turn off the screen" is no layer switch), not after "show"
// ("show me the view from the map" is a question), and after "clear"
// only for the whole map ("clear all flights" would read as a place).
const bare = read.replace(
/^((?:turn|switch) off|hide|remove|disable|clear)\s+(\S.*?)\s+(?:from|off) (?:the )?(?:map|globe|screen|view)$/i,
'$1 $2',
);
if (bare === read || !/^clear\b/i.test(bare)) return bare;
// "clear" takes the whole map: "clear flights" would read as a place.
const lower = bare.toLowerCase();
return CLEAR_ALL.test(lower) ||
/^clear (?:everything|all(?: the)?(?: other)?(?: layers?)?|every layer) (?:except|but|other than|apart from|besides|save for)\b/.test(
lower,
)
? bare
: read;
}
/** A request by its own words: a verb starting it, or a real question. */
@@ -362,6 +391,74 @@ const GO_TAIL =
const SEPARATORS =
/(\s*(?:,|;(?!\s*[-+]?\d)|\+(?!\d)|&|\band then\b|\bthen\b|\band\b|\balso\b)\s*)/;
/**
* Places whose own name holds "and" (or "&"), kept whole after "near" or
* "in" instead of read as two places: "flights near Trinidad and Tobago".
*/
const COMPOUND_PLACES = new Set([
'trinidad and tobago',
'antigua and barbuda',
'bosnia and herzegovina',
'saint kitts and nevis',
'st kitts and nevis',
'st. kitts and nevis',
'saint vincent and the grenadines',
'st vincent and the grenadines',
'st. vincent and the grenadines',
'sao tome and principe',
'são tomé and príncipe',
'turks and caicos',
'turks and caicos islands',
'wallis and futuna',
'saint pierre and miquelon',
'heard island and mcdonald islands',
'svalbard and jan mayen',
'south georgia and the south sandwich islands',
'newfoundland and labrador',
'jammu and kashmir',
'andaman and nicobar islands',
'dadra and nagar haveli',
'brighton and hove',
]);
/**
* The joining words of a compound place ("and", or "and the" when "the" was
* read off the second part: "Saint Vincent and the Grenadines"), or null.
*/
const compoundJoin = (first, second) =>
COMPOUND_PLACES.has(`${first} and ${second}`.toLowerCase())
? ' and '
: COMPOUND_PLACES.has(`${first} and the ${second}`.toLowerCase())
? ' and the '
: null;
/**
* Lower case one character at a time, so the line keeps its length and
* "İstanbul" reads "istanbul" (not "i̇stanbul" with a combining dot).
*/
function lowerEach(text) {
return Array.from(text, (char) =>
char === 'İ' ? 'i' : char.toLowerCase().normalize('NFC'),
).join('');
}
/**
* A place as it was typed: "İstanbul", "iPhone store", "McAllen" are kept,
* where the line read them in lower case. A place the line put together
* ("Trinidad and Tobago" from "Trinidad & Tobago") stays as read.
*/
export function asTypedIn(raw, place) {
const lowered = lowerEach(raw).replace(/\s+/g, ' ');
const spaced = raw.replace(/\s+/g, ' ');
if (lowered.length !== spaced.length) return place;
const at = lowered.indexOf(place);
if (at < 0) return place;
const before = lowered[at - 1];
const after = lowered[at + place.length];
if (/[\p{L}\p{N}]/u.test(before || '') || /[\p{L}\p{N}]/u.test(after || ''))
return place;
return spaced.slice(at, at + place.length);
}
function tidy(text) {
return text.replace(/\s+/g, ' ').trim();
}
@@ -410,7 +507,7 @@ export function parseOmnibar(
{ isEntity = () => false } = {},
) {
const raw = String(text || '').trim();
const line = tidy(raw.toLowerCase()).replace(
const line = tidy(lowerEach(raw)).replace(
/\b(black[- ]and[- ]white|b ?& ?w)\b/g,
'noir',
);
@@ -443,6 +540,9 @@ export function parseOmnibar(
const extraPlaces = [];
let previousHadPlace = false;
let previousBarePlace = false;
// Whether the clause before was a further place ("near Paris and
// Trinidad"), which a compound name may go on ("and Tobago").
let previousExtraPlace = false;
let previousGo = false;
// Whether a request was peeled off a "go to" clause, and how the place
// was named: after "go to", after "near"/"in", or bare.
@@ -478,9 +578,12 @@ export function parseOmnibar(
for (let i = 0; i < clauses.length; i += 2) {
let clause = tidy(clauses[i]);
const separator = clauses[i - 1]?.trim();
const afterPlace = previousHadPlace;
const afterPlaceComma = previousHadPlace && separator === ',';
// "trinidad and tobago": a bare place joined to a bare place by "and".
const afterBarePlaceAnd = previousBarePlace && separator === 'and';
const afterExtraPlace = previousExtraPlace;
previousExtraPlace = false;
const continuedLayer = previousLayerEnabled;
const afterGo = previousGo;
previousGo = false;
@@ -521,9 +624,35 @@ export function parseOmnibar(
const addPlace = (value, { bare = false, leftover = false } = {}) => {
if (!value) return;
if (leftover) placeClauses.add(i);
// "near Trinidad and Tobago", "in Bosnia & Herzegovina": one place.
const joinsName =
place &&
afterPlace &&
(separator === 'and' || separator === '&') &&
compoundJoin(place.split(', ').at(-1), value);
if (joinsName) {
// The name is whole: a further "and" names another place ("near
// Trinidad and Tobago and Barbados").
place += `${joinsName}${value}`;
previousHadPlace = true;
previousBarePlace = false;
return;
}
// "near Paris and Trinidad and Tobago": the further place is whole too.
const joinsExtra =
afterExtraPlace &&
(separator === 'and' || separator === '&') &&
compoundJoin(extraPlaces.at(-1), value);
if (joinsExtra) {
extraPlaces[extraPlaces.length - 1] += `${joinsExtra}${value}`;
return;
}
if (place && bare && afterBarePlaceAnd) place += ` and ${value}`;
else if (place && !afterPlaceComma) {
if (separator === 'and') extraPlaces.push(value);
if (separator === 'and') {
extraPlaces.push(value);
previousExtraPlace = true;
}
return;
} else if (!place) {
place = value;
@@ -829,7 +958,18 @@ export function parseOmnibar(
// Thermal"): no plan runs on Enter; the line may still be a name.
const unasked = steps.length > 0 && steps.every((step) => !asked.has(step));
if (place && !placeFrom) placeFrom = placeBare ? 'bare' : 'near';
if (place) steps.unshift({ kind: 'place', place });
if (place) {
// A grid reference is read only as typed ("14R PU 2090 4906"; in lower
// case it may be words), so the plan keeps it so.
const typed = asTypedIn(raw, place);
if (!parseCoordinateQuery(place) && parseCoordinateQuery(typed))
place = typed;
const step = { kind: 'place', place };
// How the place was typed, for its label only ("İstanbul", "iPhone
// store"); kept off the step's fields, which plans compare.
Object.defineProperty(step, 'shown', { value: asTypedIn(raw, place) });
steps.unshift(step);
}
steps.verb = LAYER_OFF.test(line) || LAYER_ON.test(line) || GO.test(line);
// Following happens once the camera has settled on the new view.
steps.sort((a, b) => (a.kind === 'follow') - (b.kind === 'follow'));
+11
View File
@@ -123,6 +123,16 @@ test('near-miss lines read as people mean them', () => {
]);
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 },
@@ -252,6 +262,7 @@ test('ar and he mark every Omnibar string alike with a right-to-left mark', asyn
// 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',
+116 -25
View File
@@ -22,6 +22,7 @@ import {
hasActionVerb,
isPanelText,
isRealQuestion,
asTypedIn,
isWholeMapClear,
magnitudeFloor,
normalizeLine,
@@ -152,6 +153,24 @@ const SETTINGS_FOR =
const SWITCH =
/^(turn on|switch on|enable|show|display|add|turn off|switch off|disable|hide|remove|toggle)(?:\s+(.*))?$/;
const SWITCH_OFF = /^(turn off|switch off|disable|hide|remove)\b/;
/**
* A word for a kind of place, alone: after a keyword it ends a name ("Fire
* Island", "Ship Bottom", "Radio City"), and is no place to go to by itself.
* Followed by more words it may begin one ("City Hall", "Peak District").
*/
const NAME_TAIL =
/^(?:islands?|isle|city|hall|bottom|beach|station|street|road|hills?|valley|falls|springs?|creek|county|town|village|harbou?r|cove|canyon|center|centre|square|bridge|ridge|peak)$/i;
/**
* A layer that shows itself through another, which must stay on with it:
* Space Missions draws its missions with Satellites, and switching it off
* puts Satellites back as it was before.
*/
const SHOWN_THROUGH = new Map([['rocket-launches', ['satellites']]]);
/** "hide everything except …", "turn off all layers but …". */
const EXCEPT =
/^(?:turn off|switch off|disable|hide|remove|clear)\s+(?:everything|all(?: the)?(?: other)?(?: layers?)?|every layer)\s+(?:except(?: for)?|but(?: for)?|other than|apart from|besides|save for)\s+(.+)$/;
// Layers people reach for first, so "turn on" offers these before the rest.
export const POPULAR_LAYERS = [
'flights',
@@ -393,12 +412,19 @@ const SMALL_WORDS = new Set([
'da',
'des',
]);
/**
* A place's name for a row: as typed when it has a capital ("iPhone store",
* "McAllen", "İstanbul"), else each word capitalised but the small joining
* ones ("santa fe de bogotá" reads "Santa Fe de Bogotá").
*/
export const titleCase = (text) =>
text.replace(/\S+/g, (word, at) =>
at > 0 && SMALL_WORDS.has(word)
? word
: word[0].toUpperCase() + word.slice(1),
);
/\p{Lu}/u.test(text)
? text
: text.replace(/\S+/g, (word, at) =>
at > 0 && SMALL_WORDS.has(word)
? word
: word[0].toUpperCase() + word.slice(1),
);
const STYLE_LABELS = {
noir: msg('Style: Noir'),
@@ -503,19 +529,13 @@ export const COMMANDS = Object.freeze([
name: 'Visual',
},
),
cmd(
'open-context',
msg('Open Context'),
'context missions panel open',
'radar',
{
kind: 'panel',
action: 'open',
side: 'right',
item: 'global-context-panel',
name: 'Context',
},
),
cmd('open-context', msg('Open Context'), 'context panel open', 'radar', {
kind: 'panel',
action: 'open',
side: 'right',
item: 'global-context-panel',
name: 'Context',
}),
cmd('reset', msg('Reset view'), 'home start over reset camera', 'public', {
kind: 'camera',
act: 'reset',
@@ -713,7 +733,7 @@ export function matchCommands(text) {
export function stepLabel(step) {
switch (step.kind) {
case 'place':
return titleCase(step.place);
return titleCase(step.shown ?? step.place);
case 'layer':
return step.enabled
? t('{layer} on', { layer: step.layer.shown })
@@ -825,12 +845,13 @@ const askRow = (text) => ({
label: t('Ask GEV: “{query}”', { query: text }),
hint: t('Opens chat'),
});
const placeRow = (place) => ({
/** `shown`: the place as typed, for the label ("İstanbul", "iPhone store"). */
const placeRow = (place, shown = place) => ({
key: `place:${place}`,
kind: 'place',
icon: 'location_on',
place,
label: t('Go to {place}', { place: titleCase(place) }),
label: t('Go to {place}', { place: titleCase(shown) }),
hint: t('Place or coordinates'),
});
/**
@@ -920,6 +941,60 @@ export function createOmnibar({ layers = [], isEntity = () => false } = {}) {
return cache.get(line);
}
/**
* "hide everything except flights", "turn off all but ships": a plan that
* switches off every layer that is on but the ones named. Null when the
* line is not that, or names no layer to keep.
*/
function exceptRows(line, ask) {
const match = EXCEPT.exec(line.toLowerCase());
if (!match) return null;
// Every layer to keep must be one: with a name not read ("flights and
// the fog") nothing is switched off, and only GEV is offered.
const kept = match[1]
.split(/\s*(?:,|\band\b|&)\s*/)
.filter(Boolean)
.map((term) => matchLayers(term.replace(/^(?:the|my)\s+/, ''))[0]);
if (!kept.length) return null;
if (!kept.every(named)) return [ask];
const keptIds = new Set(kept.map((layer) => layer.id));
// Keeping either of a pair keeps both while the first is on: switching
// one off would take the other with it ("except space missions",
// "except satellites").
for (const [layer, through] of SHOWN_THROUGH) {
const on = all().find((entry) => entry.id === layer)?.enabled;
if (on && (keptIds.has(layer) || through.some((id) => keptIds.has(id))))
for (const id of [layer, ...through]) keptIds.add(id);
}
const steps = all()
.filter((layer) => layer.enabled && !keptIds.has(layer.id))
.map((layer) => ({ kind: 'layer', layer, enabled: false }));
if (!steps.length)
return [
{
key: 'none',
kind: 'none',
icon: 'layers',
label: t('No other layers are on'),
hint: '',
},
ask,
];
return [
{
key: `plan:${JSON.stringify(steps)}`,
kind: 'plan',
icon: 'bolt',
steps,
// Asked for in so many words: Enter runs it.
asked: true,
label: steps.map(stepLabel).join(' · '),
hint: t('Do all'),
},
ask,
];
}
/**
* "turn on …", "hide …", "toggle …", alone or with a few letters: the
* layers and features that switch that way, never places. Null when the
@@ -927,6 +1002,8 @@ export function createOmnibar({ layers = [], isEntity = () => false } = {}) {
* ("Show Low, AZ").
*/
function switchRows(line, ask) {
const excepted = exceptRows(line, ask);
if (excepted) return excepted;
const switching = line.toLowerCase().match(SWITCH);
if (
!switching ||
@@ -1055,7 +1132,7 @@ export function createOmnibar({ layers = [], isEntity = () => false } = {}) {
realPlaces.length
? realPlaces
: place.trim().length >= minPlaceChars(place)
? [placeRow(place)]
? [placeRow(place, asTypedIn(text, place))]
: [];
const titled = writtenAsName(text.split(/\s+/));
@@ -1266,7 +1343,7 @@ export function createOmnibar({ layers = [], isEntity = () => false } = {}) {
...(placeStep ? placeRows(placeStep.place).slice(0, 2) : []),
// "near New York and Paris": the plan goes to the first; the others
// are offered rather than dropped.
...extraPlaces.map((extra) => placeRow(extra)),
...extraPlaces.map((extra) => placeRow(extra, asTypedIn(text, extra))),
...steps
.filter((step) => step.kind === 'layer')
.map((step) => layerRow(step.layer, step.enabled)),
@@ -1275,11 +1352,25 @@ export function createOmnibar({ layers = [], isEntity = () => false } = {}) {
// without a verb may be part of the place's name, so the whole line as a
// place comes first and the plan second. After "go to …" with a request
// peeled off, the place is the one read ("go to London with flights").
// A keyword ahead of the rest of a name ("Fire Island", "Ship Bottom")
// begins that name when what is left is only a word for a kind of
// place: a fragment, not a place, so no plan goes there. "earthquakes
// japan", "traffic city hall", "tokyo traffic" and "Thermal, California"
// (a comma parts them) keep their plans.
const lower = text.toLowerCase();
const fragment =
ambiguous &&
!peeled &&
placeStep &&
!/[,;]/.test(text) &&
lower.endsWith(placeStep.place.toLowerCase()) &&
!lower.startsWith(placeStep.place.toLowerCase()) &&
NAME_TAIL.test(placeStep.place);
if (ambiguous)
return withEntities(
[
placeRow(peeled ? placeStep.place : text),
plan,
peeled ? placeRow(placeStep.place, placeStep.shown) : placeRow(text),
...(fragment ? [] : [plan]),
...alternatives.filter((row) => row.kind !== 'place'),
ask,
],
+243 -5
View File
@@ -148,16 +148,15 @@ const OUTCOMES = [
['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 or four words are.
// 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?',
'ask(how about the weather in paris today?)',
],
['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;
@@ -647,3 +646,242 @@ test('several switches in one line are one plan', () => {
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,
);
}
});
+44 -18
View File
@@ -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() {
@@ -204,22 +205,7 @@ export class PanelChrome {
beforeCollapse: () => {
if (panelId === 'location-bar') this._closeLocationSearch?.();
},
// A desktop side panel hides entirely once collapsed; its rail item
// takes the focus its own disclosure can no longer hold.
returnFocusTo: () => {
const panel = document.getElementById(panelId);
if (!panel?.getClientRects || panel.getClientRects().length > 0)
return null;
const item = document.querySelector?.(
`.ui-rail [data-rail-item="${panelId}"]`,
);
return item &&
!item.disabled &&
item.getClientRects().length > 0 &&
getComputedStyle(item).visibility === 'visible'
? item
: null;
},
returnFocusTo: () => this._railFocusStand(panelId),
});
}
@@ -228,9 +214,49 @@ export class PanelChrome {
if (this._disposed || !this._disclosurePanelIds?.has(panelId)) return;
const panel = document.getElementById(panelId);
if (!panel) return;
// Opening a panel folds others too (the side accordion, Cockpit's
// Contact card): note which open ones hold the focus.
const focused = document.activeElement;
const holders = [...this._disclosurePanelIds]
.map((id) => document.getElementById(id))
.filter((el) => el?.contains(focused) && !this._shownPanel(el).collapsed);
const cockpit = this.cockpitView;
const contactHeld =
cockpit?.active &&
!cockpit.contextCollapsed &&
document.getElementById('cockpit-context')?.contains(focused);
this.setPanelCollapsed(panelId, !this._shownPanel(panel).collapsed, {
explicit: true,
});
const stand =
contactHeld && cockpit.contextCollapsed
? document.getElementById('cockpit-context-toggle')
: holders
.filter((el) => this._shownPanel(el).collapsed)
.map((el) => this._railFocusStand(el.id))
.find(Boolean);
stand?.focus({ preventScroll: true });
}
/**
* A desktop side panel hides entirely once collapsed; its rail item takes
* the focus its own disclosure can no longer hold. Null while the panel or
* the item is not shown.
* @param {string} panelId Panel element id.
*/
_railFocusStand(panelId) {
const panel = document.getElementById(panelId);
if (!panel?.getClientRects || panel.getClientRects().length > 0)
return null;
const item = document.querySelector?.(
`.ui-rail [data-rail-item="${panelId}"]`,
);
return item &&
!item.disabled &&
item.getClientRects().length > 0 &&
getComputedStyle(item).visibility === 'visible'
? item
: null;
}
_setCommandDockPanelPinState(
+188
View File
@@ -14,6 +14,8 @@ import PanelCollapseButton from './rail/PanelCollapseButton.vue';
import RailPanel from './rail/RailPanel.vue';
import UiPanel from './kit/UiPanel.vue';
import { usePanelChromeStore } from './stores/panelChrome.js';
import { useDisplayStore } from './stores/display.js';
import { DisplayBindings } from './displayBindings.js';
import CommandDockView from './views/CommandDockView.vue';
function mount(t, component) {
@@ -427,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>
@@ -462,3 +489,164 @@ test('the accordion closes peers through the real store, and opens them again',
assert.equal(panels[0].className, '');
chrome.destroy();
});
test('F collapses Data Layers like its button and keeps its rail entry', (t) => {
document.body.innerHTML = `
<nav class="ui-rail"><button data-rail-item="data-panel" style="visibility: visible"></button></nav>
<div id="data-panel" class="active"><button class="panel-collapse-btn" data-collapse-target="data-panel"></button></div>`;
const panel = document.getElementById('data-panel');
const item = document.querySelector('[data-rail-item="data-panel"]');
panel.getClientRects = () =>
panel.classList.contains('collapsed') ? [] : [{}];
item.getClientRects = () => [{}];
const store = usePanelChromeStore(createPinia());
const chrome = panelChrome(store);
followPanelState(store, 'data-panel', panel);
chrome._disclosurePanelIds = new Set(['data-panel']);
const bindings = new DisplayBindings({
viewer: null,
services: { isScopeMaskEnabled: () => false, cycleDetectionMode() {} },
elements: { _locationSearch: document.createElement('input') },
operations: {
_setScope() {},
_togglePanel: (panelId) => chrome._togglePanel(panelId),
},
readState: () => ({}),
claimDetection() {},
displayStore: useDisplayStore(createPinia()),
});
bindings._initUI();
t.after(() => {
bindings.destroy();
chrome.destroy();
});
const press = (init = {}) =>
document.activeElement.dispatchEvent(
new KeyboardEvent('keydown', { key: 'f', bubbles: true, ...init }),
);
panel.querySelector('button').focus();
press();
assert.equal(store.panels['data-panel']?.collapsed, true);
assert.ok(document.activeElement === item, 'focus moves to the rail');
assert.ok(panel.classList.contains('collapsed'));
// `active` is what shows Data Layers at all (layers.css).
assert.ok(panel.classList.contains('active'));
press({ metaKey: true });
assert.equal(store.panels['data-panel'].collapsed, true, 'Cmd+F is not ours');
press();
assert.equal(store.panels['data-panel'].collapsed, false);
assert.ok(!panel.classList.contains('collapsed'));
assert.ok(panel.classList.contains('active'));
});
test('F that folds a focused peer hands the focus to a rail entry', (t) => {
document.body.innerHTML = `
<nav class="ui-rail">
<button data-rail-item="data-panel" style="visibility: visible"></button>
<button data-rail-item="pp-toggles" style="visibility: visible"></button>
</nav>
<div id="left-panel-stack">
<div id="data-panel" data-panel-id="data-panel" class="active collapsed"><button class="panel-collapse-btn" data-collapse-target="data-panel"></button></div>
<div id="pp-toggles" data-panel-id="pp-toggles"><button class="panel-collapse-btn" data-collapse-target="pp-toggles"></button><button id="crt2">CRT 2</button></div>
</div>`;
const stack = document.getElementById('left-panel-stack');
const store = usePanelChromeStore(createPinia());
const chrome = new PanelChrome({
elements: { _leftPanelStack: stack },
operations: { _showToast() {}, _syncCctvPanelViewport() {} },
readHud: () => ({ visible: false, getVariant: () => null }),
readCockpit: () => null,
readShareLinks: () => null,
readInitialShare: () => null,
readScrollRestoreOwner: () => null,
readDisplayScrollTop: () => 0,
store,
});
for (const id of ['data-panel', 'pp-toggles']) {
const panel = document.getElementById(id);
panel.getClientRects = () =>
panel.classList.contains('collapsed') ? [] : [{}];
followPanelState(store, id, panel);
}
for (const item of document.querySelectorAll('[data-rail-item]'))
item.getClientRects = () => [{}];
chrome._disclosurePanelIds = new Set(['data-panel', 'pp-toggles']);
const bindings = new DisplayBindings({
viewer: null,
services: { isScopeMaskEnabled: () => false, cycleDetectionMode() {} },
elements: { _locationSearch: document.createElement('input') },
operations: {
_setScope() {},
_togglePanel: (panelId) => chrome._togglePanel(panelId),
},
readState: () => ({}),
claimDetection() {},
displayStore: useDisplayStore(createPinia()),
});
bindings._initUI();
t.after(() => {
bindings.destroy();
chrome.destroy();
});
const crt2 = document.getElementById('crt2');
crt2.focus();
assert.equal(document.activeElement, crt2);
crt2.dispatchEvent(new KeyboardEvent('keydown', { key: 'f', bubbles: true }));
assert.equal(
store.panels['data-panel']?.collapsed,
false,
'Data Layers opens',
);
const visual = document.getElementById('pp-toggles');
assert.ok(
visual.classList.contains('collapsed'),
'the accordion folds Visual',
);
assert.ok(
document.activeElement?.matches?.('.ui-rail [data-rail-item]'),
`focus lands on a rail entry, not inside the hidden peer (got ${document.activeElement?.id || document.activeElement?.tagName})`,
);
});
test('opening Data Layers in Cockpit hands the focus from the folded Contact card to its toggle', (t) => {
document.body.innerHTML = `
<div id="left-panel-stack">
<div id="data-panel" data-panel-id="data-panel" class="active collapsed"><button class="panel-collapse-btn" data-collapse-target="data-panel"></button></div>
</div>
<aside id="cockpit-context"><button id="cockpit-context-toggle"></button><button id="cockpit-weather-toggle"></button></aside>`;
const store = usePanelChromeStore(createPinia());
const cockpit = {
active: true,
contextCollapsed: false,
setContextCollapsed(collapsed) {
this.contextCollapsed = collapsed;
},
setSignalCollapsed() {},
scheduleContextLayout() {},
};
const chrome = new PanelChrome({
elements: { _leftPanelStack: document.getElementById('left-panel-stack') },
operations: { _showToast() {}, _syncCctvPanelViewport() {} },
readHud: () => ({ visible: false, getVariant: () => null }),
readCockpit: () => cockpit,
readShareLinks: () => null,
readInitialShare: () => null,
readScrollRestoreOwner: () => null,
readDisplayScrollTop: () => 0,
store,
});
t.after(() => chrome.destroy());
followPanelState(store, 'data-panel', document.getElementById('data-panel'));
chrome._disclosurePanelIds = new Set(['data-panel']);
document.getElementById('cockpit-weather-toggle').focus();
chrome._togglePanel('data-panel');
assert.equal(
store.panels['data-panel']?.collapsed,
false,
'Data Layers opens',
);
assert.equal(cockpit.contextCollapsed, true, 'Contact folds for it');
assert.equal(document.activeElement?.id, 'cockpit-context-toggle');
});
+71
View File
@@ -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',
+2 -5
View File
@@ -1,5 +1,5 @@
import PanelRailView from './PanelRailView.vue';
import { PANEL_RAIL_HOST_CLASS, PANEL_RAIL_ITEMS } from './panelRailCatalog.js';
import { PANEL_RAIL_HOST_CLASS } from './panelRailCatalog.js';
import { usePanelStore } from './stores/panels.js';
/**
@@ -71,7 +71,6 @@ export class PanelNavigation {
? [...stack.children]
.filter((panel) => panel.matches('[data-panel-id]'))
.map((panel) => {
const shownBy = PANEL_RAIL_ITEMS[panel.id]?.shownBy;
return {
id: panel.id,
title:
@@ -79,9 +78,7 @@ export class PanelNavigation {
.querySelector('.panel-title, .pp-header-label')
?.textContent.trim() || panel.id,
open: !panel.classList.contains('collapsed'),
available:
!panel.hidden &&
(!shownBy || panel.classList.contains(shownBy)),
available: !panel.hidden,
};
})
: [];
+2 -4
View File
@@ -22,8 +22,6 @@ function panel(id, { collapsed = true, hidden = false, title = '' } = {}) {
element.className = collapsed
? 'panel-collapsible collapsed'
: 'panel-collapsible';
// Data Layers shows only while `active` (the `f` shortcut toggles it).
if (id === 'data-panel') element.classList.add('active');
element.hidden = hidden;
if (title) element.innerHTML = `<span class="panel-title">${title}</span>`;
return element;
@@ -132,8 +130,8 @@ test('the rails follow disclosure and availability changes', async () => {
['global-context-panel', 'false'],
['host-panel', 'false'],
]);
// `f` hides Data Layers outright, so the rail stops offering it.
document.getElementById('data-panel').classList.remove('active');
// A hidden panel leaves its rail.
document.getElementById('data-panel').hidden = true;
await new Promise((resolve) => setTimeout(resolve, 0));
await nextTick();
assert.deepEqual(railItems(left), [['scene-panel', 'true']]);
+7 -8
View File
@@ -7,16 +7,11 @@ export const PANEL_RAIL_HOST_CLASS = 'gev-panel-rail';
export const PANEL_RAIL_FALLBACK_ICON = 'more_horiz';
/**
* How each side panel appears on its rail. Labels are the panels' own titles.
* `shownBy` names a class the panel needs to be shown at all (`f` toggles
* Data Layers' `active`). `context` is the label's translation context.
* How each side panel appears on its rail. Labels are the panels' own titles;
* `context` is the label's translation context.
*/
export const PANEL_RAIL_ITEMS = Object.freeze({
'data-panel': {
icon: 'layers',
label: msg('DATA LAYERS'),
shownBy: 'active',
},
'data-panel': { icon: 'layers', label: msg('DATA LAYERS') },
'utilities-panel': { icon: 'handyman', label: msg('UTILITIES') },
'scene-panel': { icon: 'movie', label: msg('AUTHORING') },
// `context` keeps the panel's name apart from the satellite class of the
@@ -31,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'),
},
});
/**
+84 -1
View File
@@ -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
View File
@@ -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);
});
+2 -6
View File
@@ -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
View File
@@ -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;
},
+43 -17
View File
@@ -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);
});
+1 -4
View File
@@ -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 (
+4 -6
View File
@@ -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="[
+15 -36
View File
@@ -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
+1 -2
View File
@@ -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,
-17
View File
@@ -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', () => {
+19
View File
@@ -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;
-3
View File
@@ -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',
),
+5 -4
View File
@@ -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);
+25 -5
View File
@@ -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 {
+87
View File
@@ -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);
}
}
+152
View File
@@ -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');
});
+3 -31
View File
@@ -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 445 files, more files were not shown because too many files have changed in this diff. Show more