Merge branch 'main' into feat/alpr-model-specs

This commit is contained in:
German Khokhlov authored and GitHub committed 2026-11-20 03:17:38 +04:00
commit aa5ab7d387
164 files changed
+8418 -1082

No files matched your search

+2 -1
View File
@@ -2,6 +2,7 @@ import { createCctvLayer } from '../../layers/cctv/index.js';
import * as credits from '../../data/dataCredits.js';
import * as sprites from '../../data/spriteOrder.js';
import * as activation from '../../cctvFocusRequest.js';
import { keyholeLabelAlphaFromGeometry } from '../../celestialRing.js';
import * as overlays from '../../overlays/worldOverlay.js';
import { CITY_POIS } from '../../cityPois.js';
import * as picking from '../../data/pickRegistry.js';
@@ -17,7 +18,7 @@ export function createApplicationCctv({ surface, source }) {
credits,
sprites,
activation,
overlays,
overlays: { ...overlays, keyholeAlpha: keyholeLabelAlphaFromGeometry },
locations: { CITY_POIS },
picking,
terrain,
+8 -2
View File
@@ -90,8 +90,14 @@ test('the ring renders its overlay in the viewer container', async (t) => {
['DIV', 'celestial-ring-outline'],
['CANVAS', 'celestial-ring-canvas celestial-sun-canvas'],
['CANVAS', 'celestial-ring-canvas celestial-moon-canvas'],
['SPAN', 'celestial-marker celestial-sun material-symbols-outlined'],
['SPAN', 'celestial-marker celestial-moon material-symbols-outlined'],
[
'SPAN',
'ui-icon material-symbols-outlined celestial-marker celestial-sun',
],
[
'SPAN',
'ui-icon material-symbols-outlined celestial-marker celestial-moon',
],
],
);
assert.equal(root.children[0].style.display, 'none');
+24 -11
View File
@@ -74,10 +74,14 @@ const voiceActions = fs.readFileSync(
test('Cockpit has one reset action beside its bottom exit path', () => {
assert.doesNotMatch(html, /id="cockpit-quick-entry"/);
assert.doesNotMatch(html, /id="cockpit-exit"/);
assert.match(
html,
/id="map-view-switch"[^>]*aria-label="Exit cockpit view"[^>]*aria-keyshortcuts="Escape"[\s\S]*?close_fullscreen[\s\S]*?EXIT COCKPIT/,
// The exit button's attributes, in whatever order the button renders them.
const exit = html.match(
/<button\b(?=[^>]*\sid="map-view-switch")([^>]*)>([\s\S]*?)<\/button>/,
);
assert.ok(exit, 'Cockpit exit is missing');
assert.match(exit[1], /\saria-label="Exit cockpit view"/);
assert.match(exit[1], /\saria-keyshortcuts="Escape"/);
assert.match(exit[2], /close_fullscreen[\s\S]*?EXIT COCKPIT/);
const topCenterActions = html.match(
/<nav id="top-center-actions"[\s\S]*?<\/nav>/,
);
@@ -108,9 +112,18 @@ test('Cockpit has one reset action beside its bottom exit path', () => {
/id="reset-globe-view"/,
'map-only reset must stay outside Cockpit',
);
assert.match(
viewSwitcher[0],
/id="cockpit-reset-globe"[^>]*type="button"[^>]*aria-label="Reset cockpit to full globe view"[^>]*hidden[\s\S]*?public[\s\S]*?RESET[\s\S]*?id="map-view-switch"/,
// The reset button's attributes, in whatever order the button renders them.
const reset = viewSwitcher[0].match(
/<button\b(?=[^>]*\sid="cockpit-reset-globe")([^>]*)>([\s\S]*?)<\/button>/,
);
assert.ok(reset, 'Cockpit Reset is missing from the view switcher');
assert.match(reset[1], /\stype="button"/);
assert.match(reset[1], /\saria-label="Reset cockpit to full globe view"/);
assert.match(reset[1], /\shidden(?=[\s>=]|$)/);
assert.match(reset[2], /public[\s\S]*?RESET/);
assert.ok(
viewSwitcher[0].indexOf('id="map-view-switch"') > reset.index,
'Cockpit Reset must sit before the exit button',
);
const actions = html.match(
@@ -194,12 +207,12 @@ test('Cockpit vision cycle exposes every map preset exactly once', () => {
test('Contacts uses the approved radar icon', () => {
const button = html.match(
/<button id="global-context-flights-btn"[\s\S]*?<\/button>/,
/<button\b[^>]*\bid="global-context-flights-btn"[\s\S]*?<\/button>/,
);
assert.ok(button, 'Contacts button is missing');
assert.match(
button[0],
/material-symbols-outlined" aria-hidden="true">radar<\/span>/,
/material-symbols-outlined"[^>]*aria-hidden="true">radar<\/span>/,
);
});
@@ -369,11 +382,11 @@ test('Cockpit owns a focused shared Display portal and compact Radio controls',
assert.doesNotMatch(html, /data-cockpit-display-slot="presets"/);
assert.match(
html,
/id="clear-selected-layers"[^>]*aria-label="Clear selected data layers"/,
/<button\b(?=[^>]*\bid="clear-selected-layers")[^>]*aria-label="Clear selected data layers"/,
);
assert.match(
html,
/id="reset-globe-view"[^>]*aria-label="Reset to full globe view"/,
/<button\b(?=[^>]*\bid="reset-globe-view")[^>]*aria-label="Reset to full globe view"/,
);
assert.match(
css,
@@ -1231,7 +1244,7 @@ test('Cockpit Contact navigation omits the redundant Focus camera action', () =>
test('Global Context names its mixed contact cycle without changing the stable mode id', () => {
const match = html.match(
/<button id="global-context-flights-btn"[\s\S]*?<\/button>/,
/<button\b[^>]*\bid="global-context-flights-btn"[\s\S]*?<\/button>/,
);
assert.ok(match, 'Global Context contacts button is missing');
assert.match(match[0], />CONTACTS</);
+4 -4
View File
@@ -25,12 +25,12 @@ const css = readStylesheet(new URL('../style.css', import.meta.url));
test('Contacts stays in the keyboard sequence and Space Missions owns its rail item', () => {
const button = html.match(
/<button id="global-context-flights-btn"[\s\S]*?<\/button>/,
/<button\b[^>]*\bid="global-context-flights-btn"[\s\S]*?<\/button>/,
)?.[0];
assert.ok(button, 'Contacts control is missing');
assert.match(button, /role="tab"/);
assert.match(button, /tabindex="0"/);
const tag = contextView.match(/<button id="global-context-flights-btn"[^>]*>/)?.[0];
const tag = contextView.match(/<UiButton id="global-context-flights-btn"[^>]*>/)?.[0];
assert.ok(tag, 'Contacts control is missing from the view');
assert.doesNotMatch(tag, /:tabindex|:disabled|\sdisabled/);
assert.doesNotMatch(html, /id="global-context-missions-btn"/);
@@ -111,7 +111,7 @@ test('Context async action buttons remain focused while busy', () => {
assert.match(init, /if \(this\._installationsSearchBusy\) return;/);
assert.doesNotMatch(init, /\.disabled\s*=\s*true/);
const search = contextView.match(
/<button id="installations-search-btn"[^>]*>/,
/<UiButton id="installations-search-btn"[^>]*>/,
)?.[0];
assert.ok(search, 'nearby sites search is missing');
assert.doesNotMatch(search, /:disabled|\sdisabled/);
@@ -140,7 +140,7 @@ test('Context async action buttons remain focused while busy', () => {
'utf8',
);
const clearButton = globeActions.match(
/<button id="clear-selected-layers"[^>]*>/,
/<UiButton id="clear-selected-layers"[^>]*>/,
)?.[0];
assert.ok(clearButton, 'Clear selected layers button is missing');
assert.doesNotMatch(clearButton, /disabled(?!=")|:disabled=/);
+173 -179
View File
@@ -6,6 +6,8 @@ import {
} from '../render/rendererOf.js';
import { dot, sub } from '../geo/vector.js';
import { t, msg, onLocaleChange } from '../i18n/index.js';
import { h, render as renderVue } from 'vue';
import BhoteKoshiMediaCards from '../ui/bhoteKoshi/BhoteKoshiMediaCards.vue';
const YOUTUBE_HOSTS = new Set([
'youtube.com',
@@ -98,6 +100,7 @@ export function bhoteEventText(value) {
let _xWidgetsPromise = null;
let _facebookSdkPromise = null;
let _facebookEmbedSequence = 0;
let _cardSequence = 0;
const youtubeApis = new WeakMap();
function loadYouTubeApi(documentRef, globalRef) {
@@ -682,32 +685,61 @@ export function createBhoteKoshiEmbeddedMedia({
let record = null;
let warmRecord = null;
let generation = 0;
// Text the cards show, kept as the calls that word it so a locale change
// words it again. A node is forgotten once it has left the page.
const worded = new Map();
function forgetDetached() {
for (const node of worded.keys())
if (!node.isConnected) worded.delete(node);
let destroyed = false;
// The cards in the root, in the order they were shown: the current one and
// any still leaving. Their text is kept as the calls that word it, so a
// locale change words it again.
const cards = [];
/** Render the cards and the YouTube preload into the root, synchronously. */
function render() {
if (destroyed) return;
const warmFrame = warmRecord?.frame;
renderVue(
h(BhoteKoshiMediaCards, {
warm: warmFrame
? {
key: warmRecord.key,
src: warmFrame.src,
title: warmFrame.title(),
}
: null,
cards: cards.map((current) => ({
id: current.id,
provider: current.source.provider,
portrait: current.portrait,
entering: current.entering,
leaving: current.leaving,
unavailable: current.unavailable,
label: current.label(),
title: current.title(),
status: current.status(),
url: current.source.url,
frame: current.frame && {
src: current.frame.src,
title: current.frame.title(),
onLoad: current.frame.onLoad,
},
bind: current.bind,
})),
}),
root,
);
}
function word(node, property, text) {
let properties = worded.get(node);
if (!properties) worded.set(node, (properties = new Map()));
properties.set(property, text);
writeWord(node, property, text());
}
function writeWord(node, property, value) {
if (property === 'textContent' || property === 'title')
node[property] = value;
else node.setAttribute(property, value);
}
const offLocale = onLocaleChange(() => {
forgetDetached();
for (const [node, properties] of worded)
for (const [property, text] of properties)
writeWord(node, property, text());
});
const offLocale = onLocaleChange(render);
const leavingRecords = new Set();
/** Word a card's status and draw it. */
function setStatus(current, text) {
current.status = text;
render();
}
/** Mark a card unavailable or not and draw it. */
function setUnavailable(current, unavailable) {
current.unavailable = unavailable;
render();
}
const prefersReducedMotion = () =>
globalRef.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches ===
true;
@@ -848,9 +880,10 @@ export function createBhoteKoshiEmbeddedMedia({
if (current.exitTimer != null) globalRef.clearTimeout?.(current.exitTimer);
destroyFacebookSession(current.facebookSession);
current.youtubeSession?.destroy();
current.card?.remove?.();
const at = cards.indexOf(current);
if (at !== -1) cards.splice(at, 1);
leavingRecords.delete(current);
forgetDetached();
render();
}
const position = () => {
@@ -866,7 +899,8 @@ export function createBhoteKoshiEmbeddedMedia({
current.enterFrame = scheduleFrame(() => {
current.enterFrame = null;
if (token !== generation || record !== current) return;
current.card.classList.add('is-entering');
current.entering = true;
render();
});
}
}
@@ -888,9 +922,10 @@ export function createBhoteKoshiEmbeddedMedia({
removeRecord(current);
return;
}
current.card.classList.remove('is-entering');
current.card.classList.add('is-leaving');
current.entering = false;
current.leaving = true;
leavingRecords.add(current);
render();
current.exitTimer =
globalRef.setTimeout?.(
() => removeRecord(current),
@@ -900,11 +935,10 @@ export function createBhoteKoshiEmbeddedMedia({
function clearWarm(key = null) {
if (!warmRecord || (key && warmRecord.key !== key)) return;
if (warmRecord.facebookSession)
destroyFacebookSession(warmRecord.facebookSession);
else warmRecord.iframe?.remove?.();
const facebookSession = warmRecord.facebookSession;
warmRecord = null;
forgetDetached();
if (facebookSession) destroyFacebookSession(facebookSession);
else render();
}
function takeWarmFacebook(key, host) {
@@ -944,29 +978,26 @@ export function createBhoteKoshiEmbeddedMedia({
warmRecord = { key, facebookSession };
return true;
}
const iframe = documentRef.createElement('iframe');
iframe.className = 'bhote-embedded-media-warmup';
iframe.src = embeddedMediaFrameUrl(source, {
autoplay: false,
startAtSec,
endAtSec,
});
word(iframe, 'title', () =>
t('Preloading {provider} media', {
provider: providerLabel(source.provider),
}),
);
iframe.tabIndex = -1;
iframe.setAttribute('aria-hidden', 'true');
iframe.loading = 'eager';
iframe.referrerPolicy = 'strict-origin-when-cross-origin';
root.append(iframe);
warmRecord = { key, iframe };
warmRecord = {
key,
frame: {
src: embeddedMediaFrameUrl(source, {
autoplay: false,
startAtSec,
endAtSec,
}),
title: () =>
t('Preloading {provider} media', {
provider: providerLabel(source.provider),
}),
},
};
render();
return true;
}
async function mountX(current, token) {
word(current.status, 'textContent', () => t('LOADING X POST…'));
setStatus(current, () => t('LOADING X POST…'));
try {
const api = await xLoader(documentRef, globalRef);
if (token !== generation || record !== current) return;
@@ -986,14 +1017,12 @@ export function createBhoteKoshiEmbeddedMedia({
throw new Error(
msg('The X post is unavailable or cannot be embedded.'),
);
word(current.status, 'textContent', () =>
t('X POST · PROVIDER CONTROLS'),
);
setStatus(current, () => t('X POST · PROVIDER CONTROLS'));
position();
} catch (error) {
if (token !== generation || record !== current) return;
current.card.classList.add('is-unavailable');
word(current.status, 'textContent', () =>
current.unavailable = true;
setStatus(current, () =>
t('{reason} OPEN ORIGINAL.', {
reason: t(String(error?.message || msg('X embed unavailable'))),
}),
@@ -1010,16 +1039,14 @@ export function createBhoteKoshiEmbeddedMedia({
session.shouldPlay = autoplay === true;
session.onReady = () => {
if (token !== generation || record !== current) return;
word(current.status, 'textContent', () =>
t('FACEBOOK · PROVIDER CONTROLS'),
);
current.card.classList.remove('is-unavailable');
current.status = () => t('FACEBOOK · PROVIDER CONTROLS');
setUnavailable(current, false);
position();
};
session.onError = (error) => {
if (token !== generation || record !== current) return;
current.card.classList.add('is-unavailable');
word(current.status, 'textContent', () =>
current.unavailable = true;
setStatus(current, () =>
t('{reason} OPEN ORIGINAL.', {
reason: t(
String(error?.message || msg('Facebook embed unavailable')),
@@ -1030,9 +1057,7 @@ export function createBhoteKoshiEmbeddedMedia({
};
session.onPlaybackBlocked = () => {
if (token !== generation || record !== current) return;
word(current.status, 'textContent', () =>
t('AUTOPLAY BLOCKED · USE PROVIDER CONTROLS'),
);
setStatus(current, () => t('AUTOPLAY BLOCKED · USE PROVIDER CONTROLS'));
};
if (session.ready) session.onReady();
else if (session.error) session.onError(session.error);
@@ -1078,104 +1103,69 @@ export function createBhoteKoshiEmbeddedMedia({
if (warmRecord && warmRecord.key !== warmKey) clearWarm();
hide({ preserveWarm: true });
const token = ++generation;
const card = documentRef.createElement('section');
const portraitClass = isPortraitMedia(media) ? ' is-portrait' : '';
card.className = `bhote-embedded-callout is-${source.provider}${portraitClass}`;
card.dataset.provider = source.provider;
word(card, 'aria-label', () =>
t('Embedded {provider} media for {source}', {
provider: providerLabel(source.provider),
source: observation?.title
? bhoteEventText(observation.title)
: t('witness source'),
}),
);
const leader = documentRef.createElementNS(
'http://www.w3.org/2000/svg',
'svg',
);
leader.classList.add('bhote-embedded-callout-leader');
leader.setAttribute('aria-hidden', 'true');
leader.innerHTML =
'<path pathLength="1" fill="none" stroke="rgba(147,213,228,.72)" stroke-width="1.5"/><circle r="4" fill="#6be8ff" stroke="#ffffff" stroke-width="1.5"/>';
const player = documentRef.createElement('div');
player.className = 'bhote-embedded-callout-player ui-scroll';
const footer = documentRef.createElement('footer');
const title = documentRef.createElement('strong');
word(title, 'textContent', () =>
bhoteEventText(
observation?.shortTitle || observation?.title || t('Witness source'),
).toUpperCase(),
);
const status = documentRef.createElement('small');
status.setAttribute('role', 'status');
word(status, 'textContent', () =>
t('{provider} · EMBEDDED SOURCE', {
provider: providerLabel(source.provider),
}),
);
const link = documentRef.createElement('a');
link.href = source.url;
link.target = '_blank';
link.rel = 'noopener noreferrer';
word(link, 'textContent', () => t('OPEN ORIGINAL ↗'));
footer.append(title, status, link);
const body = documentRef.createElement('div');
body.className = 'bhote-embedded-callout-body';
// The card takes taps (its container and leader do not); Stories keeps that.
body.setAttribute('data-overlay-input', '');
body.append(player, footer);
card.append(leader, body);
root.append(card);
record = {
const providerName = () => providerLabel(source.provider);
const sourceName = () =>
observation?.title
? bhoteEventText(observation.title)
: t('witness source');
const current = {
id: ++_cardSequence,
key,
source,
anchor,
card,
leader,
player,
status,
portrait: isPortraitMedia(media),
entering: false,
leaving: false,
unavailable: false,
label: () =>
t('Embedded {provider} media for {source}', {
provider: providerName(),
source: sourceName(),
}),
title: () =>
bhoteEventText(
observation?.shortTitle || observation?.title || t('Witness source'),
).toUpperCase(),
status: () =>
t('{provider} · EMBEDDED SOURCE', { provider: providerName() }),
frame: null,
frameElement: null,
card: null,
leader: null,
player: null,
entered: false,
};
if (source.provider === 'x') {
void mountX(record, token);
} else if (source.provider === 'facebook') {
bindFacebook(record, token, warmKey, autoplay);
} else {
const iframe = documentRef.createElement('iframe');
iframe.src = embeddedMediaFrameUrl(source, {
autoplay,
startAtSec,
endAtSec,
});
const controlled =
// The elements the card's view draws: placed after each frame, filled by
// the provider.
current.bind = (name, element) => {
if (element) current[name] = element;
};
let controlled = false;
if (source.provider === 'youtube') {
const url = new URL(
embeddedMediaFrameUrl(source, {
autoplay,
startAtSec,
endAtSec,
}),
);
controlled =
autoplay &&
Number.isFinite(Number(endAtSec)) &&
Number(endAtSec) > startAtSec;
if (controlled) {
const url = new URL(iframe.src);
url.searchParams.set('enablejsapi', '1');
if (globalRef.location?.origin)
url.searchParams.set('origin', globalRef.location.origin);
iframe.src = url.href;
}
word(iframe, 'title', () =>
t('{provider} media: {source}', {
provider: providerLabel(source.provider),
source: observation?.title
? bhoteEventText(observation.title)
: t('witness source'),
}),
);
iframe.allow =
'autoplay; encrypted-media; picture-in-picture; fullscreen';
iframe.allowFullscreen = true;
iframe.loading = 'eager';
iframe.referrerPolicy = 'strict-origin-when-cross-origin';
iframe.addEventListener?.(
'load',
() => {
current.frame = {
src: url.href,
title: () =>
t('{provider} media: {source}', {
provider: providerName(),
source: sourceName(),
}),
onLoad: () => {
if (token !== generation || record?.key !== key) return;
clearWarm(warmKey);
if (
@@ -1184,38 +1174,41 @@ export function createBhoteKoshiEmbeddedMedia({
record.youtubeSession.getState().phase,
)
) {
word(status, 'textContent', () =>
t('{provider} · PROVIDER CONTROLS', {
provider: providerLabel(source.provider),
}),
setStatus(current, () =>
t('{provider} · PROVIDER CONTROLS', { provider: providerName() }),
);
}
position();
},
{ once: true },
);
player.append(iframe);
if (controlled) {
const current = record;
current.youtubeSession = createTrimmedYouTubePlayback({
iframe,
endAtSec: Number(endAtSec),
startAtSec,
globalRef,
loadApi: () => youtubeLoader(documentRef, globalRef),
isCurrent: () => token === generation && record === current,
onStatus: (phase) => {
if (phase !== 'completed')
word(status, 'textContent', () =>
t('YOUTUBE {state} · OPEN ORIGINAL', {
state: YOUTUBE_PHASE_LABELS[phase]
? t(YOUTUBE_PHASE_LABELS[phase])
: phase.toUpperCase(),
}),
);
},
});
}
};
}
record = current;
cards.push(current);
render();
if (source.provider === 'x') {
void mountX(current, token);
} else if (source.provider === 'facebook') {
bindFacebook(current, token, warmKey, autoplay);
} else if (controlled) {
current.youtubeSession = createTrimmedYouTubePlayback({
iframe: current.frameElement,
endAtSec: Number(endAtSec),
startAtSec,
globalRef,
loadApi: () => youtubeLoader(documentRef, globalRef),
isCurrent: () => token === generation && record === current,
onStatus: (phase) => {
if (phase !== 'completed')
setStatus(current, () =>
t('YOUTUBE {state} · OPEN ORIGINAL', {
state: YOUTUBE_PHASE_LABELS[phase]
? t(YOUTUBE_PHASE_LABELS[phase])
: phase.toUpperCase(),
}),
);
},
});
}
position();
return true;
@@ -1223,11 +1216,12 @@ export function createBhoteKoshiEmbeddedMedia({
function destroy() {
offLocale();
worded.clear();
hide({ immediate: true });
for (const current of [...leavingRecords]) removeRecord(current);
clearWarm();
removePostRender?.();
destroyed = true;
renderVue(null, root);
root.remove();
}
+171 -68
View File
@@ -1,3 +1,4 @@
import '../testSupport/registerDom.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
@@ -12,6 +13,31 @@ import {
} from './bhoteKoshiEmbeddedMedia.js';
import { bindRenderer } from '../render/rendererOf.js';
// The cards draw provider frames; the tests never load their pages, and the
// page's note that each one is not loaded is dropped.
window.happyDOM.settings.disableIframePageLoading = true;
const consoleError = console.error;
console.error = (error, ...rest) => {
if (!/Iframe page loading is disabled/.test(String(error?.message)))
consoleError(error, ...rest);
};
/**
* Embedded media in a fresh globe container of the page, and the overlay
* root it renders into.
*/
function domFixture(options = {}) {
document.body.replaceChildren();
const container = document.body.appendChild(document.createElement('div'));
const media = createBhoteKoshiEmbeddedMedia({
viewer: { container },
documentRef: document,
globalRef: {},
...options,
});
return { media, container, root: container.firstElementChild };
}
test('Pinokio fallback never creates provider DOM or loads SDKs', async () => {
const unexpected = () => { throw new Error('Provider resource allocated in Pinokio'); };
const media = createBhoteKoshiEmbeddedMedia({
@@ -186,31 +212,138 @@ test('trimmed YouTube teardown revokes pending SDK and player callbacks', async
});
test('pausing YouTube removes its frame and rejects a late load from the stopped generation', () => {
const nodes = [];
class Element extends EventTarget {
constructor(tag) { super(); this.tag = tag; this.children = []; this.dataset = {}; this.classList = { add() {}, remove() {} }; nodes.push(this); }
setAttribute() {}
append(...children) { for (const child of children) { child.parent = this; this.children.push(child); } }
remove() { if (this.parent) this.parent.children = this.parent.children.filter((child) => child !== this); this.parent = null; }
}
const documentRef = {
body: new Element('body'),
createElement: (tag) => new Element(tag),
createElementNS: (_, tag) => new Element(tag),
};
const media = createBhoteKoshiEmbeddedMedia({ viewer: {}, documentRef, globalRef: {} });
const { media, container, root } = domFixture();
const options = { observation: { title: 'Clip', media: { sourceUrl: 'https://youtu.be/DbqRexFxv3k' } }, anchor: {}, autoplay: true };
assert.equal(media.show(options), true);
const frame = nodes.find((node) => node.tag === 'iframe');
const card = nodes.find((node) => node.tag === 'section');
assert.ok(card.parent);
const card = root.querySelector('section');
const frame = card.querySelector('iframe');
assert.ok(card.isConnected);
assert.equal(media.pause(), true);
assert.equal(card.parent, null);
assert.equal(card.isConnected, false);
frame.dispatchEvent(new Event('load'));
assert.equal(card.parent, null);
assert.equal(root.querySelector('section'), null);
assert.equal(media.show(options), true, 'an explicit replay creates a fresh player');
assert.notEqual(root.querySelector('section iframe'), frame);
media.destroy();
assert.equal(container.children.length, 0);
});
test('a card draws its provider, source, status and original link, and words them again in a new locale', async () => {
const { setLocale } = await import('../i18n/index.js');
const { media, root } = domFixture();
assert.equal(media.show({
observation: { title: 'Flood footage', media: { sourceUrl: 'https://youtu.be/DbqRexFxv3k', orientation: 'portrait' } },
anchor: {},
}), true);
const card = root.querySelector('section');
assert.equal(card.className, 'bhote-embedded-callout is-youtube is-portrait');
assert.equal(card.dataset.provider, 'youtube');
assert.equal(card.getAttribute('aria-label'), 'Embedded YOUTUBE media for Flood footage');
const leader = card.firstElementChild;
assert.equal(leader.namespaceURI, 'http://www.w3.org/2000/svg');
assert.equal(leader.getAttribute('class'), 'bhote-embedded-callout-leader');
assert.equal(leader.getAttribute('aria-hidden'), 'true');
assert.equal(leader.querySelector('path').getAttribute('pathLength'), '1');
assert.equal(leader.querySelector('circle').getAttribute('r'), '4');
const body = card.querySelector('.bhote-embedded-callout-body');
assert.equal(body.getAttribute('data-overlay-input'), '');
const player = body.firstElementChild;
assert.equal(player.className, 'bhote-embedded-callout-player ui-scroll');
const frame = player.firstElementChild;
assert.equal(frame.tagName, 'IFRAME');
assert.equal(new URL(frame.src).pathname, '/embed/DbqRexFxv3k');
assert.equal(frame.title, 'YOUTUBE media: Flood footage');
assert.equal(frame.getAttribute('allow'), 'autoplay; encrypted-media; picture-in-picture; fullscreen');
assert.equal(frame.hasAttribute('allowfullscreen'), true);
assert.equal(frame.getAttribute('referrerpolicy'), 'strict-origin-when-cross-origin');
const [title, status, link] = body.querySelector('footer').children;
assert.equal(title.tagName, 'STRONG');
assert.equal(title.textContent, 'FLOOD FOOTAGE');
assert.equal(status.getAttribute('role'), 'status');
assert.equal(status.textContent, 'YOUTUBE · EMBEDDED SOURCE');
assert.equal(link.href, 'https://www.youtube.com/watch?v=DbqRexFxv3k');
assert.equal(link.target, '_blank');
assert.equal(link.rel, 'noopener noreferrer');
assert.equal(link.textContent, 'OPEN ORIGINAL ↗');
frame.dispatchEvent(new Event('load'));
assert.equal(status.textContent, 'YOUTUBE · PROVIDER CONTROLS');
try {
await setLocale('es');
assert.notEqual(link.textContent, 'OPEN ORIGINAL ↗', 'the link is worded again');
assert.notEqual(status.textContent, 'YOUTUBE · PROVIDER CONTROLS', 'the status is worded again');
assert.ok(root.querySelector('section') === card, 'in place');
} finally {
await setLocale('en');
}
media.destroy();
});
test('an X post is built by the provider inside the card and its failure marks the card', async () => {
let fail = false;
const { media, root } = domFixture({
xLoader: async () => ({ widgets: { createTweet: async (id, target) => {
if (fail) return null;
target.append(Object.assign(document.createElement('div'), { className: 'twitter-tweet', textContent: id }));
return {};
} } }),
});
const observation = { title: 'Clip', media: { sourceUrl: 'https://x.com/Indowatchosint/status/2092640554568007958' } };
assert.equal(media.show({ observation, anchor: {} }), true);
const card = root.querySelector('section');
const status = card.querySelector('[role="status"]');
assert.equal(status.textContent, 'LOADING X POST…');
await new Promise((resolve) => setTimeout(resolve));
assert.equal(card.querySelector('.bhote-embedded-callout-player .twitter-tweet').textContent, '2092640554568007958');
assert.equal(status.textContent, 'X POST · PROVIDER CONTROLS');
assert.equal(card.classList.contains('is-unavailable'), false);
media.hide({ immediate: true });
fail = true;
assert.equal(media.show({ observation, anchor: {} }), true);
await new Promise((resolve) => setTimeout(resolve));
const failed = root.querySelector('section');
assert.ok(failed.classList.contains('is-unavailable'));
assert.equal(failed.querySelector('[role="status"]').textContent, 'The X post is unavailable or cannot be embedded. OPEN ORIGINAL.');
media.destroy();
});
test('a warmed Facebook player moves into the card and stays through its redraws', async () => {
let ready;
const { media, root } = domFixture({
facebookLoader: async () => ({
Event: { subscribe(_name, callback) { ready = callback; }, unsubscribe() {} },
XFBML: { parse() {} },
}),
});
const observation = { title: 'Clip', media: { sourceUrl: 'https://www.facebook.com/reel/1571491657757829' } };
media.warm({ observation });
await Promise.resolve(); await Promise.resolve();
const host = root.querySelector('.bhote-embedded-media-warmup');
const embed = host.querySelector('.fb-video');
assert.equal(media.show({ observation, anchor: {} }), true);
const card = root.querySelector('section');
const player = card.querySelector('.bhote-embedded-callout-player');
assert.ok(host.parentNode === player, 'the warmed player is carried over, not rebuilt');
assert.equal(host.className, 'bhote-facebook-player-host');
assert.equal(host.hasAttribute('aria-hidden'), false);
ready({ type: 'video', id: embed.id, instance: { mute() {}, play() {}, pause() {} } });
assert.equal(card.querySelector('[role="status"]').textContent, 'FACEBOOK · PROVIDER CONTROLS');
assert.ok(host.parentNode === player, 'a redraw keeps the provider player');
media.destroy();
});
test('a leaving card animates out and is removed after its exit', () => {
const timers = [];
const { media, root } = domFixture({ globalRef: { setTimeout: (fn) => timers.push(fn), clearTimeout() {} } });
media.show({ observation: { media: { sourceUrl: 'https://youtu.be/DbqRexFxv3k' } }, anchor: {} });
const card = root.querySelector('section');
card.hidden = false;
media.hide();
assert.ok(card.isConnected);
assert.ok(card.classList.contains('is-leaving'));
assert.equal(card.classList.contains('is-entering'), false);
timers.forEach((fn) => fn());
assert.equal(card.isConnected, false);
media.destroy();
assert.equal(documentRef.body.children.length, 0);
});
test('resolves supported embedded callout providers from canonical public URLs', () => {
@@ -303,28 +436,8 @@ test('Mailung playback stops at source timestamp 0:07 without changing other cli
});
function preloadFixture(options = {}) {
class Element extends EventTarget {
constructor(tag) {
super(); this.tag = tag; this.children = []; this.dataset = {};
this.classList = { add() {}, remove() {}, contains() { return false; } };
}
setAttribute() {}
removeAttribute() {}
append(...children) {
for (const child of children) { child.remove(); child.parent = this; this.children.push(child); }
}
remove() {
if (this.parent) this.parent.children = this.parent.children.filter(child => child !== this);
this.parent = null;
}
}
const documentRef = {
body: new Element('body'),
createElement: tag => new Element(tag),
createElementNS: (_, tag) => new Element(tag),
};
const media = createBhoteKoshiEmbeddedMedia({ viewer: {}, documentRef, globalRef: {}, ...options });
return { media, root: documentRef.body.children[0] };
const { media, root } = domFixture(options);
return { media, root };
}
for (const operation of ['pause', 'hide', 'destroy']) {
@@ -343,16 +456,18 @@ test('camera updates retain a preload until the visible player loads', () => {
const observation = { media: { sourceUrl: 'https://youtu.be/DbqRexFxv3k' } };
media.warm({ observation });
const frame = root.children[0];
assert.equal(frame.className, 'bhote-embedded-media-warmup');
assert.equal(frame.getAttribute('aria-hidden'), 'true');
assert.equal(frame.tabIndex, -1);
assert.equal(frame.title, 'Preloading YOUTUBE media');
media.hide({ preserveWarm: true });
media.warm({ observation });
assert.equal(root.children[0], frame);
assert.ok(root.children[0] === frame);
assert.equal(media.show({ observation, anchor: {} }), true);
assert.equal(frame.parent, root, 'keep the preload while the visible player starts');
const card = root.children.find(node => node.tag === 'section');
const body = card.children.find(node => node.className === 'bhote-embedded-callout-body');
const player = body.children.find(node => node.className.split(' ').includes('bhote-embedded-callout-player'));
player.children.find(node => node.tag === 'iframe').dispatchEvent(new Event('load'));
assert.equal(frame.parent, null, 'visible player readiness releases the preload');
assert.ok(frame.parentNode === root, 'keep the preload while the visible player starts');
root.querySelector('section .bhote-embedded-callout-body > .bhote-embedded-callout-player > iframe')
.dispatchEvent(new Event('load'));
assert.equal(frame.isConnected, false, 'visible player readiness releases the preload');
media.destroy();
assert.equal(root.children.length, 0);
});
@@ -420,25 +535,9 @@ test('a media card stays between the panels when right-to-left swaps their sides
});
test('a shown card follows its anchor through the renderer ports', () => {
class Element extends EventTarget {
constructor(tag) {
super(); this.tag = tag; this.children = []; this.dataset = {}; this.style = {};
this.classList = { add() {}, remove() {}, contains() { return false; } };
}
setAttribute() {}
removeAttribute() {}
querySelector() { return null; }
getBoundingClientRect() { return { left: 0, top: 0, right: 1000, bottom: 800, width: 1000, height: 800 }; }
append(...children) { for (const child of children) { child.remove(); child.parent = this; this.children.push(child); } }
remove() { if (this.parent) this.parent.children = this.parent.children.filter((child) => child !== this); this.parent = null; }
}
const documentRef = {
body: new Element('body'),
createElement: (tag) => new Element(tag),
createElementNS: (_, tag) => new Element(tag),
};
const listeners = new Set();
const viewer = { canvas: { getBoundingClientRect: () => ({ left: 500, top: 500 }) } };
const container = document.body.appendChild(document.createElement('div'));
const viewer = { container, canvas: { getBoundingClientRect: () => ({ left: 500, top: 500 }) } };
let pose = { position: { x: 0, y: 0, z: 0 }, direction: { x: 1, y: 0, z: 0 } };
const projected = [];
// The renderer's canvas, not the viewer's, places the card.
@@ -454,14 +553,18 @@ test('a shown card follows its anchor through the renderer ports', () => {
},
},
});
const media = createBhoteKoshiEmbeddedMedia({ viewer, documentRef, globalRef: {} });
const media = createBhoteKoshiEmbeddedMedia({ viewer, documentRef: document, globalRef: {} });
const root = container.firstElementChild;
root.getBoundingClientRect = () => ({ left: 0, top: 0, right: 1000, bottom: 800, width: 1000, height: 800 });
assert.deepEqual([...listeners].map(([phase]) => phase), ['postRender']);
const anchor = { x: 10, y: 0, z: 0 };
assert.equal(media.show({ observation: { title: 'Clip', media: { sourceUrl: 'https://youtu.be/DbqRexFxv3k' } }, anchor }), true);
const card = documentRef.body.children[0].children.find((node) => node.tag === 'section');
const card = root.querySelector('section');
assert.equal(card.hidden, false);
assert.equal(projected.at(-1), anchor);
assert.equal(card.style.left, `${300 + 10 + 42}px`);
// The leader runs from the anchor to the card's near edge.
assert.equal(card.querySelector('path').getAttribute('d'), `M ${300 + 10 - 352} ${200 + 5 - parseFloat(card.style.top)} L 0 ${Math.max(16, Math.min(360 - 16, 200 + 5 - parseFloat(card.style.top)))}`);
// Behind the eye: hidden on the next drawn frame.
pose = { ...pose, direction: { x: -1, y: 0, z: 0 } };
for (const [, cb] of listeners) cb();
+3 -2
View File
@@ -989,9 +989,10 @@ function createPanelRecords(event) {
textContent: t('▶ PLAY SCENE'),
hidden: true,
}),
// `pressed` is the button's pressed state; the view renders it as one.
cinematicButton: panelRecord({
textContent: t('◉ CINEMATIC'),
attributes: { 'aria-pressed': 'false' },
pressed: false,
}),
storyReplayButton: panelRecord({ textContent: t('↺ FULL STORY') }),
corridorButton: panelRecord(),
@@ -2860,7 +2861,7 @@ export function createBhoteKoshiEventLayer({
'textContent',
_cinematicActive ? t('■ RELEASE CAMERA') : t('◉ CINEMATIC'),
);
setElementAttribute(button, 'aria-pressed', String(_cinematicActive));
setElementProperty(button, 'pressed', _cinematicActive);
return true;
}
+4
View File
@@ -101,6 +101,7 @@ function eventPanel() {
get textContent() { return record().textContent; },
get hidden() { return record().hidden; },
get disabled() { return record().disabled; },
get pressed() { return record().pressed; },
get value() { return typed ?? record().value; },
set value(value) { typed = value; },
getAttribute: (name) => record().attributes[name] ?? null,
@@ -2711,6 +2712,8 @@ test('Bhote Koshi replay restores cinematic ownership unless the operator releas
play.dispatch('click');
assert.equal(layer.getCinematicState().active, true);
assert.equal(layer.getPlaybackState().progress, 0);
const cinematicControl = panel.querySelector('[data-action="cinematic"]');
assert.equal(cinematicControl.pressed, true, 'the cinematic button is pressed while it owns the camera');
assert.equal(layer.getPlaybackState().playing, true);
assert.equal(
body.children.some((element) => element.id === 'bhote-koshi-story-strap'),
@@ -2720,6 +2723,7 @@ test('Bhote Koshi replay restores cinematic ownership unless the operator releas
panel.querySelector('[data-action="cinematic"]').dispatch('click');
assert.equal(layer.getCinematicState().active, false);
assert.equal(viewer._test.cameraTransforms.length, 2);
assert.equal(cinematicControl.pressed, false, 'releasing the camera unpresses the button');
animationCallbacks[1](91001);
assert.equal(play.textContent, '↺ REPLAY');
const cameraLookCount = viewer._test.cameraLooks.length;
+8 -1
View File
@@ -38,7 +38,7 @@ function presentation(patch = {}) {
playSceneButton: record({ textContent: '▶ PLAY SCENE', hidden: true }),
cinematicButton: record({
textContent: '◉ CINEMATIC',
attributes: { 'aria-pressed': 'false' },
pressed: false,
}),
storyReplayButton: record({ textContent: '↺ FULL STORY' }),
corridorButton: record(),
@@ -156,6 +156,10 @@ test('a later presentation updates the controls in place', async (t) => {
disabled: true,
attributes: { 'aria-label': 'Play Global context' },
});
next.refs.cinematicButton = record({
textContent: '■ RELEASE CAMERA',
pressed: true,
});
next.refs.progressInput = record({ value: '250', hidden: true });
next.refs.imagerySection = record({ hidden: true });
store.publish(next);
@@ -164,6 +168,9 @@ test('a later presentation updates the controls in place', async (t) => {
assert.equal(play.textContent, '▶ PLAY SHOT');
assert.equal(play.disabled, true);
assert.equal(play.getAttribute('aria-label'), 'Play Global context');
const cinematic = $('[data-action="cinematic"]');
assert.equal(cinematic.getAttribute('aria-pressed'), 'true');
assert.equal(cinematic.textContent, '■ RELEASE CAMERA');
assert.ok(
$('#bhote-koshi-event-panel').classList.contains('bhote-event-scene-beat'),
);
+1 -1
View File
@@ -1,4 +1,4 @@
import { toRadians } from '../geo/index.js';
import { toRadians } from '../geo/vector.js';
import { findCamera } from '../render/rendererOf.js';
/** The camera port's pose, or null when there is none to read. */
+15 -1
View File
@@ -85,7 +85,9 @@ import {
} from '../cctvFocusRequest.js';
import {
ACTIVE_CAMERA_COLOR,
CAMERA_ICON,
IDLE_CAMERA_COLOR,
IDLE_CAMERA_ICON,
LIVE_CAMERA_COLOR,
} from '../layers/cctv/policy.js';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
@@ -353,7 +355,7 @@ test('default COVERAGE refresh materializes the active and visible camera frustu
}
});
test('camera icons are violet for video feeds, cyan for stills, amber when active', () => {
test('camera icons are violet for video feeds, green for stills, amber when active', () => {
const record = (id, feedType) => ({
camera: { ...UNCLAMPED_CAMERA, id, feedType, groundElevationM: 0 },
// Every catalog record is placed as it is made, and drawn there.
@@ -385,6 +387,18 @@ test('camera icons are violet for video feeds, cyan for stills, amber when activ
assert.deepEqual(color(activeVideo), ACTIVE_CAMERA_COLOR);
assert.equal(icons.item(activeVideo.camera.id).scale, 1.25);
assert.equal(icons.item(idleVideo.camera.id).scale, 1);
const image = (record) => icons.item(record.camera.id).image;
const idleImage = image(idleStill);
assert.equal(idleImage, IDLE_CAMERA_ICON);
assert.equal(image(activeVideo), CAMERA_ICON);
assert.equal(image(idleVideo), CAMERA_ICON);
idleStill.camera.feedType = 'hls';
refreshCoverageStyles();
assert.equal(image(idleStill), CAMERA_ICON);
idleStill.camera.feedType = 'image';
refreshCoverageStyles();
assert.equal(image(idleStill), idleImage);
} finally {
_setCctvCoverageStateForTest({ enabled: false });
unbind();
+2
View File
@@ -86,6 +86,8 @@ const RETRY_BASE_MS = 15_000;
const RETRY_MAX_MS = 5 * 60 * 1000;
export const CCTV_OVERLAY_SOURCE_ID = 'cctv';
/** The source a CCTV count marker takes clicks as. */
export const CCTV_COUNT_CARD_SOURCE_ID = 'cctv-count';
export const CCTV_THUMBNAIL_ALTITUDE_SCALE = Object.freeze({
fullEnd: CCTV_CARD_SCALE_FULL_M,
midEnd: CCTV_CARD_SCALE_MID_M,
+238
View File
@@ -0,0 +1,238 @@
import { fromDegrees } from '../geo/ellipsoid.js';
/** Exact below 1,000, then K with one decimal below 10K. Uses Latin digits in every locale. */
export function formatCameraCount(count) {
if (count < 1000) return String(count);
const thousands =
count < 10000 ? Math.round(count / 100) / 10 : Math.round(count / 1000);
return `${thousands}K`;
}
/** An empty cell and its on-screen picker candidate. */
export function createCameraCell(key) {
return {
key,
count: 0,
latSum: 0,
lonSum: 0,
heightSum: 0,
south: Infinity,
north: -Infinity,
west: Infinity,
east: -Infinity,
low: Infinity,
high: -Infinity,
winner: null,
rank: Infinity,
};
}
/** Accumulate one horizon-visible mount in its ground cell. */
export function addCellCamera(cell, camera) {
const { lat, lon, absoluteHeightM: height = 0 } = camera;
cell.count++;
// Integer sums make the mean independent of catalog order, to about a centimetre.
cell.latSum += Math.round(lat * 1e7);
cell.lonSum += Math.round(lon * 1e7);
cell.heightSum += Math.round(height * 100);
cell.south = Math.min(cell.south, lat);
cell.north = Math.max(cell.north, lat);
cell.west = Math.min(cell.west, lon);
cell.east = Math.max(cell.east, lon);
cell.low = Math.min(cell.low, height);
cell.high = Math.max(cell.high, height);
}
const wrapLongitude = (lon) => ((((lon + 180) % 360) + 360) % 360) - 180;
/** Mean longitude and latitude of a cell's mounts, in degrees. */
export function cellLonLat(cell) {
return {
lon: wrapLongitude(cell.lonSum / (1e7 * cell.count)),
lat: cell.latSum / (1e7 * cell.count),
};
}
/**
* Geographic mean of the mounts. Its height is the drawn ground under it
* when the cell carries one (`groundM`), since a camera nobody has looked at
* yet may still hold a catalog height far from the terrain; otherwise the
* mean mount height.
*/
export function cellCenter(cell) {
const { lon, lat } = cellLonLat(cell);
return fromDegrees(
lon,
lat,
Number.isFinite(cell.groundM)
? cell.groundM
: cell.heightSum / (100 * cell.count),
);
}
/** Half the east-west and north-south ground extent of a cell's mounts, in metres. */
export function cellHalfExtents(cell) {
// The parallel nearest the equator bounds the width of every row.
const parallel = (Math.max(0, cell.south, -cell.north) * Math.PI) / 180;
return {
halfWidthM: 0.5 * (cell.east - cell.west) * 111_320 * Math.cos(parallel),
halfHeightM: 0.5 * (cell.north - cell.south) * 111_320,
};
}
/** A padded sphere over the rectangle and every mount, centred at groundM
* when set, otherwise at the mid mount height. */
export function cellBounds(cell) {
const lat = (cell.north + cell.south) / 2;
const lon = wrapLongitude((cell.east + cell.west) / 2);
const height = Number.isFinite(cell.groundM)
? cell.groundM
: (cell.high + cell.low) / 2;
const { halfWidthM, halfHeightM } = cellHalfExtents(cell);
const halfWidth = Math.hypot(halfWidthM, halfHeightM);
const vertical = Math.max(cell.high - height, height - cell.low);
const radius = 1.2 * Math.hypot(halfWidth, vertical);
return { center: fromDegrees(lon, lat, height), radius: Math.max(1, radius) };
}
/** Add a whole ground cell to a marker, retaining the sums for a weighted mean. */
function addCell(target, cell) {
// Across the antimeridian a cell joins on the side of the group's mean.
const shift = target.count
? 360 *
Math.round(
(target.lonSum / target.count - cell.lonSum / cell.count) / 3.6e9,
)
: 0;
target.count += cell.count;
target.latSum += cell.latSum;
target.lonSum += cell.lonSum + shift * 1e7 * cell.count;
target.heightSum += cell.heightSum;
target.south = Math.min(target.south, cell.south);
target.north = Math.max(target.north, cell.north);
target.west = Math.min(target.west, cell.west + shift);
target.east = Math.max(target.east, cell.east + shift);
target.low = Math.min(target.low, cell.low);
target.high = Math.max(target.high, cell.high);
}
/** Visit the touching pills in this marker's bucket and its eight neighbors. */
function visitNeighbors(marker, grid, gap, visit) {
for (let col = -1; col <= 1; col++) {
for (let row = -1; row <= 1; row++) {
const bucket = grid.get(`${marker.col + col},${marker.row + row}`);
if (!bucket) continue;
for (const other of bucket) {
// Distance between the horizontal centre segments of the two pills.
const extra = marker.halfSegment + other.halfSegment;
const dx = Math.max(0, Math.abs(marker.x - other.x) - extra);
const dy = marker.y - other.y;
const reach = marker.radius + other.radius + gap;
if (dx * dx + dy * dy >= reach * reach) continue;
visit(other, dx * dx + dy * dy, reach);
}
}
}
}
/**
* Merge connected groups of overlapping horizontal pills. Each marker occupies
* one grid bucket. Even the widest pill can only touch its eight neighbors.
* A cell with one camera takes the footprint `sizeFor(1)` gives its icon and
* joins the nearest count it touches. Lone cameras never join each other
* or bridge two counts. A spread icon's `offsetPx` shifts its footprint sideways.
* A merged group lists its ground cells in `parts`.
* Ground cells stay intact for the camera picker and individual-icon pass.
*/
export function mergeCountCells(cells, project, sizeFor, gap) {
let columnWidth = 0;
let rowHeight = 0;
const markers = cells.map((cell) => {
const screen = project(cellCenter(cell));
const { width, height } = sizeFor(cell.count, cell);
columnWidth = Math.max(columnWidth, width + gap);
rowHeight = Math.max(rowHeight, height + gap);
// The view projector reuses its result object.
return {
cell,
x: screen ? screen.x + (cell.offsetPx ?? 0) : undefined,
y: screen?.y,
halfSegment: (width - height) / 2,
radius: height / 2,
};
});
const grid = new Map();
for (const marker of markers) {
if (!Number.isFinite(marker.x) || !Number.isFinite(marker.y)) continue;
marker.col = Math.floor(marker.x / columnWidth);
marker.row = Math.floor(marker.y / rowHeight);
const key = `${marker.col},${marker.row}`;
if (!grid.has(key)) grid.set(key, new Set());
marker.bucket = grid.get(key);
if (marker.cell.count > 1) marker.bucket.add(marker);
}
for (const marker of markers) {
if (marker.cell.count !== 1 || !marker.bucket) continue;
let best = Infinity;
visitNeighbors(marker, grid, gap, (other, distanceSquared, reach) => {
const clearance = Math.sqrt(distanceSquared) - reach;
if (clearance < best) {
best = clearance;
marker.nearest = other;
}
});
}
// Only counts were candidates for nearest. Now they can claim lone cameras.
for (const marker of markers)
if (marker.cell.count === 1) marker.bucket?.add(marker);
const members = [];
for (const seed of markers) {
if (seed.cell.count === 1 || !seed.bucket?.delete(seed)) continue;
members.length = 0;
members.push(seed);
for (const marker of members) {
if (marker.cell.count === 1) continue;
visitNeighbors(marker, grid, gap, (other) => {
if (other.cell.count === 1 && other.nearest !== marker) return;
other.bucket.delete(other);
members.push(other);
});
}
if (members.length === 1) {
seed.result = seed.cell;
} else {
const group = createCameraCell(seed.cell.key);
group.lone = [];
group.parts = [];
for (const { cell } of members) {
addCell(group, cell);
group.parts.push(...(cell.parts ?? [cell]));
if (cell.count === 1) group.lone.push(cell);
else if (cell.lone) group.lone.push(...cell.lone);
}
seed.result = group;
}
}
const groups = [];
for (const marker of markers) {
if (marker.result) groups.push(marker.result);
else if (!marker.bucket || marker.bucket.has(marker))
groups.push(marker.cell);
}
return groups;
}
/** Rebuild a group's count under its original key, keeping only the lone cameras in `keep`. */
export function withoutLoneCameras(group, keep = []) {
const counts = (group.parts ?? []).filter((cell) => cell.count > 1);
if (!counts.length) return null;
const core = createCameraCell(group.key);
core.parts = [...counts, ...keep];
if (keep.length) core.lone = [...keep];
for (const cell of core.parts) addCell(core, cell);
return core;
}
+216
View File
@@ -0,0 +1,216 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { fromDegrees } from '../geo/ellipsoid.js';
import { distance } from '../geo/vector.js';
import { getLocale, setLocale } from '../i18n/index.js';
import {
createCameraCell,
addCellCamera,
cellCenter,
cellBounds,
formatCameraCount,
mergeCountCells,
} from './cctvCellCounts.js';
test('camera counts use Latin digits and K notation whatever the UI language', () => {
const previous = getLocale();
const examples = [
[2, '2'],
[999, '999'],
[1000, '1K'],
[1150, '1.2K'],
[1687, '1.7K'],
[9960, '10K'],
[10000, '10K'],
[12345, '12K'],
[12500, '13K'],
[1000000, '1000K'],
];
try {
setLocale('ar');
for (const [count, label] of examples)
assert.equal(formatCameraCount(count), label);
} finally {
setLocale(previous);
}
});
test('the marker mean weights every mount and the flight bounds cover the outlier', () => {
const cameras = [
{ lon: 12, lat: 52, absoluteHeightM: 30 },
{ lon: 12, lat: 52, absoluteHeightM: 40 },
{ lon: 12.003, lat: 52.006, absoluteHeightM: 50 },
];
const cell = createCameraCell();
for (const camera of cameras) addCellCamera(cell, camera);
const expected = fromDegrees(12.001, 52.002, 40);
assert.ok(distance(cellCenter(cell), expected) < 0.001);
const bounds = cellBounds(cell);
for (const { lon, lat, absoluteHeightM } of cameras) {
assert.ok(
distance(bounds.center, fromDegrees(lon, lat, absoluteHeightM)) <
bounds.radius,
);
}
});
function mergeCounts(sizes, counts, positions) {
const cells = counts.map((count, i) => ({
...createCameraCell(String(i)),
count,
}));
let i = 0;
const groups = mergeCountCells(
cells,
() => positions[i++],
(count) => sizes[count],
4,
);
return { cells, groups };
}
test('stadiums merge by their own radii and segment lengths across grid boundaries', () => {
const sizes = {
2: { width: 28, height: 28 },
7350: { width: 80, height: 48 },
};
const check = (counts, positions, expected) => {
const { groups } = mergeCounts(sizes, counts, positions);
assert.deepEqual(
groups.map((cell) => cell.count),
expected,
);
assert.equal(
groups.reduce((sum, cell) => sum + cell.count, 0),
counts[0] + counts[1],
);
};
const origin = { x: 35, y: 37 };
// Mixed radii sum to 38. At 42 pixels vertically the gap is exactly clear.
check([2, 7350], [origin, { x: 35, y: 78 }], [7352]);
check([2, 7350], [origin, { x: 35, y: 79 }], [2, 7350]);
// The large pill's centre segment extends 16 pixels towards the circle.
check([7350, 2], [origin, { x: 92, y: 37 }], [7352]);
check([7350, 2], [origin, { x: 92, y: 49 }], [7350, 2]);
check([2, 2], [origin, { x: 70, y: 37 }], [2, 2]);
// Large pills can reach across a row boundary at their full diameter.
check([7350, 7350], [origin, { x: 35, y: 88 }], [14700]);
});
test('a lone camera joins a count it touches, and lone cameras alone stay apart', () => {
const sizes = {
1: { width: 24, height: 24 },
9: { width: 40, height: 40 },
};
const check = (counts, positions, expected) => {
const { cells, groups } = mergeCounts(sizes, counts, positions);
assert.deepEqual(
groups.map((cell) => cell.count),
expected,
);
// A lone camera that stays apart is still its own cell object.
assert.deepEqual(
groups.filter((cell) => cell.count === 1),
cells.filter((cell) => groups.includes(cell) && cell.count === 1),
);
};
const at = (x, y = 100) => ({ x, y });
// Radii 20 and 12: the four-pixel gap is clear at 36 pixels.
check([9, 1], [at(100), at(135)], [10]);
check([9, 1], [at(100), at(136)], [9, 1]);
check([1, 9], [at(135), at(100)], [10]);
// Overlapping icons with no count beside them stay two icons.
check([1, 1], [at(100), at(110)], [1, 1]);
// A count takes every lone camera it touches, on either side.
check([1, 9, 1], [at(70), at(100), at(130)], [11]);
// A lone camera that only touches another lone camera is left alone.
check([1, 1, 9], [at(40), at(70), at(100)], [1, 10]);
});
test('cells merged across the antimeridian stay at the antimeridian', () => {
for (const lon of [179.9, 179.99, 179.999]) {
for (const reversed of [false, true]) {
const east = createCameraCell('e');
const west = createCameraCell('w');
for (let i = 0; i < 2; i++) {
addCellCamera(east, { lon, lat: 0, absoluteHeightM: 0 });
addCellCamera(west, { lon: -lon, lat: 0, absoluteHeightM: 0 });
}
const cells = reversed ? [west, east] : [east, west];
const screens = [
{ x: 100, y: 100 },
{ x: 120, y: 100 },
];
let i = 0;
const [group, ...rest] = mergeCountCells(
cells,
() => screens[i++],
() => ({ width: 40, height: 40 }),
4,
);
assert.equal(rest.length, 0);
assert.equal(group.count, 4);
const expected = fromDegrees(180, 0, 0);
assert.ok(distance(cellCenter(group), expected) < 1000, `${lon}: centre`);
const bounds = cellBounds(group);
assert.ok(bounds.radius < 15_000, `${lon}: radius ${bounds.radius}`);
for (const l of [lon, -lon])
assert.ok(
distance(bounds.center, fromDegrees(l, 0, 0)) <= bounds.radius,
);
}
}
});
test('flight bounds on drawn ground still contain every mount', () => {
// Flat ellipsoid terrain (Re:Earth terrain failed), mounts at 1,800 m.
const flat = createCameraCell('k');
addCellCamera(flat, { lon: 10, lat: 46, absoluteHeightM: 1800 });
addCellCamera(flat, { lon: 10, lat: 46, absoluteHeightM: 1800 });
flat.groundM = 0;
const fb = cellBounds(flat);
assert.ok(
distance(fromDegrees(10, 46, 1800), fb.center) <= fb.radius,
'flat',
);
// Ravine: mounts 200 m apart at 600 m, the floor at 0 m between them.
const east = 10 + 200 / (111_320 * Math.cos((46 * Math.PI) / 180));
const ravine = createCameraCell('r');
addCellCamera(ravine, { lon: 10, lat: 46, absoluteHeightM: 600 });
addCellCamera(ravine, { lon: east, lat: 46, absoluteHeightM: 600 });
ravine.groundM = 0;
const rb = cellBounds(ravine);
for (const lon of [10, east])
assert.ok(
distance(fromDegrees(lon, 46, 600), rb.center) <= rb.radius,
'ravine',
);
});
test('a lone camera between two counts joins one of them and does not merge them', () => {
const sizes = { 1: { width: 24, height: 24 }, 9: { width: 40, height: 40 } };
const run = (counts, xs) =>
mergeCounts(
sizes,
counts,
xs.map((x) => ({ x, y: 100 })),
)
.groups.map((cell) => cell.count)
.sort((a, b) => a - b);
assert.deepEqual(run([9, 9], [70, 130]), [9, 9]);
for (const [counts, xs] of [
[
[9, 1, 9],
[70, 100, 130],
],
[
[1, 9, 9],
[100, 70, 130],
],
[
[9, 9, 1],
[70, 130, 100],
],
])
assert.deepEqual(run(counts, xs), [9, 10], String(counts));
});
+254
View File
@@ -0,0 +1,254 @@
import { afterEach, beforeEach, test } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { bindRenderer } from '../render/rendererOf.js';
import { fakeCameraPort } from '../testSupport/fakeCameraPort.mjs';
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
import cctvLayer, {
_cctvIconsForTest,
_setCctvCoverageStateForTest,
refreshHorizonCulling,
} from './cctv.js';
const WIDTH = 800;
const HEIGHT = 600;
const bindings = [];
beforeEach(() => {
globalThis.document = {
createElement: () => ({
getContext: () => ({
measureText: (text) => ({
width: text.length * 8,
actualBoundingBoxAscent: 4,
actualBoundingBoxDescent: 4,
}),
}),
}),
};
});
afterEach(() => {
delete globalThis.document;
for (const unbind of bindings.splice(0)) unbind();
});
function recordsAt(lonLats, height = 10) {
return lonLats.map(([lon, lat], index) => {
const position = Cesium.Cartesian3.fromDegrees(lon, lat, height);
return {
camera: {
id: `cam-${String(index).padStart(4, '0')}`,
name: `Camera ${index}`,
city: 'Test',
lat,
lon,
headingDeg: 0,
pitchDeg: -18,
fovDeg: 44,
rangeM: 145,
mountHeightM: 8,
absoluteHeightM: height,
},
position: { x: position.x, y: position.y, z: position.z },
groundSamples: {},
groundResolved: {},
coverageEntities: [],
projection: null,
};
});
}
const plain = ({ x, y, z }) => ({ x, y, z });
function lookingAt(eye, target, ports = {}) {
const direction = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.subtract(target, eye, new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
);
const right = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.cross(direction, eye, new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
);
const up = Cesium.Cartesian3.cross(right, direction, new Cesium.Cartesian3());
return {
viewer: viewerWithAxes(eye, direction, right, up, ports),
direction,
right,
up,
};
}
function topDown(height, ports = {}) {
const eye = Cesium.Cartesian3.fromDegrees(0, 0, height);
return viewerWithAxes(
eye,
{ x: -1, y: 0, z: 0 },
{ x: 0, y: 1, z: 0 },
{ x: 0, y: 0, z: 1 },
ports,
);
}
function viewerWithAxes(eye, direction, right, up, ports) {
const carto = Cesium.Cartographic.fromCartesian(eye);
const { port } = fakeCameraPort({
pose: {
lon: Cesium.Math.toDegrees(carto.longitude),
lat: Cesium.Math.toDegrees(carto.latitude),
height: carto.height,
position: plain(eye),
direction: plain(direction),
up: plain(up),
right: plain(right),
fovy: Math.PI / 3,
aspectRatio: WIDTH / HEIGHT,
near: 0.1,
far: 5e8,
},
});
const viewer = {};
bindings.push(
bindRenderer(viewer, {
camera: port,
canvas: { clientWidth: WIDTH, clientHeight: HEIGHT },
draw: fakeDrawPort(),
...ports,
}),
);
return viewer;
}
/** Pinhole projection, as the layer's projector. */
function project(view, eye, point) {
const d = Cesium.Cartesian3.subtract(point, eye, new Cesium.Cartesian3());
const z = Cesium.Cartesian3.dot(d, view.direction);
const t = Math.tan(Math.PI / 6);
const x = Cesium.Cartesian3.dot(d, view.right) / z / (t * (WIDTH / HEIGHT));
const y = Cesium.Cartesian3.dot(d, view.up) / z / t;
return { x: (0.5 + x / 2) * WIDTH, y: (0.5 - y / 2) * HEIGHT, z };
}
for (const [label, horizontalM, aboveM] of [
['100 m approach', 100, 4],
['800 m approach', 800, 50],
]) {
test(`a camera with a stale height is read even when it projects off the screen at ${label}`, () => {
const ground = 1872;
const records = recordsAt([
[0, 0],
[0, 0],
]);
// geoid fallback after a 429
for (const r of records)
r.groundPrior = { ellipsoid: 2, source: 'geoid-fallback' };
const mount = Cesium.Cartesian3.fromDegrees(0, 0, ground + 8);
const eye = Cesium.Cartesian3.fromDegrees(
0,
-horizontalM / 111_320,
ground + 8 + aboveM,
);
const reads = [];
const view = lookingAt(eye, mount, {
globe: { isGlobeVisible: () => true },
query: {
sampleHeightNow(point) {
reads.push(point);
return ground;
},
},
});
_setCctvCoverageStateForTest({ viewer: view.viewer, records });
const stale = project(view, eye, records[0].position);
const truth = project(view, eye, mount);
assert.ok(stale.y > HEIGHT * 2);
assert.ok(truth.y > 0 && truth.y < HEIGHT);
refreshHorizonCulling();
refreshHorizonCulling();
assert.equal(records[0].groundPrior.ellipsoid, ground);
assert.ok(reads.length > 0, 'the stale camera was never read');
});
}
test('cameras off the visible screen cannot spend the whole terrain read budget', () => {
// 300 cameras with no prior around the screen edge, tiles not loaded; the
// 301st at the screen centre over a loaded tile.
const lonLats = [];
for (let i = 0; i < 300; i++) {
const a = (i / 300) * 2 * Math.PI;
// ~ 0.8 screen widths out at 200 m altitude (screen ~ 307 m wide)
lonLats.push([
(Math.cos(a) * 250) / 111_320,
(Math.sin(a) * 190) / 111_320,
]);
}
lonLats.push([0, 0]);
const records = recordsAt(lonLats);
const perPass = [];
let reads;
const viewer = topDown(200, {
globe: { isGlobeVisible: () => true },
query: {
sampleHeightNow(point) {
reads.push(point);
return Math.abs(point.lon) < 1e-9 && Math.abs(point.lat) < 1e-9
? 40
: null;
},
},
});
_setCctvCoverageStateForTest({ viewer, records });
for (let pass = 0; pass < 3; pass++) {
reads = [];
refreshHorizonCulling();
perPass.push(reads.length);
}
const last = records.at(-1);
assert.equal(last.groundPrior?.ellipsoid, 40);
assert.ok(perPass.every((n) => n <= 300));
});
test("the active camera's icon moves beside a count that would cover it", () => {
const records = recordsAt([
[0, 0],
[0, 0],
[0, 0],
]);
const viewer = topDown(20_000);
_setCctvCoverageStateForTest({ viewer, records, activeCameraId: 'cam-0000' });
refreshHorizonCulling();
const icons = _cctvIconsForTest();
const [marker] = cctvLayer._cctvDrawnForTest().counts.markers;
const metresPerPixel = ((2 * Math.tan(Math.PI / 6)) / HEIGHT) * 19_990;
const apartPx =
Cesium.Cartesian3.distance(marker.pos, icons.item('cam-0000').pos) /
metresPerPixel;
assert.ok(apartPx > marker.width / 2, 'the marker covers the active icon');
});
test('a lone camera just inside the grouping threshold joins the count beside it', () => {
const h = 740;
// mounts at 8 m mount height above a 0 m ground: positions at 10 m, eye at h+10
const records = recordsAt([
[0, 235 / 111_320],
[0, 255 / 111_320],
[0, 255 / 111_320],
]);
for (const r of records) r.groundPrior = { ellipsoid: 2, source: 'reearth' };
const viewer = topDown(h + 10);
_setCctvCoverageStateForTest({ viewer, records });
refreshHorizonCulling();
const icons = _cctvIconsForTest();
const markers = cctvLayer._cctvDrawnForTest().counts.markers;
assert.deepEqual(
markers.map((marker) => marker.cell.count),
[3],
);
assert.equal(
icons.item('cam-0000').show,
false,
'the near singleton still draws beside the count',
);
});
File diff suppressed because it is too large. Load diff
+36 -4
View File
@@ -154,6 +154,24 @@ export function pickContact(query, position, options = {}) {
let _overlayHitTest = null;
/** @type {WeakMap<object, {sourceId: string, entryId: string}|null>} */
const clickCards = new WeakMap();
const _clickClaims = new Map();
/**
* Register a target drawn outside the world overlay's entries, such as a CCTV
* count. A claim runs once per click where no card or label is painted above
* it and must not call `clickCard`.
* @param {string} layerId
* @param {(click: object) => ({sourceId: string, entryId: string}|null)} claim
*/
export function registerClickClaim(layerId, claim) {
if (!layerId || typeof claim !== 'function') return;
_clickClaims.set(layerId, claim);
}
/** Remove a layer's claim when it is disabled or destroyed. */
export function unregisterClickClaim(layerId) {
_clickClaims.delete(layerId);
}
/**
* Sets (or with null, clears) the hit test that names the card or label
@@ -166,8 +184,8 @@ export function setClickCardHitTest(hitTest) {
}
/**
* The topmost interactive card or label painted at a click, read once per
* click so every handler of it sees the same one whatever ran first.
* The topmost interactive card or label painted at a click, or a target a
* layer claims (`registerClickClaim`). All handlers share one result per click.
* @param {{screenPosition?: {x: number, y: number}}|null|undefined} click
* @returns {{sourceId: string, entryId: string}|null}
*/
@@ -179,14 +197,28 @@ export function clickCard(click) {
try {
card = _overlayHitTest?.(at?.x, at?.y) ?? null;
} catch {
// a broken hit test must never break click handling
clickCards.set(click, null);
return null;
}
if (!card) {
// A claim that reads this click again cannot re-enter the claims loop.
clickCards.set(click, null);
for (const claim of _clickClaims.values()) {
try {
card = claim(click) ?? null;
} catch {
card = null;
}
if (card) break;
}
}
clickCards.set(click, card);
return card;
}
/**
* True when another layer's card or label is painted on top at a click. The
* True when another layer has the top card, label, or claimed target
* (`registerClickClaim`) at a click. The
* card on top takes the click: a scene item under it does not act, and is
* not empty space either, so the layer leaves its selection alone.
* @param {object} click The shared dispatcher event.
+41
View File
@@ -20,6 +20,8 @@ import {
clickCard,
isUnderOtherCard,
setClickCardHitTest,
registerClickClaim,
unregisterClickClaim,
} from './pickRegistry.js';
// ---------------------------------------------------------------------------
@@ -237,3 +239,42 @@ test("the card on top is read once per click, and only another layer's card coun
setClickCardHitTest(null);
}
});
test('a click claim is the card on top only where no card or label is painted', () => {
const event = (x) => ({ screenPosition: { x, y: 5 } });
let calls = 0;
registerClickClaim('counts', (click) => {
calls++;
return click.screenPosition.x === 4
? { sourceId: 'counts', entryId: 'k' }
: null;
});
try {
registerClickClaim('counts', null);
const click = event(4);
assert.equal(isUnderOtherCard(click), true);
assert.equal(isUnderOtherCard(click, ['counts']), false);
assert.equal(calls, 1);
assert.equal(clickCard(event(9)), null);
const quake = { sourceId: 'quake-card', entryId: 'q1' };
setClickCardHitTest(() => quake);
assert.deepEqual(clickCard(event(4)), quake);
assert.equal(calls, 2);
setClickCardHitTest(() => {
throw new Error('broken overlay hit test');
});
assert.equal(clickCard(event(4)), null);
assert.equal(calls, 2);
setClickCardHitTest(null);
unregisterClickClaim('counts');
assert.equal(clickCard(event(4)), null);
registerClickClaim('counts', () => {
throw new Error('broken claim');
});
assert.equal(clickCard(event(4)), null);
} finally {
unregisterClickClaim('counts');
setClickCardHitTest(null);
}
});
+1 -1
View File
@@ -229,7 +229,7 @@ export function createCards({ state: layerState, services, parts, source }) {
let rank = 0;
const push = (id, { pinned = false, active = false } = {}) => {
const record = layerState._recordById.get(id);
if (!record?.position) return;
if (!record?.position || (!active && record.viewGrouped)) return;
entries.push(
createCctvThumbnailOverlayEntry({
id,
+2 -1
View File
@@ -219,7 +219,8 @@ export function createControls({ state: layerState, services, parts, source }) {
for (let i = start; i < records.length; i += stride) {
const camera = records[i].camera;
objects.push({
position: records[i].position,
// A camera sharing its mount is drawn beside its mates.
position: records[i].spreadPosition ?? records[i].position,
sourceId: camera.id,
// Short semantic code where the id is opaque (see cameraDisplayCode).
id: `CAM-${camera.code || camera.id}`,
+430
View File
@@ -0,0 +1,430 @@
import {
cellCenter,
cellLonLat,
formatCameraCount,
mergeCountCells,
withoutLoneCameras,
} from '../../data/cctvCellCounts.js';
import { WORLD_OVERLAY_STYLE } from '../../overlays/worldOverlayTokens.js';
import {
CAMERA_GREEN,
COUNT_CAMERA_ICON,
CAMERA_ICON_PX,
COUNT_MERGE_GAP_PX,
} from './policy.js';
import { liftedForHorizon } from '../../geo/horizon.js';
// Diameter at one camera before applying the size limits, in CSS pixels.
const COUNT_BASE_PX = 38;
// Extra diameter for each tenfold increase in camera count.
const COUNT_PX_PER_DECADE = 5;
// Minimum height of a count marker in CSS pixels.
const COUNT_MIN_HEIGHT_PX = 40;
// Maximum height of a count marker in CSS pixels.
const COUNT_MAX_HEIGHT_PX = 58;
// Clear fill between the count and the inside of the ring, in CSS pixels.
const COUNT_TEXT_PADDING_PX = 6;
// Height of the camera glyph in the smallest and the largest marker.
const COUNT_GLYPH_MIN_PX = 7.5;
const COUNT_GLYPH_MAX_PX = 10;
// Clear fill above the glyph in the smallest and the largest marker.
const COUNT_GLYPH_TOP_MIN_PX = 3;
const COUNT_GLYPH_TOP_MAX_PX = 4;
// Clear fill between the glyph's top corners and the inside of the ring.
const COUNT_GLYPH_PADDING_PX = 2;
// The middle of the digits sits this share of the inner radius below the
// marker's centre, which leaves the glyph clear of the count.
const COUNT_LABEL_DROP = 0.2;
// Merge passes per view. A merged centre and wider label can reach a further
// marker. The cap bounds work on motion ticks.
const COUNT_MERGE_PASSES = 3;
const FONT = WORLD_OVERLAY_STYLE.fontTitle;
// Reserve the camera's landscape slot even while the map sprite is loading.
const GLYPH_ASPECT = 1.5;
const RING_PX = 2;
const RIM_PX = 1;
const STROKE_INSET = RIM_PX + RING_PX / 2;
// Painted bounds of the camera art, scaled from its viewBox to source pixels.
const GLYPH_SOURCE = [3.4, 13.4, 28.1, 19.5].map((v) => (v * 48) / 36);
const GLYPH_SOURCE_ASPECT = 28.1 / 19.5;
/** Merged camera groups and their last painted hit rectangles in CSS pixels. */
export function createCountMarkers(
registerPaintLane,
id,
refreshView,
keyholeAlpha,
) {
let hardUi = null;
let sprite = null;
let spriteReady = false;
const markers = [];
const hits = [];
const textMetrics = new Map();
const fonts = globalThis.document?.fonts;
let measureCtx;
let hitCount = 0;
const lane = registerPaintLane?.('ambient-label', paint, {
id,
active: false,
target: 'shared',
});
function loadSprite() {
if (sprite || typeof Image === 'undefined') return;
sprite = new Image();
sprite.onload = () => {
spriteReady = true;
if (markers.length) lane?.requestPaint();
};
sprite.src = COUNT_CAMERA_ICON;
}
fonts?.addEventListener?.('loadingdone', fontsLoaded);
/** Font changes can widen a pill enough to merge it with its neighbor. */
function fontsLoaded() {
textMetrics.clear();
if (!markers.length) return;
refreshView();
lane?.requestPaint();
}
/** Seat the glyph under the top of the ring and the count just below centre. */
function sizeFor(count) {
const text = formatCameraCount(count);
let metrics = textMetrics.get(text);
if (!metrics) {
measureCtx ??= globalThis.document
.createElement('canvas')
.getContext('2d');
measureCtx.font = FONT;
measureCtx.textBaseline = 'middle';
metrics = measureCtx.measureText(text);
textMetrics.set(text, metrics);
}
const diameter = COUNT_BASE_PX + COUNT_PX_PER_DECADE * Math.log10(count);
const clamped = Math.max(
COUNT_MIN_HEIGHT_PX,
Math.min(COUNT_MAX_HEIGHT_PX, diameter),
);
const height = 2 * Math.round(clamped / 2);
const grown =
(height - COUNT_MIN_HEIGHT_PX) /
(COUNT_MAX_HEIGHT_PX - COUNT_MIN_HEIGHT_PX);
const glyphHeight =
COUNT_GLYPH_MIN_PX + (COUNT_GLYPH_MAX_PX - COUNT_GLYPH_MIN_PX) * grown;
const radius = height / 2 - RIM_PX - RING_PX;
const glyphTop =
COUNT_GLYPH_TOP_MIN_PX +
(COUNT_GLYPH_TOP_MAX_PX - COUNT_GLYPH_TOP_MIN_PX) * grown -
radius;
const ascent = metrics.actualBoundingBoxAscent;
const descent = metrics.actualBoundingBoxDescent;
const labelY = COUNT_LABEL_DROP * radius + (ascent - descent) / 2;
// Each row must clear the ring at the edge where the circle is narrowest.
const chordAt = (y) => 2 * Math.sqrt(Math.max(0, radius ** 2 - y ** 2));
const extra = Math.max(
0,
Math.ceil(
Math.max(
metrics.width + 2 * COUNT_TEXT_PADDING_PX - chordAt(labelY + descent),
glyphHeight * GLYPH_ASPECT +
2 * COUNT_GLYPH_PADDING_PX -
chordAt(glyphTop),
),
),
);
return {
text,
width: height + extra,
height,
glyphHeight,
glyphBottom: glyphTop + glyphHeight,
labelY,
};
}
/** Keep covered icons in the restored count if its new label clears the HUD. */
function retainCoveredCameras(group, core, project) {
const anchor = cellCenter(core);
const at = project(anchor);
if (!at) return core;
const { x, y } = at; // The projector reuses its result.
const size = sizeFor(core.count);
const halfSegment = (size.width - size.height) / 2;
const covered = group.lone.filter((lone) => {
const p = project(cellCenter(lone));
if (!p) return false;
// The pill outline that merging measures, without its gap.
const dx = Math.max(
0,
Math.abs(p.x + (lone.offsetPx ?? 0) - x) - halfSegment,
);
const reach = (size.height + (lone.iconPx ?? CAMERA_ICON_PX)) / 2;
return dx * dx + (p.y - y) ** 2 < reach * reach;
});
if (!covered.length) return core;
const { width, height } = sizeFor(core.count + covered.length);
if (hardUi({ x: x - width / 2, y: y - height / 2, w: width, h: height }))
return core;
const held = withoutLoneCameras(group, covered);
held.anchor = anchor;
held.groundM = core.groundM;
for (const lone of covered) lone.absorbed = true;
return held;
}
/**
* Reuse marker slots in ground-key order, and invalidate only changed frames.
* `groundHeight(lon, lat)` gives the drawn terrain in metres, or a non-finite
* value where it has not loaded. A count stands on that ground when available
* and otherwise uses its cameras' mean mount height.
*/
function update(cells, project, groundHeight = null) {
// Lone cameras take part so that one beside a count joins it.
let visible = cells.slice().sort((a, b) => a.key.localeCompare(b.key));
const footprint = (count, cell) => {
if (count > 1) return sizeFor(count);
const px = cell.iconPx ?? CAMERA_ICON_PX;
return { width: px, height: px };
};
/** A lone camera keeps its icon's own position; a count goes to ground. */
const ground = (list) => {
if (!groundHeight) return;
for (const cell of list) {
if (cell.count === 1 || cell.groundM !== undefined) continue;
const { lon, lat } = cellLonLat(cell);
const height = groundHeight(lon, lat);
cell.groundM = Number.isFinite(height) ? Math.round(height) : null;
}
};
for (
let pass = 0;
pass < COUNT_MERGE_PASSES &&
visible.length > 1 &&
visible.some((cell) => cell.count > 1);
pass++
) {
ground(visible);
const merged = mergeCountCells(
visible,
project,
footprint,
COUNT_MERGE_GAP_PX,
);
if (merged.length === visible.length) break;
visible = merged;
}
// A lone camera that is no longer its own entry now counts in a marker.
const apart = new Set(visible);
for (const cell of cells)
if (cell.count === 1) cell.absorbed = !apart.has(cell);
visible = visible.filter((cell) => cell.count > 1);
ground(visible);
let changed = visible.length !== markers.length;
for (let i = 0; i < visible.length; i++) {
let cell = visible[i];
// If the merged count is under the HUD, restore the count and its lone icons.
if (hardUi && cell.lone?.length) {
const at = project(cellCenter(cell));
const { width, height } = sizeFor(cell.count);
const rect = at && {
x: at.x - width / 2,
y: at.y - height / 2,
w: width,
h: height,
};
if (rect && hardUi(rect)) {
for (const lone of cell.lone) lone.absorbed = false;
const core = withoutLoneCameras(cell);
if (core) {
ground([core]);
cell = retainCoveredCameras(cell, core, project);
cell.releasedAt = rect;
}
}
}
const marker = (markers[i] ??= { focus: 1 });
const last = marker.cell;
const size = sizeFor(cell.count);
if (
!last ||
last.count !== cell.count ||
last.latSum !== cell.latSum ||
last.lonSum !== cell.lonSum ||
last.heightSum !== cell.heightSum ||
last.groundM !== cell.groundM ||
last.anchor?.x !== cell.anchor?.x ||
last.anchor?.y !== cell.anchor?.y ||
last.anchor?.z !== cell.anchor?.z
) {
marker.pos = cell.anchor ?? cellCenter(cell);
marker.cullPos = liftedForHorizon(marker.pos);
marker.hudHidden = undefined;
changed = true;
}
changed ||=
size.text !== marker.text ||
size.width !== marker.width ||
size.glyphBottom !== marker.glyphBottom ||
size.labelY !== marker.labelY;
marker.cell = cell;
Object.assign(marker, size);
// Paint never grows the hit buffer, even when a pan reveals every group.
hits[i] ??= {};
}
markers.length = visible.length;
if (markers.length) loadSprite();
// Keep the last frame pickable until the host clears its pixels.
lane?.setActive(markers.length > 0 || hitCount > 0);
if (changed) lane?.requestPaint();
}
/** Draw at device density using the host's CSS-pixel transform and projection. */
function paint(frame) {
hardUi = frame.overlapsHardUi ?? hardUi;
if (!markers.length) {
// Deactivating invalidates the host, so finish the shared frame first.
if (hitCount) queueMicrotask(deactivateIfEmpty);
hitCount = 0;
return;
}
hitCount = 0;
const { ctx, occluder, viewProjectionMatrix: m } = frame;
let refresh = false;
ctx.save();
try {
ctx.font = FONT;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
for (let i = 0; i < markers.length; i++) {
const marker = markers[i];
// The core can stay visible while the HUD uncovers the merged count.
if (marker.cell.releasedAt) refresh ||= !hardUi(marker.cell.releasedAt);
const { height } = marker;
const { x: px, y: py, z: pz } = marker.pos;
const w = m[3] * px + m[7] * py + m[11] * pz + m[15];
if (!(w > 0) || (occluder && !occluder.isPointVisible(marker.cullPos)))
continue;
const x =
(0.5 + (0.5 * (m[0] * px + m[4] * py + m[8] * pz + m[12])) / w) *
frame.width;
const y =
(0.5 - (0.5 * (m[1] * px + m[5] * py + m[9] * pz + m[13])) / w) *
frame.height;
const rect = hits[hitCount];
rect.x = x - marker.width / 2;
rect.y = y - height / 2;
rect.w = marker.width;
rect.h = height;
if (
rect.x >= frame.width ||
rect.y >= frame.height ||
rect.x + rect.w <= 0 ||
rect.y + rect.h <= 0
)
continue;
const hidden = Boolean(hardUi?.(rect));
const previous = marker.hudHidden;
if (previous !== hidden) {
marker.hudHidden = hidden;
// The active icon steps aside only for visible counts beside it.
refresh ||=
((hidden || previous !== undefined) && marker.besideActive) ||
marker.cell.lone?.some((cell) => cell.absorbed === hidden);
}
if (hidden) continue;
const fade =
frame.keyhole && keyholeAlpha ? keyholeAlpha(x, y, frame.keyhole) : 1;
if (!(fade > 0)) continue;
ctx.globalAlpha = marker.focus * fade;
ctx.beginPath();
ctx.roundRect(
rect.x + STROKE_INSET,
rect.y + STROKE_INSET,
rect.w - 2 * STROKE_INSET,
height - 2 * STROKE_INSET,
height / 2 - STROKE_INSET,
);
ctx.strokeStyle = 'rgba(8, 14, 20, 0.85)';
ctx.lineWidth = RING_PX + 2 * RIM_PX;
ctx.stroke();
ctx.fillStyle = '#0e1720';
ctx.fill();
ctx.strokeStyle = CAMERA_GREEN;
ctx.lineWidth = RING_PX;
ctx.stroke();
ctx.fillStyle = CAMERA_GREEN;
if (spriteReady) {
const width = marker.glyphHeight * GLYPH_SOURCE_ASPECT;
ctx.drawImage(
sprite,
...GLYPH_SOURCE,
x - width / 2,
y + marker.glyphBottom - marker.glyphHeight,
width,
marker.glyphHeight,
);
}
ctx.fillText(marker.text, x, y + marker.labelY);
rect.cell = marker.cell;
hitCount++;
}
} finally {
ctx.restore();
}
if (refresh) queueMicrotask(refreshView);
}
/** Resolve the topmost group actually painted at this screen position. */
function pickedCell(point) {
if (!point) return null;
for (let i = hitCount - 1; i >= 0; i--) {
const rect = hits[i];
const radius = rect.h / 2;
// Distance from the pill's horizontal centre segment.
const dx = Math.max(
0,
Math.abs(point.x - (rect.x + rect.w / 2)) - (rect.w - rect.h) / 2,
);
const dy = point.y - (rect.y + radius);
if (dx * dx + dy * dy <= radius * radius) return rect.cell;
}
return null;
}
/** A new group may already have arrived since the empty frame. */
function deactivateIfEmpty() {
if (!markers.length) lane?.setActive(false);
}
/** Release the visible groups and clear their hit targets immediately. */
function hide() {
markers.length = hits.length = hitCount = 0;
lane?.setActive(false);
}
/** Unhook this viewer's painter and its font listener. */
function dispose() {
hide();
fonts?.removeEventListener?.('loadingdone', fontsLoaded);
lane?.unregister();
}
return {
markers,
update,
pickedCell,
hide,
dispose,
requestPaint: () => lane?.requestPaint(),
};
}
+179
View File
@@ -0,0 +1,179 @@
import { test, beforeEach, afterEach } from 'node:test';
import assert from 'node:assert/strict';
import { createCountMarkers } from './countMarkers.js';
import { addCellCamera, createCameraCell } from '../../data/cctvCellCounts.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { horizonFrom } from '../../geo/horizon.js';
const W = 800;
const H = 600;
const A = 6378137;
// Screen x = W/2 + ecefY/30, y = H/2 - ecefZ/30 (as the view-thinning fixture).
const project = (p) => ({ x: W / 2 + p.y / 30, y: H / 2 - p.z / 30 });
const lonFor = (x) => (Math.asin(((x - W / 2) * 30) / A) * 180) / Math.PI;
const matrix = new Float64Array([
0,
0,
0,
0,
2 / (30 * W),
0,
0,
0,
0,
2 / (30 * H),
0,
0,
0,
0,
0,
1,
]);
function cellAt(key, x, count, height = 0) {
const cell = createCameraCell(key);
for (let i = 0; i < count; i++)
addCellCamera(cell, { lon: lonFor(x), lat: 0, absoluteHeightM: height });
return cell;
}
let painter;
function makeCtx() {
return {
labels: [],
globalAlpha: 1,
save() {},
restore() {},
beginPath() {},
roundRect() {},
stroke() {},
fill() {},
drawImage() {},
fillText(text, x, y) {
this.labels.push({ text, x, y, alpha: this.globalAlpha });
},
};
}
function paint(overrides = {}) {
const ctx = makeCtx();
painter({
ctx,
width: W,
height: H,
dpr: 1,
viewProjectionMatrix: matrix,
occluder: { isPointVisible: () => true },
overlapsHardUi: () => false,
...overrides,
});
return ctx.labels;
}
function counts(refresh = () => {}, keyholeAlpha) {
return createCountMarkers(
(_lane, paintFn) => {
painter = paintFn;
return { requestPaint() {}, setActive() {}, unregister() {} };
},
'counts',
refresh,
keyholeAlpha,
);
}
beforeEach(() => {
globalThis.document = {
createElement: () => ({
getContext: () => ({
measureText: (text) => ({
width: text.length * 7,
actualBoundingBoxAscent: 4,
actualBoundingBoxDescent: 4,
}),
}),
}),
};
});
afterEach(() => {
delete globalThis.document;
});
test('a count on ground below the ellipsoid stays painted while its mounts are above the horizon', () => {
const m = counts();
m.update([cellAt('a', 400, 2, -20)], project, () => -30);
const eye = fromDegrees(-0.009, 0, 30); // about 1 km away, 30 m above the ellipsoid
const horizon = horizonFrom(eye);
assert.equal(horizon.isPointVisible(fromDegrees(lonFor(400), 0, -20)), true);
assert.equal(paint({ occluder: horizon }).length, 1);
});
test('a lone camera clear of the HUD keeps its icon when the count beside it is hidden', async () => {
const hud = { overlapsHardUi: (rect) => rect.x < 200 };
for (const paintedFirst of [true, false]) {
const cells = [cellAt('a', 200, 2), cellAt('b', 234, 1)];
const m = counts(() => m.update(cells, project));
if (paintedFirst) paint(hud);
m.update(cells, project);
const labels = paint(hud);
await Promise.resolve();
assert.ok(!cells[1].absorbed || labels.length > 0);
// Moving the HUD at rest also changes whether the lone icon is needed.
paint();
await Promise.resolve();
assert.equal(cells[1].absorbed, true);
paint(hud);
await Promise.resolve();
assert.equal(cells[1].absorbed, false);
m.dispose();
}
});
test('a count stays visible when a lone camera would move it under the HUD', async () => {
const cells = [cellAt('a', 200, 2), cellAt('b', 234, 1)];
const hud = { overlapsHardUi: (rect) => rect.x + rect.w > 225 };
const m = counts(() => m.update(cells, project));
paint(hud);
m.update(cells, project);
assert.equal(paint(hud)[0]?.text, '2');
assert.equal(cells[1].absorbed, false);
await Promise.resolve();
paint(hud);
await Promise.resolve();
paint();
await Promise.resolve();
assert.equal(cells[1].absorbed, true);
assert.equal(paint()[0]?.text, '3');
m.dispose();
});
test('a restored count includes the lone camera it still covers at the HUD edge', async () => {
const cells = [cellAt('a', 200, 2), cellAt('b', 206, 1)];
const hud = { overlapsHardUi: (rect) => rect.x + rect.w > 221 };
const scratch = {};
const update = () =>
m.update(cells, (p) => Object.assign(scratch, project(p)));
const m = counts(update);
update();
assert.equal(Math.round(paint()[0].x), 202);
paint(hud);
await Promise.resolve();
const [marker] = paint(hud);
assert.equal(marker?.text, '3');
assert.equal(Math.round(marker.x), 200);
assert.equal(cells[1].absorbed, true);
assert.ok(m.pickedCell({ x: 206, y: 300 }).parts.includes(cells[1]));
paint();
await Promise.resolve();
assert.equal(Math.round(paint()[0].x), 202);
m.dispose();
});
test('counts fade with the Scope keyhole like the callouts', () => {
const m = counts(undefined, (_x, _y, keyhole) => keyhole.alpha);
m.update([cellAt('a', 400, 2)], project);
assert.equal(paint({ keyhole: { alpha: 0.25 } })[0].alpha, 0.25);
assert.deepEqual(paint({ keyhole: { alpha: 0 } }), []);
assert.equal(m.pickedCell({ x: 400, y: 300 }), null);
assert.equal(paint()[0].alpha, 1);
});
@@ -0,0 +1,76 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { bindRenderer } from '../../render/rendererOf.js';
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
import {
addCellCamera,
createCameraCell,
mergeCountCells,
} from '../../data/cctvCellCounts.js';
import { createNavigation } from './navigation.js';
const M = 111_320;
// Cesium's default 60 degree field of view spans the wider side, so a 4:3
// window has a vertical fovy of about 46.8 degrees. Two pairs 50 km and 80 km
// east of an eye 800 m up merge into one count. At half the distance all four
// fit in the frame (the group is wide, not tall), so the flight must keep all
// four in frame instead of approaching only the near pair.
test('a count click on an east-west group that fits keeps every member in the frame', () => {
const viewer = {};
const flights = [];
const aspectRatio = 800 / 600;
const fovy = 2 * Math.atan(Math.tan(Math.PI / 6) / aspectRatio);
const unbind = bindRenderer(viewer, {
camera: {
pose: () => ({ fovy, aspectRatio, position: fromDegrees(0, 0, 800) }),
flyToBounds: (bounds, options) => flights.push({ bounds, options }),
},
canvas: { clientHeight: 600, clientWidth: 800 },
});
try {
const members = [];
const cells = [50_000, 80_000].map((start) => {
const cell = createCameraCell(String(start));
for (const eastM of [start, start + 10]) {
const lon = eastM / M;
addCellCamera(cell, { lat: 0, lon, absoluteHeightM: 8 });
members.push(lon);
}
return cell;
});
const screens = [
{ x: 400, y: 300 },
{ x: 433, y: 300 },
];
const groups = mergeCountCells(
cells,
() => screens.shift(),
() => ({ width: 40, height: 40 }),
2,
);
assert.equal(groups.length, 1);
assert.equal(groups[0].count, 4);
// Reference: a north-up top-down frame at half the distance holds all four.
const halfwayM = 65_005 / 2;
const refHalfX = halfwayM * Math.tan(fovy / 2) * aspectRatio;
assert.ok(members.every((lon) => Math.abs(lon * M - 65_005) <= refHalfX));
createNavigation({ state: { _viewer: viewer }, parts: {} }).zoomToCell(
groups[0],
);
assert.equal(flights.length, 1);
const { range } = flights[0].options.offset;
const center = toLonLatH(flights[0].bounds.center);
const halfX = range * Math.tan(fovy / 2) * aspectRatio;
const inFrame = members.filter(
(lon) => Math.abs((lon - center.lon) * M) <= halfX,
);
assert.equal(
inFrame.length,
4,
`only ${inFrame.length} of 4 members in frame (range ${Math.round(range)} m)`,
);
} finally {
unbind();
}
});
@@ -0,0 +1,67 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { bindRenderer } from '../../render/rendererOf.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { distance } from '../../geo/vector.js';
import {
addCellCamera,
createCameraCell,
mergeCountCells,
} from '../../data/cctvCellCounts.js';
import { createNavigation } from './navigation.js';
// A count of four merged in a tilted view: two pairs 10 km and 40 km north of
// an eye 800 m up. After the click, at least one member must be in frame.
test('a count click from a tilted view keeps the group members in the frame', () => {
const viewer = {};
const flights = [];
const fovy = Math.PI / 3;
const aspectRatio = 800 / 600;
const unbind = bindRenderer(viewer, {
camera: {
pose: () => ({ fovy, aspectRatio, position: fromDegrees(0, 0, 800) }),
flyToBounds: (bounds, options) => flights.push({ bounds, options }),
},
canvas: { clientHeight: 600, clientWidth: 800 },
});
try {
const metresPerDegree = 111_320;
const members = [];
const cells = [10_000, 40_000].map((start) => {
const cell = createCameraCell(String(start));
for (const northM of [start, start + 10]) {
const lat = northM / metresPerDegree;
addCellCamera(cell, { lat, lon: 0, absoluteHeightM: 8 });
members.push(fromDegrees(0, lat, 8));
}
return cell;
});
const screens = [
{ x: 400, y: 300 },
{ x: 433, y: 300 },
];
const groups = mergeCountCells(
cells,
() => screens.shift(),
() => ({ width: 40, height: 40 }),
2,
);
assert.equal(groups.length, 1);
assert.equal(groups[0].count, 4);
const state = { _viewer: viewer };
const navigation = createNavigation({ state, parts: {} });
navigation.zoomToCell(groups[0]);
assert.equal(flights.length, 1);
const { range, pitch } = flights[0].options.offset;
assert.equal(pitch, -Math.PI / 2);
const { center } = flights[0].bounds;
const halfSpanM = range * Math.tan(fovy / 2);
assert.ok(
members.some((point) => distance(point, center) <= halfSpanM),
'no member of the group is in the final frame',
);
assert.ok(range < distance(fromDegrees(0, 0, 800), center));
} finally {
unbind();
}
});
@@ -0,0 +1,69 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { bindRenderer } from '../../render/rendererOf.js';
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
import {
addCellCamera,
createCameraCell,
mergeCountCells,
} from '../../data/cctvCellCounts.js';
import { createNavigation } from './navigation.js';
const M = 111_320;
// A count of 40 cameras 40 km north of an eye 800 m up takes in a lone camera
// 10 km north that is drawn just below it. The click must not land on the lone
// camera alone: at least one of the 40 counted cameras must be in the frame.
test('a count click does not fly to a lone camera that joined the count', () => {
const viewer = {};
const flights = [];
const fovy = Math.PI / 3;
const aspectRatio = 800 / 600;
const unbind = bindRenderer(viewer, {
camera: {
pose: () => ({ fovy, aspectRatio, position: fromDegrees(0, 0, 800) }),
flyToBounds: (bounds, options) => flights.push({ bounds, options }),
},
canvas: { clientHeight: 600, clientWidth: 800 },
});
try {
const crowd = createCameraCell('crowd');
const counted = [];
for (let i = 0; i < 40; i++) {
const lat = (40_000 + i / 4) / M;
addCellCamera(crowd, { lat, lon: 0, absoluteHeightM: 8 });
counted.push(lat);
}
const lone = createCameraCell('lone');
addCellCamera(lone, { lat: 10_000 / M, lon: 0, absoluteHeightM: 8 });
const screens = [
{ x: 400, y: 300 },
{ x: 400, y: 330 },
];
const groups = mergeCountCells(
[crowd, lone],
() => screens.shift(),
(count) =>
count > 1 ? { width: 40, height: 40 } : { width: 24, height: 24 },
2,
);
assert.equal(groups.length, 1);
assert.equal(groups[0].count, 41);
createNavigation({ state: { _viewer: viewer }, parts: {} }).zoomToCell(
groups[0],
);
assert.equal(flights.length, 1);
const { range } = flights[0].options.offset;
const center = toLonLatH(flights[0].bounds.center);
const halfY = range * Math.tan(fovy / 2);
const inFrame = counted.filter(
(lat) => Math.abs((lat - center.lat) * M) <= halfY,
);
assert.ok(
inFrame.length > 0,
`none of the 40 counted cameras is in the frame (range ${Math.round(range)} m, centre ${Math.round(center.lat * M)} m north)`,
);
} finally {
unbind();
}
});
@@ -0,0 +1,65 @@
import * as picking from '../../data/pickRegistry.js';
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createSelection } from './selection.js';
function setup() {
let zooms = 0,
clicks = 0;
const selection = createSelection({
services: { activation: {}, picking },
state: {
_enabled: true,
_counts: { pickedCell: () => ({}) },
_cctvOverlayHost: { hitTest: () => null },
},
parts: {
navigation: { zoomToCell: () => zooms++ },
rendering: { extractPickedCameraId: () => null },
},
});
const click = selection.bindCctvWorldClickGesture(
{ onClick: (fn) => fn },
() => clicks++,
);
return { click, counts: () => [zooms, clicks] };
}
test('a click a painted overlay target took (Space Missions label) does not fly to the count', () => {
const { click, counts } = setup();
// What the dispatcher hands subscribers after an onOverlayClick handler returned true.
click({
screenPosition: { x: 20, y: 26 },
overlay: true,
topHit: { set: '', id: null, surface: false },
drawHit: null,
gesture: { travelPx: 0, durationMs: 20 },
});
assert.equal(
counts()[0],
0,
'count flight ran although an overlay target handled the click',
);
});
test("another layer's world-overlay card on top (clickCard) takes the click from the count", () => {
const { click, counts } = setup();
picking.setClickCardHitTest(() => ({
sourceId: 'earthquakes',
entryId: 'eq-1',
}));
try {
click({
screenPosition: { x: 20, y: 26 },
topHit: null,
drawHit: null,
gesture: { travelPx: 0, durationMs: 20 },
});
assert.ok(
picking.isUnderOtherCard({ screenPosition: { x: 1, y: 1 } }, ['cctv']),
);
assert.equal(counts()[0], 0, 'count flight ran under another layer card');
} finally {
picking.setClickCardHitTest(null);
}
});
@@ -0,0 +1,96 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { bindRenderer } from '../../render/rendererOf.js';
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
import {
addCellCamera,
createCameraCell,
mergeCountCells,
} from '../../data/cctvCellCounts.js';
import { createNavigation } from './navigation.js';
const M = 111_320;
function run({ aspectRatio, fovy, eye, pairs, groundM }) {
const viewer = {};
const flights = [];
const unbind = bindRenderer(viewer, {
camera: {
pose: () => ({ fovy, aspectRatio, position: eye }),
flyToBounds: (bounds, options) => flights.push({ bounds, options }),
},
canvas: { clientHeight: 600, clientWidth: Math.round(600 * aspectRatio) },
});
try {
const members = [];
const cells = pairs.map(({ eastM = 0, northM = 0, h }, i) => {
const cell = createCameraCell(String(i));
for (const d of [0, 10]) {
const m = { lon: (eastM + d) / M, lat: northM / M, h };
addCellCamera(cell, { lat: m.lat, lon: m.lon, absoluteHeightM: h });
members.push(m);
}
cell.groundM = h;
return cell;
});
const screens = [
{ x: 400, y: 300 },
{ x: 420, y: 300 },
];
const groups = mergeCountCells(
cells,
() => screens.shift(),
() => ({ width: 40, height: 40 }),
2,
);
assert.equal(groups.length, 1);
groups[0].groundM = groundM;
createNavigation({ state: { _viewer: viewer }, parts: {} }).zoomToCell(
groups[0],
);
const { range } = flights[0].options.offset;
const c = toLonLatH(flights[0].bounds.center);
const eyeH = c.height + range;
const tanY = Math.tan(fovy / 2);
const inFrame = members.filter((m) => {
const depth = eyeH - m.h;
if (!(depth > 0)) return false;
return (
Math.abs((m.lon - c.lon) * M) <= depth * tanY * aspectRatio &&
Math.abs((m.lat - c.lat) * M) <= depth * tanY
);
});
return { range, inFrame: inFrame.length, centerH: c.height };
} finally {
unbind();
}
}
test('a count click on pairs 300 m above the ground under the group centre keeps a member in the frame', () => {
const aspectRatio = 4 / 3;
const fovy = 2 * Math.atan(Math.tan(Math.PI / 6) / aspectRatio);
const r = run({
aspectRatio,
fovy,
eye: fromDegrees(0, 0, 900),
pairs: [
{ eastM: 3000, h: 800 },
{ eastM: 5000, h: 800 },
],
groundM: 500,
});
const flat = run({
aspectRatio,
fovy,
eye: fromDegrees(0, 0, 900),
pairs: [
{ eastM: 3000, h: 500 },
{ eastM: 5000, h: 500 },
],
groundM: 500,
});
assert.equal(flat.inFrame, 4);
assert.ok(r.inFrame > 0, `no member in frame: ${JSON.stringify(r)}`);
});
@@ -0,0 +1,84 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { bindRenderer } from '../../render/rendererOf.js';
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
import {
addCellCamera,
createCameraCell,
mergeCountCells,
} from '../../data/cctvCellCounts.js';
import { createNavigation } from './navigation.js';
const M = 111_320;
function run({ aspectRatio, fovy, eye, pairs, groundM }) {
const viewer = {};
const flights = [];
const unbind = bindRenderer(viewer, {
camera: {
pose: () => ({ fovy, aspectRatio, position: eye }),
flyToBounds: (bounds, options) => flights.push({ bounds, options }),
},
canvas: { clientHeight: 600, clientWidth: Math.round(600 * aspectRatio) },
});
try {
const members = [];
const cells = pairs.map(({ eastM = 0, northM = 0, h }, i) => {
const cell = createCameraCell(String(i));
for (const d of [0, 10]) {
const m = { lon: (eastM + d) / M, lat: northM / M, h };
addCellCamera(cell, { lat: m.lat, lon: m.lon, absoluteHeightM: h });
members.push(m);
}
cell.groundM = h;
return cell;
});
const screens = [
{ x: 400, y: 300 },
{ x: 420, y: 300 },
];
const groups = mergeCountCells(
cells,
() => screens.shift(),
() => ({ width: 40, height: 40 }),
2,
);
assert.equal(groups.length, 1);
groups[0].groundM = groundM;
createNavigation({ state: { _viewer: viewer }, parts: {} }).zoomToCell(
groups[0],
);
const { range } = flights[0].options.offset;
const c = toLonLatH(flights[0].bounds.center);
const eyeH = c.height + range;
const tanY = Math.tan(fovy / 2);
const inFrame = members.filter((m) => {
const depth = eyeH - m.h;
if (!(depth > 0)) return false;
return (
Math.abs((m.lon - c.lon) * M) <= depth * tanY * aspectRatio &&
Math.abs((m.lat - c.lat) * M) <= depth * tanY
);
});
return { range, inFrame: inFrame.length, centerH: c.height };
} finally {
unbind();
}
}
test('a count click on a north-south group in a 32:9 window keeps every member in the frame', () => {
const aspectRatio = 32 / 9;
const fovy = 2 * Math.atan(Math.tan(Math.PI / 6) / aspectRatio);
const r = run({
aspectRatio,
fovy,
eye: fromDegrees(0, 0, 800),
pairs: [
{ northM: 15_000, h: 8 },
{ northM: 17_000, h: 8 },
],
groundM: 8,
});
assert.equal(r.inFrame, 4, JSON.stringify(r));
});
+145
View File
@@ -0,0 +1,145 @@
import { test, beforeEach, afterEach } from 'node:test';
import assert from 'node:assert/strict';
import { createCountMarkers } from './countMarkers.js';
import { addCellCamera, createCameraCell } from '../../data/cctvCellCounts.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { horizonFrom } from '../../geo/horizon.js';
const W = 800;
const H = 600;
const A = 6378137;
// Screen x = W/2 + ecefY/30, y = H/2 - ecefZ/30 (as the view-thinning fixture).
const project = (p) => ({ x: W / 2 + p.y / 30, y: H / 2 - p.z / 30 });
const lonFor = (x) => (Math.asin(((x - W / 2) * 30) / A) * 180) / Math.PI;
const matrix = new Float64Array([
0,
0,
0,
0,
2 / (30 * W),
0,
0,
0,
0,
2 / (30 * H),
0,
0,
0,
0,
0,
1,
]);
function cellAt(key, x, count, height = 0, y = H / 2) {
const cell = createCameraCell(key);
for (let i = 0; i < count; i++)
addCellCamera(cell, {
lon: lonFor(x),
lat: (Math.asin(((H / 2 - y) * 30) / A) * 180) / Math.PI,
absoluteHeightM: height,
});
return cell;
}
let painter;
function makeCtx() {
return {
labels: [],
globalAlpha: 1,
save() {},
restore() {},
beginPath() {},
roundRect() {},
stroke() {},
fill() {},
drawImage() {},
fillText(text, x, y) {
this.labels.push({ text, x, y, alpha: this.globalAlpha });
},
};
}
function paint(overrides = {}) {
const ctx = makeCtx();
painter({
ctx,
width: W,
height: H,
dpr: 1,
viewProjectionMatrix: matrix,
occluder: { isPointVisible: () => true },
overlapsHardUi: () => false,
...overrides,
});
return ctx.labels;
}
function counts(refresh = () => {}, keyholeAlpha) {
return createCountMarkers(
(_lane, paintFn) => {
painter = paintFn;
return { requestPaint() {}, setActive() {}, unregister() {} };
},
'counts',
refresh,
keyholeAlpha,
);
}
beforeEach(() => {
globalThis.document = {
createElement: () => ({
getContext: () => ({
measureText: (text) => ({
width: text.length * 7,
actualBoundingBoxAscent: 4,
actualBoundingBoxDescent: 4,
}),
}),
}),
};
});
afterEach(() => {
delete globalThis.document;
});
// 75 counts in five staggered rows, no lone cameras and no active camera,
// pan right 7 CSS px per frame for 60 frames past a left HUD rail. Counts must
// still hide and reappear at the rail, but the paint must not start a full
// view pass on almost every frame: the motion timer passes the view every
// 250 ms, about 4 times in these 60 frames at 60 Hz.
test('a pan past the HUD edge does not pass the view on every frame', async () => {
const run = async (hud) => {
const cells = [];
for (let row = 0; row < 5; row++)
for (let col = 0; col < 15; col++)
cells.push(
cellAt(
`r${row}c${String(col).padStart(2, '0')}`,
30 + col * 50 + row * 10,
2,
0,
120 + row * 60,
),
);
let refreshes = 0;
let hiddenFrames = 0;
const m = counts(() => refreshes++);
m.update(cells, project);
for (let f = 0; f < 60; f++) {
const panned = matrix.slice();
panned[12] = (2 * (f * 7)) / W;
const labels = paint({ ...hud, viewProjectionMatrix: panned });
if (labels.length < 75) hiddenFrames++;
await Promise.resolve();
}
m.dispose();
return { refreshes, hiddenFrames };
};
const control = await run({});
const withHud = await run({ overlapsHardUi: (rect) => rect.x < 150 });
assert.equal(control.refreshes, 0);
assert.ok(withHud.hiddenFrames > 0, 'the HUD hides no count');
assert.ok(
withHud.refreshes <= 4,
`${withHud.refreshes} full view passes from paint in 60 frames`,
);
});
@@ -0,0 +1,59 @@
import * as picking from '../../data/pickRegistry.js';
import { CCTV_COUNT_CARD_SOURCE_ID } from '../../data/cctvCards.js';
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createSelection } from './selection.js';
// Earthquake discs (like fire perimeters and drone airspace) are deliberately
// unowned background fills. A clean tap on a count painted over a disc must
// zoom to the count and be the card on top for every layer, so Earthquakes
// opens no card. An owned scene object (an aircraft) still takes the click.
test('a count over an earthquake disc takes the click', () => {
let zooms = 0;
let clicks = 0;
const selection = createSelection({
services: { activation: {}, picking },
state: {
_enabled: true,
_counts: { pickedCell: () => ({ key: 'g' }) },
_cctvOverlayHost: { hitTest: () => null },
},
parts: {
navigation: { zoomToCell: () => zooms++ },
rendering: {
extractPickedCameraId: (hit) =>
hit?.set === 'cctv-icons' ? hit.id : null,
},
},
});
const click = selection.bindCctvWorldClickGesture(
{ onClick: (fn) => fn },
() => clicks++,
);
const event = (hit) => ({
screenPosition: { x: 20, y: 26 },
topHit: hit,
drawHit: hit,
hit,
gesture: { travelPx: 0, durationMs: 20 },
});
picking.registerClickClaim('cctv', selection.countClickCard);
picking.registerPickOwner('flights', (id) => id.startsWith('aircraft:'));
try {
const disc = event({ set: 'earthquakes:1:discs', id: 'earthquake:abc' });
assert.deepEqual(picking.clickCard(disc), {
sourceId: CCTV_COUNT_CARD_SOURCE_ID,
entryId: 'g',
});
click(disc);
assert.deepEqual([zooms, clicks], [1, 0]);
const aircraft = event({ set: 'flights:icons', id: 'aircraft:abc' });
assert.equal(picking.clickCard(aircraft), null);
click(aircraft);
assert.deepEqual([zooms, clicks], [1, 1]);
} finally {
picking.unregisterClickClaim('cctv');
picking.unregisterPickOwner('flights');
}
});
+77 -47
View File
@@ -1,4 +1,4 @@
import { fromDegrees } from '../../geo/ellipsoid.js';
import { fromDegreesInto } from '../../geo/ellipsoid.js';
import { findGlobe } from '../../render/rendererOf.js';
import {
SUPPORT_KEYS,
@@ -22,11 +22,12 @@ export function createGround({ state: layerState, services, parts, source }) {
* - `google-3d` — photoreal stack: globe hidden, the visible Google 3D
* tileset IS the surface → one-shot scene sampling refines.
* - `terrain-globe` — any globe stack: the Re:Earth point-height prior IS the
* resolution (zero scene queries).
* resolution. A camera the batch left unanswered takes the
* drawn terrain from the view pass (`adoptDrawnGround`).
*
* Only an explicit `false` (the photoreal stack hides the globe) selects
* `google-3d`; undefined/null (no viewer / torn down) must fall to the regime
* that never touches the scene. Pure — exported for the unit suite.
* that never samples the scene's tiles. Pure — exported for the unit suite.
* @param {boolean|undefined|null} globeShow - Whether the renderer shows the
* globe (`globe.isGlobeVisible()`).
* @returns {'google-3d'|'terrain-globe'}
@@ -214,56 +215,84 @@ export function createGround({ state: layerState, services, parts, source }) {
let applied = 0;
let moved = 0;
for (let i = 0; i < records.length && i < priors.length; i++) {
const record = records[i];
const prior = priors[i];
if (!record || !prior || !Number.isFinite(prior.ellipsoid)) continue;
// Stale-record guard: init() may have re-run (destroy/init cycle) while
// the batch was in flight — only touch records still live in the map.
if (layerState._recordById.get(record.camera.id) !== record) continue;
record.groundPrior = prior;
// Keep the cheap pre-enable altitude consistent for records whose
// geometry hasn't been applied yet (applyFrustumGeometry overwrites it).
if (!record.frustumPositions) {
record.camera.absoluteHeightM =
prior.ellipsoid + record.camera.mountHeightM;
}
// Cameras without geometry only move their icon onto the prior, so the
// view pass projects the right point; their frustums are built when
// they enter the view, as recomputing the whole catalog here would
// stall a large one.
if (!record.frustumGeometry) {
if (record.position) {
// In place: the record keeps its position object.
const { x, y, z } = fromDegrees(
record.camera.lon,
record.camera.lat,
record.camera.absoluteHeightM,
);
record.position.x = x;
record.position.y = y;
record.position.z = z;
parts.rendering.moveCameraIcon(record);
moved += 1;
}
continue;
}
const regime = currentSurfaceRegime();
if (regime === 'terrain-globe') {
// Prior IS the resolution — re-latch onto the fresh value.
parts.geometry.updateRecordGeometry(record, { sampleGround: false });
applied += 1;
} else if (!Number.isFinite(record.groundSamples['google-3d'])) {
// Still awaiting the shared floor: snap interim geometry onto the exact
// prior (pure recompute; the shared cell may refine later).
parts.geometry.applyFrustumGeometry(record, prior.ellipsoid);
applied += 1;
}
const outcome = applyGroundPrior(records[i], priors[i]);
if (outcome === 'moved') moved += 1;
else if (outcome === 'applied') applied += 1;
}
if (moved && parts.rendering.refreshHorizonCulling())
parts.geometryQueue.enqueueViewGeometry();
if (applied || moved) parts.presentation.notifyListeners();
}
/**
* Gives one live record a ground prior: `'moved'` when only its icon went
* onto the prior in place, `'applied'` when its geometry was recomputed,
* null when nothing changed. Pure recomputes, no scene queries.
*/
function applyGroundPrior(record, prior) {
if (!record || !prior || !Number.isFinite(prior.ellipsoid)) return null;
// Stale-record guard: init() may have re-run (destroy/init cycle) while
// the batch was in flight — only touch records still live in the map.
if (layerState._recordById.get(record.camera.id) !== record) return null;
// The drawn terrain beats a fallback. Only a real batch answer replaces it.
if (
prior.source === 'geoid-fallback' &&
record.groundPrior?.source === 'drawn-terrain'
)
return null;
record.groundPrior = prior;
// Keep the cheap pre-enable altitude consistent for records whose
// geometry hasn't been applied yet (applyFrustumGeometry overwrites it).
if (!record.frustumPositions) {
record.camera.absoluteHeightM =
prior.ellipsoid + record.camera.mountHeightM;
}
// Cameras without geometry only move their icon onto the prior, so the
// view pass projects the right point; their frustums are built when
// they enter the view, as recomputing the whole catalog here would
// stall a large one.
if (!record.frustumGeometry) {
if (!record.position) return null;
// In place: the record keeps its position object.
fromDegreesInto(
record.camera.lon,
record.camera.lat,
record.camera.absoluteHeightM,
record.position,
);
parts.rendering.moveCameraIcon(record);
return 'moved';
}
const regime = currentSurfaceRegime();
if (regime === 'terrain-globe') {
// Prior IS the resolution — re-latch onto the fresh value.
parts.geometry.updateRecordGeometry(record, { sampleGround: false });
return 'applied';
}
if (!Number.isFinite(record.groundSamples['google-3d'])) {
// Still awaiting the shared floor: snap interim geometry onto the exact
// prior (pure recompute; the shared cell may refine later).
parts.geometry.applyFrustumGeometry(record, prior.ellipsoid);
return 'applied';
}
return null;
}
/**
* Applies drawn terrain as a drawn-terrain prior. The read records the eye
* distance (rangeM), globe surface version (surface) and whether terrain
* loading had finished (settled). Reading from under half that range or
* receiving a later Re:Earth answer replaces the height.
* @returns {'moved'|'applied'|null} As `applyGroundPrior`.
*/
function adoptDrawnGround(record, heightM, read) {
return applyGroundPrior(record, {
ellipsoid: heightM,
source: 'drawn-terrain',
...read,
});
}
/**
* Task 5: surface-regime change handler ('gev:map-stack-changed'
* CustomEvent, dispatched by main.js from MapStackController.onChange). The
@@ -399,6 +428,7 @@ export function createGround({ state: layerState, services, parts, source }) {
resolveCommittedGroundAnchor,
resolveGroundPriors,
applyLateGroundPriors,
adoptDrawnGround,
handleMapStackChanged,
};
}
+64
View File
@@ -0,0 +1,64 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createGround } from './ground.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
function setup(record) {
const calls = { culling: 0, geometry: [], notify: 0 };
const state = {
_viewer: null,
_recordById: new Map([[record.camera.id, record]]),
};
const parts = {
rendering: {
refreshHorizonCulling: () => (calls.culling++, true),
moveCameraIcon() {},
},
geometryQueue: { enqueueViewGeometry() {} },
presentation: { notifyListeners: () => calls.notify++ },
geometry: {
// Same choice as geometry.updateRecordGeometry on a globe with a cold floor cell.
updateRecordGeometry(r) {
calls.geometry.push(
ground.groundPriorAltFor(r) + r.camera.mountHeightM,
);
},
},
};
const ground = createGround({
state,
services: {
ground: { resolveGroundFloorCells: async () => {} },
terrain: { resolveEllipsoidalGround: async () => [] },
},
parts,
});
return { ground, calls };
}
test('a late geoid fallback leaves a drawn-terrain height in place', () => {
const camera = {
id: 'a',
lat: 42,
lon: -118,
mountHeightM: 8,
absoluteHeightM: 1880,
};
const record = {
camera,
position: fromDegrees(camera.lon, camera.lat, 1880),
frustumGeometry: {},
frustumPositions: {},
groundSamples: {},
groundResolved: {},
groundPrior: { ellipsoid: 1872, source: 'drawn-terrain', rangeM: 2000 },
};
const { ground, calls } = setup(record);
ground.applyLateGroundPriors(
[record],
[{ ellipsoid: 0, source: 'geoid-fallback' }],
);
assert.equal(record.groundPrior.source, 'drawn-terrain');
assert.ok(!calls.geometry.includes(8), 'mount not lowered to the fallback');
});
+45 -6
View File
@@ -1,6 +1,6 @@
import { fromDegrees } from '../../geo/ellipsoid.js';
import { distance, dot } from '../../geo/vector.js';
import { canvasOf, findCamera } from '../../render/rendererOf.js';
import { canvasOf, findCamera, findGlobe } from '../../render/rendererOf.js';
import { viewshedColors, cameraHue } from '../../data/cctvViewshed.js';
import { CCTV_OVERLAY_SOURCE_ID } from '../../data/cctvCards.js';
import { GIZMO_ID_PREFIX } from '../../data/cctvGizmo.js';
@@ -23,8 +23,14 @@ export function createLifecycle({
source,
}) {
const { activateCctvCameraFromWorldClick } = services.activation;
const { resolvePickId, registerPickOwner, unregisterPickOwner, clickCard } =
services.picking;
const {
resolvePickId,
registerPickOwner,
unregisterPickOwner,
clickCard,
registerClickClaim,
unregisterClickClaim,
} = services.picking;
const { onFocusTargetAppear } = services.focus;
const { releaseContinuousRender } = services.render;
@@ -103,6 +109,30 @@ export function createLifecycle({
* listeners to its camera; one against the same viewer keeps them.
*/
function attachViewListeners() {
const globe = findGlobe(layerState._viewer);
if (layerState._surfaceListenerGlobe !== globe) {
layerState._surfaceListener?.();
layerState._surfaceListener = null;
layerState._surfaceListenerGlobe = globe;
}
if (!layerState._surfaceListener && globe?.on) {
// Refresh drawn heights when terrain finishes loading or the surface changes.
let version = globe.surfaceVersion?.();
let terrainPending = globe.isSettled?.('terrain') === false ? 1 : 0;
layerState._surfaceListener = globe.on('progress', (progress) => {
const next = globe.surfaceVersion?.();
const loaded = progress?.terrainPending === 0 && terrainPending !== 0;
const swapped = next !== version;
version = next;
terrainPending = progress?.terrainPending ?? terrainPending;
if (
(loaded || swapped) &&
layerState._enabled &&
!layerState._cameraMoving
)
settleView();
});
}
const viewCamera = findCamera(layerState._viewer);
if (
layerState._viewListenerCamera &&
@@ -140,6 +170,9 @@ export function createLifecycle({
/** Drop the move listeners; nothing reports the end of a move after it. */
function detachViewListeners() {
layerState._surfaceListener?.();
layerState._surfaceListener = null;
layerState._surfaceListenerGlobe = null;
layerState._horizonCullListener?.();
layerState._horizonCullListener = null;
layerState._moveStartListener?.();
@@ -163,9 +196,11 @@ export function createLifecycle({
layerState._records = [];
layerState._recordById = new Map();
layerState._viewRecords = [];
layerState._pickerRecords = [];
layerState._cameraIndexCache = null;
layerState._coverageVisibleIds = new Set();
layerState._neighborCountCache = null;
layerState._coverageCohort = null;
layerState._viewUnpublished = false;
layerState._viewPose = null;
layerState._viewMotionPass = null;
@@ -285,9 +320,8 @@ export function createLifecycle({
coverageEntities: [],
projection: null,
// Task 5 (height-datum fix): regime-aware ground resolution state.
// groundPrior — { ellipsoid, source } from the Re:Earth batch
// (null until a late batch lands). The prior applies in EVERY
// regime and is the terrain-globe resolution outright.
// groundPrior — { ellipsoid, source } from the Re:Earth batch, or
// drawn-terrain with its read conditions for an unanswered camera.
// groundResolved — PER-REGIME one-shot latch (regime key →
// boolean): true once this record's resolution completed for that
// regime; such records are excluded from the completion pass so
@@ -386,6 +420,7 @@ export function createLifecycle({
parts.rendering.refreshHorizonCulling();
const input = inputFor(layerState._viewer);
layerState._clickSubscription?.();
const unsubscribeClick = parts.selection.bindCctvWorldClickGesture(
input,
(event) => {
@@ -481,6 +516,7 @@ export function createLifecycle({
);
return Boolean(coverage && layerState._recordById.has(coverage[1]));
});
registerClickClaim?.('cctv', parts.selection.countClickCard);
if (!layerState._activeCameraId && layerState._records.length) {
layerState._activeCameraId = parts.navigation.openingCameraId();
layerState._autoHopSuspended = false;
@@ -517,6 +553,7 @@ export function createLifecycle({
services.credits?.hideOsmCredit?.(layerState._viewer, 'cctv');
layerState._enabled = false;
unregisterPickOwner('cctv');
unregisterClickClaim?.('cctv');
// ADJUST mode does not survive a layer toggle — predictable re-entry.
layerState._calibrationMode = false;
releaseContinuousRender('cctv-adjust');
@@ -532,6 +569,7 @@ export function createLifecycle({
parts.rendering.hideCctvVisuals();
// Nothing is in view while the layer is off.
layerState._viewRecords = [];
layerState._pickerRecords = [];
layerState._cameraIndexCache = null;
parts.presentation.notifyListeners();
},
@@ -550,6 +588,7 @@ export function createLifecycle({
parts.cards.handleVisibilityChange,
);
unregisterPickOwner('cctv');
unregisterClickClaim?.('cctv');
if (layerState._mapStackListener && typeof window !== 'undefined') {
window.removeEventListener(
'gev:map-stack-changed',
+34
View File
@@ -77,6 +77,40 @@ test('the view listeners follow the camera port and let go on teardown', () => {
assert.equal(state._viewListenerCamera, null);
});
test('terrain loading and surface changes rerun the view pass', () => {
const viewer = {};
let version = 1,
progress,
removed = false;
bindRenderer(viewer, {
camera: fakeCameraPort().port,
globe: {
surfaceVersion: () => version,
on(event, cb) {
assert.equal(event, 'progress');
progress = cb;
return () => {
removed = true;
};
},
},
});
const { lifecycle, passes } = lifecycleFor({
_viewer: viewer,
_enabled: true,
});
lifecycle.attachViewListeners();
progress({ terrainPending: 2 });
assert.equal(passes.length, 0);
progress({ terrainPending: 0 });
assert.equal(passes.length, 1);
version++;
progress({ terrainPending: 0 });
assert.equal(passes.length, 2);
lifecycle.detachViewListeners();
assert.ok(removed);
});
/** A part whose members are `own`'s, and any other a function that does
* nothing. */
const inert = (own = {}) =>
+86 -7
View File
@@ -1,6 +1,14 @@
import { distance } from '../../geo/vector.js';
import { toLonLatH } from '../../geo/ellipsoid.js';
import { rangeForBoundingSphere } from '../../data/cameraFraming.js';
import { isFollowing } from '../../data/followed.js';
import { CCTV_FOCUS_RESULT } from './policy.js';
import { cameraOf } from '../../render/rendererOf.js';
import {
cellBounds,
cellCenter,
cellHalfExtents,
} from '../../data/cctvCellCounts.js';
import { CCTV_FOCUS_RESULT, VIEW_CELL_PX, VIEW_MIN_CELL_M } from './policy.js';
import { cameraOf, canvasOf } from '../../render/rendererOf.js';
export function createNavigation({
state: layerState,
@@ -79,6 +87,16 @@ export function createNavigation({
return true;
}
/** What holds the view instead of a CCTV flight, or null when it is free. */
function viewHeldBy(viewer) {
if (
typeof document !== 'undefined' &&
document.body?.classList.contains('cockpit-mode')
)
return CCTV_FOCUS_RESULT.COCKPIT_ACTIVE;
return isFollowing(viewer) ? CCTV_FOCUS_RESULT.TRACKING_HOLDS_VIEW : null;
}
/**
* Flies the viewer's camera to frame the specified CCTV camera,
* looking along its heading from above.
@@ -90,14 +108,12 @@ export function createNavigation({
function focusCctvRecord(viewer, record, duration = 2.2) {
if (!viewer || !record) return CCTV_FOCUS_RESULT.NO_ACTIVE_CAMERA;
if (
typeof document !== 'undefined' &&
document.body?.classList.contains('cockpit-mode')
) {
const held = viewHeldBy(viewer);
if (held === CCTV_FOCUS_RESULT.COCKPIT_ACTIVE) {
console.debug('[Data:CCTV] focus ignored while cockpit owns the camera');
return CCTV_FOCUS_RESULT.COCKPIT_ACTIVE;
}
if (isFollowing(viewer)) {
if (held === CCTV_FOCUS_RESULT.TRACKING_HOLDS_VIEW) {
console.debug(
'[Data:CCTV] focus ignored while a tracked entity owns the camera',
);
@@ -120,6 +136,68 @@ export function createNavigation({
return CCTV_FOCUS_RESULT.FOCUSED;
}
/** The nearest ground cell with two or more cameras, or the group itself if unmerged. */
function nearestPart(cell, eye) {
let nearest = cell;
let best = Infinity;
for (const part of cell.parts ?? []) {
if (part.count < 2) continue;
const d = distance(eye, cellCenter(part));
if (d < best) {
best = d;
nearest = part;
}
}
return nearest;
}
/** Frame a group's padded bounds from above, including coincident mounts. */
function zoomToCell(cell) {
const viewer = layerState._viewer;
if (!viewer || viewHeldBy(viewer)) return;
const camera = cameraOf(viewer);
const pose = camera.pose();
const tanHalfY = Math.tan((pose.fovy || Math.PI / 3) / 2);
const canvas = canvasOf(viewer);
const height = canvas?.clientHeight || canvas?.height || 1;
// Half the range where cells stop grouping, so even coincident mounts split.
const closeRange =
(VIEW_MIN_CELL_M * height) / (4 * VIEW_CELL_PX * tanHalfY);
const tanHalfX = tanHalfY * (pose.aspectRatio || 1);
// Range where a cell's ground extent, times `pad`, fits the frame at the
// depth of its highest mount above the bounds centre.
const extentRange = (target, bounds, pad = 1) => {
const { halfWidthM, halfHeightM } = cellHalfExtents(target);
const rise = Math.max(0, target.high - toLonLatH(bounds.center).height);
return (
rise + pad * Math.max(halfWidthM / tanHalfX, halfHeightM / tanHalfY)
);
};
// The sphere fit spans the wider side, so a very wide window also needs the extent.
const fitRange = (target, bounds) =>
Math.max(
closeRange,
rangeForBoundingSphere(viewer, bounds.radius),
extentRange(target, bounds, 1.2),
);
// Approach long groups in halves so every click gets closer.
const halfway = (bounds) =>
pose.position ? distance(pose.position, bounds.center) / 2 : Infinity;
let bounds = cellBounds(cell);
let range = Math.min(halfway(bounds), fitRange(cell, bounds));
// If the group overflows the frame at that range, approach its nearest counted cell.
if (range < extentRange(cell, bounds)) {
const part = nearestPart(cell, pose.position);
bounds = cellBounds(part);
range = Math.min(halfway(bounds), fitRange(part, bounds));
}
camera.flyToBounds(bounds, {
offset: { heading: 0, pitch: -Math.PI / 2, range },
durationS: 1.2,
easing: 'cubicInOut',
});
}
function focusCamera(cameraId, duration = 2.2) {
return focusCctvRecord(
layerState._viewer,
@@ -196,6 +274,7 @@ export function createNavigation({
openingCameraId,
reopenNearestCamera,
focusCctvRecord,
zoomToCell,
focusCamera,
maybeAutoHop,
cctvCycleIndex,
+66 -18
View File
@@ -60,17 +60,38 @@ export const GEO_PROGRESS_NOTIFY_INTERVAL_MS = 300;
export const GEO_PROGRESS_NOTIFY_BATCH_LIMIT = 10;
// View thinning: camera icons show only on or near the screen, and each
// camera competes for a world-anchored grid cell sized to about VIEW_CELL_PX
// at its distance from the viewer (in power-of-two metre steps, so a pan
// keeps the same winners until a camera's distance crosses a step). Cells
// smaller than VIEW_MIN_CELL_M do not thin:
// close up every camera shows, co-located ones included.
// View thinning groups cameras into world-anchored cells of about VIEW_CELL_PX
// at their distance. Power-of-two metre steps keep cells stable during a pan.
// A cell with several cameras draws one count. Its best-ranked camera represents
// it in the picker. Cells smaller than VIEW_MIN_CELL_M do not group, so
// every camera shows close up.
export const VIEW_CELL_PX = 40;
export const VIEW_MIN_CELL_M = 60;
// Cameras within this horizontal distance in metres share a mount.
export const VIEW_SITE_M = 1.5;
// Cameras on one mount (VIEW_SITE_M) draw side by side,
// this many pixels apart, once they show as icons.
export const VIEW_SITE_SPREAD_PX = 30;
// Drawn-terrain reads per view pass for unanswered cameras and for re-reads
// of drawn heights. Off-screen cameras can use at most half of the budget.
// Remaining reads wait for the next pass.
export const VIEW_GROUND_READS = 300;
/**
* The camera icon's drawn size (px). Its SVG is 48 px: 1.25×
* near scale on a 2× display draws it at 60 device px, so it is rasterised
* past the drawn size to stay sharp there.
*/
export const CAMERA_ICON_PX = 24;
// Minimum gap between the outer rims of two separate markers.
export const COUNT_MERGE_GAP_PX = 4;
// Icons this far past the screen edge (fraction of its size) still show, so
// a pan does not reveal empty ground before the next view pass.
@@ -182,28 +203,51 @@ export const DEFAULT_CAMERA_CALIBRATION = Object.freeze({
/**
* Base64-encoded SVG camera icon for the camera icons. Icons rasterise an
* SVG at its own size, so it is 48 px: drawn at 24 px, 1.25× near scale on a
* 2× display draws it at 60 device px, and it stays sharp there.
* 2× display draws it at 60 device px, and it stays sharp there. Active and
* live cameras use cyan art with a billboard tint. Idle cameras use white
* and gray art so the billboard green shows true. The overlay draws the
* green variant directly.
*/
export const CAMERA_ICON = (() => {
function cameraIcon(tint = null) {
function tone(original, gray) {
if (!tint) return original;
const shade = parseInt(gray.slice(1, 3), 16) / 255;
return (
'#' +
tint
.slice(1)
.match(/../g)
.map((channel) =>
Math.round(parseInt(channel, 16) * shade)
.toString(16)
.padStart(2, '0'),
)
.join('')
);
}
const stroke = tone('#75e7ff', '#ffffff');
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 36 36">
<defs>
<linearGradient id="lens" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#c9f6ff"/>
<stop offset="45%" stop-color="#6fd9ff"/>
<stop offset="100%" stop-color="#1a5f78"/>
<stop offset="0%" stop-color="${tone('#c9f6ff', '#ffffff')}"/>
<stop offset="45%" stop-color="${tone('#6fd9ff', '#dddddd')}"/>
<stop offset="100%" stop-color="${tone('#1a5f78', '#666666')}"/>
</linearGradient>
</defs>
<g transform="translate(4 6)">
<rect x="0" y="8" width="20" height="9" rx="2.5" fill="#0e1720" stroke="#75e7ff" stroke-width="1.2"/>
<rect x="17" y="10" width="10" height="5" rx="1.5" fill="#132433" stroke="#75e7ff" stroke-width="1"/>
<circle cx="24" cy="12.5" r="3.1" fill="url(#lens)" stroke="#dbfbff" stroke-width="0.8"/>
<rect x="6.4" y="17" width="4.2" height="8.5" rx="1.2" fill="#10212d" stroke="#75e7ff" stroke-width="1"/>
<rect x="4.2" y="24" width="8.6" height="2.5" rx="1.1" fill="#0b151d" stroke="#4ecde7" stroke-width="0.8"/>
<rect x="0" y="8" width="20" height="9" rx="2.5" fill="${tone('#0e1720', '#181818')}" stroke="${stroke}" stroke-width="1.2"/>
<rect x="17" y="10" width="10" height="5" rx="1.5" fill="${tone('#132433', '#222222')}" stroke="${stroke}" stroke-width="1"/>
<circle cx="24" cy="12.5" r="3.1" fill="url(#lens)" stroke="${tone('#dbfbff', '#ffffff')}" stroke-width="0.8"/>
<rect x="6.4" y="17" width="4.2" height="8.5" rx="1.2" fill="${tone('#10212d', '#202020')}" stroke="${stroke}" stroke-width="1"/>
<rect x="4.2" y="24" width="8.6" height="2.5" rx="1.1" fill="${tone('#0b151d', '#151515')}" stroke="${tone('#4ecde7', '#cccccc')}" stroke-width="0.8"/>
</g>
</svg>`;
return 'data:image/svg+xml;base64,' + btoa(svg);
})();
}
export const CAMERA_ICON = cameraIcon();
export const IDLE_CAMERA_ICON = cameraIcon('#ffffff');
/**
* Seed camera definitions used when no live sources are available.
@@ -441,7 +485,11 @@ export const CAMERA_SEEDS = [
// Visual style constants: renderer colours, [r, g, b, a] in 0..1
// ---------------------------------------------------------------------------
export const IDLE_CAMERA_COLOR = hexColor('#6be8ff', 0.88);
/** Shared accent for idle still cameras and grouped cameras. */
export const CAMERA_GREEN = '#5dff8f';
export const COUNT_CAMERA_ICON = cameraIcon(CAMERA_GREEN);
export const IDLE_CAMERA_COLOR = hexColor(CAMERA_GREEN);
export const ACTIVE_CAMERA_COLOR = hexColor('#ffd97a', 0.95);
+12 -9
View File
@@ -229,9 +229,12 @@ export function createPresentation({
// separately from the currently applied frustum ground. Google-3D may
// legitimately refine the latter to the rendered mesh, so callers must
// not infer the prior by subtracting mount height from live geometry.
groundPriorM: Number.isFinite(record.groundPrior?.ellipsoid)
? record.groundPrior.ellipsoid
: null,
// A height read from drawn terrain is unavailable as a Re:Earth prior.
groundPriorM:
Number.isFinite(record.groundPrior?.ellipsoid) &&
record.groundPrior.source !== 'drawn-terrain'
? record.groundPrior.ellipsoid
: null,
intrinsics: camera.intrinsics ? { ...camera.intrinsics } : null,
extrinsics: camera.extrinsics ? { ...camera.extrinsics } : null,
anchor: camera.anchor ? { ...camera.anchor } : null,
@@ -310,16 +313,16 @@ export function createPresentation({
}
/**
* `{ id, city, name }` for the active camera, then every camera the view
* pass shows: what the camera picker lists. A whole catalog would put tens
* of thousands of options in the DOM and slow every layout. The same array
* is returned until the view or the active camera changes, so a consumer
* can compare it by identity.
* `{ id, city, name }` for the active camera, then each camera shown as an
* icon and the best-ranked camera of each visible group. A whole catalog
* would put tens of thousands of options in the DOM and slow every layout.
* Consumers can compare the array by identity until the picker records or
* active camera change.
* @returns {{id: string, city: string, name: string}[]}
*/
function cameraIndex() {
const view = layerState._viewRecords;
const view = layerState._pickerRecords;
const active = parts.selection.getActiveRecord();
const cached = layerState._cameraIndexCache;
if (cached?.view === view && cached.active === active) return cached.list;
+416 -87
View File
@@ -1,7 +1,13 @@
import { createCountMarkers } from './countMarkers.js';
import { addCellCamera, createCameraCell } from '../../data/cctvCellCounts.js';
import { isHeadingEstimated } from './headingConfidence.js';
import {
ACTIVE_CAMERA_COLOR,
CAMERA_ICON,
CAMERA_ICON_PX,
COUNT_MERGE_GAP_PX,
VIEW_SITE_M,
IDLE_CAMERA_ICON,
IDLE_CAMERA_COLOR,
LIVE_CAMERA_COLOR,
ACTIVE_COVERAGE_CENTER,
@@ -14,6 +20,8 @@ import {
VIEW_CELL_PX,
VIEW_ICON_MARGIN,
VIEW_MIN_CELL_M,
VIEW_SITE_SPREAD_PX,
VIEW_GROUND_READS,
} from './policy.js';
import { createIconBook } from '../../render/motion/iconBook.js';
import { frustumVolumeGeometryData } from '../../data/cctvViewshed.js';
@@ -24,11 +32,21 @@ import {
findGlobe,
findQuery,
} from '../../render/rendererOf.js';
import { fromDegrees, WGS84 } from '../../geo/ellipsoid.js';
import { heightsOf } from '../../queries/heights.js';
import {
fromDegrees,
fromDegreesInto,
toLonLatH,
WGS84,
} from '../../geo/ellipsoid.js';
import { eastNorthUp } from '../../geo/frames.js';
import { poseProjector } from '../../geo/frustum.js';
import { horizonFrom } from '../../geo/horizon.js';
import { distance } from '../../geo/vector.js';
import { add, distance, dot, scale, sub } from '../../geo/vector.js';
const IDLE_ICON_STYLE = { image: IDLE_CAMERA_ICON, color: IDLE_CAMERA_COLOR };
const ACTIVE_ICON_STYLE = { image: CAMERA_ICON, color: ACTIVE_CAMERA_COLOR };
const LIVE_ICON_STYLE = { image: CAMERA_ICON, color: LIVE_CAMERA_COLOR };
/** An RGBA colour with another alpha. */
const withAlpha = (color, alpha) => [color[0], color[1], color[2], alpha];
@@ -46,12 +64,6 @@ const samePoint = (a, b) =>
/** Degrees to radians. */
const toRadians = (degrees) => (degrees * Math.PI) / 180;
/**
* The camera icon's drawn size (px). Its SVG is 48 px (policy.js): 1.25×
* near scale on a 2× display draws it at 60 device px, so it is rasterised
* past the drawn size to stay sharp there.
*/
const CAMERA_ICON_PX = 24;
const CAMERA_SCALE_BY_DISTANCE = Object.freeze({
near: 350,
nearValue: 1.25,
@@ -139,6 +151,12 @@ export function createRendering({
// with its first camera.
set.setColumns?.({ ids: [] });
layerState._icons = createIconBook(set);
layerState._counts = createCountMarkers(
services.overlays?.registerWorldOverlayPaintLane,
`cctv:${iconSets}:counts`,
refreshViewFromCounts,
services.overlays?.keyholeAlpha,
);
return set.id;
}
@@ -146,6 +164,8 @@ export function createRendering({
function destroyCameraIcons() {
layerState._icons?.dispose();
layerState._icons = null;
layerState._counts?.dispose();
layerState._counts = null;
}
/** The icon item a camera record draws, idle and shown, at its position. */
@@ -153,10 +173,9 @@ export function createRendering({
const id = record.camera.id;
return {
id,
pos: copyPoint(record.position),
image: CAMERA_ICON,
pos: copyPoint(record.spreadPosition ?? record.position),
...cameraIconStyleFor(record),
size: [CAMERA_ICON_PX, CAMERA_ICON_PX],
color: cameraColorFor(record),
scale: 1,
scaleByDistance: CAMERA_SCALE_BY_DISTANCE,
disableDepthTest: Infinity,
@@ -195,22 +214,26 @@ export function createRendering({
function moveCameraIcon(record) {
const icons = layerState._icons;
if (!icons || !record.position) return;
// A camera drawn beside its mount mates keeps its offset from the mount.
if (record.spreadOffset)
record.spreadPosition = add(record.position, record.spreadOffset);
const pos = record.spreadPosition ?? record.position;
const item = icons.item(record.camera.id);
// A camera whose icon waited for a position is drawn now.
if (!item) {
icons.put(cameraIconItem(record));
return;
}
if (samePoint(item.pos, record.position)) return;
icons.put({ ...item, pos: copyPoint(record.position) });
if (samePoint(item.pos, pos)) return;
icons.put({ ...item, pos: copyPoint(pos) });
}
/** Icon color: active wins, then live-capable video feeds, then idle stills. */
function cameraColorFor(record) {
/** Select the sprite and tint together when a camera changes state. */
function cameraIconStyleFor(record) {
if (record.camera.id === layerState._activeCameraId)
return ACTIVE_CAMERA_COLOR;
if (parts.model.isVideoFeedCamera(record.camera)) return LIVE_CAMERA_COLOR;
return IDLE_CAMERA_COLOR;
return ACTIVE_ICON_STYLE;
if (parts.model.isVideoFeedCamera(record.camera)) return LIVE_ICON_STYLE;
return IDLE_ICON_STYLE;
}
const {
@@ -219,11 +242,14 @@ export function createRendering({
focusPassIsNeeded,
advanceSpriteFocus,
focusAlphaNeedsWrite,
nearFarScalarValueAtDistance,
} = services.focus;
const iconScaleAt = (range) =>
nearFarScalarValueAtDistance?.(CAMERA_SCALE_BY_DISTANCE, range) ?? 1;
/**
* Focus modulation rides the layer's existing animation loop; no additional
* scene listener is installed. Only camera-icon alpha changes here — coverage
* scene listener is installed. Camera and count icons share the fade. Coverage
* geometry and monitor-plane styling retain their established cadence.
*/
@@ -276,61 +302,76 @@ export function createRendering({
let writes = 0;
let transitioning = false;
let activeCount = 0;
for (const record of records || []) {
const id = record.camera?.id;
const item = icons?.item(id);
if (!item) continue;
const position = record.position;
const scale = item.scale ?? 1;
// CCTV never publishes a tracked focus target, so every icon is ambient.
const focus = advanceSpriteFocus(item.meta, {
// Keep hidden icons in the state/release pass so the active count cannot
// drop while a stale dim alpha remains waiting to reappear.
screenPosition:
item.show === false || !position ? null : screenPositionFor(position),
/**
* A changed focus factor for an icon or count. CCTV publishes no tracked
* focus target, so every icon is ambient.
*/
function changedFocus(owner, position, shown, width, height, current) {
const focus = advanceSpriteFocus(owner, {
// Keep hidden owners in the active count until their dim alpha clears,
// so the focus pass keeps running while they recover.
screenPosition: shown && position ? screenPositionFor(position) : null,
cameraDistance: position ? cameraDistanceFor(position) : Number.NaN,
nowMs,
target,
params,
spriteHalfWidthPx: item.size[0] * scale * 0.5,
spriteHalfHeightPx: item.size[1] * scale * 0.5,
spriteHalfWidthPx: width / 2,
spriteHalfHeightPx: height / 2,
});
transitioning ||= focus.transitioning;
if (focus.active) activeCount += 1;
// Order-independent narrow amendment to always-visible icons: CCTV
// contacts retain a non-zero floor while yielding near the tracked target.
if (focusAlphaNeedsWrite(icons.focus(id), focus.factor, params)) {
icons.setFocus(id, focus.factor);
writes += 1;
}
if (focus.active) activeCount++;
if (!focusAlphaNeedsWrite(current, focus.factor, params)) return null;
writes++;
return focus.factor;
}
for (const record of records || []) {
const id = record.camera?.id;
const item = icons?.item(id);
if (!item) continue;
const scale = item.scale ?? 1;
const factor = changedFocus(
item.meta,
record.position,
item.show !== false,
item.size[0] * scale,
item.size[1] * scale,
icons.focus(id),
);
if (factor !== null) icons.setFocus(id, factor);
}
const counts = layerState._counts;
const iconWrites = writes;
for (const marker of counts?.markers ?? []) {
const factor = changedFocus(
marker,
marker.pos,
true,
marker.width,
marker.height,
marker.focus,
);
if (factor !== null) marker.focus = factor;
}
if (writes > iconWrites) counts.requestPaint();
return { writes, transitioning, activeCount, ran: true };
}
/** During camera motion the timer and settle pass refresh the counts. */
function refreshViewFromCounts() {
if (!layerState._cameraMoving) refreshHorizonCulling();
}
/**
* Updates visual styles (colors, widths, visibility) for all camera icons,
* coverage polylines, viewshed volumes, and projection entities based on which
* camera is active, whether the layer is enabled, and the current
* coverage-mode/projection toggle states.
*/
/**
* Field-test fix (2026-07-06): horizon-culls camera icons on the CPU as the
* icon shader does on the GPU. With the globe hidden (Google-3D
* regime) nothing writes far-side depth and the icons are always-on-top, so
* the shown set (cards, geometry, the picker) must not include London's
* cluster from a US viewpoint.
*
* The same pass thins the view so a large catalog stays readable and cheap:
* icons well off screen hide, and each camera competes for a world-anchored
* cell sized to VIEW_CELL_PX at its distance (healthiest first, then a stable
* id order). The active camera shows whenever it is above the horizon
* and near the screen, even in a crowded cell. The shown records become
* `_viewRecords`, the working set for geometry, cards and the camera picker;
* the array keeps its identity while the shown set is unchanged.
* Cull far-side cameras on the CPU because the hidden globe writes no depth.
* Group the rest by ground cell. _viewRecords holds the active camera and
* every nearby icon outside a count for geometry and cards. Cells smaller
* than VIEW_MIN_CELL_M do not form groups. _pickerRecords adds the
* best-ranked camera of each visible cell. Both arrays keep their identity
* while their contents are unchanged.
*
* Runs on camera settle, throttled during motion, on resize, enable and
* activation changes — never per frame.
* @returns {boolean} Whether the shown set changed.
* @returns {boolean} Whether the shown set or the picker list changed.
*/
function refreshHorizonCulling() {
@@ -365,7 +406,30 @@ export function createRendering({
const project = screenProjector(pose, width, height);
const pass = (layerState._viewPassId = (layerState._viewPassId || 0) + 1);
const shown = [];
const picker = [];
const cells = new Map();
const visibleCells = [];
// Drawn terrain where the globe is the surface. The photoreal stack has
// no reader, and unloaded tiles return a non-finite height.
const heights = heightsOf(layerState._viewer);
const globe = findGlobe(layerState._viewer);
const groundHeight =
findQuery(layerState._viewer) && globe?.isGlobeVisible?.() === true
? (lon, lat) => heights.now({ lon, lat }, { against: 'terrain' })
: null;
const surface = globe?.surfaceVersion?.() ?? 0;
const terrainSettled = globe?.isSettled?.('terrain') ?? true;
let groundReads = groundHeight ? VIEW_GROUND_READS : 0;
let offscreenReads = groundReads / 2;
let eyeGround;
const column = { x: 0, y: 0, z: 0 };
const inReadWindow = (s) =>
s &&
s.x >= -width &&
s.x <= 2 * width &&
s.y >= -height &&
s.y <= 2 * height;
const regrounded = [];
for (const record of layerState._records) {
const position = record.position;
if (!position) continue;
@@ -380,48 +444,307 @@ export function createRendering({
(vtDotVc * vtDotVc) / (vx * vx + vy * vy + vz * vz) > limbSquared
)
continue;
const screen = project(position);
let screen = project(position);
let range = distance(position, viewer);
// Missing, unresolved and fallback priors can put a mount kilometres
// below the terrain, shifting its projection and inflating its cell.
// Read nearby mounts again from under half the range, on finer terrain
// after loading, or on a different surface.
const prior = record.groundPrior;
const drawn = prior?.source === 'drawn-terrain';
const unanswered =
!Number.isFinite(prior?.ellipsoid) || prior.source === 'geoid-fallback';
if (
!screen ||
!(screen.x >= minX && screen.x <= maxX) ||
!(screen.y >= minY && screen.y <= maxY)
)
continue;
const dx = position.x - viewer.x;
const dy = position.y - viewer.y;
const dz = position.z - viewer.z;
const cellM =
VIEW_CELL_PX *
metresPerPixelPerMetre *
Math.sqrt(dx * dx + dy * dy + dz * dz);
if (record.camera.id === activeId || !(cellM >= VIEW_MIN_CELL_M)) {
record.viewPass = pass;
groundReads > 0 &&
!record.regroundPending &&
(unanswered ||
(drawn &&
(prior.rangeM > 2 * range ||
prior.surface !== surface ||
(!prior.settled && terrainSettled))))
) {
let probe = inReadWindow(screen) ? screen : null;
if (!probe && unanswered) {
// Its height is a guess. Try the ground under the eye instead.
if (eyeGround === undefined) {
const eye = toLonLatH(viewer);
eyeGround = eye ? (groundHeight(eye.lon, eye.lat) ?? null) : null;
groundReads--;
}
if (Number.isFinite(eyeGround)) {
fromDegreesInto(
record.camera.lon,
record.camera.lat,
eyeGround + (record.camera.mountHeightM || 0),
column,
);
const at = project(column);
if (inReadWindow(at)) probe = at;
}
}
const onScreen =
probe &&
probe.x >= 0 &&
probe.x <= width &&
probe.y >= 0 &&
probe.y <= height;
if (probe && groundReads > 0 && (onScreen || offscreenReads > 0)) {
groundReads--;
if (!onScreen) offscreenReads--;
const ground = groundHeight(record.camera.lon, record.camera.lat);
if (Number.isFinite(ground)) {
const read = { rangeM: range, surface, settled: terrainSettled };
if (drawn && Math.abs(ground - prior.ellipsoid) < 1)
Object.assign(prior, read);
else if (record.frustumGeometry) {
// Recomputing geometry writes draw sets after this pass.
record.regroundPending = true;
regrounded.push([record, ground, read]);
} else parts.ground.adoptDrawnGround(record, ground, read);
}
}
// The probe reuses the projector's result, and the mount may have moved.
screen = project(position);
range = distance(position, viewer);
}
const nearScreen =
screen &&
screen.x >= minX &&
screen.x <= maxX &&
screen.y >= minY &&
screen.y <= maxY;
const cellM = VIEW_CELL_PX * metresPerPixelPerMetre * range;
if (record.camera.id === activeId) {
if (!nearScreen) continue;
record.viewPass = record.pickerPass = pass;
shown.push(record);
picker.push(record);
continue;
}
if (!(cellM >= VIEW_MIN_CELL_M)) {
if (!nearScreen) continue;
// Too close to group, but a count beside it can still take it in.
const cell = createCameraCell(`near:${record.camera.id}`);
addCellCamera(cell, record.camera);
cell.iconPx = CAMERA_ICON_PX * iconScaleAt(range);
cell.winner = record;
cell.rank = 0;
record.viewCell = cell;
visibleCells.push(cell);
continue;
}
const key = worldCellKey(record, cellM);
let cell = cells.get(key);
if (!cell) {
cell = createCameraCell(key);
cells.set(key, cell);
}
addCellCamera(cell, record.camera);
if (cell.count === 1) cell.iconPx = CAMERA_ICON_PX * iconScaleAt(range);
record.viewCell = cell;
if (!nearScreen) continue;
// The picker ranks only candidates that were in its padded viewport.
if (!cell.winner) visibleCells.push(cell);
const rank = viewRank(record);
const holder = cells.get(key);
if (!holder || rank < holder.rank) cells.set(key, { record, rank });
if (rank < cell.rank) {
cell.winner = record;
cell.rank = rank;
}
}
for (const { record } of cells.values()) {
record.viewPass = pass;
shown.push(record);
// Check each mount mate against counts where its icon will be drawn.
const lone = visibleCells.filter((cell) => cell.count === 1);
spreadSharedMounts(
shown.concat(lone.map((cell) => cell.winner)),
pose,
metresPerPixelPerMetre,
pass,
);
for (const cell of lone)
cell.offsetPx =
cell.winner.spreadPass === pass ? cell.winner.spreadPx : 0;
// A count stands on the drawn terrain too: its cell may be too far for
// its cameras to have been read. Marks each lone camera that a count
// marker beside it has taken in.
layerState._counts?.update(visibleCells, project, groundHeight);
for (const cell of visibleCells) {
const record = cell.winner;
picker.push(record);
record.pickerPass = pass;
if (cell.count === 1 && !cell.absorbed) {
record.viewPass = pass;
shown.push(record);
}
}
clearActiveOfCounts(project, pose, metresPerPixelPerMetre, pass);
const writes = [];
let coverageChanged = false;
let cardsChanged = false;
for (const record of layerState._records) {
const item = patchedCameraIcon(record.camera.id, {
show: record.viewPass === pass,
});
const cell = record.viewCell;
record.viewCell = null;
const grouped = Boolean(
cell?.winner && (cell.count > 1 || cell.absorbed),
);
if (grouped !== !!record.viewGrouped) {
const id = record.camera.id;
coverageChanged ||= layerState._coverageCohort?.has(id);
cardsChanged ||=
layerState._cardIds?.has(id) || layerState._hoverCardId === id;
}
record.viewGrouped = grouped;
const fields = { show: record.viewPass === pass };
if (record.spreadPass === pass) {
const drawn = layerState._icons?.item(record.camera.id)?.pos;
if (!drawn || !samePoint(drawn, record.spreadPosition))
fields.pos = copyPoint(record.spreadPosition);
} else if (record.spreadPosition) {
// No longer beside a mount mate: back onto its own position.
record.spreadOffset = null;
record.spreadPosition = null;
fields.pos = copyPoint(record.position);
}
const item = patchedCameraIcon(record.camera.id, fields);
if (item) writes.push(item);
}
writeCameraIcons(writes);
if (regrounded.length) queueMicrotask(() => reground(regrounded));
const previous = layerState._viewRecords;
const changed =
previous.length !== shown.length ||
previous.some((record) => record.viewPass !== pass);
if (changed) layerState._viewRecords = shown;
return changed;
const oldPicker = layerState._pickerRecords ?? [];
const pickerChanged =
picker.length !== oldPicker.length ||
oldPicker.some((record) => record.pickerPass !== pass);
if (pickerChanged) layerState._pickerRecords = picker;
if (coverageChanged) refreshCoverageStyles();
if (cardsChanged) parts.cards.pushAmbientCardEntries();
return changed || pickerChanged;
}
/**
* Cameras that have geometry take the drawn terrain after the pass that
* read it, then the view is passed again from their new positions.
*/
function reground(entries) {
let changed = false;
for (const [record, ground, read] of entries) {
record.regroundPending = false;
changed =
parts.ground.adoptDrawnGround(record, ground, read) !== null || changed;
}
if (!changed) return;
if (refreshHorizonCulling()) parts.geometryQueue.enqueueViewGeometry();
parts.presentation.notifyListeners();
}
/**
* Cameras on one mount would draw as one icon with several callouts. Among
* icon candidates, those within VIEW_SITE_M horizontally get draw positions
* side by side in id order, `VIEW_SITE_SPREAD_PX` apart on screen. A mate
* absorbed by a count keeps its place in the row. Geometry and cards stay
* on the mount.
*/
function spreadSharedMounts(shown, pose, metresPerPixelPerMetre, pass) {
const { right, direction, position: eye } = pose;
if (!right || !direction || shown.length < 2) return;
const grid = new Map();
const mounts = [];
const axes = eastNorthUp(eye);
for (const record of shown) {
// Sea-level coordinates compare horizontal distance across longitude
// and latitude boundaries, including the antimeridian.
const p = fromDegrees(record.camera.lon, record.camera.lat, 0);
const col = Math.floor(dot(p, axes.x) / VIEW_SITE_M);
const row = Math.floor(dot(p, axes.y) / VIEW_SITE_M);
let mount;
for (let i = col - 1; !mount && i <= col + 1; i++)
for (let j = row - 1; !mount && j <= row + 1; j++)
mount = grid
.get(`${i}:${j}`)
?.find((site) => distance(p, site.p) <= VIEW_SITE_M);
if (!mount) {
mount = { p, mates: [] };
mounts.push(mount);
const key = `${col}:${row}`;
if (!grid.has(key)) grid.set(key, []);
grid.get(key).push(mount);
}
mount.mates.push(record);
}
for (const { mates } of mounts) {
if (mates.length < 2) continue;
mates.sort((a, b) => a.camera.id.localeCompare(b.camera.id));
for (let i = 0; i < mates.length; i++) {
const record = mates[i];
const p = record.position;
// A pixel's width on the ground grows with depth along the view.
const depth =
(p.x - eye.x) * direction.x +
(p.y - eye.y) * direction.y +
(p.z - eye.z) * direction.z;
const px = (i - (mates.length - 1) / 2) * VIEW_SITE_SPREAD_PX;
record.spreadPx = px;
const metres = px * metresPerPixelPerMetre * depth;
record.spreadOffset = scale(right, metres);
record.spreadPosition = add(p, record.spreadOffset);
record.spreadPass = pass;
}
}
}
/** Only counts visible outside the HUD push the active icon aside. */
function clearActiveOfCounts(project, pose, metresPerPixelPerMetre, pass) {
const markers = layerState._counts?.markers;
for (const marker of markers ?? []) marker.besideActive = false;
if (!layerState._activeCameraId) return;
const record = layerState._recordById.get(layerState._activeCameraId);
if (
record?.viewPass !== pass ||
!markers?.length ||
!pose.right ||
!pose.direction
)
return;
const spread = record.spreadPass === pass;
const p = spread ? record.spreadPosition : record.position;
const screen = project(p);
if (!screen) return;
const { x, y } = screen;
const half =
(CAMERA_ICON_PX * 1.25 * iconScaleAt(distance(p, pose.position))) / 2;
const spans = [];
for (const marker of markers) {
const at = project(marker.pos);
if (
!at ||
Math.abs(y - at.y) >= marker.height / 2 + half + COUNT_MERGE_GAP_PX
)
continue;
marker.besideActive = true;
if (marker.hudHidden) continue;
const reach = marker.width / 2 + half + COUNT_MERGE_GAP_PX;
spans.push([at.x - reach, at.x + reach]);
}
// Leave the entire overlapping interval, including an adjacent count.
spans.sort((a, b) => a[0] - b[0]);
let left = Infinity,
right = -Infinity;
for (const [start, end] of spans) {
if (start >= right) {
if (left < x && x < right) break;
left = start;
right = end;
} else right = Math.max(right, end);
}
if (!(left < x && x < right)) return;
const shift = x - left < right - x ? left - x : right - x;
const depth = dot(sub(p, pose.position), pose.direction);
const offset = scale(pose.right, shift * metresPerPixelPerMetre * depth);
record.spreadOffset = spread ? add(record.spreadOffset, offset) : offset;
record.spreadPosition = add(record.position, record.spreadOffset);
record.spreadPass = pass;
}
/**
@@ -526,6 +849,7 @@ export function createRendering({
);
parts.projection.clearProjectionOverlay();
if (layerState._icons) layerState._icons.show = false;
layerState._counts?.hide();
parts.projection.pauseInactiveProjectionFeeds(null);
}
@@ -535,8 +859,12 @@ export function createRendering({
const activeRecord = parts.selection.getActiveRecord();
parts.geometry.ensureActiveCoverageEntities(activeRecord);
const activeId = activeRecord?.camera.id || null;
const coverageVisible =
parts.geometry.buildCoverageVisibleSet(activeRecord);
const cohort = parts.geometry.buildCoverageVisibleSet(activeRecord);
layerState._coverageCohort = cohort;
const coverageVisible = new Set();
for (const id of cohort) {
if (!layerState._recordById.get(id)?.viewGrouped) coverageVisible.add(id);
}
// Drawn coverage needs geometry too (geometryQueue's working set).
layerState._coverageVisibleIds = coverageVisible;
const coverageOn = layerState._coverageMode !== 'off';
@@ -553,7 +881,7 @@ export function createRendering({
for (const record of layerState._records) {
const isActive = record.camera.id === activeId;
const icon = patchedCameraIcon(record.camera.id, {
color: cameraColorFor(record),
...cameraIconStyleFor(record),
scale: isActive ? 1.25 : 1.0,
});
if (icon) restyled.push(icon);
@@ -865,6 +1193,7 @@ export function createRendering({
* @returns {string|null}
*/
function pickCameraIdAt(position) {
if (layerState._counts?.pickedCell(position)) return null;
let hit = null;
try {
hit = findQuery(layerState._viewer)?.pick(position.x, position.y) ?? null;
+85 -2
View File
@@ -1,7 +1,7 @@
// src/layers/cctv/rendering.test.mjs
// Icon colors under focus de-emphasis (#1200): the focus pass fades each icon
// from the same base color the coverage refresh assigns, so a video-feed camera
// stays violet while it dims instead of falling back to the idle cyan.
// stays violet while it dims instead of falling back to the idle green.
// Teardown lets go of the icon set of the viewer that drew it.
import { test } from 'node:test';
import assert from 'node:assert/strict';
@@ -114,29 +114,80 @@ test('focus de-emphasis fades each icon from its own color', () => {
}
});
test('focus uses the painted half-width and half-height of each count', () => {
const markers = [
{ width: 40, height: 40 },
{ width: 72, height: 58 },
];
const sizes = [];
const rendering = createRendering({
state: { _counts: { markers } },
services: {
focus: {
focusPassIsNeeded: () => true,
advanceSpriteFocus(_owner, { spriteHalfWidthPx, spriteHalfHeightPx }) {
sizes.push([spriteHalfWidthPx, spriteHalfHeightPx]);
return { factor: 1 };
},
focusAlphaNeedsWrite: () => false,
},
},
});
rendering.applyCctvFocusDeemphasis({});
assert.deepEqual(sizes, [
[20, 20],
[36, 29],
]);
});
test('the icons go with the viewer that drew them, whichever tears down', () => {
const first = {};
const second = {};
const one = bindFakeDraw(first);
const two = bindFakeDraw(second);
const state = { _viewer: first };
const lanes = [];
const overlays = {
registerWorldOverlayPaintLane(name, paint, options) {
const lane = {
name,
paint,
options,
setActive() {},
unregister() {
this.disposed = true;
},
};
lanes.push(lane);
return lane;
},
};
const { createCameraIcons, destroyCameraIcons } = createRendering({
state,
services: { focus: {} },
services: { focus: {}, overlays },
parts: {},
source: {},
});
try {
const old = createCameraIcons(first);
assert.equal(one.draw.sets.size, 1);
assert.equal(lanes[0].name, 'ambient-label');
assert.equal(lanes[0].options.target, 'shared');
assert.equal(lanes[0].options.active, false);
state._viewer = second;
const current = createCameraIcons(second);
assert.notEqual(old, current);
assert.equal(one.draw.sets.get(old).disposed, true, 'a re-init lets go');
assert.equal(two.draw.sets.get(current).disposed, false);
assert.equal(lanes[0].disposed, true);
lanes[0].paint({});
destroyCameraIcons();
assert.equal(two.draw.sets.get(current).disposed, true);
assert.equal(state._icons, null);
assert.equal(lanes[1].disposed, true);
lanes[1].paint({});
assert.equal(state._counts, null);
} finally {
one.unbind();
two.unbind();
@@ -376,3 +427,35 @@ test('a pose with no perspective field of view is projected by the renderer', ()
unbind();
}
});
test('hover picks the underlying camera only outside a painted count', () => {
const viewer = {};
const icon = { set: 'icons', id: 'camera' };
let picks = 0;
const unbind = bindRenderer(viewer, {
query: {
pick() {
picks++;
return icon;
},
},
});
try {
const state = {
_viewer: viewer,
_counts: { pickedCell: ({ x }) => (x <= 17 ? {} : null) },
_icons: { setId: icon.set, has: () => true },
_recordById: new Map([[icon.id, {}]]),
};
const rendering = createRendering({
state,
services: { focus: {} },
parts: {},
});
assert.equal(rendering.pickCameraIdAt({ x: 17, y: 0 }), null);
assert.equal(picks, 0);
assert.equal(rendering.pickCameraIdAt({ x: 18, y: 0 }), icon.id);
} finally {
unbind();
}
});
+65 -5
View File
@@ -1,3 +1,7 @@
import {
CCTV_COUNT_CARD_SOURCE_ID,
CCTV_OVERLAY_SOURCE_ID,
} from '../../data/cctvCards.js';
import { isTrackingClickGesture } from '../../data/trackingClickGesture.js';
export function createSelection({
@@ -7,7 +11,13 @@ export function createSelection({
source,
}) {
const { CCTV_ACTIVATION_RESULT } = services.activation;
const { resolvePickId } = services.picking;
const {
resolvePickId,
findPickOwner,
isOwnedByOtherLayer,
isUnderOtherCard,
} = services.picking;
const OWN_CARD_SOURCES = [CCTV_OVERLAY_SOURCE_ID, CCTV_COUNT_CARD_SOURCE_ID];
/**
* Returns the camera record for the currently active camera. A stale ID falls
@@ -29,6 +39,49 @@ export function createSelection({
return fallback;
}
/** Whether another layer's scene object owns the click at this count. */
function sceneTakesCountClick(event) {
const top = event.topHit;
if (!top) return false;
const drawHit = event.drawHit;
if (drawHit) {
// Unowned fills, such as earthquake discs, let the count take the click.
if (parts.rendering.extractPickedCameraId(drawHit)) return false;
const id = resolvePickId(drawHit);
return id !== null && Boolean(isOwnedByOtherLayer?.('cctv', id));
}
const id = resolvePickId(top);
return id !== null && findPickOwner?.(id) !== 'cctv';
}
/** Leave other layers' cards to the caller since clickCard also calls this. */
function clickedCount(event) {
if (
!isTrackingClickGesture(event.gesture) ||
!layerState._enabled ||
event.overlay
)
return null;
const cell = layerState._counts?.pickedCell(event.screenPosition);
if (!cell) return null;
const { x, y } = event.screenPosition;
if (
layerState._cctvOverlayHost?.hitTest(x, y, {
sourceId: CCTV_OVERLAY_SOURCE_ID,
})?.entryId
)
return null;
return sceneTakesCountClick(event) ? null : cell;
}
/** The count marker as the card on top of a click it takes, for every layer's clickCard. */
function countClickCard(event) {
const cell = clickedCount(event);
return cell
? { sourceId: CCTV_COUNT_CARD_SOURCE_ID, entryId: String(cell.key ?? '') }
: null;
}
/**
* Bind CCTV activation to clean taps. Drag-like and long-press gestures do
* not reach camera activation or focus dispatch.
@@ -41,6 +94,12 @@ export function createSelection({
function bindCctvWorldClickGesture(input, onClick) {
return input.onClick((event) => {
if (!isTrackingClickGesture(event.gesture)) return;
const cell = clickedCount(event);
// Another layer's card or label painted above the count takes the click.
if (cell && !isUnderOtherCard?.(event, OWN_CARD_SOURCES)) {
parts.navigation.zoomToCell(cell);
return;
}
onClick(event);
});
}
@@ -139,11 +198,11 @@ export function createSelection({
// is looking at ever asks.
void parts.ground.resolveFootprintGround(record);
record.activationDone = true;
parts.rendering.refreshCoverageStyles();
// The active camera's icon always shows; the previously active one
// competes for its cell again. Its coverage neighbours join the working
// set and are queued for grounding.
// The active icon always shows and the previous one rejoins its cell.
// Restyle coverage after the view pass sets grouping. Its coverage
// neighbours join the working set and are queued for grounding.
parts.rendering.refreshHorizonCulling();
parts.rendering.refreshCoverageStyles();
parts.geometryQueue.enqueueViewGeometry();
// The newly active camera leaves the ambient ring (its monitor plane takes
// over); the freed slot re-fills on this same pass.
@@ -218,6 +277,7 @@ export function createSelection({
return {
getActiveRecord,
bindCctvWorldClickGesture,
countClickCard,
setActiveCamera,
deactivateActiveCamera,
cctvEmptyClickDeselects,
+163
View File
@@ -1,6 +1,10 @@
import * as picking from '../../data/pickRegistry.js';
import { CCTV_COUNT_CARD_SOURCE_ID } from '../../data/cctvCards.js';
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { CCTV_ACTIVATION_RESULT } from '../../cctvFocusRequest.js';
import { bindRenderer } from '../../render/rendererOf.js';
import { createNavigation } from './navigation.js';
import { createSelection } from './selection.js';
function makeSelection(sourceKind) {
@@ -52,3 +56,162 @@ test('same-camera selection notifies browser-overlay feeds so playback can retry
assert.equal(fixture.state._activeCameraReselection, 1);
assert.equal(fixture.notifications(), 1);
});
test('a count click preserves the provisional opening pick until the view settles', () => {
const viewer = {};
const flights = [];
const unbind = bindRenderer(viewer, {
camera: {
pose: () => ({ fovy: Math.PI / 3, aspectRatio: 1 }),
flyToBounds: (bounds) => flights.push(bounds),
},
canvas: { height: 600 },
});
try {
const cell = { west: 1, east: 2, south: 0, north: 0, low: 0, high: 0 };
const state = {
_enabled: true,
_viewer: viewer,
_openingCameraProvisional: true,
_activeCameraId: 'opening',
_counts: {
pickedCell: (point) => (point?.x === 14 && point.y === 26 ? cell : null),
},
};
const parts = {};
parts.navigation = createNavigation({ state, parts });
const selection = createSelection({
state,
parts,
services: { activation: {}, picking: {} },
});
const click = selection.bindCctvWorldClickGesture(
{ onClick: (fn) => fn },
() => {
assert.fail('a count click reached activation or deselection');
},
);
click({
screenPosition: { x: 14, y: 26 },
get drawHit() {
assert.fail('the camera underneath was picked');
},
gesture: { travelPx: 0, durationMs: 20 },
});
assert.equal(flights.length, 1);
assert.equal(state._activeCameraId, 'opening');
assert.equal(state._openingCameraProvisional, true);
} finally {
unbind();
}
});
test("a count click yields to a card above it and to another layer's object, not to a CCTV icon", () => {
let zooms = 0,
clicks = 0;
const selection = createSelection({
services: { activation: {}, picking },
state: {
_enabled: true,
_counts: { pickedCell: () => ({}) },
_cctvOverlayHost: {
hitTest: (x) => (x === 14 ? { entryId: 'cam-1' } : null),
},
},
parts: {
navigation: { zoomToCell: () => zooms++ },
rendering: {
extractPickedCameraId: (hit) =>
hit?.set === 'cctv-icons' ? hit.id : null,
},
},
});
const click = selection.bindCctvWorldClickGesture(
{ onClick: (fn) => fn },
() => clicks++,
);
picking.registerPickOwner('cctv', (id) => id.startsWith('cam-'));
picking.registerPickOwner('flights', (id) => id === 'abc' || id === 'cam-2');
try {
for (const [x, topHit, expected] of [
[14, null, [0, 1]],
[20, { set: 'flights', id: 'abc' }, [0, 2]],
[20, { set: 'cctv-icons', id: 'cam-2' }, [1, 2]],
[20, null, [2, 2]],
[20, { set: 'flights', id: 'cam-2' }, [2, 3]],
]) {
click({
screenPosition: { x, y: 26 },
topHit,
drawHit: topHit,
gesture: { travelPx: 0, durationMs: 20 },
});
assert.deepEqual([zooms, clicks], expected);
}
} finally {
picking.unregisterPickOwner('cctv');
picking.unregisterPickOwner('flights');
}
});
test('a count click is the card on top for every layer, unless the count yields', () => {
let zooms = 0;
let clicks = 0;
const selection = createSelection({
services: { activation: {}, picking },
state: {
_enabled: true,
_counts: { pickedCell: (p) => (p?.x === 20 ? { key: 'g' } : null) },
_cctvOverlayHost: { hitTest: () => null },
},
parts: {
navigation: { zoomToCell: () => zooms++ },
rendering: {
extractPickedCameraId: (hit) =>
hit?.set === 'cctv-icons' ? hit.id : null,
},
},
});
const click = selection.bindCctvWorldClickGesture(
{ onClick: (fn) => fn },
() => clicks++,
);
const event = (topHit = null, x = 20, durationMs = 20) => ({
screenPosition: { x, y: 26 },
topHit,
drawHit: topHit,
gesture: { travelPx: 0, durationMs },
});
picking.registerClickClaim('cctv', selection.countClickCard);
picking.registerPickOwner('flights', (id) => id === 'abc');
try {
const aircraftFirst = event();
assert.equal(picking.isUnderOtherCard(aircraftFirst), true);
assert.deepEqual(picking.clickCard(aircraftFirst), {
sourceId: CCTV_COUNT_CARD_SOURCE_ID,
entryId: 'g',
});
click(aircraftFirst);
assert.deepEqual([zooms, clicks], [1, 0]);
const cctvFirst = event();
click(cctvFirst);
assert.equal(picking.isUnderOtherCard(cctvFirst), true);
assert.deepEqual([zooms, clicks], [2, 0]);
for (const [e, claimed, expected] of [
[event({ set: 'flights', id: 'abc' }), false, [2, 1]],
[event({ set: 'cctv-icons', id: 'cam-2' }), true, [3, 1]],
[event(null, 20, 1000), false, [3, 1]],
[event(null, 60), false, [3, 2]],
[{ ...event(), overlay: true }, false, [3, 3]],
]) {
assert.equal(picking.isUnderOtherCard(e), claimed);
click(e);
assert.deepEqual([zooms, clicks], expected);
}
} finally {
picking.unregisterClickClaim('cctv');
picking.unregisterPickOwner('flights');
}
});
+11 -3
View File
@@ -15,6 +15,7 @@ export function createState({ services }) {
/** The catalog's camera icons: the icon book over their draw set. */
layerState._icons = null;
layerState._counts = null;
layerState._records = [];
@@ -95,10 +96,14 @@ export function createState({ services }) {
// work over these, not the whole catalog.
layerState._viewRecords = [];
// The view records plus the best-ranked camera of each visible cell.
layerState._pickerRecords = [];
// Coverage ids refreshCoverageStyles last drew: part of the geometry
// working set even when their icons are thinned out.
// The active camera's coverage neighbours, including grouped ones. A
// grouping change in this cohort requires a coverage refresh.
layerState._coverageCohort = null;
// The cohort minus grouped cameras, last drawn by refreshCoverageStyles.
// These belong to the geometry working set even off screen.
layerState._coverageVisibleIds = new Set();
// View pass triggers besides camera settle: an interval while the camera
@@ -113,6 +118,9 @@ export function createState({ services }) {
// The camera port the moveStart/moveEnd listeners are on.
layerState._viewListenerCamera = null;
// Reruns the view pass when terrain loads or the surface changes.
layerState._surfaceListener = null;
layerState._surfaceListenerGlobe = null;
// A motion pass changed the shown set and the settle pass has not yet told
// subscribers; the camera pose the last view pass ran at.
+12
View File
@@ -1,3 +1,4 @@
import { createCountMarkers } from './countMarkers.js';
import { createIconBook } from '../../render/motion/iconBook.js';
/** A draw set that draws nothing, for the icon book the tests read. */
@@ -90,6 +91,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
* @param {'off'|'on'|'viewshed'} [options.coverageMode='on'] Coverage mode.
* @param {boolean} [options.showProjection=false] Projection visibility.
* @param {Map<string, Object>} [options.healthById] Health rows by camera id.
* @param {Function} [options.registerPaintLane] Receives the count painter.
* @returns {void}
*/
@@ -102,6 +104,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
showProjection = false,
healthById = new Map(),
openingCameraProvisional = false,
registerPaintLane,
} = {}) {
layerState._viewer = viewer;
layerState._records = Array.isArray(records) ? records : [];
@@ -123,12 +126,20 @@ export function createTesting({ state: layerState, services, parts, source }) {
layerState._showProjection = !!showProjection;
layerState._healthById = healthById;
layerState._viewRecords = [];
layerState._pickerRecords = [];
layerState._cameraIndexCache = null;
layerState._coverageVisibleIds = new Set();
layerState._neighborCountCache = null;
layerState._coverageCohort = null;
// A real book (over a set that draws nothing): every record gets its
// icon as init adds it.
layerState._icons = createIconBook(testIconSet());
layerState._counts?.dispose();
layerState._counts = createCountMarkers(
registerPaintLane,
'cctv:test:counts',
parts.rendering.refreshHorizonCulling,
);
for (const record of layerState._records)
if (record?.camera?.id) parts.rendering.addCameraIcon(record);
}
@@ -148,6 +159,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
for (const runtime of layerState._projectionEntities)
if (runtime?.plane) planes[runtime.plane.id] = runtime.plane;
return {
counts: layerState._counts,
gizmo: layerState._gizmo?.partsForTest() ?? {},
coverage,
planes,
+17
View File
@@ -5,6 +5,7 @@ import { createCredits } from './credits.js';
import { createPickRouter } from './pickRouter.js';
import { createSelection } from './selection.js';
import { createViewerHost } from './viewerHost.js';
import { subscribePhotoViewers } from './photoViewers.js';
import { filtersOf, requiresKeyIdFor, validateProviders } from './registry.js';
import { normalizeFilter, resolveFilter, sameFilter } from './filter.js';
import { worldTimeFor } from '../../time/worldClock.js';
@@ -703,6 +704,22 @@ 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, the one mounted last (see photoViewers.js), starting with the
* current one; null while none is mounted. A view draws it (see
* photoViewer.js); with nobody subscribed, those providers' photos
* cannot open.
* @param {(view: ?object) => void} listener
* @returns {() => void} Unsubscribe.
*/
subscribePhotoViewer(listener) {
return subscribePhotoViewers(
[...state.providers.values()].map((entry) => entry.instance.viewer),
listener,
);
},
setProviderEnabled,
openImage,
/**
+38
View File
@@ -2176,3 +2176,41 @@ 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 later 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 supersede = () => {};
const viewA = { host: 'a', mountKey: 1, actions: { supersede } };
const viewB = { host: 'b', mountKey: 2, actions: { supersede } };
a.present(viewA);
b.present(viewB);
a.present(null);
b.present(null);
assert.deepEqual(shown, [null, viewA, viewB, null]);
unsubscribe();
a.present(viewA);
assert.equal(shown.length, 4, 'unsubscribed');
});
+177 -83
View File
@@ -36,6 +36,14 @@ function tooManyPixels(width, height) {
);
}
/**
* Keys for each mount's and each canvas's elements, never reused by any
* viewer: a view that sees one viewer unmount and another mount in the same
* tick still draws them fresh elements (a destroyed renderer leaves its
* canvas's context lost).
*/
let viewKeys = 0;
/** Panorama texture widths: enough for a docked viewer, and for an expanded one. */
const PANO_MID_SIZE = Object.freeze([2048, 1024]);
export const PANO_FULL_SIZE = Object.freeze([4096, 2048]);
@@ -213,6 +221,21 @@ 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, mountKey, providerId, label, alt, kind, src, fit, canvasKey,
* dragging, prevLabel, prevDisabled, nextLabel, nextDisabled, actions}` on
* each change,
* or null while unmounted. A view draws it into `host` (the application's is
* `StreetLevelPhotoViewer`), forwards its events to `actions` and hands each
* element back through `actions.attach(name, element)`: the panorama canvas
* to draw on, the frame and picture to measure, the root and buttons to
* keep focus. Each mount has its own `mountKey`, and a new `canvasKey` asks
* for a fresh canvas (a lost WebGL context): neither is ever reused.
* `actions.supersede()` tells a viewer another one is drawn in its place:
* it unmounts, and a mount still waiting to be drawn fails as closed.
* Mounting with no view subscribed fails.
*
* Photos are normalized by the provider: `{id, sequenceId, lon, lat,
* heading, isPano, capturedAt}` plus whatever its `sources` read.
*
@@ -249,11 +272,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 its canvas: a fresh one, or the next draw. */
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 +295,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 +382,71 @@ 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 });
});
}
/** The view's next draw (it hands the canvas back each time), or none coming. */
function nextDraw(signal) {
if (!presented || signal?.aborted) return Promise.resolve();
return new Promise((resolve) => {
canvasWaiters.add(resolve);
signal?.addEventListener?.('abort', resolve, { once: true });
});
}
function syncButtons() {
const enabled = Boolean(photo?.sequenceId) && showing !== null;
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 +465,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 +479,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: ++viewKeys });
// 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 +492,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 +512,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 +546,7 @@ export function createPhotoViewer({
y: event.clientY,
view: renderer.getView(),
};
canvas.classList.add('sl-photo-dragging');
present({ dragging: true });
}
function onPointerMove(event) {
@@ -532,7 +574,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 +645,67 @@ 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),
supersede: current(() => adapter.unmount()),
step: current((delta, event) => {
event?.stopPropagation?.();
stepBy(delta);
}),
};
presented = {
host,
mountKey: ++viewKeys,
providerId,
label: t(
'{name} photo. ← and → step along the sequence. On a 360° photo, drag or use Shift+← →, ↑ ↓ to look around, and + − to zoom',
{ 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: ++viewKeys,
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 +713,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 +800,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 +832,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);
}
@@ -801,8 +864,15 @@ export function createPhotoViewer({
else if (!keepView || showing !== 'pano')
renderer.setView({ yaw: 0, pitch: 0, fov: PANO_FOV_DEFAULT_DEG });
photo = target;
// Shown first: a hidden canvas measures 0 and would be sized 1×1.
// Shown first: a hidden canvas measures 0 and would be sized 1×1. The
// view draws it shown on a microtask, and hands the canvas back then.
show('pano');
await nextDraw(signal);
if (seq !== openSeq || !renderer) {
image.close?.();
if (seq !== openSeq) return false;
throw new Error(LOAD_FAILED);
}
renderer.setImage(image);
panoWidth = first.width || 0;
// A sharper version of the photo before was dropped by `open`; one of
@@ -827,7 +897,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 +907,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 +932,17 @@ 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;
// Unmounted or superseded before the view drew it.
if (!root) throw new Error('Street-level viewer was closed');
},
/** Resolves once the photo is on screen and its pose was emitted. */
@@ -896,7 +978,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 +1019,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;
}
+74 -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,69 @@ 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 on a microtask, as Vue does, handing its canvas back
// each time, but draws a replacement canvas only a while after it is
// asked.
let shown = null;
let canvas = { name: 'canvas', clientWidth: 400 };
let late = null;
viewer.subscribeView((view) => {
const first = view && !shown;
const replaced = view && shown && view.canvasKey !== shown.canvasKey;
shown = view;
if (!view) return;
queueMicrotask(() => {
if (first)
for (const name of ['root', 'picture', 'prev', 'next'])
view.actions.attach(name, { name, clientWidth: 400 });
if (replaced) {
canvas = null;
late = () => {
canvas = { name: 'canvas again', clientWidth: 400 };
shown.actions.attach('canvas', canvas);
};
}
if (canvas) view.actions.attach('canvas', canvas);
});
});
await viewer.mount({});
await viewer.open('a');
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', 'canvas again'],
);
assert.equal(shown.kind, 'pano', 'not the front view');
});
+45
View File
@@ -0,0 +1,45 @@
/**
* Receive the photo viewer to draw, out of several photo viewers mounting
* in one host (see photoViewer.js): the one mounted last, by its mount key,
* whatever order they present in. One view draws one viewer, so a viewer
* still mounting when a later one presents is superseded: it settles its
* mount as closed and stops presenting. Starts with the current one (null
* while none is mounted).
* @param {Iterable<{subscribeView?: Function}>} viewers
* @param {(view: ?object) => void} listener
* @returns {() => void} Unsubscribe.
*/
export function subscribePhotoViewers(viewers, listener) {
// Each viewer's current presentation.
const shown = new Map();
let ready = false;
let last;
const publish = () => {
let next = null;
for (const view of shown.values())
if (!next || view.mountKey > next.mountKey) next = view;
if (!ready || next === last) return;
last = next;
listener(next);
// The others are not drawn: a mount still waiting on the view never
// would be.
if (next)
for (const view of [...shown.values()])
if (view.mountKey < next.mountKey) view.actions.supersede();
};
const unsubscribes = [];
for (const viewer of viewers) {
const unsubscribe = viewer?.subscribeView?.((view) => {
if (view) shown.set(viewer, view);
else shown.delete(viewer);
publish();
});
if (typeof unsubscribe === 'function') unsubscribes.push(unsubscribe);
}
ready = true;
publish();
if (last === undefined) listener((last = null));
return () => {
for (const unsubscribe of unsubscribes.splice(0)) unsubscribe();
};
}
@@ -0,0 +1,55 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { subscribePhotoViewers } from './photoViewers.js';
/**
* A photo viewer whose presentations the test sends; `superseded` counts.
* Unlike photoViewer.js it keeps presenting once superseded, so the order
* is seen to come from the mount keys alone.
*/
function fakeViewer() {
const listeners = new Set();
const viewer = {
superseded: 0,
view(mountKey) {
return {
mountKey,
actions: { supersede: () => viewer.superseded++ },
};
},
present(view) {
for (const listener of [...listeners]) listener(view);
},
subscribeView(listener) {
listeners.add(listener);
listener(null);
return () => listeners.delete(listener);
},
};
return viewer;
}
test('the later mount is drawn, whatever order the viewers present in', () => {
const a = fakeViewer();
const b = fakeViewer();
const shown = [];
const unsubscribe = subscribePhotoViewers([a, b], (view) => shown.push(view));
assert.deepEqual(shown, [null], 'the current one first');
const first = a.view(1);
a.present(first);
const later = b.view(2);
b.present(later);
assert.equal(shown.at(-1), later);
assert.equal(a.superseded, 1, 'the earlier mount is told it is not drawn');
// The earlier viewer presents again: it does not take the view back.
a.present({ ...first, kind: 'flat' });
assert.equal(shown.at(-1), later);
assert.equal(shown.length, 3);
b.present(null);
assert.equal(shown.at(-1).mountKey, 1, 'the only one presenting');
a.present(null);
assert.equal(shown.at(-1), null);
unsubscribe();
a.present(first);
assert.equal(shown.length, 5, 'unsubscribed');
});
@@ -13,7 +13,11 @@ import {
TOO_HIGH_HINT,
} from './policy.js';
import { validateProviders } from '../../registry.js';
import { fakeHost, until } from '../../../../testSupport/kartaViewFakes.mjs';
import {
drawn,
fakeHost,
until,
} from '../../../../testSupport/kartaViewFakes.mjs';
import {
bindStreetViewer,
coverageViewer,
@@ -190,7 +194,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 +289,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 +974,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));
@@ -978,6 +982,7 @@ test('after a GPU reset the photo is drawn again by the viewer, not through the
const canvas = () => host.children[0].children[1];
const kind = () => host.children[0].dataset.kind;
canvas().fire('webglcontextlost');
await drawn();
assert.equal(kind(), '', 'cleared while it is drawn again');
assert.ok(await until(() => kind() === 'pano'), 'drawn again');
assert.ok(poses.length >= 2);
@@ -1010,7 +1015,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 +1106,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.
@@ -1,7 +1,11 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createKartaViewViewer, loadImage, panoSizeFor } from './viewer.js';
import { fakeHost, until } from '../../../../testSupport/kartaViewFakes.mjs';
import {
drawn,
fakeHost,
until,
} from '../../../../testSupport/kartaViewFakes.mjs';
const PHOTOS = {
flat1: {
@@ -148,7 +152,7 @@ function setup({
});
const poses = [];
viewer.onPose((pose) => poses.push(pose));
const host = fakeHost();
const host = fakeHost(viewer);
return {
viewer,
poses,
@@ -223,6 +227,7 @@ test('a flat photo shows its 1280 px version, then the sharp one, with a pose fa
assert.equal(picture.src, loads[1].url, 'upgraded to the sharp version');
assert.equal(viewer.supportsRenderModes(), true);
viewer.setRenderMode('fill');
await drawn();
assert.equal(picture.style.objectFit, 'cover');
});
@@ -357,12 +362,14 @@ test('a newer open wins; close hides the photo; unmount tears down the panorama'
assert.equal(renderers.length, 0, 'nor built a WebGL context');
await viewer.open('pano1');
viewer.close();
await drawn();
const { picture, canvas, root } = parts(host);
assert.equal(canvas.hidden, true);
assert.equal(picture.hidden, true);
assert.equal(root.dataset.kind, '');
await assert.rejects(viewer.open('nope'), /no such photo/);
viewer.unmount();
await drawn();
assert.equal(host.children.length, 0);
assert.equal(renderers[0].destroyed, true);
await assert.rejects(viewer.open('flat1'), /not mounted/);
@@ -463,12 +470,14 @@ test('a lost WebGL context drops the panorama and shows the photo again on a new
const lost = parts(host).canvas;
lost.fire('webglcontextlost');
assert.equal(renderers[0].destroyed, true);
await drawn();
// A lost canvas only ever gives back its lost context: a new element.
assert.notEqual(parts(host).canvas, lost);
assert.deepEqual(stepped, ['pano1'], 'reopened through the core');
assert.ok(await until(() => renderers.length === 2), 'a new renderer');
assert.equal(renderers[1].canvas, parts(host).canvas);
assert.equal(poses.at(-1).imageId, 'pano1');
await drawn();
assert.equal(parts(host).canvas.hidden, false);
});
@@ -498,7 +507,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 +598,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 +807,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(
@@ -931,7 +940,7 @@ test('a docked viewer keeps the 1,280 px photo; expanding it brings the 2,560 px
viewer.resize();
assert.ok(await until(() => loads.length === 2));
assert.match(loads[1].url, /rs:fit:2560:2560/);
assert.equal(parts(host).picture.src, loads[1].url);
assert.ok(await until(() => parts(host).picture.src === loads[1].url));
viewer.resize();
for (let i = 0; i < 4; i++) await settle();
assert.equal(loads.length, 2, 'once only');
@@ -14,7 +14,11 @@ import {
} from './policy.js';
import { validateProviders } from '../../registry.js';
import { tileBounds } from '../../tileMath.js';
import { fakeHost, until } from '../../../../testSupport/kartaViewFakes.mjs';
import {
drawn,
fakeHost,
until,
} from '../../../../testSupport/kartaViewFakes.mjs';
import {
bindStreetViewer,
coverageViewer,
@@ -284,7 +288,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 +324,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 +989,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));
@@ -994,6 +998,8 @@ test('after a GPU reset the viewer draws the same picture itself, leaving the co
const kind = () => host.children[0].dataset.kind;
assert.equal(kind(), 'pano');
canvas().fire('webglcontextlost');
await drawn();
assert.equal(kind(), '', 'cleared while it is drawn again');
assert.ok(await until(() => kind() === 'pano'), 'drawn again');
assert.deepEqual(poses, ['p-0', 'p-0']);
assert.deepEqual(actions.opened, [], 'not through the core');
@@ -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
+1 -1
View File
@@ -294,7 +294,7 @@ test('Location markup provides one named native disclosure linked to its popover
assert.match(locationToggleMarkup[2], /class="location-toolbar-label"/);
assert.doesNotMatch(locationToggleMarkup[2], /<button\b/);
assert.match(locationMarkup.slice(locationToggleMarkup.index + locationToggleMarkup[0].length),
/^\s*<button class="panel-collapse-btn" data-collapse-target="location-bar"/);
/^\s*<button type="button" class="[^"]*\bpanel-collapse-btn\b[^"]*"[^>]*\sdata-collapse-target="location-bar"/);
assert.match(locationMarkup, /<div id="location-bar-popover" class="dock-popover-content">/);
});
+1 -1
View File
@@ -349,7 +349,7 @@ test('the Visual Presets tray owns Map Source and the retired left panel is abse
);
assert.match(
html,
/<button id="control-panel-toggle"[\s\S]*?data-dock-toggle-target="control-panel"[\s\S]*?aria-controls="control-panel-popover"/,
/<button\b[^>]*\bid="control-panel-toggle"[\s\S]*?data-dock-toggle-target="control-panel"[\s\S]*?aria-controls="control-panel-popover"/,
'the compact wing must expose a semantic keyboard disclosure',
);
const panels = readFileSync(
+3
View File
@@ -244,6 +244,9 @@ const _customPaintFrame = {
cameraHeight: Number.NaN,
occluder: null,
keyhole: null,
// Anchored custom glyphs yield to the same below-host chrome as entries.
overlapsHardUi: (rect) =>
overlayRectIntersectsAnyHard(rect, _uiOcclusionRects),
uiRects: _uiOcclusionRects,
uiRectCount: 0,
layoutRevision: 0,
+5
View File
@@ -1514,9 +1514,14 @@ test('a placement is only ever kept under chrome that composites ABOVE the host'
const paintedUnder = (occluders) => {
const env = installMockEnvironment({ width: 400, height: 300, dpr: 1, occluders });
initWorldOverlay(env.viewer);
let hardUi;
registerWorldOverlayPaintLane('ambient-label', (frame) => {
hardUi = frame.overlapsHardUi({ x: 180, y: 130, w: 40, h: 40 });
}, { id: 'anchored-label', active: true });
setOverlayEntries('ambient', [selectedEntry('CONTACT')]);
env.postRender.raise();
const { paintedCount } = getWorldOverlayDiagnostics();
assert.equal(hardUi, paintedCount === 0);
env.cleanup();
return paintedCount;
};
+16 -9
View File
@@ -92,6 +92,7 @@ out vec2 v_uv;
out vec4 v_color;
out vec4 v_pickColor;
out float v_proxy;
out float v_overDepth; // 1 for a row drawn over depth, on the near plane
// The row's anchor in clip space before screen offsets, for effects that wrap
// main() (sonar) and must not change geometry or picks.
@@ -125,6 +126,7 @@ void main() {
v_uv = vec2(0.0);
v_color = vec4(0.0);
v_proxy = 0.0;
v_overDepth = 0.0;
gl_Position = vec4(0.0, 0.0, 2.0, 1.0); // outside the clip volume: not drawn
float flags = style1.z;
@@ -260,14 +262,9 @@ void main() {
distanceSq < style3.w * style3.w;
if (overDepth && zclip >= -1.0 && zclip <= 1.0) {
gl_Position.z = -gl_Position.w;
#ifdef LOG_DEPTH
// Just past the near plane, not on it: czm_writeLogDepth discards a
// fragment at or below 0.9999999, and 1.0 interpolated across the quad
// can arrive a rounding step or two under that, dropping the icon for a
// frame as it moves (flicker). 1e-4 m past the near plane is still in
// front of everything the scene draws.
v_depthFromNearPlusOne = 1.0001;
#endif
// With a log depth buffer the fragment shader writes the near plane's
// depth itself.
v_overDepth = 1.0;
}
v_uv = mix(rect.xy, rect.zw, vec2(corner.x * 0.5 + 0.5, 0.5 - corner.y * 0.5));
@@ -282,6 +279,7 @@ in vec2 v_uv;
in vec4 v_color;
in vec4 v_pickColor;
in float v_proxy;
in float v_overDepth;
void main() {
vec4 color = czm_gammaCorrect(texture(u_atlas, v_uv));
@@ -296,7 +294,16 @@ void main() {
#endif
out_FragColor = color;
#ifdef LOG_DEPTH
czm_writeLogDepth(v_depthFromNearPlusOne);
// Over depth: exactly the near plane's depth, written here and not through
// czm_writeLogDepth. That function discards a fragment whose interpolated
// depth arrives a rounding step under the near plane (the icon drops for a
// frame as it moves), and any depth past the near plane is a surface to
// Cesium's depth pick: the camera controller then sizes a zoom step from an
// icon under the canvas centre, a near plane's distance away, and the wheel
// stops zooming. The pick reads a depth of 0 as nothing drawn, and keeps
// the depth of the ground under the icon.
if (v_overDepth > 0.5) gl_FragDepth = 0.0;
else czm_writeLogDepth(v_depthFromNearPlusOne);
#endif
}
`;
@@ -1,5 +1,6 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import fs from 'node:fs';
import * as Cesium from 'cesium';
import { createIconSet } from '../../data/iconSet.js';
import { IconSetPrimitive } from './iconSetPrimitive.js';
@@ -58,3 +59,29 @@ test('by default the set draws an opaque pass and a translucent one, and draws n
assert.equal(translucent.renderState.depthMask, false);
assert.equal(primitive.drawsBlend('translucent'), false);
});
test('an over-depth row writes a depth of exactly 0, which a depth pick ignores', () => {
// Shaders do not compile under node: this reads the fragment shader's
// source. A depth past the near plane (as 1.0001 through
// czm_writeLogDepth was) is a surface to Cesium's depth pick, a near
// plane's distance from the camera, and the wheel stops zooming with an
// icon under the canvas centre (scripts/qa-zoom-under-icon.mjs).
const source = fs.readFileSync(
new URL('./iconSetPrimitive.js', import.meta.url),
'utf8',
);
const [vertex, fragment] = source
.slice(source.indexOf('const VERTEX_SHADER'))
.split('const FRAGMENT_SHADER')
.map((shader) => shader.replace(/\/\/.*$/gm, '')); // comments out
assert.match(
fragment,
/if \(v_overDepth > 0\.5\) gl_FragDepth = 0\.0;\s+else czm_writeLogDepth\(v_depthFromNearPlusOne\);/,
);
// The vertex shader flags the row and leaves its log depth alone.
assert.match(
vertex,
/gl_Position\.z = -gl_Position\.w;[^}]*v_overDepth = 1\.0;/,
);
assert.doesNotMatch(vertex, /v_depthFromNearPlusOne\s*=/);
});
+112 -3
View File
@@ -60,13 +60,119 @@ 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 through Vue: changes made in one tick are
* drawn once, on a microtask, with their final value; the root (keyed by
* the mount) holds the picture, the panorama canvas (keyed by its canvas
* key) and the ‹ › buttons, kept while their keys are, and every element
* is handed back on each draw. A value is written only when the drawn
* presentation changes it, and the elements' events reach the viewer's
* actions.
* @returns {() => void} Stop drawing.
*/
export function drawPhotoViewer(viewer) {
let parts = null;
let last = null;
let pending = null;
let queued = false;
const on = (element, type, name) =>
element.addEventListener(type, (event) => last?.actions[name](event));
const canvasFor = () => {
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 draw = (view) => {
if (!view) {
parts?.root.remove();
parts = last = null;
return;
}
if (!parts || last.mountKey !== view.mountKey) {
parts?.root.remove();
parts = build(view);
last = null;
} else if (last.host !== view.host) {
parts.root.remove();
view.host.append(parts.root);
}
const changed = (key) => !last || last[key] !== view[key];
let canvasFresh = !last;
if (last && changed('canvasKey')) {
const canvas = canvasFor();
parts.canvas.replaceWith(canvas);
parts.canvas = canvas;
canvasFresh = true;
}
const { root, picture, canvas, prev, next } = parts;
if (changed('providerId')) root.dataset.provider = view.providerId;
if (changed('label')) root.attributes['aria-label'] = view.label;
if (changed('kind') && view.kind !== undefined)
root.dataset.kind = view.kind;
if (changed('alt')) picture.alt = view.alt;
if (changed('src')) {
if (view.src) picture.src = view.src;
else picture.removeAttribute('src');
}
if (changed('fit')) picture.style.objectFit = view.fit;
if (changed('kind')) picture.hidden = view.kind !== 'flat';
if (changed('kind') || canvasFresh) canvas.hidden = view.kind !== 'pano';
if (changed('dragging') || canvasFresh) {
if (view.dragging) canvas.classList.add('sl-photo-dragging');
else canvas.classList.remove('sl-photo-dragging');
}
if (changed('prevLabel')) prev.attributes['aria-label'] = view.prevLabel;
if (changed('nextLabel')) next.attributes['aria-label'] = view.nextLabel;
if (changed('prevDisabled')) prev.disabled = view.prevDisabled;
if (changed('nextDisabled')) next.disabled = view.nextDisabled;
last = view;
for (const name of ['root', 'picture', 'canvas', 'prev', 'next'])
view.actions.attach(name, parts[name]);
};
return viewer.subscribeView((view) => {
pending = view;
if (queued) return;
queued = true;
queueMicrotask(() => {
queued = false;
draw(pending);
});
});
}
/**
* 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
@@ -79,3 +185,6 @@ export async function until(condition, { ticks = 200 } = {}) {
}
return Boolean(await condition());
}
/** Let a photo viewer's view draw what was presented in this tick. */
export const drawn = () => new Promise((resolve) => queueMicrotask(resolve));
+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,98 @@
<script setup>
import { t } from '../../i18n/index.js';
// The Bhote Koshi event's embedded media cards and the hidden YouTube
// preload, as src/data/bhoteKoshiEmbeddedMedia.js presents them inside its
// overlay root. The owner renders synchronously on every change and places
// each card beside its map anchor after each frame (its position, its
// leader's line and whether it shows); a card's player is filled by the
// provider: the YouTube frame drawn here, or the Facebook player and X post
// the provider SDKs build inside it. The card's body takes taps (the root
// and the leader do not); Stories keeps that.
defineProps({
/** `{key, src, title}` of the hidden YouTube preload, or null. */
warm: { type: Object, default: null },
/**
* The cards in insertion order: `{id, provider, portrait, entering,
* leaving, unavailable, label, title, status, url, frame, bind}`; `frame`
* is `{src, title, onLoad}` for a YouTube card and null otherwise, and
* `bind(name, element)` hands the owner the elements it places and fills.
*/
cards: { type: Array, default: () => [] },
});
</script>
<template>
<iframe
v-if="warm"
:key="warm.key"
class="bhote-embedded-media-warmup"
:src="warm.src"
:title="warm.title"
tabindex="-1"
aria-hidden="true"
loading="eager"
referrerpolicy="strict-origin-when-cross-origin"
></iframe>
<section
v-for="card in cards"
:key="card.id"
:ref="(el) => card.bind('card', el)"
class="bhote-embedded-callout"
:class="[
`is-${card.provider}`,
{
'is-portrait': card.portrait,
'is-entering': card.entering,
'is-leaving': card.leaving,
'is-unavailable': card.unavailable,
},
]"
:data-provider="card.provider"
:aria-label="card.label"
>
<svg
:ref="(el) => card.bind('leader', el)"
class="bhote-embedded-callout-leader"
aria-hidden="true"
>
<path
pathLength="1"
fill="none"
stroke="rgba(147,213,228,.72)"
stroke-width="1.5"
/>
<circle r="4" fill="#6be8ff" stroke="#ffffff" stroke-width="1.5" />
</svg>
<div class="bhote-embedded-callout-body" data-overlay-input>
<div
v-if="card.frame"
:ref="(el) => card.bind('player', el)"
class="bhote-embedded-callout-player ui-scroll"
>
<iframe
:ref="(el) => card.bind('frameElement', el)"
:src="card.frame.src"
:title="card.frame.title"
allow="autoplay; encrypted-media; picture-in-picture; fullscreen"
allowfullscreen
loading="eager"
referrerpolicy="strict-origin-when-cross-origin"
@load.once="card.frame.onLoad"
></iframe>
</div>
<div
v-else
:ref="(el) => card.bind('player', el)"
class="bhote-embedded-callout-player ui-scroll"
></div>
<footer>
<strong>{{ card.title }}</strong>
<small role="status">{{ card.status }}</small>
<a :href="card.url" target="_blank" rel="noopener noreferrer">{{
t('OPEN ORIGINAL ↗')
}}</a>
</footer>
</div>
</section>
</template>
+3 -2
View File
@@ -3,6 +3,7 @@ import { storeToRefs } from 'pinia';
import { computed } from 'vue';
import { t } from '../../i18n/index.js';
import { useCctvStore } from '../stores/cctv.js';
import UiButton from '../kit/UiButton.vue';
// One click-to-type pose chip. The panel's delegated click starts an edit
// in CctvControls, which publishes it; the chip then holds a number input
@@ -42,7 +43,7 @@ function onBlur(event) {
</script>
<template>
<button
<UiButton
class="cctv-cal-value"
:data-cal-field="field"
:disabled="edit ? false : view?.calibration.disabled"
@@ -60,6 +61,6 @@ function onBlur(event) {
@click.stop /></template
><template v-else>{{
view?.calibration.values[field] ?? `${t(label)} --`
}}</template></button
}}</template></UiButton
>
</template>
+4 -1
View File
@@ -58,7 +58,10 @@ test('before ContextControls renders, the switch shows its initial markup', (t)
);
assert.equal(panel.hasAttribute('data-context-mode'), false);
const tab = $('global-context-flights-btn');
assert.equal(tab.className, 'context-mode-button');
assert.equal(
tab.className,
'ui-button ui-focus ui-button--ghost ui-button--accent context-mode-button',
);
assert.equal(tab.getAttribute('aria-selected'), 'false');
assert.equal(tab.getAttribute('tabindex'), '0');
assert.equal(tab.hasAttribute('aria-busy'), false);
+11 -3
View File
@@ -1,5 +1,6 @@
<script setup>
import { t } from '../../i18n/index.js';
import UiButton from '../kit/UiButton.vue';
import UiCloseButton from '../kit/UiCloseButton.vue';
import CreditItem from './CreditItem.vue';
@@ -33,6 +34,12 @@ const props = defineProps({
const SEPARATOR = ' · ';
/** A credit's key: the same text and link are one credit. */
const key = (credit) => `${credit.text}\u0000${credit.href ?? ''}`;
// The list button's words are the slot of a UiButton, which renders inside
// the button: a locale that is not bound to a ref changes nothing the button
// reads, and the owner patches synchronously and reads the result at once. A
// slot given under a condition (`redrawWithView`, always true) is redrawn
// whenever this view is, so the words follow a new locale with the rest.
const redrawWithView = true;
/** Keep `name`'s element for the owner. */
const keep = (name) => (element) => {
props.elements[name] = element?.$el ?? element;
@@ -46,16 +53,17 @@ const keep = (name) => (element) => {
><template v-for="(credit, i) in props.inline" :key="key(credit)"
>{{ i ? SEPARATOR : '' }}<CreditItem :credit="credit" /></template
>{{ props.inline.length && props.listed.length ? SEPARATOR : '' }}</span
><button
><UiButton
:ref="keep('expand')"
type="button"
class="gev-credits-expand"
aria-haspopup="dialog"
:aria-controls="props.panelId"
:aria-expanded="String(props.open)"
:hidden="props.listed.length === 0"
@click="props.onExpand()"
>{{ t('Data attribution') }}</button
><template v-if="redrawWithView" #default>{{
t('Data attribution')
}}</template></UiButton
></div
><div
:id="props.panelId"
+1 -1
View File
@@ -557,7 +557,7 @@ test('the imported files render what the file import publishes and keep focus',
assert.equal(name.textContent, '<b>a</b>.geojson');
assert.equal(name.children.length, 0, 'the name is text');
assert.match(name.title, /GEOJSON, 2 map objects$/);
assert.equal(toggle.className, 'geo-import-action');
assert.ok(toggle.classList.contains('geo-import-action'));
assert.equal(toggle.getAttribute('type'), 'button');
assert.equal(toggle.getAttribute('aria-pressed'), 'true');
assert.equal(toggle.getAttribute('aria-label'), 'Hide <b>a</b>.geojson');
+1 -1
View File
@@ -162,7 +162,7 @@ export function initGeoFileImport({
? t('Hide {name}', { name: item.name })
: t('Show {name}', { name: item.name }),
action: 'toggle',
pressed: String(item.visible),
pressed: Boolean(item.visible),
},
{
icon: 'my_location',
+1 -1
View File
@@ -220,7 +220,7 @@ test('row buttons hide, show, fly to and remove a file', async () => {
shapes: [],
});
assert.equal(t.tool.list()[0].visible, false);
assert.equal(action(rows(t)[0], 'toggle').pressed, 'false');
assert.equal(action(rows(t)[0], 'toggle').pressed, false);
assert.equal(action(rows(t)[0], 'toggle').icon, 'visibility_off');
assert.equal(action(rows(t)[0], 'toggle').label, 'Show a.gpx');
glyphClick('fly');
+1 -1
View File
@@ -53,7 +53,7 @@ test('the divider renders on the body with its labels and slider', async (t) =>
assert.equal(after.title, 'After');
assert.equal(handle.tagName, 'BUTTON');
assert.equal(handle.type, 'button');
assert.equal(handle.className, 'split-handle');
assert.ok(handle.classList.contains('split-handle'));
assert.equal(handle.textContent, '↔');
assert.equal(handle.getAttribute('role'), 'slider');
assert.equal(handle.getAttribute('aria-label'), 'Divider');
+119
View File
@@ -0,0 +1,119 @@
// The Bhote Koshi event's controls are the kit's: its reconstruction panel
// hand-writes no <button> and no Material Symbols span, its buttons are ghost
// UiButtons that keep their data-action hooks for bhote-koshi.css and the
// tests, and its cinematic button is a pressed toggle whose state the event
// layer presents as `pressed`, not as an `aria-pressed` it writes. The
// embedded media cards are an SFC rather than markup built in script; they
// hold no control (the original link stays a link), and the script builds
// only what the provider SDKs need: their script and preconnect tags, the
// overlay root, and the Facebook player node it warms and carries into a
// card.
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 PANEL = 'ui/views/panels/BhoteKoshiPanel.vue';
const CARDS = 'ui/bhoteKoshi/BhoteKoshiMediaCards.vue';
// Per file: its UiButtons, UiCloseButtons, UiSliders and UiIcons.
const SURFACES = {
// Previous and next beat, Play, Play scene, Cinematic, Full story, Open
// original, Lower gorge, a field report (one tag, one per report) and Open
// public map; Close; the split and progress sliders.
[PANEL]: [10, 1, 2, 0],
// The media cards: a frame, a leader, a footer and the original link.
[CARDS]: [0, 0, 0, 0],
};
test('the Bhote Koshi views hand-write no button; each is a kit button', () => {
for (const [file, [buttons, closes, sliders]] of Object.entries(SURFACES)) {
const markup = template(file);
assert.deepEqual(markup.match(/<button\b/gi) ?? [], [], file);
assert.deepEqual(markup.match(/<(select|input)\b/gi) ?? [], [], file);
assert.equal(tags(markup, 'UiButton').length, buttons, file);
assert.equal(tags(markup, 'UiCloseButton').length, closes, file);
assert.equal(tags(markup, 'UiSlider').length, sliders, file);
}
});
test('the Bhote Koshi views hand-write no Material glyph', () => {
for (const [file, [, , , icons]] of Object.entries(SURFACES)) {
const markup = template(file);
assert.deepEqual(markup.match(/material-symbols/g) ?? [], [], file);
const found = tags(markup, 'UiIcon');
assert.equal(found.length, icons, file);
for (const icon of found) assert.match(icon, /\s:size="null"/, file);
}
});
test('the cinematic button takes the kit pressed state', () => {
for (const file of Object.keys(SURFACES))
for (const [tag, attrs] of template(file).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,
);
}
const pressed = tags(template(PANEL), 'UiButton').filter((tag) =>
/\s:pressed=/.test(tag),
);
assert.equal(pressed.length, 1);
assert.match(
pressed[0],
/^<UiButton data-action="cinematic" :pressed="Boolean\(panel\.refs\.cinematicButton\.pressed\)"/,
);
// bhote-koshi.css styles the pressed button by its aria-pressed.
assert.doesNotMatch(pressed[0], /pressed-class/);
// The layer presents the state; it writes no aria-pressed of its own.
const layer = read('data/bhoteKoshiEvent.js');
assert.doesNotMatch(layer, /aria-pressed/);
assert.match(
layer,
/setElementProperty\(button, 'pressed', _cinematicActive\)/,
);
});
test('the media cards are drawn by their view, not built in script', () => {
const source = read('data/bhoteKoshiEmbeddedMedia.js');
assert.doesNotMatch(source, /innerHTML|insertAdjacentHTML|createElementNS/);
// Provider scripts and preconnects, the overlay root, and the Facebook
// embed node and its warm host.
assert.deepEqual(
[...source.matchAll(/createElement\('(\w+)'\)/g)].map((m) => m[1]),
['script', 'script', 'script', 'link', 'div', 'div', 'div'],
);
assert.match(source, /renderVue\(\s*h\(BhoteKoshiMediaCards,/);
const cards = template(CARDS);
const opening = (name, attribute) =>
new RegExp(String.raw`<${name}\b${ATTRS}\s${attribute}${ATTRS}>`);
for (const part of [
opening('iframe', 'class="bhote-embedded-media-warmup"'),
opening('section', 'class="bhote-embedded-callout"'),
opening('svg', 'class="bhote-embedded-callout-leader"'),
opening('div', 'class="bhote-embedded-callout-body" data-overlay-input'),
opening('small', 'role="status"'),
opening('a', 'target="_blank" rel="noopener noreferrer"'),
])
assert.match(cards, part);
});
+150
View File
@@ -0,0 +1,150 @@
// The AI chat panel's and the voice control's buttons and Material glyphs
// are the kit's: neither their templates nor the voice card and panel
// layout buttons they render hand-write a <button> or a Material Symbols
// span. Their other glyphs (the chat bubble, the globe, attach, send and
// stop, expand and the two Back chevrons) are inline SVG drawn with their own
// strokes, which no Material symbol the page loads draws the same, so they
// stay SVG. The voice panel's Preview and Settings are tabs (`role="tab"`
// with `aria-selected`), not pressed toggles, and DISMISS is a text button,
// not a cross, so it is a UiButton rather than a UiCloseButton. The chat's
// message box, file picker and the minutes field stay native: the kit has
// no text area, file or number field. The voice modules build no controls
// in script.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync, readdirSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
/** A view's template block: everything outside script, style and comments. */
function template(file) {
const source = readFileSync(
new URL(`../views/panels/${file}`, import.meta.url),
'utf8',
);
return source
.replace(/<(script|style)\b[\s\S]*?<\/\1\s*>/g, '')
.replace(/<!--[\s\S]*?-->/g, '');
}
// A tag's attributes, read past quoted values so a handler's `=>` does not
// end the tag early.
const ATTRS = String.raw`(?:[^>"']|"[^"]*"|'[^']*')*`;
const tag = (pattern, flags = '') =>
new RegExp(pattern.replaceAll('ATTRS', ATTRS), flags);
const tags = (markup, name) =>
markup.match(tag(String.raw`<${name}\bATTRS>`, 'g')) ?? [];
const views = {
// Settings, the quick prompts, an attachment's remove, Attach layer,
// Attach a file, Expand conversation, the command suggestions, Expand
// chat, Add attachment and Send / Stop reply.
'ChatPanel.vue': {
UiButton: 10,
UiCloseButton: 1,
UiIcon: 1,
UiSelect: 1,
svgs: 5,
},
// The tier button (dock and panel), the mic, Open AI chat, Back to chat,
// Back to voice, the Preview and Settings tabs and DISMISS.
'VoiceControl.vue': {
UiButton: 9,
UiCloseButton: 1,
UiIcon: 2,
UiSelect: 3,
UiCheckbox: 2,
svgs: 3,
},
'VoiceCard.vue': { UiButton: 0, UiCloseButton: 1, UiIcon: 0, svgs: 0 },
// Dock and minimize.
'PanelLayoutButtons.vue': { UiButton: 2, UiIcon: 0, svgs: 2 },
'VoiceVisualizer.vue': { UiButton: 0, UiIcon: 0, svgs: 1 },
};
const markup = Object.fromEntries(
Object.keys(views).map((file) => [file, template(file)]),
);
test('the chat and voice views hand-write no button; each is the kit', () => {
for (const [file, counts] of Object.entries(views)) {
assert.deepEqual(markup[file].match(/<button\b/gi) ?? [], [], file);
for (const name of ['UiButton', 'UiCloseButton', 'UiSelect', 'UiCheckbox'])
assert.equal(tags(markup[file], name).length, counts[name] ?? 0, file);
}
});
test('the pressed toggles take the kit pressed state', () => {
for (const [file, view] of Object.entries(markup))
assert.doesNotMatch(view, /aria-pressed/, file);
const voice = tags(markup['VoiceControl.vue'], 'UiButton');
const tiers = voice.filter((button) => /id="gev-voice-tier"/.test(button));
assert.equal(tiers.length, 2);
for (const tier of tiers)
assert.match(tier, /\s:pressed="Boolean\(view\.tier\.pressed\)"/);
// The mic writes no aria-pressed while its owner has no state for it.
assert.match(
markup['VoiceControl.vue'],
tag(
String.raw`<UiButton\s+id="gev-voice-button"ATTRS\s:pressed="view\.button\.pressed \?\? undefined"`,
),
);
assert.match(
markup['PanelLayoutButtons.vue'],
tag(
String.raw`<UiButton\s+data-layout-dockATTRS\s:pressed="props\.docked"`,
),
);
// The panel tabs are tabs: selected, never pressed.
const tabs = voice.filter((button) => /role="tab"/.test(button));
assert.equal(tabs.length, 2);
for (const button of tabs) {
assert.match(button, /\s:aria-selected="/);
assert.doesNotMatch(button, /\s:pressed=/);
}
});
test('the views hand-write no Material glyph; each is a UiIcon the site sizes', () => {
for (const [file, { UiIcon, svgs }] of Object.entries(views)) {
assert.deepEqual(markup[file].match(/material-symbols/g) ?? [], [], file);
const icons = tags(markup[file], 'UiIcon');
assert.equal(icons.length, UiIcon, file);
// Without it the kit writes an 18px size that beats voice-cost.css and
// voice-card.css.
for (const icon of icons) assert.match(icon, /\s:size="null"/, file);
assert.equal(markup[file].match(/<svg\b/g)?.length ?? 0, svgs, file);
}
assert.match(
markup['ChatPanel.vue'],
/<UiIcon name="settings" class="gev-voice-settings-icon" :size="null" \/>/,
);
assert.equal(
markup['VoiceControl.vue'].match(
/<UiIcon name="(?:visibility|settings)" class="gev-voice-panel-tab-icon" :size="null" \/>/g,
)?.length,
2,
);
});
test('the only native fields left are the message box, file picker and minutes', () => {
const inputs = Object.values(markup).flatMap((view) => tags(view, 'input'));
assert.equal(inputs.length, 2);
assert.match(inputs[0], /id="gev-chat-file" type="file"/);
assert.match(inputs[1], /id="gev-voice-timeout-input" type="number"/);
assert.equal(tags(markup['ChatPanel.vue'], 'textarea').length, 1);
for (const view of Object.values(markup)) {
assert.deepEqual(view.match(/<select\b/gi) ?? [], []);
assert.doesNotMatch(view, /type="(?:checkbox|range)"/);
}
});
test('the voice modules build no buttons or Material glyphs in script', () => {
const root = fileURLToPath(new URL('../../voice/', import.meta.url));
const modules = readdirSync(root, { recursive: true })
.filter((file) => file.endsWith('.js') && !/test|Harness/.test(file))
.map((file) => path.join(root, file));
assert.ok(modules.length > 50);
for (const file of modules) {
const source = readFileSync(file, 'utf8');
assert.doesNotMatch(source, /createElement\(\s*['"]button/, file);
assert.doesNotMatch(source, /<button\b|material-symbols/, file);
}
});
+9 -3
View File
@@ -1,6 +1,7 @@
// Every close, dismiss and clear button in a Vue view is a UiCloseButton: no
// SFC template hand-writes a button whose only content is × or the Material
// `close` symbol. Buttons built in script are not read here.
// SFC template hand-writes a button whose only content is × (bare or in a
// span) or the Material `close` symbol. Buttons built in script are not read
// here.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync, readdirSync } from 'node:fs';
@@ -30,8 +31,10 @@ function template(source) {
// An opening tag's attributes, quoted values may hold `>` (`() => x`).
const ATTRS = String.raw`(?:[^>"']|"[^"]*"|'[^']*')*`;
const BUTTON = String.raw`(button|UiButton)`;
const TIMES = String.raw`×|&times;|&#215;|&#xd7;`;
const CLOSE_GLYPH = [
String.raw`×|&times;|&#215;|&#xd7;`,
TIMES,
String.raw`<span\b${ATTRS}>\s*(?:${TIMES})\s*</span\s*>`,
String.raw`<span\b[^>]*\bmaterial-symbols-outlined\b[^>]*>\s*close\s*</span\s*>`,
String.raw`<UiIcon${ATTRS}\bname="close"${ATTRS}/>`,
].join('|');
@@ -54,11 +57,14 @@ test('the scan finds each hand-written close glyph', () => {
'<template><UiButton class="x" :label="l">&times;</UiButton></template>',
'<template><button type="button" class="x">\n <span class="material-symbols-outlined" aria-hidden="true">close</span>\n</button></template>',
'<template><UiButton class="x"><UiIcon name="close" :size="14" /></UiButton></template>',
'<template><button type="button" :aria-label="l"><span aria-hidden="true">×</span></button></template>',
'<template><UiButton class="x">\n <span class="glyph">&times;</span>\n</UiButton></template>',
])
assert.equal(handWrittenCloses(markup).length, 1, markup);
for (const markup of [
'<template><UiCloseButton class="x" :label="l" /></template>',
'<template><button type="button">{{ name }} ×</button></template>',
'<template><button type="button"><span>{{ name }}</span> ×</button></template>',
'<template><button type="button">On<span class="material-symbols-outlined">close</span></button></template>',
'<template><button type="button"><span class="material-symbols-outlined">close_fullscreen</span></button></template>',
])
+148
View File
@@ -0,0 +1,148 @@
// The Cockpit HUD's controls and glyphs are the kit's: no Cockpit view
// hand-writes a <button>, a Material Symbols span, a select, a checkbox or a
// range. Its buttons are ghost UiButtons that keep their ids, classes and
// labels for the Cockpit controller's listeners and the cockpit stylesheets;
// its glyphs are UiIcons with `:size="null"`, so those stylesheets still size
// them. The utility strip's −, ◀ ▶ and transport glyphs and the orbital
// zoom's − and + are text characters, not Material symbols, and stay text.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readdirSync, readFileSync } from 'node:fs';
/** A view's template block: everything outside script, style and comments. */
function template(file) {
const source = readFileSync(
new URL(`../views/${file}`, import.meta.url),
'utf8',
);
return source
.replace(/<(script|style)\b[\s\S]*?<\/\1\s*>/g, '')
.replace(/<!--[\s\S]*?-->/g, '');
}
const views = {
// The vision selector's Previous, Current and Next, Look ahead, and the
// view switcher's Reset and Exit; the speed and altitude rims' pointers,
// the two vision chevrons, the reticle, the heading caret and the view
// switcher's two glyphs.
'CockpitView.vue': { buttons: 6, icons: 8 },
// Display's and Radio's collapse and launcher buttons, Radio's Enable,
// Previous, Play and Next, and the desktop rail's two items and glyphs.
'panels/CockpitUtilityControls.vue': { buttons: 10, icons: 2 },
// Previous, Next, Auto, the card's collapse and the three page tabs; the
// first, second and fourth draw a glyph.
'panels/CockpitBriefing.vue': { buttons: 7, icons: 3 },
// Previous, Next, the card's collapse and Weather; three of them draw a
// glyph, and the nearest contact's arrow is the fourth.
'panels/CockpitContext.vue': { buttons: 4, icons: 4 },
// A signal row's target and its chevron.
'panels/CockpitSignalList.vue': { buttons: 1, icons: 1 },
// TLE, Nadir, Zoom out, Zoom in and Sensor.
'panels/CockpitOrbital.vue': { buttons: 5, icons: 0 },
// The range step.
'panels/CockpitRadar.vue': { buttons: 1, icons: 0 },
// The flight plan's arrow.
'panels/CockpitRoute.vue': { buttons: 0, icons: 1 },
// Readouts only.
'panels/CockpitProgress.vue': { buttons: 0, icons: 0 },
'panels/CockpitRollingValue.vue': { buttons: 0, icons: 0 },
};
// A tag's attributes, read past quoted values so a handler's `=>` does not
// end the tag early.
const ATTRS = String.raw`(?:[^>"']|"[^"]*"|'[^']*')*`;
const tag = (pattern, flags = '') =>
new RegExp(pattern.replaceAll('ATTRS', ATTRS), flags);
const markup = Object.fromEntries(
Object.keys(views).map((file) => [file, template(file)]),
);
test('every Cockpit view is in the list above', () => {
const dir = (sub) =>
readdirSync(new URL(`../views/${sub}`, import.meta.url))
.filter((name) => /^Cockpit.*\.vue$/.test(name))
.map((name) => sub + name);
assert.deepEqual(
[...dir(''), ...dir('panels/')].sort(),
Object.keys(views).sort(),
);
});
test('the Cockpit views hand-write no button; each is a UiButton', () => {
for (const [file, { buttons }] of Object.entries(views)) {
assert.deepEqual(markup[file].match(/<button\b/gi) ?? [], [], file);
assert.equal(
markup[file].match(/<UiButton\b/g)?.length ?? 0,
buttons,
file,
);
}
});
test('the Cockpit views hand-write no select, checkbox or range', () => {
for (const [file, view] of Object.entries(markup)) {
assert.deepEqual(view.match(/<(select|input)\b/gi) ?? [], [], file);
}
// The compact Radio volume.
assert.equal(
markup['panels/CockpitUtilityControls.vue'].match(/<UiSlider\b/g)?.length,
1,
);
});
test('the pressed toggles take the kit pressed state', () => {
for (const view of Object.values(markup))
assert.doesNotMatch(view, tag(String.raw`<\w+\bATTRS\s:?aria-pressed`));
const pressed = Object.values(markup).flatMap(
(view) =>
view.match(tag(String.raw`<UiButton\bATTRS\s:pressed=ATTRS>`, 'g')) ?? [],
);
// Radio's Enable, the briefing's Auto and the Contact card's Weather.
assert.equal(pressed.length, 3);
for (const button of pressed) assert.match(button, /:pressed="Boolean\(/);
assert.match(
markup['panels/CockpitUtilityControls.vue'],
tag(
String.raw`<UiButton\s+id="cockpit-radio-enable-btn"ATTRS\s:pressed="Boolean\(cockpit\?\.enable\.active\)" pressed-class="active"`,
),
);
assert.match(
markup['panels/CockpitBriefing.vue'],
tag(
String.raw`<UiButton\s+id="cockpit-brief-auto"ATTRS\s:pressed="Boolean\(b\.autoRotate\)"`,
),
);
assert.match(
markup['panels/CockpitContext.vue'],
tag(
String.raw`<UiButton\s+id="cockpit-weather-toggle"ATTRS\s:pressed="Boolean\(c\.weather\)"`,
),
);
});
test('the Cockpit views hand-write no Material glyph; each is a UiIcon', () => {
for (const [file, { icons }] of Object.entries(views)) {
assert.deepEqual(
markup[file].match(/material-symbols-outlined/g) ?? [],
[],
file,
);
const found =
markup[file].match(tag(String.raw`<UiIcon\bATTRS>`, 'g')) ?? [];
assert.equal(found.length, icons, file);
// Without it the kit writes an 18px size that beats the cockpit's rules.
for (const icon of found) assert.match(icon, /\s:size="null"/, file);
}
});
test('the heading caret outranks the kit icon rule that loads after it', () => {
const css = readFileSync(
new URL('../styles/cockpit.css', import.meta.url),
'utf8',
);
// kit.css's `.ui-icon` sets display and line-height with one class and
// loads after cockpit.css, so a one-class caret rule would lose to it.
assert.match(
css,
/\n\.cockpit-compass \.cockpit-heading-caret \{\n {2}display: block;/,
);
assert.doesNotMatch(css, /\n\.cockpit-heading-caret \{/);
});
+127
View File
@@ -0,0 +1,127 @@
// The command dock's and the Context panel's buttons and Material glyphs are
// the kit's: neither the dock, the Context view nor the view context it
// shows while nothing is picked hand-writes a <button> or a Material Symbols
// span. The dock's style buttons are pressed toggles with `active`, its
// glyphs (◯ ▦ 🌙 🌡️ ✦ ◐, the search 🔎 and the collapse +) are text
// characters, not Material symbols, and stay plain text. Context's tabs and
// its Contacts mode button are `role="tab"` controls: they say they are
// chosen with `aria-selected` and keep their own `active` class, never
// `aria-pressed`.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
/** A view's template block: everything outside script, style and comments. */
function template(file) {
const source = readFileSync(
new URL(`../views/${file}`, import.meta.url),
'utf8',
);
return source
.replace(/<(script|style)\b[\s\S]*?<\/\1\s*>/g, '')
.replace(/<!--[\s\S]*?-->/g, '');
}
// A tag's attributes, read past quoted values so a handler's `=>` does not
// end the tag early.
const ATTRS = String.raw`(?:[^>"']|"[^"]*"|'[^']*')*`;
const tag = (pattern, flags = '') =>
new RegExp(pattern.replaceAll('ATTRS', ATTRS), flags);
const tags = (markup, name) =>
markup.match(tag(String.raw`<${name}\bATTRS>`, 'g')) ?? [];
const dock = template('CommandDockView.vue');
const context = template('ContextView.vue');
const inView = template('panels/ViewContext.vue');
const views = {
// The six style buttons, the two tray toggles and their pins, the map
// source chips, Location's collapse, its landmark and city pills and the
// search toggle.
'CommandDockView.vue': { markup: dock, buttons: 15, icons: 0, closes: 0 },
// Search and Expand in the header, the two tabs, Contacts, the cockpit
// entry, SEARCH NEARBY SITES and the TR-3B chip.
'ContextView.vue': { markup: context, buttons: 8, icons: 7, closes: 0 },
// An off layer's worldwide tile, an item's row, the place and layer chips
// and Ask GEV; a layer's Turn off is a UiCloseButton. The glyphs: the
// header's eye, a worldwide tile's (on and off), a layer group's, an
// item's motion and the layer chips' add.
'panels/ViewContext.vue': { markup: inView, buttons: 5, icons: 6, closes: 1 },
};
test('the dock and Context hand-write no button; each is a UiButton', () => {
for (const [file, { markup, buttons, closes }] of Object.entries(views)) {
assert.deepEqual(markup.match(/<button\b/gi) ?? [], [], file);
assert.deepEqual(markup.match(/<component\b/gi) ?? [], [], file);
assert.equal(tags(markup, 'UiButton').length, buttons, file);
assert.equal(tags(markup, 'UiCloseButton').length, closes, file);
}
});
test('the style buttons are pressed toggles with active', () => {
assert.doesNotMatch(dock, /v-class-toggle="\{[^"]*\bactive\b/);
const styles = tags(dock, 'UiButton').filter((b) =>
/class="style-btn"/.test(b),
);
assert.deepEqual(
styles.map((b) => b.match(/data-style="(\w+)"/)[1]),
['normal', 'retro', 'surveillance', 'thermal', 'anime', 'noir'],
);
for (const button of styles) {
const name = button.match(/data-style="(\w+)"/)[1];
assert.match(button, /\spressed-class="active"/, name);
// Normal stays the pressed one until a style is published.
assert.match(
button,
name === 'normal'
? /\s:pressed="!style \|\| style\.name === 'normal'"/
: new RegExp(String.raw`\s:pressed="style\?\.name === '${name}'"`),
name,
);
}
});
test('no tag hand-writes aria-pressed; the pressed toggles take :pressed', () => {
for (const [file, { markup }] of Object.entries(views))
assert.doesNotMatch(
markup,
tag(String.raw`<\w+\bATTRS\s:?aria-pressed`),
file,
);
const pressed = (markup) =>
tags(markup, 'UiButton').filter((b) => /\s:pressed=/.test(b)).length;
// The six styles, two pins, map sources, landmarks and cities.
assert.equal(pressed(dock), 11);
// Search, Expand and TR-3B.
assert.equal(pressed(context), 3);
assert.equal(pressed(inView), 0);
});
test("Context's tabs say they are chosen, not pressed", () => {
const tabs = tags(context, 'UiButton').filter((b) => /\srole="tab"/.test(b));
assert.equal(tabs.length, 3);
for (const button of tabs) {
assert.match(button, /\s:aria-selected=/);
assert.doesNotMatch(button, /\s:pressed=/);
assert.match(button, /\s(?::class|v-class-toggle)="\{ active: /);
}
});
test('they hand-write no Material glyph; each is a UiIcon', () => {
for (const [file, { markup, icons }] of Object.entries(views)) {
assert.deepEqual(
markup.match(/material-symbols-outlined/g) ?? [],
[],
file,
);
const found = tags(markup, 'UiIcon');
assert.equal(found.length, icons, file);
// Without it the kit writes an 18px size that beats the site rules.
for (const icon of found) assert.match(icon, /\s:size="null"/, file);
}
// An item's motion glyph is an image with its own name, not decoration.
const [motion] = tags(inView, 'UiIcon').filter((i) =>
/view-context__row-motion/.test(i),
);
assert.match(motion, /\srole="img"/);
assert.match(motion, /\s:aria-label=/);
assert.match(motion, /\s:aria-hidden="null"/);
});
+3 -2
View File
@@ -1,7 +1,8 @@
// Every modal dialog in a Vue view is a UiDialog: no SFC template hand-writes
// `<dialog>`. Panels drawn as `role="dialog"` (key setup, the welcome
// launcher, the CCTV popup, Story Explore's filter) and the render failure's
// `alertdialog` are other controls.
// launcher, the CCTV popup, Story Explore's filter, the credits, the Omnibar
// guide's callout) and the render failure's `alertdialog` are other
// controls.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync, readdirSync } from 'node:fs';
+126
View File
@@ -0,0 +1,126 @@
// UTILITIES ▸ Draw (its toggle, Clear, the colour swatches and the drawn
// shapes' rows), Import and the Street Level panel are on the kit: none of
// them hand-writes a <button>, a Material Symbols span, a select, a checkbox
// or a range. The Draw toggle is a pressed toggle with `active`. The colour
// swatches are `role="radio"` buttons: they say they are chosen with
// `aria-checked` and their own `active` class, never `aria-pressed`. A drawn
// shape's show/hide renames itself (Show …, Hide …) rather than being pressed.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
const source = (file) =>
readFileSync(new URL(`../views/panels/${file}`, import.meta.url), 'utf8');
/** A view's template block: everything outside script, style and comments. */
const template = (file) =>
source(file)
.replace(/<(script|style)\b[\s\S]*?<\/\1\s*>/g, '')
.replace(/<!--[\s\S]*?-->/g, '');
// A tag's attributes, read past quoted values so a handler's `=>` does not
// end the tag early.
const ATTRS = String.raw`(?:[^>"']|"[^"]*"|'[^']*')*`;
const tag = (pattern, flags = '') =>
new RegExp(pattern.replaceAll('ATTRS', ATTRS), flags);
const tags = (markup, name) =>
markup.match(tag(String.raw`<${name}\bATTRS>`, 'g')) ?? [];
const views = {
// Draw and Clear.
'DrawControls.vue': { buttons: 2, icons: 1, closes: 0 },
// The five colours, one v-for.
'DrawSwatches.vue': { buttons: 1, icons: 0, closes: 0 },
// A row's swatch, show/hide, the application's actions and fly to; remove
// is a UiCloseButton.
'DrawMarkList.vue': { buttons: 4, icons: 3, closes: 1 },
// Import and a file's row actions.
'GeoImport.vue': { buttons: 2, icons: 2, closes: 0 },
// The status toggle, EXPAND and the nearest-imagery button; the viewer's
// close. EXPAND's ⤢ ⤡ and the errors' ⚠ are text, not Material symbols.
'StreetLevelPanel.vue': { buttons: 3, icons: 0, closes: 1 },
};
const markup = Object.fromEntries(
Object.keys(views).map((file) => [file, template(file)]),
);
test('the Draw, Import and Street Level views hand-write no button', () => {
for (const [file, { buttons, closes }] of Object.entries(views)) {
const html = markup[file];
assert.deepEqual(html.match(/<button\b/gi) ?? [], [], file);
assert.deepEqual(html.match(/<component\b/gi) ?? [], [], file);
assert.equal(tags(html, 'UiButton').length, buttons, file);
assert.equal(tags(html, 'UiCloseButton').length, closes, file);
}
});
test('they hand-write no select, checkbox or range', () => {
for (const [file, html] of Object.entries(markup)) {
assert.deepEqual(html.match(/<select\b/gi) ?? [], [], file);
assert.doesNotMatch(
html,
tag(String.raw`<input\bATTRS\stype="(?:checkbox|range)"`),
file,
);
}
// SINCE is the kit's range.
assert.equal(tags(markup['StreetLevelPanel.vue'], 'UiSlider').length, 1);
});
test('they hand-write no Material glyph; each is a UiIcon sized by the site', () => {
for (const [file, { icons }] of Object.entries(views)) {
const html = markup[file];
assert.deepEqual(html.match(/material-symbols-outlined/g) ?? [], [], file);
const found = tags(html, 'UiIcon');
assert.equal(found.length, icons, file);
// Without it the kit writes an 18px size that beats the site rules.
for (const icon of found) assert.match(icon, /\s:size="null"/, file);
}
// Draw's and Import's glyphs keep pp-icon, which sizes them.
for (const file of ['DrawControls.vue', 'GeoImport.vue']) {
const [icon] = tags(markup[file], 'UiIcon');
assert.match(icon, /\sclass="pp-icon"/, file);
}
});
test('no tag hand-writes aria-pressed; Draw is a pressed toggle with active', () => {
for (const [file, html] of Object.entries(markup))
assert.doesNotMatch(
html,
tag(String.raw`<\w+\bATTRS\s:?aria-pressed`),
file,
);
const [draw] = tags(markup['DrawControls.vue'], 'UiButton').filter((b) =>
/\sid="draw-toggle"/.test(b),
);
assert.match(draw, /\s:pressed="draw\?\.active \?\? false"/);
assert.match(draw, /\spressed-class="active"/);
const [clear] = tags(markup['DrawControls.vue'], 'UiButton').filter((b) =>
/\sid="draw-clear"/.test(b),
);
assert.doesNotMatch(clear, /\s:pressed=/);
// A shape's show/hide says what it does in its name, not by being pressed.
for (const button of tags(markup['DrawMarkList.vue'], 'UiButton'))
assert.doesNotMatch(button, /\s:pressed=/);
});
test('the colour swatches are radios chosen by aria-checked, never pressed', () => {
const [swatch] = tags(markup['DrawSwatches.vue'], 'UiButton');
assert.match(swatch, /\srole="radio"/);
assert.match(
swatch,
/\s:aria-checked="String\(color === props\.modelValue\)"/,
);
assert.match(swatch, /\s:class="\{ active: color === props\.modelValue \}"/);
assert.doesNotMatch(swatch, /\s:pressed=|\spressed-class=/);
});
test('code that focuses a converted button reaches its element', () => {
// A template ref on a component holds the component, not the button.
assert.match(
source('DrawSwatches.vue'),
/:ref="\(swatch\) => \(buttons\[index\] = swatch\?\.\$el\)"/,
);
assert.match(
source('GeoImport.vue'),
/importButton\.value\?\.\$el\.focus\(\)/,
);
});
+142
View File
@@ -0,0 +1,142 @@
// The space missions, Contacts, Radio and provider settings controls are the
// kit's: none of their views hand-writes a <button>, a Material Symbols span,
// a select or a checkbox. Radio's Enable, the RTL-SDR card's Connect and its
// FM and ADS-B modes are pressed toggles with `active`; Radio's Play and the
// card's Locate keep their own `active` class, since their words change
// with their state rather than saying they are pressed. The RTL-SDR card's
// FM frequency stays a native number field (the kit has none), and the radio
// tuner's range stays native: its owner moves the handle back to the
// selected station on a drag's first input without changing the slot.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
/** A view's template block: everything outside script, style and comments. */
function template(file) {
const source = readFileSync(
new URL(`../views/${file}`, import.meta.url),
'utf8',
);
return source
.replace(/<(script|style)\b[\s\S]*?<\/\1\s*>/g, '')
.replace(/<!--[\s\S]*?-->/g, '');
}
// A tag's attributes, read past quoted values so a handler's `=>` does not
// end the tag early.
const ATTRS = String.raw`(?:[^>"']|"[^"]*"|'[^']*')*`;
const tag = (pattern, flags = '') =>
new RegExp(pattern.replaceAll('ATTRS', ATTRS), flags);
const tags = (markup, name) =>
markup.match(tag(String.raw`<${name}\bATTRS>`, 'g')) ?? [];
const byId = (markup, name, id) => {
const found = tags(markup, name).filter((t) =>
new RegExp(String.raw`\sid="${id}"`).test(t),
);
assert.equal(found.length, 1, id);
return found[0];
};
// Each view's UiButtons, UiCloseButtons, UiIcons, UiSelects and UiSliders.
const VIEWS = {
// FOCUS, REPLAY ASCENT, the replay's pause, PREV, NEXT and SHOW ALL; the
// header's deselect and the replay's Cancel close.
'panels/MissionDetail.vue': [6, 2, 0, 0, 1],
// A mission's row.
'panels/MissionRoster.vue': [1, 0, 0, 0, 0],
'panels/MissionReplayOverlay.vue': [0, 0, 0, 0, 0],
'panels/SpaceMissionsPanel.vue': [0, 0, 0, 0, 0],
// PREV, FOCUS, NEXT and a contact's row.
'panels/AwarenessPanel.vue': [4, 0, 0, 0, 0],
'panels/AwarenessDirection.vue': [0, 0, 0, 0, 0],
'panels/AwarenessNames.vue': [0, 0, 0, 0, 0],
// Connect, Locate, Change device, FM, ADS-B, Tune and the two seeks.
'panels/SdrCard.vue': [8, 0, 0, 1, 1],
// Enable, PREV, PLAY, NEXT and STOP.
'panels/RadioPanel.vue': [5, 0, 0, 1, 1],
'panels/RadioTuner.vue': [0, 0, 0, 0, 0],
// The POWER UP chip and its bolt, a key's REMOVE, the voice auth toggle
// and SAVE KEYS; the dialog's close.
'ProviderSettingsView.vue': [4, 1, 1, 0, 0],
};
const views = Object.entries(VIEWS).map(([file, counts]) => ({
file,
markup: template(file),
counts,
}));
test('they hand-write no button; each is a UiButton or UiCloseButton', () => {
for (const { file, markup, counts } of views) {
assert.deepEqual(markup.match(/<button\b/gi) ?? [], [], file);
assert.deepEqual(markup.match(/<component\b/gi) ?? [], [], file);
assert.equal(tags(markup, 'UiButton').length, counts[0], file);
assert.equal(tags(markup, 'UiCloseButton').length, counts[1], file);
}
});
test('they hand-write no Material glyph; each is a UiIcon sized by its site', () => {
for (const { file, markup, counts } of views) {
assert.deepEqual(
markup.match(/material-symbols-outlined/g) ?? [],
[],
file,
);
const icons = tags(markup, 'UiIcon');
assert.equal(icons.length, counts[2], file);
// Without it the kit writes an 18px size that beats the site rules.
for (const icon of icons) assert.match(icon, /\s:size="null"/, file);
}
});
test('their selects and ranges are the kit’s, apart from the tuner', () => {
for (const { file, markup, counts } of views) {
assert.deepEqual(markup.match(/<select\b/gi) ?? [], [], file);
assert.doesNotMatch(markup, /type="checkbox"/, file);
assert.equal(tags(markup, 'UiSelect').length, counts[3], file);
assert.equal(tags(markup, 'UiSlider').length, counts[4], file);
const ranges = tags(markup, 'input').filter((i) =>
/\stype="range"/.test(i),
);
assert.equal(ranges.length, file === 'panels/RadioTuner.vue' ? 1 : 0, file);
}
});
test('no tag hand-writes aria-pressed; the pressed toggles take :pressed', () => {
const pressed = {
'panels/MissionDetail.vue': 1,
'panels/SdrCard.vue': 3,
'panels/RadioPanel.vue': 1,
};
for (const { file, markup } of views) {
assert.doesNotMatch(
markup,
tag(String.raw`<\w+\bATTRS\s(?:v-bind)?:?aria-pressed`),
file,
);
const toggles = tags(markup, 'UiButton').filter((b) =>
/\s:pressed=/.test(b),
);
assert.equal(toggles.length, pressed[file] ?? 0, file);
}
const sdr = views.find((v) => v.file === 'panels/SdrCard.vue').markup;
const radio = views.find((v) => v.file === 'panels/RadioPanel.vue').markup;
for (const [markup, id] of [
[sdr, 'sdr-connect-btn'],
[sdr, 'sdr-mode-fm-btn'],
[sdr, 'sdr-mode-adsb-btn'],
[radio, 'radio-enable-btn'],
])
assert.match(byId(markup, 'UiButton', id), /\spressed-class="active"/, id);
});
test('Play and Locate keep their own active class rather than pressed', () => {
const sdr = views.find((v) => v.file === 'panels/SdrCard.vue').markup;
const radio = views.find((v) => v.file === 'panels/RadioPanel.vue').markup;
for (const [markup, id] of [
[radio, 'radio-play-btn'],
[sdr, 'sdr-locate-btn'],
]) {
const button = byId(markup, 'UiButton', id);
assert.doesNotMatch(button, /\s:pressed=/, id);
assert.match(button, /\sv-class-toggle="\{ active: /, id);
}
});
+135
View File
@@ -0,0 +1,135 @@
// The small surfaces' buttons and Material glyphs are the kit's: the locale
// picker, the phone tab bar, the globe actions and compass, the imagery
// divider, the scene sharing dialog, the layer group index, the celestial
// ring, the title logo, Exit clean view, the HUD's cockpit entry, the News
// cards, the rail cards, the layer rows' toggles, the credits line and the
// camera calibration chips hand-write no <button> and no Material Symbols
// span. The Omnibar guide's extra rings are its template's, not built in
// script. The locale picker's globe, caret and check and a News card's
// category icon stay inline SVG: none is a Material symbol the page loads.
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')) ?? [];
// Per file: its UiButtons, UiCloseButtons and UiIcons.
const SURFACES = {
'views/panels/LocalePicker.vue': [1, 0, 0],
'views/panels/PhoneTabBar.vue': [1, 0, 1],
'views/panels/GlobeCompass.vue': [1, 0, 1],
// Clear, share, tilt and reset; the clear, tilt and reset glyphs.
'views/panels/GlobeActions.vue': [4, 0, 3],
'views/panels/ImagerySplitView.vue': [1, 0, 0],
// The body's buttons and the footer's.
'views/panels/SceneDialog.vue': [2, 0, 0],
'views/panels/LayerSectionIndex.vue': [1, 0, 0],
// The sun and moon markers.
'views/panels/CelestialRing.vue': [0, 0, 2],
'views/panels/OmnibarGuide.vue': [3, 1, 0],
// The overlay targets' buttons and the title logo.
'views/SceneChromeView.vue': [2, 0, 0],
'views/DisplayControlsView.vue': [1, 0, 0],
'views/IntelHudView.vue': [1, 0, 1],
// The card's face and the selected card's clear chip.
'news/NewsCard.vue': [2, 0, 0],
'rail/RailCard.vue': [1, 0, 0],
'layerPanel/LayerRows.vue': [1, 0, 0],
'credits/CreditsView.vue': [1, 1, 0],
'cctv/CctvCalValue.vue': [1, 0, 0],
};
test('the small surfaces hand-write no button; each is a kit button', () => {
for (const [file, [buttons, closes]] of Object.entries(SURFACES)) {
const markup = template(file);
assert.deepEqual(markup.match(/<button\b/gi) ?? [], [], file);
assert.equal(tags(markup, 'UiButton').length, buttons, file);
assert.equal(tags(markup, 'UiCloseButton').length, closes, file);
}
});
test('the small surfaces hand-write no Material glyph; each is a UiIcon', () => {
for (const [file, [, , count]] of Object.entries(SURFACES)) {
const markup = template(file);
assert.deepEqual(
markup.match(/material-symbols-outlined/g) ?? [],
[],
file,
);
const icons = tags(markup, 'UiIcon');
assert.equal(icons.length, count, file);
// Without it the kit writes an 18px size that beats the sites' own rules.
for (const icon of icons) assert.match(icon, /\s:size="null"/, file);
}
});
test('the only inline SVG glyphs are the locale picker’s and a News category’s', () => {
for (const file of Object.keys(SURFACES)) {
const expected =
file === 'views/panels/LocalePicker.vue'
? 3
: file === 'news/NewsCard.vue'
? 1
: 0;
assert.equal(template(file).match(/<svg\b/g)?.length ?? 0, expected, file);
}
});
test('buttons whose owner patches synchronously redraw their contents with it', () => {
// A UiButton's slot renders inside the button, a tick after a change the
// button's own attributes do not carry; a conditional slot is redrawn with
// its view.
// How many of each file's first buttons the owner redraws and reads.
for (const [file, count] of [
['news/NewsCard.vue', 1],
['rail/RailCard.vue', 1],
['credits/CreditsView.vue', 1],
['views/panels/OmnibarGuide.vue', 3],
]) {
const markup = template(file);
const buttons = tags(markup, 'UiButton').slice(0, count);
assert.equal(buttons.length, count, file);
let from = 0;
for (const button of buttons) {
from = markup.indexOf(button, from) + button.length;
assert.match(
markup.slice(from),
/^\s*<template v-if="redrawWithView" #default\s*>/,
file,
);
}
assert.match(read(file), /const redrawWithView = true;/, file);
}
});
test('the Omnibar guide draws its extra rings in its template', () => {
const guide = template('views/panels/OmnibarGuide.vue');
assert.match(
guide,
/<div\s+v-for="i in view\.subRings"\s+:key="i"\s+class="gev-guide-ring gev-guide-ring--sub"\s*><\/div\s*>\s*<\/div\s*>\s*<\/Teleport/,
);
const owner = read('omnibarGuide.js');
assert.deepEqual(owner.match(/createElement\(/g), ['createElement(']);
assert.doesNotMatch(owner, /\.className\s*=|\.append\(/);
assert.match(owner, /view\.subRings = rest\.length;\s*paint\(\);/);
});
test('the layer disclosure builds no control', () => {
// Its one `<button` is a comment's word for the element Chromium focuses.
const disclosure = read('panelDisclosure.js');
assert.doesNotMatch(disclosure, /createElement|innerHTML|insertAdjacentHTML/);
const code = disclosure
.replace(/\/\/.*$/gm, '')
.replace(/\/\*[\s\S]*?\*\//g, '');
assert.doesNotMatch(code, /<button/);
});
+6 -5
View File
@@ -3,11 +3,12 @@
// `<input type="checkbox">`. Their glyphs are inline SVG drawn for Stories
// (play, pause, back, filter, search, clear, expand, the GEV eye); no
// Material symbol the page loads draws any of them the same, so they stay
// SVG, and no view hand-writes a Material Symbols span. The two search
// fields keep their own markup rather than UiSearchField, whose Material
// magnifier would replace their SVG one, and their clear buttons stay ghost
// UiButtons with an SVG cross rather than UiCloseButtons, whose glyph is ×
// or the Material `close` symbol.
// SVG, and no view hand-writes a Material Symbols span. The three search
// fields (Explore's two and the Story context sheet's) keep their own markup
// rather than UiSearchField, whose Material magnifier would replace their
// SVG one, and Explore's two clear buttons stay ghost UiButtons with an SVG
// cross rather than UiCloseButtons, whose glyph is × or the Material `close`
// symbol.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
@@ -0,0 +1,116 @@
// 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);
// No element made, inserted, moved, removed or written: the view does
// all of that. (An Image the loader downloads with is not on the page.)
for (const write of [
/createElement/,
/\b(?:inner|outer)HTML\b/,
/insertAdjacent(?:HTML|Element|Text)/,
/\.(?:append|prepend|appendChild|insertBefore|replaceWith|replaceChildren|before|after)\(/,
/\.remove\(\)/,
/\.(?:set|remove|toggle)Attribute(?:NS)?\(/,
/\.(?:classList|className|dataset|style)\b/,
/\.(?:hidden|disabled|textContent|innerText|tabIndex|title|alt)\s*=[^=]/,
/from 'vue'|\.vue'/,
])
assert.doesNotMatch(source, write);
const markup = template(VIEW);
const opening = (name, attribute) =>
new RegExp(String.raw`<${name}\b${ATTRS}\s${attribute}${ATTRS}>`);
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,
);
});
+171
View File
@@ -0,0 +1,171 @@
// The kit's every-control claims in docs/VUE-MIGRATION.md, read from every
// SFC outside the kit: every select is a UiSelect, every pressed toggle a
// UiButton with `pressed` (no template hand-writes `aria-pressed` on any
// element, as an attribute or inside a `v-bind` object, apart from the
// exceptions below), and every close, dismiss and clear button a
// UiCloseButton.
// Controls built in script are not read here.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync, readdirSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const SRC_ROOT = fileURLToPath(new URL('../../', import.meta.url));
const KIT_ROOT = fileURLToPath(new URL('./', import.meta.url));
const REPO_ROOT = path.resolve(SRC_ROOT, '..');
// The pressed toggles that still hand-write `aria-pressed`, by file: each
// pattern matches exactly one of the file's tags, and no other tag may.
const HAND_WRITTEN_PRESSED = {
// Explore's story cards are `role="button"` elements, not buttons.
'src/ui/views/stories/ExploreScreen.vue': [
/^<div class="card" role="button"/,
],
};
/** Every SFC under src, outside the kit. */
function sfcFiles(directory = SRC_ROOT) {
const files = [];
for (const entry of readdirSync(directory, { withFileTypes: true })) {
const absolute = path.join(directory, entry.name);
if (entry.isDirectory()) {
if (path.relative(KIT_ROOT, absolute) !== '')
files.push(...sfcFiles(absolute));
} else if (entry.isFile() && entry.name.endsWith('.vue'))
files.push(absolute);
}
return files.sort();
}
/** The template block: everything outside script, style and comments. */
function template(source) {
return source
.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 RAW_SELECT = /<select\b/gi;
const ANY_TAG = new RegExp(String.raw`<[A-Za-z][\w-]*\b(${ATTRS})>`, 'g');
// An attribute's name, outside the quoted values.
const names = (attrs) => attrs.replace(/"[^"]*"|'[^']*'/g, '""');
const PRESSED = /(?:^|\s)(?::|v-bind:)?aria-pressed(?=[\s=/]|$)/;
// A `v-bind` object that names aria-pressed.
const BOUND_PRESSED =
/(?:^|\s)(?:v-bind|:)=(?:"[^"]*aria-?pressed[^"]*"|'[^']*aria-?pressed[^']*')/i;
const TIMES = String.raw`×|&times;|&#215;|&#xd7;`;
const CLOSE_GLYPH = [
TIMES,
String.raw`<span\b${ATTRS}>\s*(?:${TIMES})\s*</span\s*>`,
String.raw`<span\b[^>]*\bmaterial-symbols-outlined\b[^>]*>\s*close\s*</span\s*>`,
String.raw`<UiIcon${ATTRS}\bname="close"${ATTRS}/>`,
].join('|');
const HAND_WRITTEN_CLOSE = new RegExp(
String.raw`<(button|UiButton)\b${ATTRS}>\s*(?:${CLOSE_GLYPH})\s*</\1\s*>`,
'gi',
);
const tidy = (markup) => markup.replace(/\s+/g, ' ');
/** Raw selects in an SFC's template. */
const rawSelects = (source) =>
[...template(source).matchAll(RAW_SELECT)].map((m) => m[0]);
/** Tags that hand-write aria-pressed. */
function handWrittenPressed(source) {
const found = [];
for (const m of template(source).matchAll(ANY_TAG))
if (PRESSED.test(names(m[1])) || BOUND_PRESSED.test(m[1]))
found.push(tidy(m[0]));
return found;
}
/** Hand-written close buttons in an SFC's template. */
const handWrittenCloses = (source) =>
[...template(source).matchAll(HAND_WRITTEN_CLOSE)].map((m) => tidy(m[0]));
const views = sfcFiles().map((file) => ({
file: path.relative(REPO_ROOT, file).split(path.sep).join('/'),
source: readFileSync(file, 'utf8'),
}));
test('the scans find each hand-written control', () => {
for (const markup of [
'<template><select id="x" v-model="a"><option>1</option></select></template>',
'<template><SELECT\n class="x"></SELECT></template>',
])
assert.equal(rawSelects(markup).length, 1, markup);
for (const markup of [
'<template><UiSelect id="x" v-model="a" /></template>',
'<script>const html = "<select>";</script><template><p /></template>',
'<template><!-- a <select> once sat here --><p /></template>',
])
assert.equal(rawSelects(markup).length, 0, markup);
for (const markup of [
'<template><button type="button" :aria-pressed="String(on)">A</button></template>',
'<template><UiButton\n class="x"\n :title="a > b ? 1 : 2"\n aria-pressed="true"\n>A</UiButton></template>',
'<template><button v-bind:aria-pressed="on">A</button></template>',
'<template><div class="card" role="button" tabindex="0" :aria-pressed="on" /></template>',
'<template><li role="option" :aria-pressed="on" /></template>',
'<template><a :role="\'button\'" :aria-pressed="on">A</a></template>',
'<template><UiButton v-bind="{ \'aria-pressed\': on }">A</UiButton></template>',
])
assert.equal(handWrittenPressed(markup).length, 1, markup);
for (const markup of [
'<template><UiButton :pressed="Boolean(on)" pressed-class="active">A</UiButton></template>',
'<template><button :title="\'aria-pressed\'" @click="q(\'[aria-pressed=true]\')">A</button></template>',
'<template><li role="option" :aria-selected="on" /></template>',
])
assert.equal(handWrittenPressed(markup).length, 0, markup);
for (const markup of [
'<template><button type="button" @click="close">×</button></template>',
'<template><button type="button" :aria-label="l"><span aria-hidden="true">×</span></button></template>',
'<template><UiButton class="x"><UiIcon name="close" :size="null" /></UiButton></template>',
])
assert.equal(handWrittenCloses(markup).length, 1, markup);
for (const markup of [
'<template><UiCloseButton class="x" :label="l" /></template>',
'<template><UiButton :label="l"><UiIcon :name="item.icon" :size="null" /></UiButton></template>',
])
assert.equal(handWrittenCloses(markup).length, 0, markup);
});
test('the views are read: the scan reaches the views and skips the kit', () => {
const files = views.map((view) => view.file);
assert.ok(files.includes('src/ui/views/panels/ChatPanel.vue'));
assert.ok(files.includes('src/ui/layerPanel/RowRange.vue'));
assert.ok(!files.some((file) => file.startsWith('src/ui/kit/')));
});
test('every select in the views is a UiSelect', () => {
const found = [];
for (const { file, source } of views)
for (const markup of rawSelects(source)) found.push(`${file}: ${markup}`);
assert.deepEqual(found, []);
});
test('no view hand-writes aria-pressed on a button outside the documented exceptions', () => {
const unexpected = [];
for (const { file, source } of views) {
const allowed = [...(HAND_WRITTEN_PRESSED[file] ?? [])];
for (const markup of handWrittenPressed(source)) {
const at = allowed.findIndex((pattern) => pattern.test(markup));
if (at === -1) unexpected.push(`${file}: ${markup}`);
else allowed.splice(at, 1);
}
assert.deepEqual(allowed, [], `${file}: an exception no longer matches`);
}
assert.deepEqual(unexpected, []);
});
test('no view hand-writes a close button; each is a UiCloseButton', () => {
const found = [];
for (const { file, source } of views)
for (const markup of handWrittenCloses(source))
found.push(`${file}: ${markup}`);
assert.deepEqual(found, []);
});
+3 -3
View File
@@ -5,6 +5,7 @@ import RowRange from './RowRange.vue';
import RowSlider from './RowSlider.vue';
import RowSwitch from './RowSwitch.vue';
import RowText from './RowText.vue';
import UiButton from '../kit/UiButton.vue';
import { vClassToggle } from '../rail/classToggle.js';
// The data layer rows under their group headings. LayerPanel presents every
@@ -45,8 +46,7 @@ defineProps({
v-if="item.count"
:class="['data-count', { 'data-count-empty': item.count.empty }]"
:text="item.count.text"
/><button
type="button"
/><UiButton
:class="['data-toggle-btn', item.toggle.classes]"
:data-feed-state="item.toggle.feedState"
:aria-disabled="String(item.toggle.ariaDisabled)"
@@ -54,7 +54,7 @@ defineProps({
:title="item.toggle.title"
:aria-label="item.toggle.ariaLabel"
@click="onToggle(item.id)"
>{{ item.toggle.text }}</button
>{{ item.toggle.text }}</UiButton
></div
></div
><RowText tag="div" class="data-toggle-meta" :text="item.meta" /><template
+10 -4
View File
@@ -1,7 +1,13 @@
<script setup>
import UiSelect from '../kit/UiSelect.js';
// A row's start and end pickers on one line (e.g. the Shipwrecks period).
// Both ends share one option list; `onSelect` reports which end moved
// ('from' or 'to') and the chosen option value.
// ('from' or 'to') and the chosen option value. The owner repaints the row
// on a later frame and may reorder the ends (a start picked after the end
// swaps them), so each select is given its end's value as a plain `value`
// rather than a model: the pick stays until the owner publishes a different
// value, which then shows at once, even on the focused select.
defineProps({
range: { type: Object, required: true },
onSelect: { type: Function, default: () => {} },
@@ -21,18 +27,18 @@ defineProps({
:key="end"
class="data-toggle-range-end"
><span class="data-toggle-range-caption">{{ range[end].label }}</span
><select
><UiSelect
class="data-toggle-range-select"
:data-range-end="end"
:aria-label="range[end].ariaLabel || undefined"
:value="String(range[end].value)"
@change="onSelect(end, $event.target.value)"
@update:model-value="onSelect(end, $event)"
><option
v-for="option in range.options"
:key="option.value"
:value="String(option.value)"
>{{ option.label }}</option
></select
></UiSelect
></label
></div
></div
+1 -1
View File
@@ -241,7 +241,7 @@ test('a Data Library row names its entry and draws icon action chips', () => {
assert.equal(element.dataset.libraryEntry, 'nasa-black-marble');
const button = element.querySelector('[data-chip-id="zoom"]');
const glyph = button.children[0];
assert.equal(glyph.className, 'material-symbols-outlined');
assert.ok(glyph.classList.contains('material-symbols-outlined'));
assert.equal(glyph.textContent, 'zoom_in_map');
assert.equal(glyph.getAttribute('aria-hidden'), 'true');
assert.equal(button.getAttribute('aria-label'), 'Zoom to layer');
+51
View File
@@ -0,0 +1,51 @@
import { after, before, test } from 'node:test';
import assert from 'node:assert/strict';
import { installVueDom } from '../../testSupport/vueDom.mjs';
let mount;
let RowRange;
let uninstall;
before(async () => {
uninstall = installVueDom();
({ mount } = await import('@vue/test-utils'));
RowRange = (await import('./RowRange.vue')).default;
});
after(() => uninstall());
const range = (from, to) => ({
id: 'period',
label: 'Period',
valueText: `${from}–${to}`,
from: { label: 'From', value: from },
to: { label: 'To', value: to },
options: [1900, 1950, 1960, 2000].map((value) => ({
value,
label: String(value),
})),
});
test('a range end keeps a pick until the owner repaints, then shows the owner’s ends', async () => {
const picks = [];
const wrapper = mount(RowRange, {
attachTo: document.body,
props: {
range: range(1900, 1950),
onSelect: (end, value) => picks.push([end, value]),
},
});
const [from, to] = wrapper.findAll('select').map((w) => w.element);
assert.equal(from.value, '1900');
assert.equal(to.value, '1950');
// A start picked after the end: the owner swaps the ends on a later frame.
from.focus();
from.value = '1960';
from.dispatchEvent(new Event('change'));
assert.deepEqual(picks, [['from', '1960']]);
await wrapper.vm.$nextTick();
assert.equal(from.value, '1960');
await wrapper.setProps({ range: range(1950, 1960) });
assert.equal(document.activeElement, from);
assert.equal(from.value, '1950');
assert.equal(to.value, '1960');
wrapper.unmount();
});
+58 -51
View File
@@ -49,6 +49,11 @@ const meta = () =>
]
.filter(Boolean)
.join(' · ');
// The card's face is the slot of a UiButton, which renders inside the
// button: a new item alone would reach it only on a later tick, but the panel
// patches synchronously. A slot given under a condition (`redrawWithView`,
// always true) is redrawn whenever this card is, so it keeps up.
const redrawWithView = true;
</script>
<template>
@@ -58,60 +63,62 @@ const meta = () =>
:data-report-id="item.id"
:style="{ '--news-color': item.color }"
>
<button
type="button"
class="news-card__main ui-focus"
<UiButton
class="news-card__main"
:aria-expanded="open ? 'true' : 'false'"
@click="onChoose(item)"
><template v-if="redrawWithView" #default>
<span v-if="item.picture && !pictureFailed" class="news-card__thumb"
><img
:src="item.picture.url"
alt=""
loading="lazy"
decoding="async"
referrerpolicy="no-referrer"
v-on="{ error: dropPicture }"
/><span
v-if="item.picture.video && !clipFailed"
class="news-card__play"
role="img"
:aria-label="t('Video')"
>▶</span
><span v-if="item.picture.credit" class="news-card__credit">{{
item.picture.credit
}}</span></span
>
<span class="news-card__title">{{ item.title }}</span>
<span v-if="item.original" class="news-card__note">{{
t('English headline by the model')
}}</span>
<span class="news-card__meta ui-mono"
><span
class="news-card__marker"
:class="{ solid: item.solid }"
role="img"
:aria-label="item.severityLabel"
:title="item.severityLabel"
><svg viewBox="0 0 16 16" aria-hidden="true">
<path :d="item.icon" /></svg></span
><span v-if="item.severity >= 2" class="news-card__severity">{{
item.severityLabel
}}</span
>{{ item.severity >= 2 ? ` · ${meta()}` : meta() }}</span
>
<span v-if="item.sides" class="news-card__sides">{{ item.sides }}</span>
<span v-if="item.chips.length" class="news-card__chips"
><span
v-for="chip in item.chips"
:key="`${chip.kind}:${chip.label}`"
class="news-chip"
:class="`news-chip--${chip.kind}`"
>{{ chip.label }}</span
></span
>
<span v-if="item.via" class="news-card__via ui-mono">{{
item.via
}}</span>
</template></UiButton
>
<span v-if="item.picture && !pictureFailed" class="news-card__thumb"
><img
:src="item.picture.url"
alt=""
loading="lazy"
decoding="async"
referrerpolicy="no-referrer"
v-on="{ error: dropPicture }"
/><span
v-if="item.picture.video && !clipFailed"
class="news-card__play"
role="img"
:aria-label="t('Video')"
>▶</span
><span v-if="item.picture.credit" class="news-card__credit">{{
item.picture.credit
}}</span></span
>
<span class="news-card__title">{{ item.title }}</span>
<span v-if="item.original" class="news-card__note">{{
t('English headline by the model')
}}</span>
<span class="news-card__meta ui-mono"
><span
class="news-card__marker"
:class="{ solid: item.solid }"
role="img"
:aria-label="item.severityLabel"
:title="item.severityLabel"
><svg viewBox="0 0 16 16" aria-hidden="true">
<path :d="item.icon" /></svg></span
><span v-if="item.severity >= 2" class="news-card__severity">{{
item.severityLabel
}}</span
>{{ item.severity >= 2 ? ` · ${meta()}` : meta() }}</span
>
<span v-if="item.sides" class="news-card__sides">{{ item.sides }}</span>
<span v-if="item.chips.length" class="news-card__chips"
><span
v-for="chip in item.chips"
:key="`${chip.kind}:${chip.label}`"
class="news-chip"
:class="`news-chip--${chip.kind}`"
>{{ chip.label }}</span
></span
>
<span v-if="item.via" class="news-card__via ui-mono">{{ item.via }}</span>
</button>
<div v-if="open" class="news-card__open">
<video
v-if="item.picture?.video && !clipFailed"
+10 -6
View File
@@ -472,6 +472,9 @@ export function startGuide(steps, { title = '' } = {}) {
nextLabel: t('Next'),
nextHidden: false,
nextQuiet: false,
// The extra rings for a step's further targets, after the callout; the
// count only grows, and rings a step does not use are faded out.
subRings: 0,
// Announces each step once; the dialog itself is not a live region, so
// its buttons and progress are not read out on every change.
status: '',
@@ -511,7 +514,9 @@ export function startGuide(steps, { title = '' } = {}) {
const root = paint().component.subTree.children[0].el;
const ring = root.querySelector(':scope > .gev-guide-ring');
const callout = root.querySelector(':scope > .gev-guide-callout');
const subRings = [];
// The extra rings, read again from the rendered tree whenever more are
// drawn.
let subRings = [];
const live = steps.filter(Boolean);
let index = -1;
@@ -657,11 +662,10 @@ export function startGuide(steps, { title = '' } = {}) {
width: `${main.width + pad * 2}px`,
height: `${main.height + pad * 2}px`,
});
while (subRings.length < rest.length) {
const sub = doc.createElement('div');
sub.className = 'gev-guide-ring gev-guide-ring--sub';
root.append(sub);
subRings.push(sub);
if (subRings.length < rest.length) {
view.subRings = rest.length;
paint();
subRings = [...root.querySelectorAll(':scope > .gev-guide-ring--sub')];
}
subRings.forEach((sub, i) => {
const box = rest[i];
+36
View File
@@ -134,3 +134,39 @@ test('a walk started while Vue mounts something else still starts and ends', asy
assert.equal($('.gev-guide'), null);
assert.equal(document.activeElement, field);
});
test('each further target of a step gets its own ring after the callout', async (t) => {
const { target } = fixture(t);
const more = document.body.appendChild(document.createElement('button'));
const box = (left) => () => ({
left,
top: 20,
right: left + 30,
bottom: 50,
width: 30,
height: 30,
});
target.getBoundingClientRect = box(10);
more.getBoundingClientRect = box(100);
let targets = [target, more];
startGuide([{ targets: () => targets, text: () => 'Press these' }]);
const frame = () => new Promise((resolve) => requestAnimationFrame(resolve));
await settle();
await frame();
const subs = () => [...document.querySelectorAll('.gev-guide-ring--sub')];
assert.equal(subs().length, 1);
const [sub] = subs();
assert.equal(sub.className, 'gev-guide-ring gev-guide-ring--sub');
assert.equal(sub.parentElement, $('.gev-guide'));
assert.equal(sub.previousElementSibling, $('.gev-guide-callout'));
assert.equal(sub.childElementCount, 0);
assert.equal(sub.style.opacity, '1');
assert.equal(sub.style.left, '96px');
assert.equal(sub.style.width, '38px');
// A step with fewer targets keeps the ring, faded out.
targets = [target];
$('.gev-guide-ring').dispatchEvent(new Event('scroll', { bubbles: true }));
await frame();
assert.deepEqual(subs(), [sub]);
assert.equal(sub.style.opacity, '0');
});
+3 -3
View File
@@ -68,7 +68,7 @@ test('before RadioControls renders, the panel shows its initial markup', (t) =>
assert.equal($('radio-filter').options.length, 1);
assert.equal($('radio-filter').options[0].value, 'all');
assert.equal($('radio-filter').options[0].textContent, 'All');
assert.equal($('radio-play-btn').getAttribute('class'), null);
assert.equal(coreClasses($('radio-play-btn')), '');
assert.equal($('radio-play-btn').disabled, true);
assert.equal($('radio-volume').value, '80');
assert.equal($('radio-volume-value').textContent, '80%');
@@ -120,7 +120,7 @@ test('the panel renders the presented directory, station, transport and playback
assert.equal($('radio-station-homepage').getAttribute('href'), 'https://example.org/');
assert.equal($('radio-station-homepage').hidden, false);
const play = $('radio-play-btn');
assert.equal(play.className, 'active');
assert.equal(coreClasses(play), 'active');
assert.equal(play.textContent, 'PAUSE');
assert.equal(play.getAttribute('aria-label'), 'Pause selected radio station');
assert.equal($('radio-prev-btn').disabled, false);
@@ -128,7 +128,7 @@ test('the panel renders the presented directory, station, transport and playback
assert.equal($('radio-playback-state').textContent, 'Playing KJAZ');
await render({ audioState: 'error', filter: 'all' });
assert.equal(play.className, '');
assert.equal(coreClasses(play), '');
assert.equal($('radio-playback-state').className, 'radio-playback-state error');
assert.equal($('radio-station-homepage').hasAttribute('href'), false);
assert.equal($('radio-station-homepage').hidden, true);
+33 -23
View File
@@ -2,6 +2,7 @@
import { computed, onBeforeUnmount } from 'vue';
import RailCardBlocks from './RailCardBlocks.vue';
import UiBadge from '../kit/UiBadge.vue';
import UiButton from '../kit/UiButton.vue';
// One keyed card: a disclosure header and its blocks. The owner decides
// which card is open.
@@ -20,6 +21,12 @@ onBeforeUnmount(() => {
live = false;
});
const select = () => live && props.onOpen(props.card.id);
// The header's contents are the slot of a UiButton, which renders inside the
// button: a new card alone would reach them only on a later tick, but the
// owner patches synchronously and measures at once. A slot given under a
// condition (`redrawWithView`, always true) is redrawn whenever this card is,
// so it keeps up.
const redrawWithView = true;
</script>
<script>
@@ -32,33 +39,36 @@ const nextBodyId = () => ++bodies;
:class="`rail-card${cardClassName ? ` ${cardClassName}` : ''}${open ? ' is-open' : ''}`"
:data-card-id="card.id"
:data-open="String(open)"
><button
><UiButton
class="rail-card-header"
type="button"
:aria-controls="bodyId"
:aria-expanded="String(open)"
@click="select"
><span class="rail-card-labels"
><span class="rail-card-heading"
><span class="data-icon" aria-hidden="true" :hidden="!card.icon">{{
card.icon || ''
}}</span
><span class="rail-card-title rail-card-nowrap" :title="card.title">{{
card.title
}}</span></span
><UiBadge
:class="`gev-status-badge--plain rail-card-badge${badgeClassName ? ` ${badgeClassName}` : ''}`"
:hidden="!card.badge"
>{{ card.badge || '' }}</UiBadge
></span
><span class="rail-card-disclosure" aria-hidden="true">{{
open ? '▾' : '▸'
}}</span
><span
:class="`rail-card-compact${card.compactStatus ? ' status' : ''}`"
:hidden="open"
>{{ card.compact || '' }}</span
></button
><template v-if="redrawWithView" #default
><span class="rail-card-labels"
><span class="rail-card-heading"
><span class="data-icon" aria-hidden="true" :hidden="!card.icon">{{
card.icon || ''
}}</span
><span
class="rail-card-title rail-card-nowrap"
:title="card.title"
>{{ card.title }}</span
></span
><UiBadge
:class="`gev-status-badge--plain rail-card-badge${badgeClassName ? ` ${badgeClassName}` : ''}`"
:hidden="!card.badge"
>{{ card.badge || '' }}</UiBadge
></span
><span class="rail-card-disclosure" aria-hidden="true">{{
open ? '▾' : '▸'
}}</span
><span
:class="`rail-card-compact${card.compactStatus ? ' status' : ''}`"
:hidden="open"
>{{ card.compact || '' }}</span
></template
></UiButton
><div :id="bodyId" class="rail-card-body" :hidden="!open"
><RailCardBlocks
:blocks="card.blocks || []"
+7 -11
View File
@@ -2,6 +2,7 @@
import { onBeforeUnmount } from 'vue';
import { t } from '../../i18n/index.js';
import { formatScaleRange } from '../unitLabels.js';
import UiButton from '../kit/UiButton.vue';
import UiCloseButton from '../kit/UiCloseButton.vue';
import RailCardSetting from './RailCardSetting.vue';
import RailChips from './RailChips.vue';
@@ -166,28 +167,23 @@ function legendView(legend) {
:title="action.title || undefined"
@click="dispatch(action, block)"
>{{ action.label }}</a
><button
><UiButton
v-else
:class="[
'data-toggle-chip',
{ active: action.pressed, 'is-reserved': action.reserved },
]"
type="button"
:class="['data-toggle-chip', { 'is-reserved': action.reserved }]"
:data-action-id="action.id"
:title="action.title || undefined"
:disabled="Boolean(action.disabled)"
:aria-pressed="
action.pressed === undefined
? undefined
: String(Boolean(action.pressed))
:pressed="
action.pressed === undefined ? undefined : Boolean(action.pressed)
"
pressed-class="active"
:aria-hidden="
action.reserved === undefined
? undefined
: String(Boolean(action.reserved))
"
@click="dispatch(action, block)"
>{{ action.label }}</button
>{{ action.label }}</UiButton
><span class="rail-card-action-hint" :hidden="!action.hint">{{
action.hint || ''
}}</span></template
+5 -6
View File
@@ -1,5 +1,6 @@
<script setup>
import UiButton from '../kit/UiButton.vue';
import UiIcon from '../kit/UiIcon.vue';
// Keyed chips shared by rail cards; the owner decides what a click does.
// An `icon` chip shows a Material Symbol (named in index.html's `icon_names`
@@ -29,11 +30,9 @@ const chipClass = (chip) =>
:disabled="Boolean(chip.disabled)"
:aria-busy="String(Boolean(chip.busy))"
@click="onSelect(chip)"
><span
v-if="chip.icon"
class="material-symbols-outlined"
aria-hidden="true"
>{{ chip.icon }}</span
><template v-else>{{ chip.label }}</template></UiButton
><UiIcon v-if="chip.icon" :name="chip.icon" :size="null" /><template
v-else
>{{ chip.label }}</template
></UiButton
>
</template>
+6 -5
View File
@@ -1,5 +1,6 @@
<script setup>
import { onMounted, onUpdated, ref } from 'vue';
import UiButton from '../kit/UiButton.vue';
// An ordered list whose rows keep their identity, so a focused row stays.
const props = defineProps({
@@ -10,7 +11,7 @@ const props = defineProps({
const root = ref(null);
const rowClass = (item) =>
`data-row-list-item${item.disabled ? ' note' : ''}${item.active ? ' active' : ''}${item.current ? ' current' : ''}`;
`data-row-list-item${item.disabled ? ' note' : ''}${item.current ? ' current' : ''}`;
// Follow the flight, but never steal a scroll the reader is making
// themselves: only when the step actually changed.
@@ -43,19 +44,19 @@ onUpdated(followCurrent);
v-for="item in list?.items ?? []"
:key="item.id"
:data-list-item-id="item.id"
><button
type="button"
><UiButton
:class="rowClass(item)"
:data-list-item-id="item.id"
:disabled="Boolean(item.disabled)"
:aria-current="item.current ? 'step' : 'false'"
:aria-pressed="item.active ? 'true' : 'false'"
:pressed="Boolean(item.active)"
pressed-class="active"
:title="String(item.text ?? '')"
@click="onSelect(item)"
><span class="data-row-list-lead">{{ String(item.lead ?? '') }}</span
><span class="data-row-list-text">{{
String(item.text ?? '')
}}</span></button
}}</span></UiButton
></li
></ol
>
+7 -9
View File
@@ -1,5 +1,6 @@
<script setup>
import { t } from '../../i18n/index.js';
import UiButton from '../kit/UiButton.vue';
// One imagery day in the strip. The owner computes every value; clicks reach
// it through the readout's delegated listener.
@@ -46,21 +47,18 @@ defineProps({
><div class="ri-card-sensor">{{ card.sensor }}</div
><div class="ri-card-cloud">{{ card.cloud }}</div
><div class="ri-card-chips"
><button
><UiButton
v-for="chip in card.chips"
:key="chip.slot"
type="button"
:class="[
'data-toggle-chip ri-chip',
{ active: chip.active, 'is-reserved': chip.reserved },
]"
:class="['data-toggle-chip ri-chip', { 'is-reserved': chip.reserved }]"
tabindex="-1"
:data-slot="chip.slot"
:disabled="chip.disabled"
:aria-pressed="String(chip.active)"
:disabled="Boolean(chip.disabled)"
:pressed="Boolean(chip.active)"
pressed-class="active"
:aria-hidden="String(chip.reserved)"
:aria-label="chip.ariaLabel"
>{{ chip.label }}</button
>{{ chip.label }}</UiButton
></div
></div
>
+8 -11
View File
@@ -1,6 +1,7 @@
<script setup>
import { computed } from 'vue';
import { t } from '../../i18n/index.js';
import UiButton from '../kit/UiButton.vue';
import UiCloseButton from '../kit/UiCloseButton.vue';
import UiSegmented from '../kit/UiSegmented.vue';
import RailCardBlocks from '../rail/RailCardBlocks.vue';
@@ -51,17 +52,16 @@ const modeOptions = computed(() =>
aria-live="polite"
:title="view.notice.text"
>{{ view.notice.text }}</span
><button
><UiButton
id="ri-zoom-in"
:class="[
'data-toggle-chip ri-zoom-in',
{ 'is-reserved': !view.notice.fit },
]"
type="button"
:title="t('Fly in until the view fits the 1,000 km limit')"
:disabled="!view.notice.fit"
:aria-hidden="String(!view.notice.fit)"
>{{ t('ZOOM IN') }}</button
>{{ t('ZOOM IN') }}</UiButton
></div
><div
id="ri-strip"
@@ -131,21 +131,18 @@ const modeOptions = computed(() =>
max="100"
step="1"
:aria-label="t('Imagery opacity')"
:disabled="!view.opacityEnabled" /><button
:disabled="!view.opacityEnabled" /><UiButton
id="ri-swap"
:class="[
'data-toggle-chip ri-swap',
{
'is-reserved': !view.swap.live,
active: view.swap.pressed,
},
{ 'is-reserved': !view.swap.live },
]"
type="button"
:title="t('Trade the two sides of the divider')"
:disabled="!view.swap.live"
:aria-hidden="String(!view.swap.live)"
:aria-pressed="String(view.swap.pressed)"
>{{ t('SWAP') }}</button
:pressed="Boolean(view.swap.pressed)"
pressed-class="active"
>{{ t('SWAP') }}</UiButton
><div class="ri-exports"
><RailCardBlocks
:blocks="view.exports"
+4 -3
View File
@@ -417,9 +417,10 @@ export class ShareRestoration {
this._layerStateRestorePromise = this._layerStateCoordinator.start({
shareLayerState: this._initialShareState?.layerState || null,
shareCreatedAtMs: this._initialShareState?.sharedAtMs ?? null,
// Any valid camera/style share isolates recipient-local preferences,
// including legacy and malformed-v2 layer payloads.
allowLocalState: !this._initialShareState,
// A link restores what it carries; a bare address is a clean start
// with the default layers. Saved layer choices never come back on
// their own, so clearing the address always resets the view.
allowLocalState: false,
});
if (this._initialShareSelectionSuperseded) {
this._layerStateCoordinator.cancelPendingShareTracking(
+2 -1
View File
@@ -13,7 +13,8 @@ export const useBhoteKoshiPanelStore = defineStore(
/**
* `{owner, sceneBeat, refs, beforeDate, afterDate, reports}`, or null while
* the event layer is off. Each entry of `refs` holds one control's
* `textContent`, `hidden`, `disabled`, `value` and `attributes`.
* `textContent`, `hidden`, `disabled`, `value` and `attributes`; the
* cinematic button's also holds `pressed`.
*/
const panel = shallowRef(null);
+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 };
},
);
+3 -1
View File
@@ -703,7 +703,9 @@ html:not([lang='en']) .cockpit-roll-token.is-separator {
color: var(--cockpit-accent);
font-size: 12px;
}
.cockpit-heading-caret {
/* Inside the compass, so it outranks the kit icon's own display and
line height. */
.cockpit-compass .cockpit-heading-caret {
display: block;
height: 20px;
color: var(--cockpit-accent);
Loaded 100 of 164 files, more files were not shown because too many files have changed in this diff. Show more