diff --git a/changelog.d/1911-page-root-classes.md b/changelog.d/1911-page-root-classes.md new file mode 100644 index 0000000000..a904c570d0 --- /dev/null +++ b/changelog.d/1911-page-root-classes.md @@ -0,0 +1,4 @@ +- Stop restyling the whole page on every DOM change. Rules that checked + `body:has(...)` now read classes on the page root that the components owning + that state set, and the Intel HUD runs no timers and writes nothing while it + is not displayed (samehkhamis, #1911). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index faff17524e..3c658841df 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -6327,7 +6327,12 @@ Historical planning documents may not match runtime behavior. ## Runtime Stack - Vite + CesiumJS app with Google Photorealistic 3D Tiles -- Scene/HUD/style systems in `src/ui/` and `src/hud.js` +- Scene/HUD/style systems in `src/ui/` and `src/hud.js`. While `#intel-hud` is + not displayed (it or a parent has `display: none`, or its view is + unmounted), the Intel HUD runs no timers, drops a summary it was working + out and publishes no readouts, only its own `active`, variant and colors, + which stylesheets and layout elsewhere read; it shows current readouts, and + a reply that was typing out in full, as soon as it is displayed again. - Layer management in `src/data/manager.js` - Map stack switching in `src/mapStackController.js` - Voice control in `src/voice/` (OpenAI Realtime over WebRTC) diff --git a/docs/VUE-MIGRATION.md b/docs/VUE-MIGRATION.md index aa2909df10..478dce4975 100644 --- a/docs/VUE-MIGRATION.md +++ b/docs/VUE-MIGRATION.md @@ -629,7 +629,12 @@ slot whenever its view is drawn. store, which IntelHUD publishes to through its `publish` option: the readouts, the typing summary, the REC blink, visibility, layout variant and style colors; the vessel layer presents the selected vessel's - readout through `src/hudReadouts.js` instead of writing into the HUD), + readout through `src/hudReadouts.js` instead of writing into the HUD; + the view reports through the store whether `#intel-hud` is displayed + (not displayed once it is unmounted), and while it is not IntelHUD runs + no timers and publishes only the root's `active`, variant and colors, + then shows current readouts as soon as it is; the readouts that change many times a + second keep their text node through `v-text-data`), the first-run mission launcher (the welcome view renders the card's visibility, busy state, status line, copy and scroll fade from the `gev-first-run` store that `initFirstRunExperience` publishes to, and its @@ -700,6 +705,28 @@ slot whenever its view is drawn. hosts to register panels and rail items is deferred until a host needs one. +## Page-root state classes + +A stylesheet that styles one surface by the state of another, in a different +view (the dock and credits while the Omnibar is on the page, the Stories +entry while the loading screen shows), selects a class on `` rather +than `body:has(...)`. Chrome checks a `:has()` on body again after every node +added or removed anywhere on the page and restyles the whole page when it +does; a class changes only with the state it names. `src/ui/rail/rootClass.js` +holds them: `v-root-class` on the element whose presence or state it names +(the Omnibar, the voice control in the dock, `#intel-hud`, the first-run +launcher, the World Timeline, the language picker), its hooks running inside +Vue's patch so the class changes with the element; `followSelectorRootClass()` +for markup Vue does not render (the loading screen, followed by the Stories +view wherever in body it is added, removed or shown, as `:has()` would); and +`followRootClass()` for nodes that move at run time (the left panel stack's +own panels, followed by the layer panels view). They live on ``, not +`
`, whose class changes several owners follow to lay the page out +again. A rule selects one as `body:is(.has-omnibar *, #gev-omnibar)`: the +second argument never matches body and keeps the specificity the +`:has(#gev-omnibar)` it replaced had. `src/ui/pageRootClasses.test.mjs` +holds each class to its state and every stylesheet to the pattern. + ## Verification - Unit tests: stores and components run under `npm test`. Single-file diff --git a/scripts/format-scope.json b/scripts/format-scope.json index 6d032d05a1..16a0939248 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -1449,6 +1449,7 @@ "src/hudReadouts.js", "src/ui/stores/hud.js", "src/ui/views/intelHudView.test.mjs", + "src/ui/pageRootClasses.test.mjs", "src/testSupport/hudReadouts.mjs", "src/ui/stores/firstRun.js", "src/firstRunLauncherView.test.mjs", diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 0c2b77ae5c..fced41d91a 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -194,6 +194,8 @@ "src/ui/stores/owners.js", "src/ui/rail/rangeValue.js", "src/ui/rail/classToggle.js", + "src/ui/rail/rootClass.js", + "src/ui/rail/textData.js", "src/ui/rail/focusSafeChildren.js", "src/ui/rail/fieldValue.js", "src/ui/rail/statusText.js", @@ -4853,6 +4855,7 @@ "src/ui/layerRowText.js", "src/ui/layerPanel/LayerRows.vue", "src/ui/rail/classToggle.js", + "src/ui/rail/rootClass.js", "src/ui/rail/focusSafeChildren.js", "src/ui/layerPanel/RowText.vue", "src/ui/layerPanel/RowSwitch.vue", diff --git a/src/creditAttribution.test.mjs b/src/creditAttribution.test.mjs index c8a8a30a80..a864340c3a 100644 --- a/src/creditAttribution.test.mjs +++ b/src/creditAttribution.test.mjs @@ -243,7 +243,7 @@ const RECOGNIZED = new Set([ // credit '#cesium-credits', 'body:not(.ui-clean-view):not(.recording-mode) #cesium-credits', - "body:not(.ui-clean-view):not(.recording-mode):has(#intel-hud[data-variant='minimal'].active) #cesium-credits", + "body:not(.ui-clean-view):not(.recording-mode):is(.hud-minimal-active *, #intel-hud[data-variant='minimal'].active) #cesium-credits", 'body.ui-clean-view #cesium-credits', 'body.recording-mode #cesium-credits', // dock @@ -274,12 +274,12 @@ const DOCKED_RAIL = 'body.context-docked #right-context-rail'; // the Omnibar and the voice control share the dock; outside it the legacy // layout below governs. const OMNIBAR_SCOPE = - 'body:not(.mobile-shell):not(.cockpit-mode):not(.scene-playback-mode):not(.ui-clean-view):not(.recording-mode):where(:has(#gev-omnibar):has(#command-dock > #gev-voice-control))'; + 'body:not(.mobile-shell):not(.cockpit-mode):not(.scene-playback-mode):not(.ui-clean-view):not(.recording-mode):where(.has-omnibar.dock-has-voice *)'; const OMNIBAR = Object.freeze({ dock: `${OMNIBAR_SCOPE} #command-dock`, credit: `${OMNIBAR_SCOPE} :is(#cesium-credits, #gev-credits)`, - minimalCredit: `${OMNIBAR_SCOPE}:has(#intel-hud[data-variant='minimal'].active) :is(#cesium-credits, #gev-credits)`, - minimalRail: `${OMNIBAR_SCOPE}:not(.context-docked):has(#intel-hud[data-variant='minimal'].active) #right-context-rail`, + minimalCredit: `${OMNIBAR_SCOPE}:is(.hud-minimal-active *, #intel-hud[data-variant='minimal'].active) :is(#cesium-credits, #gev-credits)`, + minimalRail: `${OMNIBAR_SCOPE}:not(.context-docked):is(.hud-minimal-active *, #intel-hud[data-variant='minimal'].active) #right-context-rail`, trays: `${OMNIBAR_SCOPE} #command-dock > :is(#location-bar, #control-panel)`, }); // What each Omnibar-scope rule may set on a modelled box; the Omnibar @@ -518,7 +518,7 @@ const CREDIT_SELECTORS = [ 'body:not(.ui-clean-view):not(.recording-mode) #cesium-credits', ]; const MINIMAL_HUD_CREDIT = - "body:not(.ui-clean-view):not(.recording-mode):has(#intel-hud[data-variant='minimal'].active) #cesium-credits"; + "body:not(.ui-clean-view):not(.recording-mode):is(.hud-minimal-active *, #intel-hud[data-variant='minimal'].active) #cesium-credits"; const TRAY_ORDINARY = [ '#command-dock .dock-popover-content', '#command-dock #location-bar .dock-popover-content', @@ -1279,7 +1279,7 @@ test('expanded Context keeps the credits beside it right to left and with the mi // The minimal HUD puts the credits bottom right, where the column docks. assert.ok( rule( - "^.*body\\.context-docked:not\\(\\.ui-clean-view\\):not\\(\\.recording-mode\\):has\\( #intel-hud\\[data-variant='minimal'\\]\\.active \\)", + "^.*body\\.context-docked:not\\(\\.ui-clean-view\\):not\\(\\.recording-mode\\):is\\( \\.hud-minimal-active \\*, #intel-hud\\[data-variant='minimal'\\]\\.active \\)", 'right: calc\\(36px \\+ var\\(--context-dock-width\\)\\)', ), 'with the minimal HUD, the credits end before the expanded column', diff --git a/src/firstRunExperience.test.mjs b/src/firstRunExperience.test.mjs index a2d5b31396..b10b1e203d 100644 --- a/src/firstRunExperience.test.mjs +++ b/src/firstRunExperience.test.mjs @@ -920,7 +920,7 @@ test('the Stories announcement waits behind the welcome card', () => { // the card is dismissed. assert.match( css, - /body:has\(#first-run-launcher\) #gev-stories #hPop,\s*body\.first-run-opening-stories #gev-stories #hPop \{\s*visibility: hidden;\s*pointer-events: none;\s*\}/, + /body:is\(\.launcher-shown \*, #first-run-launcher\) #gev-stories #hPop,\s*body\.first-run-opening-stories #gev-stories #hPop \{\s*visibility: hidden;\s*pointer-events: none;\s*\}/, ); // The selector only works while Stories still renders the popup as #hPop // inside #gev-stories. diff --git a/src/hud.js b/src/hud.js index b26912af1f..0e25d3c279 100644 --- a/src/hud.js +++ b/src/hud.js @@ -227,6 +227,17 @@ const NEARBY_POINTS = Object.values(CITY_POIS).flatMap((city) => * and the altitude-scaled GSD/NIIRS figures. Readouts update on independent * fixed cadences. */ +/** + * The view's attributes on #intel-hud itself: shown or not, layout variant + * and style colors. Stylesheets and layout elsewhere on the page read them. + */ +const HUD_FRAME_KEYS = Object.freeze(['active', 'variant', 'colors']); + +/** @param {object} view @returns {object} Its {@link HUD_FRAME_KEYS}. */ +function pickFrame(view) { + return Object.fromEntries(HUD_FRAME_KEYS.map((key) => [key, view[key]])); +} + export class IntelHUD { /** * @param {object} viewer - The scene the HUD sits over. @@ -254,6 +265,19 @@ export class IntelHUD { this.placeSearch = placeSearch; this.viewer = viewer; this._visible = false; + // Whether the HUD's view is on screen (setDisplayed). While it is not, + // no timer runs and no readout is worked out or published; what was + // skipped is caught up when it is back. + this._displayed = true; + this._unseen = { settle: false, show: false, summary: false }; + /** Summary updates under way; one still running when the view goes is + * dropped and asked again when it is back. */ + this._summaryRuns = 0; + /** The text the typewriter is typing out, while it types. */ + this._summaryTypingText = null; + /** When the view stopped being displayed (Date.now()), or null. */ + this._undisplayedAt = null; + this._destroyed = false; this._autoMode = true; // auto show/hide based on style this._currentStyle = 'normal'; /** The presented HUD; see {@link IntelHUD#_initView}. */ @@ -320,20 +344,8 @@ export class IntelHUD { }; this._onCameraMoveEnd = () => { this._markSummaryDirty(); - // The 250 ms telemetry timer and 15 s semantic-summary timer must not - // leave the prior city on-screen after a long CCTV focus flight. - // Refresh deterministic camera context synchronously on settle; the AI - // summary can still upgrade it on its normal cadence. - if (this._visible) { - this._updateCameraData(); - this._setSummaryText(this._composeSummary(), false); - } - // First settled view: request the AI summary now rather than waiting for - // the periodic tick (saves up to ~15s of "Awaiting telemetry..."). - if (!this._firstSummaryKicked && this._visible && this._latestMetrics) { - this._firstSummaryKicked = true; - void this._updateSummary(true, true); - } + if (this._displayed) this._settle(); + else this._unseen.settle = true; }; // Session-consistent pseudorandom identifiers (generated once at construction) @@ -358,6 +370,27 @@ export class IntelHUD { this._startTimers(); } + /** + * The camera has settled: show the readouts and the plain summary for the + * view it settled on. + */ + _settle() { + // The 250 ms telemetry timer and 15 s semantic-summary timer must not + // leave the prior city on-screen after a long CCTV focus flight. + // Refresh deterministic camera context synchronously on settle; the AI + // summary can still upgrade it on its normal cadence. + if (this._visible) { + this._updateCameraData(); + this._setSummaryText(this._composeSummary(), false); + } + // First settled view: request the AI summary now rather than waiting for + // the periodic tick (saves up to ~15s of "Awaiting telemetry..."). + if (!this._firstSummaryKicked && this._visible && this._latestMetrics) { + this._firstSummaryKicked = true; + void this._updateSummary(true, true); + } + } + /** Show the HUD's words in the new locale; drop AI text in the old one. */ _relocalize() { this._markSummaryDirty(); @@ -374,7 +407,8 @@ export class IntelHUD { ? {} : { vessel: { active: false, text: t('AIS: --') } }), }); - if (this._visible && this._latestMetrics) this._updateCameraData(); + if (this._visible && this._displayed && this._latestMetrics) + this._updateCameraData(); this._setSummaryText(this._composeSummary(), false); } @@ -417,10 +451,17 @@ export class IntelHUD { */ _present(patch) { Object.assign(this._view, patch); - const signature = JSON.stringify(this._view); + // Not displayed: only the view's own attributes are published, which the + // page's stylesheets and layout read from #intel-hud while it is hidden + // too; the readouts wait until it is displayed again. + const view = this._displayed + ? this._view + : { ...this._shown, ...pickFrame(this._view) }; + const signature = JSON.stringify(view); if (signature === this._viewSignature) return; this._viewSignature = signature; - this._publish(Object.freeze({ ...this._view })); + this._shown = Object.freeze({ ...view }); + this._publish(this._shown); } /** @@ -429,6 +470,7 @@ export class IntelHUD { * cadences and are cleaned up in {@link destroy}. */ _startTimers() { + this._stopTimers(); // Timestamp — every second this._timestampInterval = setInterval(() => { this._present({ timestamp: this._formatUTC() }); @@ -455,6 +497,18 @@ export class IntelHUD { }, HUD_SUMMARY_INTERVAL_MS); } + /** Stop the periodic timers {@link _startTimers} started. */ + _stopTimers() { + clearInterval(this._timestampInterval); + clearInterval(this._recBlinkInterval); + clearInterval(this._updateInterval); + clearInterval(this._summaryInterval); + this._timestampInterval = null; + this._recBlinkInterval = null; + this._updateInterval = null; + this._summaryInterval = null; + } + /** * Format the HUD's world time as a UTC Zulu string. * @returns {string} Timestamp in `YYYY-MM-DD HH:MM:SSZ` format. @@ -844,6 +898,7 @@ export class IntelHUD { _stopSummaryTyping() { clearInterval(this._summaryTypingInterval); this._summaryTypingInterval = null; + this._summaryTypingText = null; } /** @@ -853,6 +908,7 @@ export class IntelHUD { */ _typeSummary(text) { clearInterval(this._summaryTypingInterval); + this._summaryTypingText = text; let index = 0; this._present({ summary: '' }); this._summaryTypingInterval = setInterval(() => { @@ -861,6 +917,7 @@ export class IntelHUD { this._present({ summary: text }); clearInterval(this._summaryTypingInterval); this._summaryTypingInterval = null; + this._summaryTypingText = null; return; } this._present({ summary: text.slice(0, index) }); @@ -873,6 +930,16 @@ export class IntelHUD { * by character; otherwise sets it instantly. */ async _updateSummary(animate = false, force = false) { + this._summaryRuns += 1; + try { + await this._runSummaryUpdate(animate, force); + } finally { + this._summaryRuns -= 1; + } + } + + /** {@link _updateSummary}'s work. */ + async _runSummaryUpdate(animate, force) { const fallbackText = this._composeSummary(); if (!this._latestMetrics) { this._setSummaryText(fallbackText, animate); @@ -1002,7 +1069,8 @@ export class IntelHUD { } _setSummaryText(text, animate) { - if (animate) { + // Nothing types out off screen: the text is there when the view is back. + if (animate && this._displayed) { this._typeSummary(text); return; } @@ -1123,11 +1191,63 @@ export class IntelHUD { show() { this._visible = true; this._present({ active: true }); + if (this._displayed) this._refreshShown(); + else this._unseen.show = true; + } + + /** Readouts and a fresh summary for a HUD just shown. */ + _refreshShown() { this._updateCameraData(); // immediate update this._markSummaryDirty(); void this._updateSummary(false, true); } + /** + * Whether the HUD's view is on screen. A stylesheet can give the view + * `display: none`, or the view can be unmounted; until it is displayed + * again no timer runs, a summary being worked out is dropped and only the + * view's own attributes ({@link HUD_FRAME_KEYS}) are published. Then the + * timers start again and current readouts show at once. + * @param {boolean} displayed + */ + setDisplayed(displayed) { + displayed = Boolean(displayed); + if (this._destroyed || displayed === this._displayed) return; + this._displayed = displayed; + if (!displayed) { + this._undisplayedAt = Date.now(); + this._stopTimers(); + // A reply still typing is finished: the view shows all of it when it + // is back, not the rest of it typing out. + const typing = this._summaryTypingText; + this._stopSummaryTyping(); + if (typing !== null) this._present({ summary: typing }); + // A summary being worked out is dropped, and asked again when the + // view is back. + if (this._summaryRuns > 0) { + this._unseen.summary = true; + this._markSummaryDirty(); + this._summaryRequest?.abort(); + } + return; + } + const { settle, show } = this._unseen; + // The summary refresh that would have come round while it was away. + const summary = + this._unseen.summary || + Date.now() - (this._undisplayedAt ?? Date.now()) >= + HUD_SUMMARY_INTERVAL_MS; + this._unseen = { settle: false, show: false, summary: false }; + this._undisplayedAt = null; + this._startTimers(); + // Publishes the whole view: what changed while it was not displayed. + this._present({ timestamp: this._formatUTC() }); + if (settle) this._settle(); + if (show && this._visible) this._refreshShown(); + else if (!settle && this._visible) this._updateCameraData(); + if (summary && !show && this._visible) void this._updateSummary(true); + } + /** Hide the HUD overlay. */ hide() { this._visible = false; @@ -1214,10 +1334,8 @@ export class IntelHUD { /** Tear down all running intervals. Call when discarding the HUD instance. */ destroy() { - clearInterval(this._updateInterval); - clearInterval(this._recBlinkInterval); - clearInterval(this._timestampInterval); - clearInterval(this._summaryInterval); + this._destroyed = true; + this._stopTimers(); clearInterval(this._summaryTypingInterval); for (const off of this._offCamera.splice(0)) off(); this._dataManagerUnsubscribe?.(); diff --git a/src/ui/applicationShell.js b/src/ui/applicationShell.js index 8bad25216d..fd54d8132b 100644 --- a/src/ui/applicationShell.js +++ b/src/ui/applicationShell.js @@ -426,6 +426,9 @@ export class StyleManager extends ShellFacade { summaryService: requestServices?.summary, publish: (view) => hudStore.publish(view), }); + // The view says whether it is on screen; off screen the HUD does no + // readout work. + hudStore.connect(this.hud); this._recording.hud = this.hud; this._cockpitCoordinator = new CockpitCoordinator({ viewer, diff --git a/src/ui/hudSonarStyle.test.mjs b/src/ui/hudSonarStyle.test.mjs index c6074702a4..16a6a9c829 100644 --- a/src/ui/hudSonarStyle.test.mjs +++ b/src/ui/hudSonarStyle.test.mjs @@ -502,7 +502,7 @@ test('the desktop bottom row: credits on the Power Up baseline, the dock lifted, const timeline = read('./styles/world-timeline.css'); const timelineLift = value( timeline, - /body:has\(#world-timeline\) \{\s*--world-timeline-lift: (\d+)px;/, + /body:is\(\.has-world-timeline \*, #world-timeline\) \{\s*--world-timeline-lift: (\d+)px;/, ); // From 1200px the dock and the World Timeline leave the bottom 74px; below @@ -549,7 +549,7 @@ test('the desktop bottom row: credits on the Power Up baseline, the dock lifted, ); 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\);/, + /:where\(\.has-omnibar\.dock-has-voice \*\)\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]]; })(), @@ -578,7 +578,7 @@ test('the desktop bottom row: credits on the Power Up baseline, the dock lifted, // 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;/, + /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\):is\(\s*\.hud-minimal-active \*,\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 @@ -791,7 +791,7 @@ test('the Omnibar dock sits above the World Timeline, and narrow corners clear t ); assert.doesNotMatch(css, /--world-timeline-lift\s*:/); const lift = read('./styles/world-timeline.css').match( - /body:has\(#world-timeline\) \{\s*--world-timeline-lift: (\d+)px;/, + /body:is\(\.has-world-timeline \*, #world-timeline\) \{\s*--world-timeline-lift: (\d+)px;/, ); const height = read('./styles/world-timeline.css').match( /#world-timeline \{[^}]*\n {2}height: (\d+)px;/, diff --git a/src/ui/pageRootClasses.test.mjs b/src/ui/pageRootClasses.test.mjs new file mode 100644 index 0000000000..705b9e3025 --- /dev/null +++ b/src/ui/pageRootClasses.test.mjs @@ -0,0 +1,517 @@ +// src/ui/pageRootClasses.test.mjs — the classes on that stylesheets +// select on in place of `body:has(...)` (src/ui/rail/rootClass.js) are on +// exactly while the state each names holds, and every such rule still weighs +// what the `:has()` it replaced did. +import '../testSupport/registerDom.mjs'; +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { createApp, h, nextTick, shallowRef, withDirectives } from 'vue'; +import { createPinia } from 'pinia'; +import { holdRootClass, vRootClass } from './rail/rootClass.js'; +import { assertSameNode } from '../testSupport/domAssert.mjs'; +import { createTestVoiceUi } from '../testSupport/voiceUi.mjs'; +import { worldClock } from '../time/worldClock.js'; +import { useFirstRunStore } from './stores/firstRun.js'; +import { useHudStore } from './stores/hud.js'; +import { useWorldTimeStore } from './stores/worldTime.js'; +import CommandDockView from './views/CommandDockView.vue'; +import IntelHudView from './views/IntelHudView.vue'; +import LayerPanelsView from './views/LayerPanelsView.vue'; +import StoriesView from './views/StoriesView.vue'; +import WelcomeView from './views/WelcomeView.vue'; +import LocalePicker from './views/panels/LocalePicker.vue'; +import Omnibar from './views/panels/Omnibar.vue'; +import WorldTimeline from './views/panels/WorldTimeline.vue'; + +const ROOT = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + '..', + '..', +); +const on = (name) => document.documentElement.classList.contains(name); +const settle = async () => { + await nextTick(); + await nextTick(); +}; + +/** Mount `component` into a fresh body; unmounted after the test. */ +function mount(t, component, props, pinia = createPinia()) { + document.body.replaceChildren(); + const app = createApp(component, props).use(pinia); + app.mount(document.body.appendChild(document.createElement('div'))); + let mounted = true; + const unmount = () => { + if (mounted) app.unmount(); + mounted = false; + }; + t.after(unmount); + return { pinia, unmount }; +} + +test('a held class stays until its last holder lets go', () => { + const first = holdRootClass(document, 'test-held'); + const second = holdRootClass(document, 'test-held'); + assert.ok(on('test-held')); + first(); + first(); + assert.ok(on('test-held'), 'a second release of one hold changes nothing'); + second(); + assert.ok(!on('test-held')); +}); + +test('v-root-class: mounted, updated, swapped and unmounted', async (t) => { + const shown = shallowRef(true); + const lit = shallowRef(false); + const key = shallowRef(1); + const seen = []; + mount(t, { + render: () => + shown.value + ? withDirectives( + h('div', { + key: key.value, + onVnodeMounted: () => seen.push(on('test-present')), + }), + [[vRootClass, { 'test-present': true, 'test-lit': lit.value }]], + ) + : null, + }); + assert.ok(on('test-present')); + assert.deepEqual(seen, [true], 'on before the element is mounted'); + assert.ok(!on('test-lit')); + lit.value = true; + await settle(); + assert.ok(on('test-lit')); + key.value = 2; + await settle(); + assert.ok(on('test-present') && on('test-lit'), 'a keyed swap keeps both'); + lit.value = false; + await settle(); + assert.ok(!on('test-lit')); + shown.value = false; + await settle(); + assert.ok(!on('test-present') && !on('test-lit')); +}); + +test('the Omnibar holds has-omnibar, its results and focus inside it', async (t) => { + const { unmount } = mount(t, Omnibar); + await settle(); + assert.ok(on('has-omnibar')); + assert.ok(!on('omnibar-focus-within')); + const root = document.getElementById('gev-omnibar'); + // happy-dom does not track :focus-within; a browser answers it from focus. + root.matches = (selector) => + selector === ':focus-within' + ? root.contains(document.activeElement) + : Element.prototype.matches.call(root, selector); + const input = document.getElementById('gev-omnibar-input'); + input.focus(); + await settle(); + assert.ok(on('omnibar-focus-within')); + assert.equal( + on('omnibar-has-results'), + root.classList.contains('has-results'), + ); + const outside = document.body.appendChild(document.createElement('button')); + outside.focus(); + await settle(); + assert.ok(!on('omnibar-focus-within')); + assert.equal( + on('omnibar-has-results'), + root.classList.contains('has-results'), + ); + unmount(); + assert.ok(!on('has-omnibar') && !on('omnibar-has-results')); +}); + +test('the dock holds dock-has-voice and assistant-voice-mode with its voice control', async (t) => { + const { pinia, unmount } = mount(t, CommandDockView); + await settle(); + assertSameNode( + document.querySelector('#command-dock > #gev-voice-control'), + null, + ); + assert.ok(!on('dock-has-voice')); + const ui = createTestVoiceUi({ pinia }); + await settle(); + assert.ok(document.querySelector('#command-dock > #gev-voice-control')); + assert.ok(on('dock-has-voice')); + assert.ok(!on('assistant-voice-mode')); + ui.replace('root', { ...ui.state.root, assistantMode: 'voice' }); + await settle(); + assert.equal( + document.getElementById('gev-voice-control').dataset.assistantMode, + 'voice', + ); + assert.ok(on('assistant-voice-mode')); + ui.replace('root', { ...ui.state.root, assistantMode: 'chat' }); + await settle(); + assert.ok(!on('assistant-voice-mode')); + ui.replace('root', { ...ui.state.root, assistantMode: 'voice' }); + await settle(); + unmount(); + assert.ok(!on('dock-has-voice') && !on('assistant-voice-mode')); +}); + +test('the HUD holds hud-minimal-active only while the Minimal HUD is active', async (t) => { + const { pinia, unmount } = mount(t, IntelHudView); + const store = useHudStore(pinia); + const cases = [ + [{ active: false, variant: 'minimal' }, false], + [{ active: true, variant: 'tactical' }, false], + [{ active: true, variant: 'minimal' }, true], + [{ active: false, variant: 'minimal' }, false], + [{ active: true, variant: 'minimal' }, true], + ]; + for (const [hud, expected] of cases) { + store.publish({ vessel: {}, sensor: [], recShown: null, ...hud }); + await settle(); + const el = document.getElementById('intel-hud'); + assert.equal( + el.classList.contains('active') && el.dataset.variant === 'minimal', + expected, + ); + assert.equal(on('hud-minimal-active'), expected, JSON.stringify(hud)); + } + unmount(); + assert.ok(!on('hud-minimal-active')); +}); + +test('launcher-shown is on while the first-run launcher is on the page', async (t) => { + const { pinia } = mount(t, WelcomeView); + const store = useFirstRunStore(pinia); + await settle(); + assert.ok(document.getElementById('first-run-launcher')); + assert.ok(on('launcher-shown'), 'drawn hidden before it is presented'); + store.publish({ removed: false, shown: true, visible: true }); + await settle(); + assert.ok(on('launcher-shown')); + store.publish({ removed: true }); + await settle(); + assertSameNode(document.getElementById('first-run-launcher'), null); + assert.ok(!on('launcher-shown')); +}); + +test('a launcher removed outside the welcome view clears launcher-shown', async (t) => { + mount(t, WelcomeView); + await settle(); + assert.ok(on('launcher-shown')); + // As a page clearing the first-run dialog by hand does: `body:has()` stopped + // matching, so the class goes too. + document.getElementById('first-run-launcher').remove(); + await settle(); + assert.ok(!on('launcher-shown')); +}); + +test('the World Timeline holds has-world-timeline while it is drawn', async (t) => { + const { pinia } = mount(t, WorldTimeline); + t.after(() => { + useWorldTimeStore(pinia).$dispose(); + worldClock.goLive(); + worldClock.setRate(1); + }); + await settle(); + assertSameNode(document.getElementById('world-timeline'), null); + assert.ok(!on('has-world-timeline')); + const at = Date.now(); + const release = worldClock.hold('test-root-class'); + const unregister = worldClock.register({ + id: 'test-root-class', + coverage: () => ({ start: at - 3_600_000, end: at }), + }); + await settle(); + assert.ok(document.getElementById('world-timeline')); + assert.ok(on('has-world-timeline')); + unregister(); + release(); + await settle(); + assertSameNode(document.getElementById('world-timeline'), null); + assert.ok(!on('has-world-timeline')); +}); + +test('the language picker holds has-locale-picker while it is drawn', (t) => { + const { unmount } = mount(t, LocalePicker, { + current: 'en', + onSelect: () => {}, + }); + assert.ok(document.getElementById('locale-picker')); + assert.ok(on('has-locale-picker')); + unmount(); + assert.ok(!on('has-locale-picker')); +}); + +test('the panel stack holds left-panel-open while a panel directly in it is open', async (t) => { + const { unmount } = mount(t, LayerPanelsView); + await settle(); + const stack = document.getElementById('left-panel-stack'); + const open = () => + [...stack.children].some((child) => + child.matches('.panel-collapsible:not(.collapsed)'), + ); + const check = async (message) => { + await settle(); + assert.equal(on('left-panel-open'), open(), message); + }; + for (const panel of stack.querySelectorAll(':scope > .panel-collapsible')) + panel.classList.add('collapsed'); + await check('every panel closed'); + assert.ok(!on('left-panel-open')); + const data = document.getElementById('data-panel'); + data.classList.remove('collapsed'); + await check('a panel opened'); + assert.ok(on('left-panel-open')); + data.classList.add('collapsed'); + await check('closed again'); + // Panels move in and out of the stack at run time. + const moved = document.createElement('div'); + moved.className = 'panel-collapsible'; + stack.append(moved); + await check('an open panel moved in'); + assert.ok(on('left-panel-open')); + moved.classList.add('collapsed'); + await check('the moved panel closed'); + moved.classList.remove('collapsed'); + await check('and opened'); + document.body.append(moved); + await check('moved out again'); + assert.ok(!on('left-panel-open')); + // A deeper open panel is not one of the stack's own. + const nested = data.appendChild(document.createElement('div')); + nested.className = 'panel-collapsible'; + await check('a nested panel does not count'); + assert.ok(!on('left-panel-open')); + data.classList.remove('collapsed'); + await check('opened before the stack goes'); + unmount(); + assert.ok(!on('left-panel-open')); +}); + +test('Stories holds loading-screen-shown while the loading screen shows', async (t) => { + document.body.replaceChildren(); + const cover = document.body.appendChild(document.createElement('div')); + cover.id = 'loading-screen'; + const host = document.body.appendChild(document.createElement('div')); + const app = createApp(StoriesView).use(createPinia()); + app.mount(host); + t.after(() => localStorage.removeItem('gevStoriesPopSeen')); + await settle(); + assert.ok(on('loading-screen-shown')); + cover.classList.add('hidden'); + await settle(); + assert.ok(!on('loading-screen-shown')); + cover.classList.remove('hidden'); + await settle(); + assert.ok(on('loading-screen-shown')); + app.unmount(); + assert.ok(!on('loading-screen-shown')); + document.body.replaceChildren(); +}); + +test('Stories without a loading screen holds no class', async (t) => { + document.body.replaceChildren(); + const host = document.body.appendChild(document.createElement('div')); + const app = createApp(StoriesView).use(createPinia()); + app.mount(host); + t.after(() => { + app.unmount(); + localStorage.removeItem('gevStoriesPopSeen'); + }); + await settle(); + assert.ok(!on('loading-screen-shown')); +}); + +/** Whether `body:has(#loading-screen:not(.hidden))` holds. */ +const loadingShown = () => + Boolean(document.body.querySelector('#loading-screen:not(.hidden)')); + +test('Stories follows a loading screen removed, added later, nested or renamed', async (t) => { + document.body.replaceChildren(); + const cover = document.body.appendChild(document.createElement('div')); + cover.id = 'loading-screen'; + const host = document.body.appendChild(document.createElement('div')); + const app = createApp(StoriesView).use(createPinia()); + app.mount(host); + t.after(() => { + app.unmount(); + localStorage.removeItem('gevStoriesPopSeen'); + document.body.replaceChildren(); + }); + const agree = async (message) => { + await settle(); + assert.equal(on('loading-screen-shown'), loadingShown(), message); + }; + await agree('shown'); + assert.ok(on('loading-screen-shown')); + cover.remove(); + await agree('a shown loading screen removed'); + assert.ok(!on('loading-screen-shown')); + const wrap = document.body.appendChild(document.createElement('section')); + const late = document.createElement('div'); + late.id = 'loading-screen'; + late.className = 'hidden'; + wrap.append(late); + await agree('a hidden one added later, inside another element'); + late.classList.remove('hidden'); + await agree('the later one shown'); + assert.ok(on('loading-screen-shown')); + late.id = 'cover'; + await agree('renamed away'); + late.id = 'loading-screen'; + await agree('renamed back'); + const second = document.body.appendChild(document.createElement('div')); + second.id = 'loading-screen'; + second.className = 'hidden'; + late.classList.add('hidden'); + await agree('two, both hidden'); + second.classList.remove('hidden'); + await agree('the second one shown'); + assert.ok(on('loading-screen-shown')); + wrap.remove(); + second.remove(); + await agree('both gone'); + assert.ok(!on('loading-screen-shown')); +}); + +test('Stories mounted before the loading screen follows it once it is added', async (t) => { + document.body.replaceChildren(); + const host = document.body.appendChild(document.createElement('div')); + const app = createApp(StoriesView).use(createPinia()); + app.mount(host); + t.after(() => { + app.unmount(); + localStorage.removeItem('gevStoriesPopSeen'); + document.body.replaceChildren(); + }); + await settle(); + assert.ok(!on('loading-screen-shown')); + const cover = document.body.appendChild(document.createElement('div')); + cover.id = 'loading-screen'; + await settle(); + assert.ok(on('loading-screen-shown')); + cover.classList.add('hidden'); + await settle(); + assert.ok(!on('loading-screen-shown')); +}); + +// ── The stylesheets ───────────────────────────────────────────────────────── + +const STYLESHEETS = [ + 'style.css', + ...fs + .readdirSync(path.join(ROOT, 'src/ui/styles')) + .filter((name) => name.endsWith('.css')) + .map((name) => `src/ui/styles/${name}`), +]; +const SFC_STYLES = fs + .readdirSync(path.join(ROOT, 'src/ui/views/panels')) + .filter((name) => name.endsWith('.vue')) + .map((name) => `src/ui/views/panels/${name}`); + +/** Every selector of `css`, comments removed and whitespace collapsed. */ +function selectors(css) { + const out = []; + for (const match of css + .replace(/\/\*[\s\S]*?\*\//g, '') + .matchAll(/([^{};]+)\{/g)) { + const text = match[1].replace(/\s+/g, ' ').trim(); + if (text && !text.startsWith('@')) out.push(text); + } + return out; +} + +// The class each state stands for, and the condition it replaced. +const ROOT_CLASSES = Object.freeze({ + 'hud-minimal-active': "#intel-hud[data-variant='minimal'].active", + 'omnibar-focus-within': '#gev-omnibar:focus-within', + 'omnibar-has-results': '#gev-omnibar.has-results', + 'assistant-voice-mode': "#gev-voice-control[data-assistant-mode='voice']", + 'left-panel-open': '#left-panel-stack > .panel-collapsible:not(.collapsed)', + 'launcher-shown': '#first-run-launcher', + 'loading-screen-shown': '#loading-screen:not(.hidden)', + 'has-world-timeline': '#world-timeline', + 'has-locale-picker': '#locale-picker', + 'has-omnibar': '#gev-omnibar', +}); + +/** The compound selectors of `selector`, split at combinators and commas outside parentheses. */ +function compounds(selector) { + const out = ['']; + let depth = 0; + for (const char of selector) { + if (char === '(' || char === '[') depth += 1; + if (char === ')' || char === ']') depth -= 1; + if (depth === 0 && /[\s>+~,]/.test(char)) { + if (out[out.length - 1]) out.push(''); + } else out[out.length - 1] += char; + } + return out.filter(Boolean); +} + +/** + * The `[class, condition]` of every `:is(.class *, condition)` and + * `:not(.class *, condition)` in `selector`. + */ +function rootClassArguments(selector) { + const out = []; + for (const match of selector.matchAll(/:(?:is|not)\(/g)) { + let depth = 0; + let end = -1; + const args = ['']; + for ( + let i = match.index + match[0].length - 1; + i < selector.length; + i += 1 + ) { + const char = selector[i]; + if (char === '(') depth += 1; + if (char === ')') depth -= 1; + if (depth === 0) { + end = i; + break; + } + if (char === ',' && depth === 1) args.push(''); + else if (!(char === '(' && depth === 1)) args[args.length - 1] += char; + } + assert.ok(end > 0, `unbalanced: ${selector}`); + const name = args[0].trim().match(/^\.([\w-]+) \*$/)?.[1]; + if (name) { + assert.equal(args.length, 2, selector); + out.push([name, args[1].trim()]); + } + } + return out; +} + +test('no rule hangs a :has() on body, and every root class keeps its weight', () => { + const seen = new Set(); + for (const file of [...STYLESHEETS, ...SFC_STYLES]) { + const css = fs.readFileSync(path.join(ROOT, file), 'utf8'); + for (const selector of selectors(css)) { + // A :has() on the page's root, its body, or a rule nested in one. + for (const compound of compounds(selector)) + assert.ok( + !/^(body|html|:root|&)(?![\w-])/.test(compound) || + !compound.includes(':has('), + `${file}: ${selector}`, + ); + // A root class is selected with the condition it stands for beside + // it, which never matches body and keeps the rule's specificity. + for (const [name, condition] of rootClassArguments(selector)) { + assert.ok( + Object.hasOwn(ROOT_CLASSES, name), + `${file}: unknown class .${name}`, + ); + assert.equal(condition, ROOT_CLASSES[name], `${file}: ${selector}`); + seen.add(name); + } + } + } + assert.deepEqual( + [...seen].sort(), + Object.keys(ROOT_CLASSES).sort(), + 'every root class is selected somewhere', + ); +}); diff --git a/src/ui/rail/rootClass.js b/src/ui/rail/rootClass.js new file mode 100644 index 0000000000..9459c2e354 --- /dev/null +++ b/src/ui/rail/rootClass.js @@ -0,0 +1,161 @@ +/** + * Classes on the page's root element (``) that say what is on the page: + * the Omnibar is shown, the voice control sits in the dock, a layer has a + * World Timeline. A stylesheet selects on that state through them instead of + * `body:has(...)`: Chrome checks a `:has()` on body again after every node + * added or removed anywhere on the page, and restyles the whole page when it + * does, while a class changes only when the state it names does. + * + * A rule selects such a class as `body:is(.has-omnibar *, #gev-omnibar)`. + * The first argument holds when body is inside the class's element; the + * second never matches body and gives the rule the specificity the + * `:has(#gev-omnibar)` it replaced had, so the rule keeps its place in the + * cascade. + * + * The classes live on `` rather than ``, whose class changes + * several owners already follow to lay the page out again. + * + * Several holders can share a class; it stays on until the last lets go. + */ + +/** @type {WeakMap