refactor(street-level): simpler panel — native fullscreen, no FOLLOW button, no provider chips

EXPAND now uses the browser's Fullscreen API on the viewer element, which
stays in the panel; the hand-built modal (re-parenting to <body>, inert
siblings, focus trap, document-level Esc/Tab, Clean View/recording/cockpit
hide rules) is gone. The button is hidden where the API is missing.

The FOLLOW button and the PROVIDERS chip row are removed. The header pill is
the only layer switch and re-enables a provider switched off elsewhere; under
KEY REQUIRED the error line says which key to add. Chip colour support in
chipGroup, dead CSS and tests pinning the removed behaviour go with them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
German KhokhlovandClaude Opus 5.5 committed 2026-10-07 21:50:11 +04:00
1 parent fbbc4cda5c
commit 7dec7883aa
17 files changed
+285 -1444

No files matched your search

+140 -569
View File
@@ -16,20 +16,6 @@ import { fakeStreetLevelProvider } from '../testSupport/streetLevelFakes.mjs';
/** Every write a page would see as a mutation, even one to the same value. */
const mutations = { count: 0 };
const REFLECTED = ['hidden', 'disabled', 'textContent', 'title', 'value'];
/** The reflected properties a MutationObserver sees, as the record it gets. */
const REFLECTED_RECORDS = {
hidden: { type: 'attributes', attributeName: 'hidden' },
disabled: { type: 'attributes', attributeName: 'disabled' },
title: { type: 'attributes', attributeName: 'title' },
textContent: { type: 'childList' },
};
const liveObservers = new Set();
function recordMutation(target, { type, attributeName = null }) {
for (const observer of liveObservers)
observer.consider(target, type, attributeName);
}
class FakeNode {
constructor(document, tag, { id = null, dataset = {}, classes = [] } = {}) {
@@ -53,42 +39,20 @@ class FakeNode {
set: (value) => {
mutations.count++;
this.props[key] = value;
if (REFLECTED_RECORDS[key])
recordMutation(this, REFLECTED_RECORDS[key]);
},
});
this.attributes = new Map();
const names = new Set(classes);
// Every DOMTokenList write sets the class attribute, changed or not.
const classChanged = () =>
recordMutation(this, { type: 'attributes', attributeName: 'class' });
this.classList = {
add: (name) => {
names.add(name);
classChanged();
},
remove: (name) => {
names.delete(name);
classChanged();
},
contains: (name) => names.has(name),
toggle: (name, force) => {
const on = force ?? !names.has(name);
if (on) names.add(name);
else names.delete(name);
classChanged();
return on;
},
};
const style = {};
this.style = Object.assign(style, {
setProperty: (key, value) => {
style[key] = value;
},
removeProperty: (key) => {
delete style[key];
},
});
this.style = {};
Object.defineProperty(this, 'className', {
get: () => [...names].join(' '),
set: (value) => {
@@ -96,92 +60,39 @@ class FakeNode {
names.clear();
for (const name of String(value).split(/\s+/).filter(Boolean))
names.add(name);
classChanged();
},
});
}
get childElementCount() {
return this.children.length;
}
get parentNode() {
return this.parent;
}
get nextSibling() {
if (!this.parent) return null;
const siblings = this.parent.children;
return siblings[siblings.indexOf(this) + 1] || null;
}
/** Null when this node or an ancestor is hidden or disconnected. */
get offsetParent() {
if (!this.isConnected) return null;
for (let node = this; node; node = node.parent)
if (node.hidden) return null;
return this.parent;
}
setAttribute(key, value) {
mutations.count++;
this.attributes.set(key, String(value));
recordMutation(this, { type: 'attributes', attributeName: key });
}
getAttribute(key) {
return this.attributes.get(key) ?? null;
}
removeAttribute(key) {
if (!this.attributes.delete(key)) return;
mutations.count++;
recordMutation(this, { type: 'attributes', attributeName: key });
}
appendChild(child) {
return this.insertBefore(child, null);
}
/** Like the DOM's: a reference that is not a child throws NotFoundError. */
insertBefore(child, reference) {
if (reference != null && reference.parent !== this)
throw new DOMException('not a child of this node', 'NotFoundError');
if (reference === child) return child;
child.remove();
const index = reference
? this.children.indexOf(reference)
: this.children.length;
this.children.splice(index, 0, child);
child.parent = this;
recordMutation(this, { type: 'childList' });
this.children.push(child);
return child;
}
append(...nodes) {
for (const node of nodes) this.appendChild(node);
}
replaceChildren(...nodes) {
for (const child of [...this.children]) child.remove();
this.children = [];
this.append(...nodes);
}
remove() {
const parent = this.parent;
if (!parent) return;
parent.children.splice(parent.children.indexOf(this), 1);
this.parent = null;
recordMutation(parent, { type: 'childList' });
}
contains(node) {
for (let current = node; current; current = current.parent)
if (current === this) return true;
return false;
}
get isConnected() {
return this.ownerDocument?.contains(this) === true;
}
focus() {
this.ownerDocument.activeElement = this;
}
/** `.class` or `#id`. */
closest(selector) {
const byId = /^#(.+)$/.exec(selector);
const name = selector.replace(/^\./, '');
for (let node = this; node; node = node.parent)
if (byId ? node.id === byId[1] : node.classList?.contains(name))
return node;
return null;
}
*walk() {
for (const child of this.children) {
yield child;
@@ -191,79 +102,40 @@ class FakeNode {
querySelector(selector) {
return this.querySelectorAll(selector)[0] || null;
}
/** `#id`, `[data-x]`, and the tag / attribute forms of a focusable list. */
/** `#id`, `.class` or `[data-x]`. */
matches(selector) {
return selector.split(',').some((part) => {
const one = part.trim();
const byId = /^#(.+)$/.exec(one);
if (byId) return this.id === byId[1];
const byData = /^\[data-([a-z-]+)\]$/.exec(one);
if (byData)
return (
byData[1].replace(/-([a-z])/g, (_, c) => c.toUpperCase()) in
this.dataset
);
if (one === '[tabindex]:not([tabindex="-1"])')
return ![null, '-1'].includes(this.getAttribute('tabindex'));
const byTag = /^([a-z]+)(\[href\])?(:not\(\[disabled\]\))?$/.exec(one);
if (!byTag || this.tagName !== byTag[1].toUpperCase()) return false;
if (byTag[2] && this.getAttribute('href') === null) return false;
return !(byTag[3] && this.disabled);
});
const byId = /^#(.+)$/.exec(selector);
if (byId) return this.id === byId[1];
const byClass = /^\.(.+)$/.exec(selector);
if (byClass) return this.classList.contains(byClass[1]);
const byData = /^\[data-([a-z-]+)\]$/.exec(selector);
return Boolean(
byData &&
byData[1].replace(/-([a-z])/g, (_, c) => c.toUpperCase()) in this.dataset,
);
}
querySelectorAll(selector) {
return [...this.walk()].filter((node) => node.matches(selector));
}
addEventListener(type, listener, { signal, capture = false } = {}) {
addEventListener(type, listener, { signal } = {}) {
if (signal?.aborted) return;
if (!this.listeners.has(type)) this.listeners.set(type, new Map());
this.listeners.get(type).set(listener, capture);
if (!this.listeners.has(type)) this.listeners.set(type, new Set());
this.listeners.get(type).add(listener);
signal?.addEventListener('abort', () =>
this.listeners.get(type)?.delete(listener),
);
}
removeEventListener(type, listener) {
this.listeners.get(type)?.delete(listener);
}
/**
* Capture down from the document, then deliver to this node and bubble
* back up with the same target; `stopPropagation` ends the trip.
*/
/** Deliver to this node, then bubble up with the same target. */
dispatchEvent(event) {
let stopped = false;
const delivered = {
type: event.type,
target: this,
bubbles: event.bubbles,
key: event.key,
shiftKey: event.shiftKey === true,
defaultPrevented: false,
preventDefault() {
this.defaultPrevented = true;
},
stopPropagation() {
stopped = true;
},
preventDefault() {},
};
const path = [];
for (let node = this; node; node = node.parent) path.push(node);
const run = (node, phase) => {
for (const [listener, capture] of [
...(node.listeners.get(event.type) || []),
])
if (phase === 'target' || capture === (phase === 'capture'))
listener(delivered);
};
for (const node of path.slice(1).reverse()) {
run(node, 'capture');
if (stopped) return true;
}
run(this, 'target');
if (!delivered.bubbles) return true;
for (const node of path.slice(1)) {
if (stopped) return true;
run(node, 'bubble');
}
for (let node = this; node; node = event.bubbles ? node.parent : null)
for (const listener of [...(node.listeners.get(event.type) || [])])
listener(delivered);
return true;
}
click() {
@@ -271,14 +143,24 @@ class FakeNode {
}
}
/** The Street Level panel's body, as layer-panels.html lays it out. */
function panelDom() {
/**
* The Street Level panel's body, as layer-panels.html lays it out, on a page
* with the Fullscreen API unless `fullscreen` is false.
*/
function panelDom({ fullscreen = true } = {}) {
const document = new FakeNode(null, '#document');
Object.assign(document, {
ownerDocument: document,
activeElement: null,
fullscreenElement: null,
createElement: (tag) => new FakeNode(document, tag),
});
// The browser reports a change after the request settles.
const fullscreenTo = (element) => {
document.fullscreenElement = element;
setTimeout(() => document.dispatchEvent({ type: 'fullscreenchange' }), 0);
};
document.exitFullscreen = async () => fullscreenTo(null);
document.body = document.appendChild(new FakeNode(document, 'body'));
const root = document.body.appendChild(
new FakeNode(document, 'section', { id: 'street-level-panel' }),
@@ -286,14 +168,14 @@ function panelDom() {
const add = (parent, tag, options) =>
parent.appendChild(new FakeNode(document, tag, options));
add(root, 'button', { id: 'sl-status' });
const main = add(root, 'div', { classes: ['sl-main'] });
// The viewer's own tool bar lives inside the wrap, as in the markup.
const wrap = add(main, 'div', { id: 'sl-viewer-wrap' });
add(wrap, 'button', { id: 'sl-viewer-expand' });
const wrap = add(root, 'div', { id: 'sl-viewer-wrap' });
if (fullscreen) wrap.requestFullscreen = async () => fullscreenTo(wrap);
const expand = add(wrap, 'button', { id: 'sl-viewer-expand' });
add(expand, 'span', { classes: ['sl-btn-icon'] });
add(expand, 'span', { classes: ['sl-btn-text'] });
for (const mode of ['letterbox', 'fill'])
add(wrap, 'button', { dataset: { slRender: mode } });
for (const id of ['sl-follow-btn', 'sl-viewer-close'])
add(wrap, 'button', { id });
add(wrap, 'button', { id: 'sl-viewer-close' });
for (const id of [
'sl-viewer-placeholder',
'sl-viewer',
@@ -302,35 +184,25 @@ function panelDom() {
'sl-image-link',
])
add(wrap, id === 'sl-image-link' ? 'a' : 'div', { id });
const settings = add(main, 'div', { classes: ['sl-settings'] });
for (const id of ['sl-provider-chips', 'sl-error', 'sl-error-text'])
add(settings, 'div', { id });
// A missing key gates the filters only; the chips stay outside the gate.
const controls = add(settings, 'fieldset', { id: 'sl-controls' });
const error = add(root, 'div', { id: 'sl-error' });
add(error, 'span', { id: 'sl-error-text' });
const controls = add(root, 'fieldset', { id: 'sl-controls' });
for (const pano of ['all', 'pano', 'flat'])
add(controls, 'button', { dataset: { slPano: pano } });
add(controls, 'input', { id: 'sl-since' });
add(controls, 'output', { id: 'sl-since-label' });
add(settings, 'ul', { id: 'sl-legend' });
add(settings, 'div', { id: 'sl-coverage-meta' });
// The globe's canvas is focusable too (tabindex=0).
const globe = add(
add(document.body, 'div', { id: 'cesiumContainer' }),
'canvas',
);
globe.setAttribute('tabindex', '0');
// A field in another panel (the location search).
const search = add(document.body, 'input', { id: 'location-search' });
return { document, root, globe, search, main, wrap, settings };
add(root, 'ul', { id: 'sl-legend' });
add(root, 'div', { id: 'sl-coverage-meta' });
return { document, root, wrap };
}
/** Run `fn` with the fake document and an immediate animation frame. */
async function withDom(fn) {
async function withDom(fn, options) {
const saved = {
document: globalThis.document,
requestAnimationFrame: globalThis.requestAnimationFrame,
};
const page = panelDom();
const page = panelDom(options);
globalThis.document = page.document;
globalThis.requestAnimationFrame = (task) => setTimeout(task, 0);
try {
@@ -436,7 +308,7 @@ test('a 360° click reaches the share link through the data manager', () =>
'durable state recorded it',
);
assert.ok(share().includes(`${TOKEN}.p.p`), `share link: ${share()}`);
controls.destroy?.();
controls.destroy();
coordinator.destroy();
}));
@@ -451,11 +323,11 @@ test('releasing the SINCE slider records the window in the share link', () =>
coordinator.getDurableState().options['street-level'].sinceDays;
assert.ok(days > 0, 'a window was recorded');
assert.ok(share().includes(`${TOKEN}.s.${days}`), `share link: ${share()}`);
controls.destroy?.();
controls.destroy();
coordinator.destroy();
}));
/* ── Chip rules and render behaviour, against a stand-in layer ─────────── */
/* ── Render behaviour, against a stand-in layer ────────────────────────── */
function stubLayer() {
const listeners = new Set();
@@ -501,7 +373,7 @@ function uiState({
on,
configured: !keyRequired,
keyRequired,
requiresKeyId: keyRequired ? 'mapillary' : null,
requiresKeyId: 'mapillary',
loading: false,
count: 3,
hint: '',
@@ -517,8 +389,6 @@ function uiState({
street: {
open,
loading: false,
follow: false,
followAvailable: false,
renderMode,
providerId: open ? 'mapillary' : null,
imageId: open ? 'img-1' : null,
@@ -530,7 +400,7 @@ function uiState({
function stubPanel(dom, state, extraActions = {}) {
const layer = stubLayer();
const calls = { setParams: [], setEnabled: [], collapsed: [], toasts: [] };
const calls = { setParams: [], setEnabled: [], collapsed: [] };
let enabled = state.enabled;
layer.publish(state);
const controls = new StreetLevelControls({
@@ -545,60 +415,71 @@ function stubPanel(dom, state, extraActions = {}) {
setParams: (params, options) => calls.setParams.push([params, options]),
setPanelCollapsed: (collapsed, options) =>
calls.collapsed.push([collapsed, options]),
showToast: (message) => calls.toasts.push(message),
showToast() {},
...extraActions,
},
});
controls.connect();
const chip = () => dom.root.querySelector('#sl-provider-chips').children[0];
return { layer, calls, controls, chip };
return { layer, calls, controls };
}
test('darkening the only lit chip turns the layer off and keeps the provider switched on', () =>
test('the header pill switches the layer, bringing back a provider switched off elsewhere', () =>
withDom(async (dom) => {
const { calls, chip } = stubPanel(dom, uiState());
assert.equal(chip().dataset.chipId, 'mapillary');
chip().click();
const status = dom.root.querySelector('#sl-status');
const on = stubPanel(dom, uiState());
status.click();
await settle();
assert.deepEqual(calls.setEnabled, [false]);
assert.deepEqual(calls.setParams, [], 'the provider switch is untouched');
}));
test('lighting a dark chip switches the provider on as a user params request, then the layer', () =>
withDom(async (dom) => {
const { calls, chip } = stubPanel(
dom,
uiState({ enabled: false, on: false }),
assert.deepEqual(on.calls.setEnabled, [false]);
assert.deepEqual(
on.calls.setParams,
[],
'switching off keeps the provider',
);
chip().click();
on.controls.destroy();
const dark = stubPanel(dom, uiState({ enabled: false, on: false }));
status.click();
await settle();
assert.deepEqual(calls.setParams, [
assert.deepEqual(dark.calls.setParams, [
[{ mapillary: true }, { origin: 'user' }],
]);
assert.deepEqual(calls.setEnabled, [true]);
assert.deepEqual(dark.calls.setEnabled, [true]);
dark.controls.destroy();
}));
test('under KEY REQUIRED the filters are gated and the error line says how to add the key', () =>
withDom(async (dom) => {
const { controls } = stubPanel(dom, uiState({ keyRequired: true }));
assert.equal(dom.root.querySelector('#sl-controls').disabled, true);
assert.equal(dom.root.querySelector('#sl-error').hidden, false);
assert.match(
dom.root.querySelector('#sl-error-text').textContent,
/^Mapillary: Needs MAPILLARY_CLIENT_TOKEN/,
);
controls.destroy();
}));
test('the legend rebuilds when a swatch changes, even at the same count', () =>
withDom(async (dom) => {
const { layer } = stubPanel(dom, uiState());
const { layer, controls } = stubPanel(dom, uiState());
const legend = dom.root.querySelector('#sl-legend');
const swatch = () => legend.children[0].children[0].style.background;
assert.equal(swatch(), '#05cb63');
layer.publish(
uiState({
legend: [
{ key: 'panoramax', label: 'Panoramax', color: '#a66bff' },
{ key: 'mapillary', label: 'Mapillary', color: '#a66bff' },
{ key: 'selected', label: 'Selected', color: '#00d4ff' },
],
}),
);
assert.equal(legend.childElementCount, 2);
assert.equal(swatch(), '#a66bff');
controls.destroy();
}));
test('the viewer is resized once when it opens, not on every render', () =>
withDom(async (dom) => {
const { layer } = stubPanel(dom, uiState());
const { layer, controls } = stubPanel(dom, uiState());
await settle();
assert.equal(layer.calls.resize, 0);
layer.publish(uiState({ open: true }));
@@ -612,64 +493,6 @@ test('the viewer is resized once when it opens, not on every render', () =>
layer.publish(uiState({ open: true }));
await settle();
assert.equal(layer.calls.resize, 2, 'the next photo resizes again');
}));
/* ── The expanded viewer as a dialog, and where focus goes ─────────────── */
const keydown = (target, key, { shiftKey = false } = {}) =>
target.dispatchEvent({ type: 'keydown', bubbles: true, key, shiftKey });
/** The map's own Esc handler (selection.js) listens on the document. */
function mapEscape(dom) {
const reached = [];
dom.document.addEventListener('keydown', (event) => {
if (event.key === 'Escape') reached.push(event);
});
return reached;
}
test('Esc shrinks the expanded viewer after focus left it, and the map keeps its selection', () =>
withDom(async (dom) => {
const { controls } = stubPanel(dom, uiState({ open: true }));
const reached = mapEscape(dom);
controls.setViewerExpanded(true);
dom.globe.focus(); // a click on the globe
keydown(dom.globe, 'Escape');
assert.equal(controls.isViewerExpanded(), false);
assert.equal(reached.length, 0, 'the selected sequence was not cleared');
keydown(dom.globe, 'Escape');
assert.equal(reached.length, 1, 'once shrunk, Esc is the map’s again');
controls.destroy();
}));
test('Tab from outside the expanded viewer brings focus back into it', () =>
withDom(async (dom) => {
const { controls } = stubPanel(dom, uiState({ open: true }));
// A tool hidden in this state (no box, so not a tab stop) ends the bar.
const hiddenTool = dom.wrap.appendChild(
new FakeNode(dom.document, 'button', { id: 'sl-hidden-tool' }),
);
hiddenTool.hidden = true;
controls.setViewerExpanded(true);
dom.globe.focus();
keydown(dom.globe, 'Tab');
const wrap = dom.document.body.querySelector('#sl-viewer-wrap');
assert.equal(
dom.document.activeElement,
wrap.querySelector('#sl-viewer-expand'),
);
keydown(dom.document.activeElement, 'Tab', { shiftKey: true });
assert.equal(
dom.document.activeElement,
wrap.querySelector('#sl-viewer-close'),
'Shift+Tab wraps to the last control, past the hidden one',
);
keydown(dom.document.activeElement, 'Tab');
assert.equal(
dom.document.activeElement,
wrap.querySelector('#sl-viewer-expand'),
'Tab from the last shown control wraps to the first',
);
controls.destroy();
}));
@@ -678,7 +501,7 @@ test('closing the image from its × button leaves focus on the panel, not <body>
const { layer, controls } = stubPanel(dom, uiState({ open: true }));
dom.root.querySelector('#sl-viewer-close').focus();
layer.publish(uiState({ open: false }));
assert.equal(dom.root.querySelector('#sl-viewer-wrap').hidden, true);
assert.equal(dom.wrap.hidden, true);
assert.equal(
dom.document.activeElement,
dom.root.querySelector('#sl-status'),
@@ -686,21 +509,61 @@ test('closing the image from its × button leaves focus on the panel, not <body>
controls.destroy();
}));
test('an image closed while expanded does not return focus into the hidden viewer', () =>
/* ── EXPAND is the browser's fullscreen ────────────────────────────────── */
const expandLabel = (dom) => {
const button = dom.root.querySelector('#sl-viewer-expand');
return [
button.querySelector('.sl-btn-text').textContent,
button.getAttribute('aria-pressed'),
];
};
test('EXPAND puts the viewer full screen in place, and the button shrinks it again', () =>
withDom(async (dom) => {
const { layer, controls } = stubPanel(dom, uiState({ open: true }));
dom.root.querySelector('#sl-viewer-expand').focus();
controls.setViewerExpanded(true); // remembers EXPAND to return to
layer.publish(uiState({ open: false }));
assert.equal(controls.isViewerExpanded(), false);
assert.equal(
dom.document.activeElement,
dom.root.querySelector('#sl-status'),
);
await settle();
const resizes = layer.calls.resize;
const expand = dom.root.querySelector('#sl-viewer-expand');
expand.click();
await settle();
await settle();
assert.equal(dom.document.fullscreenElement, dom.wrap);
assert.equal(dom.root.contains(dom.wrap), true, 'never leaves the panel');
assert.deepEqual(expandLabel(dom), ['SHRINK', 'true']);
assert.equal(layer.calls.resize, resizes + 1, 'the viewer refits');
expand.click();
await settle();
await settle();
assert.equal(dom.document.fullscreenElement, null);
assert.deepEqual(expandLabel(dom), ['EXPAND', 'false']);
controls.destroy();
}));
/* ── Restores, the modal viewer and keyboard rules ─────────────────────── */
test('an image closed while full screen leaves full screen', () =>
withDom(async (dom) => {
const { layer, controls } = stubPanel(dom, uiState({ open: true }));
dom.root.querySelector('#sl-viewer-expand').click();
await settle();
layer.publish(uiState({ open: false }));
await settle();
assert.equal(dom.document.fullscreenElement, null);
assert.equal(dom.wrap.hidden, true);
assert.deepEqual(expandLabel(dom), ['EXPAND', 'false']);
controls.destroy();
}));
test('without the Fullscreen API there is no EXPAND button', () =>
withDom(
async (dom) => {
const { controls } = stubPanel(dom, uiState({ open: true }));
assert.equal(dom.root.querySelector('#sl-viewer-expand').hidden, true);
controls.destroy();
},
{ fullscreen: false },
));
/* ── Restores and keyboard rules ───────────────────────────────────────── */
test('a restored layer does not reopen a panel the user collapsed, and automatic opens are never stored (P2-1)', () =>
withDom(async (dom) => {
@@ -763,205 +626,11 @@ test('with request origins, only a user switch-on opens the panel; a restore nev
assert.equal(announce, null, 'destroy unsubscribes');
}));
test('Esc and Tab from a field outside the expanded viewer stay with that field (P3)', () =>
withDom(async (dom) => {
const { controls } = stubPanel(dom, uiState({ open: true }));
const reached = mapEscape(dom);
controls.setViewerExpanded(true);
dom.search.focus();
keydown(dom.search, 'Escape');
assert.equal(controls.isViewerExpanded(), true, 'the search keeps its Esc');
assert.equal(reached.length, 1, 'and the event was not swallowed');
keydown(dom.search, 'Tab');
assert.equal(dom.document.activeElement, dom.search, 'Tab stays put');
// From <body> (focus nowhere), Esc is still the viewer's.
keydown(dom.document.body, 'Escape');
assert.equal(controls.isViewerExpanded(), false);
controls.destroy();
}));
test('a hidden expanded viewer (Clean View, recording, cockpit) holds neither Esc nor Tab (P2-5)', () =>
withDom(async (dom) => {
const { controls } = stubPanel(dom, uiState({ open: true }));
const reached = mapEscape(dom);
controls.setViewerExpanded(true);
const wrap = dom.document.body.querySelector('#sl-viewer-wrap');
wrap.checkVisibility = () => false; // the mode's CSS hides it
dom.globe.focus();
keydown(dom.globe, 'Tab');
assert.equal(dom.document.activeElement, dom.globe);
keydown(dom.globe, 'Escape');
assert.equal(controls.isViewerExpanded(), true);
assert.equal(reached.length, 1, 'Esc went on to the map');
controls.destroy();
}));
/**
* A MutationObserver stand-in: queues only the records its options cover and
* delivers them in a microtask; `fire()` delivers at once.
*/
function fakeMutationObserver() {
const observers = [];
class FakeMutationObserver {
constructor(callback) {
this.callback = callback;
this.target = null;
this.options = null;
this.records = [];
observers.push(this);
}
observe(target, options = {}) {
this.target = target;
this.options = {
...options,
// Per the spec, an attribute filter implies `attributes`.
attributes: options.attributes ?? Boolean(options.attributeFilter),
};
liveObservers.add(this);
}
disconnect() {
this.target = null;
this.records = [];
liveObservers.delete(this);
}
consider(node, type, attributeName) {
const { childList, attributes, attributeFilter, subtree } = this.options;
const inScope =
node === this.target ||
(subtree === true && this.target.contains(node));
if (!inScope) return;
if (type === 'childList' && childList !== true) return;
if (type === 'attributes') {
if (attributes !== true) return;
if (attributeFilter && !attributeFilter.includes(attributeName)) return;
}
this.records.push({ type, target: node, attributeName });
if (this.records.length === 1) queueMicrotask(() => this.deliver());
}
deliver() {
if (!this.target || !this.records.length) return;
const records = this.records;
this.records = [];
this.callback(records, this);
}
}
const fire = () => {
for (const observer of observers) observer.deliver();
};
const watching = () => observers.some((observer) => observer.target);
return { FakeMutationObserver, fire, watching };
}
/** Run `fn` with a fake MutationObserver installed. */
async function withObserver(fn) {
const saved = globalThis.MutationObserver;
const fake = fakeMutationObserver();
globalThis.MutationObserver = fake.FakeMutationObserver;
try {
return await fn(fake);
} finally {
liveObservers.clear();
if (saved === undefined) delete globalThis.MutationObserver;
else globalThis.MutationObserver = saved;
}
}
/** Every <body> child but the viewer, by id. */
const inertOutside = (dom) =>
dom.document.body.children
.filter((node) => node.id !== 'sl-viewer-wrap')
.map((node) => [node.id, node.inert === true]);
test('the expanded viewer makes the rest of the app inert and gives it back on shrink', () =>
withObserver(() =>
withDom(async (dom) => {
const { controls } = stubPanel(dom, uiState({ open: true }));
// Another dialog's own inert backdrop: it is not ours to release.
const owned = dom.document.body.appendChild(
new dom.globe.constructor(dom.document, 'div', { id: 'owned' }),
);
owned.inert = true;
controls.setViewerExpanded(true);
assert.deepEqual(inertOutside(dom), [
['street-level-panel', true],
['cesiumContainer', true],
['location-search', true],
['owned', true],
]);
const wrap = dom.document.body.querySelector('#sl-viewer-wrap');
assert.notEqual(wrap.inert, true, 'the viewer itself stays live');
// Shrinking returns focus into the panel: it must be live again first.
dom.root.querySelector('#sl-status').focus();
controls.setViewerExpanded(false);
assert.deepEqual(inertOutside(dom), [
['street-level-panel', false],
['cesiumContainer', false],
['location-search', false],
['owned', true],
]);
controls.destroy();
}),
));
test('a CSS-hidden expanded viewer releases the app; showing it again, and new children, go inert', () =>
withObserver((observer) =>
withDom(async (dom) => {
const { controls } = stubPanel(dom, uiState({ open: true }));
controls.setViewerExpanded(true);
assert.equal(observer.watching(), true);
const wrap = dom.document.body.querySelector('#sl-viewer-wrap');
let visible = true;
wrap.checkVisibility = () => visible;
// Clean View (or recording, or the cockpit) hides the viewer by CSS.
visible = false;
dom.document.body.classList.add('ui-clean-view');
observer.fire();
assert.ok(
inertOutside(dom).every(([, inert]) => !inert),
'a hidden modal leaves nothing inert',
);
// Leaving the mode shows the viewer again: the app is inert once more,
// and so is a child added to <body> meanwhile.
visible = true;
const toast = dom.document.body.appendChild(
new dom.globe.constructor(dom.document, 'div', { id: 'toast' }),
);
observer.fire();
assert.ok(inertOutside(dom).every(([, inert]) => inert));
assert.equal(toast.inert, true);
controls.destroy();
assert.ok(
inertOutside(dom).every(([, inert]) => !inert),
'destroy releases the app',
);
assert.equal(observer.watching(), false, 'and stops watching');
}),
));
test('an image closed while expanded releases the app', () =>
withObserver(() =>
withDom(async (dom) => {
const { layer, controls } = stubPanel(dom, uiState({ open: true }));
controls.setViewerExpanded(true);
assert.ok(inertOutside(dom).every(([, inert]) => inert));
layer.publish(uiState({ open: false }));
assert.equal(controls.isViewerExpanded(), false);
assert.ok(inertOutside(dom).every(([, inert]) => !inert));
assert.equal(
dom.document.activeElement,
dom.root.querySelector('#sl-status'),
);
controls.destroy();
}),
));
test('FIT / FILL show the selection while the viewer is expanded (P3)', () =>
test('FIT / FILL show the selected render mode (P3)', () =>
withDom(async (dom) => {
const { layer, controls } = stubPanel(dom, uiState({ open: true }));
controls.setViewerExpanded(true);
layer.publish(uiState({ open: true, renderMode: 'fill' }));
const wrap = dom.document.body.querySelector('#sl-viewer-wrap');
const [fit, fill] = wrap.querySelectorAll('[data-sl-render]');
const [fit, fill] = dom.wrap.querySelectorAll('[data-sl-render]');
assert.equal(fill.getAttribute('aria-checked'), 'true');
assert.equal(fit.getAttribute('aria-checked'), 'false');
assert.equal(fill.classList.contains('is-active'), true);
@@ -1011,6 +680,8 @@ test('identical renders write nothing to the DOM (P3: rail MutationObserver)', (
test('arrow keys move the selection within a radiogroup, which has one tab stop (P3)', () =>
withDom(async (dom) => {
const { layer, calls, controls } = stubPanel(dom, uiState());
const keydown = (target, key) =>
target.dispatchEvent({ type: 'keydown', bubbles: true, key });
const [all, pano, flat] = dom.root.querySelectorAll('[data-sl-pano]');
assert.deepEqual(
[all, pano, flat].map((button) => button.getAttribute('tabindex')),
@@ -1034,103 +705,3 @@ test('arrow keys move the selection within a radiogroup, which has one tab stop
);
controls.destroy();
}));
test('under KEY REQUIRED the provider chip stays live and explains the key instead of toggling (P3)', () =>
withDom(async (dom) => {
const { calls, chip, controls } = stubPanel(
dom,
uiState({ keyRequired: true }),
);
assert.equal(dom.root.querySelector('#sl-controls').disabled, true);
assert.equal(
dom.root.querySelector('#sl-controls').contains(chip()),
false,
'the chip is outside the disabled fieldset',
);
chip().click();
await settle();
assert.deepEqual(calls.setEnabled, []);
assert.deepEqual(calls.setParams, []);
assert.equal(calls.toasts.length, 1);
assert.match(calls.toasts[0], /^Mapillary: Needs /);
controls.destroy();
}));
/* ── The expanded viewer goes back where it came from ──────────────────── */
/** A node by name, so a failed comparison prints a word, not the DOM. */
const nameOf = (node) =>
node ? node.id || node.className || node.tagName.toLowerCase() : null;
/** Where the viewer sits: its parent and the sibling it sits before. */
const placeOf = (wrap) => [nameOf(wrap.parentNode), nameOf(wrap.nextSibling)];
const PANEL_PLACE = ['sl-main', 'sl-settings'];
test('shrinking returns the viewer into the panel at its own place', () =>
withDom(async (dom) => {
const { controls } = stubPanel(dom, uiState({ open: true }));
assert.deepEqual(placeOf(dom.wrap), PANEL_PLACE);
controls.setViewerExpanded(true);
assert.equal(nameOf(dom.wrap.parentNode), 'body', 'lifted out');
controls.setViewerExpanded(false);
assert.deepEqual(placeOf(dom.wrap), PANEL_PLACE, 'before the settings');
assert.equal(dom.main.children.indexOf(dom.wrap), 0);
assert.equal(dom.root.contains(dom.wrap), true);
// A second round trip lands in the same place.
controls.setViewerExpanded(true);
controls.setViewerExpanded(false);
assert.deepEqual(placeOf(dom.wrap), PANEL_PLACE);
controls.destroy();
}));
test('an image closed while expanded returns the viewer into the panel', () =>
withDom(async (dom) => {
const { layer, controls } = stubPanel(dom, uiState({ open: true }));
controls.setViewerExpanded(true);
layer.publish(uiState({ open: false }));
assert.deepEqual(placeOf(dom.wrap), PANEL_PLACE);
assert.equal(dom.wrap.hidden, true, 'and hidden there');
controls.destroy();
}));
test('destroying the panel while expanded returns the viewer into it', () =>
withDom(async (dom) => {
const { controls } = stubPanel(dom, uiState({ open: true }));
controls.setViewerExpanded(true);
controls.destroy();
assert.deepEqual(placeOf(dom.wrap), PANEL_PLACE);
assert.equal(
dom.document.body.children.includes(dom.wrap),
false,
'nothing left on <body>',
);
}));
test('a <body> child added while the viewer is expanded goes inert with the rest', () =>
withObserver((observer) =>
withDom(async (dom) => {
const { controls } = stubPanel(dom, uiState({ open: true }));
controls.setViewerExpanded(true);
// A toast, a menu or another panel's popup, appended later.
const toast = dom.document.body.appendChild(
new FakeNode(dom.document, 'div', { id: 'toast' }),
);
assert.equal(toast.inert, undefined, 'not before the observer runs');
await settle(); // records are delivered in a microtask
assert.equal(toast.inert, true);
// Changes inside the app are not the modal's business: nothing runs.
let syncs = 0;
const sync = controls._syncModal.bind(controls);
controls._syncModal = () => {
syncs++;
return sync();
};
dom.root.querySelector('#sl-status').setAttribute('class', 'x');
dom.root.appendChild(new FakeNode(dom.document, 'div'));
await settle();
assert.equal(syncs, 0);
controls.destroy();
assert.equal(toast.inert, false, 'destroy releases it too');
assert.equal(observer.watching(), false);
}),
));