diff --git a/src/layers/streetLevel/photoViewer.js b/src/layers/streetLevel/photoViewer.js index e2d8d14e29..8a6f2a97de 100644 --- a/src/layers/streetLevel/photoViewer.js +++ b/src/layers/streetLevel/photoViewer.js @@ -4,8 +4,14 @@ import { wrapDegrees, } from './panorama.js'; import { imageSize } from './imageSize.js'; +import { nextViewKey } from './photoViewers.js'; import { msg, t } from '../../i18n/index.js'; +// Each mount's and each canvas's key comes from `nextViewKey()`, 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). + /** * EXPAND puts the viewer's wrap full screen, or (iPhone) opens it as a * popover. Each is tried on its own: a browser that cannot parse one @@ -36,14 +42,6 @@ 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]); @@ -301,6 +299,13 @@ export function createPhotoViewer({ const canvasWaiters = new Set(); /** How many times the view has handed the canvas back (once per draw). */ let canvasDraws = 0; + /** + * Canvases the panorama moved off: one handed back again (a second view + * drawing its own) is not moved back to, so two views cannot take turns. + */ + const retiredCanvases = new WeakSet(); + /** The canvas moved while an open waited on its draw. */ + let canvasMoved = false; let renderer = null; /** WebGL failed once: 360° photos show their front view instead. */ let rendererFailed = false; @@ -496,7 +501,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: ++viewKeys }); + present({ canvasKey: nextViewKey() }); reopen(); } @@ -507,8 +512,11 @@ export function createPhotoViewer({ */ function moveCanvas(element) { dropRenderer(); + retiredCanvases.add(canvas); canvas = element; - reopen(); + // An open waiting on the draw goes on, on the new canvas. + if (openingId !== null) canvasMoved = true; + else reopen(); } /** Let the renderer go, keeping the user's look for the photo's reopen. */ @@ -708,6 +716,7 @@ export function createPhotoViewer({ const actions = { attach(name, element) { if (presented?.actions !== actions || !element) return; + if (name === 'canvas' && retiredCanvases.has(element)) return; if (name === 'canvas' && renderer && canvas && element !== canvas) moveCanvas(element); else ELEMENTS[name]?.(element); @@ -731,7 +740,7 @@ export function createPhotoViewer({ }; presented = { host, - mountKey: ++viewKeys, + mountKey: nextViewKey(), providerId, label: t( '{name} photo. ← and → step along the sequence. On a 360° photo, drag or use Shift+← →, ↑ ↓ to look around, and + − to zoom', @@ -741,7 +750,7 @@ export function createPhotoViewer({ kind: undefined, src: null, fit: renderMode === 'fill' ? 'cover' : 'contain', - canvasKey: ++viewKeys, + canvasKey: nextViewKey(), dragging: false, prevLabel: t('Previous photo in this sequence (←)'), prevDisabled: true, @@ -916,8 +925,16 @@ export function createPhotoViewer({ // view draws it shown, at once or on a microtask, and hands the canvas // back then. const draws = canvasDraws; + canvasMoved = false; show('pano'); await drawnAfter(draws, signal); + // The view drew it on another canvas: the panorama goes there. + if (canvasMoved && seq === openSeq && !renderer && ensureRenderer()) { + const moved = restoreView?.id === target.id ? restoreView.view : null; + restoreView = null; + if (moved) renderer.setView(moved); + } + canvasMoved = false; // 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) { @@ -998,14 +1015,27 @@ export function createPhotoViewer({ throw new Error('Street Level photo viewer has no view to draw it'); // 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)); + const waitRoot = () => new Promise((resolve) => rootWaiters.add(resolve)); + let drawn = waitRoot(); build(host); - if (!root) await drawn; - 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(); + // This mount's presentation: a later mount presents its own. + const mine = presented.actions; + for (;;) { + if (!root) await drawn; + const current = presented?.actions === mine; + if (root && current) return; + // Unmounted, superseded or mounted again: that is not this mount. + if (!current) throw undrawn(); + // Its last view left, and another subscribed since: it draws. + if (viewListeners.size) { + drawn = waitRoot(); + continue; + } + // No view will draw it. Unmounted, as when superseded, so a view + // subscribing later draws nothing. + adapter.unmount(); + throw undrawn(); + } }, /** Resolves once the photo is on screen and its pose was emitted. */ diff --git a/src/layers/streetLevel/photoViewer.test.mjs b/src/layers/streetLevel/photoViewer.test.mjs index ac3e252885..370ae53986 100644 --- a/src/layers/streetLevel/photoViewer.test.mjs +++ b/src/layers/streetLevel/photoViewer.test.mjs @@ -828,3 +828,129 @@ test('a viewer left by an earlier test is not superseded by a later test’s', a earlier.viewer.unmount(); later.viewer.unmount(); }); + +/** A panorama viewer whose renderers and flat loads the test reads. */ +function trackedViewer(options = {}) { + const renderers = []; + const loads = []; + const viewer = createPhotoViewer({ + providerId: 'test', + name: 'Test', + sources: SOURCES, + getPhoto: async (id) => PHOTOS[id], + step: async () => null, + onStep() {}, + load: async (url) => { + loads.push(url); + return { src: url }; + }, + createRenderer: (canvas) => { + const renderer = { + canvas, + images: [], + setImage: (image) => renderer.images.push(image.src), + setView() {}, + getView: () => ({ yaw: 0, pitch: 0, fov: 80 }), + resize() {}, + clear() {}, + destroy() {}, + }; + renderers.push(renderer); + return renderer; + }, + ...options, + }); + return { viewer, renderers, loads }; +} + +/** Hand `parts` back to the viewer that presented `view`. */ +const attachAll = (view, parts) => { + for (const [name, element] of Object.entries(parts)) + view.actions.attach(name, element); +}; + +test('a mount overtaken by a second mount of the same viewer closes, and the second stays', async () => { + const { viewer } = trackedViewer(); + let latest = null; + const unsubscribe = viewer.subscribeView((view) => (latest = view)); + const first = viewer.mount({ id: 1 }); + const hostTwo = { id: 2 }; + const second = viewer.mount(hostTwo); + // The view draws on a later macrotask. + setTimeout(() => latest && attachAll(latest, elements()), 0); + await assert.rejects(first, /viewer was closed/); + await second; + assert.equal(latest?.host, hostTwo, 'the second mount is presented'); + viewer.unmount(); + unsubscribe(); +}); + +test('a mount whose view subscribes again in the same tick is drawn', async () => { + const { viewer } = trackedViewer(); + let latest = null; + const view = (next) => (latest = next); + let unsubscribe = viewer.subscribeView(view); + const mounting = viewer.mount({}); + // The view is replaced at once, and draws on a later macrotask. + unsubscribe(); + unsubscribe = viewer.subscribeView(view); + setTimeout(() => latest && attachAll(latest, elements()), 0); + await mounting; + assert.ok(latest, 'still presented'); + viewer.unmount(); + unsubscribe(); +}); + +test('a canvas handed back while a panorama’s open waits on its draw takes the panorama', async () => { + const { viewer, renderers, loads } = trackedViewer(); + const first = elements(); + const second = elements(); + let latest = null; + let hold = false; + const unsubscribe = viewer.subscribeView((view) => { + latest = view; + if (view && !hold) attachAll(view, first); + }); + await viewer.mount({}); + hold = true; + const opening = viewer.open('a'); + assert.ok(await until(() => latest?.kind === 'pano'), 'waiting on a draw'); + // The view draws it with a canvas of its own. + attachAll(latest, second); + await opening; + assert.equal(latest.kind, 'pano', 'not the front view'); + assert.deepEqual(loads, ['a-first'], 'no flat version loaded'); + assert.equal(renderers.at(-1).canvas, second.canvas); + assert.deepEqual(renderers.at(-1).images, ['a-first']); + viewer.unmount(); + unsubscribe(); +}); + +test('two views handing back canvases of their own do not take the panorama in turns', async () => { + let reopened = 0; + const { viewer, renderers } = trackedViewer({ + onReopen: (id) => { + reopened++; + if (reopened < 20) viewer.open(id).catch(() => {}); + }, + }); + const one = elements(); + const two = elements(); + const unsubscribes = [ + viewer.subscribeView((view) => view && attachAll(view, one)), + viewer.subscribeView((view) => view && attachAll(view, two)), + ]; + await viewer.mount({}); + await viewer.open('a'); + const built = renderers.length; + // Each presentation is drawn by both views. + for (const mode of ['fill', 'letterbox', 'fill']) { + viewer.setRenderMode(mode); + for (let i = 0; i < 5; i++) await tick(); + } + assert.equal(reopened, 0); + assert.equal(renderers.length, built, 'the panorama stays where it is'); + assert.deepEqual(renderers.at(-1).images, ['a-first']); + viewer.unmount(); + for (const unsubscribe of unsubscribes) unsubscribe(); +}); diff --git a/src/layers/streetLevel/photoViewers.js b/src/layers/streetLevel/photoViewers.js index d8e0176a98..ed32dd5208 100644 --- a/src/layers/streetLevel/photoViewers.js +++ b/src/layers/streetLevel/photoViewers.js @@ -1,3 +1,22 @@ +/** The last key handed out by `nextViewKey()`. */ +let viewKeys = 0; + +/** + * A key no viewer or picker was ever given: photo viewers key their mounts + * and canvases with it, and a presentation without a mount key is stamped + * with one when first seen, so both rank on one scale. + */ +export function nextViewKey() { + return ++viewKeys; +} + +/** + * Each keyless viewer's current mount, `{actions, key}`: stamped once, by + * whichever picker sees it first, and kept until it presents null, so a + * picker made later ranks it the same. + */ +const keylessMounts = new WeakMap(); + /** * Receive the photo viewer to draw, out of several photo viewers mounting * in one host (see photoViewer.js): the one mounted last, whatever order @@ -8,10 +27,10 @@ * * 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 mounted when it began presenting: - * after every mount presenting before it, before any later mount, keyed - * or not. + * - `mountKey`, a number larger for each later mount (from `nextViewKey()`), + * orders the mounts. A presentation without one counts as mounted when + * any picker first saw it present: it is stamped with a `nextViewKey()` + * then, the same for every picker, however many are made later. * - `actions.supersede()`, where present, is called on each presentation * not drawn, whenever more than one presents. It runs on a microtask, * after the presentation that won has reached every subscriber: a @@ -22,27 +41,21 @@ * @returns {() => void} Unsubscribe. */ export function subscribePhotoViewers(viewers, listener) { - // Each viewer's current presentation and its rank, {key, arrival}. + // Each viewer's current presentation and its rank, {view, key}. 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) => - 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, - }; + /** A mount's rank: its key, or the stamp of its first presentation. */ + const rank = (viewer, view) => { + if (Number.isFinite(view.mountKey)) return view.mountKey; + let mount = keylessMounts.get(viewer); + if (!mount || mount.actions !== view.actions) { + mount = { actions: view.actions, key: nextViewKey() }; + keylessMounts.set(viewer, mount); + } + return mount.key; }; // The others are not drawn: a mount still waiting on the view never // would be. @@ -55,7 +68,7 @@ export function subscribePhotoViewers(viewers, listener) { const publish = () => { let next = null; for (const entry of shown.values()) - if (!next || later(entry, next)) next = entry; + if (!next || entry.key > next.key) next = entry; next = next?.view ?? null; if (!ready) return; if (next !== last) { @@ -71,11 +84,10 @@ export function subscribePhotoViewers(viewers, listener) { for (const viewer of viewers) { const unsubscribe = viewer?.subscribeView?.((view) => { 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, ...rank(view) }); + if (!view) { + shown.delete(viewer); + keylessMounts.delete(viewer); + } else shown.set(viewer, { view, key: rank(viewer, view) }); publish(); }); if (typeof unsubscribe === 'function') unsubscribes.push(unsubscribe); diff --git a/src/layers/streetLevel/photoViewers.test.mjs b/src/layers/streetLevel/photoViewers.test.mjs index b27e315b78..aa56b6b316 100644 --- a/src/layers/streetLevel/photoViewers.test.mjs +++ b/src/layers/streetLevel/photoViewers.test.mjs @@ -1,7 +1,7 @@ import assert from 'node:assert/strict'; import test from 'node:test'; import { createPhotoViewer } from './photoViewer.js'; -import { subscribePhotoViewers } from './photoViewers.js'; +import { nextViewKey, subscribePhotoViewers } from './photoViewers.js'; /** * A photo viewer whose presentations the test sends; `superseded` counts. @@ -10,6 +10,7 @@ import { subscribePhotoViewers } from './photoViewers.js'; */ function fakeViewer() { const listeners = new Set(); + let current = null; const viewer = { superseded: 0, view(mountKey) { @@ -19,11 +20,12 @@ function fakeViewer() { }; }, present(view) { + current = view; for (const listener of [...listeners]) listener(view); }, subscribeView(listener) { listeners.add(listener); - listener(null); + listener(current); return () => listeners.delete(listener); }, }; @@ -101,7 +103,7 @@ test('a presentation without a mount key counts as mounted when it began present const unsubscribe = subscribePhotoViewers([a, b, c], (view) => shown.push(view), ); - a.present(a.view(5)); + a.present(a.view(nextViewKey())); const keyless = b.view(undefined); b.present(keyless); assert.equal(shown.at(-1), keyless, 'after the keyed one'); @@ -112,7 +114,7 @@ test('a presentation without a mount key counts as mounted when it began present 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); + const latest = a.view(nextViewKey()); a.present(latest); assert.equal(shown.at(-1), latest); await Promise.resolve(); @@ -186,3 +188,28 @@ test('a presentation without actions or supersede is drawn and passed over witho assert.equal(shown.at(-1).mountKey, 3); unsubscribe(); }); + +test('a keyless viewer on screen keeps its place when the picker is made again', async () => { + const keyed = fakeViewer(); + const keyless = fakeViewer(); + keyed.present(keyed.view(nextViewKey())); + const shown = []; + let unsubscribe = subscribePhotoViewers([keyless, keyed], (view) => + shown.push(view), + ); + const mounted = keyless.view(undefined); + keyless.present(mounted); + assert.equal(shown.at(-1), mounted); + await Promise.resolve(); + unsubscribe(); + // A new picker, the keyless viewer first: it is still the later mount. + const again = []; + unsubscribe = subscribePhotoViewers([keyless, keyed], (view) => + again.push(view), + ); + assert.equal(again.at(-1), mounted); + await Promise.resolve(); + assert.equal(keyless.superseded, 0, 'never told it is not drawn'); + assert.ok(keyed.superseded > 0); + unsubscribe(); +}); diff --git a/src/ui/kit/streetLevelPhotoControls.test.mjs b/src/ui/kit/streetLevelPhotoControls.test.mjs index f30f86c6c7..1c65279af4 100644 --- a/src/ui/kit/streetLevelPhotoControls.test.mjs +++ b/src/ui/kit/streetLevelPhotoControls.test.mjs @@ -79,6 +79,13 @@ test('the step buttons are not pressed toggles', () => { * the page: the one place a `.src` is written. */ const LOADER = /^export function loadImage\([\s\S]*?^}$/m; +// An assignment, plain or compound (`=`, `+=`, `||=`, `??=`, `**=`…), not +// a comparison or an arrow. +const ASSIGN = String.raw`\s*(?:[-+*/%&|^]|\*\*|<<|>>>?|&&|\|\||\?\?)?=(?![=>])`; +const assigned = (target, flags = '') => + new RegExp(String.raw`${target}${ASSIGN}`, flags); +// A member or computed member: what a destructuring write must not target. +const MEMBER = /[\w$)\]]\s*(?:\.\s*[\w$]|\[)/; test('the photo viewer is drawn by its view, and its layer needs no Vue', () => { const source = read(VIEWER); @@ -96,19 +103,34 @@ test('the photo viewer is drawn by its view, and its layer needs no Vue', () => /\.remove\(\)/, /\.(?:set|remove|toggle)Attribute(?:NS)?\(/, /\.(?:classList|className|dataset|style)\b/, - /\.(?:hidden|disabled|textContent|innerText|tabIndex|title|alt)\s*=[^=]/, - /\.(?:width|height|ariaLabel|id|value)\s*=[^=]/, + assigned( + String.raw`\.(?:hidden|disabled|textContent|innerText|tabIndex|title|alt)`, + ), + assigned(String.raw`\.(?:width|height|ariaLabel|id|value)`), + // Properties written in bulk or by reflection (an Error's own fields + // aside). + /\bObject\.assign\(\s*(?!new Error\()/, + /\bObject\.definePropert(?:y|ies)\(/, + /\bReflect\.(?:set|defineProperty)\(/, /from 'vue'|\.vue'/, ]) assert.doesNotMatch(source, write); // No property written through brackets (`picture['src'] = …`, - // `el[name] = …`), outside array destructuring declarations. + // `el[name] ||= …`), outside array destructuring declarations. assert.doesNotMatch( source.replace(/\b(?:const|let|var)\s*\[/g, ''), - /[\w$)\]]\s*\[[^[\]]*\]\s*=(?![=>])/, + assigned(String.raw`[\w$)\]]\s*\[[^[\]]*\]`), 'a bracket write', ); - const SRC = /\.src\s*=(?![=>])/g; + // No destructuring write to a property (`[el.src] = …`, + // `({ a: el.id } = …)`); declarations bind names only. + for (const pattern of [ + /(?])/g, + /(?])/g, + ]) + for (const [write, targets] of source.matchAll(pattern)) + assert.doesNotMatch(targets, MEMBER, write); + const SRC = assigned(String.raw`\.src`, '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. @@ -119,17 +141,18 @@ test('the photo viewer is drawn by its view, and its layer needs no Vue', () => 'one binding of image', ); for (const rebinding of [ - /(?])/, + assigned(String.raw`(?/, /\((?:[^()]*[,{[\s(])?image\b[^()]*\)\s*=>/, /\bfunction\b[^(]*\((?:[^)]*[,{[\s(])?image\b[^)]*\)/, /\b(?:const|let|var)\s*[{[][^=]*\bimage\b/, - /\bcatch\s*\(\s*image\b/, + /\bcatch\s*\([^)]*\bimage\b/, ]) assert.doesNotMatch(loader, rebinding, 'image rebound or shadowed'); const writes = loader.match(SRC)?.length ?? 0; assert.equal( - loader.match(/(?])/g)?.length ?? 0, + loader.match(assigned(String.raw`(?