Merge main through #1637 into the renderer seam

Ports the cockpit bridge view, the orbital view riding a satellite with
ground-site focus, satellite classes and draw-mark row actions onto the
renderer contract. The orbital view's imagery look-ahead pre-load is
dropped (no contract member); tiles load as they come on screen.
This commit is contained in:
Sameh Khamis committed 2026-11-10 01:35:00 -08:00
commit e48ed3eb9e
169 files changed
+22415 -681

No files matched your search

+144 -1
View File
@@ -43,24 +43,167 @@ export function drawMarkFallbackName(mark) {
: shape;
}
/** The kind of shape a row action is offered for: `area` or `line`. */
const ACTION_SHAPES = Object.freeze({ area: 'area', route: 'line' });
const lonLat = (point) =>
Array.isArray(point)
? [Number(point[0]), Number(point[1])]
: [Number(point?.lon), Number(point?.lat)];
const finitePairs = (points) =>
(Array.isArray(points) ? points : [])
.map(lonLat)
.filter(([lon, lat]) => Number.isFinite(lon) && Number.isFinite(lat));
/** A longitude in [-180, 180]; an unwrapped outline can carry ±540. */
const wrapLon = (lon) =>
lon >= -180 && lon <= 180 ? lon : ((((lon + 180) % 360) + 360) % 360) - 180;
/** Whether consecutive positions step across the antimeridian once wrapped. */
const crossesAntimeridian = (points) =>
points.some(
(point, index) =>
index > 0 && Math.abs(point[0] - points[index - 1][0]) > 180,
);
/** Positions wrapped into range, or null when the sequence crosses ±180°. */
const inRange = (points) => {
if (points.some(([, lat]) => Math.abs(lat) > 90)) return null;
const wrapped = points.map(([lon, lat]) => [wrapLon(lon), lat]);
return crossesAntimeridian(wrapped) ? null : wrapped;
};
const closed = (ring) => {
if (ring.length < 3) return ring;
const [first, last] = [ring[0], ring[ring.length - 1]];
return first[0] === last[0] && first[1] === last[1] ? ring : [...ring, first];
};
/**
* A drawn shape's geometry as GeoJSON in `[lon, lat]` degrees, longitudes in
* [-180, 180]: an area is a closed `Polygon` (a `MultiPolygon` when an area
* handle has several parts), a line a `LineString`. A pin, a shape too small
* to be one, or one that crosses the antimeridian has none, so it is offered
* no action rather than a shape that wraps the wrong way round the world.
*/
export function drawMarkGeometry(mark) {
if (mark?.type === 'route') {
const path = inRange(finitePairs(mark.path));
return path?.length >= 2 ? { type: 'LineString', coordinates: path } : null;
}
if (mark?.type !== 'area') return null;
const ringOf = (points) => {
const ring = inRange(closed(finitePairs(points)));
return ring?.length >= 4 ? ring : null;
};
if (Array.isArray(mark.polygons) && mark.polygons.length) {
const polygons = [];
for (const rings of mark.polygons) {
const parts = (Array.isArray(rings) ? rings : []).map(ringOf);
// A part that cannot be given whole is no part: never a hole dropped.
if (!parts.length || parts.some((ring) => !ring)) return null;
polygons.push(parts);
}
return polygons.length > 1
? { type: 'MultiPolygon', coordinates: polygons }
: { type: 'Polygon', coordinates: polygons[0] };
}
const ring = ringOf(mark.ring);
return ring ? { type: 'Polygon', coordinates: [ring] } : null;
}
/**
* The actions an application adds to Draw's rows, checked once: each has an
* `id`, a Material Symbols `icon`, a `label(name)` worded by the application,
* the `shapes` it is for (`area`, `line`), an optional `accepts(geometry)` and
* `run({ id, shape, name, title, geometry })` (`name` the person's own, `title`
* as the row shows it). Malformed or repeated ids are dropped.
*/
export function drawMarkActions(actions = []) {
const kept = new Map();
for (const action of Array.isArray(actions) ? actions : []) {
const wellFormed =
typeof action?.id === 'string' &&
/^[a-z][a-z0-9-]{0,39}$/.test(action.id) &&
typeof action.icon === 'string' &&
typeof action.label === 'function' &&
typeof action.run === 'function' &&
Array.isArray(action.shapes);
if (!wellFormed || kept.has(action.id)) continue;
kept.set(
action.id,
Object.freeze({
id: action.id,
icon: action.icon,
label: action.label,
shapes: Object.freeze(
action.shapes.filter((shape) =>
Object.values(ACTION_SHAPES).includes(shape),
),
),
accepts:
typeof action.accepts === 'function' ? action.accepts : () => true,
run: action.run,
}),
);
}
return Object.freeze([...kept.values()]);
}
/** The actions from `drawMarkActions` that `mark` is offered, with its geometry. */
export function drawMarkActionsFor(mark, actions = []) {
const shape = ACTION_SHAPES[mark?.type];
if (!shape || !actions.length) return { shape, geometry: null, actions: [] };
const geometry = drawMarkGeometry(mark);
if (!geometry) return { shape, geometry, actions: [] };
return {
shape,
geometry,
actions: actions.filter((action) => {
if (!action.shapes.includes(shape)) return false;
try {
return action.accepts(geometry, shape) === true;
} catch {
return false;
}
}),
};
}
/** An action's words for a row; an application's label that throws shows its id. */
function actionLabel(action, title) {
try {
const text = action.label(title);
return typeof text === 'string' && text.trim() ? text.trim() : action.id;
} catch {
return action.id;
}
}
/**
* 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()`.
* @param {ReturnType<typeof drawMarkActions>} [actions] The application's row actions.
* @param {Map<string, {busy: boolean, text: string}>} [notes] What an action said on a shape.
*/
export function presentDrawMarks(marks = []) {
export function presentDrawMarks(marks = [], actions = [], notes = new Map()) {
return marks
.filter((mark) => mark?.manual === true)
.map((mark) => {
const fallback = drawMarkFallbackName(mark);
const title = mark.name || fallback;
const visible = !mark.hidden;
const offered = drawMarkActionsFor(mark, actions).actions;
return {
id: mark.id,
name: mark.name || '',
placeholder: fallback,
color: DRAW_COLORS.includes(mark.color) ? mark.color : 'primary',
hidden: !visible,
busy: notes.get(mark.id)?.busy === true,
note: offered.length ? notes.get(mark.id)?.text || '' : '',
actions: offered.map((action) => ({
id: action.id,
icon: action.icon,
label: actionLabel(action, title),
})),
labels: {
name: t('Name of {name}', { name: title }),
swatch: t('Change the colour of {name}', { name: title }),
+219
View File
@@ -3,7 +3,10 @@ import assert from 'node:assert/strict';
import {
DRAW_COLORS,
DRAW_COLOR_CSS,
drawMarkActions,
drawMarkActionsFor,
drawMarkFallbackName,
drawMarkGeometry,
presentDrawMarks,
} from './drawMarks.js';
@@ -78,3 +81,219 @@ test('rows list only hand-drawn marks, in board order, with their words', () =>
test('every colour has its swatch', () => {
assert.deepEqual(Object.keys(DRAW_COLOR_CSS), [...DRAW_COLORS]);
});
test("a drawn shape's geometry is GeoJSON in [lon, lat]: a closed area, a line, no pin", () => {
assert.deepEqual(
drawMarkGeometry({
type: 'area',
ring: [
[0, 0],
[1, 0],
[1, 1],
[0, 0],
],
}),
{
type: 'Polygon',
coordinates: [
[
[0, 0],
[1, 0],
[1, 1],
[0, 0],
],
],
},
);
assert.deepEqual(
drawMarkGeometry({
type: 'area',
ring: [
[0, 0],
[1, 0],
[1, 1],
],
}).coordinates[0].at(-1),
[0, 0],
'an open ring is closed',
);
assert.equal(
drawMarkGeometry({
type: 'area',
ring: [
[0, 0],
[1, 0],
],
}),
null,
);
assert.deepEqual(
drawMarkGeometry({
type: 'route',
path: [
{ lon: 1, lat: 2, height: 9 },
{ lon: 3, lat: 4, height: 0 },
],
}),
{
type: 'LineString',
coordinates: [
[1, 2],
[3, 4],
],
},
);
assert.equal(
drawMarkGeometry({ type: 'pin', longitude: 1, latitude: 2 }),
null,
);
const square = (x) => [
[x, 0],
[x + 1, 0],
[x + 1, 1],
[x, 0],
];
assert.deepEqual(
drawMarkGeometry({
type: 'area',
ring: square(0),
polygons: [[square(0)], [square(5)]],
}),
{ type: 'MultiPolygon', coordinates: [[square(0)], [square(5)]] },
'an area handle with several parts keeps them all',
);
assert.equal(
drawMarkGeometry({
type: 'area',
polygons: [
[
square(0),
[
[0.2, 0.2],
[0.3, 0.2],
],
],
],
}),
null,
'a hole that cannot be given whole is never dropped silently',
);
});
test('longitudes are wrapped into range, and a shape across the antimeridian has no geometry', () => {
assert.deepEqual(
drawMarkGeometry({
type: 'route',
path: [
[370, 1],
[371, 1],
],
}).coordinates,
[
[10, 1],
[11, 1],
],
);
assert.deepEqual(
drawMarkGeometry({
type: 'area',
ring: [
[180, 0],
[179, 0],
[179, 1],
],
}).coordinates[0][0],
[180, 0],
'the antimeridian itself stays put',
);
assert.equal(
drawMarkGeometry({
type: 'area',
ring: [
[179.9, 0],
[-179.9, 0],
[-179.9, 1],
],
}),
null,
);
assert.equal(
drawMarkGeometry({
type: 'route',
path: [
[179.5, 0],
[180.5, 0],
],
}),
null,
);
assert.equal(
drawMarkGeometry({
type: 'route',
path: [
[0, 91],
[1, 0],
],
}),
null,
);
});
test('row actions are checked once: malformed ones and repeated ids are dropped', () => {
const run = () => {};
const label = () => 'x';
const actions = drawMarkActions([
{ id: 'Bad Id', icon: 'a', label, run, shapes: ['area'] },
{ id: 'tag', icon: 'a', label: 'not a function', run, shapes: ['area'] },
{
id: 'tag',
icon: 'sell',
label,
run,
shapes: ['area', 'line', 'pin'],
},
{ id: 'tag', icon: 'other', label, run, shapes: ['area'] },
null,
]);
assert.deepEqual(
actions.map(({ id, icon, shapes }) => ({ id, icon, shapes: [...shapes] })),
[{ id: 'tag', icon: 'sell', shapes: ['area', 'line'] }],
);
assert.deepEqual(drawMarkActions('nope'), []);
const area = {
type: 'area',
ring: [
[0, 0],
[1, 0],
[1, 1],
],
};
const offer = drawMarkActionsFor(area, actions);
assert.equal(offer.shape, 'area');
assert.deepEqual(
offer.actions.map((a) => a.id),
['tag'],
);
const refusing = drawMarkActions([
{
id: 'measure',
icon: 'a',
label,
run,
shapes: ['area'],
accepts: () => {
throw new Error('no');
},
},
]);
assert.deepEqual(
drawMarkActionsFor(area, refusing).actions,
[],
'an accepts that throws offers nothing',
);
assert.deepEqual(
presentDrawMarks([{ id: 'p', type: 'pin', manual: true }], actions)[0]
.actions,
[],
);
});
+90 -5
View File
@@ -50,12 +50,31 @@ import {
removeLastVertex,
} from './drawMode.js';
import { DRAW_COLORS, DRAW_COLOR_CSS, presentDrawMarks } from './drawMarks.js';
import {
DRAW_COLORS,
DRAW_COLOR_CSS,
drawMarkActions,
drawMarkActionsFor,
drawMarkFallbackName,
presentDrawMarks,
} from './drawMarks.js';
import { onLocaleChange, t, translateKnown } from '../i18n/index.js';
import { fromDegrees } from '../geo/index.js';
import { cssColor } from '../render/color.js';
import { drawOf, findFrame, rendererOf } from '../render/rendererOf.js';
/** The longest note a row action leaves under its row, in characters. */
const NOTE_MAX = 200;
/** An action's answer as a row note: trimmed, and cut at a word with an ellipsis. */
function noteText(text) {
if (typeof text !== 'string') return '';
const trimmed = text.trim();
if (trimmed.length <= NOTE_MAX) return trimmed;
const cut = trimmed.slice(0, NOTE_MAX - 1);
const space = cut.lastIndexOf(' ');
return `${(space > NOTE_MAX / 2 ? cut.slice(0, space) : cut).trimEnd()}…`;
}
/** The id this tool claims the pointer under. */
const DRAW_POINTER_OWNER = 'draw';
/** Each tool's preview sets get their own ids. */
@@ -78,7 +97,10 @@ const PREVIEW = DRAW_COLOR_CSS;
* through the actions it gives `connect`, which returns their disconnect.
* 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: object, annotations: {annotate: Function, clear: Function}, navigation?: object, publish?: Function, connect?: Function}} deps
* `markActions` are the application's own buttons on an area's or a line's
* row (drawMarks.js `drawMarkActions`); a press runs the action with the
* shape's id, kind, name and geometry (drawMarks.js `drawMarkGeometry`).
* @param {{viewer: object, annotations: {annotate: Function, clear: Function}, navigation?: object, publish?: Function, connect?: Function, markActions?: object[]}} deps
* @returns {{destroy: Function}|null}
*/
export function initDrawTool({
@@ -87,7 +109,12 @@ export function initDrawTool({
navigation = null,
publish = () => {},
connect = () => () => {},
markActions = [],
}) {
const rowActions = drawMarkActions(markActions);
// What a row action said last on each drawn shape: `{ run, busy, text }`.
const notes = new Map();
let noteRun = 0;
// A page without the Draw controls (the Display controls view omitted) has
// no draw tool.
if (!viewer || !annotations || !document.getElementById('draw-toggle'))
@@ -135,14 +162,19 @@ export function initDrawTool({
// Teardown finishes synchronously; `whenSettled()` keeps its promise.
const attaching = Promise.resolve();
const present = () =>
const present = () => {
const marks = annotations.list?.() || [];
// A note goes with its shape.
for (const id of notes.keys())
if (!marks.some((mark) => mark.id === id)) notes.delete(id);
publish({
active,
shape,
color,
hint,
marks: presentDrawMarks(annotations.list?.() || []),
marks: presentDrawMarks(marks, rowActions, notes),
});
};
// The hint is kept as the call that words it, so a language switch can
// word it again.
let hintText = () => '';
@@ -446,6 +478,56 @@ export function initDrawTool({
return annotations.frame?.(id) ?? false;
}
/**
* Run the application's row action `actionId` on drawn shape `id`, if the
* shape is still on the board and still offered it. Returns whether it ran.
* What the action returns, or resolves to, is the row's note (a measurement,
* "saved"): the row is busy until it settles, a newer press or the shape's
* removal makes a late answer moot, and a failure clears the note, so an
* action words its own refusals and resolves with them.
*/
function runMarkAction(id, actionId) {
const mark = (annotations.list?.() || []).find(
(entry) => entry.id === id && entry.manual === true,
);
const offer = drawMarkActionsFor(mark, rowActions);
const action = offer.actions.find((entry) => entry.id === actionId);
if (!action || notes.get(mark.id)?.busy) return false;
const run = ++noteRun;
const settle = (text) => {
if (destroyed || notes.get(mark.id)?.run !== run) return;
notes.set(mark.id, {
run,
busy: false,
text: noteText(text),
});
present();
};
const fail = (error) => {
console.warn(`[draw] ${actionId} failed`, error);
settle('');
};
notes.set(mark.id, { run, busy: true, text: '' });
let answer;
try {
answer = action.run({
id: mark.id,
shape: offer.shape,
name: mark.name || '',
title: mark.name || drawMarkFallbackName(mark),
geometry: offer.geometry,
});
} catch (error) {
fail(error);
return false;
}
if (typeof answer?.then === 'function') {
present();
Promise.resolve(answer).then(settle, fail);
} else settle(answer);
return true;
}
/** Draw `next` from now on; an open shape starts over in it. */
function chooseShape(next) {
shape = normalizeShape(next);
@@ -474,6 +556,7 @@ export function initDrawTool({
},
flyToDrawMark: flyToMark,
removeDrawMark: (id) => annotations.remove?.(id),
runDrawMarkAction: runMarkAction,
});
// The rows follow the board: a shape drawn, renamed, hidden or removed
// here, by voice or by a clear.
@@ -496,13 +579,15 @@ export function initDrawTool({
setActive,
setShape: chooseShape,
/** The hand-drawn marks the list shows, as its rows. */
marks: () => presentDrawMarks(annotations.list?.() || []),
marks: () =>
presentDrawMarks(annotations.list?.() || [], rowActions, notes),
setColor(next) {
color = DRAW_COLORS.includes(next) ? next : 'primary';
present();
syncPreview();
},
flyToMark,
runMarkAction,
/** Test seam: add a vertex from lon/lat as if it had been clicked. */
addVertex(lon, lat, height = 0) {
if (!session) return false;
+424 -32
View File
@@ -70,9 +70,17 @@ class FakeElement {
}
closest(selector) {
// Only what the tool asks: "am I inside an activatable control?"
const activatable = ['button', 'a', 'select', '[role="button"]', '[role="radio"]'];
const activatable = [
'button',
'a',
'select',
'[role="button"]',
'[role="radio"]',
];
if (!activatable.some((part) => selector.includes(part))) return null;
return this.tagName === 'BUTTON' || this.tagName === 'A' || this.tagName === 'SELECT'
return this.tagName === 'BUTTON' ||
this.tagName === 'A' ||
this.tagName === 'SELECT'
? this
: null;
}
@@ -153,7 +161,14 @@ function fakeViewer() {
}
function fakeAnnotations() {
const calls = { annotate: [], clear: 0, restyle: [], setHidden: [], frame: [], remove: [] };
const calls = {
annotate: [],
clear: 0,
restyle: [],
setHidden: [],
frame: [],
remove: [],
};
const marks = [];
const listeners = new Set();
const changed = () => listeners.forEach((listener) => listener());
@@ -201,7 +216,11 @@ function fakeAnnotations() {
}
/** Stand up a tool against fresh doubles, with globals restored afterwards. */
function harness({ navigation = null, beforeInput = () => {} } = {}) {
function harness({
navigation = null,
beforeInput = () => {},
markActions = [],
} = {}) {
resetPointerOwnership();
const { byId, documentDouble } = fakeDom();
const viewer = fakeViewer();
@@ -224,6 +243,7 @@ function harness({ navigation = null, beforeInput = () => {} } = {}) {
viewer,
annotations,
navigation,
markActions,
publish: (view) => (shown.view = view),
connect: (actions) => {
controls.actions = actions;
@@ -288,7 +308,11 @@ test('Draw refuses to start when something else holds the pointer', async () =>
h.shown.view.hint,
'Directions is using the pointer — close it first.',
);
assert.equal(h.tool.diagnostics().sceneHandler, false, 'no handler was bound');
assert.equal(
h.tool.diagnostics().sceneHandler,
false,
'no handler was bound',
);
releasePointer(other);
h.act('toggleDraw');
@@ -330,7 +354,10 @@ test('both stock viewer click actions are held off for the session and given bac
const h = harness({
beforeInput(viewer) {
viewer.screenSpaceEventHandler.setInputAction(stockClick, LEFT_CLICK);
viewer.screenSpaceEventHandler.setInputAction(stockDouble, LEFT_DOUBLE_CLICK);
viewer.screenSpaceEventHandler.setInputAction(
stockDouble,
LEFT_DOUBLE_CLICK,
);
},
});
try {
@@ -371,20 +398,34 @@ test('Enter finishes from the canvas and the label field, never from a focused b
h.tool.addVertex(-97.74, 30.27);
// Enter while the Clear button has keyboard focus means "press Clear".
h.documentDouble.emit('keydown', { key: 'Enter', target: h.element('draw-clear') });
h.documentDouble.emit('keydown', {
key: 'Enter',
target: h.element('draw-clear'),
});
await Promise.resolve();
assert.equal(
h.annotations.calls.annotate.length,
0,
'a focused button keeps its own Enter',
);
assert.equal(h.tool.session.vertices.length, 3, 'and the shape is untouched');
assert.equal(
h.tool.session.vertices.length,
3,
'and the shape is untouched',
);
// Enter from the page body (the canvas has focus in practice) finishes it.
h.documentDouble.emit('keydown', { key: 'Enter', target: h.documentDouble.body });
h.documentDouble.emit('keydown', {
key: 'Enter',
target: h.documentDouble.body,
});
await Promise.resolve();
await Promise.resolve();
assert.equal(h.annotations.calls.annotate.length, 1, 'Enter on the map finishes');
assert.equal(
h.annotations.calls.annotate.length,
1,
'Enter on the map finishes',
);
assert.equal(h.annotations.calls.annotate[0].specs[0].type, 'area');
} finally {
h.restore();
@@ -407,14 +448,21 @@ test('the live preview hangs at the height the click landed on', async () => {
const band = [...h.draw.sets.values()]
.find((set) => !set.disposed && set.kind === 'lines')
.items.get('band');
assert.equal(band.positions.length, 2, 'the rubber band joins the vertices');
assert.equal(
band.positions.length,
2,
'the rubber band joins the vertices',
);
assert.equal(band.mode, 'geodesic', 'it follows the globe, not draped');
assert.ok(Math.abs(heights[0] - 187.5) < 0.5, `got ${heights[0]}`);
assert.ok(Math.abs(heights[1] - 212.25) < 0.5, `got ${heights[1]}`);
// …and the finished shape is still flattened, deliberately: the renderer
// drapes, so a height carried further would be discarded out of sight.
h.documentDouble.emit('keydown', { key: 'Enter', target: h.documentDouble.body });
h.documentDouble.emit('keydown', {
key: 'Enter',
target: h.documentDouble.body,
});
await Promise.resolve();
await Promise.resolve();
const spec = h.annotations.calls.annotate[0].specs[0];
@@ -431,18 +479,29 @@ test('the rubber band follows the pointer, closes an area and takes the chosen c
const h = harness();
try {
const sets = () => [...h.draw.sets.values()].filter((set) => !set.disposed);
const band = () => sets().find((set) => set.kind === 'lines').items.get('band');
const band = () =>
sets()
.find((set) => set.kind === 'lines')
.items.get('band');
h.act('toggleDraw');
h.tool.setShape('area');
h.tool.addVertex(-97.75, 30.26);
assert.equal(band(), undefined, 'one vertex and no pointer draw no band');
h.tool.addVertex(-97.74, 30.26);
h.tool.addVertex(-97.74, 30.27);
assert.equal(band().positions.length, 4, 'an area of three closes back to its first vertex');
assert.equal(
band().positions.length,
4,
'an area of three closes back to its first vertex',
);
assert.deepEqual(band().positions[3], band().positions[0]);
h.tool.setColor('red');
assert.deepEqual(band().style.color, [1, 107 / 255, 107 / 255, 0.9], 'the band takes the colour');
assert.deepEqual(
band().style.color,
[1, 107 / 255, 107 / 255, 0.9],
'the band takes the colour',
);
assert.deepEqual(
band().depthFailColor,
[139 / 255, 233 / 255, 1, 0.35],
@@ -467,7 +526,11 @@ test('destroy in the same tick as init disposes the preview sets', async () => {
assert.equal(live().length, 2, 'the rubber band and the vertex dots');
await h.tool.destroy();
assert.equal(live().length, 0, 'nothing is left drawn behind the teardown');
assert.equal(h.tool.diagnostics().previewSets, 0, 'no live tool draws a preview');
assert.equal(
h.tool.diagnostics().previewSets,
0,
'no live tool draws a preview',
);
} finally {
h.restore();
}
@@ -490,7 +553,11 @@ test('destroy releases the pointer, the handler, the listeners and the stock act
assert.equal(isPointerFree(), true, 'the pointer is free');
const after = h.tool.diagnostics();
assert.equal(after.destroyed, true);
assert.equal(after.sceneHandler, false, 'the pointer subscriptions are gone');
assert.equal(
after.sceneHandler,
false,
'the pointer subscriptions are gone',
);
assert.equal(after.domListeners, 0, 'every DOM listener came off');
assert.equal(h.documentDouble.listeners.length, 0, 'including the keydown');
assert.equal(h.controls.actions, null, 'and the controls are disconnected');
@@ -500,7 +567,11 @@ test('destroy releases the pointer, the handler, the listeners and the stock act
'the viewer got its selecting click back',
);
assert.equal(after.previewSets, 0, 'the preview sets are disposed');
assert.equal(h.annotations.listeners.size, 0, 'and it no longer follows the board');
assert.equal(
h.annotations.listeners.size,
0,
'and it no longer follows the board',
);
// Idempotent: a second destroy is harmless.
await h.tool.destroy();
@@ -519,7 +590,11 @@ test('Clear wipes the board and the shape in progress', async () => {
h.act('clearDraw');
assert.equal(h.annotations.calls.clear, 1, 'placed marks are removed');
assert.equal(h.tool.session.vertices.length, 0, 'and so is the shape in progress');
assert.equal(
h.tool.session.vertices.length,
0,
'and so is the shape in progress',
);
} finally {
h.restore();
}
@@ -533,7 +608,13 @@ test('the controls choose the shape and colour the next shape is drawn with; it
h.act('setDrawColor', 'amber');
assert.deepEqual(
{ ...h.shown.view, hint: undefined },
{ active: true, shape: 'line', color: 'amber', hint: undefined, marks: [] },
{
active: true,
shape: 'line',
color: 'amber',
hint: undefined,
marks: [],
},
'the view shows what the controls chose',
);
h.act('setDrawColor', 'purple');
@@ -545,7 +626,10 @@ test('the controls choose the shape and colour the next shape is drawn with; it
assert.equal(h.tool.session.vertices.length, 0);
h.tool.addVertex(-97.75, 30.26);
h.tool.addVertex(-97.74, 30.26);
h.documentDouble.emit('keydown', { key: 'Enter', target: h.documentDouble.body });
h.documentDouble.emit('keydown', {
key: 'Enter',
target: h.documentDouble.body,
});
await Promise.resolve();
await Promise.resolve();
const spec = h.annotations.calls.annotate[0].specs[0];
@@ -570,12 +654,31 @@ test('each drawn shape is a row whose actions reach the board, and fly-to is a n
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 },
{
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 })),
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',
);
@@ -590,7 +693,11 @@ test('each drawn shape is a row whose actions reach the board, and fly-to is a n
]);
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(
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 {
@@ -598,36 +705,321 @@ test('each drawn shape is a row whose actions reach the board, and fly-to is a n
}
});
test("an application's row actions show on the shapes they are for and run with the shape", async () => {
const ran = [];
const h = harness({
markActions: [
{
id: 'tag',
icon: 'sell',
label: (name) => `Tag ${name}`,
shapes: ['area', 'line'],
run: (shape) => ran.push(['tag', shape]),
},
{
id: 'measure',
icon: 'straighten',
label: (name) => `Measure ${name}`,
shapes: ['area'],
accepts: (geometry) => geometry.type === 'Polygon',
run: (shape) => ran.push(['measure', shape]),
},
],
});
try {
const board = h.annotations;
board.marks.push(
{
id: 'r1',
type: 'area',
manual: true,
name: 'Strait',
color: 'primary',
hidden: false,
ring: [
[29, 41],
[29.1, 41],
[29.1, 41.1],
],
},
{
id: 'l1',
type: 'route',
manual: true,
name: null,
label: '9 km',
color: 'amber',
hidden: false,
path: [
{ lon: 29, lat: 41.05, height: 0 },
{ lon: 29.1, lat: 41.05, height: 0 },
],
},
{
id: 'p1',
type: 'pin',
manual: true,
name: 'Camp',
color: 'red',
hidden: false,
},
);
board.changed();
assert.deepEqual(
h.shown.view.marks.map(({ id, actions }) => [id, actions]),
[
[
'r1',
[
{ id: 'tag', icon: 'sell', label: 'Tag Strait' },
{ id: 'measure', icon: 'straighten', label: 'Measure Strait' },
],
],
['l1', [{ id: 'tag', icon: 'sell', label: 'Tag Line · 9 km' }]],
['p1', []],
],
);
assert.equal(h.act('runDrawMarkAction', 'l1', 'tag'), true);
assert.equal(
h.act('runDrawMarkAction', 'l1', 'measure'),
false,
'a line is not offered an area action',
);
assert.equal(h.act('runDrawMarkAction', 'p1', 'tag'), false);
assert.equal(h.act('runDrawMarkAction', 'gone', 'tag'), false);
assert.equal(h.act('runDrawMarkAction', 'r1', 'measure'), true);
assert.deepEqual(ran, [
[
'tag',
{
id: 'l1',
shape: 'line',
name: '',
title: 'Line · 9 km',
geometry: {
type: 'LineString',
coordinates: [
[29, 41.05],
[29.1, 41.05],
],
},
},
],
[
'measure',
{
id: 'r1',
shape: 'area',
name: 'Strait',
title: 'Strait',
geometry: {
type: 'Polygon',
coordinates: [
[
[29, 41],
[29.1, 41],
[29.1, 41.1],
[29, 41],
],
],
},
},
],
]);
} finally {
h.restore();
}
});
test('an action that throws is reported and leaves the row alone', async () => {
const h = harness({
markActions: [
{
id: 'boom',
icon: 'bolt',
label: () => {
throw new Error('label');
},
shapes: ['area'],
run: () => {
throw new Error('run');
},
},
],
});
const warn = console.warn;
const warned = [];
console.warn = (...args) => warned.push(args[0]);
try {
h.annotations.marks.push({
id: 'r1',
type: 'area',
manual: true,
name: null,
color: 'primary',
hidden: false,
ring: [
[0, 0],
[1, 0],
[1, 1],
],
});
h.annotations.changed();
assert.deepEqual(h.shown.view.marks[0].actions, [
{ id: 'boom', icon: 'bolt', label: 'boom' },
]);
assert.equal(h.act('runDrawMarkAction', 'r1', 'boom'), false);
assert.deepEqual(warned, ['[draw] boom failed']);
} finally {
console.warn = warn;
h.restore();
}
});
test("what a row action answers is its row's note; the row is busy until then, and a removed shape drops it", async () => {
const pending = [];
const h = harness({
markActions: [
{
id: 'measure',
icon: 'straighten',
label: (name) => `Measure ${name}`,
shapes: ['area'],
run: () =>
new Promise((resolve, reject) => pending.push({ resolve, reject })),
},
{
id: 'now',
icon: 'bolt',
label: () => 'Now',
shapes: ['area'],
run: () => ' 12 km² ',
},
{
id: 'long',
icon: 'notes',
label: () => 'Long',
shapes: ['area'],
run: () => `${'word '.repeat(60)}end`,
},
],
});
const warn = console.warn;
console.warn = () => {};
try {
const board = h.annotations;
const area = (id) => ({
id,
type: 'area',
manual: true,
name: null,
color: 'primary',
hidden: false,
ring: [
[0, 0],
[1, 0],
[1, 1],
],
});
board.marks.push(area('r1'), area('r2'));
board.changed();
const row = (id) => h.shown.view.marks.find((entry) => entry.id === id);
assert.equal(h.act('runDrawMarkAction', 'r1', 'now'), true);
assert.deepEqual([row('r1').busy, row('r1').note], [false, '12 km²']);
h.act('runDrawMarkAction', 'r1', 'long');
assert.ok(
row('r1').note.length <= 200 && row('r1').note.endsWith('word…'),
'a long note is cut at a word',
);
assert.equal(h.act('runDrawMarkAction', 'r1', 'measure'), true);
assert.deepEqual([row('r1').busy, row('r1').note], [true, '']);
assert.equal(
h.act('runDrawMarkAction', 'r1', 'now'),
false,
'a busy row takes no second press',
);
pending[0].resolve('412 km², 38 km of edge');
await new Promise((resolve) => setTimeout(resolve, 0));
assert.deepEqual(
[row('r1').busy, row('r1').note],
[false, '412 km², 38 km of edge'],
);
h.act('runDrawMarkAction', 'r1', 'measure');
pending[1].reject(new Error('refused'));
await new Promise((resolve) => setTimeout(resolve, 0));
assert.deepEqual(
[row('r1').busy, row('r1').note],
[false, ''],
'a failure clears the note',
);
h.act('runDrawMarkAction', 'r2', 'measure');
board.marks.splice(1, 1);
board.changed();
pending[2].resolve('late');
await new Promise((resolve) => setTimeout(resolve, 0));
assert.equal(row('r2'), undefined);
board.marks.push(area('r2'));
board.changed();
assert.deepEqual(
[row('r2').busy, row('r2').note],
[false, ''],
'a late answer never reaches a shape that went',
);
} finally {
console.warn = warn;
h.restore();
}
});
test('Backspace on the page removes the last vertex', () => {
const h = harness();
try {
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 });
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 () => {
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);
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: 'Escape', target: listButton });
assert.equal(h.tool.session.vertices.length, 2, 'Escape in the list keeps the shape');
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: h.documentDouble.body });
assert.equal(h.tool.session.vertices.length, 0, 'Escape on the page drops the open shape');
assert.equal(
h.annotations.calls.annotate.length,
0,
'another field keeps its Enter',
);
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();
}