Start the application through the contract, not on the Cesium viewer

The application scene takes a renderer plugin and no longer refuses one
without a Cesium viewer. It loads the default (Cesium) plugin only when it
is given none, so a page on the stub never loads Cesium.

- Every layer and tool is handed the application's own scene object
  (createSceneHost): the container and isDestroyed(), bound to the
  renderer, the same on Cesium and the stub.
- What only Cesium needs at startup is done in its plugin's create: the
  free-look height limit, and keyboard access to its credits' expand link
  (creditKeyboard.js moves into the adapter).
- What a plugin may hand the application beside the contract goes through
  provideApplicationHooks, each hook optional: Cesium's map engine, stale
  command trimming, inline panel rendering, viewerDrawsEntity, the zoom-out
  guard, and the viewer QA scripts read from window.__godsEyeView.
- The map stacks, and the photoreal base the scene loads, switch through
  the renderer's own map engine (mapEngineFor), else its globe port
  (globeEngine.js). The Cesium engine takes the scene object and changes
  the viewer behind it.
This commit is contained in:
Sameh Khamis committed 2026-11-10 17:18:48 -08:00
1 parent a72d4c3b1f
commit 6daf63d90c
24 files changed
+825 -241

No files matched your search

+43
View File
@@ -0,0 +1,43 @@
/**
* @module render/applicationHooks
* @description What a renderer's plugin may hand the application beside the
* contract: behaviour the application uses where a renderer has it, and does
* without where it has none. Nothing here is part of the renderer contract,
* and the application never asks which renderer it runs on: it reads the
* hooks of the renderer it was given, each of them optional.
*
* - `mapEngine`: the renderer's own map engine (`src/maps/engine.js`), which
* the map stacks switch through in place of the globe port
* (`src/maps/globeEngine.js`).
* - `trimStaleCommands()`: drops the draw commands a renderer keeps for a
* while after it stops drawing them; run after a layer turns off.
* - `keepPanelRendering(options)`: keeps the globe drawing in an inline panel
* whose host stops animation frames (embed mode); returns its disposer.
* - `viewerDrawsEntity(entity)`: whether an entity is one the renderer draws
* itself (Cockpit asks whether the aircraft it flies still draws).
* - `installZoomOutGuard(options)`: keeps outward user zooms bounded and the
* Earth framed; returns its disposer.
* - `qaHandles`: values QA scripts read from `window.__godsEyeView`.
*/
const hooks = new WeakMap();
const NONE = Object.freeze({});
/**
* Hand the application `value`'s hooks for `renderer`. A renderer's plugin
* calls it as it creates the renderer; a later call replaces them.
* @param {object} renderer
* @param {object} value
*/
export function provideApplicationHooks(renderer, value) {
hooks.set(renderer, Object.freeze({ ...value }));
}
/**
* The hooks `renderer`'s plugin provided; an empty object when it provided
* none, or `renderer` is not an object.
* @param {object|null|undefined} renderer
* @returns {Readonly<object>}
*/
export const applicationHooksOf = (renderer) =>
(renderer && hooks.get(renderer)) || NONE;
+60 -21
View File
@@ -8,27 +8,41 @@
* ports (`ports.js`), the ones the conformance renderer is checked with,
* and it has every member of the contract. The application's base (the
* photoreal tiles, the map stack's imagery and terrain) is still loaded
* through the viewer by the scene and the map stack; the globe port drapes
* its imagery on that base as drawn (see `globe.js`). `whenSettled` waits
* for the globe, the scene's 3D tiles and what the draw sets hold, not for
* what layers still draw through the viewer themselves.
* Until a family is ported, its code reaches the Cesium viewer through
* `cesiumViewerOf`, never through a renderer member, so no engine type
* crosses the contract and each call marks code still to port. Ported code
* that still holds the viewer reaches the renderer through `rendererOf`.
* through the Cesium map engine (`mapEngine.js`), which the plugin hands
* the application with the renderer (`../applicationHooks.js`); the globe
* port drapes its imagery on that base as drawn (see `globe.js`).
* `whenSettled` waits for the globe, the scene's 3D tiles and what the draw
* sets hold.
*
* What only this renderer needs at startup is set up here: the free-look
* height limit, keyboard access to the credits' expand link (in the page's
* language), and the hooks the application uses where a renderer has
* them (stale command trimming, inline panel rendering, whether an entity
* is the viewer's own, the zoom-out guard, the viewer QA scripts read).
* Adapter code reaches the viewer behind a renderer through
* `cesiumViewerOf` (`viewers.js`), never through a renderer member, so no
* engine type crosses the contract.
*/
import { createApplicationViewer } from './applicationViewer.js';
import { CONTRACT_VERSION } from '../contract/index.js';
import { bindRenderer } from '../rendererOf.js';
import { provideApplicationHooks } from '../applicationHooks.js';
import { FREE_LOOK_MAX_HEIGHT_METERS } from '../../globeInView.js';
import { createCesiumInput } from './input.js';
import { cesiumCapabilities, createCesiumPorts } from './ports.js';
// The application's map stacks switch through the Cesium map engine.
import './mapEngine.js';
import { cesiumMapEngine } from './mapEngine.js';
import { installFreeLookHeightLimit } from './freeLookLimit.js';
import { keepPanelRendering } from './panelRendering.js';
import { trimStaleSceneCommands } from './sceneCommandRelease.js';
import { installZoomOutGuard } from './zoomOutGuard.js';
import { configureCreditKeyboardAccess } from './creditKeyboard.js';
import { onLocaleChange } from '../../i18n/index.js';
import { cesiumViewerOf, recordViewer } from './viewers.js';
export { cesiumViewerOf };
/** @typedef {import('../contract/renderer').Renderer} TransitionalRenderer */
const viewers = new WeakMap();
/** A Set no one can change once built, so `capabilities` stays true. */
export class ReadonlySet extends Set {
#sealed;
@@ -51,14 +65,6 @@ export class ReadonlySet extends Set {
}
}
/**
* The Cesium viewer behind a renderer this plugin made, or null for any
* renderer it did not make.
* @param {object} renderer
* @returns {object|null}
*/
export const cesiumViewerOf = (renderer) => viewers.get(renderer) ?? null;
/**
* The Cesium plugin over a viewer factory; tests pass a fake one.
* @param {{createViewer?: typeof createApplicationViewer}} [options]
@@ -90,6 +96,8 @@ export function createCesiumRendererPlugin({
let ports;
let input;
let capabilities;
let releaseFreeLook = () => {};
let offLocale = () => {};
try {
viewer = createViewer({ container, creditContainer });
capabilities = new ReadonlySet(cesiumCapabilities(viewer.scene));
@@ -101,7 +109,19 @@ export function createCesiumRendererPlugin({
query: ports.query,
report: ports.report,
});
// Free look is limited to low heights from the start.
releaseFreeLook = installFreeLookHeightLimit(
viewer,
FREE_LOOK_MAX_HEIGHT_METERS,
);
configureCreditKeyboardAccess(document);
offLocale = onLocaleChange(() =>
configureCreditKeyboardAccess(document),
);
} catch (error) {
offLocale();
releaseFreeLook();
input?.dispose();
ports?.dispose();
if (viewer && !viewer.isDestroyed()) viewer.destroy();
creditContainer.remove();
@@ -132,6 +152,8 @@ export function createCesiumRendererPlugin({
},
destroy() {
try {
offLocale();
releaseFreeLook();
input.dispose();
ports.dispose();
if (!viewer.isDestroyed()) viewer.destroy();
@@ -143,8 +165,25 @@ export function createCesiumRendererPlugin({
}
},
});
viewers.set(renderer, viewer);
recordViewer(renderer, viewer);
unbind = bindRenderer(viewer, renderer);
provideApplicationHooks(renderer, {
mapEngine: cesiumMapEngine,
// Drops the draw commands the scene keeps after it stops drawing
// them; run after a drawn frame (see sceneCommandRelease.js).
trimStaleCommands: () => trimStaleSceneCommands(viewer.scene),
// Keeps the globe drawing in an inline panel whose host stops
// animation frames (embed mode, src/app/embed.js).
keepPanelRendering: (options) => keepPanelRendering(viewer, options),
// Whether an entity is one of the viewer's own (Cockpit asks whether
// the aircraft it flies still draws).
viewerDrawsEntity: (entity) => viewer.entities.contains(entity),
// Keeps outward user zooms bounded and the Earth framed; returns its
// disposer (see zoomOutGuard.js).
installZoomOutGuard: (options) => installZoomOutGuard(viewer, options),
// QA scripts drive and read the viewer itself.
qaHandles: { viewer },
});
return renderer;
},
});
+31 -44
View File
@@ -3,6 +3,8 @@ import test from 'node:test';
import * as Cesium from 'cesium';
import { CONTRACT_VERSION, checkRendererShape } from '../contract/index.js';
import { rendererOf } from '../rendererOf.js';
import { applicationHooksOf } from '../applicationHooks.js';
import { cesiumMapEngine } from './mapEngine.js';
import {
ReadonlySet,
cesiumRenderer,
@@ -55,12 +57,19 @@ function fakeViewer(log, { failDestroy = false } = {}) {
moveEnd: fakeEvent(listeners),
},
primitives: { add() {}, remove() {} },
// The free-look height limit writes the camera controller's look.
screenSpaceCameraController: {
enableLook: true,
minimumTrackBallHeight: 7_500_000,
},
requestRender() {},
preUpdate: fakeEvent(listeners),
postUpdate: fakeEvent(listeners),
preRender: fakeEvent(listeners),
postRender: fakeEvent(listeners),
},
camera: { positionCartographic: { height: 20_000_000 } },
entities: { contains: (entity) => entity?.own === true },
canvas: {
tag: 'canvas',
// Cesium's input handler binds the canvas's events.
@@ -128,6 +137,23 @@ test('the plugin wraps the viewer it is given, behind the accessor only', async
assert.equal(cesiumViewerOf(renderer).canvas, renderer.canvas);
assert.equal(rendererOf(viewer), renderer, 'the viewer finds its renderer');
assert.equal(
viewer.scene.screenSpaceCameraController.enableLook,
false,
'free look is limited to low heights from the start',
);
const hooks = applicationHooksOf(renderer);
assert.equal(hooks.mapEngine, cesiumMapEngine, 'the map stacks use Cesium');
assert.equal(hooks.qaHandles.viewer, viewer, 'QA scripts read the viewer');
assert.equal(hooks.viewerDrawsEntity({ own: true }), true);
assert.equal(hooks.viewerDrawsEntity({}), false);
for (const name of [
'trimStaleCommands',
'keepPanelRendering',
'installZoomOutGuard',
])
assert.equal(typeof hooks[name], 'function', name);
assert.ok(viewer.listeners.size > 0, 'the ports follow the frame phases');
assert.equal(typeof renderer.draw.icons, 'function');
assert.ok(renderer.capabilities.has('models'), 'draw.models is declared');
@@ -136,6 +162,11 @@ test('the plugin wraps the viewer it is given, behind the accessor only', async
renderer.destroy();
assert.equal(viewer.listeners.size, 0, 'and stop on destroy');
assert.equal(rendererOf(viewer), null, 'and lets go of the viewer');
assert.equal(
viewer.scene.screenSpaceCameraController.enableLook,
true,
'and gives free look back',
);
assert.deepEqual(log, ['resize', 'destroy']);
assert.deepEqual(doc.children, [], 'credits leave with the renderer');
renderer.destroy();
@@ -273,48 +304,4 @@ test('only renderers this plugin made reach a Cesium viewer', () => {
assert.equal(cesiumViewerOf({}), null);
});
test('the application refuses a renderer it cannot run on, and destroys it', async (t) => {
const { createApplicationScene } = await import('../../app/scene.js');
const { createApplicationRequestServices } =
await import('../../services/requests.js');
const destroyed = [];
const deferred = [];
const plugin = {
id: 'other',
async create(options) {
assert.ok(options.signal, 'the scene passes its signal');
return {
id: 'other',
destroy: () => {
destroyed.push('other');
throw new Error('and it fails to go');
},
};
},
};
const saved = { document: globalThis.document, window: globalThis.window };
globalThis.document = fakeDocument();
globalThis.window = new EventTarget();
const warn = console.warn;
console.warn = () => {};
t.after(() => {
for (const fn of deferred.reverse()) fn();
console.warn = warn;
globalThis.document = saved.document;
globalThis.window = saved.window;
});
await assert.rejects(
createApplicationScene({
renderer: plugin,
requestServices: createApplicationRequestServices(),
loaderStatus: { textContent: '' },
signal: new AbortController().signal,
defer: (fn) => deferred.push(fn),
}),
/renderer cannot run the application yet/,
'the refusal is not hidden by the failed destroy',
);
assert.deepEqual(destroyed, ['other']);
});
const EXPECTED_MISSING = [];
+6 -65
View File
@@ -1,69 +1,10 @@
/**
* @module render/cesium/application
* @description The Cesium adapter's side of the application scene
* (`src/app/scene.js`), its composition root: the default renderer plugin,
* the viewer behind a renderer it made, the photoreal base tileset the scene
* loads into that viewer, and the viewer hooks the scene hands the
* application (stale command trimming, inline panel rendering, whether an
* entity is the viewer's own, the zoom-out guard, the free-look height
* limit). The scene imports this module and no other
* part of the adapter (`src/render/noCesiumOutsideRender.test.mjs`).
* (`src/app/scene.js`), its composition root: the default renderer plugin.
* Everything else the application needs of this renderer comes with each
* renderer the plugin makes (`appRenderer.js`). The scene imports this
* module, when it is given no renderer of its own, and no other part of the
* adapter (`src/render/noCesiumOutsideRender.test.mjs`).
*/
import * as Cesium from 'cesium';
import { cesiumRenderer, cesiumViewerOf } from './appRenderer.js';
import { loadPhotorealisticTileset } from './google3d.js';
import { keepPanelRendering } from './panelRendering.js';
import { trimStaleSceneCommands } from './sceneCommandRelease.js';
import { installZoomOutGuard } from './zoomOutGuard.js';
import { installFreeLookHeightLimit } from './freeLookLimit.js';
export { cesiumRenderer, cesiumViewerOf };
/**
* Load Google Photorealistic 3D Tiles for the application, by the best route
* the credentials allow (`google3d.js`).
* @param {{googleApiKey?: string, googleTokens?: object|null, cesiumToken?: string}} credentials
* @returns {Promise<{tileset: object|null, route: string, errors: Error[]}>}
*/
export const loadApplicationPhotoreal = (credentials) =>
loadPhotorealisticTileset(Cesium, credentials);
/** Draw the loaded photoreal tileset in `viewer`. */
export function showApplicationPhotoreal(viewer, tileset) {
viewer.scene.primitives.add(tileset);
}
/**
* Release the photoreal tileset: out of `viewer`, which destroys it, or
* destroyed by itself when the viewer never held it.
*/
export function releaseApplicationPhotoreal(viewer, tileset) {
if (tileset && !tileset.isDestroyed()) {
if (!viewer.scene.primitives.remove(tileset)) tileset.destroy();
}
}
/**
* What the application scene hands the application about its viewer.
* @param {object} viewer
*/
export function applicationViewerHooks(viewer) {
return {
// Drops the draw commands the scene keeps after it stops drawing them;
// run after a drawn frame (see sceneCommandRelease.js).
trimStaleCommands: () => trimStaleSceneCommands(viewer.scene),
// Keeps the globe drawing in an inline panel whose host stops animation
// frames (embed mode, src/app/embed.js).
keepPanelRendering: (options) => keepPanelRendering(viewer, options),
// Whether an entity is one of the viewer's own (Cockpit asks whether
// the aircraft it flies still draws).
viewerDrawsEntity: (entity) => viewer.entities.contains(entity),
// Keeps outward user zooms bounded and the Earth framed; returns its
// disposer (see zoomOutGuard.js).
installZoomOutGuard: (options) => installZoomOutGuard(viewer, options),
// Allows the camera controller's free look only near the ground; returns
// its disposer (see freeLookLimit.js).
installFreeLookHeightLimit: (maxHeight) =>
installFreeLookHeightLimit(viewer, maxHeight),
};
}
export { cesiumRenderer } from './appRenderer.js';
+84
View File
@@ -0,0 +1,84 @@
/**
* Adds the keyboard semantics omitted by Cesium's href-less attribution links.
* Cesium retains ownership of showing and hiding its required credit lightbox.
*/
import { t } from '../../i18n/index.js';
export function configureCreditKeyboardAccess(root = document) {
const expand = root?.querySelector?.(
'#cesium-credits .cesium-credit-expand-link',
);
const lightbox = root?.querySelector?.('.cesium-credit-lightbox');
const close = lightbox?.querySelector?.('.cesium-credit-lightbox-close');
if (!expand || !lightbox || !close) return false;
const overlay = lightbox.parentElement;
// Cesium writes these two texts in English once, when it builds the credit
// display, and never rewrites them; English is Cesium's own text. Called
// again after a locale change, this words them again.
expand.textContent = t('Data attribution');
const title = lightbox.querySelector?.('.cesium-credit-lightbox-title');
if (title) title.textContent = t('Data provided by:');
if (!lightbox.id) lightbox.id = 'cesium-credit-lightbox';
expand.setAttribute('role', 'button');
expand.setAttribute('tabindex', '0');
expand.setAttribute('aria-haspopup', 'dialog');
expand.setAttribute('aria-controls', lightbox.id);
if (!expand.hasAttribute?.('aria-expanded'))
expand.setAttribute('aria-expanded', 'false');
close.setAttribute('role', 'button');
close.setAttribute('tabindex', '0');
close.setAttribute('aria-label', t('Close data attribution'));
if (expand.dataset.gevKeyboardReady === 'true') return true;
expand.dataset.gevKeyboardReady = 'true';
const installKeyboardActivation = (control) => {
let spacePressed = false;
control.addEventListener('keydown', (event) => {
if (event.key === 'Enter') {
event.preventDefault();
if (!event.repeat) control.click();
return;
}
if (event.key !== ' ') return;
event.preventDefault();
if (!event.repeat) spacePressed = true;
});
control.addEventListener('keyup', (event) => {
if (event.key !== ' ') return;
event.preventDefault();
if (!spacePressed) return;
spacePressed = false;
control.click();
});
// A long Space hold may hand control to push-to-talk and move focus away.
// Cancelling the armed release prevents that eventual keyup from also
// activating the attribution control.
control.addEventListener('blur', () => {
spacePressed = false;
});
};
const closeAndRestoreFocus = () => {
expand.setAttribute('aria-expanded', 'false');
expand.focus();
};
installKeyboardActivation(expand);
installKeyboardActivation(close);
lightbox.addEventListener('keydown', (event) => {
if (event.key !== 'Escape' || event.defaultPrevented) return;
event.preventDefault();
event.stopPropagation();
close.click();
});
expand.addEventListener('click', () => {
expand.setAttribute('aria-expanded', 'true');
close.focus();
});
close.addEventListener('click', closeAndRestoreFocus);
overlay?.addEventListener?.('click', (event) => {
if (!lightbox.contains(event.target)) closeAndRestoreFocus();
});
return true;
}
+236
View File
@@ -0,0 +1,236 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { configureCreditKeyboardAccess } from './creditKeyboard.js';
import { setLocale } from '../../i18n/index.js';
function fakeElement() {
const attributes = new Map();
const listeners = new Map();
return {
dataset: {},
focused: false,
id: '',
setAttribute(name, value) { attributes.set(name, String(value)); },
getAttribute(name) { return attributes.get(name) ?? null; },
addEventListener(type, listener) {
if (!listeners.has(type)) listeners.set(type, []);
listeners.get(type).push(listener);
},
dispatch(type, event = {}) {
const dispatched = {
currentTarget: this,
target: this,
defaultPrevented: false,
propagationStopped: false,
preventDefault() { this.defaultPrevented = true; },
stopPropagation() { this.propagationStopped = true; },
...event,
};
for (const listener of listeners.get(type) || []) listener(dispatched);
return dispatched;
},
click() {
this.onclick?.();
this.dispatch('click');
},
focus() { this.focused = true; },
listenerCount(type) { return listeners.get(type)?.length || 0; },
};
}
function fixture() {
const expand = fakeElement();
const close = fakeElement();
const lightbox = fakeElement();
lightbox.querySelector = () => close;
lightbox.contains = (target) => target === lightbox || target === close;
const overlay = fakeElement();
lightbox.parentElement = overlay;
const root = {
querySelector(selector) {
if (selector === '#cesium-credits .cesium-credit-expand-link') return expand;
if (selector === '.cesium-credit-lightbox') return lightbox;
return null;
},
};
return { close, expand, lightbox, overlay, root };
}
test('Cesium Data attribution and close controls join the keyboard tab order', () => {
const f = fixture();
assert.equal(configureCreditKeyboardAccess(f.root), true);
assert.equal(f.expand.getAttribute('role'), 'button');
assert.equal(f.expand.getAttribute('tabindex'), '0');
assert.equal(f.expand.getAttribute('aria-haspopup'), 'dialog');
assert.equal(f.expand.getAttribute('aria-expanded'), 'false');
assert.equal(f.close.getAttribute('role'), 'button');
assert.equal(f.close.getAttribute('tabindex'), '0');
assert.equal(f.close.getAttribute('aria-label'), 'Close data attribution');
});
test('Enter opens and closes attribution on initial keydown', () => {
const f = fixture();
let opened = 0;
let closed = 0;
f.expand.onclick = () => { opened++; };
f.close.onclick = () => { closed++; };
configureCreditKeyboardAccess(f.root);
const openEvent = f.expand.dispatch('keydown', { key: 'Enter' });
assert.equal(openEvent.defaultPrevented, true);
assert.equal(opened, 1);
assert.equal(f.expand.getAttribute('aria-expanded'), 'true');
assert.equal(f.close.focused, true);
const closeEvent = f.close.dispatch('keydown', { key: 'Enter' });
assert.equal(closeEvent.defaultPrevented, true);
assert.equal(closed, 1);
assert.equal(f.expand.getAttribute('aria-expanded'), 'false');
assert.equal(f.expand.focused, true);
});
test('Space opens and closes attribution only on key release', () => {
const f = fixture();
let opened = 0;
let closed = 0;
f.expand.onclick = () => { opened++; };
f.close.onclick = () => { closed++; };
configureCreditKeyboardAccess(f.root);
const openDown = f.expand.dispatch('keydown', { key: ' ' });
assert.equal(openDown.defaultPrevented, true);
assert.equal(opened, 0);
assert.equal(f.expand.getAttribute('aria-expanded'), 'false');
const openUp = f.expand.dispatch('keyup', { key: ' ' });
assert.equal(openUp.defaultPrevented, true);
assert.equal(opened, 1);
assert.equal(f.expand.getAttribute('aria-expanded'), 'true');
assert.equal(f.close.focused, true);
const closeDown = f.close.dispatch('keydown', { key: ' ' });
assert.equal(closeDown.defaultPrevented, true);
assert.equal(closed, 0);
const closeUp = f.close.dispatch('keyup', { key: ' ' });
assert.equal(closeUp.defaultPrevented, true);
assert.equal(closed, 1);
assert.equal(f.expand.getAttribute('aria-expanded'), 'false');
assert.equal(f.expand.focused, true);
});
test('held activation keys do not repeat open or close actions', () => {
const f = fixture();
let opened = 0;
f.expand.onclick = () => { opened++; };
configureCreditKeyboardAccess(f.root);
f.expand.dispatch('keydown', { key: ' ' });
const repeated = f.expand.dispatch('keydown', { key: ' ', repeat: true });
assert.equal(repeated.defaultPrevented, true);
assert.equal(opened, 0);
f.expand.dispatch('keyup', { key: ' ' });
assert.equal(opened, 1);
f.expand.dispatch('keyup', { key: ' ' });
assert.equal(opened, 1);
const g = fixture();
let enterOpened = 0;
g.expand.onclick = () => { enterOpened++; };
configureCreditKeyboardAccess(g.root);
g.expand.dispatch('keydown', { key: 'Enter' });
g.expand.dispatch('keydown', { key: 'Enter', repeat: true });
assert.equal(enterOpened, 1);
});
test('losing focus during a Space hold cancels release activation', () => {
const f = fixture();
let opened = 0;
f.expand.onclick = () => { opened++; };
configureCreditKeyboardAccess(f.root);
f.expand.dispatch('keydown', { key: ' ' });
f.expand.dispatch('blur');
const release = f.expand.dispatch('keyup', { key: ' ' });
assert.equal(release.defaultPrevented, true);
assert.equal(opened, 0);
assert.equal(f.expand.getAttribute('aria-expanded'), 'false');
});
test('Escape and backdrop dismissal close attribution and restore its disclosure', () => {
const f = fixture();
let closed = 0;
f.close.onclick = () => { closed++; };
configureCreditKeyboardAccess(f.root);
f.expand.click();
const escape = f.lightbox.dispatch('keydown', { key: 'Escape', target: f.close });
assert.equal(escape.defaultPrevented, true);
assert.equal(escape.propagationStopped, true);
assert.equal(closed, 1);
assert.equal(f.expand.getAttribute('aria-expanded'), 'false');
assert.equal(f.expand.focused, true);
f.expand.focused = false;
f.expand.click();
f.overlay.dispatch('click', { target: f.overlay });
assert.equal(f.expand.getAttribute('aria-expanded'), 'false');
assert.equal(f.expand.focused, true);
});
test('credit keyboard setup is idempotent and safely declines incomplete markup', () => {
const f = fixture();
assert.equal(configureCreditKeyboardAccess(f.root), true);
assert.equal(configureCreditKeyboardAccess(f.root), true);
assert.equal(f.expand.listenerCount('keydown'), 1);
assert.equal(f.expand.listenerCount('keyup'), 1);
assert.equal(f.expand.listenerCount('blur'), 1);
assert.equal(f.close.listenerCount('keydown'), 1);
assert.equal(f.close.listenerCount('keyup'), 1);
assert.equal(f.close.listenerCount('blur'), 1);
assert.equal(f.lightbox.listenerCount('keydown'), 1);
assert.equal(f.overlay.listenerCount('click'), 1);
assert.equal(configureCreditKeyboardAccess({ querySelector: () => null }), false);
});
function textFixture() {
const f = fixture();
const title = fakeElement();
title.textContent = 'Data provided by:';
f.expand.textContent = 'Data attribution';
f.lightbox.querySelector = (selector) =>
selector === '.cesium-credit-lightbox-title' ? title : f.close;
return { ...f, title };
}
test('English keeps Cesium attribution texts', () => {
setLocale('en');
const f = textFixture();
configureCreditKeyboardAccess(f.root);
assert.equal(f.expand.textContent, 'Data attribution');
assert.equal(f.title.textContent, 'Data provided by:');
});
for (const [locale, link, title] of [
['ru', 'Источники данных', 'Данные предоставлены:'],
['es', 'Atribución de datos', 'Datos proporcionados por:'],
])
test(`${locale}: Cesium attribution link and lightbox title are translated`, () => {
setLocale(locale);
try {
const f = textFixture();
configureCreditKeyboardAccess(f.root);
assert.equal(f.expand.textContent, link);
assert.equal(f.title.textContent, title);
} finally {
setLocale('en');
}
});
test('setting up again after a switch back to English restores the English texts', () => {
const f = textFixture();
setLocale('ru');
try {
configureCreditKeyboardAccess(f.root);
} finally {
setLocale('en');
}
configureCreditKeyboardAccess(f.root);
assert.equal(f.expand.textContent, 'Data attribution');
assert.equal(f.title.textContent, 'Data provided by:');
});
+33 -16
View File
@@ -2,11 +2,17 @@
* @module render/cesium/mapEngine
* @description The Cesium map engine (`src/maps/engine.js`): the providers
* the map stacks' imagery and terrain come from (`mapImagery.js`,
* `mapTerrain.js`), and the viewer operations the map source controller
* switches stacks with. Provided as this module loads.
* `mapTerrain.js`), the photoreal base the application scene loads
* (`google3d.js`), and the viewer operations the map source controller
* switches stacks with. Each operation takes the scene object: the viewer
* behind it (`viewers.js`) is the one it changes. Provided as this module
* loads, for viewers with no renderer bound, and handed to the application
* with each renderer the plugin makes (`appRenderer.js`).
*/
import * as Cesium from 'cesium';
import { provideMapEngine } from '../../maps/engine.js';
import { loadPhotorealisticTileset } from './google3d.js';
import { viewerBehind } from './viewers.js';
import {
createEsriImagery,
createIonImagery,
@@ -27,33 +33,35 @@ export const cesiumMapEngine = Object.freeze({
}),
/** The layer a globe stack's imagery provider draws through. */
createImageryLayer: (provider) => new Cesium.ImageryLayer(provider),
requestRender(viewer) {
viewer?.scene?.requestRender?.();
requestRender(host) {
viewerBehind(host)?.scene?.requestRender?.();
},
globeShown: (viewer) => viewer?.scene?.globe?.show === true,
setGlobeShown(viewer, shown) {
viewer.scene.globe.show = shown;
globeShown: (host) => viewerBehind(host)?.scene?.globe?.show === true,
setGlobeShown(host, shown) {
viewerBehind(host).scene.globe.show = shown;
},
addTileset(viewer, tileset) {
viewer.scene.primitives.add(tileset);
addTileset(host, tileset) {
viewerBehind(host).scene.primitives.add(tileset);
},
removeTileset(viewer, tileset) {
viewer.scene.primitives.remove(tileset);
/** Removed, which destroys it. */
removeTileset(host, tileset) {
viewerBehind(host).scene.primitives.remove(tileset);
},
tilesetShown: (tileset) => tileset?.show === true,
showTileset(tileset, shown) {
tileset.show = shown;
},
/** Below every other imagery layer, at `index`. */
addImageryLayer(viewer, layer, index) {
viewer.imageryLayers.add(layer, index);
addImageryLayer(host, layer, index) {
viewerBehind(host).imageryLayers.add(layer, index);
},
/** Removed and destroyed. */
removeImageryLayer(viewer, layer) {
viewer.imageryLayers.remove(layer, true);
removeImageryLayer(host, layer) {
viewerBehind(host).imageryLayers.remove(layer, true);
},
/** A terrain factory's result: `{terrain}` or `{provider}`. */
applyTerrain(viewer, result) {
applyTerrain(host, result) {
const viewer = viewerBehind(host);
if (result.terrain) viewer.scene.setTerrain(result.terrain);
else viewer.terrainProvider = result.provider;
},
@@ -75,6 +83,15 @@ export const cesiumMapEngine = Object.freeze({
if (typeof value?.destroy === 'function' && !value.isDestroyed?.())
value.destroy();
},
/**
* Load Google Photorealistic 3D Tiles by the best route the credentials
* allow (`google3d.js`); the tileset is not yet drawn.
* @param {object} host
* @param {{googleApiKey?: string, googleTokens?: object|null, cesiumToken?: string}} credentials
* @returns {Promise<{tileset: object|null, route: string, errors: Error[]}>}
*/
loadPhotoreal: (host, credentials) =>
loadPhotorealisticTileset(Cesium, credentials),
});
provideMapEngine(cesiumMapEngine);
+5 -4
View File
@@ -17,6 +17,7 @@ import { provideNativeClick } from '../rendererOf.js';
import { drawHitOf } from './drawHit.js';
import { pickThroughFollowHelper } from './follow.js';
import { recentPick } from './pickMemo.js';
import { viewerBehind } from './viewers.js';
/** A drill is run at least this deep and sliced, so callers asking for
* different depths on one click share one pass. */
@@ -165,10 +166,10 @@ export function createNativeClick(scene, at) {
};
}
// Any Cesium viewer, bound or not, by shape: a caller's may come from
// another copy of Cesium.
provideNativeClick((viewer, at) => {
const scene = viewer?.scene;
// The viewer behind the scene object, bound or not, by shape: an unbound one
// may come from another copy of Cesium.
provideNativeClick((host, at) => {
const scene = viewerBehind(host)?.scene;
if (typeof scene?.pick !== 'function') return null;
return createNativeClick(scene, at);
});
+36
View File
@@ -0,0 +1,36 @@
/**
* @module render/cesium/viewers
* @description The Cesium viewer behind each renderer the application's
* plugin made (`appRenderer.js`), and the viewer behind a scene object the app
* holds: the one its bound renderer draws with, or the scene object itself
* when it is a viewer with no renderer bound.
*/
import { rendererOf } from '../rendererOf.js';
const viewers = new WeakMap();
/**
* Record `viewer` as the one behind `renderer`.
* @param {object} renderer
* @param {object} viewer
*/
export function recordViewer(renderer, viewer) {
viewers.set(renderer, viewer);
}
/**
* The Cesium viewer behind a renderer the application's plugin made, or
* null for the test stub.
* @param {object} renderer
* @returns {object|null}
*/
export const cesiumViewerOf = (renderer) =>
(renderer && viewers.get(renderer)) || null;
/**
* The Cesium viewer behind the scene object `host`: its bound renderer's,
* else `host` itself (a viewer with no renderer bound, or none at all).
* @param {object|null|undefined} host
* @returns {object|null|undefined}
*/
export const viewerBehind = (host) => cesiumViewerOf(rendererOf(host)) ?? host;
+2 -3
View File
@@ -6,7 +6,6 @@ import {
maxPitchForHeight,
MAXIMUM_ZOOM_DISTANCE_M,
} from './zoomOutGuard.js';
import { applicationViewerHooks } from './application.js';
const deg = Cesium.Math.toDegrees;
const { WHEEL, PINCH, RIGHT_DRAG, LEFT_DRAG, MIDDLE_DRAG } =
@@ -764,7 +763,7 @@ test('a tracked camera cannot climb past the ceiling from its target', () => {
}
});
test("the application scene's viewer hooks install the guard on the viewer and hand back its disposer", () => {
test('the guard installs on the viewer and hands back its disposer', () => {
const controller = { maximumZoomDistance: Infinity };
const scene = {
mode: Cesium.SceneMode.SCENE3D,
@@ -778,7 +777,7 @@ test("the application scene's viewer hooks install the guard on the viewer and h
};
const viewer = { scene, camera, canvas: new EventTarget() };
const handoffs = new Set();
const dispose = applicationViewerHooks(viewer).installZoomOutGuard({
const dispose = installZoomOutGuard(viewer, {
subscribeCameraHandoff(listener) {
handoffs.add(listener);
return () => handoffs.delete(listener);
+24
View File
@@ -223,6 +223,30 @@ export function bindRenderer(host, renderer) {
};
}
/**
* The scene object the application holds for `renderer`: what every layer
* and tool is handed, and reaches the renderer's ports through. It is the
* application's own: the element the renderer
* fills (`container`) and whether the scene is gone (`isDestroyed()`), and
* nothing of the engine.
* @param {object} renderer
* @param {{container: HTMLElement}} options
* @returns {{host: Readonly<{container: HTMLElement, isDestroyed: () => boolean}>,
* release: () => void}} `release` marks the scene gone and unbinds it.
*/
export function createSceneHost(renderer, { container }) {
let destroyed = false;
const host = Object.freeze({ container, isDestroyed: () => destroyed });
const unbind = bindRenderer(host, renderer);
return {
host,
release() {
destroyed = true;
unbind();
},
};
}
/**
* @param {object|null|undefined} host
* @returns {object|null} The renderer bound to `host`, or null.