Merge main and keep both sets of CCTV rendering tests

This commit is contained in:
German Khokhlov committed 2026-11-20 13:24:48 +04:00
commit f10ea2e6b4
190 files changed
+10516 -971

No files matched your search

+2
View File
@@ -50,6 +50,7 @@ test('normalizeAlprNode: maps a full OSM node to a plain record', () => {
'surveillance:type': 'ALPR',
operator: 'Flock Safety',
'camera:type': 'fixed',
model: ' L6Q ',
'surveillance:zone': 'traffic',
'camera:direction': '270',
ref: 'ATX-001',
@@ -63,6 +64,7 @@ test('normalizeAlprNode: maps a full OSM node to a plain record', () => {
longitude: -97.7431,
operator: 'Flock Safety',
manufacturer: null,
model: 'L6Q',
cameraType: 'fixed',
zone: 'traffic',
directionDeg: 270,
+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
+1 -1
View File
@@ -32,7 +32,7 @@ export function createInfrastructureLayers(services) {
name: 'Dams',
color: '#0088ff', // Blue
icon: '▰',
source: 'USACE',
source: 'OpenStreetMap / OpenInfraMap',
osmDerived: true,
labels: true,
labelMax: 900,
+79 -2
View File
@@ -6,6 +6,7 @@ import { createInfrastructureLayers } from 'gods-eye-view/infrastructure';
import { createLocalGeoJsonLayer } from 'gods-eye-view/infrastructure/geojson';
import { fakeInput } from '../input/testDoubles.mjs';
import { bindFakeGroundRenderer } from '../testSupport/fakeGroundRenderer.mjs';
import { parseGeojsonLines } from '../sources/infrastructureData.js';
function services() {
const records = new Map();
@@ -34,6 +35,20 @@ function services() {
};
}
// Added from the OSM API, not the OpenInfraMap extract: [id, name, OSM
// object, version]. Both must stay polygons: the Dams layer skips
// LineStrings.
const OSM_API_DAMS = [
[262532166, 'Acaray', 'way/262532166', 7],
[-5671745, 'Represa Yacyretá-Apipé', 'relation/5671745', 2],
];
const DAMS = parseGeojsonLines(
readFileSync(
new URL('./local_data/dams/dams.geojsonl', import.meta.url),
'utf8',
),
);
test('package exports import without an application, DOM, fetch, or timers', () => {
const result = spawnSync(
process.execPath,
@@ -66,7 +81,11 @@ test('infrastructure factory preserves identity and creates independent state wi
first.map(({ id, name, source }) => ({ id, name, source })),
[
{ id: 'local-datacenters', name: 'Datacenters', source: 'Local' },
{ id: 'local-dams', name: 'Dams', source: 'USACE' },
{
id: 'local-dams',
name: 'Dams',
source: 'OpenStreetMap / OpenInfraMap',
},
],
);
first.forEach((layer, index) => {
@@ -84,7 +103,7 @@ test('infrastructure factory preserves identity and creates independent state wi
test('dataset URLs still name the complete bundled sources', () => {
for (const [file, count] of [
['datacenters', 4352],
['dams', 704],
['dams', 706],
]) {
const lines = readFileSync(
new URL(`./local_data/${file}/${file}.geojsonl`, import.meta.url),
@@ -96,6 +115,64 @@ test('dataset URLs still name the complete bundled sources', () => {
}
});
test('Acaray and Yacyretá appear once each with OSM provenance', () => {
for (const [id, name, object, version] of OSM_API_DAMS) {
const matches = DAMS.filter((feature) => feature.id === id);
assert.equal(matches.length, 1);
const { properties } = matches[0];
assert.equal(properties.name, name);
assert.equal(properties.osm_id, id);
assert.equal(properties.source_version, version);
assert.equal(
properties.source_url,
`https://www.openstreetmap.org/${object}`,
);
assert.equal(properties.retrieved_at, '2026-10-15');
}
});
test('Acaray and Yacyretá each get a stem, a selection context and an analyst record', async (t) => {
const added = DAMS.filter((feature) =>
OSM_API_DAMS.some(([id]) => id === feature.id),
);
t.mock.method(globalThis, 'fetch', async () => ({
ok: true,
text: async () =>
added.map((feature) => JSON.stringify(feature)).join('\n'),
}));
const host = services();
const layer = createLocalGeoJsonLayer(
{
id: 'local-dams',
name: 'Dams',
osmDerived: true,
color: '#0088ff',
url: '/dams.geojsonl',
},
host,
);
const viewer = {
scene: { screenSpaceCameraController: { enableInputs: true } },
};
const fake = bindFakeGroundRenderer(viewer);
fakeInput(viewer);
t.after(() => layer.destroy(viewer));
await layer.enable(viewer);
const names = OSM_API_DAMS.map(([, name]) => name).sort();
assert.equal(fake.set('stems').items.size, 2, 'both dams get a stem');
assert.deepEqual(
[...host.records.values()].map((record) => record.label).sort(),
names,
);
assert.deepEqual(
layer
.getAnalystRecords()
.map((record) => record.name)
.sort(),
names,
);
});
test('two viewers use their supplied contexts and dispose independently', async (t) => {
t.mock.method(globalThis, 'fetch', async () => ({
ok: true,
+43
View File
@@ -3231,3 +3231,46 @@ test('an application with every layer registered keeps every requested layer', a
]);
coordinator.destroy();
});
test('start layers turn on when nothing names any, and are never written as the user choice', async () => {
const storage = memoryStorage();
const manager = productionManager();
const coordinator = new LayerStateCoordinator(manager, shareSink(), {
storage,
});
const results = await coordinator.start({
allowLocalState: false,
startLayerIds: ['earthquakes', 'traffic', 'not-a-layer'],
});
assert.equal(coordinator.source, 'start');
assert.deepEqual(coordinator.getDurableState().enabledLayerIds, [
'earthquakes',
'traffic',
]);
assert.equal(manager.isEnabled('earthquakes'), true);
assert.equal(manager.isEnabled('traffic'), true);
assert.equal(
results.every((result) => result.persistenceWrite === false),
true,
);
assert.deepEqual(storage.writes, []);
coordinator.destroy();
});
test('a shared layer payload wins over start layers', async () => {
const manager = productionManager();
const coordinator = new LayerStateCoordinator(manager, shareSink(), {
storage: memoryStorage(),
});
const shared = createDefaultLayerState();
shared.enabledLayerIds = ['radio'];
await coordinator.start({
shareLayerState: shared,
allowLocalState: false,
startLayerIds: ['earthquakes'],
});
assert.equal(coordinator.source, 'share');
assert.deepEqual(coordinator.getDurableState().enabledLayerIds, ['radio']);
assert.equal(manager.isEnabled('earthquakes'), false);
coordinator.destroy();
});
+8 -1
View File
@@ -103,6 +103,7 @@ export class LayerStateCoordinator {
shareLayerState = null,
allowLocalState = true,
shareCreatedAtMs = null,
startLayerIds = [],
} = {}) {
if (this._destroyed)
throw new Error('Layer-state coordinator is destroyed');
@@ -125,7 +126,13 @@ export class LayerStateCoordinator {
selected = this._normalize(stored);
this._source = 'local';
}
} else {
}
if (!selected && startLayerIds.length) {
// The layers the application starts with when nothing names any:
// restored passively, so they are never written as the user's choice.
selected = this._normalize({ enabledLayerIds: startLayerIds });
this._source = 'start';
} else if (!selected && !allowLocalState) {
// A valid historical camera/style share with no v2 layer payload keeps
// the exact legacy default-layer behavior. It must not inherit an
// unrelated recipient's saved local layer preferences.
+14 -1
View File
@@ -4,7 +4,7 @@ Extracted from local decoded OpenInfraMap/PostGIS layers.
Filters: `waterway=dam`, `man_made=dam`, or `building=dam`.
Feature count: 704
Feature count: 706
Runtime output: `dams.geojsonl`
@@ -15,3 +15,16 @@ this derived database.
The public-release snapshot removes contact-oriented fields and note values
that contain email or phone identifiers. The runtime layer does not display or
depend on those fields.
## OSM API additions
Two dams come from the public OpenStreetMap API rather than the extract:
- Acaray: [way 262532166](https://www.openstreetmap.org/way/262532166), its closed outline of nine nodes.
- Represa Yacyretá-Apipé: [relation 5671745](https://www.openstreetmap.org/relation/5671745), its eight outer ways joined into one closed outline.
Both are under the same ODbL 1.0; the relation keeps the extract's negative ID (-5671745).
Keep both as polygons: the Dams layer skips LineStrings.
The layer puts a polygon's marker at the centre of its bounding sphere. The Yacyretá outline is L-shaped, so its
marker sits about 1.6 km from the outline, over the reservoir.
+2
View File
@@ -702,3 +702,5 @@
{"id":1415605139,"type":"Feature","geometry":{"type":"LineString","coordinates":[[169.362055788,-45.423612051],[169.360158461,-45.423276272],[169.358642426,-45.4229907],[169.357633077,-45.422794061],[169.356944755,-45.42275366],[169.356044036,-45.422764473]]},"properties":{"id":2377429,"line":"","tags":{"power":"minor_line","voltage":"11000","operator":"Aurora Energy","waterway":"dam","operator:wikidata":"Q4822522"},"type":"minor_line","osm_id":1415605139,"tunnel":false,"disused":"","voltage":"11000","circuits":null,"location":"","frequency":"","construction":"","source_layer":"osm_power_line"}}
{"id":405007988,"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[51.592068922,43.199413946],[51.59684602,43.199885177],[51.59724064,43.197759191],[51.593578084,43.197397847],[51.59272137,43.197675623],[51.592397577,43.197643772],[51.592068922,43.199413946]]]},"properties":{"id":33090,"name":"","tags":{"man_made":"wastewater_plant","waterway":"dam"},"type":"wastewater_plant","osm_id":405007988,"source_layer":"osm_wastewater_plant"}}
{"id":-19953989,"type":"Feature","geometry":{"type":"MultiLineString","coordinates":[[[14.292237283,46.169084857],[14.292230326,46.169090389],[14.292224878,46.169096341],[14.292219346,46.169103549],[14.292216999,46.169113188],[14.292215322,46.169122744],[14.29221658,46.169131796],[14.292221273,46.169138334],[14.292231918,46.169148225],[14.29223963,46.169150823]],[[14.292171736,46.168911268],[14.292167462,46.168929289],[14.29216654,46.168975893],[14.292183555,46.169023083],[14.292186321,46.169030124],[14.292204593,46.169025933],[14.292237283,46.169084857]],[[14.293466824,46.169211843],[14.293464394,46.169201869],[14.293090644,46.16923657],[14.293067678,46.169224248],[14.293022583,46.169223662],[14.292636178,46.169247718],[14.292563842,46.169209496],[14.292558394,46.169207988],[14.292478766,46.169186446],[14.292457643,46.169185021],[14.292426882,46.169183429],[14.29241347,46.169186446],[14.292388492,46.169203545],[14.292448842,46.169220477],[14.292470384,46.169226428],[14.292521681,46.169242772],[14.292532661,46.169225673],[14.292546659,46.169229529],[14.29256468,46.169234558],[14.292535679,46.169293483],[14.292533499,46.169297925],[14.292576582,46.169300859],[14.292619162,46.169286191],[14.293023422,46.169262554],[14.293072791,46.169259536],[14.293092321,46.169248388],[14.293466824,46.169211843]],[[14.292535679,46.169293483],[14.29249905,46.169285185],[14.292510198,46.169267248],[14.292313977,46.169211927],[14.292318755,46.169203042],[14.29232546,46.169190721],[14.292333256,46.169176472],[14.292290089,46.169164653],[14.292276175,46.169192062],[14.292257986,46.169227769],[14.29231163,46.169241767],[14.292303919,46.169254842],[14.292294196,46.169271439],[14.292207024,46.169244868],[14.292170647,46.169314522],[14.29248589,46.169394736],[14.292518496,46.169328436],[14.292526123,46.169312845],[14.292533499,46.169297925],[14.292535679,46.169293483]],[[14.292426882,46.169183429],[14.292448172,46.169103549],[14.292476838,46.169107153],[14.292457643,46.169185021],[14.292426882,46.169183429]],[[14.292237283,46.169084857],[14.292246922,46.169084941],[14.292247257,46.169081086],[14.292319845,46.169084857],[14.292448172,46.169103549],[14.292476838,46.169107153],[14.292575074,46.169109333],[14.292575493,46.169095838],[14.292480777,46.169093156],[14.292326383,46.169069099],[14.292247341,46.169065747],[14.292242228,46.169055269],[14.292266117,46.169050324],[14.292263099,46.169041858],[14.292231835,46.169048899],[14.292217418,46.169022161],[14.292267374,46.16901336],[14.292264943,46.169006235],[14.292183555,46.169023083],[14.292186321,46.169030124],[14.292204593,46.169025933],[14.292237283,46.169084857]]]},"properties":{"name":"HE Podlubnik - Centrala","tags":{"name":"HE Podlubnik - Centrala","type":"site","power":"plant","alt_name":"HE Škofja Loka","operator":"Elektro Gorenjska","waterway":"dam","start_date":"1969","plant:method":"run-of-the-river","plant:source":"hydro","plant:output:electricity":"330KW"},"osm_id":-19953989,"output":"330KW","source":"hydro","construction":"","source_layer":"power_plant_relation_by_geom_type"}}
{"type":"Feature","id":-5671745,"geometry":{"type":"Polygon","coordinates":[[[-56.7356385,-27.4830326],[-56.7356372,-27.4836817],[-56.7356918,-27.4837745],[-56.7356509,-27.4838875],[-56.7355326,-27.4837665],[-56.7354735,-27.4836131],[-56.7353507,-27.4835526],[-56.7353552,-27.4830522],[-56.7354053,-27.483032],[-56.7354041,-27.4829378],[-56.7350345,-27.4826704],[-56.7321442,-27.4826598],[-56.7319588,-27.4828659],[-56.7018972,-27.4827418],[-56.7018797,-27.4821358],[-56.706089,-27.4821869],[-56.7060921,-27.4821089],[-56.7063455,-27.482095],[-56.7063734,-27.4821649],[-56.7090948,-27.482163],[-56.7091818,-27.4821095],[-56.7093995,-27.4820799],[-56.7094201,-27.4821854],[-56.7106196,-27.4821876],[-56.7109955,-27.4820628],[-56.7121754,-27.4820408],[-56.7121751,-27.4817168],[-56.712209,-27.4817165],[-56.7122144,-27.4803221],[-56.7121755,-27.4803209],[-56.7121781,-27.4793322],[-56.7122425,-27.4793286],[-56.7122439,-27.4791204],[-56.7121688,-27.479118],[-56.7121795,-27.4788039],[-56.7122371,-27.4788007],[-56.7122492,-27.4788015],[-56.7122948,-27.4790038],[-56.7123002,-27.4793441],[-56.7123005,-27.4796668],[-56.7124411,-27.4796679],[-56.7125759,-27.4796689],[-56.7125765,-27.47935],[-56.7125805,-27.4792477],[-56.7125939,-27.4790371],[-56.7126422,-27.4788016],[-56.7126649,-27.4788009],[-56.7127186,-27.4788051],[-56.7127213,-27.4791216],[-56.7126462,-27.4791276],[-56.7126516,-27.4793274],[-56.7127079,-27.4793263],[-56.7127072,-27.4803126],[-56.7126744,-27.4803132],[-56.712673,-27.4817118],[-56.7127239,-27.481713],[-56.7127247,-27.4820404],[-56.7132439,-27.4820594],[-56.7135349,-27.4821853],[-56.716431,-27.4821918],[-56.7166924,-27.4821402],[-56.7169096,-27.482192],[-56.7354167,-27.4822992],[-56.7432767,-27.4822775],[-56.7432829,-27.4821624],[-56.7433092,-27.4820925],[-56.7433441,-27.4820092],[-56.743387,-27.4819117],[-56.7433977,-27.481826],[-56.7434058,-27.481362],[-56.743385,-27.4806888],[-56.7435047,-27.4806879],[-56.7435053,-27.480804],[-56.7517581,-27.4808023],[-56.7519858,-27.4807842],[-56.7522074,-27.4807224],[-56.7529074,-27.4805122],[-56.7530675,-27.4804512],[-56.753188,-27.4804018],[-56.7536873,-27.4801667],[-56.7539035,-27.480035],[-56.7540186,-27.4799455],[-56.7546428,-27.4793125],[-56.7548624,-27.4789803],[-56.755134,-27.4784449],[-56.7553243,-27.4776504],[-56.7553385,-27.4775558],[-56.7553453,-27.4773839],[-56.7553663,-27.453364],[-56.756278,-27.4533505],[-56.7566902,-27.4545407],[-56.7565699,-27.4671653],[-56.7566153,-27.4769172],[-56.7565098,-27.4782975],[-56.7561882,-27.4791614],[-56.7557343,-27.4797995],[-56.7548315,-27.4808659],[-56.7541622,-27.4813087],[-56.753515,-27.4815729],[-56.7529038,-27.4817915],[-56.7522708,-27.4819086],[-56.7486914,-27.4820093],[-56.7480953,-27.4820155],[-56.7478466,-27.4820264],[-56.747675,-27.4820455],[-56.7475127,-27.4820919],[-56.7469953,-27.4823096],[-56.7450435,-27.4829093],[-56.7443696,-27.4830283],[-56.7436163,-27.4830891],[-56.7434021,-27.483068],[-56.7396907,-27.4830592],[-56.7396861,-27.4833826],[-56.7394399,-27.4833826],[-56.739439,-27.4830604],[-56.7356385,-27.4830326]]]},"properties":{"name":"Represa Yacyretá-Apipé","tags":{"name":"Represa Yacyretá-Apipé","type":"multipolygon","waterway":"dam"},"osm_id":-5671745,"source_layer":"osm_relation","source_url":"https://www.openstreetmap.org/relation/5671745","source_version":2,"retrieved_at":"2026-10-15"}}
{"type":"Feature","id":262532166,"geometry":{"type":"Polygon","coordinates":[[[-54.6285064,-25.4587626],[-54.628456,-25.4586556],[-54.6286513,-25.458535],[-54.6287352,-25.4587382],[-54.6292971,-25.459876],[-54.6290649,-25.4599721],[-54.6285037,-25.4588762],[-54.6285459,-25.4588065],[-54.6285064,-25.4587626]]]},"properties":{"name":"Acaray","tags":{"name":"Acaray","waterway":"dam","wikidata":"Q3433454"},"osm_id":262532166,"source_layer":"osm_way","source_url":"https://www.openstreetmap.org/way/262532166","source_version":7,"retrieved_at":"2026-10-15"}}
+102
View File
@@ -0,0 +1,102 @@
import { fromDegreesInto } from '../geo/ellipsoid.js';
/**
* Finding a selected vessel or aircraft again once it has left the screen or
* its layer's feed: where its own track has it at a time, and whether a point
* is on screen at all.
*/
/**
* The newest point of a track at or before `atMs` (any time when `atMs` is
* not given), from a live source's `getTrack` records
* (`{observedAtMs, latitude, longitude, baroAltitudeM?}`).
* @param {Array<object>} points
* @param {number} [atMs]
* @returns {{lat: number, lon: number, altitudeM: ?number, observedAtMs: number}|null}
*/
export function readingAt(points, atMs) {
let best = null;
for (const point of points ?? []) {
const lat = Number(point?.latitude);
const lon = Number(point?.longitude);
const observedAtMs = point?.observedAtMs;
if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue;
if (!Number.isFinite(observedAtMs)) continue;
if (Number.isFinite(atMs) && observedAtMs > atMs) continue;
if (best && best.observedAtMs >= observedAtMs) continue;
const altitude = Number(point.baroAltitudeM ?? point.altitudeM);
best = {
lat,
lon,
altitudeM: Number.isFinite(altitude) ? altitude : null,
observedAtMs,
};
}
return best;
}
/**
* Where a source's track has a vessel or aircraft at `atMs` (now, when not
* given): `{status: 'found', lat, lon, altitudeM, observedAtMs, atMs}`, or
* `{status: 'none'}` when the track has no point at or before the time, the
* source keeps no tracks or the lookup fails.
* @param {{getTrack?: Function}|null} source
* @param {string} reference The track reference the layer's records carry.
* @param {{atMs?: number, signal?: AbortSignal}} [options]
*/
export async function locateOnTrack(source, reference, { atMs, signal } = {}) {
if (typeof source?.getTrack !== 'function' || !reference)
return { status: 'none' };
try {
const track = await source.getTrack(
reference,
Number.isFinite(atMs) ? { signal, atMs } : { signal },
);
const reading = readingAt(track?.records, atMs);
// The time it was looked up for, so its reading's age can be told.
const at = Number.isFinite(atMs) ? atMs : Date.now();
return reading
? { status: 'found', ...reading, atMs: at }
: { status: 'none' };
} catch (error) {
if (signal?.aborted) throw error;
return { status: 'none' };
}
}
/** Mean Earth radius (m), for the horizon test. */
const EARTH_RADIUS_M = 6_371_000;
/**
* Whether a point is in the camera's view: in front of it, inside its field
* of view and on the near side of the globe.
* @param {{position: {x, y, z}, direction: {x, y, z}, up: {x, y, z},
* right: {x, y, z}, fovy: number, aspectRatio: number}} pose
* @param {number} lat
* @param {number} lon
* @param {number} [heightM]
* @returns {boolean}
*/
export function onScreen(pose, lat, lon, heightM = 0) {
if (!pose?.position || !Number.isFinite(lat) || !Number.isFinite(lon))
return false;
const p = fromDegreesInto(lon, lat, Math.max(0, heightM || 0), {
x: 0,
y: 0,
z: 0,
});
const c = pose.position;
const v = { x: p.x - c.x, y: p.y - c.y, z: p.z - c.z };
const dot = (a, b) => a.x * b.x + a.y * b.y + a.z * b.z;
const ahead = dot(v, pose.direction);
if (!(ahead > 0)) return false;
const tanY = Math.tan(pose.fovy / 2);
const tanX = tanY * (pose.aspectRatio || 1);
if (Math.abs(dot(v, pose.right) / ahead) > tanX) return false;
if (Math.abs(dot(v, pose.up) / ahead) > tanY) return false;
// Behind the globe: the camera is below the point's horizon plane. Judged
// on a sphere through the point, which is close enough for a button.
const length = Math.hypot(p.x, p.y, p.z) || EARTH_RADIUS_M;
const normal = { x: p.x / length, y: p.y / length, z: p.z / length };
return dot({ x: c.x - p.x, y: c.y - p.y, z: c.z - p.z }, normal) > 0;
}
+114
View File
@@ -0,0 +1,114 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { locateOnTrack, onScreen, readingAt } from './locate.js';
import { fromDegreesInto } from '../geo/ellipsoid.js';
const point = (observedAtMs, latitude, longitude, extra = {}) => ({
observedAtMs,
latitude,
longitude,
...extra,
});
test('the reading at a time is the newest point at or before it', () => {
const track = [
point(3_000, 3, 30),
point(1_000, 1, 10, { baroAltitudeM: 900 }),
point(2_000, 2, 20),
point(Number.NaN, 9, 90),
point(4_000, Number.NaN, 40),
];
assert.deepEqual(readingAt(track, 2_500), {
lat: 2,
lon: 20,
altitudeM: null,
observedAtMs: 2_000,
});
assert.equal(readingAt(track, 1_000).altitudeM, 900, 'at its own time');
assert.equal(readingAt(track).observedAtMs, 3_000, 'no time: the newest');
assert.equal(readingAt(track, 500), null, 'before its first point');
assert.equal(readingAt([], 500), null);
});
test('a track lookup asks for the time and reads the point at it', async () => {
const asked = [];
const source = {
async getTrack(reference, options) {
asked.push([reference, options.atMs]);
return { records: [point(1_000, 1, 10), point(5_000, 5, 50)] };
},
};
assert.deepEqual(await locateOnTrack(source, 'vessel:a', { atMs: 2_000 }), {
status: 'found',
lat: 1,
lon: 10,
altitudeM: null,
observedAtMs: 1_000,
atMs: 2_000,
});
assert.deepEqual(asked, [['vessel:a', 2_000]]);
assert.deepEqual(await locateOnTrack(source, 'vessel:a', { atMs: 500 }), {
status: 'none',
});
const live = await locateOnTrack(source, 'vessel:a');
assert.equal(live.observedAtMs, 5_000, 'live: its newest point');
assert.equal(asked.at(-1)[1], undefined, 'live asks for no time');
});
test('a source without tracks, or one that fails, finds nothing', async () => {
assert.deepEqual(await locateOnTrack({}, 'a'), { status: 'none' });
assert.deepEqual(await locateOnTrack(null, 'a'), { status: 'none' });
const failing = {
getTrack: async () => {
throw new Error('down');
},
};
assert.deepEqual(await locateOnTrack(failing, 'a'), { status: 'none' });
assert.deepEqual(
await locateOnTrack({ getTrack: async () => ({ records: [] }) }, ''),
{ status: 'none' },
'no reference',
);
});
/** A camera 1000 km above a point, looking straight down. */
function poseAbove(lat, lon) {
const at = fromDegreesInto(lon, lat, 0, { x: 0, y: 0, z: 0 });
const length = Math.hypot(at.x, at.y, at.z);
const up = { x: at.x / length, y: at.y / length, z: at.z / length };
const position = {
x: at.x + up.x * 1e6,
y: at.y + up.y * 1e6,
z: at.z + up.z * 1e6,
};
const direction = { x: -up.x, y: -up.y, z: -up.z };
// North-ish screen up, east right: any pair at right angles will do.
const east = {
x: -Math.sin((lon * Math.PI) / 180),
y: Math.cos((lon * Math.PI) / 180),
z: 0,
};
const north = {
x: up.y * east.z - up.z * east.y,
y: up.z * east.x - up.x * east.z,
z: up.x * east.y - up.y * east.x,
};
return {
position,
direction,
up: north,
right: east,
fovy: Math.PI / 3,
aspectRatio: 1.5,
};
}
test('a point is on screen in view, and not out of view or behind the globe', () => {
const pose = poseAbove(10, 20);
assert.equal(onScreen(pose, 10, 20), true, 'under the camera');
assert.equal(onScreen(pose, 11, 21), true, 'near it');
assert.equal(onScreen(pose, 30, 20), false, 'outside the view');
assert.equal(onScreen(pose, -10, -160), false, 'the far side of the globe');
assert.equal(onScreen(pose, Number.NaN, 20), false, 'no position');
assert.equal(onScreen(null, 10, 20), false, 'no camera');
});
+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);
}
});