Street Level photo viewer: keyless ranking, closed waits, a moved canvas

Review follow-ups to the previous commit:

- photoViewers.js ranks a presentation without a mountKey as mounted when
  it began presenting (after the latest key seen, before any later mount),
  so a photo viewer mounting while a keyless one shows is drawn and the
  keyless one superseded; supersede is queued whenever more than one
  presents after any change, not only when the pick changes.
- A panorama's open still waiting on a draw when the last view leaves
  fails as closed and leaves no photo shown, instead of uploading to a
  canvas never drawn. A mount waiting on its first draw then also fails as
  closed and is unmounted, so a view subscribing later sees nothing.
- A view handing back another canvas element than the renderer's drops
  the renderer and draws the panorama again on the new one, as after a
  lost context.
- The guard test allows a .src write in loadImage only on the one `image`
  binding, created by new Image() and never rebound or shadowed, and
  refuses `(expr).src =` and bracket property writes anywhere.
- The test fakes' shared view is reset before each test
  (resetPhotoView), so a viewer left by an earlier test is neither drawn
  with nor superseded by a later test's.

Nothing changes in the running app.

Co-authored-by: Manjunath Paparaju <[email protected]>
This commit is contained in:
Sameh KhamisandManjunath Paparaju committed 2026-11-19 16:04:21 -08:00
1 parent 33ac0545ef
commit e6f21777ba
11 files changed
+327 -50

No files matched your search

+65 -14
View File
@@ -159,6 +159,16 @@ async function loadBitmap(url, timeoutMs, resize, failure, signal) {
}
}
/**
* Unmounted, superseded or left without a view before the view drew what
* was waiting on it (`undrawn`): a mount or an open that fails as closed.
*/
function undrawn() {
return Object.assign(new Error('Street-level viewer was closed'), {
undrawn: true,
});
}
/**
* A picture refused for its size (`tooLarge`): the viewer will not load
* that file another way, an <img> having no size limit at all.
@@ -235,8 +245,11 @@ export function panoSizeFor(canvasPixels, fovDeg) {
* and a new `canvasKey` asks for a fresh canvas (a lost WebGL context):
* neither is ever reused. `actions.supersede()` tells a viewer another one
* is drawn in its place: it unmounts, and a mount still waiting to be drawn
* fails as closed. Mounting with no view subscribed fails; an open waiting
* on a draw when the last view leaves goes on without it.
* fails as closed. Mounting with no view subscribed fails, and a mount or
* a panorama's open waiting on a draw when the last view leaves fails as
* closed (the mount unmounts; the open leaves no photo shown). A view
* handing back another canvas element than the renderer's (one subscribed
* since) gets the panorama drawn again on it, as after a lost context.
*
* Photos are normalized by the provider: `{id, sequenceId, lon, lat,
* heading, isPano, capturedAt}` plus whatever its `sources` read.
@@ -479,6 +492,27 @@ export function createPhotoViewer({
const from = event?.currentTarget ?? event?.target;
if (from && from !== canvas) return;
event.preventDefault?.();
dropRenderer();
// A lost canvas hands back its lost context: the view draws a new
// element in its place and hands it back.
canvas = null;
present({ canvasKey: ++viewKeys });
reopen();
}
/**
* The view drew the panorama on another canvas element than the
* renderer's (a view that subscribed since): the renderer cannot follow
* it, so the photo is drawn again on a new one, as after a lost context.
*/
function moveCanvas(element) {
dropRenderer();
canvas = element;
reopen();
}
/** Let the renderer go, keeping the user's look for the photo's reopen. */
function dropRenderer() {
const lost = renderer;
renderer = null;
// The new renderer starts facing the photo's heading: keep the user's look.
@@ -489,11 +523,10 @@ export function createPhotoViewer({
} catch {
/* already gone */
}
// A lost canvas hands back its lost context: the view draws a new
// element in its place and hands it back.
canvas = null;
present({ canvasKey: ++viewKeys });
// Show the photo again through the core, unless a newer one is opening.
}
/** Show the panorama again through the core, unless a newer photo is opening. */
function reopen() {
if (showing === 'pano' && photo && openingId === null) {
const again = photo.id;
show(null);
@@ -675,7 +708,9 @@ export function createPhotoViewer({
const actions = {
attach(name, element) {
if (presented?.actions !== actions || !element) return;
ELEMENTS[name]?.(element);
if (name === 'canvas' && renderer && canvas && element !== canvas)
moveCanvas(element);
else ELEMENTS[name]?.(element);
if (name === 'root') wake(rootWaiters);
if (name === 'canvas') {
canvasDraws++;
@@ -883,6 +918,14 @@ export function createPhotoViewer({
const draws = canvasDraws;
show('pano');
await drawnAfter(draws, signal);
// The last view left before drawing it: the canvas was never shown, and
// nothing is drawn until a view is back.
if (seq === openSeq && canvasDraws === draws && !viewListeners.size) {
image.close?.();
photo = null;
show(null);
throw undrawn();
}
if (seq !== openSeq || !renderer) {
image.close?.();
if (seq !== openSeq) return false;
@@ -931,7 +974,8 @@ export function createPhotoViewer({
if (sources.hasPano(target) && ensureRenderer()) {
try {
shown = await showPano(target, seq, keepView, signal);
} catch {
} catch (error) {
if (error?.undrawn) throw error;
// The panorama failed: its front view is better than nothing.
if (seq !== openSeq) return;
shown = await showFlat(target, seq, signal);
@@ -952,12 +996,16 @@ export function createPhotoViewer({
rendererFailed = false;
if (!viewListeners.size)
throw new Error('Street Level photo viewer has no view to draw it');
// Resolves once the view drew the viewer, or it was unmounted meanwhile.
// Resolves once the view drew the viewer, or it was unmounted, or its
// last view left, meanwhile.
const drawn = new Promise((resolve) => rootWaiters.add(resolve));
build(host);
if (!root) await drawn;
// Unmounted or superseded before the view drew it.
if (!root) throw new Error('Street-level viewer was closed');
if (root) return;
// The last view left before drawing it: no view will. Unmounted, as
// when superseded, so a view subscribing later draws nothing.
if (presented) adapter.unmount();
throw undrawn();
},
/** Resolves once the photo is on screen and its pose was emitted. */
@@ -1045,9 +1093,12 @@ export function createPhotoViewer({
viewListeners.add(listener);
listener(presented);
return () => {
// The last view went: an open waiting on its draw goes on without.
if (viewListeners.delete(listener) && !viewListeners.size)
// The last view went: a mount or an open waiting on its draw fails
// as closed.
if (viewListeners.delete(listener) && !viewListeners.size) {
wake(rootWaiters);
wake(canvasWaiters);
}
};
},
};
+104 -3
View File
@@ -1,7 +1,14 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createPhotoViewer } from './photoViewer.js';
import { fakeHost, until } from '../../testSupport/kartaViewFakes.mjs';
import {
fakeHost,
until,
resetPhotoView,
} from '../../testSupport/kartaViewFakes.mjs';
// Each test draws its own viewers only.
test.beforeEach(resetPhotoView);
const PHOTOS = {
a: { id: 'a', sequenceId: 's', lon: 1, lat: 2, heading: 0, isPano: true },
@@ -697,12 +704,14 @@ test('a view that draws at once, inside its listener, opens a panorama', async (
unsubscribe();
});
test('an open waiting on the view’s draw goes on when the view unsubscribes', async () => {
const { viewer } = panoramaViewer();
test('a panorama’s open waiting on the view’s draw fails as closed when the view leaves', async () => {
const { viewer, images } = panoramaViewer();
const parts = elements();
const kinds = [];
const presented = [];
// Draws the mount, then nothing more.
const unsubscribe = viewer.subscribeView((view) => {
presented.push(view);
if (!view) return;
kinds.push(view.kind);
if (kinds.length > 1) return;
@@ -714,9 +723,85 @@ test('an open waiting on the view’s draw goes on when the view unsubscribes',
assert.ok(await until(() => kinds.includes('pano')), 'waiting on a draw');
unsubscribe();
assert.equal(await settles(opening), true, 'not left pending');
await assert.rejects(opening, /viewer was closed/);
assert.deepEqual(images, [], 'nothing uploaded to a canvas never shown');
// A view back draws the viewer mounted, with no photo shown.
let again = null;
const resubscribe = viewer.subscribeView((view) => (again = view));
assert.ok(again, 'still mounted');
assert.equal(again.kind, '');
resubscribe();
viewer.unmount();
});
test('a mount waiting on the view’s draw fails as closed when the view leaves, and is unmounted', async () => {
const { viewer } = panoramaViewer();
const unsubscribe = viewer.subscribeView(() => {});
const mounting = viewer.mount(fakeHost());
unsubscribe();
assert.equal(await settles(mounting), true, 'not left pending');
await assert.rejects(mounting, /viewer was closed/);
let current;
const resubscribe = viewer.subscribeView((view) => (current = view));
assert.equal(current, null, 'nothing presented');
await assert.rejects(viewer.open('a'), /not mounted/);
resubscribe();
});
test('a view handing back another canvas gets the panorama drawn again on it', async () => {
const renderers = [];
const reopened = [];
const viewer = createPhotoViewer({
providerId: 'test',
name: 'Test',
sources: SOURCES,
getPhoto: async (id) => PHOTOS[id],
step: async () => 'b',
onStep() {},
onReopen: (id) => {
reopened.push(id);
viewer.open(id);
},
load: async (url) => ({ src: url }),
createRenderer: (canvas) => {
const renderer = {
canvas,
images: [],
destroyed: false,
setImage: (image) => renderer.images.push(image.src),
setView() {},
getView: () => ({ yaw: 10, pitch: 0, fov: 80 }),
resize() {},
clear() {},
destroy: () => (renderer.destroyed = true),
};
renderers.push(renderer);
return renderer;
},
});
const drawWith = (parts) => (view) => {
if (!view) return;
for (const [name, element] of Object.entries(parts))
view.actions.attach(name, element);
};
const first = elements();
const unsubscribe = viewer.subscribeView(drawWith(first));
await viewer.mount(fakeHost());
await viewer.open('a');
assert.equal(renderers[0].canvas, first.canvas);
// Another view takes over, with elements of its own.
const second = elements();
const resubscribe = viewer.subscribeView(drawWith(second));
unsubscribe();
assert.ok(await until(() => renderers[1]?.images.length > 0));
assert.deepEqual(reopened, ['a']);
assert.equal(renderers[0].destroyed, true);
assert.equal(renderers[1].canvas, second.canvas);
assert.deepEqual(renderers[1].images, ['a-first']);
viewer.unmount();
resubscribe();
});
test('the shared fake view draws only the later of two mounts, as the app does', async () => {
const one = setup();
const two = setup();
@@ -727,3 +812,19 @@ test('the shared fake view draws only the later of two mounts, as the app does',
await assert.rejects(one.viewer.open('f'), /not mounted/, 'superseded');
two.viewer.unmount();
});
test('a viewer left by an earlier test is not superseded by a later test’s', async () => {
const earlier = setup();
await earlier.viewer.mount(earlier.host);
// As before each test.
resetPhotoView();
const later = setup();
await later.viewer.mount(later.host);
await tick();
const opening = earlier.viewer.open('f');
await until(() => earlier.loads.includes('f-first'));
earlier.release('f-first');
await opening;
earlier.viewer.unmount();
later.viewer.unmount();
});
+28 -17
View File
@@ -9,31 +9,40 @@
* Two fields of a presentation are read here (see ViewerAdapter.subscribeView
* in registry.js):
* - `mountKey`, a number larger for each later mount, orders the mounts. A
* presentation without one counts as the latest mount; among several
* without, the one that began presenting last is.
* presentation without one counts as mounted when it began presenting:
* after every mount presenting before it, before any later mount, keyed
* or not.
* - `actions.supersede()`, where present, is called on each presentation
* not drawn once the pick changes. It runs on a microtask, after the
* presentation that won has reached every subscriber: a subscriber never
* sees the superseded one withdraw before it sees the one replacing it.
* not drawn, whenever more than one presents. It runs on a microtask,
* after the presentation that won has reached every subscriber: a
* subscriber never sees the superseded one withdraw before it sees the
* one replacing it.
* @param {Iterable<{subscribeView?: Function}>} viewers
* @param {(view: ?object) => void} listener
* @returns {() => void} Unsubscribe.
*/
export function subscribePhotoViewers(viewers, listener) {
// Each viewer's current presentation, and when it began presenting.
// Each viewer's current presentation and its rank, {key, arrival}.
const shown = new Map();
let arrivals = 0;
/** The largest mount key seen: a keyless mount ranks just after it. */
let latestKey = -Infinity;
let ready = false;
let closed = false;
let superseding = false;
let last;
/** Whether `a` was mounted after `b`. */
const later = (a, b) => {
const key = ({ view }) =>
Number.isFinite(view.mountKey) ? view.mountKey : Infinity;
const ka = key(a);
const kb = key(b);
return ka !== kb ? ka > kb : a.arrival > b.arrival;
const later = (a, b) =>
a.key !== b.key ? a.key > b.key : a.arrival > b.arrival;
/** A new mount's rank: its key, or, without one, the latest key seen. */
const rank = (view) => {
const keyed = Number.isFinite(view.mountKey);
if (keyed) latestKey = Math.max(latestKey, view.mountKey);
return {
key: keyed ? view.mountKey : latestKey,
// A keyed mount comes before a keyless one ranked on its key.
arrival: keyed ? 0 : ++arrivals,
};
};
// The others are not drawn: a mount still waiting on the view never
// would be.
@@ -48,10 +57,12 @@ export function subscribePhotoViewers(viewers, listener) {
for (const entry of shown.values())
if (!next || later(entry, next)) next = entry;
next = next?.view ?? null;
if (!ready || next === last) return;
last = next;
listener(next);
if (next && shown.size > 1 && !superseding) {
if (!ready) return;
if (next !== last) {
last = next;
listener(next);
}
if (last && shown.size > 1 && !superseding) {
superseding = true;
queueMicrotask(supersede);
}
@@ -64,7 +75,7 @@ export function subscribePhotoViewers(viewers, listener) {
if (!view) shown.delete(viewer);
else if (entry && entry.view.mountKey === view.mountKey)
entry.view = view;
else shown.set(viewer, { view, arrival: ++arrivals });
else shown.set(viewer, { view, ...rank(view) });
publish();
});
if (typeof unsubscribe === 'function') unsubscribes.push(unsubscribe);
+61 -6
View File
@@ -1,5 +1,6 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createPhotoViewer } from './photoViewer.js';
import { subscribePhotoViewers } from './photoViewers.js';
/**
@@ -92,7 +93,7 @@ test('every subscriber sees the earlier mount, then the later one, with no gap',
for (const unsubscribe of unsubscribes) unsubscribe();
});
test('a presentation without a mount key counts as the latest mount', () => {
test('a presentation without a mount key counts as mounted when it began presenting', async () => {
const a = fakeViewer();
const b = fakeViewer();
const c = fakeViewer();
@@ -101,18 +102,72 @@ test('a presentation without a mount key counts as the latest mount', () => {
shown.push(view),
);
a.present(a.view(5));
const keyless = { actions: {} };
const keyless = b.view(undefined);
b.present(keyless);
assert.equal(shown.at(-1), keyless, 'after the keyed one');
// A keyed mount presenting later does not take it back.
a.present(a.view(6));
assert.equal(shown.at(-1), keyless);
// Of two without, the one that began presenting last.
const newer = { actions: {} };
const newer = c.view(undefined);
c.present(newer);
assert.equal(shown.at(-1), newer);
b.present({ ...keyless, kind: 'flat' });
assert.equal(shown.at(-1), newer, 'presenting again is not a new mount');
// A keyed mount made after them wins.
const latest = a.view(6);
a.present(latest);
assert.equal(shown.at(-1), latest);
await Promise.resolve();
assert.ok(b.superseded > 0 && c.superseded > 0, 'the keyless ones are told');
unsubscribe();
});
test('a presentation that is not drawn is superseded even when the pick stays', async () => {
const a = fakeViewer();
const b = fakeViewer();
const shown = [];
const unsubscribe = subscribePhotoViewers([a, b], (view) => shown.push(view));
const later = b.view(2);
b.present(later);
// An earlier mount presents once the later one is drawn.
a.present(a.view(1));
assert.deepEqual(shown, [null, later]);
await Promise.resolve();
assert.equal(a.superseded, 1);
unsubscribe();
});
test('a photo viewer mounting while a keyless presentation shows is drawn, and the keyless one superseded', async () => {
let superseded = 0;
const keyless = {
subscribeView(listener) {
listener({ actions: { supersede: () => superseded++ } });
return () => {};
},
};
const viewer = createPhotoViewer({
providerId: 'test',
name: 'Test',
sources: {},
getPhoto: async () => null,
step: async () => null,
onStep() {},
});
const shown = [];
const element = { clientWidth: 400, clientHeight: 250 };
const unsubscribe = subscribePhotoViewers([keyless, viewer], (view) => {
shown.push(view);
if (!view?.mountKey) return;
for (const name of ['root', 'picture', 'canvas', 'prev', 'next'])
view.actions.attach(name, element);
});
const mounting = viewer.mount({});
const outcome = await Promise.race([
mounting.then(() => 'mounted'),
new Promise((resolve) => setTimeout(() => resolve('pending'), 50)),
]);
assert.equal(outcome, 'mounted');
assert.ok(Number.isFinite(shown.at(-1)?.mountKey), 'the mount is drawn');
assert.ok(superseded >= 1, 'the keyless one is told');
viewer.unmount();
unsubscribe();
});
@@ -17,6 +17,7 @@ import {
drawn,
fakeHost,
until,
resetPhotoView,
} from '../../../../testSupport/kartaViewFakes.mjs';
import {
bindStreetViewer,
@@ -26,6 +27,9 @@ import {
} from '../../../../testSupport/streetLevelFakes.mjs';
import { fakeDrawPort } from '../../../../testSupport/fakeDrawPort.mjs';
// Each test draws its own viewers only.
test.beforeEach(resetPhotoView);
/** A photo record `metres` east of (42.3314, -83.0458), in sequence `seq` at `index`. */
function photoRecord(id, { metres = 0, seq = '14010', index = 0 } = {}) {
const lon = -83.0458 + metres / 82_300;
@@ -5,8 +5,12 @@ import {
drawn,
fakeHost,
until,
resetPhotoView,
} from '../../../../testSupport/kartaViewFakes.mjs';
// Each test draws its own viewers only.
test.beforeEach(resetPhotoView);
const PHOTOS = {
flat1: {
id: 'flat1',
@@ -18,6 +18,7 @@ import {
drawn,
fakeHost,
until,
resetPhotoView,
} from '../../../../testSupport/kartaViewFakes.mjs';
import {
bindStreetViewer,
@@ -31,6 +32,9 @@ import {
stacItem,
} from '../../../../testSupport/panoramaxFixtures.mjs';
// Each test draws its own viewers only.
test.beforeEach(resetPhotoView);
const ORIGIN = { lon: 2.3495, lat: 48.8874 };
/** A point `metres` east of ORIGIN. */
const east = (metres) => ({
@@ -2,9 +2,16 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import { PANORAMAX_SOURCES, createPanoramaxViewer } from './viewer.js';
import { normalizeItem } from './policy.js';
import { fakeHost, until } from '../../../../testSupport/kartaViewFakes.mjs';
import {
fakeHost,
until,
resetPhotoView,
} from '../../../../testSupport/kartaViewFakes.mjs';
import { stacItem } from '../../../../testSupport/panoramaxFixtures.mjs';
// Each test draws its own viewers only.
test.beforeEach(resetPhotoView);
const photo = (options) =>
normalizeItem(stacItem({ lon: 2.35, lat: 48.85, ...options }));
+4 -4
View File
@@ -69,10 +69,10 @@ export function filtersOf(provider) {
* presentation at once, then each new one, null while unmounted. One view
* draws one viewer (photoViewers.js picks it), reading two fields:
* `mountKey`, a number larger for each later mount (the later mount is
* drawn; a presentation without one counts as the latest), and
* `actions.supersede()`, called on a mount that is not drawn because a
* later one is (it should unmount, failing a mount still waiting to be
* drawn; an adapter without it is simply not drawn).
* drawn; a presentation without one counts as mounted when it began
* presenting), and `actions.supersede()`, called on a mount that is not
* drawn because a later one is (it should unmount, failing a mount still
* waiting to be drawn; an adapter without it is simply not drawn).
*
* @typedef {object} StreetPose
* @property {string} providerId
+14 -1
View File
@@ -95,9 +95,22 @@ function resubscribe() {
previous?.();
}
/**
* Start the shared view afresh, with no viewer: a test file calls it before
* each test, so a viewer left by an earlier test is not drawn with a later
* test's (nor superseded by it). A viewer it held is left without a view.
*/
export function resetPhotoView() {
shared.generation++;
shared.unsubscribe?.();
shared.unsubscribe = null;
shared.viewers.clear();
shared.draw = null;
}
/**
* Draw a photo viewer with the shared view, alongside every other viewer
* given here (see `shared`).
* given here since the last `resetPhotoView()` (see `shared`).
* @returns {() => void} Stop drawing it.
*/
export function drawPhotoViewer(viewer) {
+31 -4
View File
@@ -101,11 +101,38 @@ test('the photo viewer is drawn by its view, and its layer needs no Vue', () =>
/from 'vue'|\.vue'/,
])
assert.doesNotMatch(source, write);
assert.doesNotMatch(rest, /\.src\s*=[^=]/, 'a .src written on the page');
// In loadImage, only on the off-page Image it creates.
// No property written through brackets (`picture['src'] = …`,
// `el[name] = …`), outside array destructuring declarations.
assert.doesNotMatch(
source.replace(/\b(?:const|let|var)\s*\[/g, ''),
/[\w$)\]]\s*\[[^[\]]*\]\s*=(?![=>])/,
'a bracket write',
);
const SRC = /\.src\s*=(?![=>])/g;
assert.doesNotMatch(rest, SRC, 'a .src written on the page');
// In loadImage, only on the off-page Image it creates: `image` is bound
// once, to that Image, and never rebound or shadowed.
assert.match(loader, /\bconst image = new Image\(\);/);
for (const [write] of loader.matchAll(/[\w$.\]]+\.src\s*=(?!=)/g))
assert.match(write, /^image\.src\s*=$/, write);
assert.equal(
loader.match(/\b(?:const|let|var|function|class)\s+image\b/g)?.length,
1,
'one binding of image',
);
for (const rebinding of [
/(?<!\b(?:const|let|var)\s+)(?<![\w$.])image\s*=(?![=>])/,
/(?<![\w$.])image\s*=>/,
/\((?:[^()]*[,{[\s(])?image\b[^()]*\)\s*=>/,
/\bfunction\b[^(]*\((?:[^)]*[,{[\s(])?image\b[^)]*\)/,
/\b(?:const|let|var)\s*[{[][^=]*\bimage\b/,
/\bcatch\s*\(\s*image\b/,
])
assert.doesNotMatch(loader, rebinding, 'image rebound or shadowed');
const writes = loader.match(SRC)?.length ?? 0;
assert.equal(
loader.match(/(?<![\w$.)\]])image\.src\s*=(?![=>])/g)?.length ?? 0,
writes,
'a .src written on something other than the Image',
);
const markup = template(VIEW);
const opening = (name, attribute) =>
new RegExp(String.raw`<${name}\b${ATTRS}\s${attribute}${ATTRS}>`);