diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 06c3093d7d..ce7a0e21c7 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -6354,8 +6354,9 @@ viewer host and hands back the canvas the panorama is drawn on (a fresh one 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. +earlier one's mount closes. A view may draw at once or later; what it +reads (`mountKey`, `actions.supersede()`) is `ViewerAdapter.subscribeView` +in `registry.js`. 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 diff --git a/src/layers/streetLevel/photoViewer.js b/src/layers/streetLevel/photoViewer.js index c9b9f48a11..f802777e78 100644 --- a/src/layers/streetLevel/photoViewer.js +++ b/src/layers/streetLevel/photoViewer.js @@ -228,13 +228,15 @@ export function panoSizeFor(canvasPixels, fovDeg) { * 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. 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. + * element back through `actions.attach(name, element)` on every draw: the + * panorama canvas to draw on, the frame and picture to measure, the root + * and buttons to keep focus. A view may draw at once, inside its listener, + * or later (Vue draws on a microtask). 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; an open waiting + * on a draw when the last view leaves goes on without it. * * Photos are normalized by the provider: `{id, sequenceId, lon, lat, * heading, isPano, capturedAt}` plus whatever its `sources` read. @@ -284,6 +286,8 @@ export function createPhotoViewer({ /** 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(); + /** How many times the view has handed the canvas back (once per draw). */ + let canvasDraws = 0; let renderer = null; /** WebGL failed once: 360° photos show their front view instead. */ let rendererFailed = false; @@ -396,22 +400,28 @@ export function createPhotoViewer({ waiters.clear(); } - /** The panorama canvas once the view has drawn it, or the open stopped. */ - function canvasReady(signal) { - if (canvas || !presented || signal?.aborted) return Promise.resolve(); + /** A draw of the canvas, or none coming: unmounted, no view, or the open stopped. */ + function canvasDrawn(drawn, signal) { + if (drawn() || !presented || !viewListeners.size || signal?.aborted) + return Promise.resolve(); return new Promise((resolve) => { canvasWaiters.add(resolve); signal?.addEventListener?.('abort', resolve, { once: true }); }); } - /** 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 }); - }); + /** The panorama canvas once the view has drawn it, or the open stopped. */ + function canvasReady(signal) { + return canvasDrawn(() => Boolean(canvas), signal); + } + + /** + * A draw of the canvas after the `count`th (it hands the canvas back each + * time), or none coming. A view may draw synchronously, inside the + * presentation, before anything waits: counted, that draw is not missed. + */ + function drawnAfter(count, signal) { + return canvasDrawn(() => canvasDraws > count, signal); } function syncButtons() { @@ -667,7 +677,10 @@ export function createPhotoViewer({ if (presented?.actions !== actions || !element) return; ELEMENTS[name]?.(element); if (name === 'root') wake(rootWaiters); - if (name === 'canvas') wake(canvasWaiters); + if (name === 'canvas') { + canvasDraws++; + wake(canvasWaiters); + } }, keydown: current(onKeyDown), pointerdown: current(onPointerDown), @@ -865,9 +878,11 @@ export function createPhotoViewer({ 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. The - // view draws it shown on a microtask, and hands the canvas back then. + // view draws it shown, at once or on a microtask, and hands the canvas + // back then. + const draws = canvasDraws; show('pano'); - await nextDraw(signal); + await drawnAfter(draws, signal); if (seq !== openSeq || !renderer) { image.close?.(); if (seq !== openSeq) return false; @@ -1029,7 +1044,11 @@ export function createPhotoViewer({ subscribeView(listener) { viewListeners.add(listener); listener(presented); - return () => viewListeners.delete(listener); + return () => { + // The last view went: an open waiting on its draw goes on without. + if (viewListeners.delete(listener) && !viewListeners.size) + wake(canvasWaiters); + }; }, }; return adapter; diff --git a/src/layers/streetLevel/photoViewer.test.mjs b/src/layers/streetLevel/photoViewer.test.mjs index 97c8bf4000..e1e9b14f5d 100644 --- a/src/layers/streetLevel/photoViewer.test.mjs +++ b/src/layers/streetLevel/photoViewer.test.mjs @@ -636,3 +636,94 @@ test('a panorama reopened after a lost context waits for the view’s fresh canv ); assert.equal(shown.kind, 'pano', 'not the front view'); }); + +/** + * A panorama viewer whose sequence goes on both ways (its ‹ › present no + * change once shown), drawn by `view` alone, not by the shared fake view. + */ +function panoramaViewer() { + const images = []; + const viewer = createPhotoViewer({ + providerId: 'test', + name: 'Test', + sources: SOURCES, + getPhoto: async (id) => PHOTOS[id], + step: async () => 'b', + onStep() {}, + load: async (url) => ({ src: url }), + createRenderer: () => ({ + setImage: (image) => images.push(image.src), + setView() {}, + getView: () => ({ yaw: 0, pitch: 0, fov: 80 }), + resize() {}, + clear() {}, + destroy() {}, + }), + }); + return { viewer, images }; +} + +/** Elements a view hands back: what the viewer measures and focuses. */ +const elements = () => + Object.fromEntries( + ['root', 'picture', 'canvas', 'prev', 'next'].map((name) => [ + name, + { clientWidth: 400, clientHeight: 250 }, + ]), + ); + +/** Whether `promise` settles within a few macrotasks. */ +const settles = (promise) => + Promise.race([ + promise.then( + () => true, + () => true, + ), + new Promise((resolve) => setTimeout(() => resolve(false), 50)), + ]); + +test('a view that draws at once, inside its listener, opens a panorama', async () => { + const { viewer, images } = panoramaViewer(); + const parts = elements(); + const unsubscribe = viewer.subscribeView((view) => { + if (!view) return; + for (const [name, element] of Object.entries(parts)) + view.actions.attach(name, element); + }); + await viewer.mount(fakeHost()); + assert.equal(await settles(viewer.open('a')), true, 'not left pending'); + assert.deepEqual(images, ['a-first']); + viewer.unmount(); + unsubscribe(); +}); + +test('an open waiting on the view’s draw goes on when the view unsubscribes', async () => { + const { viewer } = panoramaViewer(); + const parts = elements(); + const kinds = []; + // Draws the mount, then nothing more. + const unsubscribe = viewer.subscribeView((view) => { + if (!view) return; + kinds.push(view.kind); + if (kinds.length > 1) return; + for (const [name, element] of Object.entries(parts)) + view.actions.attach(name, element); + }); + await viewer.mount(fakeHost()); + const opening = viewer.open('a'); + assert.ok(await until(() => kinds.includes('pano')), 'waiting on a draw'); + unsubscribe(); + assert.equal(await settles(opening), true, 'not left pending'); + viewer.unmount(); +}); + +test('the shared fake view draws only the later of two mounts, as the app does', async () => { + const one = setup(); + const two = setup(); + await one.viewer.mount(one.host); + assert.equal(one.host.children.length, 1); + await two.viewer.mount(one.host); + assert.equal(one.host.children.length, 1, 'one root, not one per viewer'); + await assert.rejects(one.viewer.open('f'), /not mounted/, 'superseded'); + two.viewer.unmount(); +}); diff --git a/src/layers/streetLevel/photoViewers.js b/src/layers/streetLevel/photoViewers.js index ecf4eab5a1..bb1ddf404f 100644 --- a/src/layers/streetLevel/photoViewers.js +++ b/src/layers/streetLevel/photoViewers.js @@ -1,37 +1,70 @@ /** * 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). + * in one host (see photoViewer.js): the one mounted last, 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). + * + * 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. + * - `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. * @param {Iterable<{subscribeView?: Function}>} viewers * @param {(view: ?object) => void} listener * @returns {() => void} Unsubscribe. */ export function subscribePhotoViewers(viewers, listener) { - // Each viewer's current presentation. + // Each viewer's current presentation, and when it began presenting. const shown = new Map(); + let arrivals = 0; 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; + }; + // The others are not drawn: a mount still waiting on the view never + // would be. + const supersede = () => { + superseding = false; + if (closed || !last) return; + for (const { view } of [...shown.values()]) + if (view !== last) view.actions?.supersede?.(); + }; const publish = () => { let next = null; - for (const view of shown.values()) - if (!next || view.mountKey > next.mountKey) next = view; + 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); - // 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(); + if (next && shown.size > 1 && !superseding) { + superseding = true; + queueMicrotask(supersede); + } }; const unsubscribes = []; for (const viewer of viewers) { const unsubscribe = viewer?.subscribeView?.((view) => { - if (view) shown.set(viewer, view); - else shown.delete(viewer); + if (closed) return; + const entry = shown.get(viewer); + if (!view) shown.delete(viewer); + else if (entry && entry.view.mountKey === view.mountKey) + entry.view = view; + else shown.set(viewer, { view, arrival: ++arrivals }); publish(); }); if (typeof unsubscribe === 'function') unsubscribes.push(unsubscribe); @@ -40,6 +73,7 @@ export function subscribePhotoViewers(viewers, listener) { publish(); if (last === undefined) listener((last = null)); return () => { + closed = true; for (const unsubscribe of unsubscribes.splice(0)) unsubscribe(); }; } diff --git a/src/layers/streetLevel/photoViewers.test.mjs b/src/layers/streetLevel/photoViewers.test.mjs index a4525723bc..f9b3f609d6 100644 --- a/src/layers/streetLevel/photoViewers.test.mjs +++ b/src/layers/streetLevel/photoViewers.test.mjs @@ -29,7 +29,7 @@ function fakeViewer() { return viewer; } -test('the later mount is drawn, whatever order the viewers present in', () => { +test('the later mount is drawn, whatever order the viewers present in', async () => { const a = fakeViewer(); const b = fakeViewer(); const shown = []; @@ -40,6 +40,8 @@ test('the later mount is drawn, whatever order the viewers present in', () => { const later = b.view(2); b.present(later); assert.equal(shown.at(-1), later); + // Once every subscriber has the later one. + await Promise.resolve(); 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' }); @@ -53,3 +55,79 @@ test('the later mount is drawn, whatever order the viewers present in', () => { a.present(first); assert.equal(shown.length, 5, 'unsubscribed'); }); + +/** A viewer that, superseded, unmounts as photoViewer.js does: it presents null. */ +function unmountingViewer() { + const viewer = fakeViewer(); + const view = viewer.view; + viewer.view = (mountKey) => { + const presented = view(mountKey); + const supersede = presented.actions.supersede; + presented.actions.supersede = () => { + supersede(); + viewer.present(null); + }; + return presented; + }; + return viewer; +} + +test('every subscriber sees the earlier mount, then the later one, with no gap', async () => { + const a = unmountingViewer(); + const b = unmountingViewer(); + const first = []; + const second = []; + const unsubscribes = [ + subscribePhotoViewers([a, b], (view) => first.push(view)), + subscribePhotoViewers([a, b], (view) => second.push(view)), + ]; + const earlier = a.view(1); + a.present(earlier); + const later = b.view(2); + b.present(later); + await Promise.resolve(); + assert.equal(a.superseded, 1, 'superseded once, by both'); + assert.deepEqual(first, [null, earlier, later]); + assert.deepEqual(second, [null, earlier, later], 'never null between'); + for (const unsubscribe of unsubscribes) unsubscribe(); +}); + +test('a presentation without a mount key counts as the latest mount', () => { + const a = fakeViewer(); + const b = fakeViewer(); + const c = fakeViewer(); + const shown = []; + const unsubscribe = subscribePhotoViewers([a, b, c], (view) => + shown.push(view), + ); + a.present(a.view(5)); + const keyless = { actions: {} }; + 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: {} }; + 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'); + unsubscribe(); +}); + +test('a presentation without actions or supersede is drawn and passed over without throwing', async () => { + const a = fakeViewer(); + const b = fakeViewer(); + const shown = []; + const unsubscribe = subscribePhotoViewers([a, b], (view) => shown.push(view)); + a.present({ mountKey: 1 }); + const later = { mountKey: 2, actions: {} }; + assert.doesNotThrow(() => b.present(later)); + await Promise.resolve(); + assert.equal(shown.at(-1), later); + a.present({ mountKey: 3 }); + await Promise.resolve(); + assert.equal(shown.at(-1).mountKey, 3); + unsubscribe(); +}); diff --git a/src/layers/streetLevel/registry.js b/src/layers/streetLevel/registry.js index b74cfcdc99..177028d570 100644 --- a/src/layers/streetLevel/registry.js +++ b/src/layers/streetLevel/registry.js @@ -65,7 +65,14 @@ export function filtersOf(provider) { * @property {(listener: (pose: StreetPose) => void) => () => void} onPose * @property {(listener: (view: ?object) => void) => () => void} [subscribeView] * An adapter that draws nothing itself presents its viewer here, for the - * layer's `subscribePhotoViewer()` (see photoViewer.js). + * layer's `subscribePhotoViewer()` (see photoViewer.js): its current + * 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). * * @typedef {object} StreetPose * @property {string} providerId diff --git a/src/testSupport/kartaViewFakes.mjs b/src/testSupport/kartaViewFakes.mjs index 83ed5f38f5..c4b5ba5cce 100644 --- a/src/testSupport/kartaViewFakes.mjs +++ b/src/testSupport/kartaViewFakes.mjs @@ -1,4 +1,5 @@ // DOM stand-ins for the KartaView viewer's tests (no browser in Node). +import { subscribePhotoViewers } from '../layers/streetLevel/photoViewers.js'; /** A DOM element with what the viewer touches: children, events, attributes. */ function fakeElement(tag) { @@ -71,7 +72,45 @@ export function fakeHost(viewer = null) { } /** - * Draw a photo viewer's presentations with fake elements, as + * The one view of the photo viewers given to `drawPhotoViewer`, as the + * application has one StreetLevelPhotoViewer: the viewers reach it through + * photoViewers.js's picker, as the layer's `subscribePhotoViewer()` does, + * so only the mount made last is drawn and the earlier ones are superseded. + */ +const shared = { + viewers: new Set(), + draw: null, + unsubscribe: null, + generation: 0, +}; + +/** Subscribe the view to the viewers it has now, then let the old picker go. */ +function resubscribe() { + const previous = shared.unsubscribe; + const generation = ++shared.generation; + // The new picker first: a viewer is never left without a view. + shared.unsubscribe = subscribePhotoViewers([...shared.viewers], (view) => { + if (generation === shared.generation) shared.draw(view); + }); + previous?.(); +} + +/** + * Draw a photo viewer with the shared view, alongside every other viewer + * given here (see `shared`). + * @returns {() => void} Stop drawing it. + */ +export function drawPhotoViewer(viewer) { + shared.draw ??= photoView(); + shared.viewers.add(viewer); + resubscribe(); + return () => { + if (shared.viewers.delete(viewer)) resubscribe(); + }; +} + +/** + * A view drawing the presentations it is given with fake elements, as * 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 @@ -79,9 +118,9 @@ export function fakeHost(viewer = null) { * 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. + * @returns {(view: ?object) => void} Draw this presentation. */ -export function drawPhotoViewer(viewer) { +function photoView() { let parts = null; let last = null; let pending = null; @@ -162,7 +201,7 @@ export function drawPhotoViewer(viewer) { for (const name of ['root', 'picture', 'canvas', 'prev', 'next']) view.actions.attach(name, parts[name]); }; - return viewer.subscribeView((view) => { + return (view) => { pending = view; if (queued) return; queued = true; @@ -170,7 +209,7 @@ export function drawPhotoViewer(viewer) { queued = false; draw(pending); }); - }); + }; } /** diff --git a/src/ui/kit/streetLevelPhotoControls.test.mjs b/src/ui/kit/streetLevelPhotoControls.test.mjs index be1d65a8b5..5f20b03faf 100644 --- a/src/ui/kit/streetLevelPhotoControls.test.mjs +++ b/src/ui/kit/streetLevelPhotoControls.test.mjs @@ -74,10 +74,20 @@ test('the step buttons are not pressed toggles', () => { } }); +/** + * `loadImage`, which downloads through an Image of its own that is never on + * the page: the one place a `.src` is written. + */ +const LOADER = /^export function loadImage\([\s\S]*?^}$/m; + test('the photo viewer is drawn by its view, and its layer needs no Vue', () => { const source = read(VIEWER); + const loader = source.match(LOADER)?.[0]; + assert.ok(loader, 'loadImage is found'); + const rest = source.replace(LOADER, ''); // 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.) + // all of that. (The panorama renderer in panorama.js sizes its canvas's + // drawing buffer, as WebGL drawing does; nothing here does.) for (const write of [ /createElement/, /\b(?:inner|outer)HTML\b/, @@ -87,9 +97,15 @@ test('the photo viewer is drawn by its view, and its layer needs no Vue', () => /\.(?:set|remove|toggle)Attribute(?:NS)?\(/, /\.(?:classList|className|dataset|style)\b/, /\.(?:hidden|disabled|textContent|innerText|tabIndex|title|alt)\s*=[^=]/, + /\.(?:width|height|ariaLabel|id|value)\s*=[^=]/, /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. + assert.match(loader, /\bconst image = new Image\(\);/); + for (const [write] of loader.matchAll(/[\w$.\]]+\.src\s*=(?!=)/g)) + assert.match(write, /^image\.src\s*=$/, write); const markup = template(VIEW); const opening = (name, attribute) => new RegExp(String.raw`<${name}\b${ATTRS}\s${attribute}${ATTRS}>`); diff --git a/src/ui/stores/streetLevelPhoto.js b/src/ui/stores/streetLevelPhoto.js index dc0ebffacb..b9498452b3 100644 --- a/src/ui/stores/streetLevelPhoto.js +++ b/src/ui/stores/streetLevelPhoto.js @@ -10,9 +10,12 @@ export const useStreetLevelPhotoStore = defineStore( 'gev-street-level-photo', () => { /** - * `{host, providerId, label, alt, kind, src, fit, canvasKey, dragging, - * prevLabel, prevDisabled, nextLabel, nextDisabled, actions}`, or null - * while no photo viewer is mounted. + * `{host, mountKey, providerId, label, alt, kind, src, fit, canvasKey, + * dragging, prevLabel, prevDisabled, nextLabel, nextDisabled, actions}`, + * or null while no photo viewer is mounted. Of the viewers mounting in + * the host, only the one mounted last (the largest `mountKey`) is + * published; `actions.supersede()` tells the others they are not drawn + * (see `ViewerAdapter.subscribeView` in src/layers/streetLevel/registry.js). */ const photo = shallowRef(null);