Vue kit: Street Level's photo viewer is a view with kit buttons

The photo viewer KartaView and Panoramax share (photoViewer.js) no longer
builds its root, picture, panorama canvas and ‹ › buttons in script. It
presents them through subscribeView(), which the street-level layer
gathers in subscribePhotoViewer(); the application shell publishes that
to the gev-street-level-photo store, and StreetLevelPhotoViewer, beside
the Street Level panel in the layer panels, teleports the viewer into the
viewer host with the same classes, data attributes, labels and order. Its
‹ and › are ghost UiButtons. The view forwards keys, pointers, wheel, the
step clicks and a lost WebGL context to the viewer and hands each element
back: the canvas the panorama is drawn on (a fresh, keyed one after a lost
context, which an open now waits for), and the frame, picture, root and
buttons the viewer measures and keeps focus with. The viewer keeps every
decision: loading, upgrades, size limits, keys, drag, pinch, zoom, Esc on
the viewer's box and focus when a step button disables. The street-level
layer still needs no Vue; with no view subscribed these photos cannot
mount, which docs/VUE-MIGRATION.md records.

The provider and viewer tests draw the viewer with a fake view in
kartaViewFakes.mjs; StreetLevelPhotoViewer.test.mjs runs the real view on
a page, and streetLevelPhotoControls.test.mjs pins the kit controls. The
panel page's lost-graphics notice in globePanelRuntime.js stays built in
script, as the document now says.

Co-authored-by: Manjunath Paparaju <[email protected]>
This commit is contained in:
Sameh KhamisandManjunath Paparaju committed 2026-11-19 13:33:58 -08:00
1 parent 9423a26487
commit 766364f691
20 files changed
+911 -112

No files matched your search

+36
View File
@@ -703,6 +703,42 @@ export function createStreetLevelLayer({
attachViewerHost(element) {
parts.viewerHost.attach(element);
},
/**
* 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.
* @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();
};
},
setProviderEnabled,
openImage,
/**
+37
View File
@@ -2176,3 +2176,40 @@ test('proceed() is asked after the lookup: false loads nothing and clears the sp
true,
);
});
test('subscribePhotoViewer hands on the photo viewer a provider presents, the latest mount’s while two overlap', async (t) => {
const presenting = (id, pickPrefix) => {
const provider = fakeProvider({ id, pickPrefix });
const create = provider.create;
const listeners = new Set();
provider.present = (view) => {
for (const listener of [...listeners]) listener(view);
};
provider.create = (context) => {
const instance = create(context);
instance.viewer.subscribeView = (listener) => {
listeners.add(listener);
listener(null);
return () => listeners.delete(listener);
};
return instance;
};
return provider;
};
const a = presenting('mapillary', 'mly:');
const b = presenting('other', 'oth:');
const { layer } = await enabledLayer(t, [a, b]);
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' };
a.present(viewA);
b.present(viewB);
a.present(null);
b.present(null);
assert.deepEqual(shown, [null, viewA, viewB, null]);
unsubscribe();
a.present(viewA);
assert.equal(shown.length, 4, 'unsubscribed');
});
+144 -82
View File
@@ -213,6 +213,17 @@ export function panoSizeFor(canvasPixels, fovDeg) {
* or pinch to zoom), and ‹ › to step along the sequence (also ← →). Poses
* follow the view direction.
*
* 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,
* 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.
*
* Photos are normalized by the provider: `{id, sequenceId, lon, lat,
* heading, isPano, capturedAt}` plus whatever its `sources` read.
*
@@ -249,11 +260,18 @@ export function createPhotoViewer({
}) {
const LOAD_FAILED = `The ${name} photo could not be loaded`;
const listeners = new Set();
/** The elements the view handed back. */
let root = null;
let picture = null;
let canvas = null;
let prevButton = null;
let nextButton = null;
/** 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). */
const rootWaiters = new Set();
const canvasWaiters = new Set();
let renderer = null;
/** WebGL failed once: 360° photos show their front view instead. */
let rendererFailed = false;
@@ -265,8 +283,6 @@ export function createPhotoViewer({
let drag = null;
let poseFrame = 0;
let removeListeners = [];
/** The document the viewer was built in (new canvases come from it). */
let documentOf = null;
/** A context loss's look direction, for the reopen of that photo. */
let restoreView = null;
/** The panel's viewer box, where Esc is listened for (null: the root). */
@@ -354,44 +370,62 @@ export function createPhotoViewer({
});
}
/** Present the viewer with `patch` applied (null: nothing to draw). */
function present(patch) {
if (patch === null) presented = null;
else if (presented) presented = { ...presented, ...patch };
else return;
for (const listener of [...viewListeners]) listener(presented);
}
/** Settle everything waiting on the view (it drew, or it went). */
function wake(waiters) {
for (const resolve of waiters) resolve();
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();
return new Promise((resolve) => {
canvasWaiters.add(resolve);
signal?.addEventListener?.('abort', resolve, { once: true });
});
}
function syncButtons() {
const enabled = Boolean(photo?.sequenceId) && showing !== null;
if (prevButton) prevButton.disabled = !enabled;
if (nextButton) nextButton.disabled = !enabled;
present({ prevDisabled: !enabled, nextDisabled: !enabled });
if (enabled) checkEnds(photo);
}
/** Disable ‹ or › at once where the sequence ends (it also warms the neighbours). */
function checkEnds(target) {
for (const [delta, button] of [
[-1, prevButton],
[1, nextButton],
])
for (const delta of [-1, 1])
step(target, delta).then(
(id) => {
if (photo === target && button && !id) disable(button);
if (photo === target && presented && !id) disable(delta);
},
() => {},
);
}
/** Disable a step button, keeping keyboard focus in the viewer. */
function disable(button) {
if (button.ownerDocument?.activeElement === button) root?.focus?.();
button.disabled = true;
function disable(delta) {
const button = delta < 0 ? prevButton : nextButton;
if (button && button.ownerDocument?.activeElement === button)
root?.focus?.();
present(delta < 0 ? { prevDisabled: true } : { nextDisabled: true });
}
function show(kind) {
showing = kind;
if (picture) picture.hidden = kind !== 'flat';
if (canvas) canvas.hidden = kind !== 'pano';
if (root) root.dataset.kind = kind || '';
present({ kind: kind || '' });
syncButtons();
}
function applyRenderMode() {
if (picture)
picture.style.objectFit = renderMode === 'fill' ? 'cover' : 'contain';
present({ fit: renderMode === 'fill' ? 'cover' : 'contain' });
}
function ensureRenderer() {
@@ -410,6 +444,9 @@ export function createPhotoViewer({
* with it: drop the renderer, and show the photo again on a new one.
*/
function onContextLost(event) {
// Only the canvas on screen: a replaced one has nothing left to lose.
const from = event?.currentTarget ?? event?.target;
if (from && from !== canvas) return;
event.preventDefault?.();
const lost = renderer;
renderer = null;
@@ -421,11 +458,10 @@ export function createPhotoViewer({
} catch {
/* already gone */
}
// A lost canvas hands back its lost context: draw on a new element.
const fresh = makeCanvas(documentOf);
fresh.hidden = canvas.hidden;
canvas.replaceWith?.(fresh);
canvas = fresh;
// 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 });
// Show the photo again through the core, unless a newer one is opening.
if (showing === 'pano' && photo && openingId === null) {
const again = photo.id;
@@ -435,20 +471,6 @@ export function createPhotoViewer({
}
}
/** The panorama canvas, wired for drag, pinch, wheel and context loss. */
function makeCanvas(doc) {
const element = doc.createElement('canvas');
element.className = 'sl-photo-pano';
element.hidden = true;
listen(element, 'pointerdown', onPointerDown);
listen(element, 'pointermove', onPointerMove);
listen(element, 'pointerup', onPointerUp);
listen(element, 'pointercancel', onPointerUp);
listen(element, 'wheel', onWheel, { passive: false });
listen(element, 'webglcontextlost', onContextLost);
return element;
}
/**
* Step along the sequence from the photo showing, or from the one on its
* way after an earlier press, and open it through the core.
@@ -469,8 +491,7 @@ export function createPhotoViewer({
// Closed, or another photo was opened meanwhile.
if ((openingId ?? photo?.id) !== fromId) return;
if (!nextId) {
const button = delta < 0 ? prevButton : nextButton;
if (button && photo?.id === fromId) disable(button);
if (presented && photo?.id === fromId) disable(delta);
return;
}
openingId = nextId;
@@ -504,7 +525,7 @@ export function createPhotoViewer({
y: event.clientY,
view: renderer.getView(),
};
canvas.classList.add('sl-photo-dragging');
present({ dragging: true });
}
function onPointerMove(event) {
@@ -532,7 +553,7 @@ export function createPhotoViewer({
if (pointers.size < 2) pinch = null;
if (!drag || event.pointerId !== drag.id) return;
drag = null;
canvas.classList.remove('sl-photo-dragging');
present({ dragging: false });
}
function onWheel(event) {
@@ -603,51 +624,65 @@ export function createPhotoViewer({
);
}
/** The elements the view hands back, by name. */
const ELEMENTS = {
root: (element) => (root = element),
picture: (element) => (picture = element),
canvas: (element) => (canvas = element),
prev: (element) => (prevButton = element),
next: (element) => (nextButton = element),
};
/** Present the viewer in `host`; its view draws it and hands back its elements. */
function build(host) {
const doc = host.ownerDocument;
documentOf = doc;
root = doc.createElement('div');
root.className = 'sl-photo-viewer';
root.dataset.provider = providerId;
root.tabIndex = 0;
root.setAttribute('role', 'group');
root.setAttribute(
'aria-label',
t(
// Events from a view drawn for an earlier mount are not this one's.
const current =
(handler) =>
(...args) => {
if (presented?.actions === actions) handler(...args);
};
const actions = {
attach(name, element) {
if (presented?.actions !== actions || !element) return;
ELEMENTS[name]?.(element);
if (name === 'root') wake(rootWaiters);
if (name === 'canvas') wake(canvasWaiters);
},
keydown: current(onKeyDown),
pointerdown: current(onPointerDown),
pointermove: current(onPointerMove),
pointerup: current(onPointerUp),
wheel: current(onWheel),
contextLost: current(onContextLost),
step: current((delta, event) => {
event?.stopPropagation?.();
stepBy(delta);
}),
};
presented = {
host,
providerId,
label: t(
'{name} photo. ← and → step along the sequence. On a 360° photo, drag or use Shift+← →, ↑ ↓ to look around, and + − to zoom',
{ name },
),
);
picture = doc.createElement('img');
picture.className = 'sl-photo-flat';
picture.alt = t('{name} street-level photo', { name });
picture.draggable = false;
picture.hidden = true;
canvas = makeCanvas(doc);
const nav = (label, glyph, delta) => {
const button = doc.createElement('button');
button.type = 'button';
button.className = `sl-photo-step sl-photo-step-${delta < 0 ? 'prev' : 'next'}`;
button.textContent = glyph;
button.title = label;
button.setAttribute('aria-label', label);
button.disabled = true;
listen(button, 'click', (event) => {
event.stopPropagation();
stepBy(delta);
});
return button;
alt: t('{name} street-level photo', { name }),
kind: undefined,
src: null,
fit: renderMode === 'fill' ? 'cover' : 'contain',
canvasKey: 0,
dragging: false,
prevLabel: t('Previous photo in this sequence (←)'),
prevDisabled: true,
nextLabel: t('Next photo in this sequence (→)'),
nextDisabled: true,
actions,
};
prevButton = nav(t('Previous photo in this sequence (←)'), '‹', -1);
nextButton = nav(t('Next photo in this sequence (→)'), '›', 1);
root.append(picture, canvas, prevButton, nextButton);
host.append(root);
listen(root, 'keydown', onKeyDown);
present({});
// The viewer's box in the panel; without one, the root's own handler
// takes Esc (one listener per element and type).
escapeTarget = host.closest?.('.sl-viewer-wrap') ?? null;
if (escapeTarget) listen(escapeTarget, 'keydown', onEscapeKey);
applyRenderMode();
}
function teardown() {
@@ -655,13 +690,17 @@ export function createPhotoViewer({
pinch = null;
for (const remove of removeListeners) remove();
removeListeners = [];
escapeTarget = null;
if (poseFrame) cancelAnimationFrame(poseFrame);
poseFrame = 0;
drag = null;
renderer?.destroy();
renderer = null;
root?.remove();
// The view takes its elements away.
present(null);
root = picture = canvas = prevButton = nextButton = null;
wake(rootWaiters);
wake(canvasWaiters);
showing = null;
photo = null;
}
@@ -738,7 +777,7 @@ export function createPhotoViewer({
try {
const image = await loadAs(url, { crossOrigin: false, signal });
if (seq !== openSeq || photo !== target || showing !== 'flat') return;
picture.src = image.src;
present({ src: image.src });
sharp.shown = url;
requestRender();
} catch {
@@ -770,7 +809,8 @@ export function createPhotoViewer({
/** The sharp panorama this viewer needs now: 2,048 docked, 4,096 expanded. */
function panoSizeNow() {
const ratio = Math.min(globalThis.devicePixelRatio || 1, 2);
const width = (canvas?.clientWidth || 0) * ratio;
// The canvas fills the frame; until the view shows it, it measures 0.
const width = (canvas?.clientWidth || root?.clientWidth || 0) * ratio;
return panoSizeFor(width, renderer?.getView().fov ?? PANO_FOV_DEFAULT_DEG);
}
@@ -827,7 +867,7 @@ export function createPhotoViewer({
}
if (!image) throw failure || new Error(LOAD_FAILED);
if (seq !== openSeq) return false;
picture.src = image.src;
present({ src: image.src });
flatSharp = { shown: null, loading: null };
photo = target;
show('flat');
@@ -837,6 +877,11 @@ export function createPhotoViewer({
async function openPhoto(id, seq, keepView, signal) {
const target = await getPhoto(id, { signal });
if (seq !== openSeq) return;
// A canvas lost moments ago: the view is drawing its replacement.
if (sources.hasPano(target) && !rendererFailed) {
await canvasReady(signal);
if (seq !== openSeq) return;
}
let shown = false;
if (sources.hasPano(target) && ensureRenderer()) {
try {
@@ -857,10 +902,15 @@ export function createPhotoViewer({
const adapter = {
async mount(host) {
if (!host) throw new Error('Street Level viewer has no host element');
if (root && root.parentNode === host) return;
if (root && presented?.host === host) return;
teardown();
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.
const drawn = new Promise((resolve) => rootWaiters.add(resolve));
build(host);
if (!root) await drawn;
},
/** Resolves once the photo is on screen and its pose was emitted. */
@@ -896,7 +946,7 @@ export function createPhotoViewer({
photo = null;
flatSharp = { shown: null, loading: null };
show(null);
if (picture) picture.removeAttribute('src');
present({ src: null });
renderer?.clear?.();
},
@@ -937,6 +987,18 @@ export function createPhotoViewer({
listeners.add(listener);
return () => listeners.delete(listener);
},
/**
* Receive every presentation of the viewer, starting with the current
* one (null while unmounted).
* @param {(view: ?object) => void} listener
* @returns {() => void} Unsubscribe.
*/
subscribeView(listener) {
viewListeners.add(listener);
listener(presented);
return () => viewListeners.delete(listener);
},
};
return adapter;
}
+65 -9
View File
@@ -56,7 +56,7 @@ function setup() {
pending.get(url).reject(new Error('gone'));
pending.delete(url);
};
return { viewer, loads, images, release, fail, host: fakeHost() };
return { viewer, loads, images, release, fail, host: fakeHost(viewer) };
}
const tick = () => new Promise((resolve) => setTimeout(resolve, 0));
@@ -146,7 +146,7 @@ test('Esc: the docked viewer offers it to the provider first; expanded, it is th
onEscape: () => ++asked > 0,
load: async (url) => ({ src: url }),
});
const host = fakeHost();
const host = fakeHost(viewer);
await viewer.mount(host);
const root = host.children[0];
const press = () => {
@@ -195,7 +195,7 @@ test('a sharp panorama still downloading when another photo opens is aborted', a
});
t.after(() => delete globalThis.devicePixelRatio);
globalThis.devicePixelRatio = 1;
const host = fakeHost();
const host = fakeHost(viewer);
await viewer.mount(host);
parts(host).canvas.clientWidth = 1800;
await viewer.open('a');
@@ -235,7 +235,7 @@ test('a lost WebGL context while the first panorama loads releases its bitmap',
};
},
});
const host = fakeHost();
const host = fakeHost(viewer);
await viewer.mount(host);
const opening = viewer.open('a');
assert.ok(await until(() => land !== null), 'the panorama is loading');
@@ -262,7 +262,7 @@ test('docked, Esc anywhere in the viewer’s box (toolbar, caption) is offered t
onEscape: () => ++asked > 0,
load: async (url) => ({ src: url }),
});
const host = fakeHost();
const host = fakeHost(viewer);
const wrap = fakeHost();
host.closest = (selector) => (selector === '.sl-viewer-wrap' ? wrap : null);
await viewer.mount(host);
@@ -363,7 +363,7 @@ function heldViewer() {
pending.get(url).resolve({ src: url });
pending.delete(url);
};
return { viewer, pending, signals, loads, release, host: fakeHost() };
return { viewer, pending, signals, loads, release, host: fakeHost(viewer) };
}
test('a new open, a close or an unmount stops the downloads of the open before it', async () => {
@@ -439,7 +439,6 @@ test('a resize while another photo opens does not upgrade the photo still shown'
});
test('a panorama is always decoded at a bounded size', async () => {
const env = heldViewer();
const options = [];
const viewer = createPhotoViewer({
providerId: 'test',
@@ -461,7 +460,7 @@ test('a panorama is always decoded at a bounded size', async () => {
destroy() {},
}),
});
await viewer.mount(env.host);
await viewer.mount(fakeHost(viewer));
await viewer.open('a');
// SOURCES' panoFirst names no size: the viewer still bounds it.
assert.deepEqual(options[0].resize, [2048, 1024]);
@@ -549,7 +548,7 @@ test('a browser without :fullscreen / :popover-open (Safari < 16.4) still opens
onEscape: () => ++asked > 0,
load: async (url) => ({ src: url }),
});
const host = fakeHost();
const host = fakeHost(viewer);
await viewer.mount(host);
const root = host.children[0];
// Safari 16.0–16.3: neither pseudo-class parses, so closest() throws.
@@ -571,3 +570,60 @@ test('a browser without :fullscreen / :popover-open (Safari < 16.4) still opens
assert.doesNotThrow(() => root.fire('keydown', event), 'Esc does not throw');
assert.equal(asked, 1, 'Esc reaches the provider');
});
test('a panorama reopened after a lost context waits for the view’s fresh canvas', async () => {
const canvases = [];
const reopened = [];
const viewer = createPhotoViewer({
providerId: 'test',
name: 'Test',
sources: SOURCES,
getPhoto: async (id) => PHOTOS[id],
step: async () => null,
onStep() {},
onReopen: (id) => reopened.push(id),
load: async (url) => ({ src: url }),
createRenderer: (canvas) => {
canvases.push(canvas);
return {
setImage() {},
setView() {},
getView: () => ({ yaw: 0, pitch: 0, fov: 80 }),
resize() {},
clear() {},
destroy() {},
};
},
});
// A view that draws a replacement canvas a while after it is asked.
let shown = null;
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,
});
shown = view;
});
await viewer.mount({});
await viewer.open('a');
assert.equal(shown.kind, 'pano');
shown.actions.contextLost({ preventDefault() {} });
assert.deepEqual(reopened, ['a']);
const opening = viewer.open('a');
await tick();
assert.equal(canvases.length, 1, 'no renderer without a canvas');
late();
await opening;
assert.deepEqual(
canvases.map((canvas) => canvas.name),
['canvas 0', 'canvas 1'],
);
assert.equal(shown.kind, 'pano', 'not the front view');
});
@@ -190,7 +190,7 @@ test('the nearest photo is the closest within 50 m, and opening it asks nothing
});
const id = await instance.nearestImage({ lat: 42.3314, lon: -83.0458 });
assert.equal(id, 'near');
const host = fakeHost();
const host = fakeHost(instance.viewer);
await instance.viewer.mount(host);
await instance.viewer.open(id);
assert.deepEqual(source.calls.photo, [], 'the lookup filled the cache');
@@ -285,7 +285,7 @@ const press = async (button, opened) => {
async function mounted(sourceOptions, contextOptions) {
const env = setup(sourceOptions, contextOptions);
const host = fakeHost();
const host = fakeHost(env.instance.viewer);
await env.instance.viewer.mount(host);
const poses = [];
env.instance.viewer.onPose((pose) => poses.push(pose.imageId));
@@ -970,7 +970,7 @@ test('after a GPU reset the photo is drawn again by the viewer, not through the
context.actions.reportError = (message) => errors.push(message);
const instance = definition.create(context);
actions.instance = instance;
const host = fakeHost();
const host = fakeHost(instance.viewer);
await instance.viewer.mount(host);
const poses = [];
instance.viewer.onPose((pose) => poses.push(pose.imageId));
@@ -1010,7 +1010,7 @@ test('the marker is KartaView’s own cone, and it points along the drive, not a
photos: page.photos.map((record) => ({ ...record, heading: '200' })),
};
};
const host = fakeHost();
const host = fakeHost(env.instance.viewer);
await env.instance.viewer.mount(host);
const bearings = [];
env.instance.viewer.onPose((pose) => bearings.push(pose.bearing));
@@ -1101,7 +1101,7 @@ test('a sequence page that lands while a lost GPU context recovers still draws i
const instance = definition.create(context);
actions.instance = instance;
const cones = await withCones(t, { instance });
const host = fakeHost();
const host = fakeHost(instance.viewer);
await instance.viewer.mount(host);
await instance.viewer.open('p-0');
// › to the next panorama; the GPU resets while it loads.
@@ -148,7 +148,7 @@ function setup({
});
const poses = [];
viewer.onPose((pose) => poses.push(pose));
const host = fakeHost();
const host = fakeHost(viewer);
return {
viewer,
poses,
@@ -498,7 +498,7 @@ test('a WebGL failure only lasts until the viewer is mounted again', async () =>
return renderer;
},
});
const host = fakeHost();
const host = fakeHost(viewer);
await viewer.mount(host);
await viewer.open('pano1');
assert.equal(parts(host).picture.hidden, false, 'front view');
@@ -589,7 +589,7 @@ function heldSetup({ slowSteps = false } = {}) {
});
const poses = [];
viewer.onPose((pose) => poses.push(pose.imageId));
const host = fakeHost();
const host = fakeHost(viewer);
/** Let the load showing `what` (e.g. 'a@1280') finish. */
const release = async (what) => {
assert.ok(
@@ -798,7 +798,7 @@ function heldPanoSetup(held) {
});
const poses = [];
viewer.onPose((pose) => poses.push(pose));
return { viewer, renderers, stepped, poses, host: fakeHost(), release };
return { viewer, renderers, stepped, poses, host: fakeHost(viewer), release };
}
const pano2Preview = Buffer.from(
@@ -284,7 +284,7 @@ async function mounted(sourceOptions, contextOptions) {
const env = setup(sourceOptions, contextOptions);
const poses = [];
env.instance.viewer.onPose((pose) => poses.push(pose.imageId));
const host = fakeHost();
const host = fakeHost(env.instance.viewer);
await env.instance.viewer.mount(host);
const [, , prev, next] = host.children[0].children;
return { ...env, poses, prev, next };
@@ -320,7 +320,7 @@ test('one lookup for a picture asked twice at once', async () => {
await gate;
return getItem(id);
};
const host = fakeHost();
const host = fakeHost(instance.viewer);
await instance.viewer.mount(host);
const first = instance.viewer.open('s-0');
const second = instance.viewer.open('s-0');
@@ -985,7 +985,7 @@ test('after a GPU reset the viewer draws the same picture itself, leaving the co
const { context, actions } = fakeContext();
const instance = definition.create(context);
actions.instance = instance;
const host = fakeHost();
const host = fakeHost(instance.viewer);
await instance.viewer.mount(host);
const poses = [];
instance.viewer.onPose((pose) => poses.push(pose.imageId));
@@ -59,7 +59,7 @@ function setup() {
});
const poses = [];
viewer.onPose((pose) => poses.push(pose));
return { viewer, poses, loads, renderers, stepped, host: fakeHost() };
return { viewer, poses, loads, renderers, stepped, host: fakeHost(viewer) };
}
const parts = (host) => {
@@ -252,7 +252,7 @@ test('without WebGL a 360° picture shows its whole equirectangular image flat',
throw new Error('no WebGL');
},
});
const host = fakeHost();
const host = fakeHost(viewer);
await viewer.mount(host);
await viewer.open('pano');
const { picture } = parts(host);
@@ -272,7 +272,7 @@ test('a picture whose SD fails falls back to the thumbnail; the original only fo
return { src: url };
},
});
const host = fakeHost();
const host = fakeHost(viewer);
await viewer.mount(host);
await viewer.open('flat');
assert.deepEqual(tried, [PHOTOS.flat.urls.sd, PHOTOS.flat.urls.thumb]);
@@ -326,7 +326,7 @@ test('an SD panorama refused for its size is not fetched again as a flat photo',
destroy() {},
}),
});
const host = fakeHost();
const host = fakeHost(viewer);
await viewer.mount(host);
await viewer.open('pano');
const sdLoads = loads.filter((l) => l.url === PHOTOS.pano.urls.sd);
+3
View File
@@ -63,6 +63,9 @@ export function filtersOf(provider) {
* @property {(mode: 'letterbox'|'fill') => void} [setRenderMode]
* @property {() => boolean} [supportsRenderModes] False while the image has no frame to fit (a panorama): FIT / FILL hide.
* @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).
*
* @typedef {object} StreetPose
* @property {string} providerId
+102 -3
View File
@@ -60,13 +60,112 @@ function fakeElement(tag) {
return element;
}
export function fakeHost() {
const doc = { createElement: (tag) => fakeElement(tag) };
/**
* A host element; given a photo viewer, its view is drawn as
* StreetLevelPhotoViewer draws it (see `drawPhotoViewer`).
*/
export function fakeHost(viewer = null) {
const host = fakeElement('div');
host.ownerDocument = doc;
if (viewer) drawPhotoViewer(viewer);
return host;
}
/**
* 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.
* @returns {() => void} Stop drawing.
*/
export function drawPhotoViewer(viewer) {
let parts = null;
let last = null;
const on = (element, type, name) =>
element.addEventListener(type, (event) => last?.actions[name](event));
const canvasFor = () => {
const canvas = fakeElement('canvas');
canvas.classList.add('sl-photo-pano');
for (const type of ['pointerdown', 'pointermove', 'pointerup', 'wheel'])
on(canvas, type, type);
on(canvas, 'pointercancel', 'pointerup');
on(canvas, 'webglcontextlost', 'contextLost');
return canvas;
};
const build = (view) => {
const root = fakeElement('div');
const picture = fakeElement('img');
const canvas = canvasFor();
const button = (delta) => {
const element = fakeElement('button');
element.addEventListener('click', (event) =>
last?.actions.step(delta, event),
);
return element;
};
const prev = button(-1);
const next = button(1);
on(root, 'keydown', 'keydown');
root.append(picture, canvas, prev, next);
view.host.append(root);
return { root, picture, canvas, prev, next };
};
const changed = (view, key) => !last || last[key] !== view[key];
return viewer.subscribeView((view) => {
if (!view) {
parts?.root.remove();
parts = last = null;
return;
}
const fresh = !parts || last.host !== view.host;
if (fresh) {
parts?.root.remove();
parts = build(view);
last = null;
}
const { root, picture, prev, next } = parts;
if (!fresh && changed(view, 'canvasKey')) {
const canvas = canvasFor();
parts.canvas.replaceWith(canvas);
parts.canvas = canvas;
parts.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)
root.dataset.kind = view.kind;
if (changed(view, 'alt')) picture.alt = view.alt;
if (changed(view, '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 (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;
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);
});
}
/**
* Wait, a macrotask at a time, until `condition` holds; false if it never
* does within `ticks`. A test asserting that something did not happen waits
+15
View File
@@ -65,6 +65,7 @@ import { useContextStore } from './stores/context.js';
import { useSpaceMissionsStore } from './stores/spaceMissions.js';
import { SpaceMissionsControls } from './spaceMissionsControls.js';
import { useMissionReplayStore } from './stores/missionReplay.js';
import { useStreetLevelPhotoStore } from './stores/streetLevelPhoto.js';
import { useCelestialRingStore } from './stores/celestialRing.js';
import { icrfToFixedAxes } from '../sky/icrf.js';
import { useWorldOverlayActionsStore } from './stores/worldOverlayActions.js';
@@ -1200,7 +1201,18 @@ export class StyleManager extends ShellFacade {
const { streetLevelLayer } = this.services;
this._streetLevelControls?.destroy();
this._streetLevelControls = null;
// The photo viewer (KartaView, Panoramax), which the layer panels draw
// into the viewer host. A viewer left by an earlier shell must
// not outlive its layer.
const streetLevelPhotoStore = useStreetLevelPhotoStore(applicationPinia());
this._streetLevelPhotoUnsubscribe?.();
this._streetLevelPhotoUnsubscribe = null;
streetLevelPhotoStore.publish(null);
if (!this._streetLevelPanel || !streetLevelLayer) return;
this._streetLevelPhotoUnsubscribe =
streetLevelLayer.subscribePhotoViewer?.((view) =>
streetLevelPhotoStore.publish(view),
) ?? null;
// Photo framing yields to newer navigation and releases tracking like
// any deferred flight.
streetLevelLayer.attachNavigation?.({
@@ -1969,7 +1981,10 @@ export class StyleManager extends ShellFacade {
this._spaceMissionsControls = null;
this._missionReplayUnsubscribe?.();
this._missionReplayUnsubscribe = null;
this._streetLevelPhotoUnsubscribe?.();
this._streetLevelPhotoUnsubscribe = null;
useMissionReplayStore(applicationPinia()).publish(null);
useStreetLevelPhotoStore(applicationPinia()).publish(null);
const contextStore = useContextStore(applicationPinia());
contextStore.connectAwareness(null);
contextStore.publishAwareness(null);
@@ -0,0 +1,106 @@
// The Street Level photo viewer (KartaView, Panoramax) is a view with kit
// controls: StreetLevelPhotoViewer draws what the photo viewer presents and
// hand-writes no <button> and no Material Symbols span; its ‹ › are ghost
// UiButtons, not pressed toggles, whose glyphs are text characters. The
// photo viewer builds no element of its own, and the street-level layer it
// belongs to needs no Vue: the application shell publishes its
// presentation to the store the view renders.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
const read = (file) =>
readFileSync(new URL(`../../${file}`, import.meta.url), 'utf8');
/** The template block: everything outside script, style and comments. */
const template = (file) =>
read(file)
.replace(/<(script|style)\b[\s\S]*?<\/\1\s*>/g, '')
.replace(/<!--[\s\S]*?-->/g, '');
// An opening tag's attributes, quoted values may hold `>` (`() => x`).
const ATTRS = String.raw`(?:[^>"']|"[^"]*"|'[^']*')*`;
const tags = (markup, name) =>
markup.match(new RegExp(String.raw`<${name}\b${ATTRS}>`, 'g')) ?? [];
// An attribute's name, outside the quoted values.
const names = (attrs) => attrs.replace(/"[^"]*"|'[^']*'/g, '""');
const VIEW = 'ui/views/panels/StreetLevelPhotoViewer.vue';
const VIEWER = 'layers/streetLevel/photoViewer.js';
test('the photo viewer hand-writes no button; ‹ and › are kit buttons', () => {
const markup = template(VIEW);
assert.deepEqual(markup.match(/<button\b/gi) ?? [], [], VIEW);
assert.deepEqual(markup.match(/<(select|input)\b/gi) ?? [], [], VIEW);
const buttons = tags(markup, 'UiButton');
assert.equal(buttons.length, 2);
assert.equal(tags(markup, 'UiCloseButton').length, 0);
// Ghost buttons with the classes street-level.css styles.
for (const [button, side] of [
[buttons[0], 'prev'],
[buttons[1], 'next'],
]) {
assert.doesNotMatch(button, /\svariant=/);
assert.match(
button,
new RegExp(`\\sclass="sl-photo-step sl-photo-step-${side}"`),
);
}
});
test('the photo viewer hand-writes no Material glyph', () => {
const markup = template(VIEW);
assert.deepEqual(markup.match(/material-symbols/g) ?? [], [], VIEW);
assert.equal(tags(markup, 'UiIcon').length, 0);
// ‹ and › are text characters.
assert.match(markup, />‹<\/UiButton\s*>/);
assert.match(markup, />›<\/UiButton\s*>/);
});
test('the step buttons are not pressed toggles', () => {
const markup = template(VIEW);
for (const [tag, attrs] of markup.matchAll(
new RegExp(String.raw`<[A-Za-z][\w-]*\b(${ATTRS})>`, 'g'),
)) {
assert.doesNotMatch(
names(attrs),
/(?:^|\s)(?::|v-bind:)?aria-pressed(?=[\s=/]|$)/,
tag,
);
assert.doesNotMatch(
attrs,
/(?:^|\s)(?:v-bind|:)=(?:"[^"]*aria-?pressed[^"]*"|'[^']*aria-?pressed[^']*')/i,
tag,
);
assert.doesNotMatch(names(attrs), /(?:^|\s)(?::|v-bind:)?pressed\b/, tag);
}
});
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'/,
);
const markup = template(VIEW);
const opening = (name, attribute) =>
new RegExp(String.raw`<${name}\b${ATTRS}\s${attribute}${ATTRS}>`);
for (const part of [
opening('div', 'class="sl-photo-viewer"'),
opening('img', 'class="sl-photo-flat"'),
opening('canvas', ':key="photo.canvasKey"'),
opening('canvas', 'class="sl-photo-pano"'),
])
assert.match(markup, part);
const groups = JSON.parse(
readFileSync(
new URL('../../../scripts/package-boundaries.json', import.meta.url),
'utf8',
),
);
const layer = groups['street-level-layer'];
assert.ok(layer.modules.includes(`src/${VIEWER}`));
assert.equal(layer.external.includes('vue'), false);
assert.equal(
layer.modules.some((module) => module.endsWith('.vue')),
false,
);
});
+26
View File
@@ -0,0 +1,26 @@
import { defineStore } from 'pinia';
import { markRaw, shallowRef } from 'vue';
/**
* The Street Level photo viewer (KartaView, Panoramax) as its view renders
* it. The street-level layer presents it through `subscribePhotoViewer()`
* and the application shell publishes each presentation here.
*/
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.
*/
const photo = shallowRef(null);
/** @param {?object} next A fresh presentation; every publish re-renders. */
function publish(next) {
photo.value = next && markRaw(next);
}
return { photo, publish };
},
);
+2
View File
@@ -12,6 +12,7 @@ import SceneOptions from './SceneOptions.vue';
import SceneShotList from './SceneShotList.vue';
import CctvPanel from './panels/CctvPanel.vue';
import StreetLevelPanel from './panels/StreetLevelPanel.vue';
import StreetLevelPhotoViewer from './panels/StreetLevelPhotoViewer.vue';
import DrawControls from './panels/DrawControls.vue';
import GeoImport from './panels/GeoImport.vue';
import UiSelect from '../kit/UiSelect.js';
@@ -71,6 +72,7 @@ async function importChosen(event) {
<!-- Street Level Panel (moved into #right-context-rail at runtime) -->
<StreetLevelPanel />
<StreetLevelPhotoViewer />
<!-- Scene Director Panel -->
<RailPanel id="scene-panel" start-collapsed v-class-toggle="{ running: scene?.running, 'has-shots': scene?.hasShots }" :title="t('AUTHORING')" :hint="t('Create and edit scenes')" scroll>
@@ -0,0 +1,248 @@
// The Street Level photo viewer (KartaView, Panoramax) on a page: the photo
// viewer presents it, the store carries it, and StreetLevelPhotoViewer draws
// it into the viewer host, forwards its events and hands its elements back.
import '../../../testSupport/registerDom.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import { createApp, nextTick } from 'vue';
import { createPinia } from 'pinia';
import { createPhotoViewer } from '../../../layers/streetLevel/photoViewer.js';
import { useStreetLevelPhotoStore } from '../../stores/streetLevelPhoto.js';
import StreetLevelPhotoViewer from './StreetLevelPhotoViewer.vue';
const PHOTOS = {
f: { id: 'f', sequenceId: 's', lon: 1, lat: 2, heading: 0, isPano: false },
g: { id: 'g', sequenceId: 's', lon: 1, lat: 2, heading: 0, isPano: false },
p: { id: 'p', sequenceId: 's', lon: 1, lat: 2, heading: 0, isPano: true },
};
const SOURCES = {
hasPano: (photo) => photo.isPano,
panoFirst: (photo) => ({ url: `${photo.id}-pano`, width: 2048 }),
panoSharp: () => null,
flatFirst: (photo) => [`https://photos.test/${photo.id}.jpg`],
flatSharp: () => null,
describe: () => ({ externalUrl: 'https://example.org' }),
};
/** The view in an app, a viewer published to its store, and a panel host. */
function mount(t, options = {}) {
document.body.replaceChildren();
const wrap = document.body.appendChild(document.createElement('div'));
wrap.className = 'sl-viewer-wrap';
const host = wrap.appendChild(document.createElement('div'));
host.id = 'sl-viewer';
const pinia = createPinia();
const app = createApp(StreetLevelPhotoViewer).use(pinia);
app.mount(document.body.appendChild(document.createElement('div')));
const store = useStreetLevelPhotoStore(pinia);
const renderers = [];
const stepped = [];
const viewer = createPhotoViewer({
providerId: 'panoramax',
name: 'Panoramax',
sources: SOURCES,
getPhoto: async (id) => PHOTOS[id],
// f, then g: the whole sequence.
step: async (photo, delta) =>
({ f: { 1: 'g' }, g: { '-1': 'f' } })[photo.id]?.[delta] ?? null,
onStep: (id) => stepped.push(id),
load: async (url) => ({ src: url }),
createRenderer: (canvas) => {
const view = { yaw: 0, pitch: 0, fov: 80 };
const renderer = {
canvas,
setImage() {},
setView: (next) => Object.assign(view, next),
getView: () => ({ ...view }),
resize() {},
clear() {},
destroy() {},
};
renderers.push(renderer);
return renderer;
},
...options,
});
const unsubscribe = viewer.subscribeView((view) => store.publish(view));
t.after(() => {
viewer.unmount();
unsubscribe();
app.unmount();
});
return { viewer, host, wrap, renderers, stepped };
}
const tick = () => new Promise((resolve) => setTimeout(resolve, 0));
test('the viewer draws in its host with the markup its stylesheet reads', async (t) => {
const { viewer, host } = mount(t);
await viewer.mount(host);
const root = host.querySelector(':scope > .sl-photo-viewer');
assert.ok(root, 'drawn in the host');
assert.equal(root.dataset.provider, 'panoramax');
assert.equal(root.getAttribute('tabindex'), '0');
assert.equal(root.getAttribute('role'), 'group');
assert.match(root.getAttribute('aria-label'), /^Panoramax photo\. ← and →/);
assert.equal(root.hasAttribute('data-kind'), false, 'nothing shown yet');
const [picture, canvas, prev, next] = root.children;
assert.equal(picture.tagName, 'IMG');
assert.equal(picture.className, 'sl-photo-flat');
assert.equal(picture.getAttribute('alt'), 'Panoramax street-level photo');
assert.equal(picture.getAttribute('draggable'), 'false');
assert.equal(picture.hidden, true);
assert.equal(picture.hasAttribute('src'), false);
assert.equal(picture.style.objectFit, 'contain');
assert.equal(canvas.tagName, 'CANVAS');
assert.equal(canvas.className, 'sl-photo-pano');
assert.equal(canvas.hidden, true);
for (const [button, side, glyph, label] of [
[prev, 'prev', '‹', 'Previous photo in this sequence (←)'],
[next, 'next', '›', 'Next photo in this sequence (→)'],
]) {
assert.equal(button.tagName, 'BUTTON');
assert.equal(button.type, 'button');
assert.ok(button.classList.contains('sl-photo-step'));
assert.ok(button.classList.contains(`sl-photo-step-${side}`));
assert.equal(button.textContent.trim(), glyph);
assert.equal(button.getAttribute('aria-label'), label);
assert.equal(button.getAttribute('title'), label);
assert.equal(button.disabled, true);
assert.equal(button.hasAttribute('aria-pressed'), false);
}
viewer.setRenderMode('fill');
await nextTick();
assert.equal(picture.style.objectFit, 'cover');
viewer.unmount();
await nextTick();
assert.equal(host.children.length, 0, 'unmounted: gone from the host');
});
test('a flat photo shows, ‹ › and ← → step along its sequence, and close hides it', async (t) => {
const { viewer, host, stepped } = mount(t);
await viewer.mount(host);
await viewer.open('f');
await nextTick();
const root = host.querySelector('.sl-photo-viewer');
const [picture, canvas, prev, next] = root.children;
assert.equal(root.dataset.kind, 'flat');
assert.equal(picture.hidden, false);
assert.equal(canvas.hidden, true);
assert.equal(picture.getAttribute('src'), 'https://photos.test/f.jpg');
// ‹ is disabled once its end is known; › stays.
await tick();
await nextTick();
assert.equal(prev.disabled, true);
assert.equal(next.disabled, false);
let bubbled = 0;
host.addEventListener('click', () => bubbled++);
next.click();
await tick();
assert.deepEqual(stepped, ['g']);
assert.equal(bubbled, 0, 'the click stays in the viewer');
await viewer.open('g');
root.dispatchEvent(
new KeyboardEvent('keydown', { key: 'ArrowLeft', bubbles: true }),
);
await tick();
assert.deepEqual(stepped, ['g', 'f']);
viewer.close();
await nextTick();
assert.equal(root.dataset.kind, '');
assert.equal(picture.hidden, true);
assert.equal(picture.hasAttribute('src'), false);
});
test('a step button that disables under the keyboard hands focus to the viewer', async (t) => {
// The sequence's end is known only once the user is on ›.
let answer;
const asked = new Promise((resolve) => (answer = resolve));
const { viewer, host } = mount(t, {
step: async (photo, delta) => (delta > 0 ? asked : null),
});
await viewer.mount(host);
await viewer.open('g');
await nextTick();
const root = host.querySelector('.sl-photo-viewer');
const next = root.children[3];
assert.equal(next.disabled, false);
next.focus();
assert.ok(document.activeElement === next, 'on ›');
answer(null);
await tick();
await nextTick();
assert.equal(next.disabled, true, 'g is the last photo');
assert.ok(document.activeElement === root, 'focus moved to the viewer');
});
test('a panorama draws on the view’s canvas; drag, wheel and a lost context reach the viewer', async (t) => {
const { viewer, host, renderers } = mount(t);
await viewer.mount(host);
await viewer.open('p');
await nextTick();
const root = host.querySelector('.sl-photo-viewer');
const canvas = root.children[1];
assert.ok(renderers[0].canvas === canvas, 'the canvas the view drew');
assert.equal(root.dataset.kind, 'pano');
assert.equal(canvas.hidden, false);
assert.equal(root.children[0].hidden, true);
canvas.dispatchEvent(
new PointerEvent('pointerdown', {
pointerId: 1,
pointerType: 'mouse',
button: 0,
clientX: 0,
clientY: 0,
}),
);
await nextTick();
assert.ok(canvas.classList.contains('sl-photo-dragging'));
canvas.dispatchEvent(new PointerEvent('pointerup', { pointerId: 1 }));
await nextTick();
assert.equal(canvas.classList.contains('sl-photo-dragging'), false);
const wheel = new WheelEvent('wheel', { deltaY: 100, cancelable: true });
canvas.dispatchEvent(wheel);
assert.equal(wheel.defaultPrevented, true, 'the page does not scroll');
assert.ok(renderers[0].getView().fov > 80, 'zoomed out');
// A lost context: a fresh canvas in its place, which the next renderer takes.
canvas.dispatchEvent(new Event('webglcontextlost', { cancelable: true }));
await nextTick();
const fresh = root.children[1];
assert.ok(fresh !== canvas, 'a new canvas');
assert.equal(fresh.className, 'sl-photo-pano');
assert.equal(canvas.isConnected, false, 'the lost one is gone');
await viewer.open('p');
assert.ok(renderers[1].canvas === fresh, 'the next renderer takes it');
});
test('docked, Esc in the viewer’s box is offered to the provider first', async (t) => {
let asked = 0;
const { viewer, host } = mount(t, { onEscape: () => ++asked > 0 });
await viewer.mount(host);
const root = host.querySelector('.sl-photo-viewer');
const escape = new KeyboardEvent('keydown', {
key: 'Escape',
bubbles: true,
cancelable: true,
});
let reachedPage = false;
document.body.addEventListener('keydown', () => (reachedPage = true));
root.dispatchEvent(escape);
assert.equal(asked, 1);
assert.equal(escape.defaultPrevented, true);
assert.equal(reachedPage, false, 'the panel does not collapse');
});
test('without a view, the viewer cannot mount', async () => {
const viewer = createPhotoViewer({
providerId: 'test',
name: 'Test',
sources: SOURCES,
getPhoto: async (id) => PHOTOS[id],
step: async () => null,
onStep() {},
});
await assert.rejects(
viewer.mount(document.createElement('div')),
/no view to draw it/,
);
});
@@ -0,0 +1,78 @@
<script setup>
import { storeToRefs } from 'pinia';
import UiButton from '../../kit/UiButton.vue';
import { useStreetLevelPhotoStore } from '../../stores/streetLevelPhoto.js';
// The Street Level photo viewer of the providers whose photos are plain
// files (KartaView, Panoramax), in the viewer host the layer mounts it in.
// The viewer (src/layers/streetLevel/photoViewer.js) keeps every decision:
// 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.
const { photo } = storeToRefs(useStreetLevelPhotoStore());
/** Hand `name`'s element back to the viewer that presented it. */
const keep = (name) => (element) => {
if (element) photo.value?.actions.attach(name, element.$el ?? element);
};
// One function per element: a new one on each render would hand it back
// again each time.
const refs = {
root: keep('root'),
picture: keep('picture'),
canvas: keep('canvas'),
prev: keep('prev'),
next: keep('next'),
};
</script>
<template>
<Teleport v-if="photo" :to="photo.host"
><div
:ref="refs.root"
class="sl-photo-viewer"
:data-provider="photo.providerId"
tabindex="0"
role="group"
:aria-label="photo.label"
:data-kind="photo.kind"
@keydown="photo.actions.keydown"
><img
:ref="refs.picture"
class="sl-photo-flat"
:alt="photo.alt"
draggable="false"
:hidden="photo.kind !== 'flat'"
:src="photo.src ?? undefined"
:style="{ objectFit: photo.fit }" /><canvas
:key="photo.canvasKey"
:ref="refs.canvas"
class="sl-photo-pano"
:class="{ 'sl-photo-dragging': photo.dragging }"
:hidden="photo.kind !== 'pano'"
@pointerdown="photo.actions.pointerdown"
@pointermove="photo.actions.pointermove"
@pointerup="photo.actions.pointerup"
@pointercancel="photo.actions.pointerup"
@wheel="photo.actions.wheel"
@webglcontextlost="photo.actions.contextLost"
></canvas
><UiButton
:ref="refs.prev"
class="sl-photo-step sl-photo-step-prev"
:label="photo.prevLabel"
:disabled="photo.prevDisabled"
@click="photo.actions.step(-1, $event)"
>‹</UiButton
><UiButton
:ref="refs.next"
class="sl-photo-step sl-photo-step-next"
:label="photo.nextLabel"
:disabled="photo.nextDisabled"
@click="photo.actions.step(1, $event)"
>›</UiButton
></div
></Teleport
>
</template>