mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 16:22:20 +00:00
Merge main through #1591 into the renderer seam
Brings in the wildlife sightings layer (#1591, iNaturalist and Acartia sightings). Its badges, density glow and privacy cells draw through the draw port: the badges and the glow are icons sets (iconCollection.js batches point writes into one upsert per task), and the privacy cells are ground-clamped shapes and lines sets swapped whole. The eye, the view rectangle, clicks, projection, ground readiness and frames come from the camera, query, input, globe and frame ports, so the layer, its card and its placement no longer import Cesium. Differences from main: the density glow is drawn as pixel-sized splats (56 px) instead of metre-sized ones with a near fade; the card's pan eases with cubicOut, the contract's nearest ease-out; ground heights are resampled when the globe's load progress settles or its surface changes, rather than on tileset load events. Also fixes two things the last merge left: a double-click that starts on the followed track and ends off it reaches the renderer's own follow again (a press that cannot end a double-click on the track gives its hold back at its release), and the Active Fires heat drapes under the weather imagery, so weather turned on after it stacks above. CURRENT-STATE notes that the 2D and Columbus scene-mode checks are gone.
This commit is contained in:
commit
020a433b51
129 files changed
+22143
-336
No files matched your search
@@ -19,6 +19,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';
|
||||
@@ -604,6 +605,7 @@ export class StyleManager extends ShellFacade {
|
||||
this._initRadioPanel();
|
||||
this._initCctvPanel();
|
||||
this._initStreetLevelPanel();
|
||||
this._initWildlifeSightingCard();
|
||||
this._initGlobalContextPanel();
|
||||
this._initLocationBar();
|
||||
this._initMobileShell();
|
||||
@@ -1088,6 +1090,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;
|
||||
@@ -1805,6 +1820,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();
|
||||
|
||||
@@ -5,21 +5,29 @@
|
||||
// Run with: npm test
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { fakeInput } from '../input/testDoubles.mjs';
|
||||
import {
|
||||
fakeInput,
|
||||
FakeScreenSpaceEventHandler,
|
||||
FAKE_EVENT_TYPES,
|
||||
} from '../input/testDoubles.mjs';
|
||||
import { bindRenderer } from '../render/rendererOf.js';
|
||||
import { createCesiumInput } from '../render/cesium/input.js';
|
||||
import { routeSceneDoubleClick, onSceneDoubleClick } from './cockpitInput.js';
|
||||
|
||||
function harness(t) {
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
function harness(t, { stock = null } = {}) {
|
||||
t.mock.timers.enable({ apis: ['setTimeout', 'Date'] });
|
||||
const viewer = {
|
||||
scene: {
|
||||
pick: () => null,
|
||||
},
|
||||
clock: { currentTime: 0 },
|
||||
};
|
||||
const input = fakeInput(viewer);
|
||||
// The followed aircraft is drawn at (100, 100).
|
||||
bindRenderer(viewer, { query: { project: () => ({ x: 100, y: 100 }) } });
|
||||
const project = () => ({ x: 100, y: 100 });
|
||||
// With `stock`, the renderer's own input port takes the viewer's stock
|
||||
// double-click follow and runs it as the app's does; else the fake input.
|
||||
const input = stock ? cesiumInput(viewer, stock, project) : fakeInput(viewer);
|
||||
if (!stock) bindRenderer(viewer, { query: { project } });
|
||||
const entity = {
|
||||
id: 'flights:abc',
|
||||
position: { getValue: () => ({ x: 1, y: 2, z: 3 }) },
|
||||
@@ -31,12 +39,17 @@ function harness(t) {
|
||||
destroyed: false,
|
||||
entered: 0,
|
||||
holds: 0,
|
||||
holdStockFollow() {
|
||||
this.holds += 1;
|
||||
return () => {
|
||||
this.holds -= 1;
|
||||
};
|
||||
},
|
||||
// Counted here, unless the test watches the renderer's own hold.
|
||||
...(stock
|
||||
? {}
|
||||
: {
|
||||
holdStockFollow() {
|
||||
this.holds += 1;
|
||||
return () => {
|
||||
this.holds -= 1;
|
||||
};
|
||||
},
|
||||
}),
|
||||
resolveEntryKind: () => 'aircraft',
|
||||
enter() {
|
||||
this.entered += 1;
|
||||
@@ -53,6 +66,44 @@ function harness(t) {
|
||||
return { input, controller, stop };
|
||||
}
|
||||
|
||||
/** The Cesium renderer's input port over a fake handler, with `follow` as
|
||||
* the viewer's stock double-click follow. */
|
||||
function cesiumInput(viewer, follow, project) {
|
||||
const stock = new FakeScreenSpaceEventHandler();
|
||||
stock.setInputAction(follow, FAKE_EVENT_TYPES.LEFT_DOUBLE_CLICK);
|
||||
viewer.screenSpaceEventHandler = stock;
|
||||
viewer.scene.canvas = {
|
||||
addEventListener() {},
|
||||
removeEventListener() {},
|
||||
};
|
||||
const handler = new FakeScreenSpaceEventHandler();
|
||||
const query = { project, pick: () => null, drillPick: () => [] };
|
||||
const made = createCesiumInput(viewer, {
|
||||
query,
|
||||
createHandler: () => handler,
|
||||
report: (error) => {
|
||||
throw error;
|
||||
},
|
||||
document: null,
|
||||
});
|
||||
bindRenderer(viewer, { input: made.port, query });
|
||||
const T = FAKE_EVENT_TYPES;
|
||||
const fire = (type) => (position) => handler.fire(type, { position });
|
||||
return {
|
||||
down: fire(T.LEFT_DOWN),
|
||||
up: fire(T.LEFT_UP),
|
||||
click: fire(T.LEFT_CLICK),
|
||||
tap(position) {
|
||||
handler.fire(T.LEFT_DOWN, { position });
|
||||
handler.fire(T.LEFT_UP, { position });
|
||||
handler.fire(T.LEFT_CLICK, { position });
|
||||
},
|
||||
dblclick: fire(T.LEFT_DOUBLE_CLICK),
|
||||
stockEnabled: (name) => made.port.behaviours[name].enabled,
|
||||
destroy: () => made.dispose(),
|
||||
};
|
||||
}
|
||||
|
||||
const doubleClick = (input, position) => {
|
||||
input.tap(position);
|
||||
input.down(position);
|
||||
@@ -88,15 +139,74 @@ test("a double-click elsewhere is the renderer's own", (t) => {
|
||||
assert.equal(controller.holds, 0);
|
||||
});
|
||||
|
||||
test('a single press on the track gives the stock follow back by itself', (t) => {
|
||||
test('a single press on the track gives the stock follow back at its release, or by itself', (t) => {
|
||||
const { input, controller } = harness(t);
|
||||
input.tap({ x: 100, y: 100 });
|
||||
assert.equal(controller.holds, 0, 'given back at the release');
|
||||
t.mock.timers.tick(700);
|
||||
input.down({ x: 100, y: 100 });
|
||||
assert.equal(controller.holds, 1);
|
||||
t.mock.timers.tick(700);
|
||||
assert.equal(controller.holds, 0);
|
||||
assert.equal(controller.holds, 0, 'a press never released lets go');
|
||||
assert.equal(controller.entered, 0);
|
||||
});
|
||||
|
||||
test("a double-click that starts on the track and ends off it is the renderer's own", (t) => {
|
||||
const follows = [];
|
||||
const { input, controller } = harness(t, {
|
||||
stock: (event) => follows.push(event.position),
|
||||
});
|
||||
const on = { x: 120, y: 100 };
|
||||
const off = { x: 140, y: 100 };
|
||||
// As Cesium raises them: each press clicks, then the double-click.
|
||||
input.tap(on);
|
||||
input.tap(off);
|
||||
input.dblclick(off);
|
||||
assert.equal(controller.entered, 0);
|
||||
assert.equal(follows.length, 1, 'the stock follow ran');
|
||||
assert.equal(input.stockEnabled('dblclickFollow'), true);
|
||||
});
|
||||
|
||||
test('a press elsewhere just before cannot make a press on the track keep its hold', (t) => {
|
||||
const follows = [];
|
||||
const { input, controller } = harness(t, {
|
||||
stock: (event) => follows.push(event.position),
|
||||
});
|
||||
input.tap({ x: 500, y: 500 });
|
||||
input.tap({ x: 120, y: 100 });
|
||||
input.tap({ x: 140, y: 100 });
|
||||
input.dblclick({ x: 140, y: 100 });
|
||||
assert.equal(controller.entered, 0);
|
||||
assert.equal(follows.length, 1, 'the stock follow ran');
|
||||
});
|
||||
|
||||
test('a press on the track long after the last keeps no hold past its release', (t) => {
|
||||
const { input, controller } = harness(t);
|
||||
const on = { x: 100, y: 100 };
|
||||
input.tap(on);
|
||||
t.mock.timers.tick(701);
|
||||
input.down(on);
|
||||
input.up(on);
|
||||
assert.equal(controller.holds, 0, 'it cannot end a double-click');
|
||||
input.down(on);
|
||||
input.up(on);
|
||||
assert.equal(controller.holds, 1, 'a quick second press keeps it');
|
||||
});
|
||||
|
||||
test('a double-click that ends on the track holds the stock follow off', (t) => {
|
||||
const follows = [];
|
||||
const { input, controller } = harness(t, {
|
||||
stock: (event) => follows.push(event.position),
|
||||
});
|
||||
const on = { x: 110, y: 95 };
|
||||
input.tap({ x: 140, y: 100 });
|
||||
input.tap(on);
|
||||
input.dblclick(on);
|
||||
assert.equal(controller.entered, 1);
|
||||
assert.deepEqual(follows, [], 'the stock follow did not run');
|
||||
assert.equal(input.stockEnabled('dblclickFollow'), true, 'given back');
|
||||
});
|
||||
|
||||
test('an active Cockpit leaves presses alone, and stopping lets a hold go', (t) => {
|
||||
const { input, controller, stop } = harness(t);
|
||||
controller.active = true;
|
||||
|
||||
+36
-5
@@ -62,9 +62,15 @@ export function onSceneDoubleClick(position) {
|
||||
const holdStockFollow = (viewer) =>
|
||||
findInput(viewer)?.behaviours?.dblclickFollow?.suppress?.() ?? null;
|
||||
|
||||
/** How long a press on the followed track keeps the stock follow off. */
|
||||
/**
|
||||
* How long a press on the followed track keeps the stock follow off, and
|
||||
* how soon after a press the next one may end a double-click with it.
|
||||
*/
|
||||
const SUBJECT_PRESS_HOLD_MS = 700;
|
||||
|
||||
/** How far apart, CSS pixels, two presses of one double-click may land. */
|
||||
const DOUBLE_CLICK_SLOP_PX = 8;
|
||||
|
||||
/**
|
||||
* Take the scene's double-click on the followed track for the Cockpit. The
|
||||
* renderer's own double-click follow lets go of whatever is followed when
|
||||
@@ -74,7 +80,12 @@ const SUBJECT_PRESS_HOLD_MS = 700;
|
||||
* one, so a press on the followed track holds it off for that press
|
||||
* (`behaviours.dblclickFollow`, a hold a `down` subscriber takes covers its
|
||||
* press), and the double-click it ends in enters. A double-click anywhere
|
||||
* else is the renderer's, as before. `this.holdStockFollow`, when set, takes
|
||||
* else is the renderer's, as before. The renderer decides a double-click's
|
||||
* stock follow from its second press, as the hold stood when that press
|
||||
* went down, so a press that cannot end a double-click on the track (no
|
||||
* press on the track came just before it, at about the same spot) gives
|
||||
* its hold back at its release: a second press off the track then finds
|
||||
* the follow free. `this.holdStockFollow`, when set, takes
|
||||
* the hold in place of the renderer's input port (tests).
|
||||
* @returns {() => void} Stops listening and lets any hold go.
|
||||
*/
|
||||
@@ -89,29 +100,49 @@ export function routeSceneDoubleClick() {
|
||||
}
|
||||
let release = null;
|
||||
let timer = null;
|
||||
// The last left press (when, where, and whether it was on the track),
|
||||
// and whether the held press could end a double-click on the track.
|
||||
let last = null;
|
||||
let endsDouble = false;
|
||||
const drop = () => {
|
||||
globalThis.clearTimeout(timer);
|
||||
timer = null;
|
||||
release?.();
|
||||
release = null;
|
||||
};
|
||||
// Ambient `down`/`up` are the unmodified left button's, while the
|
||||
// pointer is free.
|
||||
const offDown = input.onPointer('down', ({ position }) => {
|
||||
drop();
|
||||
if (this.active || this.destroyed || !isPointerFree()) return;
|
||||
if (!doubleClickHitsSubject(position, subjectCanvasPosition.call(this)))
|
||||
return;
|
||||
const at = Date.now();
|
||||
const onSubject =
|
||||
!this.active &&
|
||||
!this.destroyed &&
|
||||
isPointerFree() &&
|
||||
doubleClickHitsSubject(position, subjectCanvasPosition.call(this));
|
||||
endsDouble =
|
||||
!!last?.onSubject &&
|
||||
at - last.at <= SUBJECT_PRESS_HOLD_MS &&
|
||||
Math.hypot(position?.x - last.x, position?.y - last.y) <=
|
||||
DOUBLE_CLICK_SLOP_PX;
|
||||
last = { at, x: position?.x, y: position?.y, onSubject };
|
||||
if (!onSubject) return;
|
||||
release = this.holdStockFollow
|
||||
? this.holdStockFollow()
|
||||
: holdStockFollow(this.viewer);
|
||||
// A press that ends in no double-click gives the follow back by itself.
|
||||
timer = globalThis.setTimeout(drop, SUBJECT_PRESS_HOLD_MS);
|
||||
});
|
||||
const offUp = input.onPointer('up', () => {
|
||||
if (!endsDouble) drop();
|
||||
});
|
||||
const offDouble = input.onPointer('dblclick', ({ position }) => {
|
||||
this.onSceneDoubleClick(position);
|
||||
drop();
|
||||
});
|
||||
return () => {
|
||||
offDown();
|
||||
offUp();
|
||||
offDouble();
|
||||
drop();
|
||||
};
|
||||
|
||||
@@ -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'),
|
||||
wind: msg('Wind'),
|
||||
'weather-radar': msg('Rain radar'),
|
||||
|
||||
@@ -80,6 +80,10 @@ const PANEL_GROUPS = [
|
||||
's2-ghostmaps',
|
||||
],
|
||||
},
|
||||
{
|
||||
label: msg('Wildlife'),
|
||||
ids: ['wildlife-sightings'],
|
||||
},
|
||||
{
|
||||
label: msg('Weather'),
|
||||
ids: [
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -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>
|
||||
@@ -0,0 +1,267 @@
|
||||
import { h, nextTick, shallowRef } from 'vue';
|
||||
import { canvasOf, findCamera, findFrame } from '../render/rendererOf.js';
|
||||
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, canvasOf(viewer), ...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 = canvasOf(viewer);
|
||||
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(camera, event, callback) {
|
||||
const remove = camera?.on(event, callback);
|
||||
if (typeof remove === 'function') removers.push(remove);
|
||||
}
|
||||
function startFrameUpdates() {
|
||||
if (!selected.value || removeFrame) return;
|
||||
// Installed only for camera motion; an idle card has zero per-frame work.
|
||||
removeFrame = findFrame(viewer)?.on('preRender', () => position()) || null;
|
||||
}
|
||||
const camera = viewer ? findCamera(viewer) : null;
|
||||
listen(camera, 'moveStart', () => {
|
||||
moving = true;
|
||||
startFrameUpdates();
|
||||
});
|
||||
listen(camera, 'moveEnd', () => {
|
||||
moving = false;
|
||||
removeFrame?.();
|
||||
removeFrame = null;
|
||||
position();
|
||||
});
|
||||
listen(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();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,793 @@
|
||||
import '../testSupport/registerDom.mjs';
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js';
|
||||
import { bindWildlifeViewer } from '../testSupport/wildlifeViewer.mjs';
|
||||
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 },
|
||||
camera: { moveStart, moveEnd, changed },
|
||||
};
|
||||
bindWildlifeViewer(viewer);
|
||||
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;
|
||||
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,
|
||||
overlayHost: {
|
||||
setEntries: (id, entries) => overlays.set(id, entries),
|
||||
hitTest: (_x, _y, { sourceId }) =>
|
||||
hit?.sourceId === sourceId ? hit : null,
|
||||
},
|
||||
input: () => ({
|
||||
onClick(fn) {
|
||||
onClick = fn;
|
||||
return () => (onClick = null);
|
||||
},
|
||||
}),
|
||||
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) {
|
||||
// Dots and icons alike are picked by their item id.
|
||||
picked = `wildlife:${target.stableId}`;
|
||||
hit =
|
||||
kind === 'ambient photo card'
|
||||
? {
|
||||
sourceId: 'wildlife-sightings',
|
||||
entry: buildWildlifeThumbnailEntry(target, NOW, {
|
||||
select: selection.selectAndFocus,
|
||||
}),
|
||||
}
|
||||
: null;
|
||||
onClick({ screenPosition: { x: 50, y: 50 }, id: picked });
|
||||
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: fromDegrees(0, 0, 250_000),
|
||||
positionCartographic: { height: 250_000 },
|
||||
heading: 0.2,
|
||||
pitch: -1.2,
|
||||
roll: 0.1,
|
||||
flyTo: (value) => flights.push(value),
|
||||
};
|
||||
const viewer = {
|
||||
camera,
|
||||
scene: {
|
||||
canvas: { getBoundingClientRect: () => rect(0, 0, 1200, 900) },
|
||||
},
|
||||
};
|
||||
bindWildlifeViewer(viewer, {
|
||||
query: { pickEllipsoid: (x, y) => fromDegrees(x / 100, y / 100) },
|
||||
});
|
||||
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(toLonLatH(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',
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,263 @@
|
||||
import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js';
|
||||
import { horizonFrom } from '../geo/horizon.js';
|
||||
import { add, sub } from '../geo/vector.js';
|
||||
import { canvasOf, findCamera, findQuery } from '../render/rendererOf.js';
|
||||
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 = canvasOf(viewer)?.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) {
|
||||
const camera = viewer ? findCamera(viewer) : null;
|
||||
const query = viewer ? findQuery(viewer) : null;
|
||||
if (
|
||||
!camera ||
|
||||
!query ||
|
||||
!Number.isFinite(row?.lat) ||
|
||||
!Number.isFinite(row?.lon)
|
||||
)
|
||||
return null;
|
||||
const position =
|
||||
layer?.getSightingPosition?.(row.stableId) || fromDegrees(row.lon, row.lat);
|
||||
if (horizonFrom(camera.pose().position).isPointVisible(position) !== true)
|
||||
return null;
|
||||
const point = query.project(position);
|
||||
if (!point) return null;
|
||||
const rect = canvasOf(viewer)?.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 ? findCamera(viewer) : null;
|
||||
const query = viewer ? findQuery(viewer) : null;
|
||||
const canvas = canvasOf(viewer);
|
||||
if (!camera || !query || !canvas) return false;
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
const pick = (p) => query.pickEllipsoid(p.x - rect.left, p.y - rect.top);
|
||||
const start = pick(from);
|
||||
const finish = pick(to);
|
||||
if (!start || !finish) return false;
|
||||
const pose = camera.pose();
|
||||
const destination = toLonLatH(add(pose.position, sub(start, finish)));
|
||||
if (!destination) return false;
|
||||
camera.flyTo(
|
||||
{ lon: destination.lon, lat: destination.lat, height: pose.height },
|
||||
{
|
||||
orientation: {
|
||||
heading: pose.heading,
|
||||
pitch: pose.pitch,
|
||||
roll: pose.roll,
|
||||
},
|
||||
durationS: reducedMotion ? 0 : 0.22,
|
||||
// The contract's nearest ease-out to a quadratic one.
|
||||
easing: 'cubicOut',
|
||||
},
|
||||
);
|
||||
return true;
|
||||
}
|
||||
Reference in new issue
Block a user