Merge main and switch Cesium and Navara in place through Vue

Preserve the camera, map source and layer selection across engine sessions. Restore the previous engine if startup fails and retain local history navigation.
This commit is contained in:
German Khokhlov committed 2026-11-02 13:10:36 +04:00
commit b8f4d097c4
1691 files changed
+225876 -41594

No files matched your search

+40
View File
@@ -0,0 +1,40 @@
import { readFileSync } from 'node:fs';
import { createPinia } from 'pinia';
import { createSSRApp } from 'vue';
import { renderToString } from 'vue/server-renderer';
import { APPLICATION_VIEWS } from '../ui/views/index.js';
const HOST = /<div class="gev-view" data-gev-view="([^"]+)"><\/div>/g;
/**
* Application markup as the browser shows it once views are mounted: each
* view rendered into its host. Markup tests read this instead of the page
* source.
* @param {string} html Document with `.gev-view` hosts.
* @returns {Promise<string>}
*/
export async function renderApplicationHtml(html) {
let output = html;
for (const [host, name] of [...output.matchAll(HOST)]) {
const view = APPLICATION_VIEWS[name];
if (!view) throw new Error(`Unknown application view: ${name}`);
const markup = (await renderToString(createSSRApp(view).use(createPinia())))
// Hydration markers, empty-attribute values and escaped apostrophes
// are SSR detail; the DOM is the same as the template's.
.replace(/<!--\[-->|<!--\]-->|<!---->/g, '')
.replace(/ ([\w:.-]+)=""/g, ' $1')
.replaceAll('&#39;', "'");
output = output.replace(
host,
() => `<div class="gev-view" data-gev-view="${name}">${markup}</div>`,
);
}
return output;
}
/** The standalone page's markup with every view rendered. */
export function readApplicationHtml() {
return renderApplicationHtml(
readFileSync(new URL('../../index.html', import.meta.url), 'utf8'),
);
}
+19
View File
@@ -0,0 +1,19 @@
import assert from 'node:assert/strict';
const describe = (node) =>
node?.nodeType === 1
? `<${node.tagName.toLowerCase()}${node.id ? `#${node.id}` : ''}>`
: String(node);
/**
* Assert that two DOM nodes (or a node and null) are the same. Never hand
* happy-dom nodes to assert.equal or deepEqual: a failure prints both, and a
* node reaches the whole page and window, which runs the process out of
* memory.
*/
export function assertSameNode(actual, expected, message = '') {
assert.ok(
actual === expected,
`${message ? `${message}: ` : ''}${describe(actual)} is not ${describe(expected)}`,
);
}
@@ -0,0 +1,367 @@
import { createCesiumEngine } from '../globe/cesium/createCesiumEngine.js';
import assert from 'node:assert/strict';
import { createVoiceSession } from '../voice/session.js';
import { createGevActionRunner } from '../voice/gevActions.js';
import { createGeminiSession } from '../voice/geminiSession.js';
import { createTestVoiceUi } from './voiceUi.mjs';
import { createNarrationScheduler } from '../voice/narration.js';
export const turnOfEventLoop = () =>
new Promise((resolve) => setImmediate(resolve));
function deferred() {
let resolve;
const promise = new Promise((done) => {
resolve = done;
});
return { promise, resolve };
}
function ownedClock() {
let now = 0;
let nextId = 0;
const timers = new Map();
return {
timers,
now: () => now,
setTimer(fn, delay = 0) {
const id = ++nextId;
timers.set(id, { fn, at: now + Math.max(0, delay) });
return id;
},
clearTimer: (id) => timers.delete(id),
advance(ms) {
const until = now + ms;
let callbacks = 0;
for (;;) {
const due = [...timers]
.filter(([, timer]) => timer.at <= until)
.sort((a, b) => a[1].at - b[1].at || a[0] - b[0])[0];
if (!due) break;
assert.ok(
++callbacks <= 1000,
'fixture timer queue must remain bounded',
);
timers.delete(due[0]);
now = due[1].at;
due[1].fn();
}
now = until;
},
};
}
/**
* Real common session -> real Gemini adapter -> real action runner.
* Only devices, transport, passive UI and wall-clock facilities are fakes.
* The optional result gate delays return AFTER the actual action commits.
*/
export function nativeIntegrationFixture(t) {
const clock = ownedClock();
const events = [];
const sockets = [];
const tracks = [];
const audios = [];
const requests = [];
const runnerCalls = [];
const runnerJobs = [];
const resultGates = new Map();
const acquisitions = { microphone: 0, audio: 0, token: 0, socket: 0 };
const state = { height: 1000, renders: 0, zooms: [], earconStarts: 0 };
const position = { x: 6379137, y: 0, z: 0 };
const viewer = {
clock: { onTick: { addEventListener: () => () => {} } },
camera: {
positionWC: position,
positionCartographic: { height: state.height },
moveEnd: { addEventListener() {} },
cancelFlight() {},
zoomIn(metres) {
position.x -= metres;
state.height -= metres;
this.positionCartographic.height = state.height;
state.zooms.push({ direction: 'in', metres });
},
zoomOut(metres) {
position.x += metres;
state.height += metres;
this.positionCartographic.height = state.height;
state.zooms.push({ direction: 'out', metres });
},
},
scene: {
canvas: {
clientWidth: 800,
clientHeight: 600,
addEventListener() {},
removeEventListener() {},
},
requestRender() {
state.renders++;
},
},
};
const dataManager = { layers: new Map() };
const actualRunner = createGevActionRunner({
engine: createCesiumEngine(viewer),
viewer,
dataManager,
styleManager: {},
});
const runner = (name, args, options) => {
runnerCalls.push({ name, args, options });
const job = (async () => {
// No fake action result: the camera and envelope come from production.
const result = await actualRunner(name, args, options);
const gate = resultGates.get(options.callId);
if (gate) {
gate.entered.resolve(result);
await gate.release.promise;
}
return result;
})();
runnerJobs.push(job);
return job;
};
class Socket {
constructor(url) {
acquisitions.socket++;
this.url = url;
this.readyState = 0;
this.bufferedAmount = 0;
this.sent = [];
sockets.push(this);
queueMicrotask(() => {
if (this.closed) return;
this.readyState = 1;
this.onopen?.();
});
}
send(raw) {
assert.equal(
this.readyState,
1,
'sending requires the owned open socket',
);
const message = JSON.parse(raw);
this.sent.push(message);
if (message.setup)
queueMicrotask(() => this.message({ setupComplete: {} }));
}
message(message) {
this.onmessage?.({ data: JSON.stringify(message) });
}
close() {
this.closed = true;
this.readyState = 3;
}
}
const session = createVoiceSession({
runner,
createAdapter: (hooks) =>
createGeminiSession({
...hooks,
ui: createTestVoiceUi(),
dataManager,
now: clock.now,
setTimer: clock.setTimer,
clearTimer: clock.clearTimer,
WebSocketClass: Socket,
getUserMedia: async () => {
acquisitions.microphone++;
const track = {
enabled: true,
readyState: 'live',
stopCalls: 0,
stop() {
this.stopCalls++;
this.readyState = 'ended';
},
};
tracks.push(track);
return { getTracks: () => [track], getAudioTracks: () => [track] };
},
fetchImpl: async (url, init) => {
acquisitions.token++;
requests.push({ url, init });
const manual = JSON.parse(init.body).inputMode === 'push-to-talk';
return Response.json({
token: 'auth_tokens/fixture-not-a-credential',
model: 'gemini-3.8-live',
websocketUrl:
'wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContentConstrained',
config: {
generationConfig: { responseModalities: ['AUDIO'] },
...(manual
? {
realtimeInputConfig: {
automaticActivityDetection: { disabled: true },
},
}
: {}),
},
});
},
createInput: ({ readStream, operations }) => ({
...operations,
setMicrophoneEnabled(enabled) {
for (const track of readStream()?.getAudioTracks() || [])
track.enabled = enabled;
},
updateVoiceButtonLabel() {},
setVoiceSpeaker() {},
startVoiceVisualizer() {},
startAssistantVoiceVisualizer() {},
cancelPushToTalkHold() {},
stopVoiceVisualizer() {},
detachBindings() {},
bindPushToTalkShortcut() {},
resetSession() {
this.pushToTalkMode =
this.pushToTalkKeyHeld =
this.spaceKeyHeld =
false;
},
}),
createAudio: (callbacks) => {
acquisitions.audio++;
const audio = {
pending: false,
closed: false,
outputStream: {},
async initialize() {},
connectMicrophone(stream, enabled, metadata) {
this.stream = stream;
this.setMicrophoneEnabled(enabled, metadata);
},
setMicrophoneEnabled(enabled, metadata) {
this.enabled = enabled;
this.metadata = metadata;
},
play() {
this.pending = true;
},
clearPlayback() {
this.pending = false;
},
drain() {
this.pending = false;
callbacks.onDrain();
},
diagnostics: () => ({ outputChunks: 0 }),
async close() {
this.closed = true;
this.pending = false;
return true;
},
};
audios.push(audio);
return audio;
},
createNarration: (options) =>
createNarrationScheduler({
...options,
now: clock.now,
setTimer: clock.setTimer,
clearTimer: clock.clearTimer,
}),
createProgressEarcon: () => ({
available: () => true,
start() {
state.earconStarts++;
},
stop() {},
dispose() {},
}),
captureViewport: async () => null,
}),
});
session.subscribe((event) => events.push(event));
const controller = session.adapter.controller;
t.after(async () => {
session.destroy();
for (const gate of resultGates.values()) gate.release.resolve();
await Promise.allSettled(runnerJobs);
actualRunner.dispose();
assert.equal(clock.timers.size, 0, 'fixture must leave no owned timer');
assert.ok(audios.every((audio) => audio.closed));
assert.ok(tracks.every((track) => track.readyState === 'ended'));
assert.ok(sockets.every((socket) => socket.closed));
});
return {
session,
controller,
state,
events,
sockets,
tracks,
audios,
requests,
acquisitions,
runnerCalls,
clock,
holdResult(callId) {
const gate = { entered: deferred(), release: deferred() };
resultGates.set(callId, gate);
return { ready: gate.entered.promise, release: gate.release.resolve };
},
async start() {
await session.start();
assert.equal(session.state, 'listening');
assert.equal(controller.getDiagnostics().connected, true);
return sockets.at(-1);
},
activity(socket = sockets.at(-1)) {
socket.message({ voiceActivity: { type: 'ACTIVITY_START' } });
socket.message({ voiceActivity: { type: 'ACTIVITY_END' } });
},
tool(callId, socket = sockets.at(-1)) {
socket.message({
toolCall: {
functionCalls: [
{
id: callId,
name: 'adjust_camera_zoom',
args: { direction: 'in', amount: 'little' },
},
],
},
});
// A deterministic settlement boundary, not a fake action dispatcher.
return controller.toolQueue;
},
outputs(socket = sockets.at(-1)) {
return socket.sent.flatMap(
(message) => message.toolResponse?.functionResponses || [],
);
},
complete(socket = sockets.at(-1)) {
socket.message({ serverContent: { turnComplete: true } });
},
};
}
export function assertSuccessfulZoom(h, socket, callId, beforeHeight) {
assert.equal(h.state.height, beforeHeight * 0.75);
assert.ok(h.state.renders > 0);
const calls = h.events.filter(
(event) => event.type === 'action-call' && event.callId === callId,
);
const results = h.events.filter(
(event) => event.type === 'action-result' && event.callId === callId,
);
assert.equal(calls.length, 1);
assert.equal(results.length, 1);
assert.equal(calls[0].name, 'adjust_camera_zoom');
assert.deepEqual(calls[0].arguments, { direction: 'in', amount: 'little' });
assert.equal(results[0].result.ok, true);
assert.equal(results[0].result.action, 'adjust_camera_zoom');
assert.equal(results[0].result.beforeHeightM, Math.round(beforeHeight));
assert.equal(results[0].result.afterHeightM, Math.round(h.state.height));
const outputs = h.outputs(socket).filter((output) => output.id === callId);
assert.equal(outputs.length, 1);
assert.equal(outputs[0].name, 'adjust_camera_zoom');
assert.equal(outputs[0].response.ok, true);
assert.equal(outputs[0].response.action, 'adjust_camera_zoom');
assert.equal(outputs[0].response.afterHeightM, Math.round(h.state.height));
}
+252
View File
@@ -0,0 +1,252 @@
import { GeminiSessionController } from '../voice/geminiSession.js';
import { createTestVoiceUi } from './voiceUi.mjs';
import { createNarrationScheduler } from '../voice/narration.js';
const endpoint =
'wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContentConstrained';
const credential = {
token: 'auth_tokens/test',
model: 'gemini-3.8-live',
websocketUrl: endpoint,
config: { generationConfig: { responseModalities: ['AUDIO'] } },
};
const manualCredential = {
...credential,
config: {
...credential.config,
realtimeInputConfig: { automaticActivityDetection: { disabled: true } },
},
};
const tick = () => new Promise((resolve) => setImmediate(resolve));
function deferred() {
let resolve;
const promise = new Promise((done) => {
resolve = done;
});
return { promise, resolve };
}
function harness(overrides = {}) {
const { autoSetup = true, ...controllerOverrides } = overrides;
const events = [];
const sockets = [];
const media = [];
const tracks = [];
const captures = [];
const calls = [];
const requests = [];
const state = { playing: 0, ducked: false, stopped: 0 };
let clock = 0;
let nextTimer = 0;
const timers = new Map();
const earcon = { playing: false, starts: 0, disposals: 0 };
const advance = (ms) => {
const target = clock + ms;
for (;;) {
const due = [...timers]
.filter(([, timer]) => timer.at <= target)
.sort((a, b) => a[1].at - b[1].at)[0];
if (!due) break;
timers.delete(due[0]);
clock = due[1].at;
due[1].fn();
}
clock = target;
};
let radioControl;
const radio = {
setVoiceDucked(value) {
state.ducked = value;
},
pause() {},
subscribePlaybackControls(callback) {
radioControl = callback;
return () => {
radioControl = null;
};
},
async playForVoice() {
state.playing++;
return true;
},
stopPlayback() {
state.stopped++;
},
};
class Socket {
constructor(url) {
this.url = url;
this.readyState = 0;
this.bufferedAmount = 0;
this.sent = [];
sockets.push(this);
queueMicrotask(() => {
this.readyState = 1;
this.onopen?.();
});
}
send(raw) {
const value = JSON.parse(raw);
this.sent.push(value);
if (value.setup && autoSetup)
queueMicrotask(() => this.message({ setupComplete: {} }));
}
message(value) {
this.onmessage?.({ data: JSON.stringify(value) });
}
error() {
this.onerror?.();
}
remoteClose() {
this.readyState = 3;
this.onclose?.();
}
close() {
this.readyState = 3;
this.closed = true;
}
}
const makeStream = () => {
const track = {
enabled: true,
readyState: 'live',
stop() {
this.readyState = 'ended';
},
};
tracks.push(track);
return { getTracks: () => [track], getAudioTracks: () => [track] };
};
const c = new GeminiSessionController({
emit: (event) => events.push(event),
runAction: async (name, args, options) => {
calls.push({ name, args, options });
return { ok: true, action: name };
},
ui: createTestVoiceUi(),
radioLayer: radio,
now: () => clock,
setTimer: (fn, ms) => {
const id = ++nextTimer;
timers.set(id, { fn, at: clock + ms });
return id;
},
clearTimer: (id) => timers.delete(id),
WebSocketClass: Socket,
fetchImpl: async (_url, init) => {
requests.push(init);
return Response.json(
JSON.parse(init.body).inputMode === 'push-to-talk'
? manualCredential
: credential,
);
},
getUserMedia: async () => makeStream(),
createInput: ({ readStream, operations }) => ({
...operations,
setMicrophoneEnabled(enabled) {
for (const track of readStream()?.getAudioTracks() || [])
track.enabled = enabled;
},
updateVoiceButtonLabel() {},
setVoiceSpeaker() {},
startVoiceVisualizer() {},
startAssistantVoiceVisualizer() {},
cancelPushToTalkHold() {},
stopVoiceVisualizer() {},
detachBindings() {},
bindPushToTalkShortcut() {},
resetSession() {
this.pushToTalkMode = false;
this.pushToTalkKeyHeld = false;
this.spaceKeyHeld = false;
},
}),
createNarration: (options) =>
createNarrationScheduler({
...options,
now: () => clock,
setTimer: (fn, ms) => {
const id = ++nextTimer;
timers.set(id, { fn, at: clock + ms });
return id;
},
clearTimer: (id) => timers.delete(id),
}),
createProgressEarcon: ({ isMicrophoneMuted }) => ({
available: isMicrophoneMuted,
start() {
earcon.playing = true;
earcon.starts++;
},
stop() {
earcon.playing = false;
},
dispose() {
this.stop();
earcon.disposals++;
},
}),
createAudio: (callbacks) => {
const audio = {
callbacks,
pending: false,
closed: false,
played: [],
async initialize() {},
connectMicrophone(stream, enabled, metadata) {
media.push({ stream, enabled });
this.connected = true;
this.setMicrophoneEnabled(enabled, metadata);
},
setMicrophoneEnabled(value, metadata) {
if (!this.connected) return;
if (value && !this.enabled) {
this.metadata = metadata;
callbacks.onAudioStart(metadata);
}
if (!value && this.enabled) callbacks.onAudioEnd(this.metadata);
this.enabled = value;
},
play(data, mime) {
this.pending = true;
this.played.push({ data, mime });
},
drain() {
this.pending = false;
callbacks.onDrain();
},
clearPlayback() {
this.pending = false;
this.cleared = true;
},
diagnostics() {
return { outputChunks: this.played.length };
},
close() {
this.closed = true;
},
};
captures.push(audio);
return audio;
},
...controllerOverrides,
});
return {
c,
sockets,
tracks,
makeStream,
events,
media,
captures,
calls,
requests,
state,
advance,
timers,
earcon,
radioControl: (value) => radioControl?.(value),
};
}
export { harness, tick, deferred };
+35
View File
@@ -0,0 +1,35 @@
// src/testSupport/hudReadouts.mjs — the Intel HUD's published readouts by the
// element ids its view renders them in, for tests that drive IntelHUD alone.
const FIELDS = Object.freeze({
'hud-alt': 'alt',
'hud-summary': 'summary',
'hud-mgrs': 'mgrs',
'hud-latlon': 'latlon',
'hud-bottom-line': 'bottom',
'hud-gsd': 'gsd',
'hud-coll': 'coll',
'hud-ona': 'ona',
'hud-mode': 'mode',
'hud-timestamp': 'timestamp',
});
/**
* A `publish` to hand IntelHUD and each readout's latest text.
* @returns {{publish: (view: object) => void, view: () => ?object,
* elements: Map<string, {readonly textContent: string}>}}
*/
export function hudReadouts() {
let view = null;
const elements = new Map(
Object.entries(FIELDS).map(([id, field]) => [
id,
{
get textContent() {
return view?.[field] ?? '';
},
},
]),
);
return { publish: (next) => (view = next), view: () => view, elements };
}
+81
View File
@@ -0,0 +1,81 @@
// DOM stand-ins for the KartaView viewer's tests (no browser in Node).
/** A DOM element with what the viewer touches: children, events, attributes. */
function fakeElement(tag) {
const listeners = new Map();
const element = {
tagName: tag.toUpperCase(),
children: [],
parentNode: null,
style: {},
dataset: {},
attributes: {},
hidden: false,
disabled: false,
clientWidth: 400,
clientHeight: 250,
classList: {
values: new Set(),
add: (name) => element.classList.values.add(name),
remove: (name) => element.classList.values.delete(name),
},
append(...nodes) {
for (const node of nodes) {
node.parentNode = element;
element.children.push(node);
}
},
remove() {
const list = element.parentNode?.children;
if (list) list.splice(list.indexOf(element), 1);
element.parentNode = null;
},
replaceWith(next) {
const parent = element.parentNode;
if (!parent) return;
parent.children[parent.children.indexOf(element)] = next;
next.parentNode = parent;
next.ownerDocument = element.ownerDocument;
element.parentNode = null;
},
setAttribute: (name, value) => (element.attributes[name] = value),
removeAttribute: (name) => {
delete element.attributes[name];
if (name === 'src') element.src = '';
},
addEventListener: (type, handler) => listeners.set(type, handler),
removeEventListener: (type) => listeners.delete(type),
setPointerCapture() {},
/** Fire an event at the element's listener. */
fire(type, event = {}) {
return listeners.get(type)?.({
preventDefault() {
this.defaultPrevented = true;
},
stopPropagation() {},
...event,
});
},
};
return element;
}
export function fakeHost() {
const doc = { createElement: (tag) => fakeElement(tag) };
const host = fakeElement('div');
host.ownerDocument = doc;
return host;
}
/**
* Wait, a macrotask at a time, until `condition` holds; false if it never
* does within `ticks`. A test asserting that something did not happen waits
* on a sign that the work is done instead of a fixed count of ticks.
*/
export async function until(condition, { ticks = 200 } = {}) {
for (let i = 0; i < ticks; i++) {
if (await condition()) return true;
await new Promise((resolve) => setTimeout(resolve, 0));
}
return Boolean(await condition());
}
+21
View File
@@ -0,0 +1,21 @@
// src/testSupport/panelState.mjs — present a panel's state the way the shell
// does (PanelChrome._presentPanel), drawn at once as its root's v-panel-state
// would, for fixtures whose panels are plain objects with a classList.
import { applyPanelState, readPanelState } from '../ui/rail/panelState.js';
/**
* @param {object|string} panelOrId A panel, or its id in `documentRef`.
* @param {object} [patch] The state that changes.
* @param {Document} [documentRef]
*/
export function presentPanelLocally(
panelOrId,
patch = {},
documentRef = globalThis.document,
) {
const panel =
typeof panelOrId === 'string'
? documentRef?.getElementById(panelOrId)
: panelOrId;
if (panel) applyPanelState(panel, { ...readPanelState(panel), ...patch });
}
+138
View File
@@ -0,0 +1,138 @@
// Panoramax stand-ins for tests and the hermetic QA gate: vector tiles in
// the meta-catalogue's shape, and STAC items.
import { PbfWriter } from 'pbf';
import {
layerWriter,
lineGeometry,
zigzag,
} from '../layers/streetLevel/providers/mapillary/coverageFixture.mjs';
/** Tile-local [x, y] (0..extent) of a lon/lat inside tile (x, y, z). */
function lonLatToTileLocal([lon, lat], { x, y, z }, extent = 4096) {
const n = 2 ** z;
const rad = (lat * Math.PI) / 180;
const tx = ((lon + 180) / 360) * n;
const ty =
((1 - Math.log(Math.tan(rad) + 1 / Math.cos(rad)) / Math.PI) / 2) * n;
return [Math.round((tx - x) * extent), Math.round((ty - y) * extent)];
}
/**
* Encode a Panoramax `/api/map/{z}/{x}/{y}.mvt` tile from lon/lat features.
* @param {{x: number, y: number, z: number}} tile
* @param {{sequences?: Array<{id: string, date?: string, type?: string, parts: Array<Array<[number, number]>>}>, grid?: Array<{lon: number, lat: number, pano?: number, flat?: number}>, pictures?: Array<{id: string, lon: number, lat: number, sequenceId: string, heading?: number, ts?: string, type?: string}>, extent?: number}} [content]
*/
export function encodePanoramaxTile(
tile,
{ sequences = [], grid = [], pictures = [], extent = 4096 } = {},
) {
const pbf = new PbfWriter();
if (sequences.length) {
const layer = layerWriter('sequences', extent);
for (const sequence of sequences)
layer.add(
2,
lineGeometry(
sequence.parts.map((part) =>
part.map((point) => lonLatToTileLocal(point, tile, extent)),
),
),
{
id: sequence.id,
type: sequence.type ?? 'flat',
date: sequence.date ?? '2025-06-01',
model: 'Test camera',
},
);
pbf.writeMessage(3, (_, out) => layer.write(out), null);
}
const point = (lon, lat) => {
const [px, py] = lonLatToTileLocal([lon, lat], tile, extent);
return [9, zigzag(px), zigzag(py)];
};
if (grid.length) {
const layer = layerWriter('grid', extent);
for (const cell of grid) {
const pano = cell.pano ?? 0;
const flat = cell.flat ?? 1;
layer.add(1, point(cell.lon, cell.lat), {
nb_pictures: pano + flat,
nb_360_pictures: pano,
nb_flat_pictures: flat,
});
}
pbf.writeMessage(3, (_, out) => layer.write(out), null);
}
if (pictures.length) {
const layer = layerWriter('pictures', extent);
for (const picture of pictures)
layer.add(1, point(picture.lon, picture.lat), {
id: picture.id,
ts: picture.ts ?? '2025-06-01 10:00:00+00',
heading: picture.heading ?? 90,
sequences: JSON.stringify([picture.sequenceId]),
first_sequence: picture.sequenceId,
type: picture.type ?? 'flat',
});
pbf.writeMessage(3, (_, out) => layer.write(out), null);
}
return new Uint8Array(pbf.finish());
}
/**
* A STAC item as the meta-catalogue returns it.
* @param {{id: string, lon: number, lat: number, sequenceId?: string, heading?: number, pano?: boolean, datetime?: string, producer?: string, license?: string, width?: number, prevId?: string|null, nextId?: string|null, host?: string}} options
*/
export function stacItem({
id,
lon,
lat,
sequenceId = 'seq-1',
heading = 90,
pano = false,
datetime = '2025-06-01T10:00:00+00:00',
producer = 'tester',
license = 'CC-BY-SA-4.0',
width = pano ? 5760 : 4032,
prevId = null,
nextId = null,
host = 'https://panoramax.example.org',
}) {
const api = 'https://api.panoramax.xyz/api';
const links = [
{ rel: 'self', href: `${api}/collections/${sequenceId}/items/${id}` },
];
if (prevId)
links.push({
rel: 'prev',
href: `${api}/collections/${sequenceId}/items/${prevId}`,
});
if (nextId)
links.push({
rel: 'next',
href: `${api}/collections/${sequenceId}/items/${nextId}`,
});
return {
type: 'Feature',
id,
collection: sequenceId,
geometry: { type: 'Point', coordinates: [lon, lat] },
providers: [{ name: producer, roles: ['producer'] }],
properties: {
datetime,
license,
'view:azimuth': heading,
'geovisio:producer': producer,
'pers:interior_orientation': {
...(pano ? { field_of_view: 360 } : {}),
sensor_array_dimensions: [width, pano ? width / 2 : 3024],
},
},
assets: {
hd: { href: `${host}/pictures/${id}/hd.jpg` },
sd: { href: `${host}/pictures/${id}/sd.jpg` },
thumb: { href: `${host}/pictures/${id}/thumb.jpg` },
},
links,
};
}
+5
View File
@@ -0,0 +1,5 @@
import { GlobalRegistrator } from '@happy-dom/global-registrator';
// Import first in a test file whose modules load Vue at import time: Vue binds
// the document when it loads. Each test file runs in its own process.
GlobalRegistrator.register({ url: 'http://localhost/' });
+103
View File
@@ -0,0 +1,103 @@
/**
* Shared fixtures for the share-view codec tests: a seeded generator and
* real long-form links.
*/
import {
REGISTERED_LAYER_IDS,
createDefaultLayerState,
optionSpecs,
} from '../data/layerState.js';
/** A long-form link copied from a real session. */
export const HAL_EXAMPLE_HASH =
'v=2&lat=30.2672&lon=-97.7431&alt=600&heading=15&pitch=-30&roll=360&style=normal&bloom=0&sharpen=1&bi=0&bv=2&si=49&hud=tactical&hv=1&dm=DENSE&dd=75&da=elastic&kf=7&ko=1&cr=0&sc=1&scf=11&map=photoreal&l=a.f.s&lo=f.e.1_k.o.n&ui=c.c.1_c.p.0_l.c.1_l.p.0_d.c.1_v.c.0_i.c.0_t.c.1_r.c.1_s.c.1_g.c.1_p.c.1_m.c.0';
/** Deterministic generator (mulberry32) for property-style tests. */
export function rng(seed) {
let a = seed >>> 0;
return () => {
a = (a + 0x6d2b79f5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const OPTION_CANDIDATES = [
true,
false,
'light',
'strong',
'gfs',
'ifs',
'none',
'speed',
'temperature',
'pressure',
'km/h',
'm/s',
'mph',
'proximity',
'all',
'core',
'dense',
'off',
'on',
'viewshed',
'tomtom',
'osm',
'hybrid',
'clouds',
'clouds-regional',
'pano',
'flat',
'filtered',
'full',
0,
1,
2,
37,
50,
100,
365,
-12345678,
12345678,
8505110,
'S30:2026-09-18',
'L30:2024-02-29',
'VIIRS:2025-01-02',
'genre:jazz & blues',
'news',
'public-safety',
0.35,
0.8,
'abc-1*def-0',
'osm-1',
25544,
'a1b2c3',
'~abc123',
];
/** A random layer state using only values each option accepts. */
export function randomLayerState(random) {
const state = createDefaultLayerState();
state.enabledLayerIds = REGISTERED_LAYER_IDS.filter(() => random() < 0.3);
for (const ownerId of Object.keys(state.options)) {
for (const spec of optionSpecs(ownerId)) {
if (random() < 0.5) continue;
const accepted = OPTION_CANDIDATES.filter(
(value) => spec.normalize(value) !== null,
);
if (accepted.length)
state.options[ownerId][spec.key] =
accepted[Math.floor(random() * accepted.length)];
}
}
return state;
}
/** One element of `values`, chosen by `random`. */
export function pick(random, values) {
return values[Math.floor(random() * values.length)];
}
+224 -5
View File
@@ -1,6 +1,11 @@
/** Shared Street Level test stand-ins: provider snapshot, minimal provider, ray-casting camera. */
/** Shared Street Level test stand-ins: provider snapshot and provider, Mapillary source, photo viewer, Cesium viewer, ray-casting camera. */
import * as Cesium from 'cesium';
import { MAPILLARY_CREDIT_HTML } from '../layers/streetLevel/providers/mapillary/policy.js';
import {
latToTileY,
lonToTileX,
tileBounds,
} from '../layers/streetLevel/tileMath.js';
const RAD = Math.PI / 180;
@@ -37,8 +42,6 @@ export function fakeStreetLevelProvider({
const filters = [];
const stats = {
count: 0,
zoom: null,
kind: null,
loading: false,
hint: '',
error: null,
@@ -65,7 +68,6 @@ export function fakeStreetLevelProvider({
activate: () => calls.activate++,
deactivate: () => calls.deactivate++,
destroy() {},
refreshCoverage() {},
setFilter: (filter) => filters.push(filter),
coverageStats: () => ({ ...stats }),
handlePick: () => false,
@@ -83,6 +85,135 @@ export function fakeStreetLevelProvider({
};
}
/**
* A Mapillary source for the provider: a configured key, empty tiles, and the
* given lookups; `calls` records tile requests.
*/
export function fakeMapillarySource(overrides = {}) {
const calls = { tiles: [] };
return {
calls,
hasToken: () => true,
getStatus: async () => ({ configured: true }),
getTile: async (...args) => {
calls.tiles.push(args);
return new Uint8Array(0);
},
getSequenceImages: async () => [],
...overrides,
};
}
/**
* A photo viewer in place of MapillaryJS: `calls` records use, and `open`
* reports a pose for the image (when `pose` is given) as the real one does.
*/
export function fakePhotoViewer({ pose = null } = {}) {
const calls = { mount: 0, open: [], unmount: 0 };
let emit = null;
return {
calls,
mount: async () => calls.mount++,
async open(imageId) {
calls.open.push(imageId);
if (pose) emit?.({ imageId, ...pose });
},
close() {},
unmount: () => calls.unmount++,
resize() {},
onPose(listener) {
emit = listener;
return () => {
emit = null;
};
},
};
}
/**
* A stand-in Cesium viewer a layer can be enabled on: a canvas for the click
* handler, camera events with Cesium's flight bookkeeping (`flights` counts
* them, lists them and can `land` the current one), primitive lists and a
* credit display. With `view`, the camera looks straight down on Sacramento
* from 900 m, so coverage asks for tiles.
*/
export function fakeCesiumViewer({ view = false } = {}) {
const credits = [];
let flight = null;
const flights = {
started: 0,
cancelled: 0,
/** Every flight asked for, oldest first: `{ sphere, options }`. */
list: [],
land() {
const current = flight;
flight = null;
current?.options.complete?.();
},
};
const stopFlight = () => {
const current = flight;
flight = null;
current?.options.cancel?.();
return Boolean(current);
};
const canvas = Object.assign(new EventTarget(), {
style: {},
// Keep Cesium's handler on the canvas; there is no real document here.
disableRootEvents: true,
onwheel: null,
...(view ? { clientWidth: 100, clientHeight: 100 } : {}),
});
const camera = Object.assign(
view
? rayCamera({
lon: -121.4944,
lat: 38.5816,
altitude: 900,
pitch: -90,
width: 100,
height: 100,
})
: {},
{
changed: new Cesium.Event(),
moveStart: new Cesium.Event(),
moveEnd: new Cesium.Event(),
flyToBoundingSphere(sphere, options = {}) {
stopFlight();
flight = { sphere, options };
flights.list.push(flight);
flights.started++;
},
cancelFlight() {
if (stopFlight()) flights.cancelled++;
},
},
);
return {
credits,
flights,
scene: {
canvas,
primitives: { add: (p) => p, remove() {} },
groundPrimitives: { add: (p) => p, remove() {} },
// Enough of a scene for the position marker to clamp to the ground.
frameState: { mode: Cesium.SceneMode.SCENE3D },
updateHeight: () => () => {},
getHeight: () => undefined,
},
camera,
creditDisplay: {
addStaticCredit: (credit) => credits.push(credit),
removeStaticCredit: (credit) => {
// Cesium ignores a credit it does not hold.
const at = credits.indexOf(credit);
if (at !== -1) credits.splice(at, 1);
},
},
};
}
/**
* A pinhole camera `altitude` m above WGS84, at `heading` (deg from north) and
* `pitch` (deg, negative down); `pickEllipsoid` hits whatever ellipsoid it gets.
@@ -138,6 +269,94 @@ export function rayCamera({
const hit = Cesium.IntersectionTests.rayEllipsoid(ray, ellipsoid);
return hit ? Cesium.Ray.getPoint(ray, hit.start) : undefined;
},
computeViewRectangle: () => undefined,
};
}
/** The centre of the tile holding a point at zoom `z`, so a small view is one tile. */
export function tileCentre(lon, lat, z = 14) {
const x = lonToTileX(lon, z);
const y = latToTileY(lat, z);
const { west, east, south, north } = tileBounds(x, y, z);
return {
tile: { x, y, z },
lon: (west + east) / 2,
lat: (south + north) / 2,
};
}
/** A scene collection that remembers what is on the globe. */
function sceneCollection() {
const items = new Set();
return {
items,
add(primitive) {
items.add(primitive);
return primitive;
},
remove(primitive) {
return items.delete(primitive);
},
};
}
/**
* A viewer looking straight down on a 0.004° square around `view`
* (`{lon, lat, height}`, mutable), enough for line coverage to attach,
* refresh and draw. Cesium's one-time terrain-height download is skipped.
*/
export function coverageViewer(view, t) {
const initialize = Cesium.GroundPolylinePrimitive.initializeTerrainHeights;
Cesium.GroundPolylinePrimitive.initializeTerrainHeights = () =>
Promise.resolve();
t?.after(() => {
Cesium.GroundPolylinePrimitive.initializeTerrainHeights = initialize;
});
// Node has no WebGL context to report line-width limits.
Cesium.ContextLimits._minimumAliasedLineWidth = 1;
Cesium.ContextLimits._maximumAliasedLineWidth = 10;
const listeners = () => {
const set = new Set();
return {
set,
addEventListener(listener) {
set.add(listener);
return () => set.delete(listener);
},
};
};
return {
view,
scene: {
canvas: { clientWidth: 100, clientHeight: 100 },
globe: { show: false, ellipsoid: Cesium.Ellipsoid.WGS84 },
frameState: { mode: Cesium.SceneMode.SCENE3D },
updateHeight: () => () => {},
getHeight: () => undefined,
groundPrimitives: sceneCollection(),
primitives: sceneCollection(),
postRender: listeners(),
preRender: listeners(),
},
camera: {
changed: new Cesium.Event(),
moveEnd: new Cesium.Event(),
get positionWC() {
return Cesium.Cartesian3.fromDegrees(view.lon, view.lat, view.height);
},
get positionCartographic() {
return {
longitude: view.lon * RAD,
latitude: view.lat * RAD,
height: view.height,
};
},
pickEllipsoid(point) {
return Cesium.Cartesian3.fromDegrees(
view.lon - 0.002 + (point.x / 100) * 0.004,
view.lat + 0.002 - (point.y / 100) * 0.004,
);
},
computeViewRectangle: () => undefined,
},
};
}
+22
View File
@@ -0,0 +1,22 @@
import { createFakeEngine } from '../globe/testing/fakeEngine.js';
/** A globe camera that follows the pose and events of a viewer test double. */
export function viewerEngine(viewer) {
const camera = viewer.camera;
const engine = createFakeEngine();
const initialPose = engine.camera.pose.bind(engine.camera);
engine.camera.pose = () => ({
...initialPose(),
cartographic: camera.positionCartographic,
heading: camera.heading ?? 0,
pitch: camera.pitch ?? 0,
roll: camera.roll ?? 0,
});
engine.camera.viewRectangle = () => camera.computeViewRectangle?.();
for (const event of ['moveStart', 'moveEnd', 'changed']) {
if (camera[event]) engine.camera[event] = camera[event];
}
if (camera.flyTo) engine.camera.flyTo = camera.flyTo.bind(camera);
if (camera.setView) engine.camera.setView = camera.setView.bind(camera);
return engine;
}
+16
View File
@@ -0,0 +1,16 @@
import { createPinia } from 'pinia';
import { useVoiceStore } from '../ui/stores/voice.js';
import { createVoiceControl } from '../voice/control.js';
/**
* A real voice control presenter on its own store, for owner tests that run
* without a page. Read what it shows from `ui.state`; report interactions
* with `ui.emit(name, ...args)`.
* @param {{panel?: boolean, pinia?: import('pinia').Pinia}} [options]
*/
export function createTestVoiceUi({
panel = false,
pinia = createPinia(),
} = {}) {
return createVoiceControl({ panel, store: useVoiceStore(pinia) });
}
+39
View File
@@ -0,0 +1,39 @@
import { createApp, h, nextTick } from 'vue';
import { createPinia, storeToRefs } from 'pinia';
import { useVoiceStore } from '../ui/stores/voice.js';
import VoiceControl from '../ui/views/panels/VoiceControl.vue';
/**
* Render whichever voice control the store presents, as the command dock
* does, into the current document. Import registerDom.mjs first.
* @param {import('node:test').TestContext} t
* @returns {{pinia: import('pinia').Pinia, settle: () => Promise<void>}}
*/
export function mountVoiceView(t) {
const doc = globalThis.document;
// happy-dom lacks the browser's `[hidden]` rule, which visibility checks
// and focus moves rely on.
if (!doc.getElementById('test-ua-hidden')) {
const style = doc.head.appendChild(doc.createElement('style'));
style.id = 'test-ua-hidden';
style.textContent = '[hidden] { display: none; }';
}
doc.body.replaceChildren();
const host = doc.body.appendChild(doc.createElement('div'));
const pinia = createPinia();
const { view } = storeToRefs(useVoiceStore(pinia));
const app = createApp({
render: () =>
view.value
? h(VoiceControl, { key: view.value.id, view: view.value })
: null,
}).use(pinia);
app.mount(host);
t.after(() => app.unmount());
// Renders, then any focus the owners asked for after it.
const settle = async () => {
await nextTick();
await nextTick();
};
return { pinia, settle };
}
+10
View File
@@ -0,0 +1,10 @@
import { GlobalRegistrator } from '@happy-dom/global-registrator';
/**
* Give a component test a browser document; returns the teardown.
* Call it from `before`/`after`, since other suites assert there is no DOM.
*/
export function installVueDom() {
GlobalRegistrator.register({ url: 'http://localhost/' });
return () => GlobalRegistrator.unregister();
}