Let the camera picker pick the opening CCTV camera

The picker preselected the active camera, and a native select fires no
change for the option it already shows. So while CCTV was still following
the view, choosing the camera the picker showed did nothing, and the next
pan switched to another camera.

The layer now reports whether the active camera is the opening one
(activeCameraProvisional). While it is, the picker shows that camera from
a hidden, disabled first option, so choosing it from the list is a change
and ends automatic selection; closing the list keeps it. A same-camera
pick that ends the opening pick notifies listeners so the picker drops the
hidden option, and reopenNearestCamera passes { opening: true } so its own
notification already carries the opening state.

docs/CURRENT-STATE.md now says when automatic selection ends. Tests cover
the hidden option, confirming and dismissing the picker before a pan, the
notification, and focusNearestToPoint, which is now on main.
This commit is contained in:
German Khokhlov committed 2026-11-20 01:10:42 +04:00
1 parent fe37cacba0
commit a6eecee157
12 files changed
+315 -30

No files matched your search

+20 -17
View File
@@ -11,6 +11,7 @@ import cctvLayer, {
_setCctvOverlayHostForTest,
reopenNearestCamera,
} from './cctv.js';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
const BASE = {
headingDeg: 41,
@@ -39,19 +40,9 @@ function record(id, lat, lon) {
}
function viewerAt(lat, lon) {
return {
entities: new Cesium.EntityCollection(),
const viewer = {
isDestroyed: () => false,
trackedEntity: null,
camera: {
positionWC: Cesium.Cartesian3.fromDegrees(lon, lat, 300),
positionCartographic: Cesium.Cartographic.fromDegrees(lon, lat, 300),
heading: 0.4,
pitch: -0.7,
roll: 0,
transform: Cesium.Matrix4.clone(Cesium.Matrix4.IDENTITY),
flyToBoundingSphere() {},
},
eye: { lat, lon, height: 300 },
scene: {
canvas: { clientWidth: 1200, clientHeight: 800 },
cartesianToCanvasCoordinates: () => undefined,
@@ -59,14 +50,20 @@ function viewerAt(lat, lon) {
requestRender() {},
},
};
// The layer reads the eye and flies through the renderer's camera port.
viewer.draw = bindFakeDraw(viewer, {
camera: {
pose: () => ({ ...viewer.eye }),
on: () => () => {},
followed: null,
flyToBounds() {},
},
}).draw;
return viewer;
}
function moveViewer(viewer, lat, lon) {
viewer.camera.positionCartographic = Cesium.Cartographic.fromDegrees(
lon,
lat,
300,
);
viewer.eye = { lat, lon, height: 300 };
}
function withReopenedLayer(fn) {
@@ -98,6 +95,7 @@ function withReopenedLayer(fn) {
moveViewer(viewer, 51.5131, -0.1291);
assert.equal(reopenNearestCamera(), true);
assert.equal(cctvLayer.getUIState().activeCameraId, 'b-cambridge');
assert.equal(cctvLayer.getUIState().activeCameraProvisional, true);
fn(viewer);
} finally {
globalThis.document = originalDocument;
@@ -114,11 +112,16 @@ for (const [name, pick] of [
'setParams({ selectedCameraId })',
() => cctvLayer.setParams({ selectedCameraId: 'b-cambridge' }),
],
[
'focusNearestToPoint',
() => cctvLayer.focusNearestToPoint(51.513, -0.129, { focus: false }),
],
]) {
test(`an explicit ${name} pick of the re-opened camera ends the opening pick`, () => {
withReopenedLayer((viewer) => {
pick();
assert.equal(cctvLayer.getUIState().activeCameraId, 'b-cambridge');
assert.equal(cctvLayer.getUIState().activeCameraProvisional, false);
// A later settled move (a pan, or the landing of the pick's own flight)
// leaves the explicit choice alone.
moveViewer(viewer, 51.5081, -0.1281);
+2 -3
View File
@@ -73,9 +73,8 @@ export function createNavigation({
return false;
const nearest = nearestCameraIdToViewer();
if (!nearest || nearest === layerState._activeCameraId) return false;
parts.selection.setActiveCamera(nearest);
// setActiveCamera ends the opening pick; this is still that pick.
layerState._openingCameraProvisional = true;
// Still the opening pick: its notification tells the picker so.
parts.selection.setActiveCamera(nearest, { opening: true });
return true;
}
+4
View File
@@ -286,6 +286,10 @@ export function createPresentation({
hoverId: layerState._hoverCardId,
},
activeCameraId: activeId,
// The camera CCTV opened on, following the view until someone picks one.
activeCameraProvisional: Boolean(
activeId && layerState._openingCameraProvisional,
),
activeCameraReselection: layerState._activeCameraReselection,
activeCamera: active ? getPublicCameraState(active, activeId) : null,
cameraIndex: cameraIndex(),
+10 -4
View File
@@ -49,10 +49,13 @@ export function createSelection({
* Sets the active camera by ID, initializes its projection runtime, refreshes
* its frame, and updates styles.
* @param {string} cameraId - ID of the camera to activate.
* @param {Object} [options]
* @param {boolean} [options.opening=false] - The opening camera following
* the view, not someone's pick: settled moves may still replace it.
* @returns {'activated'|'unchanged'|'not-found'} Discriminated activation result.
*/
function setActiveCamera(cameraId) {
function setActiveCamera(cameraId, { opening = false } = {}) {
if (!cameraId || !layerState._recordById.has(cameraId))
return CCTV_ACTIVATION_RESULT.NOT_FOUND;
const record = layerState._recordById.get(cameraId);
@@ -71,19 +74,22 @@ export function createSelection({
)
) {
// Picking the camera a settled move re-opened is still a choice: later
// settled moves must leave it alone.
layerState._openingCameraProvisional = false;
// settled moves must leave it alone, and the picker learns it.
const endsOpening = layerState._openingCameraProvisional && !opening;
if (endsOpening) layerState._openingCameraProvisional = false;
// Browser-only feeds have a separate player; a reselect retries it
// without re-running activation or touching the projection geometry.
if (parts.model.isBrowserOverlayCamera(record.camera)) {
layerState._activeCameraReselection += 1;
parts.presentation.notifyListeners();
} else if (endsOpening) {
parts.presentation.notifyListeners();
}
return CCTV_ACTIVATION_RESULT.UNCHANGED;
}
layerState._activeCameraId = cameraId;
layerState._autoHopSuspended = false;
layerState._openingCameraProvisional = false;
layerState._openingCameraProvisional = opening;
// A real activation creates projection work — wake the self-stopping loop.
parts.projection.startProjectionLoop();
if (previousActiveRecord && previousActiveRecord !== record) {
+13
View File
@@ -52,3 +52,16 @@ test('same-camera selection notifies browser-overlay feeds so playback can retry
assert.equal(fixture.state._activeCameraReselection, 1);
assert.equal(fixture.notifications(), 1);
});
test('same-camera selection ends the opening pick and tells the panel once', () => {
const fixture = makeSelection('tripcheck-odot');
fixture.state._openingCameraProvisional = true;
assert.equal(
fixture.selection.setActiveCamera('same-camera'),
CCTV_ACTIVATION_RESULT.UNCHANGED,
);
assert.equal(fixture.state._openingCameraProvisional, false);
assert.equal(fixture.state._activeCameraReselection, 0);
assert.equal(fixture.notifications(), 1);
});
+10 -1
View File
@@ -5,7 +5,9 @@ import { useCctvStore } from '../stores/cctv.js';
// The camera picker: the cameras in view and a closing note for those the
// view leaves out. It renders only when CctvControls publishes a picker,
// which re-applies the active camera, as on every layer notification.
// which re-applies the active camera, as on every layer notification. The
// opening camera, which follows the view until someone picks one, shows in a
// hidden first option: choosing that camera from the list is a change.
const { picker } = storeToRefs(useCctvStore());
// The selection, applied once the options are in place.
@@ -21,6 +23,13 @@ const vPick = { mounted: pick, updated: pick };
<template>
<UiSelect v-pick="picker?.selection" :disabled="picker?.disabled"
><option
v-if="picker?.opening"
value=""
hidden
disabled
data-cctv-opening
>{{ picker.opening }}</option
><option
v-for="option in picker?.options"
:key="option.value"
+24
View File
@@ -226,3 +226,27 @@ test('an active id without its camera record leaves the pick alone', async (t) =
});
assert.equal(select.value, 'b');
});
test('the opening camera shows in a hidden first option', async (t) => {
const { select, render, values } = fixture(t);
const [a, b] = [camera('a'), camera('b')];
const state = {
enabled: true,
count: 2,
cameraIndex: [b, a],
activeCameraId: 'b',
activeCamera: b,
};
await render({ ...state, activeCameraProvisional: true });
assert.deepEqual(values(), ['', 'b', 'a']);
assert.equal(select.selectedIndex, 0);
const opening = select.options[0];
assert.equal(opening.textContent, 'Austin · Cam b');
assert.equal(opening.hidden, true);
assert.equal(opening.disabled, true);
assert.equal(opening.dataset.cctvOpening, '');
await render(state);
assert.deepEqual(values(), ['b', 'a'], 'a picked camera has no hidden option');
assert.equal(select.value, 'b');
});
+205
View File
@@ -0,0 +1,205 @@
// src/ui/cctvPickerOpening.test.mjs — the picker can pick the opening camera.
// The opening camera follows the view until someone picks one. A native
// select fires no change for the option it already shows, so the picker keeps
// that camera in a hidden first option: choosing it from the list is a change
// and ends the opening pick, while closing the list leaves it.
import '../testSupport/registerDom.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createPinia } from 'pinia';
import { createApp, nextTick } from 'vue';
import cctvLayer, {
_setCctvCoverageStateForTest,
_setCctvOverlayHostForTest,
reopenNearestCamera,
} from '../data/cctv.js';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
import { CctvControls } from './cctvControls.js';
import { useCctvStore } from './stores/cctv.js';
import CctvPanel from './views/panels/CctvPanel.vue';
const TRAFALGAR = [51.508, -0.128];
const CAMBRIDGE = [51.513, -0.129];
function record(id, [lat, lon]) {
return {
camera: {
id,
name: `Camera ${id}`,
city: 'London',
lat,
lon,
headingDeg: 41,
pitchDeg: -5,
fovDeg: 56,
rangeM: 210,
mountHeightM: 100,
groundElevationM: 0,
},
coverageEntities: [],
projection: null,
activationDone: true,
groundResolved: {},
groundSamples: {},
groundPrior: 0,
frustumGeometry: null,
frustumPositions: null,
probeClampRangeM: null,
position: Cesium.Cartesian3.fromDegrees(lon, lat, 100),
};
}
function viewerAt([lat, lon]) {
const viewer = {
isDestroyed: () => false,
eye: { lat, lon, height: 300 },
scene: {
canvas: { clientWidth: 1200, clientHeight: 800 },
cartesianToCanvasCoordinates: () => undefined,
primitives: { add: (p) => p, remove: () => true },
requestRender() {},
},
};
// The layer reads the eye and flies through the renderer's camera port.
viewer.draw = bindFakeDraw(viewer, {
camera: {
pose: () => ({ ...viewer.eye }),
on: () => () => {},
followed: null,
flyToBounds() {},
},
}).draw;
return viewer;
}
/** A settled move: the view is now over `[lat, lon]`. */
function settleOver(viewer, [lat, lon]) {
viewer.eye = { lat, lon, height: 300 };
return reopenNearestCamera();
}
/**
* CCTV opened at Trafalgar Square, then a settled move re-opened it at
* Cambridge Circus; the panel is connected to the layer.
*/
async function reopenedAtCambridge(t) {
_setCctvOverlayHostForTest({
setEntries() {},
setVisible() {},
clearSource() {},
});
// Activation builds the frame image and asks for ground heights; this test
// has no server. happy-dom's request timeout would hold the run open 30 s.
const originalImage = globalThis.Image;
const originalFetch = globalThis.fetch;
const originalTimeout = AbortSignal.timeout;
globalThis.Image = class {};
globalThis.fetch = async () => {
throw new TypeError('no server in this test');
};
AbortSignal.timeout = () => new AbortController().signal;
const trafalgar = record('a-trafalgar', TRAFALGAR);
const cambridge = record('b-cambridge', CAMBRIDGE);
// enable() assigned the opening camera without activating it.
trafalgar.activationDone = false;
const viewer = viewerAt(TRAFALGAR);
_setCctvCoverageStateForTest({
viewer,
records: [trafalgar, cambridge],
activeCameraId: 'a-trafalgar',
enabled: true,
openingCameraProvisional: true,
});
document.body.replaceChildren();
const host = document.body.appendChild(document.createElement('div'));
const pinia = createPinia();
const app = createApp(CctvPanel).use(pinia);
app.mount(host);
const select = document.getElementById('cctv-camera-select');
const controls = new CctvControls({
elements: {
_cctvPanel: document.getElementById('cctv-panel'),
_cctvSelect: select,
},
cctv: cctvLayer,
actions: {
isEnabled: () => true,
toggleEnabled: async () => true,
runExplicitFocus(select, focus) {
const cameraId = select();
if (cameraId) focus(cameraId);
},
setParams: (params) => cctvLayer.setParams(params),
setPanelCollapsed() {},
syncViewport() {},
},
store: useCctvStore(pinia),
});
controls.connect();
t.after(() => {
controls.destroy();
app.unmount();
globalThis.Image = originalImage;
globalThis.fetch = originalFetch;
AbortSignal.timeout = originalTimeout;
_setCctvOverlayHostForTest();
_setCctvCoverageStateForTest({ enabled: false });
});
assert.equal(settleOver(viewer, CAMBRIDGE), true);
await nextTick();
assert.equal(cctvLayer.getUIState().activeCameraId, 'b-cambridge');
return { viewer, select };
}
/** The label of the opening camera's hidden option, or null. */
function openingLabel(select) {
return (
select.querySelector('option[data-cctv-opening]')?.textContent ?? null
);
}
test('the opening camera shows as itself, from a hidden option', async (t) => {
const { select } = await reopenedAtCambridge(t);
assert.equal(openingLabel(select), 'London · Camera b-cambridge');
assert.equal(select.selectedIndex, 0, 'the closed picker shows it');
const opening = select.options[0];
assert.equal(opening.dataset.cctvOpening, '');
assert.equal(opening.hidden, true, 'the open list does not show it twice');
assert.equal(opening.disabled, true);
assert.ok(
[...select.options].some((option) => option.value === 'b-cambridge'),
'the camera itself stays in the list to be picked',
);
});
test('choosing the shown camera from the picker keeps it after a pan', async (t) => {
const { viewer, select } = await reopenedAtCambridge(t);
select.value = 'b-cambridge';
select.dispatchEvent(new Event('change'));
// The change handler waits for the layer switch before it picks.
await new Promise((resolve) => setTimeout(resolve, 0));
await nextTick();
assert.equal(cctvLayer.getUIState().activeCameraProvisional, false);
assert.equal(openingLabel(select), null);
assert.equal(select.value, 'b-cambridge');
assert.equal(settleOver(viewer, TRAFALGAR), false);
assert.equal(cctvLayer.getUIState().activeCameraId, 'b-cambridge');
});
test('closing the picker without a choice lets the camera follow a pan', async (t) => {
const { viewer, select } = await reopenedAtCambridge(t);
select.focus();
select.blur();
await nextTick();
assert.equal(cctvLayer.getUIState().activeCameraProvisional, true);
assert.equal(settleOver(viewer, TRAFALGAR), true);
await nextTick();
assert.equal(cctvLayer.getUIState().activeCameraId, 'a-trafalgar');
assert.equal(openingLabel(select), 'London · Camera a-trafalgar');
assert.equal(select.selectedIndex, 0);
});
+10 -2
View File
@@ -253,15 +253,23 @@ export function _renderCctvState(state) {
};
}
this._picker = picker;
// The opening camera follows the view until someone picks one. The picker
// shows it in a hidden first option, so choosing it from the list changes
// the value and counts as that pick; closing the list leaves it as is.
const opening = Boolean(
state?.activeCameraProvisional && activeId && activeCamera,
);
this.store.setPicker({
options: picker?.options || [],
note: picker?.note || '',
opening: opening ? pickerOption(activeCamera, activeId).label : '',
disabled,
// The active camera is always one of the listed records. With nothing
// active the closed picker shows the note when nothing is in view; a
// focused picker keeps its old options, so it only clears.
selection:
activeId && activeCamera
selection: opening
? { index: 0 }
: activeId && activeCamera
? { value: activeId }
: !activeId
? { index: !picking && cameras.length === 0 && outside ? 0 : -1 }
+3 -2
View File
@@ -25,8 +25,9 @@ export const useCctvStore = defineStore('gev-cctv', () => {
/** `{label, state}` for the source badge; null until first synced. */
const sourceBadge = shallowRef(null);
/**
* The camera picker: `{options: [{value, label}], note, disabled,
* selection: {value}|{index}|null}`; null until first rendered.
* The camera picker: `{options: [{value, label}], note, opening, disabled,
* selection: {value}|{index}|null}`; null until first rendered. `opening`
* labels the opening camera's hidden first option, or is empty.
*/
const picker = shallowRef(null);
/** The scene summary as typed so far; null until the first one. */