merge feat/voice-outlines 3ac3499e into the review fixes

This commit is contained in:
Sameh Khamis committed 2026-11-02 13:14:02 -08:00
commit b9f3dd649e
78 files changed
+2579 -379

No files matched your search

+142 -1
View File
@@ -5,6 +5,7 @@ import { greatCircleMeters } from '../geoDistance.js';
import {
holdContinuousRender,
releaseContinuousRender,
governorRequestRender,
} from '../renderGovernor.js';
import {
isRateLimitedOutcome,
@@ -154,6 +155,17 @@ export function createAnnotationEngine({
// task with the FINAL outcome — resolved or failed — so narration that said
// "tracing the boundary now" can later honestly confirm or correct itself.
const outlineListeners = new Set();
// Told whenever the set of marks, or one mark's look, changes (Draw's list).
const changeListeners = new Set();
const notifyChange = () => {
for (const listener of changeListeners) {
try {
listener();
} catch {
/* one listener's failure must not stop the others */
}
}
};
function emitOutlineEvent(evt) {
for (const listener of outlineListeners) {
@@ -199,8 +211,11 @@ export function createAnnotationEngine({
// World annotations carry persistent per-frame scene animation (pulsing
// live colors, camera-scaled rings, route-flow uniforms in the renderer),
// so the scene must render continuously while any mark exists. (perf wave 2)
// Only a mark someone can see needs every frame drawn: a board of marks
// hidden from Draw's list lets the scene idle.
function syncAnnotationHold() {
if (annotations.size > 0) holdContinuousRender('annotations');
const visible = [...annotations.values()].some((anno) => !anno.hidden);
if (visible) holdContinuousRender('annotations');
else releaseContinuousRender('annotations');
}
@@ -340,6 +355,7 @@ export function createAnnotationEngine({
const now = performance.now();
let changed = false;
let pending = false; // any mark still fading in / out, or with a TTL fade ahead
let expired = false;
for (const anno of annotations.values()) {
const next = computeAlpha(anno, now);
if (next !== anno.alpha) {
@@ -351,6 +367,7 @@ export function createAnnotationEngine({
removeRendered(anno);
annotations.delete(anno.id);
changed = true;
expired = true;
} catch {
// Leave failed cleanup addressable without stopping every other mark's tick.
anno.cleanupPending = true;
@@ -362,7 +379,11 @@ export function createAnnotationEngine({
if (changed) {
renderer.sync(annotations);
syncAnnotationHold();
// The frame that takes a just-hidden mark off: with every mark hidden
// the hold is gone, and nothing else would draw it.
governorRequestRender('annotations');
}
if (expired) notifyChange();
// Stop once the board is STABLE — persistent marks (persist=true is the default)
// finish fading in after ~260ms and never change again, so without this the loop
// would spin O(N) every frame forever. ensureTicking() restarts on the next
@@ -845,6 +866,7 @@ export function createAnnotationEngine({
if (ids.length) {
renderer.sync(annotations);
ensureTicking();
notifyChange();
}
if (opts.flyTo && firstAnchor) frameAnnotation(firstAnchor);
else if (ids.length) ensureMarksVisible(ids);
@@ -1341,6 +1363,11 @@ export function createAnnotationEngine({
* degenerate geocode stacks on one point (several Capitol monuments) would erase each other. */
function findDuplicate(anno) {
if (!anno.anchor) return null;
// A shape drawn by hand is always new: each click is meant, and every
// shape is unnamed until its row names it, so two nearby pins would
// otherwise read as one and the second would replace or vanish into the
// first.
if (anno.manual) return null;
const near = (a, b) =>
a &&
b &&
@@ -1358,6 +1385,10 @@ export function createAnnotationEngine({
};
for (const ex of annotations.values()) {
if (ex.type !== anno.type || !ex.anchor) continue;
// A shape drawn by hand and a voice mark are never the same mark: a
// match would let a voice TTL expire the drawn one, or replace it. A
// hidden mark is not refreshed either; a new shape there is new.
if (Boolean(ex.manual) !== Boolean(anno.manual) || ex.hidden) continue;
// Identity is GEOMETRY, not label: "Marina" and "Marina District" resolve to the SAME
// polygon/anchor and must collapse to one mark (the caller replaces label/color in place
// so the latest caption wins). Resolution is deterministic, so the same place re-resolves
@@ -1430,6 +1461,11 @@ export function createAnnotationEngine({
alpha: 0, // animate in
bornAt: now,
expiring: false,
// Drawn by hand (drawTool.js): listed under Draw, renamed and recoloured
// there. `name` is the person's own label, before any distance is added.
manual: spec?.manual === true,
name: spec?.manual === true ? cleanLabel(spec?.label) || null : null,
hidden: false,
};
if (type === 'route') {
@@ -1523,9 +1559,102 @@ export function createAnnotationEngine({
}
renderer.sync(annotations);
syncAnnotationHold();
notifyChange();
if (failure) throw failure;
}
/** Take one mark off the board at once. */
function remove(id) {
const anno = annotations.get(id);
if (!anno) return false;
// Through removeRendered, like clear(): a failed cleanup leaves the mark on
// the board, still addressable, instead of an orphan nothing owns.
removeRendered(anno);
annotations.delete(id);
renderer.sync(annotations);
syncAnnotationHold();
notifyChange();
return true;
}
/** Hide or show one mark; a hidden mark stays on the board at alpha 0. */
function setHidden(id, hidden) {
const anno = annotations.get(id);
if (!anno) return false;
anno.hidden = Boolean(hidden);
// Skip the fade-in, so showing it again is immediate.
anno.bornAt = Math.min(anno.bornAt, performance.now() - 260);
// Take it off (or put it back) now, not when its alpha next changes: a
// mark hidden before its first frame has no alpha change to wait for.
renderer.sync(annotations);
syncAnnotationHold();
governorRequestRender('annotations');
ensureTicking();
notifyChange();
return true;
}
/**
* Rename or recolour a hand-drawn mark. The renderers build a mark's look
* when it is added, so the mark is added again with the new look.
*/
function restyle(id, { name, color } = {}) {
const anno = annotations.get(id);
if (!anno?.manual) return false;
if (name !== undefined) {
anno.name = cleanLabel(name) || null;
anno.label =
anno.type === 'route'
? composeRouteLabel(anno.name, anno.distanceM, null, 'manual', false)
: anno.name;
}
if (color !== undefined && COLORS.has(color)) anno.color = color;
renderer.remove(anno);
try {
renderer.add(anno);
} catch (error) {
rollbackRendererState(anno);
annotations.delete(id);
renderer.sync(annotations);
syncAnnotationHold();
notifyChange();
throw error;
}
renderer.sync(annotations);
ensureTicking();
notifyChange();
return true;
}
/** Fly the camera to one mark; a line is framed whole, not by its start. */
function frame(id) {
const anno = annotations.get(id);
if (!anno) return false;
if (anno.type === 'route' && anno.path?.length) {
const ring = anno.path.map((p) => [p.lon, p.lat]);
// Unwrap around the first vertex, as ringRange does, so a line across
// the antimeridian is centred on it, not on the far side of the globe.
const ref = ring[0][0];
const lons = ring.map(
([lon]) => lon - 360 * Math.round((lon - ref) / 360),
);
const lats = ring.map(([, lat]) => lat);
const midLon = (Math.min(...lons) + Math.max(...lons)) / 2;
frameAnnotation({
...anno,
to: null,
ring,
polygons: null,
anchor: {
lon: ((((midLon + 180) % 360) + 360) % 360) - 180,
lat: (Math.min(...lats) + Math.max(...lats)) / 2,
height: 0,
},
});
} else frameAnnotation(anno);
return true;
}
/** Begin a graceful fade-out of everything, then remove. */
function fadeOutAll() {
const now = performance.now();
@@ -1654,6 +1783,16 @@ export function createAnnotationEngine({
const engine = {
annotate,
clear,
remove,
setHidden,
restyle,
frame,
/** Subscribe to board changes; returns an unsubscribe fn. */
onChange(listener) {
if (destroyed || typeof listener !== 'function') return () => {};
changeListeners.add(listener);
return () => changeListeners.delete(listener);
},
destroy() {
if (destroyed) return;
destroyed = true;
@@ -1663,6 +1802,7 @@ export function createAnnotationEngine({
if (tickHandle != null) cancelAnimationFrame(tickHandle);
tickHandle = null;
outlineListeners.clear();
changeListeners.clear();
releaseContinuousRender('annotations');
renderer.destroy();
}
@@ -1970,6 +2110,7 @@ function normalizeType(type) {
}
function computeAlpha(anno, now) {
if (anno.hidden) return 0;
const inT = (now - anno.bornAt) / 260;
const fadeIn = inT >= 1 ? 1 : Math.max(0, inT);
+387 -15
View File
@@ -12,6 +12,7 @@ import { createStandalonePlaceSearch } from '../standalone/placeSearch.js';
//
// Run with: npm test (node --test)
import { test } from 'node:test';
import * as Cesium from 'cesium';
import assert from 'node:assert/strict';
import {
createAnnotationEngine,
@@ -21,6 +22,7 @@ import {
import { resolveAnnotationTarget } from './annotationResolver.js';
import {
getRenderGovernorDiagnostics,
installRenderGovernor,
_resetRenderGovernorForTest,
} from '../renderGovernor.js';
@@ -1230,6 +1232,7 @@ test('only an explicit navigation request permits resolving distant annotation t
engine.destroy();
});
test('recaption inherits outline credit from borrowed geometry rather than its new anchor', async (t) => {
installAnimationFrameStubs(t);
const { renderer } = fakeRenderer();
@@ -1249,6 +1252,390 @@ test('recaption inherits outline credit from borrowed geometry rather than its n
engine.clear();
});
// Draw's list works one hand-drawn mark at a time: hide, rename, recolour,
// frame and remove it, and hear about every change to the board.
test('hand-drawn marks: one mark can be hidden, renamed, recoloured, framed and removed', async (t) => {
installAnimationFrameStubs(t);
_resetRenderGovernorForTest();
t.after(() => _resetRenderGovernorForTest());
const { renderer, calls } = fakeRenderer();
const flights = [];
const engine = createAnnotationEngine({
viewer: { camera: { heading: 0, flyToBoundingSphere: (sphere) => flights.push(sphere) } },
renderer,
});
let changes = 0;
const unsubscribe = engine.onChange(() => { changes += 1; });
const drawn = await engine.annotate([
{ type: 'route', manual: true, path: [[-97.75, 30.26], [-97.73, 30.27]], label: '' },
{ type: 'pin', manual: true, latitude: 30.27, longitude: -97.74, label: 'Camp', color: 'amber' },
], { persist: true });
assert.equal(drawn.drawn, 2);
assert.equal(changes, 1, 'one annotate, one change');
const [line, pin] = engine.list();
assert.equal(line.manual, true);
assert.equal(line.name, null);
assert.match(line.label, /km|m$/, 'an unnamed line is labelled by its length');
assert.equal(pin.name, 'Camp');
assert.equal(engine.setHidden(pin.id, true), true);
assert.equal(pin.hidden, true);
assert.equal(changes, 2);
const addsBefore = calls.add;
assert.equal(engine.restyle(line.id, { name: 'Ridge walk', color: 'green' }), true);
assert.equal(line.name, 'Ridge walk');
assert.match(line.label, /^Ridge walk — /, 'a renamed line keeps its length');
assert.equal(line.color, 'green');
assert.equal(calls.add, addsBefore + 1, 'the new look is drawn again');
assert.equal(engine.restyle(line.id, { color: 'not-a-colour' }), true);
assert.equal(line.color, 'green', 'an unknown colour is ignored');
assert.equal(engine.frame(line.id), true);
assert.equal(flights.length, 1);
assert.equal(engine.frame('anno-missing'), false);
assert.equal(engine.remove(pin.id), true);
assert.deepEqual(engine.list().map(({ id }) => id), [line.id]);
assert.equal(engine.remove(pin.id), false);
engine.clear();
assert.equal(engine.list().length, 0);
const seen = changes;
unsubscribe();
await engine.annotate([{ type: 'pin', manual: true, latitude: 1, longitude: 1 }], { persist: true });
assert.equal(changes, seen, 'an unsubscribed listener hears nothing');
});
// The list trusts these calls to change the globe, not just the list: each
// is checked by its effect (renderer calls, alpha, camera, notifications).
test('hand-drawn marks: remove, hide, clear, expiry and framing have their effect', async (t) => {
const frames = [];
const originalRequestAnimationFrame = globalThis.requestAnimationFrame;
const originalCancelAnimationFrame = globalThis.cancelAnimationFrame;
globalThis.requestAnimationFrame = (callback) => frames.push(callback);
globalThis.cancelAnimationFrame = () => {};
let now = 1_000_000;
t.mock.method(performance, 'now', () => now);
_resetRenderGovernorForTest();
t.after(() => {
globalThis.requestAnimationFrame = originalRequestAnimationFrame;
globalThis.cancelAnimationFrame = originalCancelAnimationFrame;
_resetRenderGovernorForTest();
});
const runFrames = () => {
for (let i = 0; i < 5 && frames.length; i += 1) frames.shift()();
};
const { renderer, calls } = fakeRenderer();
const flights = [];
const engine = createAnnotationEngine({
viewer: {
camera: {
heading: 0,
flyToBoundingSphere: (sphere) => flights.push(sphere),
},
},
renderer,
});
let changes = 0;
engine.onChange(() => {
changes += 1;
});
await engine.annotate(
[
{
type: 'pin',
manual: true,
latitude: 30.27,
longitude: -97.74,
label: 'Camp',
},
{
type: 'pin',
manual: true,
latitude: 30.3,
longitude: -97.7,
label: 'Base',
},
],
{ persist: true },
);
now += 1000;
runFrames();
const [camp, base] = engine.list();
assert.equal(camp.alpha, 1);
engine.setHidden(camp.id, true);
runFrames();
assert.equal(camp.alpha, 0, 'a hidden mark is drawn at alpha 0');
assert.ok(engine.list().includes(camp), 'and stays on the board');
engine.setHidden(camp.id, false);
runFrames();
assert.equal(camp.alpha, 1, 'showing it again is immediate, with no fade-in');
const removes = calls.remove;
let seen = changes;
engine.remove(base.id);
assert.equal(calls.remove, removes + 1, 'remove takes it off the globe');
assert.equal(changes, seen + 1, 'and tells the list');
seen = changes;
engine.clear();
assert.equal(changes, seen + 1, 'a clear tells the list');
// A voice mark with a TTL: its expiry must reach the list too.
await engine.annotate(
[{ type: 'pin', latitude: 1, longitude: 1, label: 'Brief' }],
{
persist: false,
ttlMs: 2000,
},
);
seen = changes;
now += 60_000;
runFrames();
assert.equal(engine.list().length, 0, 'the mark expired');
assert.equal(changes, seen + 1, 'expiry tells the list');
// A line across the antimeridian is framed there, not on the far side.
await engine.annotate(
[
{
type: 'route',
manual: true,
path: [
[179.9, -17],
[-179.9, -17.1],
],
label: '',
},
],
{ persist: true },
);
const [line] = engine.list();
engine.frame(line.id);
const centre = Cesium.Cartographic.fromCartesian(flights.at(-1).center);
assert.ok(
Math.abs(Math.abs(Cesium.Math.toDegrees(centre.longitude)) - 180) < 0.5,
`framed at ${Cesium.Math.toDegrees(centre.longitude)}°, not near 180°`,
);
});
test('hand-drawn marks: a voice mark or a hidden mark is not taken as their duplicate', async (t) => {
installAnimationFrameStubs(t);
_resetRenderGovernorForTest();
t.after(() => _resetRenderGovernorForTest());
const { renderer } = fakeRenderer();
const engine = createAnnotationEngine({ viewer: {}, renderer });
await engine.annotate(
[
{
type: 'pin',
manual: true,
latitude: 30.27,
longitude: -97.74,
label: 'Camp',
},
],
{ persist: true },
);
const [drawn] = engine.list();
// The agent marks the same spot with the same label, briefly.
await engine.annotate(
[{ type: 'pin', latitude: 30.27, longitude: -97.74, label: 'Camp' }],
{
persist: false,
},
);
assert.equal(engine.list().length, 2, 'the voice mark is its own mark');
assert.equal(drawn.ttlMs, null, 'the drawn pin keeps persisting');
assert.equal(drawn.manual, true);
engine.setHidden(drawn.id, true);
const again = await engine.annotate(
[
{
type: 'pin',
manual: true,
latitude: 30.27,
longitude: -97.74,
label: 'Camp',
},
],
{ persist: true },
);
assert.equal(again.drawn, 1);
const visible = engine.list().filter((mark) => mark.manual && !mark.hidden);
assert.equal(
visible.length,
1,
'a pin dropped on a hidden one is a new, visible pin',
);
});
test('hand-drawn marks: only a manual mark can be restyled', async (t) => {
installAnimationFrameStubs(t);
_resetRenderGovernorForTest();
t.after(() => _resetRenderGovernorForTest());
const { renderer } = fakeRenderer();
const engine = createAnnotationEngine({
viewer: {},
renderer,
resolveTarget: async () => ({ ...FIXED_POINT }),
});
await engine.annotate([{ type: 'point', target: 'Texas Capitol', label: 'Capitol' }]);
const [voiceMark] = engine.list();
assert.equal(voiceMark.manual, false);
assert.equal(engine.restyle(voiceMark.id, { name: 'Renamed' }), false);
assert.equal(voiceMark.label, 'Capitol');
});
test('a drawn line that rounds up to the next unit is labelled in it, not as 1000 m or 10.0 km', async (t) => {
installAnimationFrameStubs(t);
const labels = [];
const renderer = { add(anno) { labels.push(anno.label); }, update() {}, remove() {}, sync() {}, destroy() {} };
const engine = createAnnotationEngine({ viewer: {}, renderer });
const metresPerDegree = (6371.0088 * 1000 * Math.PI) / 180;
for (const metres of [994, 996, 9940, 9960]) {
await engine.annotate([
{ type: 'route', manual: true, path: [[0, 0], [0, metres / metresPerDegree]] },
]);
}
assert.deepEqual(labels, ['990 m', '1.0 km', '9.9 km', '10 km']);
engine.destroy();
});
test('hand-drawn marks: two unnamed pins close together are two pins, whatever their colours', async (t) => {
installAnimationFrameStubs(t);
_resetRenderGovernorForTest();
t.after(() => _resetRenderGovernorForTest());
const { renderer } = fakeRenderer();
const engine = createAnnotationEngine({ viewer: {}, renderer });
const pin = (lon, color) => ({ type: 'pin', manual: true, latitude: 30.27, longitude: lon, label: '', color });
await engine.annotate([pin(-97.74, 'primary')], { persist: true });
await engine.annotate([pin(-97.7402, 'primary')], { persist: true });
await engine.annotate([pin(-97.7404, 'red')], { persist: true });
assert.deepEqual(
engine.list().map(({ color }) => color),
['primary', 'primary', 'red'],
'no drawn pin is dropped or replaced by the next',
);
});
test('hand-drawn marks: hiding a mark before its first frame takes it off at once', async (t) => {
installAnimationFrameStubs(t);
_resetRenderGovernorForTest();
t.after(() => _resetRenderGovernorForTest());
let syncs = 0;
const renderer = { add() {}, update() {}, remove() {}, sync() { syncs += 1; }, destroy() {} };
const engine = createAnnotationEngine({ viewer: {}, renderer });
await engine.annotate([{ type: 'pin', manual: true, latitude: 1, longitude: 1 }], { persist: true });
const [mark] = engine.list();
const before = syncs;
engine.setHidden(mark.id, true);
assert.ok(syncs > before, 'the renderer hears about it now');
assert.ok(
!getRenderGovernorDiagnostics().holds.includes('annotations'),
'and the render hold goes with the last visible mark',
);
});
test('hand-drawn marks: with every mark hidden the scene idles, and showing one wakes it', async (t) => {
installAnimationFrameStubs(t);
_resetRenderGovernorForTest();
t.after(() => _resetRenderGovernorForTest());
let renders = 0;
installRenderGovernor({ scene: { requestRenderMode: true, requestRender: () => (renders += 1) } });
const { renderer } = fakeRenderer();
const engine = createAnnotationEngine({ viewer: {}, renderer });
await engine.annotate([
{ type: 'pin', manual: true, latitude: 1, longitude: 1 },
{ type: 'pin', manual: true, latitude: 2, longitude: 2 },
], { persist: true });
const [first, second] = engine.list();
const held = () => getRenderGovernorDiagnostics().holds.includes('annotations');
assert.ok(held(), 'visible marks keep the scene drawing');
engine.setHidden(first.id, true);
assert.ok(held(), 'one visible mark is enough');
const before = renders;
engine.setHidden(second.id, true);
assert.equal(held(), false, 'every mark hidden: the scene idles');
assert.ok(renders > before, 'after one last frame that takes them off');
engine.setHidden(second.id, false);
assert.ok(held(), 'showing one wakes it again');
});
test('hand-drawn marks: a restyle the renderer cannot draw takes the mark off and says so', async (t) => {
installAnimationFrameStubs(t);
_resetRenderGovernorForTest();
t.after(() => _resetRenderGovernorForTest());
const { renderer, failAddOnce } = throwingRendererHarness();
let syncs = 0;
renderer.sync = () => (syncs += 1);
const engine = createAnnotationEngine({ viewer: {}, renderer });
await engine.annotate([{ type: 'pin', manual: true, latitude: 1, longitude: 1 }], { persist: true });
const [mark] = engine.list();
let changes = 0;
engine.onChange(() => (changes += 1));
const before = syncs;
failAddOnce();
assert.throws(() => engine.restyle(mark.id, { color: 'red' }), /WebGL context lost/);
assert.equal(engine.list().length, 0, 'no ghost row is left behind');
assert.equal(changes, 1, 'the list hears about it');
assert.ok(syncs > before, 'and the renderer is told');
});
test('hand-drawn marks: a mark shown again right after it was drawn appears at once, not fading in', async (t) => {
_resetRenderGovernorForTest();
t.after(() => _resetRenderGovernorForTest());
const queued = [];
const raf = globalThis.requestAnimationFrame;
const caf = globalThis.cancelAnimationFrame;
globalThis.requestAnimationFrame = (callback) => queued.push(callback);
globalThis.cancelAnimationFrame = () => {};
t.after(() => {
globalThis.requestAnimationFrame = raf;
globalThis.cancelAnimationFrame = caf;
});
const tick = () => queued.splice(0).forEach((callback) => callback());
const { renderer } = fakeRenderer();
const engine = createAnnotationEngine({ viewer: {}, renderer });
await engine.annotate([{ type: 'pin', manual: true, latitude: 1, longitude: 1 }], { persist: true });
const [mark] = engine.list();
engine.setHidden(mark.id, true);
tick();
assert.equal(mark.alpha, 0);
engine.setHidden(mark.id, false);
tick();
assert.equal(mark.alpha, 1, 'no fade-in after a hide');
});
test('removing one mark whose cleanup fails keeps it addressable for a retry', async (t) => {
installAnimationFrameStubs(t);
_resetRenderGovernorForTest();
t.after(() => _resetRenderGovernorForTest());
const { renderer, calls } = fakeRenderer();
let failRemove = true;
renderer.remove = () => {
calls.remove += 1;
if (failRemove) throw new Error('renderer remove failed');
};
const engine = createAnnotationEngine({ viewer: { camera: { heading: 0 } }, renderer });
await engine.annotate([
{ type: 'pin', manual: true, latitude: 30.27, longitude: -97.74, label: 'Camp' },
], { persist: true });
const [pin] = engine.list();
assert.throws(() => engine.remove(pin.id), /renderer remove failed/);
assert.deepEqual(engine.list().map(({ id }) => id), [pin.id], 'the mark is not orphaned');
assert.equal(pin.cleanupPending, true);
failRemove = false;
assert.equal(engine.remove(pin.id), true);
assert.deepEqual(engine.list(), []);
assert.equal(pin.cleanupPending, undefined);
});
test('a building install in the batch does not re-judge marks that never installed', async (t) => {
installAnimationFrameStubs(t);
const h = controlledBuildingRenderer();
@@ -1301,18 +1688,3 @@ test('plain recaption keeps the old mark addressable when its removal throws', a
);
assert.equal(engine.count(), 0);
});
test('a drawn line that rounds up to the next unit is labelled in it, not as 1000 m or 10.0 km', async (t) => {
installAnimationFrameStubs(t);
const labels = [];
const renderer = { add(anno) { labels.push(anno.label); }, update() {}, remove() {}, sync() {}, destroy() {} };
const engine = createAnnotationEngine({ viewer: {}, renderer });
const metresPerDegree = (6371.0088 * 1000 * Math.PI) / 180;
for (const metres of [994, 996, 9940, 9960]) {
await engine.annotate([
{ type: 'route', manual: true, path: [[0, 0], [0, metres / metresPerDegree]] },
]);
}
assert.deepEqual(labels, ['990 m', '1.0 km', '9.9 km', '10 km']);
engine.destroy();
});
+76
View File
@@ -0,0 +1,76 @@
/**
* The shapes drawn by hand, as UTILITIES ▸ Draw lists them: one row per shape
* with its colour, its name, and show/hide, fly-to and remove, the way Import
* lists its files. The board is the annotation engine's; voice marks are not
* listed, only `manual` ones.
*/
import { msg, t } from '../i18n/index.js';
export const DRAW_COLORS = Object.freeze([
'primary',
'amber',
'cyan',
'green',
'red',
]);
/** Each colour as drawn: the preview, the swatches and the drawn shape. */
export const DRAW_COLOR_CSS = Object.freeze({
primary: '#8be9ff',
amber: '#ffb547',
cyan: '#39d0ff',
green: '#5dff9f',
red: '#ff6b6b',
});
export const DRAW_COLOR_NAMES = Object.freeze({
primary: msg('Primary'),
amber: msg('Amber'),
cyan: msg('Cyan'),
green: msg('Green'),
red: msg('Red'),
});
const SHAPE_NAMES = Object.freeze({
area: msg('Area'),
route: msg('Line'),
pin: msg('Pin'),
});
/** What a row calls a shape that has no name of its own. */
export function drawMarkFallbackName(mark) {
const shape = t(SHAPE_NAMES[mark?.type] || SHAPE_NAMES.pin);
// An unnamed line's label is its length; keep it, it is the useful part.
return mark?.type === 'route' && !mark.name && mark.label
? `${shape} · ${mark.label}`
: shape;
}
/**
* The rows for the hand-drawn marks on the board, in board order. Text is
* worded here, in the current language; the view only lays it out.
* @param {object[]} marks The engine's `list()`.
*/
export function presentDrawMarks(marks = []) {
return marks
.filter((mark) => mark?.manual === true)
.map((mark) => {
const fallback = drawMarkFallbackName(mark);
const title = mark.name || fallback;
const visible = !mark.hidden;
return {
id: mark.id,
name: mark.name || '',
placeholder: fallback,
color: DRAW_COLORS.includes(mark.color) ? mark.color : 'primary',
hidden: !visible,
labels: {
name: t('Name of {name}', { name: title }),
swatch: t('Change the colour of {name}', { name: title }),
colors: t('Colour of {name}', { name: title }),
toggle: visible
? t('Hide {name}', { name: title })
: t('Show {name}', { name: title }),
fly: t('Fly to {name}', { name: title }),
remove: t('Remove {name}', { name: title }),
},
};
});
}
+80
View File
@@ -0,0 +1,80 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
DRAW_COLORS,
DRAW_COLOR_CSS,
drawMarkFallbackName,
presentDrawMarks,
} from './drawMarks.js';
test('an unnamed shape is called by its kind, and an unnamed line by its length too', () => {
assert.equal(drawMarkFallbackName({ type: 'area' }), 'Area');
assert.equal(drawMarkFallbackName({ type: 'pin' }), 'Pin');
assert.equal(
drawMarkFallbackName({ type: 'route', label: '300 m' }),
'Line · 300 m',
);
assert.equal(
drawMarkFallbackName({
type: 'route',
name: 'Walk',
label: 'Walk — 300 m',
}),
'Line',
);
});
test('rows list only hand-drawn marks, in board order, with their words', () => {
const rows = presentDrawMarks([
{
id: 'a1',
type: 'route',
manual: true,
name: null,
label: '950 m',
color: 'amber',
},
{ id: 'a2', type: 'area', manual: false, label: 'Texas', color: 'primary' },
{
id: 'a3',
type: 'pin',
manual: true,
name: 'Camp',
color: 'teal',
hidden: true,
},
]);
assert.deepEqual(
rows.map(({ id, name, placeholder, color, hidden }) => ({
id,
name,
placeholder,
color,
hidden,
})),
[
{
id: 'a1',
name: '',
placeholder: 'Line · 950 m',
color: 'amber',
hidden: false,
},
{
id: 'a3',
name: 'Camp',
placeholder: 'Pin',
color: 'primary',
hidden: true,
},
],
);
assert.equal(rows[0].labels.toggle, 'Hide Line · 950 m');
assert.equal(rows[1].labels.toggle, 'Show Camp');
assert.equal(rows[1].labels.fly, 'Fly to Camp');
assert.equal(rows[1].labels.colors, 'Colour of Camp');
});
test('every colour has its swatch', () => {
assert.deepEqual(Object.keys(DRAW_COLOR_CSS), [...DRAW_COLORS]);
});
+69 -31
View File
@@ -1,9 +1,10 @@
/**
* Manual whiteboard drawing: the Cesium + DOM half.
*
* DISPLAY ▸ Draw turns the globe into a whiteboard you draw on by hand: pick a
* shape (area, line or pin), click the vertices on the real world, double-click
* or press Enter to finish, type a label. Each finished shape goes through the
* UTILITIES ▸ Draw turns the globe into a whiteboard you draw on by hand: pick a
* shape (area, line or pin) and a colour, click the vertices on the real world,
* double-click or press Enter to finish, then name, recolour, hide, fly to or
* remove the shape from its row (drawMarks.js). Each finished shape goes through the
* SAME `annotationEngine.annotate()` the voice agent uses, with its geometry
* supplied and `manual: true`, so it renders with the whiteboard look,
* persists, de-dups, shows up in `.list()`, and clears with the board.
@@ -49,32 +50,30 @@ import {
removeLastVertex,
} from './drawMode.js';
import { DRAW_COLORS, DRAW_COLOR_CSS, presentDrawMarks } from './drawMarks.js';
import { onLocaleChange, t, translateKnown } from '../i18n/index.js';
/** The id this tool claims the pointer under. */
const DRAW_POINTER_OWNER = 'draw';
const PREVIEW_DATA_SOURCE_NAME = 'gev-draw-preview';
const COLORS = ['primary', 'amber', 'cyan', 'green', 'red'];
const PREVIEW = {
primary: '#8be9ff',
amber: '#ffb547',
cyan: '#39d0ff',
green: '#5dff9f',
red: '#ff6b6b',
};
const PREVIEW = DRAW_COLOR_CSS;
/**
* Run the Draw control. Returns a handle with a `destroy()` the application
* lifetime owns, plus the console/test seam (`window.__gevDrawTool`).
* The tool hands what the controls show (`{ active, shape, color, label,
* hint }`) to `publish`, which the view renders, and answers the controls
* The tool hands what the controls show (`{ active, shape, color, hint,
* marks }`) to `publish`, which the view renders, and answers the controls
* through the actions it gives `connect`, which returns their disconnect.
* @param {{viewer: Cesium.Viewer, annotations: {annotate: Function, clear: Function}, publish?: Function, connect?: Function}} deps
* A row's fly-to is an immediate navigation through `navigation`, like
* Import's, so Cockpit can refuse it and a running orbit or follow lets go.
* @param {{viewer: Cesium.Viewer, annotations: {annotate: Function, clear: Function}, navigation?: object, publish?: Function, connect?: Function}} deps
* @returns {{destroy: Function}|null}
*/
export function initDrawTool({
viewer,
annotations,
navigation = null,
publish = () => {},
connect = () => () => {},
}) {
@@ -88,7 +87,6 @@ export function initDrawTool({
let session = null;
let shape = 'area';
let color = 'primary';
let label = '';
let hint = '';
let handler = null;
let lease = null;
@@ -117,7 +115,14 @@ export function initDrawTool({
() => null,
);
const present = () => publish({ active, shape, color, label, hint });
const present = () =>
publish({
active,
shape,
color,
hint,
marks: presentDrawMarks(annotations.list?.() || []),
});
// The hint is kept as the call that words it, so a language switch can
// word it again.
let hintText = () => '';
@@ -240,15 +245,14 @@ export function initDrawTool({
if (reason !== 'too-few') setHint(() => drawHint(session));
return null;
}
const spec = finishSpec(session, { label, color });
// Named afterwards, in the shape's row.
const spec = finishSpec(session, { label: '', color });
if (!spec) return null;
// Start a fresh session BEFORE awaiting, so a second Enter or the second
// half of a double-click cannot submit the same shape twice.
session = createDrawSession(shape);
cursor = null;
syncPreview();
label = '';
present();
const attempt = generation;
try {
const result = await annotations.annotate([spec], {
@@ -287,11 +291,9 @@ export function initDrawTool({
};
// ---- keys: only while drawing, never while typing in another field ----
// The label field is this tool's own: typing there still drives drawing.
const isLabelField = (target) => target?.id === 'draw-label-input';
const typingElsewhere = (event) => {
const t = event.target;
if (!t || isLabelField(t)) return false;
if (!t) return false;
return (
t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable
);
@@ -299,12 +301,12 @@ export function initDrawTool({
/**
* Enter is the finish key, but on a focused control Enter means "press this
* control". Keyboard-focusing Clear and pressing Enter must clear the board,
* not finish the shape — so the finish key is only taken from the canvas,
* the page body, or the label field this tool owns.
* not finish the shape — so the finish key is only taken from the canvas or
* the page body.
*/
const enterBelongsToDrawing = (event) => {
const t = event.target;
if (!t || isLabelField(t)) return true;
if (!t) return true;
if (
typeof t.closest === 'function' &&
t.closest('button, a, select, [role="button"], [role="radio"]')
@@ -316,6 +318,9 @@ export function initDrawTool({
};
const onKey = (event) => {
if (!active || destroyed || typingElsewhere(event)) return;
// Keys on the shape list's own controls are the list's (Esc closes a
// colour picker there), not the drawing's.
if (event.target?.closest?.('#draw-mark-list')) return;
// Enter goes to finish() once a shape has been started; finish() owns the
// decision and says WHY it refused. Swallowing the key on a degenerate
// shape left the person pressing Enter at a silent panel. A focused button
@@ -334,7 +339,7 @@ export function initDrawTool({
else setActive(false);
return;
}
if (event.key === 'Backspace' && !isLabelField(event.target)) {
if (event.key === 'Backspace') {
if (removeLastVertex(session)) {
event.preventDefault();
syncPreview();
@@ -431,6 +436,20 @@ export function initDrawTool({
}
}
/**
* Frame one drawn shape: an immediate navigation, so Cockpit can refuse it
* and the current orbit, follow or track lets go first.
*/
function flyToMark(id) {
if (typeof navigation?.runImmediateNavigation === 'function')
return (
navigation.runImmediateNavigation('drawing', () =>
annotations.frame?.(id),
) !== false
);
return annotations.frame?.(id) ?? false;
}
/** Draw `next` from now on; an open shape starts over in it. */
function chooseShape(next) {
shape = normalizeShape(next);
@@ -446,16 +465,26 @@ export function initDrawTool({
toggleDraw: () => setActive(!active),
setDrawShape: chooseShape,
setDrawColor: (value) => {
color = COLORS.includes(value) ? value : 'primary';
color = DRAW_COLORS.includes(value) ? value : 'primary';
present();
syncPreview();
},
setDrawLabel: (text) => {
label = String(text ?? '');
present();
},
clearDraw: clearAll,
renameDrawMark: (id, name) => annotations.restyle?.(id, { name }),
recolorDrawMark: (id, next) => annotations.restyle?.(id, { color: next }),
toggleDrawMark: (id) => {
const mark = annotations.list?.().find((entry) => entry.id === id);
if (mark) annotations.setHidden?.(id, !mark.hidden);
},
flyToDrawMark: flyToMark,
removeDrawMark: (id) => annotations.remove?.(id),
});
// The rows follow the board: a shape drawn, renamed, hidden or removed
// here, by voice or by a clear.
const offBoard =
annotations.onChange?.(() => {
if (!destroyed) present();
}) || (() => {});
setHint(() => drawHint(null));
const api = {
@@ -470,6 +499,14 @@ export function initDrawTool({
},
setActive,
setShape: chooseShape,
/** The hand-drawn marks the list shows, as its rows. */
marks: () => presentDrawMarks(annotations.list?.() || []),
setColor(next) {
color = DRAW_COLORS.includes(next) ? next : 'primary';
present();
syncPreview();
},
flyToMark,
/** Test seam: add a vertex from lon/lat as if it had been clicked. */
addVertex(lon, lat, height = 0) {
if (!session) return false;
@@ -519,6 +556,7 @@ export function initDrawTool({
if (active) setActive(false);
destroyed = true;
offLocale();
offBoard();
disconnect();
releaseSceneHandler();
releasePointer(lease);
+41 -16
View File
@@ -23,7 +23,7 @@ test('the application composition wires the draw tool and owns its teardown', ()
const tools = read('src/app/tools.js');
const engineAt = tools.indexOf('const annotations = initAnnotations({');
const drawAt = tools.indexOf(
'const drawTool = initDrawTool({\n viewer,\n annotations,\n publish: (view) => displayStore.publishDraw(view),',
'const drawTool = initDrawTool({\n viewer,\n annotations,\n navigation: styleManager,\n publish: (view) => displayStore.publishDraw(view),',
);
assert.ok(engineAt >= 0, 'initAnnotations call missing');
assert.ok(
@@ -62,42 +62,62 @@ test('the engine resolves manual geometry before any name resolution', () => {
});
test('the Draw control markup carries the ids the tool binds to', () => {
// The DISPLAY rail is a Vue view now, rendered into index.html's view host —
// the markup is not in index.html any more.
const html = read('src/ui/views/panels/DisplayPanel.vue');
// UTILITIES ▸ Draw is a Vue view (DrawControls, with DrawMarkList for the
// drawn shapes' rows), rendered into the Utilities panel.
const html = [
read('src/ui/views/panels/DrawControls.vue'),
read('src/ui/views/panels/DrawMarkList.vue'),
].join('\n');
const ids = [
'draw-toggle',
'draw-mode-row',
'draw-colors',
'draw-label-row',
'draw-label-input',
'draw-color-select',
'draw-clear',
'draw-hint',
'draw-mark-list',
];
for (const id of ids) {
assert.match(
html,
new RegExp(`id="${id}"`),
`#${id} missing from index.html`,
`#${id} missing from the Draw views`,
);
}
for (const shape of ['area', 'line', 'pin']) {
// Shapes are icons, named for screen readers and tooltips.
for (const [shape, icon] of [
['area', 'pentagon'],
['line', 'timeline'],
['pin', 'location_on'],
]) {
assert.match(
html,
new RegExp(`'data-shape': '${shape}'`),
new RegExp(`icon: '${icon}', attrs: \\{ 'data-shape': '${shape}' \\}`),
`shape button ${shape} missing`,
);
}
assert.ok(
read('src/ui/views/LayerPanelsView.vue').includes('<DrawControls />'),
'the Utilities panel renders Draw',
);
assert.ok(
!read('src/ui/views/panels/DisplayPanel.vue').includes('draw-toggle'),
'Draw is no longer in DISPLAY',
);
// The rows and the hint render what the tool publishes; the controls
// call the actions the tool connects to the display store.
for (const action of [
"act('toggleDraw')",
"act('setDrawShape', $event)",
"act('setDrawLabel', $event.target.value)",
"act('setDrawColor', $event)",
"act('clearDraw')",
"act('renameDrawMark', row.id, next)",
"act('recolorDrawMark', row.id, color)",
"act('toggleDrawMark', row.id)",
"act('flyToDrawMark', row.id)",
"act('removeDrawMark', row.id)",
]) {
assert.ok(html.includes(action), `DisplayPanel must call ${action}`);
assert.ok(html.includes(action), `the Draw views must call ${action}`);
const name = /act\('([a-zA-Z]+)'/.exec(action)[1];
assert.match(
tool(),
@@ -119,14 +139,15 @@ test('the DISPLAY rail styles live in their current owner, not the shim', () =>
assert.deepEqual(rules, [], 'style.css is an import shim, not a stylesheet');
assert.doesNotMatch(
shim,
/draw-hint|pp-text-input/,
/draw-hint|draw-color/,
'draw styles belong to a component stylesheet',
);
const controls = read('src/ui/styles/controls.css');
for (const rule of [
'#draw-mode-row',
'#draw-label-row',
'.pp-text-input',
'.draw-color',
'.draw-mark-name',
'.draw-clear-btn',
'.draw-hint',
'body.gev-drawing',
@@ -149,10 +170,14 @@ test('nothing promises a GeoJSON export for drawn shapes', () => {
`${file} still claims a GeoJSON export`,
);
}
for (const file of ['README.md', 'CHANGELOG.md', 'docs/CURRENT-STATE.md']) {
// Draw lives in UTILITIES; only the changelog's history still says DISPLAY.
for (const [file, heading] of [
['README.md', 'UTILITIES ▸ **Draw**'],
['CHANGELOG.md', 'DISPLAY ▸ Draw'],
['docs/CURRENT-STATE.md', 'UTILITIES ▸ **Draw**'],
]) {
const source = read(file);
const at = source.indexOf('DISPLAY ▸ **Draw**');
const start = at >= 0 ? at : source.indexOf('DISPLAY ▸ Draw');
const start = source.indexOf(heading);
assert.ok(start >= 0, `${file} should describe the Draw control`);
const section = source.slice(start, start + 1200);
assert.doesNotMatch(
+106 -24
View File
@@ -96,11 +96,10 @@ function fakeDom() {
byId.set(id, element);
return element;
};
// The control whose presence means the page has Draw, a focused button
// whose Enter is its own, and the tool's label field.
// The control whose presence means the page has Draw, and a focused button
// whose Enter is its own.
make('draw-toggle', 'BUTTON');
make('draw-clear', 'BUTTON');
make('draw-label-input', 'INPUT');
const body = new FakeElement('BODY');
const documentDouble = {
@@ -176,9 +175,16 @@ function fakeViewer() {
}
function fakeAnnotations() {
const calls = { annotate: [], clear: 0 };
const calls = { annotate: [], clear: 0, restyle: [], setHidden: [], frame: [], remove: [] };
const marks = [];
const listeners = new Set();
const changed = () => listeners.forEach((listener) => listener());
const find = (id) => marks.find((mark) => mark.id === id);
return {
calls,
marks,
listeners,
changed,
async annotate(specs, options) {
calls.annotate.push({ specs, options });
return { drawn: specs.length };
@@ -186,11 +192,38 @@ function fakeAnnotations() {
clear() {
calls.clear += 1;
},
list: () => marks,
onChange(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
},
restyle(id, change) {
calls.restyle.push([id, change]);
Object.assign(find(id), change);
changed();
return true;
},
setHidden(id, hidden) {
calls.setHidden.push([id, hidden]);
find(id).hidden = hidden;
changed();
return true;
},
frame(id) {
calls.frame.push(id);
return true;
},
remove(id) {
calls.remove.push(id);
marks.splice(marks.indexOf(find(id)), 1);
changed();
return true;
},
};
}
/** Stand up a tool against fresh doubles, with globals restored afterwards. */
function harness() {
function harness({ navigation = null } = {}) {
resetPointerOwnership();
const { byId, documentDouble } = fakeDom();
const viewer = fakeViewer();
@@ -205,6 +238,7 @@ function harness() {
const tool = initDrawTool({
viewer,
annotations,
navigation,
publish: (view) => (shown.view = view),
connect: (actions) => {
controls.actions = actions;
@@ -426,6 +460,7 @@ test('destroy releases the pointer, the handler, the listeners and the stock act
h.tool.addVertex(-97.75, 30.26);
assert.equal(pointerOwner(), 'draw');
assert.ok(h.tool.diagnostics().domListeners > 0);
assert.equal(h.annotations.listeners.size, 1, 'the rows follow the board');
await h.tool.destroy();
await Promise.resolve();
@@ -443,6 +478,7 @@ test('destroy releases the pointer, the handler, the listeners and the stock act
'the viewer got its selecting click back',
);
assert.equal(h.viewer._attached.length, 0, 'the preview data source is detached');
assert.equal(h.annotations.listeners.size, 0, 'and it no longer follows the board');
// Idempotent: a second destroy is harmless.
await h.tool.destroy();
@@ -467,16 +503,15 @@ test('Clear wipes the board and the shape in progress', async () => {
}
});
test('the controls choose the shape, colour and label the next shape is drawn with', async () => {
test('the controls choose the shape and colour the next shape is drawn with; it is named in its row', async () => {
const h = harness();
try {
h.act('toggleDraw');
h.act('setDrawShape', 'line');
h.act('setDrawColor', 'amber');
h.act('setDrawLabel', 'Route A');
assert.deepEqual(
{ ...h.shown.view, hint: undefined },
{ active: true, shape: 'line', color: 'amber', label: 'Route A', hint: undefined },
{ active: true, shape: 'line', color: 'amber', hint: undefined, marks: [] },
'the view shows what the controls chose',
);
h.act('setDrawColor', 'purple');
@@ -494,36 +529,83 @@ test('the controls choose the shape, colour and label the next shape is drawn wi
const spec = h.annotations.calls.annotate[0].specs[0];
assert.equal(spec.type, 'route', 'a drawn line is a manual route');
assert.equal(spec.color, 'cyan');
assert.equal(spec.label, 'Route A');
assert.equal(h.shown.view.label, '', 'a finished shape empties the label');
assert.ok(!spec.label, 'a shape is named afterwards, in its row');
} finally {
h.restore();
}
});
test('keys typed in the label field: Enter finishes, Backspace edits, Escape cancels', async () => {
test('each drawn shape is a row whose actions reach the board, and fly-to is a navigation', async () => {
const navigations = [];
const h = harness({
navigation: {
runImmediateNavigation: (noun, navigate) => {
navigations.push(noun);
return navigate();
},
},
});
try {
const board = h.annotations;
board.marks.push(
{ id: 'a1', type: 'route', manual: true, name: null, label: '950 m', color: 'amber', hidden: false },
{ id: 'a2', type: 'pin', manual: false, label: 'Voice pin', color: 'primary', hidden: false },
);
board.changed();
assert.deepEqual(
h.shown.view.marks.map(({ id, placeholder, hidden }) => ({ id, placeholder, hidden })),
[{ id: 'a1', placeholder: 'Line · 950 m', hidden: false }],
'only hand-drawn marks are listed, an unnamed line by its length',
);
h.act('renameDrawMark', 'a1', 'Ridge walk');
h.act('recolorDrawMark', 'a1', 'green');
h.act('toggleDrawMark', 'a1');
h.act('flyToDrawMark', 'a1');
h.act('removeDrawMark', 'a1');
assert.deepEqual(board.calls.restyle, [
['a1', { name: 'Ridge walk' }],
['a1', { color: 'green' }],
]);
assert.deepEqual(board.calls.setHidden, [['a1', true]]);
assert.deepEqual(board.calls.frame, ['a1']);
assert.deepEqual(navigations, ['drawing'], 'fly-to goes through the navigation policy');
assert.deepEqual(board.calls.remove, ['a1']);
assert.deepEqual(h.shown.view.marks, [], 'the row goes with its mark');
} finally {
h.restore();
}
});
test('Backspace on the page removes the last vertex', () => {
const h = harness();
try {
const label = h.element('draw-label-input');
h.act('toggleDraw');
h.tool.addVertex(-97.75, 30.26);
h.tool.addVertex(-97.74, 30.26);
h.documentDouble.emit('keydown', { key: 'Backspace', target: h.documentDouble.body });
assert.equal(h.tool.session.vertices.length, 1);
} finally {
h.restore();
}
});
test('keys on the shape list are the list\'s, not the drawing\'s', async () => {
const h = harness();
try {
const listButton = new FakeElement('BUTTON');
listButton.closest = (selector) => (selector === '#draw-mark-list' ? {} : null);
const elsewhere = new FakeElement('INPUT', 'location-search');
h.act('toggleDraw');
h.tool.addVertex(-97.75, 30.26);
h.tool.addVertex(-97.74, 30.26);
h.documentDouble.emit('keydown', { key: 'Backspace', target: label });
assert.equal(h.tool.session.vertices.length, 2, 'Backspace edits the label');
h.documentDouble.emit('keydown', { key: 'Escape', target: listButton });
assert.equal(h.tool.session.vertices.length, 2, 'Escape in the list keeps the shape');
assert.equal(h.tool.active, true, 'and keeps Draw on');
h.documentDouble.emit('keydown', { key: 'Enter', target: elsewhere });
await Promise.resolve();
assert.equal(h.annotations.calls.annotate.length, 0, 'another field keeps its Enter');
h.documentDouble.emit('keydown', { key: 'Escape', target: label });
assert.equal(h.tool.session.vertices.length, 0, 'Escape drops the open shape');
assert.equal(h.tool.active, true, 'and leaves Draw on');
h.act('setDrawShape', 'line');
h.tool.addVertex(-97.75, 30.26);
h.tool.addVertex(-97.74, 30.26);
h.documentDouble.emit('keydown', { key: 'Enter', target: label });
await Promise.resolve();
await Promise.resolve();
assert.equal(h.annotations.calls.annotate.length, 1, 'Enter in the label finishes');
h.documentDouble.emit('keydown', { key: 'Escape', target: h.documentDouble.body });
assert.equal(h.tool.session.vertices.length, 0, 'Escape on the page drops the open shape');
} finally {
h.restore();
}
+3 -1
View File
@@ -488,7 +488,9 @@ export function createScreenAnnotationRenderer(
for (const rec of records.values()) {
const { anno, group, parts } = rec;
if (rec.hidden) {
// A mark hidden from Draw's list is not projected, so it neither shows
// nor pushes a visible callout aside in the placement below.
if (rec.hidden || anno.hidden) {
group.display = 'none';
continue;
}
@@ -529,3 +529,49 @@ test('Preview avoids the map callout without moving its world anchor', async (t)
assert.equal(callout().getAttribute('transform'), natural, variant);
}
});
test('a mark hidden from Draw is not drawn or placed, and comes back when shown', async (t) => {
// happy-dom measures every SVG box the same, so callout spreading cannot
// settle here; a hidden mark simply has to stay out of drawing and
// placement, which is what keeps it from pushing a visible callout aside.
const { store, svg } = board(t);
projectTo(t, { x: 200, y: 300 });
const camera = cameraOver(0, 0);
let project = null;
const renderer = createScreenAnnotationRenderer(
{
scene: sceneFor(camera, {
postRender: {
addEventListener: (listener) => (project = listener),
removeEventListener() {},
},
}),
camera,
trackedEntity: null,
},
{ store, activeTrackedReadoutId: () => null },
);
t.after(() => renderer.destroy());
const camp = {
id: 'camp',
type: 'pin',
color: 'amber',
label: 'Camp',
alpha: 1,
hidden: true,
anchor: { lon: 0, lat: 0, height: 0 },
};
renderer.add(camp);
project();
await settle();
const drawn = () =>
[...svg().querySelectorAll('g.gev-anno')].some(
(group) =>
group.textContent.includes('Camp') && group.style.display !== 'none',
);
assert.equal(drawn(), false, 'the hidden mark is not drawn');
camp.hidden = false;
project();
await settle();
assert.equal(drawn(), true, 'shown again, it is drawn');
});
+22 -3
View File
@@ -53,6 +53,8 @@ export function createWorldAnnotationRenderer(viewer) {
const dataSource = new Cesium.CustomDataSource('gev-annotations');
viewer.dataSources.add(dataSource);
const osmAnnotations = new Set();
// Every mark with entities on the globe, so sync() can take a hidden one out.
const drawn = new Set();
const pendingGround = new Map();
const groundQueue = [];
let observingGround = false;
@@ -315,6 +317,7 @@ export function createWorldAnnotationRenderer(viewer) {
// path cannot reach them and they stay on the globe forever.
const entities = [];
anno._entities = entities;
drawn.add(anno);
if (
anno.ring?.length >= 3 &&
@@ -511,6 +514,7 @@ export function createWorldAnnotationRenderer(viewer) {
width: 9,
material: new FlowMaterialProperty(
PALETTE[anno.color] || PALETTE.primary,
() => anno.alpha ?? 1,
),
clampToGround: true,
classificationType: CLASSIFY,
@@ -598,6 +602,7 @@ export function createWorldAnnotationRenderer(viewer) {
pendingGround.get(anno)?.finish('cancelled');
hideOsmCredit(viewer, anno);
osmAnnotations.delete(anno);
drawn.delete(anno);
if (!anno?._entities) return;
for (const entity of anno._entities) {
try {
@@ -609,8 +614,17 @@ export function createWorldAnnotationRenderer(viewer) {
anno._entities = null;
}
/**
* CallbackProperty drives per-frame alpha and pulse. A hidden mark is taken
* out whole, so no material that keeps its own colour (the route's flow),
* ground classification or pick can still show it.
*/
function sync() {
// No-op: CallbackProperty drives per-frame alpha/pulse animation.
for (const anno of drawn) {
const show = !anno.hidden;
for (const entity of anno._entities || [])
if (entity.show !== show) entity.show = show;
}
}
function destroy() {
@@ -618,6 +632,7 @@ export function createWorldAnnotationRenderer(viewer) {
for (const task of [...pendingGround.values()]) task.finish('cancelled');
for (const anno of osmAnnotations) hideOsmCredit(viewer, anno);
osmAnnotations.clear();
drawn.clear();
try {
viewer.dataSources.remove(dataSource, true);
} catch {
@@ -687,8 +702,11 @@ export function ensureFlowFabricRegistered() {
* returned a standalone Material Cesium never rendered, or treated `result` as a
* Material — both left the real uniforms untouched, so nothing animated.)
*/
export function FlowMaterialProperty(colorCss) {
export function FlowMaterialProperty(colorCss, alphaOf = () => 1) {
this._color = Cesium.Color.fromCssColorString(colorCss).withAlpha(0.95);
// The mark's live alpha (fade in and out, hidden), applied every frame.
this._alphaOf = alphaOf;
this._live = this._color.clone();
this._definitionChanged = new Cesium.Event();
}
Object.defineProperties(FlowMaterialProperty.prototype, {
@@ -711,7 +729,8 @@ FlowMaterialProperty.prototype.getValue = function getValue(time, result) {
// `time` is read straight from the wall clock so the dashes flow every rendered
// frame (the scene renders continuously; no requestRenderMode here).
if (!Cesium.defined(result)) result = {};
result.color = this._color;
this._live.alpha = this._color.alpha * this._alphaOf();
result.color = this._live;
result.time = performance.now() / 1000; // the per-frame animated value
result.repeat = 64.0;
result.duty = 0.46;
@@ -0,0 +1,70 @@
// A mark hidden from Draw's list leaves the globe whole: every entity it put
// there is taken out on sync and comes back when shown, and the line's
// flowing stroke, which keeps its own colour, follows the mark's alpha.
import test from 'node:test';
import assert from 'node:assert/strict';
import * as C from 'cesium';
import {
FlowMaterialProperty,
createWorldAnnotationRenderer,
} from './worldAnnotationRenderer.js';
const noop = () => {};
function viewer(t) {
for (const name of ['HTMLCanvasElement', 'HTMLImageElement', 'ImageBitmap', 'OffscreenCanvas']) {
const original = globalThis[name];
globalThis[name] = class {};
t.after(() => { if (original === undefined) delete globalThis[name]; else globalThis[name] = original; });
}
const before = globalThis.document;
globalThis.document = { addEventListener: noop, removeEventListener: noop };
t.after(() => { if (before === undefined) delete globalThis.document; else globalThis.document = before; });
return {
creditDisplay: { addStaticCredit: noop, removeStaticCredit: noop },
entities: new C.EntityCollection(),
dataSources: new C.DataSourceCollection(),
camera: { moveEnd: new C.Event(), positionCartographic: { height: 1000 } },
scene: { requestRender: noop, canvas: { addEventListener: noop, removeEventListener: noop }, preRender: new C.Event(),
primitives: { add: (p) => p, remove: noop }, screenSpaceCameraController: { enableInputs: true } },
};
}
const marks = () => [
{ id: 'route', type: 'route', color: 'amber', alpha: 1, anchor: { lat: 0, lon: 0 }, path: [{ lat: 0, lon: 0 }, { lat: 0.01, lon: 0.01 }] },
{ id: 'area', type: 'area', color: 'green', alpha: 1, anchor: { lat: 0.005, lon: 0.005 }, ring: [[0, 0], [0.01, 0], [0.01, 0.01], [0, 0]] },
{ id: 'pin', type: 'pin', color: 'primary', alpha: 1, anchor: { lat: 0.02, lon: 0.02 } },
];
test('a hidden mark has every entity taken off on sync, and back when shown', (t) => {
const renderer = createWorldAnnotationRenderer(viewer(t));
const [route, area, pin] = marks();
for (const anno of [route, area, pin]) renderer.add(anno);
const shown = (anno) => anno._entities.map((entity) => entity.show);
for (const anno of [route, area, pin]) assert.ok(anno._entities.length > 0, anno.id);
route.hidden = true;
area.hidden = true;
renderer.sync();
assert.ok(shown(route).every((show) => show === false), 'the line is off');
assert.ok(shown(area).every((show) => show === false), 'the area is off');
assert.ok(shown(pin).every((show) => show === true), 'a visible mark stays');
route.hidden = false;
renderer.sync();
assert.ok(shown(route).every((show) => show === true), 'the line is back');
renderer.remove(area);
renderer.sync();
assert.equal(area._entities, null, 'a removed mark is no longer synced');
renderer.destroy();
});
test('the line\'s flowing stroke follows its mark\'s alpha', () => {
let alpha = 1;
const material = new FlowMaterialProperty('#ffb547', () => alpha);
assert.ok(Math.abs(material.getValue(null, {}).color.alpha - 0.95) < 1e-9);
alpha = 0;
assert.equal(material.getValue(null, {}).color.alpha, 0, 'hidden: nothing painted');
alpha = 0.5;
assert.ok(Math.abs(material.getValue(null, {}).color.alpha - 0.475) < 1e-9, 'fading');
assert.equal(new FlowMaterialProperty('#fff').getValue(null, {}).color.alpha, 0.95, 'no alpha source: opaque as before');
});