Street Level photo viewer: fresh elements per mount, and one viewer drawn

Fixes from review of the move to StreetLevelPhotoViewer:

- Each mount and each panorama canvas now takes a key no viewer reuses,
  and the view keys its root by the mount. Before, switching KartaView and
  Panoramax in one tick let Vue patch the old viewer's canvas, whose
  destroyed renderer had lost its context, into the new one, so 360°
  photos fell back to their front view.
- Of the viewers mounting in the host, the view draws the one mounted
  last, by mount key (photoViewers.js, which subscribePhotoViewer() now
  uses), whatever order they present in. A viewer still mounting when a
  later one is drawn is superseded: it unmounts and its mount fails as
  closed, rather than staying pending and being drawn once the later one
  goes.
- A panorama's first image is uploaded once the view has drawn its canvas
  shown (the view hands the canvas back on every draw), so it is never
  sized into a hidden canvas.
- The tests' fake view now draws as Vue does: once per tick with the final
  value, keeping elements while their keys are unchanged and handing every
  element back on each draw. StreetLevelPhotoViewer.test.mjs covers the
  switch in one tick and the overtaken mount with the real view.
- The guard test's check that the photo viewer writes no DOM covers
  inserting, moving, removing and replacing elements, attributes, classes,
  styles and the hidden, disabled and text properties.

Co-authored-by: Manjunath Paparaju <[email protected]>
This commit is contained in:
Sameh KhamisandManjunath Paparaju committed 2026-11-19 13:52:36 -08:00
1 parent 766364f691
commit 2a0e21774b
17 files changed
+340 -107

No files matched your search

+5 -1
View File
@@ -6319,7 +6319,11 @@ element: it presents the viewer through the layer's
`subscribePhotoViewer()`, which the application shell publishes to the
`gev-street-level-photo` store, and `StreetLevelPhotoViewer` draws it in the
viewer host and hands back the canvas the panorama is drawn on (a fresh one
after a lost context). Without a subscribed view these photos cannot open.
after a lost context). Each mount and each canvas has a key of its own, so
a viewer never draws on another one's elements, and of two viewers
mounting at once only the later one is drawn (`photoViewers.js`): the
earlier one's mount closes. Without a subscribed view these photos cannot
open.
Panoramax (`providers/panoramax/`) is keyless and browser-side: the
meta-catalogue `api.panoramax.xyz` (CORS open) federates every instance, and
+5 -2
View File
@@ -406,8 +406,11 @@ slot whenever its view is drawn.
the portable `./layers/street-level` entries need no Vue; the viewer
keeps every decision, the photo loading, keys, drag and zoom, and draws
its panorama on the canvas the view hands back, a fresh one after a lost
WebGL context; with no view subscribed, as when the layer runs without
the application shell, a KartaView or Panoramax photo cannot mount),
WebGL context; each mount and canvas is keyed, so no viewer reuses
another's elements, and of two viewers mounting at once only the later
is drawn while the earlier one's mount closes; with no view
subscribed, as when the layer runs without the application shell, a
KartaView or Panoramax photo cannot mount),
CCTV (done: `CctvPanel` renders
the whole panel from the `gev-cctv` store, including the camera picker,
the inline pose editor, the frame preview, source badge and typed
+2
View File
@@ -1148,6 +1148,8 @@
"src/layers/streetLevel/providers/panoramax/decode.js",
"src/layers/streetLevel/providers/panoramax/viewer.js",
"src/layers/streetLevel/photoViewer.js",
"src/layers/streetLevel/photoViewers.js",
"src/layers/streetLevel/photoViewers.test.mjs",
"src/layers/streetLevel/limiter.js",
"src/layers/streetLevel/imageSize.js",
"src/layers/streetLevel/tileCache.js",
+3
View File
@@ -3559,6 +3559,7 @@
"src/layers/streetLevel/providers/panoramax/decode.js",
"src/layers/streetLevel/providers/panoramax/viewer.js",
"src/layers/streetLevel/photoViewer.js",
"src/layers/streetLevel/photoViewers.js",
"src/layers/streetLevel/limiter.js",
"src/layers/streetLevel/imageSize.js",
"src/layers/streetLevel/tileCache.js",
@@ -5153,6 +5154,7 @@
"src/layers/streetLevel/providers/panoramax/decode.js",
"src/layers/streetLevel/providers/panoramax/viewer.js",
"src/layers/streetLevel/photoViewer.js",
"src/layers/streetLevel/photoViewers.js",
"src/layers/streetLevel/limiter.js",
"src/layers/streetLevel/imageSize.js",
"src/layers/streetLevel/tileCache.js",
@@ -6217,6 +6219,7 @@
"src/layers/streetLevel/providers/panoramax/decode.js",
"src/layers/streetLevel/providers/panoramax/viewer.js",
"src/layers/streetLevel/photoViewer.js",
"src/layers/streetLevel/photoViewers.js",
"src/layers/streetLevel/limiter.js",
"src/layers/streetLevel/imageSize.js",
"src/layers/streetLevel/tileCache.js",
+9 -28
View File
@@ -5,6 +5,7 @@ import { createCredits } from './credits.js';
import { createPickRouter } from './pickRouter.js';
import { createSelection } from './selection.js';
import { createViewerHost } from './viewerHost.js';
import { subscribePhotoViewers } from './photoViewers.js';
import { filtersOf, requiresKeyIdFor, validateProviders } from './registry.js';
import { normalizeFilter, resolveFilter, sameFilter } from './filter.js';
import { worldTimeFor } from '../../time/worldClock.js';
@@ -706,38 +707,18 @@ export function createStreetLevelLayer({
/**
* Receive every presentation of the photo viewer the providers whose
* photos are plain files (KartaView, Panoramax) mount in the viewer
* host, starting with the current one; null while none is mounted. A
* view draws it (see photoViewer.js); with nobody subscribed, those
* providers' photos cannot open.
* host, the one mounted last (see photoViewers.js), starting with the
* current one; null while none is mounted. A view draws it (see
* photoViewer.js); with nobody subscribed, those providers' photos
* cannot open.
* @param {(view: ?object) => void} listener
* @returns {() => void} Unsubscribe.
*/
subscribePhotoViewer(listener) {
// Each mounted viewer's presentation, the latest mount last.
const shown = new Map();
let ready = false;
let last;
const publish = () => {
const next = [...shown.values()].at(-1) ?? null;
if (!ready || next === last) return;
last = next;
listener(next);
};
const unsubscribes = [];
for (const [id, entry] of state.providers) {
const unsubscribe = entry.instance.viewer?.subscribeView?.((view) => {
shown.delete(id);
if (view) shown.set(id, view);
publish();
});
if (typeof unsubscribe === 'function') unsubscribes.push(unsubscribe);
}
ready = true;
publish();
if (last === undefined) listener((last = null));
return () => {
for (const unsubscribe of unsubscribes.splice(0)) unsubscribe();
};
return subscribePhotoViewers(
[...state.providers.values()].map((entry) => entry.instance.viewer),
listener,
);
},
setProviderEnabled,
openImage,
+4 -3
View File
@@ -2177,7 +2177,7 @@ test('proceed() is asked after the lookup: false loads nothing and clears the sp
);
});
test('subscribePhotoViewer hands on the photo viewer a provider presents, the latest mount’s while two overlap', async (t) => {
test('subscribePhotoViewer hands on the photo viewer a provider presents, the later mount’s while two overlap', async (t) => {
const presenting = (id, pickPrefix) => {
const provider = fakeProvider({ id, pickPrefix });
const create = provider.create;
@@ -2202,8 +2202,9 @@ test('subscribePhotoViewer hands on the photo viewer a provider presents, the la
const shown = [];
const unsubscribe = layer.subscribePhotoViewer((view) => shown.push(view));
assert.deepEqual(shown, [null], 'the current one first');
const viewA = { host: 'a' };
const viewB = { host: 'b' };
const supersede = () => {};
const viewA = { host: 'a', mountKey: 1, actions: { supersede } };
const viewB = { host: 'b', mountKey: 2, actions: { supersede } };
a.present(viewA);
b.present(viewB);
a.present(null);
+40 -8
View File
@@ -36,6 +36,14 @@ function tooManyPixels(width, height) {
);
}
/**
* Keys for each mount's and each canvas's elements, never reused by any
* viewer: a view that sees one viewer unmount and another mount in the same
* tick still draws them fresh elements (a destroyed renderer leaves its
* canvas's context lost).
*/
let viewKeys = 0;
/** Panorama texture widths: enough for a docked viewer, and for an expanded one. */
const PANO_MID_SIZE = Object.freeze([2048, 1024]);
export const PANO_FULL_SIZE = Object.freeze([4096, 2048]);
@@ -215,14 +223,18 @@ export function panoSizeFor(canvasPixels, fovDeg) {
*
* The adapter draws nothing itself. It presents the viewer through
* `subscribeView()` (the street-level layer's `subscribePhotoViewer()`): a
* fresh `{host, providerId, label, alt, kind, src, fit, canvasKey, dragging,
* prevLabel, prevDisabled, nextLabel, nextDisabled, actions}` on each change,
* fresh `{host, mountKey, providerId, label, alt, kind, src, fit, canvasKey,
* dragging, prevLabel, prevDisabled, nextLabel, nextDisabled, actions}` on
* each change,
* or null while unmounted. A view draws it into `host` (the application's is
* `StreetLevelPhotoViewer`), forwards its events to `actions` and hands each
* element back through `actions.attach(name, element)`: the panorama canvas
* to draw on, the frame and picture to measure, the root and buttons to
* keep focus. A new `canvasKey` asks for a fresh canvas (a lost WebGL
* context). Mounting with no view subscribed fails.
* keep focus. Each mount has its own `mountKey`, 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.
*
* Photos are normalized by the provider: `{id, sequenceId, lon, lat,
* heading, isPano, capturedAt}` plus whatever its `sources` read.
@@ -269,7 +281,7 @@ export function createPhotoViewer({
/** What the view draws; null while unmounted. */
let presented = null;
const viewListeners = new Set();
/** Waiting for the view's root (a mount) or a fresh canvas (an open). */
/** Waiting for the view's root (a mount), or its canvas: a fresh one, or the next draw. */
const rootWaiters = new Set();
const canvasWaiters = new Set();
let renderer = null;
@@ -393,6 +405,15 @@ export function createPhotoViewer({
});
}
/** The view's next draw (it hands the canvas back each time), or none coming. */
function nextDraw(signal) {
if (!presented || signal?.aborted) return Promise.resolve();
return new Promise((resolve) => {
canvasWaiters.add(resolve);
signal?.addEventListener?.('abort', resolve, { once: true });
});
}
function syncButtons() {
const enabled = Boolean(photo?.sequenceId) && showing !== null;
present({ prevDisabled: !enabled, nextDisabled: !enabled });
@@ -461,7 +482,7 @@ export function createPhotoViewer({
// 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: presented.canvasKey + 1 });
present({ canvasKey: ++viewKeys });
// Show the photo again through the core, unless a newer one is opening.
if (showing === 'pano' && photo && openingId === null) {
const again = photo.id;
@@ -654,6 +675,7 @@ export function createPhotoViewer({
pointerup: current(onPointerUp),
wheel: current(onWheel),
contextLost: current(onContextLost),
supersede: current(() => adapter.unmount()),
step: current((delta, event) => {
event?.stopPropagation?.();
stepBy(delta);
@@ -661,6 +683,7 @@ export function createPhotoViewer({
};
presented = {
host,
mountKey: ++viewKeys,
providerId,
label: t(
'{name} photo. ← and → step along the sequence. On a 360° photo, drag or use Shift+← →, ↑ ↓ to look around, and + − to zoom',
@@ -670,7 +693,7 @@ export function createPhotoViewer({
kind: undefined,
src: null,
fit: renderMode === 'fill' ? 'cover' : 'contain',
canvasKey: 0,
canvasKey: ++viewKeys,
dragging: false,
prevLabel: t('Previous photo in this sequence (←)'),
prevDisabled: true,
@@ -841,8 +864,15 @@ export function createPhotoViewer({
else if (!keepView || showing !== 'pano')
renderer.setView({ yaw: 0, pitch: 0, fov: PANO_FOV_DEFAULT_DEG });
photo = target;
// Shown first: a hidden canvas measures 0 and would be sized 1×1.
// Shown first: a hidden canvas measures 0 and would be sized 1×1. The
// view draws it shown on a microtask, and hands the canvas back then.
show('pano');
await nextDraw(signal);
if (seq !== openSeq || !renderer) {
image.close?.();
if (seq !== openSeq) return false;
throw new Error(LOAD_FAILED);
}
renderer.setImage(image);
panoWidth = first.width || 0;
// A sharper version of the photo before was dropped by `open`; one of
@@ -911,6 +941,8 @@ export function createPhotoViewer({
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');
},
/** Resolves once the photo is on screen and its pose was emitted. */
+21 -12
View File
@@ -595,21 +595,30 @@ test('a panorama reopened after a lost context waits for the view’s fresh canv
};
},
});
// A view that draws a replacement canvas a while after it is asked.
// A view that draws on a microtask, as Vue does, handing its canvas back
// each time, but draws a replacement canvas only a while after it is
// asked.
let shown = null;
let canvas = { name: 'canvas', clientWidth: 400 };
let late = null;
viewer.subscribeView((view) => {
if (view && !shown) {
for (const name of ['root', 'picture', 'prev', 'next'])
view.actions.attach(name, { name, clientWidth: 400 });
view.actions.attach('canvas', { name: 'canvas 0', clientWidth: 400 });
} else if (view && view.canvasKey !== shown.canvasKey)
late = () =>
view.actions.attach('canvas', {
name: `canvas ${view.canvasKey}`,
clientWidth: 400,
});
const first = view && !shown;
const replaced = view && shown && view.canvasKey !== shown.canvasKey;
shown = view;
if (!view) return;
queueMicrotask(() => {
if (first)
for (const name of ['root', 'picture', 'prev', 'next'])
view.actions.attach(name, { name, clientWidth: 400 });
if (replaced) {
canvas = null;
late = () => {
canvas = { name: 'canvas again', clientWidth: 400 };
shown.actions.attach('canvas', canvas);
};
}
if (canvas) view.actions.attach('canvas', canvas);
});
});
await viewer.mount({});
await viewer.open('a');
@@ -623,7 +632,7 @@ test('a panorama reopened after a lost context waits for the view’s fresh canv
await opening;
assert.deepEqual(
canvases.map((canvas) => canvas.name),
['canvas 0', 'canvas 1'],
['canvas', 'canvas again'],
);
assert.equal(shown.kind, 'pano', 'not the front view');
});
+45
View File
@@ -0,0 +1,45 @@
/**
* Receive the photo viewer to draw, out of several photo viewers mounting
* in one host (see photoViewer.js): the one mounted last, by its mount key,
* whatever order they present in. One view draws one viewer, so a viewer
* still mounting when a later one presents is superseded: it settles its
* mount as closed and stops presenting. Starts with the current one (null
* while none is mounted).
* @param {Iterable<{subscribeView?: Function}>} viewers
* @param {(view: ?object) => void} listener
* @returns {() => void} Unsubscribe.
*/
export function subscribePhotoViewers(viewers, listener) {
// Each viewer's current presentation.
const shown = new Map();
let ready = false;
let last;
const publish = () => {
let next = null;
for (const view of shown.values())
if (!next || view.mountKey > next.mountKey) next = view;
if (!ready || next === last) return;
last = next;
listener(next);
// The others are not drawn: a mount still waiting on the view never
// would be.
if (next)
for (const view of [...shown.values()])
if (view.mountKey < next.mountKey) view.actions.supersede();
};
const unsubscribes = [];
for (const viewer of viewers) {
const unsubscribe = viewer?.subscribeView?.((view) => {
if (view) shown.set(viewer, view);
else shown.delete(viewer);
publish();
});
if (typeof unsubscribe === 'function') unsubscribes.push(unsubscribe);
}
ready = true;
publish();
if (last === undefined) listener((last = null));
return () => {
for (const unsubscribe of unsubscribes.splice(0)) unsubscribe();
};
}
@@ -0,0 +1,55 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { subscribePhotoViewers } from './photoViewers.js';
/**
* A photo viewer whose presentations the test sends; `superseded` counts.
* Unlike photoViewer.js it keeps presenting once superseded, so the order
* is seen to come from the mount keys alone.
*/
function fakeViewer() {
const listeners = new Set();
const viewer = {
superseded: 0,
view(mountKey) {
return {
mountKey,
actions: { supersede: () => viewer.superseded++ },
};
},
present(view) {
for (const listener of [...listeners]) listener(view);
},
subscribeView(listener) {
listeners.add(listener);
listener(null);
return () => listeners.delete(listener);
},
};
return viewer;
}
test('the later mount is drawn, whatever order the viewers present in', () => {
const a = fakeViewer();
const b = fakeViewer();
const shown = [];
const unsubscribe = subscribePhotoViewers([a, b], (view) => shown.push(view));
assert.deepEqual(shown, [null], 'the current one first');
const first = a.view(1);
a.present(first);
const later = b.view(2);
b.present(later);
assert.equal(shown.at(-1), later);
assert.equal(a.superseded, 1, 'the earlier mount is told it is not drawn');
// The earlier viewer presents again: it does not take the view back.
a.present({ ...first, kind: 'flat' });
assert.equal(shown.at(-1), later);
assert.equal(shown.length, 3);
b.present(null);
assert.equal(shown.at(-1).mountKey, 1, 'the only one presenting');
a.present(null);
assert.equal(shown.at(-1), null);
unsubscribe();
a.present(first);
assert.equal(shown.length, 5, 'unsubscribed');
});
@@ -13,7 +13,11 @@ import {
TOO_HIGH_HINT,
} from './policy.js';
import { validateProviders } from '../../registry.js';
import { fakeHost, until } from '../../../../testSupport/kartaViewFakes.mjs';
import {
drawn,
fakeHost,
until,
} from '../../../../testSupport/kartaViewFakes.mjs';
import {
bindStreetViewer,
coverageViewer,
@@ -978,6 +982,7 @@ test('after a GPU reset the photo is drawn again by the viewer, not through the
const canvas = () => host.children[0].children[1];
const kind = () => host.children[0].dataset.kind;
canvas().fire('webglcontextlost');
await drawn();
assert.equal(kind(), '', 'cleared while it is drawn again');
assert.ok(await until(() => kind() === 'pano'), 'drawn again');
assert.ok(poses.length >= 2);
@@ -1,7 +1,11 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createKartaViewViewer, loadImage, panoSizeFor } from './viewer.js';
import { fakeHost, until } from '../../../../testSupport/kartaViewFakes.mjs';
import {
drawn,
fakeHost,
until,
} from '../../../../testSupport/kartaViewFakes.mjs';
const PHOTOS = {
flat1: {
@@ -223,6 +227,7 @@ test('a flat photo shows its 1280 px version, then the sharp one, with a pose fa
assert.equal(picture.src, loads[1].url, 'upgraded to the sharp version');
assert.equal(viewer.supportsRenderModes(), true);
viewer.setRenderMode('fill');
await drawn();
assert.equal(picture.style.objectFit, 'cover');
});
@@ -357,12 +362,14 @@ test('a newer open wins; close hides the photo; unmount tears down the panorama'
assert.equal(renderers.length, 0, 'nor built a WebGL context');
await viewer.open('pano1');
viewer.close();
await drawn();
const { picture, canvas, root } = parts(host);
assert.equal(canvas.hidden, true);
assert.equal(picture.hidden, true);
assert.equal(root.dataset.kind, '');
await assert.rejects(viewer.open('nope'), /no such photo/);
viewer.unmount();
await drawn();
assert.equal(host.children.length, 0);
assert.equal(renderers[0].destroyed, true);
await assert.rejects(viewer.open('flat1'), /not mounted/);
@@ -463,12 +470,14 @@ test('a lost WebGL context drops the panorama and shows the photo again on a new
const lost = parts(host).canvas;
lost.fire('webglcontextlost');
assert.equal(renderers[0].destroyed, true);
await drawn();
// A lost canvas only ever gives back its lost context: a new element.
assert.notEqual(parts(host).canvas, lost);
assert.deepEqual(stepped, ['pano1'], 'reopened through the core');
assert.ok(await until(() => renderers.length === 2), 'a new renderer');
assert.equal(renderers[1].canvas, parts(host).canvas);
assert.equal(poses.at(-1).imageId, 'pano1');
await drawn();
assert.equal(parts(host).canvas.hidden, false);
});
@@ -931,7 +940,7 @@ test('a docked viewer keeps the 1,280 px photo; expanding it brings the 2,560 px
viewer.resize();
assert.ok(await until(() => loads.length === 2));
assert.match(loads[1].url, /rs:fit:2560:2560/);
assert.equal(parts(host).picture.src, loads[1].url);
assert.ok(await until(() => parts(host).picture.src === loads[1].url));
viewer.resize();
for (let i = 0; i < 4; i++) await settle();
assert.equal(loads.length, 2, 'once only');
@@ -14,7 +14,11 @@ import {
} from './policy.js';
import { validateProviders } from '../../registry.js';
import { tileBounds } from '../../tileMath.js';
import { fakeHost, until } from '../../../../testSupport/kartaViewFakes.mjs';
import {
drawn,
fakeHost,
until,
} from '../../../../testSupport/kartaViewFakes.mjs';
import {
bindStreetViewer,
coverageViewer,
@@ -994,6 +998,8 @@ test('after a GPU reset the viewer draws the same picture itself, leaving the co
const kind = () => host.children[0].dataset.kind;
assert.equal(kind(), 'pano');
canvas().fire('webglcontextlost');
await drawn();
assert.equal(kind(), '', 'cleared while it is drawn again');
assert.ok(await until(() => kind() === 'pano'), 'drawn again');
assert.deepEqual(poses, ['p-0', 'p-0']);
assert.deepEqual(actions.opened, [], 'not through the core');
+46 -36
View File
@@ -72,16 +72,20 @@ export function fakeHost(viewer = null) {
/**
* Draw a photo viewer's presentations with fake elements, as
* StreetLevelPhotoViewer does: the root in the host it names, holding the
* picture, the panorama canvas and the ‹ › buttons, each handed back; a
* value is written only when the presentation changes it (as Vue patches),
* and the elements' events reach the viewer's actions. A new canvas key
* puts a fresh canvas in the old one's place.
* StreetLevelPhotoViewer does through Vue: changes made in one tick are
* drawn once, on a microtask, with their final value; the root (keyed by
* the mount) holds the picture, the panorama canvas (keyed by its canvas
* key) and the ‹ › buttons, kept while their keys are, and every element
* is handed back on each draw. A value is written only when the drawn
* presentation changes it, and the elements' events reach the viewer's
* actions.
* @returns {() => void} Stop drawing.
*/
export function drawPhotoViewer(viewer) {
let parts = null;
let last = null;
let pending = null;
let queued = false;
const on = (element, type, name) =>
element.addEventListener(type, (event) => last?.actions[name](event));
const canvasFor = () => {
@@ -111,58 +115,61 @@ export function drawPhotoViewer(viewer) {
view.host.append(root);
return { root, picture, canvas, prev, next };
};
const changed = (view, key) => !last || last[key] !== view[key];
return viewer.subscribeView((view) => {
const draw = (view) => {
if (!view) {
parts?.root.remove();
parts = last = null;
return;
}
const fresh = !parts || last.host !== view.host;
if (fresh) {
if (!parts || last.mountKey !== view.mountKey) {
parts?.root.remove();
parts = build(view);
last = null;
} else if (last.host !== view.host) {
parts.root.remove();
view.host.append(parts.root);
}
const { root, picture, prev, next } = parts;
if (!fresh && changed(view, 'canvasKey')) {
const changed = (key) => !last || last[key] !== view[key];
let canvasFresh = !last;
if (last && changed('canvasKey')) {
const canvas = canvasFor();
parts.canvas.replaceWith(canvas);
parts.canvas = canvas;
parts.canvasFresh = true;
canvasFresh = true;
}
const { canvas } = parts;
if (changed(view, 'providerId')) root.dataset.provider = view.providerId;
if (changed(view, 'label')) root.attributes['aria-label'] = view.label;
if (changed(view, 'kind') && view.kind !== undefined)
const { root, picture, canvas, prev, next } = parts;
if (changed('providerId')) root.dataset.provider = view.providerId;
if (changed('label')) root.attributes['aria-label'] = view.label;
if (changed('kind') && view.kind !== undefined)
root.dataset.kind = view.kind;
if (changed(view, 'alt')) picture.alt = view.alt;
if (changed(view, 'src')) {
if (changed('alt')) picture.alt = view.alt;
if (changed('src')) {
if (view.src) picture.src = view.src;
else picture.removeAttribute('src');
}
if (changed(view, 'fit')) picture.style.objectFit = view.fit;
if (changed(view, 'kind') || parts.canvasFresh) {
picture.hidden = view.kind !== 'flat';
canvas.hidden = view.kind !== 'pano';
}
if (changed(view, 'dragging') || parts.canvasFresh) {
if (changed('fit')) picture.style.objectFit = view.fit;
if (changed('kind')) picture.hidden = view.kind !== 'flat';
if (changed('kind') || canvasFresh) canvas.hidden = view.kind !== 'pano';
if (changed('dragging') || canvasFresh) {
if (view.dragging) canvas.classList.add('sl-photo-dragging');
else canvas.classList.remove('sl-photo-dragging');
}
if (changed(view, 'prevLabel'))
prev.attributes['aria-label'] = view.prevLabel;
if (changed(view, 'nextLabel'))
next.attributes['aria-label'] = view.nextLabel;
if (changed(view, 'prevDisabled')) prev.disabled = view.prevDisabled;
if (changed(view, 'nextDisabled')) next.disabled = view.nextDisabled;
const handBack = fresh || parts.canvasFresh;
parts.canvasFresh = false;
if (changed('prevLabel')) prev.attributes['aria-label'] = view.prevLabel;
if (changed('nextLabel')) next.attributes['aria-label'] = view.nextLabel;
if (changed('prevDisabled')) prev.disabled = view.prevDisabled;
if (changed('nextDisabled')) next.disabled = view.nextDisabled;
last = view;
if (fresh)
for (const name of ['root', 'picture', 'canvas', 'prev', 'next'])
view.actions.attach(name, parts[name]);
else if (handBack) view.actions.attach('canvas', canvas);
for (const name of ['root', 'picture', 'canvas', 'prev', 'next'])
view.actions.attach(name, parts[name]);
};
return viewer.subscribeView((view) => {
pending = view;
if (queued) return;
queued = true;
queueMicrotask(() => {
queued = false;
draw(pending);
});
});
}
@@ -178,3 +185,6 @@ export async function until(condition, { ticks = 200 } = {}) {
}
return Boolean(await condition());
}
/** Let a photo viewer's view draw what was presented in this tick. */
export const drawn = () => new Promise((resolve) => queueMicrotask(resolve));
+14 -4
View File
@@ -76,10 +76,20 @@ test('the step buttons are not pressed toggles', () => {
test('the photo viewer is drawn by its view, and its layer needs no Vue', () => {
const source = read(VIEWER);
assert.doesNotMatch(
source,
/createElement|innerHTML|insertAdjacentHTML|\.append\(|\.classList|\.dataset|from 'vue'|\.vue'/,
);
// No element made, inserted, moved, removed or written: the view does
// all of that. (An Image the loader downloads with is not on the page.)
for (const write of [
/createElement/,
/\b(?:inner|outer)HTML\b/,
/insertAdjacent(?:HTML|Element|Text)/,
/\.(?:append|prepend|appendChild|insertBefore|replaceWith|replaceChildren|before|after)\(/,
/\.remove\(\)/,
/\.(?:set|remove|toggle)Attribute(?:NS)?\(/,
/\.(?:classList|className|dataset|style)\b/,
/\.(?:hidden|disabled|textContent|innerText|tabIndex|title|alt)\s*=[^=]/,
/from 'vue'|\.vue'/,
])
assert.doesNotMatch(source, write);
const markup = template(VIEW);
const opening = (name, attribute) =>
new RegExp(String.raw`<${name}\b${ATTRS}\s${attribute}${ATTRS}>`);
@@ -7,6 +7,7 @@ import assert from 'node:assert/strict';
import { createApp, nextTick } from 'vue';
import { createPinia } from 'pinia';
import { createPhotoViewer } from '../../../layers/streetLevel/photoViewer.js';
import { subscribePhotoViewers } from '../../../layers/streetLevel/photoViewers.js';
import { useStreetLevelPhotoStore } from '../../stores/streetLevelPhoto.js';
import StreetLevelPhotoViewer from './StreetLevelPhotoViewer.vue';
@@ -24,8 +25,11 @@ const SOURCES = {
describe: () => ({ externalUrl: 'https://example.org' }),
};
/** The view in an app, a viewer published to its store, and a panel host. */
function mount(t, options = {}) {
/**
* The view in an app, a viewer per provider published to its store as the
* street-level layer does, and a panel host.
*/
function mount(t, options = {}, providerIds = ['panoramax']) {
document.body.replaceChildren();
const wrap = document.body.appendChild(document.createElement('div'));
wrap.className = 'sl-viewer-wrap';
@@ -37,9 +41,10 @@ function mount(t, options = {}) {
const store = useStreetLevelPhotoStore(pinia);
const renderers = [];
const stepped = [];
const viewer = createPhotoViewer({
providerId: 'panoramax',
name: 'Panoramax',
const create = (providerId) =>
createPhotoViewer({
providerId,
name: providerId === 'panoramax' ? 'Panoramax' : 'KartaView',
sources: SOURCES,
getPhoto: async (id) => PHOTOS[id],
// f, then g: the whole sequence.
@@ -63,13 +68,16 @@ function mount(t, options = {}) {
},
...options,
});
const unsubscribe = viewer.subscribeView((view) => store.publish(view));
const viewers = providerIds.map(create);
const unsubscribe = subscribePhotoViewers(viewers, (view) =>
store.publish(view),
);
t.after(() => {
viewer.unmount();
for (const viewer of viewers) viewer.unmount();
unsubscribe();
app.unmount();
});
return { viewer, host, wrap, renderers, stepped };
return { viewer: viewers[0], viewers, host, wrap, renderers, stepped };
}
const tick = () => new Promise((resolve) => setTimeout(resolve, 0));
@@ -246,3 +254,51 @@ test('without a view, the viewer cannot mount', async () => {
/no view to draw it/,
);
});
test('a viewer mounted in the tick another unmounts gets elements of its own', async (t) => {
const { viewers, host, renderers } = mount(t, {}, ['kartaview', 'panoramax']);
const [kartaView, panoramax] = viewers;
await kartaView.mount(host);
await kartaView.open('p');
const root = host.querySelector('.sl-photo-viewer');
const canvas = root.children[1];
assert.ok(renderers[0].canvas === canvas);
// The core switches source: one unmounts and the other mounts at once.
kartaView.unmount();
const mounting = panoramax.mount(host);
await mounting;
await panoramax.open('p');
const fresh = host.querySelector('.sl-photo-viewer');
assert.equal(host.children.length, 1);
assert.ok(fresh !== root, 'a root of its own');
assert.equal(fresh.dataset.provider, 'panoramax');
assert.ok(fresh.children[1] !== canvas, 'not the destroyed renderer’s canvas');
assert.ok(renderers[1].canvas === fresh.children[1]);
assert.equal(fresh.dataset.kind, 'pano', 'not the front view');
});
test('a mount overtaken before it is drawn closes, and never shows later', async (t) => {
const { viewers, host } = mount(t, {}, ['kartaview', 'panoramax']);
const [kartaView, panoramax] = viewers;
// KartaView starts mounting; Panoramax mounts before the view draws it.
const overtaken = kartaView.mount(host);
const current = panoramax.mount(host);
// It settles, rather than wait for a draw that never comes.
const outcome = await Promise.race([
overtaken.then(
() => 'mounted',
(error) => error.message,
),
new Promise((resolve) => setTimeout(() => resolve('still pending'), 100)),
]);
assert.match(outcome, /viewer was closed/);
await current;
await nextTick();
assert.equal(host.children.length, 1);
assert.equal(host.children[0].dataset.provider, 'panoramax');
await assert.rejects(kartaView.open('f'), /not mounted/);
// Once Panoramax goes, nothing is left in the host.
panoramax.unmount();
await nextTick();
assert.equal(host.children.length, 0);
});
@@ -9,7 +9,8 @@ import { useStreetLevelPhotoStore } from '../../stores/streetLevelPhoto.js';
// which photo shows and how, its loading, the panorama it draws, the keys,
// drag and zoom. This view draws what it presents, forwards the events and
// hands each element back: the canvas it draws on, the frame and picture
// it measures, the root and buttons it keeps focus with.
// it measures, the root and buttons it keeps focus with. Each mount and each
// canvas has its own key, so a viewer never gets another one's elements.
const { photo } = storeToRefs(useStreetLevelPhotoStore());
/** Hand `name`'s element back to the viewer that presented it. */
@@ -30,6 +31,7 @@ const refs = {
<template>
<Teleport v-if="photo" :to="photo.host"
><div
:key="photo.mountKey"
:ref="refs.root"
class="sl-photo-viewer"
:data-provider="photo.providerId"