From 1f105a68afeb9ef633b0ce25259f2af61420ce08 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Mon, 23 Nov 2026 08:06:48 -0800 Subject: [PATCH] Page state is kept in classes on the page root; the HUD rests while not displayed (#1911) * Page state is kept in classes on the page root; the HUD rests while not displayed Rules that selected on `body:has(...)` now select on classes on that the components owning that state hold, as `body:is(.flag *, )`, which keeps each rule's specificity and so its place in the cascade. Chrome checks a `:has()` on body again after every node added or removed anywhere, and restyles the whole page when it does; a class changes only when its state does. The Intel HUD does no readout work and writes nothing while #intel-hud is not displayed, and shows current readouts as soon as it is displayed again. Its changing readouts update their text nodes in place. * The HUD runs no timers while not displayed; the loading screen is followed wherever it comes and goes While #intel-hud is not displayed the Intel HUD stops its timers and any reply typing out, drops a summary it was working out (asked again when it is back) and publishes only its own active, variant and colors, which stylesheets and layout elsewhere read. The vessel and language readouts wait too. Displayed again, it starts its timers and shows current readouts, and the whole reply, at once. A view that is unmounted leaves the HUD at rest until a mounted view reports it displayed. The loading-screen class now follows #loading-screen being added, removed, renamed or shown anywhere in body, as body:has() did, not only its class. * Changelog fragment for #1911 * The first-run launcher's page class follows the element, and is named launcher-shown A page that clears the first-run dialog by removing every element whose class contains first-run removed itself once it carried has-first-run-launcher. The class is now launcher-shown, and it follows #first-run-launcher wherever it comes and goes, so a launcher removed by anything clears it, as body:has(#first-run-launcher) did. --- changelog.d/1911-page-root-classes.md | 4 + docs/CURRENT-STATE.md | 7 +- docs/VUE-MIGRATION.md | 29 +- scripts/format-scope.json | 1 + scripts/package-boundaries.json | 3 + src/creditAttribution.test.mjs | 12 +- src/firstRunExperience.test.mjs | 2 +- src/hud.js | 162 ++++++-- src/ui/applicationShell.js | 3 + src/ui/hudSonarStyle.test.mjs | 8 +- src/ui/pageRootClasses.test.mjs | 517 ++++++++++++++++++++++++++ src/ui/rail/rootClass.js | 161 ++++++++ src/ui/rail/textData.js | 16 + src/ui/stores/hud.js | 34 +- src/ui/styles/cockpit.css | 7 +- src/ui/styles/command-dock-trays.css | 30 +- src/ui/styles/command-dock.css | 7 +- src/ui/styles/context-dock.css | 15 +- src/ui/styles/first-run.css | 5 +- src/ui/styles/omnibar-dock.css | 29 +- src/ui/styles/stories-entry.css | 9 +- src/ui/styles/world-timeline.css | 7 +- src/ui/views/CommandDockView.vue | 4 +- src/ui/views/IntelHudView.vue | 58 ++- src/ui/views/LayerPanelsView.vue | 28 +- src/ui/views/StoriesView.vue | 13 + src/ui/views/WelcomeView.vue | 17 +- src/ui/views/intelHudView.test.mjs | 324 +++++++++++++++- src/ui/views/panels/LocalePicker.vue | 3 +- src/ui/views/panels/Omnibar.vue | 29 +- src/ui/views/panels/WorldTimeline.vue | 3 +- 31 files changed, 1445 insertions(+), 102 deletions(-) create mode 100644 changelog.d/1911-page-root-classes.md create mode 100644 src/ui/pageRootClasses.test.mjs create mode 100644 src/ui/rail/rootClass.js create mode 100644 src/ui/rail/textData.js 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>} */ +const holders = new WeakMap(); + +/** + * Put `name` on `doc`'s root element until the returned release is called. + * @param {Document | null | undefined} doc + * @param {string} name + * @returns {() => void} Lets go of the class; later calls do nothing. + */ +export function holdRootClass(doc, name) { + const root = doc?.documentElement; + if (!root) return () => {}; + let counts = holders.get(doc); + if (!counts) holders.set(doc, (counts = new Map())); + const count = counts.get(name) ?? 0; + counts.set(name, count + 1); + if (count === 0) root.classList.add(name); + let held = true; + return () => { + if (!held) return; + held = false; + const left = (counts.get(name) ?? 1) - 1; + if (left > 0) { + counts.set(name, left); + return; + } + counts.delete(name); + doc.documentElement?.classList.remove(name); + }; +} + +/** + * Hold `name` on `doc`'s root element while `set(true)` was the last call. + * @param {Document | null | undefined} doc + * @param {string} name + * @returns {{set: (on: boolean) => void, release: () => void}} + */ +export function rootClassSwitch(doc, name) { + let release = null; + const set = (on) => { + if (on && !release) release = holdRootClass(doc, name); + else if (!on && release) { + release(); + release = null; + } + }; + return { set, release: () => set(false) }; +} + +/** Hold each class of `value` (`{name: on}`) that is on; let go of the rest. */ +function apply(el, value) { + const switches = (el._rootClasses ??= new Map()); + for (const [name, on] of Object.entries(value || {})) { + let entry = switches.get(name); + if (!entry) + switches.set(name, (entry = rootClassSwitch(el.ownerDocument, name))); + entry.set(Boolean(on)); + } + for (const [name, entry] of switches) + if (!value || !Object.hasOwn(value, name)) entry.set(false); +} + +/** + * `v-root-class="{ 'has-omnibar': true }"`: holds each named class on the + * root element while the element is on the page and the class's value is + * truthy. One per element. The hooks run inside Vue's patch, just before the + * element is inserted, patched or removed, so the classes change with the + * element itself: code that reads layout after the patch sees both. + */ +export const vRootClass = { + beforeMount(el, { value }) { + apply(el, value); + }, + beforeUpdate(el, { value }) { + apply(el, value); + }, + beforeUnmount(el) { + for (const entry of el._rootClasses?.values() ?? []) entry.release(); + el._rootClasses?.clear(); + }, +}; + +/** + * Hold `name` on `doc`'s root element while `test()` holds, testing again + * after every change a MutationObserver reports. `observe(observer)` points + * the observer at what to follow; it is called again after every change, so + * it can follow nodes that come and go. + * @param {Document} doc + * @param {string} name + * @param {() => boolean} test + * @param {(observer: MutationObserver) => void} observe + * @returns {() => void} Stops following and lets go of the class. + */ +export function followRootClass(doc, name, test, observe) { + const entry = rootClassSwitch(doc, name); + const Observer = doc?.defaultView?.MutationObserver; + const observer = + Observer && + new Observer(() => { + observer.disconnect(); + observe(observer); + entry.set(Boolean(test())); + }); + if (observer) observe(observer); + entry.set(Boolean(test())); + return () => { + observer?.disconnect(); + entry.release(); + }; +} + +/** + * Hold `name` on `doc`'s root element while an element in body matches + * `selector`, as `body:has(selector)` would: elements that match coming and + * going anywhere in body, and the class attribute of each element matching + * `watched` (the elements whose classes `selector` tests), are followed. + * @param {Document} doc + * @param {string} name + * @param {string} selector + * @param {string} watched + * @returns {() => void} Stops following and lets go of the class. + */ +export function followSelectorRootClass(doc, name, selector, watched) { + return followRootClass( + doc, + name, + () => Boolean(doc.body?.querySelector(selector)), + (observer) => { + const body = doc.body; + if (!body) return; + observer.observe(body, { + childList: true, + subtree: true, + attributes: true, + attributeFilter: ['id'], + }); + for (const el of body.querySelectorAll(watched)) + observer.observe(el, { attributes: true, attributeFilter: ['class'] }); + }, + ); +} diff --git a/src/ui/rail/textData.js b/src/ui/rail/textData.js new file mode 100644 index 0000000000..4006b8cf69 --- /dev/null +++ b/src/ui/rail/textData.js @@ -0,0 +1,16 @@ +/** + * `v-text-data="text"`: the element's text, written into its one text node. + * A `{{ }}` that is an element's only child is written with `textContent`, + * which replaces the text node on every change; a readout that changes many + * times a second keeps its node and changes only the node's data. + */ +function write(el, { value }) { + const text = value == null ? '' : String(value); + const node = el.firstChild; + // An empty readout has no text node, as `textContent = ''` leaves it. + if (text && node && node.nodeType === 3 && !node.nextSibling) { + if (node.data !== text) node.data = text; + } else if (el.textContent !== text) el.textContent = text; +} + +export const vTextData = { mounted: write, updated: write }; diff --git a/src/ui/stores/hud.js b/src/ui/stores/hud.js index 9b14c49a86..91079af06b 100644 --- a/src/ui/stores/hud.js +++ b/src/ui/stores/hud.js @@ -1,10 +1,11 @@ import { defineStore } from 'pinia'; -import { shallowRef } from 'vue'; +import { markRaw, shallowRef } from 'vue'; /** * The Intel HUD as its view renders it. IntelHUD presents its readouts, * visibility, layout variant and style colors and the application shell - * publishes them here. + * publishes them here. The view reports whether it is on screen, and the + * store passes that to the connected IntelHUD. */ export const useHudStore = defineStore('gev-hud', () => { /** The presented HUD, frozen by IntelHUD; null until it is built. */ @@ -15,5 +16,32 @@ export const useHudStore = defineStore('gev-hud', () => { hud.value = next; } - return { hud, publish }; + /** + * Whether the view is on screen: false while a stylesheet gives + * `#intel-hud` or a parent `display: none`, and once the view is + * unmounted. True until a view first says. + */ + const displayed = shallowRef(true); + + /** The IntelHUD told when `displayed` changes, or null. */ + const owner = shallowRef(null); + + /** @param {boolean} next Whether the view is on screen. */ + function setDisplayed(next) { + if (displayed.value === next) return; + displayed.value = next; + owner.value?.setDisplayed(next); + } + + /** + * Tell `next` whether the view is on screen, now and on every change. + * @param {?{setDisplayed: (displayed: boolean) => void}} next IntelHUD, or + * null to disconnect. + */ + function connect(next) { + owner.value = next && markRaw(next); + next?.setDisplayed(displayed.value); + } + + return { hud, publish, displayed, setDisplayed, owner, connect }; }); diff --git a/src/ui/styles/cockpit.css b/src/ui/styles/cockpit.css index b644526966..7d0f66e9a4 100644 --- a/src/ui/styles/cockpit.css +++ b/src/ui/styles/cockpit.css @@ -164,7 +164,12 @@ text-align: left; transform: rotateY(-24deg) translateZ(-18px); } -body.cockpit-mode:has(#left-panel-stack > .panel-collapsible:not(.collapsed)) +/* `.left-panel-open`: a panel in the left stack is open, a page-root class + (src/ui/rail/rootClass.js). */ +body.cockpit-mode:is( + .left-panel-open *, + #left-panel-stack > .panel-collapsible:not(.collapsed) + ) .cockpit-pitch-rail-left { opacity: 0; transition: opacity 0.25s; diff --git a/src/ui/styles/command-dock-trays.css b/src/ui/styles/command-dock-trays.css index 850f7f4e12..510b03f433 100644 --- a/src/ui/styles/command-dock-trays.css +++ b/src/ui/styles/command-dock-trays.css @@ -452,9 +452,11 @@ baseline, below the raised command dock (command-dock.css). It stops 26rem short of the right edge, clear of the corner row (Power Up and the language picker), and wraps rather than running under it. Below 1200px the dock - keeps to the bottom edge and the row sits above it. */ + keeps to the bottom edge and the row sits above it. `.hud-minimal-active` + and the Omnibar layout's classes are page-root classes (src/ui/rail/rootClass.js). */ body:not(.ui-clean-view):not(.recording-mode) #cesium-credits, -body:not(.ui-clean-view):not(.recording-mode):has( +body:not(.ui-clean-view):not(.recording-mode):is( + .hud-minimal-active *, #intel-hud[data-variant='minimal'].active ) #cesium-credits { @@ -467,7 +469,8 @@ body:not(.ui-clean-view):not(.recording-mode):has( } body:not(.ui-clean-view):not(.recording-mode) #gev-credits, -body:not(.ui-clean-view):not(.recording-mode):has( +body:not(.ui-clean-view):not(.recording-mode):is( + .hud-minimal-active *, #intel-hud[data-variant='minimal'].active ) #gev-credits { @@ -512,12 +515,14 @@ body:not(.ui-clean-view):not(.recording-mode):has( @media (max-width: 1199px) { body:not(.ui-clean-view):not(.recording-mode) #cesium-credits, - body:not(.ui-clean-view):not(.recording-mode):has( + body:not(.ui-clean-view):not(.recording-mode):is( + .hud-minimal-active *, #intel-hud[data-variant='minimal'].active ) #cesium-credits, body:not(.ui-clean-view):not(.recording-mode) #gev-credits, - body:not(.ui-clean-view):not(.recording-mode):has( + body:not(.ui-clean-view):not(.recording-mode):is( + .hud-minimal-active *, #intel-hud[data-variant='minimal'].active ) #gev-credits { @@ -534,9 +539,7 @@ body:not(.ui-clean-view):not(.recording-mode):has( shares the bottom edge with the corner row (omnibar-dock.css). */ 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) - ) + ):not(.recording-mode):where(.has-omnibar.dock-has-voice *) #cesium-credits .cesium-widget-credits { width: max-content; @@ -550,7 +553,7 @@ html[dir='rtl'] body:not(.mobile-shell):not(.cockpit-mode):not(.scene-playback-mode):not( .ui-clean-view ):not(.recording-mode):not(.context-docked):where( - :has(#gev-omnibar):has(#command-dock > #gev-voice-control) + .has-omnibar.dock-has-voice * ) #cesium-credits .cesium-widget-credits { @@ -574,7 +577,8 @@ html[dir='rtl'] body:not(.context-docked):not(.ui-clean-view):not(.recording-mode) :is(#cesium-credits, #gev-credits), html[dir='rtl'] - body:not(.context-docked):not(.ui-clean-view):not(.recording-mode):has( + body:not(.context-docked):not(.ui-clean-view):not(.recording-mode):is( + .hud-minimal-active *, #intel-hud[data-variant='minimal'].active ) :is(#cesium-credits, #gev-credits) { @@ -594,7 +598,8 @@ html[dir='rtl'] @media (max-width: 900px) { body:not(.ui-clean-view):not(.recording-mode) #cesium-credits, - body:not(.ui-clean-view):not(.recording-mode):has( + body:not(.ui-clean-view):not(.recording-mode):is( + .hud-minimal-active *, #intel-hud[data-variant='minimal'].active ) #cesium-credits { @@ -604,7 +609,8 @@ html[dir='rtl'] } body:not(.ui-clean-view):not(.recording-mode) #gev-credits, - body:not(.ui-clean-view):not(.recording-mode):has( + body:not(.ui-clean-view):not(.recording-mode):is( + .hud-minimal-active *, #intel-hud[data-variant='minimal'].active ) #gev-credits { diff --git a/src/ui/styles/command-dock.css b/src/ui/styles/command-dock.css index 5a9b90aa27..2c294877c3 100644 --- a/src/ui/styles/command-dock.css +++ b/src/ui/styles/command-dock.css @@ -225,7 +225,9 @@ body:not(.ui-clean-view):not(.recording-mode) #gev-credits { bottom: calc(2vh + 7rem + var(--world-timeline-lift, 0px)); } -body:not(.ui-clean-view):not(.recording-mode):has( +/* `.hud-minimal-active`: the Minimal HUD is showing, one of the page-root classes of src/ui/rail/rootClass.js. */ +body:not(.ui-clean-view):not(.recording-mode):is( + .hud-minimal-active *, #intel-hud[data-variant='minimal'].active ) #cesium-credits { @@ -235,7 +237,8 @@ body:not(.ui-clean-view):not(.recording-mode):has( text-align: right; } -body:not(.ui-clean-view):not(.recording-mode):has( +body:not(.ui-clean-view):not(.recording-mode):is( + .hud-minimal-active *, #intel-hud[data-variant='minimal'].active ) #gev-credits { diff --git a/src/ui/styles/context-dock.css b/src/ui/styles/context-dock.css index 9d071598b5..deeac24da5 100644 --- a/src/ui/styles/context-dock.css +++ b/src/ui/styles/context-dock.css @@ -17,14 +17,17 @@ body.context-docked #right-context-rail { } /* The map credits stay readable beside the column: their row ends short of - it. creditAttribution.test.mjs pins this. */ + it. creditAttribution.test.mjs pins this. `.hud-minimal-active` is a + page-root class (src/ui/rail/rootClass.js). */ body.context-docked:not(.ui-clean-view):not(.recording-mode) #cesium-credits, body.context-docked:not(.ui-clean-view):not(.recording-mode) #gev-credits, -body.context-docked:not(.ui-clean-view):not(.recording-mode):has( +body.context-docked:not(.ui-clean-view):not(.recording-mode):is( + .hud-minimal-active *, #intel-hud[data-variant='minimal'].active ) #cesium-credits, -body.context-docked:not(.ui-clean-view):not(.recording-mode):has( +body.context-docked:not(.ui-clean-view):not(.recording-mode):is( + .hud-minimal-active *, #intel-hud[data-variant='minimal'].active ) #gev-credits { @@ -197,7 +200,8 @@ body.mobile-shell .context-dock-btn { /* With the minimal HUD the credits sit at the bottom right, where the column is: they move out to its left. */ -body.context-docked:not(.ui-clean-view):not(.recording-mode):has( +body.context-docked:not(.ui-clean-view):not(.recording-mode):is( + .hud-minimal-active *, #intel-hud[data-variant='minimal'].active ) :is(#cesium-credits, #gev-credits) { @@ -213,7 +217,8 @@ html[dir='rtl'] } html[dir='rtl'] - body.context-docked:not(.ui-clean-view):not(.recording-mode):has( + body.context-docked:not(.ui-clean-view):not(.recording-mode):is( + .hud-minimal-active *, #intel-hud[data-variant='minimal'].active ) :is(#cesium-credits, #gev-credits) { diff --git a/src/ui/styles/first-run.css b/src/ui/styles/first-run.css index 8c594cfa0c..2c12437ae2 100644 --- a/src/ui/styles/first-run.css +++ b/src/ui/styles/first-run.css @@ -1869,8 +1869,9 @@ body:not(.mobile-shell) #first-run-launcher.visible { /* The Stories announcement waits behind onboarding without consuming its unseen state: from startup while the card is pending, through its reveal, until it is removed (not shown this session, or dismissed). It also stays - hidden while BROWSE STORIES is loading Stories. */ -body:has(#first-run-launcher) #gev-stories #hPop, + hidden while BROWSE STORIES is loading Stories. `.launcher-shown` + is a page-root class (src/ui/rail/rootClass.js). */ +body:is(.launcher-shown *, #first-run-launcher) #gev-stories #hPop, body.first-run-opening-stories #gev-stories #hPop { visibility: hidden; pointer-events: none; diff --git a/src/ui/styles/omnibar-dock.css b/src/ui/styles/omnibar-dock.css index d4a61bc514..738af744ab 100644 --- a/src/ui/styles/omnibar-dock.css +++ b/src/ui/styles/omnibar-dock.css @@ -1,9 +1,9 @@ -/* Shared desktop command surface. Mobile and exclusive owners keep their layout. */ +/* Shared desktop command surface. Mobile and exclusive owners keep their layout. + It applies while the Omnibar is on the page and the voice control is in the + dock; that state, and the states its rules select on below, are the page-root classes of src/ui/rail/rootClass.js. */ 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) - ) { + ):not(.recording-mode):where(.has-omnibar.dock-has-voice *) { --omnibar-dock-width: clamp(400px, 32vw, 460px); /* Clear of the attribution line under it, however many lines it wraps onto (--credit-line-height, src/ui/creditLineHeight.js). */ @@ -89,7 +89,9 @@ body:not(.mobile-shell):not(.cockpit-mode):not(.scene-playback-mode):not( 0 12px 32px rgba(0, 0, 0, 0.45); backdrop-filter: none; } - &:has(#gev-omnibar:focus-within) #command-dock > #gev-voice-control { + &:is(.omnibar-focus-within *, #gev-omnibar:focus-within) + #command-dock + > #gev-voice-control { border-color: rgba(54, 220, 255, 0.5); box-shadow: 0 12px 32px rgba(0, 0, 0, 0.45), @@ -252,8 +254,9 @@ body:not(.mobile-shell):not(.cockpit-mode):not(.scene-playback-mode):not( -webkit-backdrop-filter: blur(26px) saturate(1.2); box-shadow: 0 14px 32px rgba(0, 0, 0, 0.45); } - &:has(#gev-omnibar.has-results):not( - :has(#gev-voice-control[data-assistant-mode='voice']) + &:is(.omnibar-has-results *, #gev-omnibar.has-results):not( + .assistant-voice-mode *, + #gev-voice-control[data-assistant-mode='voice'] ) #command-dock > #gev-voice-control { @@ -308,7 +311,8 @@ body:not(.mobile-shell):not(.cockpit-mode):not(.scene-playback-mode):not( stroke-width: 1; opacity: 0.6; } - &:has(#gev-voice-control[data-assistant-mode='voice']) #gev-omnibar { + &:is(.assistant-voice-mode *, #gev-voice-control[data-assistant-mode='voice']) + #gev-omnibar { .omnibar-field { background: transparent; } @@ -336,7 +340,7 @@ body:not(.mobile-shell):not(.cockpit-mode):not(.scene-playback-mode):not( rather than running under the corner row (Power Up and the language picker), whose side it stays clear of. */ :is(#cesium-credits, #gev-credits), - &:has(#intel-hud[data-variant='minimal'].active) + &:is(.hud-minimal-active *, #intel-hud[data-variant='minimal'].active) :is(#cesium-credits, #gev-credits) { bottom: 1rem; } @@ -349,7 +353,7 @@ body:not(.mobile-shell):not(.cockpit-mode):not(.scene-playback-mode):not( the bottom right at every width. Expanded Context places it itself. */ &:where(html[dir='rtl'] *):not(.context-docked) { :is(#cesium-credits, #gev-credits), - &:has(#intel-hud[data-variant='minimal'].active) + &:is(.hud-minimal-active *, #intel-hud[data-variant='minimal'].active) :is(#cesium-credits, #gev-credits) { right: 1.5rem; left: auto; @@ -386,7 +390,10 @@ body:not(.mobile-shell):not(.cockpit-mode):not(.scene-playback-mode):not( .hud-bottom-left { bottom: var(--omnibar-coordinates-bottom); } - &:not(.context-docked):has(#intel-hud[data-variant='minimal'].active) + &:not(.context-docked):is( + .hud-minimal-active *, + #intel-hud[data-variant='minimal'].active + ) #right-context-rail { --omnibar-minimal-rail-height: min( var(--right-stack-max-height, 70vh), diff --git a/src/ui/styles/stories-entry.css b/src/ui/styles/stories-entry.css index 870cb66e75..37db660a49 100644 --- a/src/ui/styles/stories-entry.css +++ b/src/ui/styles/stories-entry.css @@ -188,8 +188,13 @@ width: 17px; height: 17px; } -body:has(#loading-screen:not(.hidden)) #gev-stories .gs-entry, -body:has(#loading-screen:not(.hidden)) #gev-stories .gs-pop, +/* `.loading-screen-shown` is a page-root class (src/ui/rail/rootClass.js). */ +body:is(.loading-screen-shown *, #loading-screen:not(.hidden)) + #gev-stories + .gs-entry, +body:is(.loading-screen-shown *, #loading-screen:not(.hidden)) + #gev-stories + .gs-pop, body.recording-mode #gev-stories .gs-entry, body.recording-mode #gev-stories .gs-pop, body.ui-clean-view #gev-stories .gs-entry, diff --git a/src/ui/styles/world-timeline.css b/src/ui/styles/world-timeline.css index 4da98a14ed..7ce072ce15 100644 --- a/src/ui/styles/world-timeline.css +++ b/src/ui/styles/world-timeline.css @@ -5,8 +5,9 @@ --world-timeline-lift: 0px; } -/* The bar and the time's bubble over its handle. */ -body:has(#world-timeline) { +/* The bar and the time's bubble over its handle. `.has-world-timeline` is a + page-root class (src/ui/rail/rootClass.js). */ +body:is(.has-world-timeline *, #world-timeline) { --world-timeline-lift: 66px; } @@ -324,7 +325,7 @@ body.cockpit-mode #world-timeline { /* On phones the bar sits just above the tab bar, under the voice dock, with the track and the speed on a row of their own beneath play and live. */ -body.mobile-shell:has(#world-timeline) { +body.mobile-shell:is(.has-world-timeline *, #world-timeline) { --world-timeline-lift: 80px; } diff --git a/src/ui/views/CommandDockView.vue b/src/ui/views/CommandDockView.vue index c1fd96c3a9..cd02d16c53 100644 --- a/src/ui/views/CommandDockView.vue +++ b/src/ui/views/CommandDockView.vue @@ -4,6 +4,7 @@ import { msg, t } from '../../i18n/index.js'; import { vPanelState } from '../rail/panelState.js'; import UiButton from '../kit/UiButton.vue'; import { vClassToggle } from '../rail/classToggle.js'; +import { vRootClass } from '../rail/rootClass.js'; import { useDisplayStore } from '../stores/display.js'; import { computed } from 'vue'; import { useLocationStore } from '../stores/location.js'; @@ -127,7 +128,8 @@ function selectMapSource(chip) { - + +