Merge branch 'main' into denis/gev-news-layer

Wildlife Sightings (#1591) published share token 9, so News takes the
next free token, 00. The token tests read the ledger before both where
they were written against it, and the README counts both layers.
This commit is contained in:
Denis Groshev committed 2026-11-06 12:33:13 +01:00
commit 2e87dd87eb
144 files changed
+26748 -489

No files matched your search

+16
View File
@@ -17,6 +17,7 @@ import { CockpitCoordinator } from './cockpitCoordinator.js';
import { ContextControls } from './context.js';
import { CctvControls } from './cctv.js';
import { StreetLevelControls } from './streetLevelControls.js';
import { createWildlifeSightingCard } from './wildlifeSightingCard.js';
import { RadioControls } from './radio.js';
import { LocalSdrControls } from './localSdrControls.js';
import { LocationNavigation } from './locationNavigation.js';
@@ -589,6 +590,7 @@ export class StyleManager extends ShellFacade {
this._initRadioPanel();
this._initCctvPanel();
this._initStreetLevelPanel();
this._initWildlifeSightingCard();
this._initGlobalContextPanel();
this._initLocationBar();
this._initMobileShell();
@@ -1073,6 +1075,19 @@ export class StyleManager extends ShellFacade {
return this._runExplicitNavigation('camera', () => focus(cameraId));
}
/** Keep one compact card anchored to the selected wildlife sighting. */
_initWildlifeSightingCard() {
this._wildlifeSightingCard?.destroy();
this._wildlifeSightingCard = null;
const layer = this.services.wildlifeSightingsLayer;
if (!layer) return;
this._wildlifeSightingCard = createWildlifeSightingCard({
layer,
ui: this._ui,
viewer: this.viewer,
});
}
/** Compose the Street Level panel controls from its layer and application actions. */
_initStreetLevelPanel() {
const { streetLevelLayer } = this.services;
@@ -1791,6 +1806,7 @@ export class StyleManager extends ShellFacade {
this._recording.destroy();
this._mobileShell?.destroy();
this._panelNavigation?.destroy();
this._wildlifeSightingCard?.destroy();
this._ui.destroy();
this._panelChrome.destroy();
this._feedback.destroy();
+1
View File
@@ -36,6 +36,7 @@ export const LAYER_NAME_KEYS = Object.freeze({
'fire-perimeters': msg('Fire Perimeters'),
'gnss-integrity': msg('GNSS Integrity'),
'drone-airspace': msg('Prohibited & Restricted Airspace'),
'wildlife-sightings': msg('Wildlife Sightings'),
's2-ghostmaps': msg('S2 GhostMaps'),
news: msg('News'),
wind: msg('Wind'),
+4
View File
@@ -82,6 +82,10 @@ const PANEL_GROUPS = [
'news',
],
},
{
label: msg('Wildlife'),
ids: ['wildlife-sightings'],
},
{
label: msg('Weather'),
ids: [
+21
View File
@@ -34,6 +34,27 @@ test('panel presentation places Transit between Street Traffic and Bike Share in
assert.equal(order.filter(({ id }) => id === 'transit').length, 1);
});
test('Wildlife follows Events and precedes Weather', () => {
const source = readFileSync(
new URL('./layerPanel.js', import.meta.url),
'utf8',
);
const declarations = source.slice(
source.indexOf('const PANEL_GROUPS ='),
source.indexOf('const PANEL_POSITIONS ='),
);
const order = JSON.parse(
runInNewContext(
`const msg = (text) => text;\n${declarations}\nJSON.stringify(PANEL_ORDER)`,
),
);
const wildlife = order.findIndex(({ id }) => id === 'wildlife-sightings');
assert.equal(order[wildlife].label, 'Wildlife');
assert.equal(order[wildlife - 1].id, 's2-ghostmaps');
assert.equal(order[wildlife + 1].id, 'air-quality');
assert.equal(order.filter(({ id }) => id === 'wildlife-sightings').length, 1);
});
test('partial feed controls distinguish incomplete records from stale data and outages', async () => {
const { LayerPanel, layerFeedState, presentLayerToggle } =
await import('./layerPanel.js');
+1 -1
View File
@@ -6,7 +6,7 @@
export class ShellFacade {
/** Observe camera ownership transfers through the navigation owner. */
subscribeCameraHandoff(listener) {
return this._navigation.subscribeCameraHandoff(listener);
return this._navigation?.subscribeCameraHandoff(listener);
}
get _models3dEnabled() {
+33
View File
@@ -0,0 +1,33 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { ShellFacade } from './shellFacade.js';
// A shell assembled without its navigation owner (as unit tests build one
// from the prototype) has no handoffs to report, like the facade's other
// optional owners; the voice runner subscribes as it is created.
test('camera handoffs without a navigation owner subscribe to nothing', () => {
const shell = Object.create(ShellFacade.prototype);
assert.equal(
shell.subscribeCameraHandoff(() => {}),
undefined,
);
});
test('camera handoffs reach listeners through the navigation owner', () => {
const listeners = new Set();
const shell = Object.create(ShellFacade.prototype);
shell._navigation = {
subscribeCameraHandoff(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
},
};
let handoffs = 0;
const unsubscribe = shell.subscribeCameraHandoff(() => {
handoffs += 1;
});
for (const listener of listeners) listener();
assert.equal(handoffs, 1);
unsubscribe();
assert.equal(listeners.size, 0);
});
+8 -1
View File
@@ -716,6 +716,11 @@
.data-icon::before {
content: '⌁';
}
:root[data-ui-theme='cyber']
.data-toggle-row[data-layer-id='wildlife-sightings']
.data-icon::before {
content: '✿';
}
:root[data-ui-theme='cyber']
.data-toggle-row[data-layer-id='radio']
.data-icon::before {
@@ -1693,7 +1698,9 @@
:root[data-ui-theme='cyber']
body:not(.cockpit-mode)
#left-panel-stack:has(> [data-panel-id]:not(.collapsed))
> :is(#data-panel, #cctv-panel, #utilities-panel, #scene-panel):not(.collapsed) {
> :is(#data-panel, #cctv-panel, #utilities-panel, #scene-panel):not(
.collapsed
) {
flex: 1 1 auto;
height: auto;
max-height: none;
@@ -0,0 +1,132 @@
<script setup>
import { computed, shallowRef, useTemplateRef, watch } from 'vue';
import { formatDate, t, translateKnown } from '../../../i18n/index.js';
import { photoCreator, formatAge } from '../../../layers/wildlifeSightings/photoText.js';
import { ACARTIA_SITE, inatLicenceLabel, inatPhotoUrl, isOpenPhoto } from '../../../layers/wildlifeSightings/records.js';
const props = defineProps({
sighting: { type: Object, required: true },
nowMs: { type: Number, required: true },
taxa: { type: String, default: 'all' },
});
const emit = defineEmits(['close', 'resize']);
const acartia = computed(() => props.sighting.origin === 'acartia');
const name = computed(() => translateKnown(props.sighting.commonName || props.sighting.scientificName) || t('SIGHTING'));
const scientificName = computed(() => translateKnown(props.sighting.scientificName || ''));
const photo = computed(() => {
const row = props.sighting;
if (row.obscured || acartia.value || !isOpenPhoto(row.photo)) return null;
const src = inatPhotoUrl(row.photo.square ?? row.photo.url, 'medium');
const creator = photoCreator(row.photo);
return src && creator ? { src, creator, licence: inatLicenceLabel(row.photo.license_code ?? row.photo.licence) } : null;
});
const observedDay = computed(() => {
const row = props.sighting;
const day = row.observedOn || (!row.obscured && Number.isFinite(row.observedAt) ? new Date(row.observedAt).toISOString().slice(0, 10) : '');
if (!/^\d{4}-\d{2}-\d{2}$/.test(day)) return '';
const date = new Date(`${day}T00:00:00Z`);
return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === day ? day : '';
});
const age = computed(() => {
const row = props.sighting;
const delta = props.nowMs - row.observedAt;
if (row.obscured || !Number.isFinite(row.observedAt) || delta >= 30 * 86_400_000) return '';
const compact = formatAge(Math.max(0, delta));
return acartia.value ? t('seen {age} ago', { age: compact }) : t('observed {age} ago', { age: compact });
});
const observedDate = computed(() => observedDay.value ? formatDate(Date.parse(`${observedDay.value}T00:00:00Z`), { year: 'numeric', month: 'short', day: 'numeric', timeZone: 'UTC' }) : '');
const link = computed(() => {
// The "Acartia" label only ever points at the Acartia site, never a row URL.
if (acartia.value) return ACARTIA_SITE;
try {
const url = new URL(props.sighting.link);
return url.protocol === 'https:' && !url.username && !url.password ? url.href : null;
} catch { return null; }
});
const providerCredit = computed(() => {
if (!acartia.value) return '';
const { name = '', entity = '' } = props.sighting.provider || {};
return entity ? t('Reported by {name} ({entity})', { name, entity }) : t('Reported by {name}', { name });
});
const actionLabel = computed(() => acartia.value ? t('Open {name} on Acartia', { name: name.value }) : t('Open {name} on iNaturalist', { name: name.value }));
const photoImage = useTemplateRef('photoImage');
const loaded = shallowRef(false);
const failed = shallowRef(false);
const currentImage = (image) => image === photoImage.value && image?.dataset.sightingId === props.sighting.stableId && image?.getAttribute('src') === photo.value?.src;
async function onPhotoLoad(event) {
const image = event.currentTarget;
// Ignore late decodes after a different observation replaces this photo.
try { await image.decode?.(); } catch { /* onload is sufficient on older engines */ }
if (!currentImage(image)) return;
loaded.value = true;
emit('resize');
}
function fail(event) {
if (!currentImage(event.currentTarget)) return;
failed.value = true;
emit('resize');
}
watch([() => props.sighting.stableId, () => photo.value?.src], () => { loaded.value = false; failed.value = false; }, { flush: 'sync' });
</script>
<template>
<section class="wildlife-sighting-card" data-wildlife-sighting-card tabindex="-1" :aria-label="name" @keydown.stop @keyup.stop>
<button type="button" class="wildlife-sighting-card-close" :aria-label="t('Close sighting')" @click="emit('close')">×</button>
<component :is="link ? 'a' : 'div'" class="wildlife-sighting-card-content" :href="link || undefined" :target="link ? '_blank' : undefined" :rel="link ? 'noopener noreferrer' : undefined" :aria-label="link ? actionLabel : undefined">
<div v-if="photo" class="wildlife-sighting-card-photo" :aria-busy="!loaded && !failed">
<p v-if="!loaded && !failed" role="status">{{ t('Loading photo...') }}</p>
<p v-if="failed" role="status">{{ t('Photo unavailable') }}</p>
<img v-show="!failed" ref="photoImage" :key="sighting.stableId + photo.src" :data-sighting-id="sighting.stableId" :src="photo.src" :alt="t('Photo of {name}', { name })" referrerpolicy="no-referrer" :class="{ loaded }" @load="onPhotoLoad" @error="fail" />
</div>
<div class="wildlife-sighting-card-caption">
<h2>{{ name }}</h2>
<p v-if="scientificName && scientificName !== name"><i>{{ scientificName }}</i></p>
<p v-if="age || observedDay"><time :datetime="observedDay || undefined">{{ age || observedDate }}</time></p>
<p v-if="sighting.obscured">{{ t('Location obscured to a 0.2° cell') }}</p>
<!-- i18n-ignore: creator and licence are provider attribution, copied verbatim -->
<p v-if="photo" class="wildlife-sighting-card-credit">© {{ photo.creator }} · {{ photo.licence }}</p>
<p v-if="providerCredit" class="wildlife-sighting-card-credit">{{ providerCredit }}</p>
<p v-if="acartia" class="wildlife-sighting-card-credit">{{ t('Acartia') }} · {{ t('CC BY 4.0') }} · {{ t('Salish Sea') }}</p>
<p v-if="link" class="wildlife-sighting-card-source">{{ acartia ? t('Acartia') : t('iNaturalist') }} ↗</p>
</div>
</component>
<p v-if="acartia || taxa === 'whales'" class="wildlife-sighting-card-guidance">
<a href="https://www.bewhalewise.org" target="_blank" rel="noopener noreferrer">{{ t('Be Whale Wise') }}</a>
</p>
</section>
</template>
<style scoped>
.wildlife-sighting-card {
position: relative;
box-sizing: border-box;
width: 100%;
max-height: inherit;
overflow: auto;
padding: 8px;
border: 1px solid var(--glass-border-hover);
border-radius: var(--btn-radius);
background: var(--menu-bg);
color: var(--text-primary);
font: 11px/1.4 var(--font-mono);
box-shadow: 0 3px 16px rgb(0 0 0 / 30%);
}
.wildlife-sighting-card-content { display: block; color: inherit; text-decoration: none; }
.wildlife-sighting-card-content:focus-visible { outline: 2px solid var(--text-primary); outline-offset: 3px; }
/* Script focus starts inside the card; tab focus still outlines its controls. */
.wildlife-sighting-card:focus-visible { outline: none !important; }
.wildlife-sighting-card-close { position: absolute; z-index: 1; inset-block-start: 4px; inset-inline-end: 4px; width: 24px; height: 24px; padding: 0; border: 0; border-radius: var(--btn-radius); background: transparent; color: inherit; font: 20px/1 var(--font-sans); cursor: pointer; }
.wildlife-sighting-card-close:hover { background: var(--menu-bg); }
.wildlife-sighting-card-close:focus-visible { outline: 2px solid var(--text-primary); outline-offset: 2px; }
.wildlife-sighting-card-photo { position: relative; width: 100%; height: 180px; }
.wildlife-sighting-card-photo > p { position: absolute; inset: 0; display: grid; place-items: center; margin: 0; }
.wildlife-sighting-card-photo > img { display: block; width: 100%; height: 100%; object-fit: contain; opacity: 0; }
.wildlife-sighting-card-photo > img.loaded { opacity: 1; }
.wildlife-sighting-card-caption { padding-top: 6px; overflow-wrap: anywhere; }
.wildlife-sighting-card-caption h2, .wildlife-sighting-card-caption p { margin: 0 0 3px; }
.wildlife-sighting-card-caption h2 { padding-inline-end: 20px; font: inherit; font-weight: 700; }
.wildlife-sighting-card-credit { color: var(--text-secondary); }
.wildlife-sighting-card-guidance { display: flex; flex-wrap: wrap; gap: 4px 12px; margin: 4px 0 0; color: var(--text-secondary); }
.wildlife-sighting-card-guidance a { color: inherit; }
.wildlife-sighting-card-source { text-decoration: underline; text-underline-offset: 2px; }
</style>
+270
View File
@@ -0,0 +1,270 @@
import { h, nextTick, shallowRef } from 'vue';
import WildlifeSightingCard from './views/panels/WildlifeSightingCard.vue';
import {
panWildlifeSighting,
placeWildlifeSightingCard,
projectWildlifeSighting,
readWildlifeCardSafeArea,
WILDLIFE_SELECTED_CARD_WIDTH,
WILDLIFE_CARD_CHROME_SELECTORS,
} from './wildlifeSightingPlacement.js';
/** Anchor the selected sighting's photo and source link clear of map chrome. */
export function createWildlifeSightingCard({
layer,
ui,
viewer = null,
documentRef = globalThis.document,
windowRef = globalThis.window,
now = () => Date.now(),
project = projectWildlifeSighting,
pan = panWildlifeSighting,
}) {
const selected = shallowRef(null);
const host = documentRef.createElement('div');
host.dataset.wildlifeSightingCardHost = '';
Object.assign(host.style, {
position: 'fixed',
zIndex: '89',
display: 'none',
width: `${WILDLIFE_SELECTED_CARD_WIDTH}px`,
});
documentRef.body.append(host);
let destroyed = false;
let moving = false;
let removeFrame = null;
let returnFocus = null;
let panForId = null;
const removers = [];
const observed = new Set();
const resizeObserver = windowRef?.ResizeObserver
? new windowRef.ResizeObserver(() => position())
: null;
const mutationObserver = windowRef?.MutationObserver
? new windowRef.MutationObserver(() => position())
: null;
const chromeSelector = WILDLIFE_CARD_CHROME_SELECTORS.join(',');
const structureObserver = windowRef?.MutationObserver
? new windowRef.MutationObserver((records) => {
if (destroyed || !selected.value) return;
const hasChromeChange = records.some((record) =>
[...record.addedNodes, ...record.removedNodes].some(
(node) =>
node.nodeType === 1 &&
!host.contains(node) &&
(node.matches(chromeSelector) ||
node.querySelector(chromeSelector)),
),
);
if (!hasChromeChange) return;
// Newly mounted chrome can cover a previously clear anchor.
panForId = null;
position({ allowPan: true });
})
: null;
function observeLayout(elements) {
const next = new Set(
[host.firstElementChild, viewer?.scene?.canvas, ...elements].filter(
Boolean,
),
);
let changed = false;
for (const element of observed) {
if (next.has(element)) continue;
resizeObserver?.unobserve(element);
observed.delete(element);
changed = true;
}
for (const element of next) {
if (observed.has(element)) continue;
observed.add(element);
resizeObserver?.observe(element);
changed = true;
}
if (!changed) return;
mutationObserver?.disconnect();
for (const element of observed) {
// Ignore HUD clock/text changes and the card's own positioning styles.
if (!host.contains(element))
mutationObserver?.observe(element, {
attributes: true,
attributeFilter: ['class', 'style', 'hidden'],
});
}
}
function position({ allowPan = false } = {}) {
if (destroyed || !selected.value || !host.firstElementChild) return;
const point = project(viewer, selected.value, layer);
if (!point || !Number.isFinite(point.x) || !Number.isFinite(point.y)) {
host.style.display = 'none';
return;
}
const safe = readWildlifeCardSafeArea({ documentRef, viewer, windowRef });
observeLayout(safe.elements);
host.style.width = `${Math.min(WILDLIFE_SELECTED_CARD_WIDTH, safe.bounds.width)}px`;
host.style.maxHeight = `${safe.bounds.height}px`;
host.style.display = 'block';
const rect = host.firstElementChild.getBoundingClientRect();
const result = placeWildlifeSightingCard(
point,
{
width:
rect.width ||
Math.min(WILDLIFE_SELECTED_CARD_WIDTH, safe.bounds.width),
height:
rect.height ||
(selected.value.photo &&
!selected.value.obscured &&
selected.value.origin !== 'acartia'
? 300
: 132),
},
safe,
);
if (!result) {
host.style.display = 'none';
return;
}
if (
(result.pan.x || result.pan.y) &&
allowPan &&
panForId !== selected.value.stableId
) {
panForId = selected.value.stableId;
const reduced =
windowRef?.matchMedia?.('(prefers-reduced-motion: reduce)').matches ===
true;
pan(viewer, point, result.anchor, reduced);
}
host.style.left = `${result.left}px`;
host.style.top = `${result.top}px`;
host.dataset.placement = result.placement;
}
const unmount = ui.mount(
{
setup: () => () =>
selected.value
? h(WildlifeSightingCard, {
sighting: selected.value,
nowMs: now(),
taxa: layer.getParams?.()?.taxa,
onClose: () => {
if (!destroyed) layer.clearSightingSelection();
},
onResize: () => position(),
})
: null,
},
host,
);
function restoreFocus() {
if (returnFocus?.isConnected) returnFocus.focus?.({ preventScroll: true });
returnFocus = null;
}
const unsubscribe = layer.subscribeSelection((row, metadata) => {
if (destroyed) return;
const fresh = row?.stableId !== selected.value?.stableId;
if (row && !selected.value) {
returnFocus = documentRef.activeElement;
structureObserver?.observe(documentRef.body, {
childList: true,
subtree: true,
});
}
selected.value = row;
if (!row) {
host.style.display = 'none';
panForId = null;
removeFrame?.();
removeFrame = null;
resizeObserver?.disconnect();
mutationObserver?.disconnect();
structureObserver?.disconnect();
observed.clear();
restoreFocus();
return;
}
if (fresh) panForId = null;
nextTick(() => {
if (destroyed || !selected.value) return;
position({ allowPan: fresh || metadata?.explicitSelection === true });
if (moving) startFrameUpdates();
// Focus the container so keyboard navigation starts inside the card.
if (fresh)
host
.querySelector('[data-wildlife-sighting-card]')
?.focus?.({ preventScroll: true });
});
});
const keydown = (event) => {
if (!selected.value || event.key !== 'Escape') return;
event.preventDefault();
event.stopImmediatePropagation();
layer.clearSightingSelection();
};
const outside = (event) => {
if (!selected.value || host.contains(event.target)) return;
// The layer selects on pointer-up; its following click must keep the card open.
const canvas = viewer?.scene?.canvas;
if (canvas && (event.target === canvas || canvas.contains?.(event.target)))
return;
layer.clearSightingSelection();
};
documentRef.addEventListener('keydown', keydown, true);
documentRef.addEventListener('click', outside, true);
const onResize = () => position();
windowRef?.addEventListener('resize', onResize);
function listen(event, callback) {
const remove = event?.addEventListener?.(callback);
if (typeof remove === 'function') removers.push(remove);
else if (event?.removeEventListener)
removers.push(() => event.removeEventListener(callback));
}
function startFrameUpdates() {
if (!selected.value || removeFrame) return;
// Installed only for camera motion; an idle card has zero per-frame work.
removeFrame =
viewer?.scene?.preRender?.addEventListener?.(() => position()) || null;
}
listen(viewer?.camera?.moveStart, () => {
moving = true;
startFrameUpdates();
});
listen(viewer?.camera?.moveEnd, () => {
moving = false;
removeFrame?.();
removeFrame = null;
position();
});
listen(viewer?.camera?.changed, () => {
if (!moving) position();
});
return {
/** Release the card, selection subscription and placement listeners. */
destroy() {
if (destroyed) return;
destroyed = true;
unsubscribe?.();
for (const remove of removers) remove();
removeFrame?.();
resizeObserver?.disconnect();
mutationObserver?.disconnect();
structureObserver?.disconnect();
documentRef.removeEventListener('keydown', keydown, true);
documentRef.removeEventListener('click', outside, true);
windowRef?.removeEventListener('resize', onResize);
unmount();
host.remove();
selected.value = null;
restoreFocus();
},
};
}
+797
View File
@@ -0,0 +1,797 @@
import '../testSupport/registerDom.mjs';
import assert from 'node:assert/strict';
import test from 'node:test';
import * as Cesium from 'cesium';
import { nextTick } from 'vue';
import { readFileSync } from 'node:fs';
import { getLocale, setLocale, t } from '../i18n/index.js';
import { LOCALES } from '../i18n/locale.js';
import { createSelection } from '../layers/wildlifeSightings/selection.js';
import { buildWildlifeThumbnailEntry } from '../layers/wildlifeSightings/cards.js';
import { createWildlifeSightingCard } from './wildlifeSightingCard.js';
import {
panWildlifeSighting,
placeWildlifeSightingCard,
readWildlifeCardSafeArea,
} from './wildlifeSightingPlacement.js';
import { createUiRuntime } from './vueRuntime.js';
import { PANEL_RAIL_ITEMS } from './panelRailCatalog.js';
import { sheetForPanelId } from './mobileShell.js';
const NOW = Date.parse('2026-11-04T13:00:00Z');
const square =
'https://inaturalist-open-data.s3.amazonaws.com/photos/456/square.jpg';
const row = {
stableId: 'inat:456',
origin: 'inaturalist',
lat: 0,
lon: 0,
commonName: 'Synthetic bird',
scientificName: 'Avis imaginaria',
iconic: 'Aves',
observedAt: NOW - 3_600_000,
observedOn: '2026-11-04',
obscured: false,
photo: {
square,
attribution: '(c) Synthetic Photographer, some rights reserved (CC BY-SA)',
licence: 'cc-by-sa',
},
link: 'https://www.inaturalist.org/observations/456',
};
const rect = (left, top, width, height) => ({
left,
top,
width,
height,
right: left + width,
bottom: top + height,
});
const events = () => {
const listeners = new Set();
return {
addEventListener(fn) {
listeners.add(fn);
return () => listeners.delete(fn);
},
emit() {
for (const fn of listeners) fn();
},
size: () => listeners.size,
};
};
const settle = async () => {
await nextTick();
await Promise.resolve();
await nextTick();
};
// All scene rows, media events and rectangles are synthetic. Browser image
// requests are disabled; decode resolution below proves the photo is exposed
// only after it has loaded into the compact card.
function fixture(
context,
initialRow = row,
point = { x: 600, y: 450 },
extraWindow = {},
) {
document.body.replaceChildren();
const opener = document.body.appendChild(document.createElement('button'));
opener.textContent = 'Globe';
opener.focus();
const canvas = document.body.appendChild(document.createElement('canvas'));
canvas.getBoundingClientRect = () => rect(0, 0, 1200, 900);
const windowRef = {
innerWidth: 1200,
innerHeight: 900,
getComputedStyle: window.getComputedStyle.bind(window),
addEventListener() {},
removeEventListener() {},
matchMedia: () => ({ matches: false }),
...extraWindow,
};
const ui = createUiRuntime();
const overlays = new Map();
const moveStart = events();
const moveEnd = events();
const changed = events();
const preRender = events();
const viewer = {
scene: { canvas, preRender, pick: () => picked },
camera: { moveStart, moveEnd, changed },
};
const state = {
enabled: true,
destroyed: false,
selectedId: null,
selectedRow: null,
ambientRows: [],
rowById: new Map([[initialRow.stableId, initialRow]]),
positions: new Map([[initialRow.stableId, { x: 1, y: 2, z: 3 }]]),
contextIds: new Set(),
viewer,
};
let picked = null;
let hit = null;
let onClick;
let clears = 0;
let staleListener;
const subscriptions = new Set();
const flights = [];
const pans = [];
const selection = createSelection({
state,
services: {
now: () => NOW,
cesium: { ScreenSpaceEventType: { LEFT_CLICK: 0 } },
overlayHost: {
setEntries: (id, entries) => overlays.set(id, entries),
hitTest: (_x, _y, { sourceId }) =>
hit?.sourceId === sourceId ? hit : null,
},
screenSpaceEventHandlerFactory: () => ({
setInputAction(fn) {
onClick = fn;
},
destroy() {},
}),
focus: { requestWorldFocus: (value) => flights.push(value) },
},
parts: {
rendering: { refreshSelection() {}, requestRender() {} },
},
});
const layer = {
getParams: () => ({ taxa: 'all' }),
subscribeSelection(listener) {
staleListener = listener;
subscriptions.add(listener);
const off = selection.subscribe(listener);
return () => {
subscriptions.delete(listener);
off();
};
},
clearSightingSelection() {
clears++;
selection.clearAndRebuild();
},
};
let currentPoint = point;
let projections = 0;
const card = createWildlifeSightingCard({
layer,
ui,
viewer,
documentRef: document,
windowRef,
now: () => NOW,
project: () => {
projections++;
return currentPoint;
},
pan: (_viewer, from, to, reduced) => {
pans.push({ from, to, reduced });
currentPoint = to;
return true;
},
});
selection.install();
context.after(() => {
card.destroy();
selection.destroy();
ui.destroy();
});
return {
state,
selection,
layer,
card,
viewer,
windowRef,
overlays,
flights,
pans,
projections: () => projections,
subscriptions,
opener,
canvas,
moveStart,
moveEnd,
preRender,
cardElement: () => document.querySelector('[data-wildlife-sighting-card]'),
host: () => document.querySelector('[data-wildlife-sighting-card-host]'),
staleListener: () => staleListener,
clears: () => clears,
async click(kind = 'dot', target = initialRow) {
picked =
kind === 'icon'
? { primitive: { id: `wildlife:${target.stableId}` } }
: { id: `wildlife:${target.stableId}` };
hit =
kind === 'ambient photo card'
? {
sourceId: 'wildlife-sightings',
entry: buildWildlifeThumbnailEntry(target, NOW, {
select: selection.selectAndFocus,
}),
}
: null;
onClick({ position: { x: 50, y: 50 } });
await settle();
},
async publish(next) {
if (next) {
state.rowById.set(next.stableId, next);
if (state.selectedId === next.stableId) state.selectedRow = next;
}
selection.notify();
await settle();
},
obstacle(selector, bounds) {
const element = document.body.appendChild(document.createElement('div'));
if (selector.startsWith('#')) element.id = selector.slice(1);
else element.className = selector.slice(1);
element.getBoundingClientRect = () => bounds;
return element;
},
setPoint(next) {
currentPoint = next;
},
};
}
test('dot, icon and ambient photo clicks open one contained medium-photo card at the sighting', async (context) => {
for (const kind of ['dot', 'icon', 'ambient photo card'])
await context.test(kind, async (context) => {
const f = fixture(context);
await f.click(kind);
const card = f.cardElement();
const image = card.querySelector('img');
assert.equal(f.state.selectedId, row.stableId);
assert.equal(
document.querySelector('dialog'),
null,
'there is no fullscreen or modal dialog',
);
assert.equal(image.src, square.replace('/square.', '/medium.'));
assert.equal(image.referrerPolicy, 'no-referrer');
assert.equal(card.querySelector('h2').textContent, row.commonName);
assert.equal(card.querySelector('i').textContent, row.scientificName);
assert.equal(card.querySelector('time').textContent, 'observed 1h ago');
assert.ok(
card.textContent.includes('© Synthetic Photographer · CC BY-SA'),
);
const link = card.querySelector('a');
assert.equal(link.href, row.link);
assert.equal(link.target, '_blank');
assert.equal(link.rel, 'noopener noreferrer');
assert.equal(
link.getAttribute('aria-label'),
`Open ${row.commonName} on iNaturalist`,
);
assert.equal(
link.querySelector('.wildlife-sighting-card-source').textContent,
'iNaturalist ↗',
);
assert.ok(
link.contains(image),
'the photograph and text are one external action',
);
assert.equal(f.flights.length, 1);
assert.equal(f.flights[0].kind, 'sighting');
assert.deepEqual(
f.flights[0].position,
f.state.positions.get(row.stableId),
);
assert.equal(f.pans.length, 0);
assert.equal(
f.preRender.size(),
0,
'an idle card installs no frame work',
);
let decoded;
image.decode = () =>
new Promise((resolve) => {
decoded = resolve;
});
image.dispatchEvent(new Event('load'));
await settle();
assert.equal(
image.classList.contains('loaded'),
false,
'a request alone does not expose an empty frame',
);
decoded();
await settle();
assert.equal(
image.classList.contains('loaded'),
true,
'the loaded medium photo is painted inside the card',
);
assert.equal(card.querySelector('[role=status]'), null);
const style = readFileSync(
new URL('./views/panels/WildlifeSightingCard.vue', import.meta.url),
'utf8',
);
assert.match(style, /object-fit: contain/);
assert.match(style, /height: 180px/);
});
});
test('missing, restricted, obscured and Acartia photos all use the same compact text card', async (context) => {
for (const [label, extra] of [
['missing', { photo: null }],
['restricted', { photo: { ...row.photo, licence: 'cc-by-nd' } }],
[
'untrusted',
{ photo: { ...row.photo, square: 'https://other.example/square.jpg' } },
],
['uncredited', { photo: { ...row.photo, attribution: '' } }],
['obscured', { obscured: true }],
[
'Acartia',
{
origin: 'acartia',
stableId: 'acartia:456',
provider: { name: 'Synthetic network' },
link: 'https://acartia.io',
},
],
])
await context.test(label, async (context) => {
const f = fixture(context, { ...row, ...extra });
await f.click();
const card = f.cardElement();
assert.equal(card.querySelector('img'), null);
assert.equal(card.querySelector('[role=status]'), null);
assert.equal(card.querySelector('h2').textContent, row.commonName);
assert.equal(card.querySelector('i').textContent, row.scientificName);
assert.equal(document.querySelector('dialog'), null);
if (extra.obscured) {
assert.doesNotMatch(card.textContent, /ago|Photographer/);
assert.ok(
card.textContent.includes('Location obscured to a 0.2° cell'),
);
assert.equal(
card.querySelector('time').getAttribute('datetime'),
row.observedOn,
);
}
if (extra.origin === 'acartia') {
assert.ok(card.textContent.includes('seen 1h ago'));
assert.ok(card.textContent.includes('Reported by Synthetic network'));
assert.ok(
card.textContent.includes('Acartia · CC BY 4.0 · Salish Sea'),
);
assert.ok(card.querySelector('a[href="https://www.bewhalewise.org"]'));
assert.equal(
card.querySelector('a').getAttribute('aria-label'),
`Open ${row.commonName} on Acartia`,
);
}
});
});
test('an Acartia card labels only the Acartia site as Acartia', async (context) => {
for (const link of [
'https://provider.example/photos/synthetic.jpg',
'https://acartia.io.attacker.example/',
'https://acartia.io/',
])
await context.test(link, async (context) => {
const f = fixture(context, {
...row,
origin: 'acartia',
stableId: 'acartia:456',
provider: { name: 'Synthetic network' },
link,
});
await f.click();
const card = f.cardElement();
const hrefs = [...card.querySelectorAll('a')].map((a) =>
a.getAttribute('href'),
);
assert.deepEqual(hrefs, [
'https://acartia.io/',
'https://www.bewhalewise.org',
]);
assert.equal(
card.querySelector('.wildlife-sighting-card-source').textContent,
'Acartia ↗',
);
});
});
test('safe placements near each viewport edge exclude actual HUD, toolbar and rail rects', () => {
const obstacles = [
rect(0, 0, 260, 160),
rect(450, 0, 300, 80),
rect(1050, 200, 150, 500),
rect(0, 760, 300, 140),
];
const safe = { bounds: rect(6, 6, 1188, 888), obstacles };
for (const point of [
{ x: 7, y: 450 },
{ x: 1193, y: 750 },
{ x: 850, y: 7 },
{ x: 600, y: 893 },
]) {
const result = placeWildlifeSightingCard(
point,
{ width: 258, height: 300 },
safe,
);
assert.ok(result);
assert.deepEqual(result.pan, { x: 0, y: 0 });
assert.ok(
result.left >= safe.bounds.left && result.right <= safe.bounds.right,
);
assert.ok(
result.top >= safe.bounds.top && result.bottom <= safe.bounds.bottom,
);
assert.ok(
obstacles.every(
(r) =>
!(
result.left < r.right &&
result.right > r.left &&
result.top < r.bottom &&
result.bottom > r.top
),
),
);
}
});
test('a selected dot flies to its true position and its card pans clear of chrome', async (context) => {
const f = fixture(context, row, { x: 100, y: 100 });
const hud = f.obstacle('.hud-top-left', rect(0, 0, 260, 160));
f.obstacle('#right-context-rail', rect(1040, 200, 160, 700));
f.windowRef.matchMedia = () => ({ matches: true });
await f.click();
assert.equal(f.pans.length, 1);
assert.equal(f.pans[0].reduced, true);
assert.deepEqual(
f.pans[0].to,
{ x: 100, y: 178 },
'nearest clear point follows the measured HUD bottom',
);
const safe = readWildlifeCardSafeArea({
documentRef: document,
viewer: f.viewer,
windowRef: f.windowRef,
});
assert.equal(
safe.obstacles[0].bottom,
hud.getBoundingClientRect().bottom + 6,
);
assert.equal(f.flights.length, 1);
assert.deepEqual(f.flights[0].position, f.state.positions.get(row.stableId));
f.moveEnd.emit();
await settle();
assert.equal(f.pans.length, 1);
f.layer.clearSightingSelection();
await settle();
f.setPoint({ x: -20, y: 400 });
await f.click();
assert.equal(f.pans.length, 2);
assert.deepEqual(f.pans[1].to, { x: 18, y: 400 });
});
test('the camera correction preserves altitude and orientation and honors reduced motion', () => {
const flights = [];
const camera = {
positionWC: Cesium.Cartesian3.fromDegrees(0, 0, 250_000),
positionCartographic: { height: 250_000 },
heading: 0.2,
pitch: -1.2,
roll: 0.1,
pickEllipsoid: (p) => Cesium.Cartesian3.fromDegrees(p.x / 100, p.y / 100),
flyTo: (value) => flights.push(value),
};
const viewer = {
camera,
scene: {
canvas: { getBoundingClientRect: () => rect(0, 0, 1200, 900) },
globe: { ellipsoid: Cesium.Ellipsoid.WGS84 },
},
};
for (const reduced of [false, true]) {
assert.equal(
panWildlifeSighting(viewer, { x: 10, y: 10 }, { x: 30, y: 50 }, reduced),
true,
);
const flight = flights.at(-1);
assert.ok(
Math.abs(
Cesium.Cartographic.fromCartesian(flight.destination).height - 250_000,
) < 0.001,
);
assert.deepEqual(flight.orientation, {
heading: 0.2,
pitch: -1.2,
roll: 0.1,
});
assert.equal(flight.duration, reduced ? 0 : 0.22);
}
});
test('the browser click that follows a globe selection does not close the card it opened', async (context) => {
const f = fixture(context);
await f.click();
assert.ok(f.cardElement(), 'the globe click opened the card');
assert.equal(
document.activeElement,
f.cardElement(),
'focus lands on the card, not as a ring on its close button',
);
// Cesium selects on pointer-up; the DOM click event lands on the canvas
// afterwards and must not count as an outside click.
f.canvas.dispatchEvent(new MouseEvent('click', { bubbles: true }));
await settle();
assert.ok(f.cardElement(), 'the card stays open');
assert.equal(f.clears(), 0);
document.body.click();
await settle();
assert.equal(f.cardElement(), null, 'a real outside click still closes it');
});
test('one card at a time, Escape, outside clicks and close all clear the selection', async (context) => {
const f = fixture(context);
await f.click();
const second = {
...row,
stableId: 'inat:789',
commonName: 'Another synthetic bird',
};
f.state.rowById.set(second.stableId, second);
await f.click('dot', second);
assert.equal(
document.querySelectorAll('[data-wildlife-sighting-card]').length,
1,
);
assert.equal(
f.cardElement().querySelector('h2').textContent,
second.commonName,
);
for (const close of ['Escape', 'outside', 'button']) {
if (close === 'Escape')
document.dispatchEvent(
new KeyboardEvent('keydown', {
key: 'Escape',
bubbles: true,
cancelable: true,
}),
);
if (close === 'outside') document.body.click();
if (close === 'button') f.cardElement().querySelector('button').click();
await settle();
assert.equal(f.cardElement(), null);
assert.equal(f.state.selectedId, null);
assert.deepEqual(f.overlays.get('wildlife-sightings-selected'), []);
assert.equal(document.activeElement, f.opener);
await f.click();
}
assert.equal(f.clears(), 3);
});
test('camera movement repositions the same card and removes frame work at rest', async (context) => {
const f = fixture(context);
await f.click();
const card = f.cardElement();
const before = f.host().style.left;
f.moveStart.emit();
assert.equal(f.preRender.size(), 1);
f.setPoint({ x: 800, y: 450 });
f.preRender.emit();
assert.equal(f.cardElement(), card);
assert.notEqual(f.host().style.left, before);
f.moveEnd.emit();
assert.equal(f.preRender.size(), 0);
await f.publish({ ...row, commonName: 'Updated synthetic bird' });
assert.equal(f.cardElement(), card);
assert.equal(card.querySelector('h2').textContent, 'Updated synthetic bird');
f.state.rowById.delete(row.stableId);
await f.publish(null);
assert.equal(
f.cardElement(),
card,
'a refreshed sample cannot close the selected card',
);
f.layer.clearSightingSelection();
await settle();
assert.equal(f.cardElement(), null);
});
test('replacement photo loads cannot expose the previous image and failures retain the text card', async (context) => {
const f = fixture(context);
await f.click();
const previous = f.cardElement().querySelector('img');
let decoded;
previous.decode = () =>
new Promise((resolve) => {
decoded = resolve;
});
previous.dispatchEvent(new Event('load'));
await f.publish({
...row,
photo: { ...row.photo, square: square.replace('/456/', '/789/') },
});
const current = f.cardElement().querySelector('img');
decoded();
await settle();
assert.equal(current.classList.contains('loaded'), false);
current.dispatchEvent(new Event('error'));
await settle();
assert.equal(
f.cardElement().querySelector('[role=status]').textContent,
'Photo unavailable',
);
assert.equal(current.style.display, 'none');
assert.equal(f.cardElement().querySelector('a').href, row.link);
});
test('teardown removes subscriptions, placement listeners and host, and ignores stale notifications', async (context) => {
const f = fixture(context);
await f.click();
f.moveStart.emit();
const stale = f.staleListener();
f.card.destroy();
assert.equal(f.cardElement(), null);
assert.equal(f.host(), null);
assert.equal(f.subscriptions.size, 0);
assert.equal(f.preRender.size(), 0);
stale(row);
await f.click();
assert.equal(f.cardElement(), null);
assert.equal(document.activeElement, f.opener);
});
test('locale changes translate the card without replacing the image or credit', async (context) => {
const before = getLocale();
context.after(() => setLocale(before));
const f = fixture(context);
await f.click();
const card = f.cardElement();
const image = card.querySelector('img');
for (const locale of LOCALES) {
setLocale(locale);
await settle();
assert.equal(f.cardElement(), card);
assert.equal(card.querySelector('img'), image);
assert.equal(
card.querySelector('button').getAttribute('aria-label'),
t('Close sighting'),
);
assert.ok(card.textContent.includes('© Synthetic Photographer · CC BY-SA'));
}
});
test('date-only and unsafe-link rows remain readable, and no sighting rail or lightbox is shipped', async (context) => {
const f = fixture(context, {
...row,
observedAt: null,
photo: null,
link: 'javascript:alert(1)',
});
await f.click();
assert.equal(f.cardElement().querySelector('a'), null);
assert.equal(
f.cardElement().querySelector('time').getAttribute('datetime'),
row.observedOn,
);
assert.equal(PANEL_RAIL_ITEMS['wildlife-sighting-panel'], undefined);
assert.equal(sheetForPanelId('wildlife-sighting-panel'), null);
const source = readFileSync(
new URL('./wildlifeSightingCard.js', import.meta.url),
'utf8',
);
assert.doesNotMatch(
source,
/Lightbox|showModal|requestAnimationFrame|setInterval/,
);
});
test('WHALES cards retain compact whale guidance outside the observation action', async (context) => {
const f = fixture(context);
f.layer.getParams = () => ({ taxa: 'whales' });
await f.click();
const guidance = f
.cardElement()
.querySelector('a[href="https://www.bewhalewise.org"]');
assert.equal(guidance.textContent, 'Be Whale Wise');
assert.equal(
guidance.parentElement.closest('a'),
null,
'the external guidance link never nests inside the observation action',
);
});
test('opening during camera motion tracks the card and closing stops frame work immediately', async (context) => {
const f = fixture(context);
f.moveStart.emit();
assert.equal(f.preRender.size(), 0);
await f.click();
assert.equal(f.preRender.size(), 1);
f.layer.clearSightingSelection();
await settle();
assert.equal(f.preRender.size(), 0);
});
test('newly mounted chrome repositions the open card without camera events or idle text work', async (context) => {
const observers = [];
class MutationObserver {
constructor(callback) {
this.callback = callback;
this.targets = [];
observers.push(this);
}
observe(target, options) {
this.targets.push({ target, options });
}
disconnect() {
this.targets = [];
}
}
const f = fixture(context, row, { x: 600, y: 450 }, { MutationObserver });
await f.click();
const structural = observers.find((observer) =>
observer.targets.some(
({ target, options }) =>
target === document.body && options.childList && options.subtree,
),
);
assert.ok(
structural,
'structural observation exists only while a card is open',
);
const original = f.cardElement();
const before = f.host().style.top;
const hudWrapper = document.body.appendChild(document.createElement('div'));
const hud = hudWrapper.appendChild(document.createElement('div'));
hud.className = 'hud-top-left';
hud.getBoundingClientRect = () => rect(500, 350, 200, 200);
structural.callback([{ addedNodes: [hudWrapper], removedNodes: [] }]);
await settle();
assert.equal(
f.pans.length,
1,
'chrome newly covering the dot triggers one minimal pan',
);
assert.equal(f.cardElement(), original);
assert.notEqual(f.host().style.top, before);
assert.equal(f.preRender.size(), 0);
const placed = rect(
Number.parseFloat(f.host().style.left),
Number.parseFloat(f.host().style.top),
258,
300,
);
assert.ok(
placed.right <= 494 ||
placed.left >= 706 ||
placed.bottom <= 344 ||
placed.top >= 556,
'the card clears the measured HUD rect',
);
const afterChrome = f.projections();
// The observer ignores text nodes, ordinary clock wrappers and the card's
// own image/caption patches even though body observation sees their records.
const clock = hud.appendChild(document.createElement('span'));
const text = clock.appendChild(document.createTextNode('13:00:01'));
structural.callback([
{
addedNodes: [clock, text, f.cardElement().querySelector('img')],
removedNodes: [],
},
]);
assert.equal(f.projections(), afterChrome);
f.layer.clearSightingSelection();
await settle();
assert.equal(
structural.targets.length,
0,
'closing disconnects structural observation',
);
});
+274
View File
@@ -0,0 +1,274 @@
import * as Cesium from 'cesium';
import { WORLD_OVERLAY_OCCLUDER_SELECTORS } from '../overlays/worldOverlayChrome.js';
// DOM cards also avoid the HUD edges and responsive sheet containers.
export const WILDLIFE_CARD_CHROME_SELECTORS = Object.freeze([
...WORLD_OVERLAY_OCCLUDER_SELECTORS,
'.hud-left-edge',
'.hud-right-edge',
'#right-panel-stack',
'.gev-panel-rail',
'#location-bar',
'#control-panel',
'#param-slider-panel',
'#cockpit-hud .cockpit-topline',
'[data-mobile-sheet]',
]);
const GAP = 12;
const EDGE = 6;
export const WILDLIFE_SELECTED_CARD_WIDTH = 258;
const overlaps = (a, b) =>
a.left < b.right && a.right > b.left && a.top < b.bottom && a.bottom > b.top;
const contains = (r, p) =>
p.x >= r.left && p.x <= r.right && p.y >= r.top && p.y <= r.bottom;
const clamp = (value, low, high) => Math.max(low, Math.min(high, value));
const rectAt = (left, top, width, height) => ({
left,
top,
right: left + width,
bottom: top + height,
width,
height,
});
/** Read visible chrome rectangles inside the viewer's usable screen area. */
export function readWildlifeCardSafeArea({
documentRef,
viewer,
windowRef = globalThis.window,
}) {
const canvasRect = viewer?.scene?.canvas?.getBoundingClientRect?.();
const width =
windowRef?.innerWidth || documentRef.documentElement.clientWidth;
const height =
windowRef?.innerHeight || documentRef.documentElement.clientHeight;
const left = Math.max(0, canvasRect?.left || 0) + EDGE;
const top = Math.max(0, canvasRect?.top || 0) + EDGE;
const right =
Math.min(width, canvasRect?.width > 0 ? canvasRect.right : width) - EDGE;
const bottom =
Math.min(height, canvasRect?.height > 0 ? canvasRect.bottom : height) -
EDGE;
const bounds = rectAt(
left,
top,
Math.max(0, right - left),
Math.max(0, bottom - top),
);
const obstacles = [];
const elements = [
...documentRef.querySelectorAll(WILDLIFE_CARD_CHROME_SELECTORS.join(',')),
];
for (const element of elements) {
let hidden = false;
for (
let node = element;
node && node !== documentRef.body;
node = node.parentElement
) {
const style = windowRef?.getComputedStyle?.(node);
if (
node.hidden ||
style?.display === 'none' ||
style?.visibility === 'hidden' ||
style?.opacity === '0'
) {
hidden = true;
break;
}
}
if (hidden) continue;
const rect = element.getBoundingClientRect();
if (!(rect.width > 0 && rect.height > 0) || !overlaps(rect, bounds))
continue;
obstacles.push(
rectAt(
rect.left - EDGE,
rect.top - EDGE,
rect.width + EDGE * 2,
rect.height + EDGE * 2,
),
);
}
return { bounds, obstacles, elements };
}
function nearestSafeAnchor(point, { bounds, obstacles }) {
const xs = [clamp(point.x, bounds.left + GAP, bounds.right - GAP)];
const ys = [clamp(point.y, bounds.top + GAP, bounds.bottom - GAP)];
for (const rect of obstacles) {
xs.push(
clamp(rect.left - GAP, bounds.left + GAP, bounds.right - GAP),
clamp(rect.right + GAP, bounds.left + GAP, bounds.right - GAP),
);
ys.push(
clamp(rect.top - GAP, bounds.top + GAP, bounds.bottom - GAP),
clamp(rect.bottom + GAP, bounds.top + GAP, bounds.bottom - GAP),
);
}
return (
xs
.flatMap((x) => ys.map((y) => ({ x, y })))
.filter(
(p) => contains(bounds, p) && !obstacles.some((r) => contains(r, p)),
)
.sort(
(a, b) =>
Math.hypot(a.x - point.x, a.y - point.y) -
Math.hypot(b.x - point.x, b.y - point.y),
)[0] || null
);
}
/** Four anchored placements, clamped along their free axis. Chrome is a set of
* actual DOM rectangles, so corner HUDs do not erase otherwise clear lanes. */
export function placeWildlifeSightingCard(point, size, safeArea) {
const { bounds, obstacles } = safeArea;
const anchor =
contains(bounds, point) && !obstacles.some((r) => contains(r, point))
? point
: nearestSafeAnchor(point, safeArea);
if (!anchor) return null;
const width = Math.min(size.width, bounds.width);
const height = Math.min(size.height, bounds.height);
const centeredX = clamp(
anchor.x - width / 2,
bounds.left,
bounds.right - width,
);
const centeredY = clamp(
anchor.y - height / 2,
bounds.top,
bounds.bottom - height,
);
const candidates = [
{
placement: 'above',
...rectAt(centeredX, anchor.y - GAP - height, width, height),
},
{ placement: 'below', ...rectAt(centeredX, anchor.y + GAP, width, height) },
{ placement: 'right', ...rectAt(anchor.x + GAP, centeredY, width, height) },
{
placement: 'left',
...rectAt(anchor.x - GAP - width, centeredY, width, height),
},
];
const fits = (rect) =>
rect.left >= bounds.left &&
rect.right <= bounds.right &&
rect.top >= bounds.top &&
rect.bottom <= bounds.bottom &&
!obstacles.some((r) => overlaps(rect, r));
let chosen = candidates.find(fits);
if (!chosen) {
// Crowded chrome may require sliding a side placement farther from its
// anchor. Search only obstacle/bounds edges; no pixels or idle frame loop.
const xs = [bounds.left, bounds.right - width, centeredX];
const ys = [bounds.top, bounds.bottom - height, centeredY];
for (const r of obstacles) {
xs.push(r.left - width, r.right);
ys.push(r.top - height, r.bottom);
}
const alternatives = xs
.flatMap((x) =>
ys.map((y) => ({
placement:
y + height <= anchor.y
? 'above'
: y >= anchor.y
? 'below'
: x >= anchor.x
? 'right'
: 'left',
...rectAt(x, y, width, height),
})),
)
.filter((r) => fits(r) && !contains(r, anchor));
alternatives.sort(
(a, b) =>
Math.hypot(
clamp(anchor.x, a.left, a.right) - anchor.x,
clamp(anchor.y, a.top, a.bottom) - anchor.y,
) -
Math.hypot(
clamp(anchor.x, b.left, b.right) - anchor.x,
clamp(anchor.y, b.top, b.bottom) - anchor.y,
),
);
chosen = alternatives[0];
}
return chosen
? {
...chosen,
anchor,
pan: { x: anchor.x - point.x, y: anchor.y - point.y },
}
: null;
}
/** Project a front-side sighting into viewport coordinates. */
export function projectWildlifeSighting(viewer, row, layer) {
if (
!viewer?.scene ||
!Number.isFinite(row?.lat) ||
!Number.isFinite(row?.lon)
)
return null;
const position =
layer?.getSightingPosition?.(row.stableId) ||
Cesium.Cartesian3.fromDegrees(row.lon, row.lat);
const ellipsoid = viewer.scene.globe?.ellipsoid || Cesium.Ellipsoid.WGS84;
if (
viewer.camera?.positionWC &&
new Cesium.EllipsoidalOccluder(
ellipsoid,
viewer.camera.positionWC,
).isPointVisible(position) !== true
)
return null;
const point = Cesium.SceneTransforms.worldToWindowCoordinates(
viewer.scene,
position,
);
if (!point) return null;
const rect = viewer.scene.canvas?.getBoundingClientRect?.();
return { x: point.x + (rect?.left || 0), y: point.y + (rect?.top || 0) };
}
/** Translate the camera by the smallest screen correction and preserve its
* altitude/orientation. A card must never zoom merely to reveal its anchor. */
export function panWildlifeSighting(viewer, from, to, reducedMotion = false) {
const camera = viewer?.camera;
if (!camera?.pickEllipsoid || !camera.flyTo) return false;
const rect = viewer.scene.canvas.getBoundingClientRect();
const local = (p) => new Cesium.Cartesian2(p.x - rect.left, p.y - rect.top);
const ellipsoid = viewer.scene.globe?.ellipsoid || Cesium.Ellipsoid.WGS84;
const start = camera.pickEllipsoid(local(from), ellipsoid);
const finish = camera.pickEllipsoid(local(to), ellipsoid);
if (!start || !finish || !camera.positionWC) return false;
const delta = Cesium.Cartesian3.subtract(
start,
finish,
new Cesium.Cartesian3(),
);
const destination = Cesium.Cartesian3.add(
camera.positionWC,
delta,
new Cesium.Cartesian3(),
);
const cartographic = ellipsoid.cartesianToCartographic(destination);
if (!cartographic) return false;
cartographic.height = camera.positionCartographic.height;
camera.flyTo({
destination: ellipsoid.cartographicToCartesian(cartographic),
orientation: {
heading: camera.heading,
pitch: camera.pitch,
roll: camera.roll,
},
duration: reducedMotion ? 0 : 0.22,
easingFunction: Cesium.EasingFunction.QUADRATIC_OUT,
});
return true;
}