Merge upstream main into denis/rail-layer

This commit is contained in:
Denis Groshev committed 2026-11-11 18:02:52 +01:00
commit 13818d0b9f
87 files changed
+7438 -144

No files matched your search

+23 -11
View File
@@ -535,14 +535,26 @@ export function createModel({
return `${isolate(latPart)} ${isolate(lonPart)}`;
}
/**
* Millisecond delta → `{ unit: '<1h' | 'h' | 'd', count }`, or null for
* invalid input. Both age formatters read it, so they pick the same unit.
*/
function ageParts(deltaMs) {
if (!Number.isFinite(deltaMs) || deltaMs < 0) return null;
const hours = deltaMs / 3600000;
if (hours < 1) return { unit: '<1h', count: 0 };
const wholeHours = Math.round(hours);
if (wholeHours < 48) return { unit: 'h', count: wholeHours };
return { unit: 'd', count: Math.round(hours / 24) };
}
/** Millisecond delta → "<1h" / "Xh" / "Xd", or '' for invalid input. */
function formatAge(deltaMs) {
if (!Number.isFinite(deltaMs) || deltaMs < 0) return '';
const hours = deltaMs / 3600000;
if (hours < 1) return '<1h';
if (hours < 48) return `${Math.round(hours)}h`;
return `${Math.round(hours / 24)}d`;
const age = ageParts(deltaMs);
if (!age) return '';
return age.unit === '<1h' ? '<1h' : `${age.count}${age.unit}`;
}
/** Millisecond delta → "<1m ago" / "Xm ago" / "Xh ago" (fresh-feed readout). */
@@ -573,12 +585,12 @@ export function createModel({
/** formatAge for a card: "<1h", "24h", "3d" in the UI language ("24 ч"). */
function formatAgeLabel(deltaMs) {
if (!Number.isFinite(deltaMs) || deltaMs < 0) return '';
const hours = deltaMs / 3600000;
if (hours < 1) return t('<1h', { context: 'age' });
if (hours < 48)
return t('{count}h', { context: 'age', count: Math.round(hours) });
return t('{count}d', { context: 'age', count: Math.round(hours / 24) });
const age = ageParts(deltaMs);
if (!age) return '';
if (age.unit === '<1h') return t('<1h', { context: 'age' });
return age.unit === 'h'
? t('{count}h', { context: 'age', count: age.count })
: t('{count}d', { context: 'age', count: age.count });
}
/** Normalized 0..1 confidence → low/nominal/high display bucket. */
+45
View File
@@ -0,0 +1,45 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { getLocale, setLocale } from '../../i18n/index.js';
import { createModel } from './model.js';
const HOUR_MS = 3600000;
test('a fire age that rounds to 48 hours reads in days, as 48 hours does', () => {
const previousLocale = getLocale();
const { formatAge, formatAgeLabel } = createModel({
services: { anchors: {} },
});
try {
setLocale('en');
assert.equal(formatAge(47.4 * HOUR_MS), '47h');
assert.equal(formatAge(47.5 * HOUR_MS), '2d');
assert.equal(formatAge(47.6 * HOUR_MS), '2d');
assert.equal(formatAge(48 * HOUR_MS), '2d');
assert.equal(formatAgeLabel(47.4 * HOUR_MS), '47h');
assert.equal(formatAgeLabel(47.5 * HOUR_MS), '2d');
assert.equal(formatAgeLabel(47.6 * HOUR_MS), formatAgeLabel(48 * HOUR_MS));
assert.equal(formatAgeLabel(48 * HOUR_MS), '2d');
} finally {
setLocale(previousLocale);
}
});
test('both fire age formatters agree on invalid, sub-hour and multi-day ages', () => {
const previousLocale = getLocale();
const { formatAge, formatAgeLabel } = createModel({
services: { anchors: {} },
});
try {
setLocale('en');
for (const format of [formatAge, formatAgeLabel]) {
assert.equal(format(-1), '');
assert.equal(format(Number.NaN), '');
assert.equal(format(0.5 * HOUR_MS), '<1h');
assert.equal(format(1 * HOUR_MS), '1h');
assert.equal(format(72 * HOUR_MS), '3d');
}
} finally {
setLocale(previousLocale);
}
});
+195 -18
View File
@@ -15,13 +15,14 @@ import {
keyAlternatives,
summarizeCoverage,
} from './uiState.js';
import { groundUnderCamera, viewCentre } from './view.js';
import { groundUnderCamera, metresBetween, viewCentre } from './view.js';
import { createGroundClick, groundClickHeightOk } from './groundClick.js';
import { msg, t, translateKnown } from '../../i18n/index.js';
import {
AIM_AT_GROUND_MESSAGE,
keyStatusLabel,
NEAREST_RADIUS_M,
NEAREST_RADIUS_MAX_M,
POSITION_PICK_ID,
STREET_LEVEL_LAYER_ID,
} from './policy.js';
@@ -33,6 +34,11 @@ const KEY_STATUS_TIMEOUT_MS = 10_000;
/** Re-measures of a ground not loaded yet (Google 3D), a second apart. */
const GROUND_RETRY_LIMIT = 5;
const GROUND_RETRY_MS = 1000;
/**
* An armed point stays the OPEN button's target while the view centre is
* this close to it (m); a user who moved on opens what the view shows now.
*/
const ARMED_REACH_M = 1000;
/**
* The Street Level layer over imagery providers (contract in registry.js).
@@ -170,6 +176,12 @@ export function createStreetLevelLayer({
const owner = state.providers.get(state.street.providerId);
if (state.street.open && owner && !providerAvailable(owner))
layer.closeViewer();
// An armed lookup for a source whose map left dies too.
const armedFor = state.street.armed?.providerIds?.map((id) =>
state.providers.get(id),
);
if (armedFor?.some((entry) => entry && !providerAvailable(entry)))
state.street.armed = null;
for (const entry of state.providers.values()) {
if (!entry.def.requiresMapStack) continue;
if (state.enabled && entry.on && providerAvailable(entry))
@@ -254,8 +266,11 @@ export function createStreetLevelLayer({
if (providerAvailable(entry)) parts.credits.show(state.viewer, entry.def);
}
/** Sources whose open photo a replacing request keeps up while it switches them off. */
const heldViewers = new Map();
function deactivate(entry) {
parts.viewerHost.unmount(entry.def.id);
if (!heldViewers.has(entry.def.id)) parts.viewerHost.unmount(entry.def.id);
entry.instance.deactivate();
parts.credits.hide(state.viewer, entry.def);
}
@@ -268,6 +283,13 @@ export function createStreetLevelLayer({
nearestLookup = null;
}
/** Close the image and deselect its sequence on the map. */
function closeViewer() {
abortNearest();
parts.viewerHost.close();
parts.clearSequences();
}
/** Ground under the screen centre; null for sky, undefined when it cannot aim. */
function screenCentreGround() {
const canvas = state.viewer?.scene?.canvas;
@@ -288,8 +310,14 @@ export function createStreetLevelLayer({
}
/** `frame: false` keeps the camera where it is (the user picked the spot). */
function openImage(providerId, imageId, { frame = true } = {}) {
function openImage(
providerId,
imageId,
{ frame = true, signal = null } = {},
) {
if (signal?.aborted) return Promise.resolve(false);
abortNearest();
state.street.armed = null;
const entry = state.providers.get(providerId);
if (entry && !providerAvailable(entry)) {
state.street.loading = false;
@@ -297,7 +325,7 @@ export function createStreetLevelLayer({
notify();
return Promise.resolve(false);
}
return parts.viewerHost.open(providerId, imageId, { frame });
return parts.viewerHost.open(providerId, imageId, { frame, signal });
}
function unavailableReason(entry) {
@@ -343,6 +371,9 @@ export function createStreetLevelLayer({
function switchProvider(entry, on) {
if (entry.on === on) return;
entry.on = on;
// A lookup armed for this source dies with it.
if (!on && state.street.armed?.providerIds?.includes(entry.def.id))
state.street.armed = null;
if (!state.enabled) return;
if (on) activate(entry);
else deactivate(entry);
@@ -479,6 +510,33 @@ export function createStreetLevelLayer({
},
/** Registered providers, in chip order. */
providerIds: defs.map((def) => def.id),
/** The map stack a provider needs (`requiresMapStack`), or null for any. */
requiredMapStack(providerId) {
const def = defs.find((entry) => entry.id === providerId);
return def?.requiresMapStack || null;
},
/**
* A provider's name and key state on any map (the panel lists a provider
* only on the map it needs). `configured` is null until its status call
* answers; `keyRequired` covers a missing or refused key.
*/
providerStatus(providerId) {
const entry = state.providers.get(providerId);
if (!entry) return null;
const stats = entry.instance.coverageStats();
return {
id: entry.def.id,
name: entry.def.name,
on: entry.on,
configured: entry.status ? entry.status.configured === true : null,
keyRequired: stats.keyRequired === true || stats.keyRejected === true,
keyRejected: stats.keyRejected === true,
groundClick: entry.def.groundClick === true,
billed: entry.def.billedPerImage === true,
available: providerAvailable(entry),
error: stats.error || null,
};
},
getSourceAvailability() {
const available = defs.length > 0;
return {
@@ -636,19 +694,66 @@ export function createStreetLevelLayer({
* Open the nearest image of the active providers (or `providerIds`) near
* a point, else the view centre, or with `aim: 'screen-centre'` the ground
* under the screen centre (sky: nothing). Providers without
* `nearestImage` are skipped.
* `nearestImage` are skipped. Options:
* - `radiusM` widens the search where a provider can (a geocoded landmark
* is rarely within 50 m of a street);
* - `signal` retires the lookup: nothing opens after it fires;
* - `armed: false` (the assistant's own request) ignores a link's armed
* point and keeps it until a photo opens;
* - `replace: true` keeps an open photo (and EXPAND) up while it looks and
* closes it if nothing opens;
* - `proceed()` is asked before a found photo loads or an empty lookup
* reports; false retires the request and leaves the panel as it was.
* Why nothing opened is in `street.nearestOutcome`: 'empty', 'sky' or
* null (an error).
*/
async openNearest(
point,
{ providerIds = null, frame = true, aim = 'view' } = {},
{
providerIds = null,
frame = true,
aim = 'view',
radiusM = null,
signal: callerSignal = null,
armed: useArmed = true,
replace = false,
proceed = null,
} = {},
) {
if (callerSignal?.aborted) return false;
state.street.nearestOutcome = null;
// An OPEN press after a link armed a lookup opens what the link asked;
// any other lookup is a new request and drops the armed one.
const armed = useArmed ? state.street.armed : null;
if (useArmed) state.street.armed = null;
const closeReplaced = () => {
if (replace && state.street.open) closeViewer();
};
if (!point && aim === 'screen-centre' && armed) {
// OPEN promises the view centre: the link's spot only while the view
// still shows it, or when the view cannot be picked.
const centre = armed.point ? screenCentreGround() : null;
if (!armed.point) radiusM ??= armed.radiusM;
else if (
centre === undefined ||
(centre && metresBetween(centre, armed.point) <= ARMED_REACH_M)
) {
point = armed.point;
radiusM ??= armed.radiusM;
}
}
const radius = Number.isFinite(radiusM)
? Math.min(NEAREST_RADIUS_MAX_M, Math.max(1, radiusM))
: NEAREST_RADIUS_M;
let view = point;
if (!view && aim === 'screen-centre') {
view = screenCentreGround();
if (view === null) {
abortNearest();
closeReplaced();
state.street.loading = false;
state.street.error = AIM_AT_GROUND_MESSAGE;
state.street.nearestOutcome = 'sky';
notify();
return false;
}
@@ -660,6 +765,19 @@ export function createStreetLevelLayer({
const lookup = new AbortController();
nearestLookup = lookup;
const { signal } = lookup;
const onCallerAbort = () => lookup.abort();
callerSignal?.addEventListener('abort', onCallerAbort, { once: true });
const retired = () => {
callerSignal?.removeEventListener('abort', onCallerAbort);
// A newer lookup owns the panel, its spinner and its error.
if (nearestLookup !== lookup) return false;
nearestLookup = null;
if (state.street.loading) {
state.street.loading = false;
notify();
}
return false;
};
state.street.loading = true;
state.street.error = null;
notify();
@@ -674,49 +792,108 @@ export function createStreetLevelLayer({
try {
imageId = await entry.instance.nearestImage(
{ lat: view.lat, lon: view.lon },
{ signal },
radius === NEAREST_RADIUS_M
? { signal }
: { signal, radiusM: radius },
);
} catch (error) {
if (callerSignal?.aborted) return retired();
// Overtaken: whatever replaced it owns the panel, errors included.
if (signal.aborted) return false;
if (signal.aborted) return retired();
// One provider failing (no key, offline) must not hide the others.
lastError = error;
continue;
}
if (signal.aborted) return false;
if (callerSignal?.aborted) return retired();
if (signal.aborted) return retired();
if (!state.enabled) break;
// Switched off, or its map left, while it looked: try the next.
if (!imageId || !entry.on || !providerAvailable(entry)) continue;
if (proceed && proceed() !== true) return retired();
nearestLookup = null;
return openImage(entry.def.id, imageId, { frame });
callerSignal?.removeEventListener('abort', onCallerAbort);
// A sequence playing in the replaced photo would step past this one.
if (replace && state.street.open) parts.viewerHost.stopPlayback();
// The caller's signal still counts while the viewer mounts and loads.
return openImage(entry.def.id, imageId, {
frame,
signal: callerSignal,
});
}
if (nearestLookup === lookup) nearestLookup = null;
callerSignal?.removeEventListener('abort', onCallerAbort);
// Replaced while it looked: the panel is the newer lookup's.
if (nearestLookup !== lookup) return false;
// Given up by its caller: the panel stays as it was.
if (proceed && proceed() !== true) return retired();
nearestLookup = null;
closeReplaced();
// Switched off while it looked: nothing to open, nothing to report.
const stillOn = entries.some(
(entry) => entry.on && providerAvailable(entry),
);
// A provider's own refusal is English data that the panel translates;
// the core's refusal is built here, for the panel only, in the language.
if (state.enabled && stillOn && !lastError)
state.street.nearestOutcome = 'empty';
if (state.enabled && stillOn)
state.street.error =
lastError?.message ||
(point
? t('No street-level imagery within {radius} m of that point', {
radius: NEAREST_RADIUS_M,
radius,
})
: t(
'No street-level imagery within {radius} m of the view centre',
{ radius: NEAREST_RADIUS_M },
{
radius,
},
));
state.street.loading = false;
notify();
return false;
},
/** Close the image and deselect its sequence on the map. */
closeViewer() {
abortNearest();
parts.viewerHost.close();
parts.clearSequences();
closeViewer,
/**
* Keep the open photo up while a request that replaces it switches its
* source off, so EXPAND stays; only that source's own switch-off is held,
* a source switched by hand meanwhile still stops a load. Release frees
* the old viewer.
*/
holdViewer() {
const id = state.street.open ? state.street.providerId : null;
if (!id) return () => {};
heldViewers.set(id, (heldViewers.get(id) || 0) + 1);
let held = true;
return () => {
if (!held) return;
held = false;
const left = heldViewers.get(id) - 1;
if (left > 0) return void heldViewers.set(id, left);
heldViewers.delete(id);
if (state.providers.get(id)?.on !== false) return;
// Its photo still up (the request gave up) closes with its source;
// otherwise the request replaced or closed it, and the panel keeps
// what that request left (an error, an armed OPEN).
if (state.street.open && state.street.providerId === id)
parts.viewerHost.unmount(id);
else parts.viewerHost.release(id);
};
},
/**
* Arm a nearest lookup for the next OPEN press without running it (a link
* to a source that bills every load). Any other lookup, open or close, the
* source switched off or its map leaving clears it.
*/
armNearest(point, { providerIds = null, radiusM = null } = {}) {
state.street.armed = {
point:
Number.isFinite(point?.lat) && Number.isFinite(point?.lon)
? { lat: point.lat, lon: point.lon }
: null,
providerIds: Array.isArray(providerIds) ? [...providerIds] : null,
radiusM: Number.isFinite(radiusM) ? radiusM : null,
};
notify();
},
setViewerRenderMode: (mode) => parts.viewerHost.setRenderMode(mode),
resizeViewer: () => parts.viewerHost.resize(),
+950 -2
View File
@@ -1,5 +1,6 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { getEventListeners } from 'node:events';
import * as Cesium from 'cesium';
import { createStreetLevelLayer } from './index.js';
import { MAPILLARY_CREDIT_HTML } from './providers/mapillary/policy.js';
@@ -12,6 +13,9 @@ import {
fakeStreetLevelProvider as fakeProvider,
} from '../../testSupport/streetLevelFakes.mjs';
import { setLocale } from '../../i18n/index.js';
// Loaded up front: it brings Vue, which reads `document` once when it loads,
// and several tests here stand a bare fake document in for the page.
import { createGevActionRunner } from '../../voice/gevActions.js';
/**
* A layer over `source` and `photoViewer`, initialised on a stand-in viewer
@@ -362,7 +366,11 @@ function fakeViewer() {
}
/** A layer over `providers`, initialised and enabled on a stand-in viewer. */
async function enabledLayer(t, providers = [fakeProvider()]) {
async function enabledLayer(
t,
providers = [fakeProvider()],
{ services, setup } = {},
) {
const saved = globalThis.document;
// A pose moves the position marker, whose glyph is drawn on a canvas.
const drawing = new Proxy({}, { get: () => () => ({ addColorStop() {} }) });
@@ -370,7 +378,11 @@ async function enabledLayer(t, providers = [fakeProvider()]) {
createElement: () => ({ getContext: () => drawing }),
});
const viewer = fakeViewer();
const layer = createStreetLevelLayer({ providers });
setup?.(viewer);
const layer = createStreetLevelLayer({
providers,
...(services ? { services } : {}),
});
layer.init(viewer);
layer.enable(viewer);
t.after(() => {
@@ -944,6 +956,54 @@ test('the button’s “centre of the view” is the ground under the middle of
assert.ok(Math.abs(lookups[0].lon - -121.4937) < 1e-9);
});
test('OPEN after a link armed opens at its point only while the view centre is still near it', async (t) => {
const { createStreetLevelLayer: create } = await import('./index.js');
const scenePick = await import('../../data/scenePick.js');
const lookups = [];
const provider = fakeProvider({
nearestImage: async (point, options) => {
lookups.push({ point, radiusM: options?.radiusM ?? null });
return null;
},
});
const saved = globalThis.document;
const drawing = new Proxy({}, { get: () => () => ({ addColorStop() {} }) });
globalThis.document = Object.assign(new EventTarget(), {
createElement: () => ({ getContext: () => drawing }),
});
const viewer = fakeViewer();
const centre = Cesium.Cartesian3.fromDegrees(-121.4937, 38.5799, 0);
Object.assign(viewer.scene, {
pickPositionSupported: true,
pickPosition: (at) => (at.x === 500 && at.y === 300 ? centre : undefined),
});
viewer.scene.canvas.clientWidth = 1000;
viewer.scene.canvas.clientHeight = 600;
const layer = create({ providers: [provider], services: { scenePick } });
layer.init(viewer);
layer.enable(viewer);
t.after(() => {
layer.destroy();
globalThis.document = saved;
});
// About 120 m from the view centre: the link's spot is still in view.
layer.armNearest({ lat: 38.5808, lon: -121.494 }, { radiusM: 250 });
await layer.openNearest(undefined, { aim: 'screen-centre' });
assert.deepEqual(lookups.at(-1), {
point: { lat: 38.5808, lon: -121.494 },
radiusM: 250,
});
// The user flew to Paris after the link armed in Sacramento: OPEN looks
// under the view centre, and the link's radius goes with its point.
layer.armNearest({ lat: 48.8584, lon: 2.2945 }, { radiusM: 250 });
await layer.openNearest(undefined, { aim: 'screen-centre' });
const press = lookups.at(-1);
assert.ok(Math.abs(press.point.lat - 38.5799) < 1e-9, 'the view centre');
assert.ok(Math.abs(press.point.lon - -121.4937) < 1e-9);
assert.equal(press.radiusM, null, 'the default radius');
assert.equal(layer.getUIState().street.armed, null, 'dropped');
});
test('the button aimed at the sky opens nothing, and says to aim at a street', async (t) => {
const { createStreetLevelLayer: create } = await import('./index.js');
const scenePick = await import('../../data/scenePick.js');
@@ -1118,6 +1178,732 @@ test('switching source by params clears a failed lookup’s error; reapplying th
assert.equal(second.getUIState().street.error, kept);
});
test('openNearest searches wider on request, never past the cap, and says how far it looked', async (t) => {
const { layer, fake } = await withStreetView(t, { nearest: () => null });
layer.setProviderEnabled('google', true);
await settle();
await layer.openNearest(
{ lat: 38.58, lon: -121.49 },
{ providerIds: ['google'], frame: false, radiusM: 250 },
);
assert.equal(fake.lookups.at(-1).radius, 250);
assert.equal(
layer.getUIState().street.error,
'No street-level imagery within 250 m of that point',
);
await layer.openNearest(
{ lat: 38.58, lon: -121.49 },
{ providerIds: ['google'], frame: false, radiusM: 5000 },
);
assert.equal(fake.lookups.at(-1).radius, 250, 'capped');
await layer.openNearest(
{ lat: 38.58, lon: -121.49 },
{ providerIds: ['google'], frame: false },
);
assert.equal(fake.lookups.at(-1).radius, 50, 'a click keeps the default');
});
test('a caller’s signal retires a nearest lookup: nothing opens after it fires', async (t) => {
let answer = null;
const { layer, fake } = await withStreetView(t, {
nearest: () => 'pano-a',
});
const lib = fake.library;
const service = lib.StreetViewService.prototype.getPanorama;
lib.StreetViewService.prototype.getPanorama = function (request) {
return new Promise((resolve, reject) => {
answer = () => service.call(this, request).then(resolve, reject);
});
};
layer.setProviderEnabled('google', true);
await settle();
const controller = new AbortController();
const pending = layer.openNearest(
{ lat: 38.58, lon: -121.49 },
{ providerIds: ['google'], frame: false, signal: controller.signal },
);
await settle();
controller.abort();
answer?.();
assert.equal(await pending, false);
const street = layer.getUIState().street;
assert.equal(street.open, false, 'the retired lookup opened nothing');
assert.equal(street.loading, false, 'no stuck spinner');
assert.equal(street.error, null, 'and reports no missing imagery');
const refused = await layer.openNearest(
{ lat: 38.58, lon: -121.49 },
{ providerIds: ['google'], frame: false, signal: controller.signal },
);
assert.equal(refused, false, 'an already-aborted signal asks nothing');
});
test('providerStatus reports name, key state and billing on any map', async (t) => {
const { layer } = await withStreetView(t, { mapStack: 'osm' });
const google = layer.providerStatus('google');
assert.equal(google.name, 'Google Street View');
assert.equal(google.billed, true, 'every Street View load is billed');
assert.equal(google.available, false, 'not on this map');
assert.equal(google.keyRequired, false);
assert.equal(layer.providerStatus('mapillary').billed, false);
assert.equal(layer.providerStatus('nope'), null);
assert.equal(layer.requiredMapStack('google'), 'photoreal');
assert.equal(layer.requiredMapStack('mapillary'), null);
});
test('an armed lookup asks nothing until the OPEN press, then opens at its point and radius once', async (t) => {
const { layer, fake, mapillaryLookups } = await withStreetView(t);
layer.setProviderEnabled('google', true);
await settle();
const before = fake.lookups.length;
layer.armNearest(
{ lat: 38.57986, lon: -121.49372 },
{ providerIds: ['google'], radiusM: 250 },
);
await settle();
await new Promise((resolve) => setTimeout(resolve, 20));
// The click gate: arming is free. No provider was asked, nothing opened.
assert.equal(
fake.lookups.length,
before,
'no Google lookup before the press',
);
assert.deepEqual(mapillaryLookups, [], 'no Mapillary lookup either');
assert.equal(layer.getUIState().street.open, false);
assert.equal(layer.getUIState().street.loading, false);
assert.deepEqual(layer.getUIState().street.armed, {
point: { lat: 38.57986, lon: -121.49372 },
providerIds: ['google'],
radiusM: 250,
});
// The OPEN button: no point, aimed at the screen centre.
const opened = await layer.openNearest(undefined, {
providerIds: ['google'],
frame: false,
aim: 'screen-centre',
});
assert.equal(opened, true);
assert.equal(
fake.lookups.length,
before + 1,
'exactly one lookup for the press',
);
const request = fake.lookups.at(-1);
assert.deepEqual(
request.location,
{ lat: 38.57986, lng: -121.49372 },
'the armed point, not the screen centre',
);
assert.equal(request.radius, 250);
assert.equal(layer.getUIState().street.armed, null, 'used once');
layer.armNearest({ lat: 1, lon: 2 }, { providerIds: ['google'] });
layer.closeViewer();
assert.equal(layer.getUIState().street.armed, null, 'closing clears it');
layer.armNearest({ lat: 1, lon: 2 }, { providerIds: ['google'] });
await layer.openNearest(
{ lat: 38.58, lon: -121.49 },
{ providerIds: ['google'], frame: false },
);
assert.deepEqual(
fake.lookups.at(-1).location,
{ lat: 38.58, lng: -121.49 },
'an explicit point wins',
);
assert.equal(layer.getUIState().street.armed, null);
// Only the OPEN press consumes the armed point: "street view here" after a
// pan is a new request at the view centre, and it drops the armed one.
layer.closeViewer();
layer.armNearest(
{ lat: 10, lon: 20 },
{ providerIds: ['google'], radiusM: 250 },
);
await layer.openNearest(null, { providerIds: ['google'], frame: false });
const centre = fake.lookups.at(-1);
assert.notDeepEqual(
centre.location,
{ lat: 10, lng: 20 },
'the view centre, not the armed point',
);
assert.equal(centre.radius, 50, 'and the default radius');
assert.equal(layer.getUIState().street.armed, null, 'dropped');
// Opening any image, or switching the layer off, clears it too.
layer.armNearest({ lat: 10, lon: 20 }, { providerIds: ['google'] });
await layer.openImage('google', 'pano-a');
assert.equal(layer.getUIState().street.armed, null, 'cleared by an open');
layer.armNearest({ lat: 10, lon: 20 }, { providerIds: ['google'] });
layer.disable();
assert.equal(layer.getUIState().street.armed, null, 'cleared by disable');
});
test('a caller’s signal: an aborted one asks nothing, and a provider that ignores the abort still opens nothing', async (t) => {
const { layer, fake } = await withStreetView(t);
layer.setProviderEnabled('google', true);
await settle();
const before = fake.lookups.length;
const done = new AbortController();
done.abort();
assert.equal(
await layer.openNearest(
{ lat: 38.58, lon: -121.49 },
{ providerIds: ['google'], frame: false, signal: done.signal },
),
false,
);
assert.equal(
fake.lookups.length,
before,
'an already-aborted signal asks nothing',
);
});
test('a provider that ignores the abort and answers late still opens nothing', async (t) => {
let seen = null;
let release = null;
const slow = fakeProvider({
nearestImage: async (_point, { signal } = {}) => {
seen = signal;
await new Promise((resolve) => {
release = resolve;
});
return 'late-image';
},
});
const { layer: ignoring } = await enabledLayer(t, [slow]);
const { fakeHost } =
await import('../../testSupport/googleStreetViewFakes.mjs');
ignoring.attachViewerHost(fakeHost());
const controller = new AbortController();
const pending = ignoring.openNearest(
{ lat: 1, lon: 2 },
{ frame: false, signal: controller.signal },
);
await settle();
controller.abort();
assert.equal(seen?.aborted, true, 'the provider sees the abort');
release();
assert.equal(await pending, false);
const street = ignoring.getUIState().street;
assert.equal(street.open, false, 'the late answer opened nothing');
assert.equal(street.loading, false, 'no stuck spinner');
assert.equal(street.error, null);
});
test('providerStatus reports a keyless source on any map', async (t) => {
const keyless = await withStreetView(t, {
mapStack: 'osm',
mapillaryKeyless: true,
});
await settle();
const mapillary = keyless.layer.providerStatus('mapillary');
assert.equal(mapillary.configured, false);
assert.equal(mapillary.keyRequired, true);
assert.equal(mapillary.keyRejected, false);
});
test('providerStatus reports the key state as unknown until the status call answers', async (t) => {
// A freshly loaded sl= link meets its source in this state: unknown is not
// "needs its key", or the link would fail on a cold load.
const pending = fakeProvider();
pending.requiresKeyId = 'mapillary';
const create = pending.create;
pending.create = (context) => ({
...create(context),
status: () => new Promise(() => {}),
});
const { layer } = await enabledLayer(t, [pending]);
const status = layer.providerStatus(pending.id);
assert.equal(status.configured, null);
assert.equal(status.keyRequired, false);
});
test('providerStatus reports a refused key on any map', async (t) => {
const refused = await withStreetView(t, { mapStack: 'osm' });
refused.loader.refuseKey();
await settle();
const google = refused.layer.providerStatus('google');
assert.equal(
google.keyRequired,
true,
'a refused key gates like a missing one',
);
assert.equal(google.keyRejected, true);
assert.equal(google.available, false, 'still not on this map');
});
test('an armed lookup dies with its source: switched off, or its map gone', async (t) => {
const { layer, stack } = await withStreetView(t);
layer.setProviderEnabled('google', true);
await settle();
layer.armNearest(
{ lat: 1, lon: 2 },
{ providerIds: ['google'], radiusM: 250 },
);
layer.setProviderEnabled('google', false);
assert.equal(
layer.getUIState().street.armed,
null,
'switching the source off clears it',
);
layer.setProviderEnabled('google', true);
layer.armNearest(
{ lat: 1, lon: 2 },
{ providerIds: ['google'], radiusM: 250 },
);
// Lighting Mapillary instead (one source at a time) turns Google off too.
layer.setProviderEnabled('mapillary', true);
assert.equal(
layer.getUIState().street.armed,
null,
'another source lit clears it',
);
layer.setProviderEnabled('google', true);
layer.armNearest(
{ lat: 1, lon: 2 },
{ providerIds: ['google'], radiusM: 250 },
);
// A map-stack notify that keeps Google 3D (a silent re-settle) keeps it.
stack.switchTo('photoreal');
assert.notEqual(
layer.getUIState().street.armed,
null,
'a notify on the same map keeps it',
);
stack.switchTo('osm');
assert.equal(
layer.getUIState().street.armed,
null,
'leaving Google 3D clears it',
);
// Arming notifies, so a panel can show the state.
let notified = 0;
const unsubscribe = layer.subscribe(() => notified++);
stack.switchTo('photoreal');
await settle();
const before = notified;
layer.armNearest({ lat: 1, lon: 2 }, { providerIds: ['google'] });
await settle();
assert.ok(notified > before, 'subscribers hear about the armed lookup');
unsubscribe();
});
test('a lookup armed with no point opens under the middle of the screen on the press', async (t) => {
const { createStreetLevelLayer: create } = await import('./index.js');
const scenePick = await import('../../data/scenePick.js');
const lookups = [];
const provider = fakeProvider({
nearestImage: async (point, options) => {
lookups.push({ ...point, radiusM: options?.radiusM ?? null });
return null;
},
});
const saved = globalThis.document;
const drawing = new Proxy({}, { get: () => () => ({ addColorStop() {} }) });
globalThis.document = Object.assign(new EventTarget(), {
createElement: () => ({ getContext: () => drawing }),
});
const viewer = fakeViewer();
const centre = Cesium.Cartesian3.fromDegrees(-121.4937, 38.5799, 0);
Object.assign(viewer.scene, {
pickPositionSupported: true,
pickPosition: (at) => (at.x === 500 && at.y === 300 ? centre : undefined),
});
viewer.scene.canvas.clientWidth = 1000;
viewer.scene.canvas.clientHeight = 600;
// Registered before the layer exists, so a throwing create() still
// restores the document; destroy() runs first, while the stub is in place.
let layer = null;
t.after(() => {
layer?.destroy();
globalThis.document = saved;
});
layer = create({ providers: [provider], services: { scenePick } });
layer.init(viewer);
layer.enable(viewer);
layer.armNearest(null, { providerIds: [provider.id], radiusM: 250 });
assert.equal(
layer.getUIState().street.armed.point,
null,
'no point stored, not 0,0',
);
await layer.openNearest(undefined, { aim: 'screen-centre' });
assert.equal(lookups.length, 1);
assert.ok(
Math.abs(lookups[0].lat - 38.5799) < 1e-9,
'the screen centre, not Null Island',
);
assert.ok(Math.abs(lookups[0].lon - -121.4937) < 1e-9);
assert.equal(lookups[0].radiusM, 250, 'with the armed radius');
});
test('the action over the real layer: a billed link arms without a lookup, and one press makes exactly one at the point', async (t) => {
const { layer, fake, viewer } = await withStreetView(t);
// The runner wires pointer tracking to the clock and camera.
viewer.clock ??= { onTick: { addEventListener: () => () => {} } };
viewer.camera.moveEnd ??= { addEventListener() {} };
const dataManager = {
layers: new Map([['street-level', { module: layer }]]),
isEnabled: () => true,
getLayerParams: () => layer.getParams(),
setLayerParams: (_id, params) => {
layer.setParams(params);
return true;
},
getAll: () => [{ id: 'street-level', name: 'Street Level', enabled: true }],
};
const styleManager = {
mapStackController: { getActiveId: () => 'photoreal' },
setMapStack: async () => ({ ok: true, activeStack: 'photoreal' }),
};
const runner = createGevActionRunner({ viewer, styleManager, dataManager });
const before = fake.lookups.length;
const armed = await runner('show_street_level', {
latitude: 38.57986,
longitude: -121.49372,
provider: 'google',
fly: false,
autoOpen: false,
});
assert.equal(armed.ok, true, armed.error);
assert.equal(armed.armed, true);
assert.equal(armed.providerName, 'Google Street View');
await settle();
assert.equal(fake.lookups.length, before, 'arming made no Google request');
assert.deepEqual(
layer
.getUIState()
.providers.filter((p) => p.on)
.map((p) => p.id),
['google'],
);
assert.equal(layer.getUIState().street.open, false);
// The OPEN button.
assert.equal(
await layer.openNearest(undefined, {
providerIds: ['google'],
frame: false,
aim: 'screen-centre',
}),
true,
);
assert.equal(fake.lookups.length, before + 1, 'one request for the press');
assert.deepEqual(fake.lookups.at(-1).location, {
lat: 38.57986,
lng: -121.49372,
});
assert.equal(fake.lookups.at(-1).radius, 250);
assert.equal(layer.getUIState().street.imageId, 'pano-a');
// The same call without the gate opens at once, with one request.
layer.closeViewer();
const opened = await runner('show_street_level', {
latitude: 38.57986,
longitude: -121.49372,
provider: 'google',
fly: false,
});
assert.equal(opened.ok, true, opened.error);
assert.equal(opened.imageId, 'pano-a');
assert.equal(fake.lookups.length, before + 2);
});
test('openNearest keeps honouring the caller after the lookup: an abort while the viewer loads opens nothing', async (t) => {
let releaseMount = null;
const provider = fakeProvider({ nearestImage: async () => 'img-1' });
const create = provider.create;
provider.create = (context) => {
const instance = create(context);
const mount = instance.viewer.mount;
instance.viewer.mount = async (...args) => {
await new Promise((resolve) => {
releaseMount = resolve;
});
return mount(...args);
};
return instance;
};
const { layer } = await enabledLayer(t, [provider]);
const { fakeHost } =
await import('../../testSupport/googleStreetViewFakes.mjs');
layer.attachViewerHost(fakeHost());
const controller = new AbortController();
const pending = layer.openNearest(
{ lat: 1, lon: 2 },
{ frame: false, signal: controller.signal },
);
for (let i = 0; i < 20 && !releaseMount; i++) await settle();
assert.ok(releaseMount, 'the lookup answered and the viewer is mounting');
controller.abort();
releaseMount();
assert.equal(await pending, false);
assert.deepEqual(provider.calls.open, [], 'the photo was never opened');
assert.equal(layer.getUIState().street.open, false);
assert.equal(layer.getUIState().street.loading, false);
});
for (const rejectsOnAbort of [true, false]) {
test(`cancelling a lookup over an open photo clears its spinner (provider rejects: ${rejectsOnAbort})`, async (t) => {
const answer = deferred();
const provider = fakeProvider({
nearestImage: (_point, { signal }) => {
if (rejectsOnAbort)
signal.addEventListener('abort', () => answer.reject(signal.reason), {
once: true,
});
return answer.promise;
},
});
const { layer } = await enabledLayer(t, [provider]);
const { fakeHost } =
await import('../../testSupport/googleStreetViewFakes.mjs');
layer.attachViewerHost(fakeHost());
assert.equal(
await layer.openImage('mapillary', 'existing', { frame: false }),
true,
);
const controller = new AbortController();
const pending = layer.openNearest(
{ lat: 1, lon: 2 },
{ frame: false, signal: controller.signal },
);
assert.equal(layer.getUIState().street.loading, true);
controller.abort();
if (!rejectsOnAbort) answer.resolve('late-image');
assert.equal(await pending, false);
const street = layer.getUIState().street;
assert.equal(
street.loading,
false,
'the cancelled lookup owns and clears the spinner',
);
assert.equal(street.open, true, 'the existing photo remains open');
assert.equal(street.error, null);
assert.deepEqual(
provider.calls.open,
['existing'],
'no replacement photo opens',
);
});
}
for (const rejectsOnAbort of [true, false]) {
test(`retired lookups release the caller listener (provider rejects: ${rejectsOnAbort})`, async (t) => {
let answer;
const provider = fakeProvider({
nearestImage: (_point, { signal }) => {
answer = deferred();
if (rejectsOnAbort)
signal.addEventListener('abort', () => answer.reject(signal.reason), {
once: true,
});
return answer.promise;
},
});
const { layer } = await enabledLayer(t, [provider]);
const lifetime = new AbortController();
for (let i = 0; i < 3; i++) {
const pending = layer.openNearest(
{ lat: 1, lon: 2 },
{ frame: false, signal: lifetime.signal },
);
assert.equal(getEventListeners(lifetime.signal, 'abort').length, 1);
layer.closeViewer();
if (!rejectsOnAbort) answer.resolve('late-image');
assert.equal(await pending, false);
assert.equal(
getEventListeners(lifetime.signal, 'abort').length,
0,
'closing the lookup releases its listener on the application lifetime',
);
}
assert.equal(lifetime.signal.aborted, false);
});
}
test('an aborted older lookup leaves its replacement’s spinner alone', async (t) => {
const answers = [];
const provider = fakeProvider({
nearestImage: (_point, { signal } = {}) =>
new Promise((resolve, reject) => {
answers.push(resolve);
signal?.addEventListener('abort', () =>
reject(Object.assign(new Error('aborted'), { name: 'AbortError' })),
);
}),
});
const { layer } = await enabledLayer(t, [provider]);
const { fakeHost } =
await import('../../testSupport/googleStreetViewFakes.mjs');
layer.attachViewerHost(fakeHost());
const older = new AbortController();
const first = layer.openNearest(
{ lat: 1, lon: 2 },
{ frame: false, signal: older.signal },
);
await settle();
// A newer request replaces it, and its caller withdraws the old one too.
const second = layer.openNearest({ lat: 3, lon: 4 }, { frame: false });
older.abort();
assert.equal(await first, false);
assert.equal(
layer.getUIState().street.loading,
true,
'the newer lookup is still loading',
);
answers.at(-1)(null);
assert.equal(await second, false);
assert.equal(layer.getUIState().street.loading, false);
assert.match(
layer.getUIState().street.error,
/No street-level imagery/,
'the newer lookup reports its own result',
);
});
test('show_street_level opens a KartaView photo, and a plain link opens it at once since it is not billed', async (t) => {
const mapillary = fakeProvider();
let nearest = 'kv-1';
const kartaview = fakeProvider({
id: 'kartaview',
pickPrefix: 'kv:',
nearestImage: async () => nearest,
});
kartaview.name = 'KartaView';
kartaview.label = 'KARTAVIEW';
kartaview.defaultOn = false;
// As the real provider: 360° / flat and SINCE (the setFilter log stays in
// the fake's closure).
kartaview.filters = Object.freeze(['pano', 'since']);
const { layer, viewer } = await enabledLayer(t, [mapillary, kartaview]);
const { fakeHost } =
await import('../../testSupport/googleStreetViewFakes.mjs');
layer.attachViewerHost(fakeHost());
viewer.clock ??= { onTick: { addEventListener: () => () => {} } };
viewer.camera.moveEnd ??= { addEventListener() {} };
const dataManager = {
layers: new Map([['street-level', { module: layer }]]),
isEnabled: () => true,
getLayerParams: () => layer.getParams(),
setLayerParams: (_id, params) => {
layer.setParams(params);
return true;
},
getAll: () => [{ id: 'street-level', name: 'Street Level', enabled: true }],
};
const styleManager = {
mapStackController: { getActiveId: () => 'osm' },
setMapStack: async () => ({ ok: false, error: 'no map switch expected' }),
};
const runner = createGevActionRunner({ viewer, styleManager, dataManager });
// The way a plain sl=kartaview link calls it: autoOpen false.
const result = await runner('show_street_level', {
latitude: 52.52,
longitude: 13.405,
provider: 'kartaview',
fly: false,
autoOpen: false,
});
assert.equal(result.ok, true, result.error);
assert.equal(result.armed, undefined, 'not armed: KartaView bills nothing');
assert.equal(result.provider, 'kartaview');
assert.equal(result.providerName, 'KartaView');
assert.deepEqual(
layer
.getUIState()
.providers.filter((p) => p.on)
.map((p) => p.id),
['kartaview'],
);
assert.deepEqual(kartaview.calls.open, ['kv-1']);
assert.equal(layer.providerStatus('kartaview').billed, false);
assert.equal(layer.requiredMapStack('kartaview'), null);
// With 360° only on, an empty search names the filter, not just "no imagery".
layer.closeViewer?.();
layer.setParams({ pano: 'pano' });
nearest = null;
const empty = await runner('show_street_level', {
latitude: 52.52,
longitude: 13.405,
provider: 'kartaview',
fly: false,
});
assert.deepEqual([empty.ok, empty.stage], [false, 'imagery']);
assert.equal(empty.filter?.pano, 'pano');
assert.match(empty.error, /with the 360° filter on$/);
layer.setParams({ pano: 'all' });
const plain = await runner('show_street_level', {
latitude: 52.52,
longitude: 13.405,
provider: 'kartaview',
fly: false,
});
assert.equal(plain.ok, false);
assert.equal(plain.filter, undefined, 'no filter, no hint');
assert.doesNotMatch(plain.error, /filter/);
});
test('show_street_level switches from KartaView to Panoramax and opens its photo at once, unbilled', async (t) => {
const mapillary = fakeProvider();
const kartaview = fakeProvider({ id: 'kartaview', pickPrefix: 'kv:' });
kartaview.name = 'KartaView';
kartaview.defaultOn = false;
const panoramax = fakeProvider({
id: 'panoramax',
pickPrefix: 'px:',
nearestImage: async () => 'px-1',
});
panoramax.name = 'Panoramax';
panoramax.label = 'PANORAMAX';
panoramax.defaultOn = false;
const { layer, viewer } = await enabledLayer(t, [
mapillary,
kartaview,
panoramax,
]);
const { fakeHost } =
await import('../../testSupport/googleStreetViewFakes.mjs');
layer.attachViewerHost(fakeHost());
viewer.clock ??= { onTick: { addEventListener: () => () => {} } };
viewer.camera.moveEnd ??= { addEventListener() {} };
layer.setParams({ mapillary: false, kartaview: true, panoramax: false });
const dataManager = {
layers: new Map([['street-level', { module: layer }]]),
isEnabled: () => true,
getLayerParams: () => layer.getParams(),
setLayerParams: (_id, params) => {
layer.setParams(params);
return true;
},
getAll: () => [{ id: 'street-level', name: 'Street Level', enabled: true }],
};
const styleManager = {
mapStackController: { getActiveId: () => 'osm' },
setMapStack: async () => ({ ok: false, error: 'no map switch expected' }),
};
const runner = createGevActionRunner({ viewer, styleManager, dataManager });
// The way a plain sl=panoramax link calls it: autoOpen false.
const result = await runner('show_street_level', {
latitude: 48.8874,
longitude: 2.3495,
provider: 'panoramax',
fly: false,
autoOpen: false,
});
assert.equal(result.ok, true, result.error);
assert.equal(result.armed, undefined, 'not armed: Panoramax bills nothing');
assert.equal(result.providerName, 'Panoramax');
assert.deepEqual(
layer
.getUIState()
.providers.filter((p) => p.on)
.map((p) => p.id),
['panoramax'],
'KartaView switched off',
);
assert.deepEqual(panoramax.calls.open, ['px-1']);
assert.deepEqual(kartaview.calls.open, [], 'nothing asked of KartaView');
assert.equal(layer.providerStatus('panoramax').billed, false);
assert.equal(layer.requiredMapStack('panoramax'), null);
});
test('the panel says why a lit Street View draws nothing off Google 3D', async (t) => {
const { presentStreetLevelPanel } =
await import('../../ui/streetLevelPresentation.js');
@@ -1128,6 +1914,88 @@ test('the panel says why a lit Street View draws nothing off Google 3D', async (
assert.match(view.meta, /Google Street View needs the Google 3D map/);
});
test('OPEN aimed at the sky after a link armed opens nothing: never the far link point', async (t) => {
const scenePick = await import('../../data/scenePick.js');
const lookups = [];
const provider = fakeProvider({
nearestImage: async (point) => {
lookups.push(point);
return null;
},
});
const { layer } = await enabledLayer(t, [provider], {
services: { scenePick },
setup: (viewer) => {
// Every pick misses the ground: the screen centre is sky.
Object.assign(viewer.scene, {
pickPositionSupported: true,
pickPosition: () => undefined,
});
viewer.globe = { pick: () => undefined };
viewer.scene.canvas.clientWidth = 1000;
viewer.scene.canvas.clientHeight = 600;
},
});
layer.armNearest({ lat: 48.8584, lon: 2.2945 }, { radiusM: 250 });
assert.equal(
await layer.openNearest(undefined, { aim: 'screen-centre' }),
false,
);
assert.deepEqual(lookups, [], 'no paid Paris lookup from another city’s sky');
const street = layer.getUIState().street;
assert.equal(street.nearestOutcome, 'sky');
assert.match(street.error, /Aim the middle of the view/);
});
test('a request of its own (armed: false) neither uses nor drops the link’s armed point', async (t) => {
const scenePick = await import('../../data/scenePick.js');
const lookups = [];
const provider = fakeProvider({
nearestImage: async (point, options) => {
lookups.push({ point, radiusM: options?.radiusM ?? null });
return null;
},
});
const centre = Cesium.Cartesian3.fromDegrees(-121.4937, 38.5799, 0);
const { layer } = await enabledLayer(t, [provider], {
services: { scenePick },
setup: (viewer) => {
Object.assign(viewer.scene, {
pickPositionSupported: true,
pickPosition: (at) =>
at.x === 500 && at.y === 300 ? centre : undefined,
});
viewer.scene.canvas.clientWidth = 1000;
viewer.scene.canvas.clientHeight = 600;
},
});
// About 120 m away: an OPEN press would take the link's spot.
layer.armNearest({ lat: 38.5808, lon: -121.494 }, { radiusM: 250 });
await layer.openNearest(undefined, { aim: 'screen-centre', armed: false });
const asked = lookups.at(-1);
assert.ok(Math.abs(asked.point.lat - 38.5799) < 1e-9, 'the screen centre');
assert.equal(asked.radiusM, null, 'its own radius');
assert.equal(layer.getUIState().street.nearestOutcome, 'empty');
assert.deepEqual(
layer.getUIState().street.armed?.point,
{ lat: 38.5808, lon: -121.494 },
'still armed for the OPEN press',
);
});
test('a failing source is not reported as missing imagery', async (t) => {
const provider = fakeProvider({
nearestImage: async () => {
throw new Error('Mapillary graph HTTP 500');
},
});
const { layer } = await enabledLayer(t, [provider]);
assert.equal(await layer.openNearest({ lat: 1, lon: 2 }), false);
const street = layer.getUIState().street;
assert.equal(street.nearestOutcome, null);
assert.equal(street.error, 'Mapillary graph HTTP 500');
});
/** Mapillary (keyless unless `mapillary` says otherwise) plus KartaView. */
function keylessLayer(t, mapillary = { hasToken: () => false }) {
const layer = createStreetLevelLayer({
@@ -1183,3 +2051,83 @@ test('filter-only updates keep the lit source, even a chosen keyless Mapillary',
);
}
});
test('a replacing lookup keeps the viewer open while it looks, so EXPAND stays with the new photo', async (t) => {
const answers = ['img-1', 'img-2'];
const provider = posingProvider({
nearestImage: async () => answers.shift(),
});
const { layer } = await enabledLayer(t, [provider]);
layer.attachViewerHost({});
assert.equal(await layer.openNearest({ lat: 1, lon: 2 }), true);
const seen = [];
const unsubscribe = layer.subscribe(() =>
seen.push(layer.getUIState().street.open),
);
t.after(unsubscribe);
assert.equal(
await layer.openNearest({ lat: 3, lon: 4 }, { replace: true }),
true,
);
assert.ok(seen.length > 0);
assert.ok(!seen.includes(false), 'never published closed on the way');
assert.deepEqual(provider.calls.open, ['img-1', 'img-2']);
});
test('a replacing lookup that finds nothing closes the old photo and keeps its own message', async (t) => {
const answers = ['img-1', null];
const provider = posingProvider({
nearestImage: async () => answers.shift(),
});
const { layer } = await enabledLayer(t, [provider]);
layer.attachViewerHost({});
await layer.openNearest({ lat: 1, lon: 2 });
assert.equal(
await layer.openNearest({ lat: 3, lon: 4 }, { replace: true }),
false,
);
const street = layer.getUIState().street;
assert.equal(street.open, false, 'no photo of another place');
assert.equal(street.nearestOutcome, 'empty');
assert.match(street.error, /No street-level imagery within 50 m/);
});
test('a found photo the viewer cannot load keeps its error on the open viewer', async (t) => {
const provider = posingProvider({ nearestImage: async () => 'img-1' });
const create = provider.create;
provider.create = (context) => {
const instance = create(context);
instance.viewer.open = async () => {
throw new Error('Image could not be opened');
};
return instance;
};
const { layer } = await enabledLayer(t, [provider]);
layer.attachViewerHost({});
assert.equal(
await layer.openNearest({ lat: 1, lon: 2 }, { replace: true }),
false,
);
const street = layer.getUIState().street;
assert.equal(street.open, true);
assert.equal(street.error, 'Image could not be opened');
});
test('proceed() is asked after the lookup: false loads nothing and clears the spinner', async (t) => {
const provider = posingProvider({ nearestImage: async () => 'img-1' });
const { layer } = await enabledLayer(t, [provider]);
layer.attachViewerHost({});
let asked = 0;
const opened = await layer.openNearest(
{ lat: 1, lon: 2 },
{ proceed: () => (asked++, false) },
);
assert.equal(opened, false);
assert.equal(asked, 1);
assert.deepEqual(provider.calls.open, [], 'the viewer never loads it');
assert.equal(layer.getUIState().street.loading, false);
assert.equal(
await layer.openNearest({ lat: 1, lon: 2 }, { proceed: () => true }),
true,
);
});
+8
View File
@@ -40,6 +40,14 @@ export const FILTER_DEFAULT = Object.freeze({ pano: 'all', sinceDays: 0 });
/** Nearest-image search radius in metres. */
export const NEAREST_RADIUS_M = 50;
/**
* Widest nearest-image radius a caller may ask for, in metres. A geocoded
* landmark sits at its centroid, often further than 50 m from the nearest
* street; providers that can search wider (Google) honour it, the rest keep
* their own cap.
*/
export const NEAREST_RADIUS_MAX_M = 250;
/** The Google 3D map stack: Street View may be shown only on it. */
export const GOOGLE_3D_MAP_STACK_ID = 'photoreal';
@@ -12,6 +12,7 @@ import {
GROUND_CLICK_HINT,
KEY_REJECTED_MESSAGE,
NEAREST_RADIUS_M,
NEAREST_RADIUS_MAX_M,
NEAREST_TIMEOUT_MS,
NO_ANSWER_MESSAGE,
PICK_PREFIX,
@@ -67,6 +68,7 @@ export function createGoogleProvider({
requiresMapStack: GOOGLE_3D_MAP_STACK_ID,
// Every panorama is billed to the Maps key.
defaultOn: false,
billedPerImage: true,
// All 360°, and no coverage for a date filter to thin.
filters: [],
marker: Object.freeze({ kind: 'view-cone', color: COLORS.coverage }),
@@ -136,8 +138,12 @@ export function createGoogleProvider({
* Nearest Google-collected outdoor panorama, or null. The imagery
* filters do not apply (see `filters`).
*/
async nearestImage({ lat, lon }, { signal } = {}) {
async nearestImage({ lat, lon }, { signal, radiusM } = {}) {
if (loader.authFailed()) throw new Error(KEY_REJECTED_MESSAGE);
// Wider than the shared default only on request, never past the cap.
const radius = Number.isFinite(radiusM)
? Math.min(NEAREST_RADIUS_MAX_M, Math.max(1, radiusM))
: NEAREST_RADIUS_M;
signal?.throwIfAborted();
// Set once the caller has its answer (aborted, timed out, refused):
// a lookup still waiting on Google's script then asks nothing.
@@ -150,7 +156,7 @@ export function createGoogleProvider({
try {
const { data } = await service.getPanorama({
location: { lat, lng: lon },
radius: NEAREST_RADIUS_M,
radius,
// Both: Google's own imagery, outdoors (sources intersect).
sources: [GOOGLE, OUTDOOR],
preference: lib.StreetViewPreference.NEAREST,
@@ -1,7 +1,7 @@
import { COLORS as SHARED_COLORS, PROVIDER_COLORS } from '../../policy.js';
import { msg } from '../../../../i18n/index.js';
export { NEAREST_RADIUS_M } from '../../policy.js';
export { NEAREST_RADIUS_M, NEAREST_RADIUS_MAX_M } from '../../policy.js';
export const GOOGLE_PROVIDER_ID = 'google';
export const GOOGLE_NAME = msg('Google Street View');
@@ -291,3 +291,13 @@ test('the panorama a lookup found is dated without a second lookup', async () =>
'no getPanorama({pano}) for a panorama the lookup already described',
);
});
test('a wider lookup radius is honoured up to the cap', async () => {
const { instance, fake } = setup();
await instance.nearestImage({ lat: 38.58, lon: -121.49 }, { radiusM: 250 });
assert.equal(fake.lookups.at(-1).radius, 250);
await instance.nearestImage({ lat: 38.58, lon: -121.49 }, { radiusM: 9999 });
assert.equal(fake.lookups.at(-1).radius, 250);
await instance.nearestImage({ lat: 38.58, lon: -121.49 }, { radiusM: NaN });
assert.equal(fake.lookups.at(-1).radius, 50);
});
@@ -5,6 +5,8 @@ import {
} from '../../lineCoverage.js';
import { createSequenceCones, thinImages } from '../../sequenceCones.js';
import { coverageZoomForHeight } from '../../tileMath.js';
import { passesImageryFilter } from '../../filter.js';
import { metresBetween } from '../../view.js';
import { decodeCoverageTile } from './decode.js';
import { createMapillaryViewer } from './viewer.js';
import {
@@ -195,6 +197,35 @@ export function createMapillaryProvider({ source, photoViewer = null }) {
error: state.sequence.error,
}),
/**
* The nearest image that passes the imagery filter, or null: what
* show_street_level and sl= links open (clicks open a line, then a
* cone). The core aborts `signal` once a newer request overtakes it.
*/
async nearestImage({ lat, lon }, { signal } = {}) {
const images = await source.nearestImages({ lat, lon }, { signal });
// The API returns the images in the radius in no particular order.
const metres = (record) => {
const [lon2, lat2] = (record.computed_geometry || record.geometry)
?.coordinates || [NaN, NaN];
const d = metresBetween({ lon, lat }, { lon: lon2, lat: lat2 });
return Number.isFinite(d) ? d : Infinity;
};
const filter = context.getFilter();
const hit = [...images]
.sort((a, b) => metres(a) - metres(b))
.find((record) =>
passesImageryFilter(
{
isPano: record.is_pano === true,
capturedAt: Number(record.captured_at) || 0,
},
filter,
),
);
return hit ? String(hit.id) : null;
},
viewer:
photoViewer ||
createMapillaryViewer({ source, render: context.services?.render }),
@@ -16,6 +16,7 @@ export const MAPILLARY_SOURCE_METHODS = Object.freeze([
'getStatus',
'getTile',
'getSequenceImages',
'nearestImages',
]);
/** Stable id prefixes for picked primitives; every one starts with `mly:`. */
@@ -72,3 +73,18 @@ export function mapillaryImageUrl(imageId) {
/** Fields requested for a sequence's images. */
export const SEQUENCE_IMAGE_FIELDS =
'id,captured_at,compass_angle,geometry,is_pano';
/**
* Images asked for in a nearest-image search: the API cuts at the limit
* before any order, so this is its most; the distance sort and the imagery
* filter choose among the photos this one request returns.
*/
export const NEAREST_LIMIT = 100;
/**
* A nearest-image search not answered in full (body included) by then is
* given up: a link or posted view, and every view queued behind it, waits.
*/
export const NEAREST_TIMEOUT_MS = 12_000;
/** Fields a nearest-image search needs: where each is, and the filter's. */
export const NEAREST_IMAGE_FIELDS =
'id,captured_at,geometry,computed_geometry,is_pano';
@@ -170,3 +170,41 @@ test('a status the server never answers falls back to the bundled token once the
assert.deepEqual(await status, { configured: false });
assert.equal(instance.coverageStats().keyRequired, true);
});
/** A graph image record at a point. */
const imageAt = (id, lon, lat, extra = {}) => ({
id,
is_pano: false,
captured_at: 10,
geometry: { type: 'Point', coordinates: [lon, lat] },
...extra,
});
test('nearestImage opens the closest image that passes the filter, not the first the API returned', async () => {
const requests = [];
const answer = [
imageAt('far', 2.0004, 1), // ~45 m east
imageAt('near-pano', 2.00002, 1, { is_pano: true }), // ~2 m, a panorama
imageAt('near', 2.00005, 1), // ~5 m east
imageAt('mid', 2, 1.0002), // ~22 m north
];
const source = fakeMapillarySource({
nearestImages: async (query, options) => {
requests.push({ query, options });
return answer;
},
});
const { signal } = new AbortController();
const flat = createMapillaryProvider({ source }).create(
fakeContext({ pano: 'flat', sinceMs: null }),
);
assert.equal(await flat.nearestImage({ lat: 1, lon: 2 }, { signal }), 'near');
assert.equal(requests[0].options.signal, signal, 'the core can abort it');
assert.deepEqual(requests[0].query, { lat: 1, lon: 2 });
const any = createMapillaryProvider({ source }).create(fakeContext());
assert.equal(await any.nearestImage({ lat: 1, lon: 2 }), 'near-pano');
const tooOld = createMapillaryProvider({ source }).create(
fakeContext({ pano: 'all', sinceMs: 100 }),
);
assert.equal(await tooOld.nearestImage({ lat: 1, lon: 2 }), null);
});
@@ -0,0 +1,56 @@
import '../../../../testSupport/registerDom.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import { registerHooks } from 'node:module';
import { createStreetLevelLayer } from '../../index.js';
import { fakeStreetLevelProvider, fakeCesiumViewer } from '../../../../testSupport/streetLevelFakes.mjs';
import { createMapillaryViewer } from './viewer.js';
import { showStreetLevel } from '../../../../voice/gevActions.js';
// Library boundary fixture: moveTo changes the image without stopping PLAY,
// matching installed MapillaryJS Viewer.moveTo / Navigator.moveTo$.
const fakeLibrary = `export class Viewer {
constructor() { globalThis.__replacePlayViewer = this; this.playing = false; this.id = null; this.stops = 0; }
on() {} remove() {} resize() {} setRenderMode() {}
getComponent() { return { play: () => {this.playing = true;}, stop: () => {this.playing = false; this.stops++;} }; }
async moveTo(id) { this.id = id; return { id, sequenceId: 'fixture-sequence', cameraType: 'perspective' }; }
async getPosition() { return { lng: 2, lat: 48 }; }
async getPointOfView() { return { bearing: 0 }; }
}
export class GraphDataProvider {}
export const RenderMode = { Fill: 1, Letterbox: 0 };`;
const hooks = registerHooks({
resolve(specifier, context, next) {
if (specifier === 'mapillary-js') return { url: 'data:text/javascript,' + encodeURIComponent(fakeLibrary), shortCircuit: true };
if (specifier.endsWith('mapillary.css')) return { url: 'data:text/javascript,export default {}', shortCircuit: true };
return next(specifier, context);
},
});
globalThis.fetch = async () => { throw new Error('Unexpected network use in offline test'); };
test('a photo the action asks for stops sequence PLAY', async t => {
const provider = fakeStreetLevelProvider({ nearestImage: async () => 'B' });
const create = provider.create;
provider.create = context => ({ ...create(context), viewer: createMapillaryViewer({ source: { token: '' } }) });
const viewer = fakeCesiumViewer(); viewer.canvas = viewer.scene.canvas;
const layer = createStreetLevelLayer({ providers: [provider] });
layer.init(viewer); layer.enable(viewer);
layer.attachViewerHost(document.body.appendChild(document.createElement('div')));
t.after(() => { layer.destroy(); hooks.deregister(); delete globalThis.__replacePlayViewer; document.body.replaceChildren(); });
await Promise.resolve();
await layer.openImage('mapillary', 'A', { frame: false });
const libraryViewer = globalThis.__replacePlayViewer;
libraryViewer.getComponent('sequence').play();
assert.equal(libraryViewer.playing, true);
const manager = {
layers: new Map([['street-level', { module: layer }]]), isEnabled: () => true,
getLayerParams: () => layer.getParams(), setLayerParams: (_id, params) => layer.setParams(params),
};
const result = await showStreetLevel({ provider: 'mapillary', latitude: 48, longitude: 2 }, {
viewer, dataManager: manager, styleManager: { _navigationGeneration: 1 },
runGevAction: async () => ({ ok: true, latitude: 48, longitude: 2, label: 'fixture destination' }),
});
assert.equal(result.ok, true);
assert.equal(libraryViewer.id, 'B');
assert.equal(layer.getUIState().street.open, true);
assert.equal(libraryViewer.playing, false, 'requested image must stay selected rather than continue sequence PLAY');
});
@@ -1,9 +1,17 @@
import { msg } from '../../../../i18n/marker.js';
import { NEAREST_RADIUS_M } from '../../policy.js';
import {
MAPILLARY_GRAPH_HOST,
NEAREST_IMAGE_FIELDS,
NEAREST_LIMIT,
NEAREST_TIMEOUT_MS,
SEQUENCE_IMAGE_FIELDS,
SEQUENCE_IMAGES_LIMIT,
} from './policy.js';
/** English data: the Street Level panel translates it. */
const NO_ANSWER = msg('Mapillary did not answer in time — try again');
/** HTTP error flagged `keyRequired`, `keyRejected` or `retryAfterSec` (429). */
export class MapillarySourceError extends Error {
constructor(message, { status = 0, payload = null, retryAfterSec } = {}) {
@@ -66,7 +74,47 @@ export function createMapillarySource({
...endpoints,
};
async function graph(path, params = {}, { signal } = {}) {
async function graph(path, params = {}, { signal, timeoutMs = 0 } = {}) {
if (!timeoutMs) return graphOnce(path, params, { signal });
// The whole answer, body included, within `timeoutMs`; the caller's
// abort still wins.
if (signal?.aborted) throw signal.reason;
const controller = new AbortController();
const onAbort = () => controller.abort(signal.reason);
signal?.addEventListener('abort', onAbort, { once: true });
const timer = setTimeout(
() =>
controller.abort(
new MapillarySourceError(NO_ANSWER, {
status: 504,
}),
),
timeoutMs,
);
try {
// A body that never ends is given up too, whatever the fetch does.
const gaveUp = new Promise((_, reject) =>
controller.signal.addEventListener(
'abort',
() => reject(controller.signal.reason),
{ once: true },
),
);
return await Promise.race([
graphOnce(path, params, { signal: controller.signal }),
gaveUp,
]);
} catch (error) {
if (signal?.aborted) throw signal.reason;
if (controller.signal.aborted) throw controller.signal.reason;
throw error;
} finally {
clearTimeout(timer);
signal?.removeEventListener('abort', onAbort);
}
}
async function graphOnce(path, params, { signal }) {
if (graphBase) {
const search = new URLSearchParams(params);
const response = await fetchImpl(`${graphBase}${path}?${search}`, {
@@ -147,5 +195,21 @@ export function createMapillarySource({
);
return Array.isArray(payload?.data) ? payload.data : [];
},
/** Images within `NEAREST_RADIUS_M` of a point, in no particular order. */
async nearestImages({ lat, lon }, { signal } = {}) {
const payload = await graph(
'images',
{
lat: String(lat),
lng: String(lon),
radius: String(NEAREST_RADIUS_M),
limit: String(NEAREST_LIMIT),
fields: NEAREST_IMAGE_FIELDS,
},
{ signal, timeoutMs: NEAREST_TIMEOUT_MS },
);
return Array.isArray(payload?.data) ? payload.data : [];
},
};
}
@@ -126,6 +126,25 @@ test('a rejected key and a rate limit are told apart from other tile errors', as
);
});
test('nearestImages asks the graph API around a point, within 50 m, for at most 100 images', async () => {
const { calls, fetchImpl } = fakeFetch(() =>
jsonResponse({ data: [{ id: '1', geometry: { coordinates: [1, 2] } }] }),
);
const source = createMapillarySource({ token: 'MLY|1|abc', fetchImpl });
const images = await source.nearestImages({ lat: 38.5, lon: -121.5 });
assert.equal(images.length, 1);
const url = new URL(calls[0].url);
assert.equal(url.pathname, '/images');
assert.equal(url.searchParams.get('lat'), '38.5');
assert.equal(url.searchParams.get('lng'), '-121.5');
assert.equal(url.searchParams.get('radius'), '50');
// The API cuts at the limit before any order: a small one would sort and
// filter a handful of arbitrary photos (a 360° filter could find none).
assert.equal(url.searchParams.get('limit'), '100', "the API's most");
assert.match(url.searchParams.get('fields'), /computed_geometry/);
assert.match(url.searchParams.get('fields'), /is_pano/);
});
test('with a Graph endpoint, sequence lookups go there without a token', async () => {
const { calls, fetchImpl } = fakeFetch(() =>
jsonResponse({ data: [{ id: '1', geometry: { coordinates: [1, 2] } }] }),
@@ -157,3 +176,63 @@ test('Graph endpoint errors keep their status', async () => {
(error) => error.status === 503 && error.keyRequired === true,
);
});
test('a nearest-image search that never answers is given up, body included', async (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
const { NEAREST_TIMEOUT_MS } = await import('./policy.js');
// Headers arrive; the body never ends, and the fetch ignores its signal.
const { fetchImpl } = fakeFetch(() => ({
ok: true,
status: 200,
json: () => new Promise(() => {}),
}));
const source = createMapillarySource({ token: 'MLY|1|abc', fetchImpl });
const pending = source.nearestImages({ lat: 1, lon: 2 });
const outcome = pending.then(
() => 'answered',
(error) => error,
);
await Promise.resolve();
t.mock.timers.tick(NEAREST_TIMEOUT_MS);
const error = await outcome;
assert.ok(error instanceof MapillarySourceError, String(error));
assert.equal(error.status, 504);
assert.equal(error.keyRequired, false, 'not a key problem');
// English data, shown in the interface language like the other sources'.
const { setLocale } = await import('../../../../i18n/index.js');
const { translateStreetLevelError } =
await import('../../../../ui/streetLevelPresentation.js');
assert.equal(
translateStreetLevelError(error.message),
'Mapillary did not answer in time — try again',
);
for (const [locale, expected] of [
['de', /nicht rechtzeitig/],
['ja', /時間内に応答/],
]) {
setLocale(locale);
try {
assert.match(translateStreetLevelError(error.message), expected, locale);
} finally {
setLocale('en');
}
}
});
test('the caller’s abort still ends a nearest-image search before its deadline', async () => {
const { fetchImpl } = fakeFetch(
(_url, init) =>
new Promise((_, reject) =>
init.signal.addEventListener('abort', () => reject(init.signal.reason)),
),
);
const source = createMapillarySource({ token: 'MLY|1|abc', fetchImpl });
const controller = new AbortController();
const pending = source.nearestImages(
{ lat: 1, lon: 2 },
{ signal: controller.signal },
);
const reason = new Error('the turn moved on');
controller.abort(reason);
await assert.rejects(pending, (error) => error === reason);
});
@@ -174,6 +174,15 @@ export function createMapillaryViewer({ source, render } = {}) {
current = null;
}
/** A playing sequence keeps stepping through (and downloading) images. */
function stopPlayback() {
try {
viewer?.getComponent('sequence')?.stop();
} catch {
/* sequence component not available */
}
}
return {
async mount(host) {
if (!host) throw new Error('Street Level viewer has no host element');
@@ -195,15 +204,12 @@ export function createMapillaryViewer({ source, render } = {}) {
close() {
pendingOpen = null;
current = null;
// A playing sequence would keep stepping through (and downloading)
// images in the hidden viewer.
try {
viewer?.getComponent('sequence')?.stop();
} catch {
/* sequence component not available */
}
// Hidden, the viewer must not keep playing.
stopPlayback();
},
stopPlayback,
unmount() {
pendingOpen = null;
// A build still waiting for the library gives up when it arrives.
+2 -1
View File
@@ -20,6 +20,7 @@ export function filtersOf(provider) {
* @property {boolean} [groundClick] No coverage: a ground click at street zoom opens its nearest image.
* @property {string} [requiresMapStack] Usable only on this map stack.
* @property {boolean} [defaultOn] Default true; the first that defaults on is lit.
* @property {boolean} [billedPerImage] Every image load costs the key's owner: a link never opens one without a click.
* @property {() => boolean} [keyReady] False when its key is missing now; the
* first keyless provider is lit instead of a default that cannot draw.
* @property {{kind: 'view-cone', color: string}} [marker] Default: GEV's pin.
@@ -50,7 +51,7 @@ export function filtersOf(provider) {
* @property {(sequenceId: string) => Promise<void>} [selectSequence]
* @property {() => void} [clearSequence]
* @property {() => {selectedId: string|null, images: number, loading: boolean, error?: string|null}} [sequenceStats]
* @property {(point: {lat: number, lon: number}, options?: {signal?: AbortSignal}) => Promise<string|null>} [nearestImage] For ground clicks and `openNearest`; an aborted lookup gives up (it may reject with an AbortError).
* @property {(point: {lat: number, lon: number}, options?: {signal?: AbortSignal, radiusM?: number}) => Promise<string|null>} [nearestImage] For ground clicks and `openNearest`; an aborted lookup gives up (it may reject with an AbortError). `radiusM` asks for a wider search than NEAREST_RADIUS_M; a provider that cannot search wider ignores it.
* @property {ViewerAdapter} viewer
*
* @typedef {object} ViewerAdapter
+4
View File
@@ -19,6 +19,8 @@ export function freshStreet() {
capturedAt: null,
/** 'day', or 'month' for providers that date images by month (Google). */
capturedAtPrecision: 'day',
/** Why the last nearest lookup opened nothing: 'empty', 'sky' or null. */
nearestOutcome: null,
/** A place name for the caption (Google's address), or null. */
title: null,
/** Whether the open viewer has FIT/FILL render modes. */
@@ -29,6 +31,8 @@ export function freshStreet() {
externalUrl: null,
loading: false,
error: null,
// A lookup a link prepared but left to a click: {point, providerIds, radiusM}.
armed: null,
};
}
+55 -5
View File
@@ -73,6 +73,19 @@ export function createViewerHost({ state, parts }) {
active.unsubscribe();
active.adapter.unmount();
active = null;
// The photo being replaced belonged to that source: none of its details
// (id, place, author, link) describe the one loading now.
const { open, loading, error, providerId, providerName, providerLabel } =
state.street;
Object.assign(state.street, freshStreet(), {
open,
loading,
error,
providerId,
providerName,
providerLabel,
});
parts.marker.clear();
}
const adapter = entry.instance.viewer;
const promise = (async () => {
@@ -99,12 +112,17 @@ export function createViewerHost({ state, parts }) {
}
/**
* Open an image: true once its first pose is in, false if it failed or was
* overtaken. `frame: false` leaves the camera where it is.
* Open an image: true once its first pose is in, false if it failed, was
* overtaken, or `signal` fired first. An abort while the viewer mounts or
* loads closes the photo: nothing opens for a request that was withdrawn.
*/
async function open(providerId, imageId, { frame = true } = {}) {
async function open(
providerId,
imageId,
{ frame = true, signal = null } = {},
) {
const entry = state.providers.get(providerId);
if (!entry || !imageId) return false;
if (!entry || !imageId || signal?.aborted) return false;
if (!state.street.host) {
// A nearest-image lookup may have set it; nothing is loading now.
state.street.loading = false;
@@ -115,6 +133,10 @@ export function createViewerHost({ state, parts }) {
}
const seq = ++openSeq;
const current = () => seq === openSeq;
const onAbort = () => {
if (current()) close();
};
signal?.addEventListener('abort', onAbort, { once: true });
// Claimed now, honoured after loading only if nothing newer took the camera.
const ticket = frame ? parts.framing.begin() : null;
Object.assign(state.street, {
@@ -138,6 +160,7 @@ export function createViewerHost({ state, parts }) {
if (current())
state.street.error = error?.message || msg('Image could not be opened');
} finally {
signal?.removeEventListener('abort', onAbort);
if (current()) state.street.loading = false;
notify();
}
@@ -165,6 +188,11 @@ export function createViewerHost({ state, parts }) {
active?.adapter.resize();
}
/** Stop a sequence playing in the open photo (adapters that play). */
function stopPlayback() {
active?.adapter.stopPlayback?.();
}
function setRenderMode(mode) {
state.street.renderMode = mode === 'fill' ? 'fill' : 'letterbox';
active?.adapter.setRenderMode?.(state.street.renderMode);
@@ -187,5 +215,27 @@ export function createViewerHost({ state, parts }) {
active = null;
}
return { attach, open, close, resize, setRenderMode, unmount };
/**
* Destroy `providerId`'s viewer and leave the panel's state alone: what a
* request leaves behind once it replaced or closed that source's photo.
*/
function release(providerId) {
if (active?.id !== providerId && mounting?.id !== providerId) return;
const pending = mounting;
mounting = null;
active?.unsubscribe();
(active?.adapter ?? pending?.adapter)?.unmount();
active = null;
}
return {
attach,
open,
close,
resize,
setRenderMode,
stopPlayback,
unmount,
release,
};
}
@@ -557,6 +557,51 @@ test('an adapter that can frame but says this image has no frame offers no FIT /
assert.equal(state.street.renderModes, true, 'a flat image can be framed');
});
test('a caller that withdraws while the viewer is still mounting gets no photo', async () => {
const gate = deferred();
const adapter = fakeAdapter({ gate });
const { state, host } = harness(adapter);
const controller = new AbortController();
const pending = host.open('mapillary', 'a', { signal: controller.signal });
assert.equal(state.street.open, true, 'opening');
controller.abort(); // the library is still loading
gate.resolve();
assert.equal(await pending, false);
assert.deepEqual(adapter.calls.open, [], 'the image was never opened');
assert.equal(state.street.open, false, 'the photo is closed');
assert.equal(state.street.loading, false, 'no stuck spinner');
assert.equal(state.street.imageId, null);
});
test('a caller that withdraws while the photo is loading gets it closed', async () => {
const openGate = deferred();
const adapter = fakeAdapter({ openGate });
const { state, host } = harness(adapter);
const controller = new AbortController();
const pending = host.open('mapillary', 'a', { signal: controller.signal });
await settle();
assert.deepEqual(adapter.calls.open, ['a'], 'loading');
controller.abort();
openGate.resolve();
assert.equal(await pending, false);
assert.equal(state.street.open, false, 'the withdrawn photo is closed');
assert.equal(state.street.imageId, null);
// An already-withdrawn request asks nothing at all.
const done = new AbortController();
done.abort();
assert.equal(
await host.open('mapillary', 'b', { signal: done.signal }),
false,
);
assert.deepEqual(adapter.calls.open, ['a']);
// A signal that never fires changes nothing.
assert.equal(
await host.open('mapillary', 'c', { signal: new AbortController().signal }),
true,
);
assert.equal(state.street.imageId, 'c');
});
test('a pose’s licence reaches the caption state, and a closed viewer forgets it', async () => {
const { state, host, google } = twoProviders();
await host.open('google', 'g-1');