Rebuild the Context panel around the selected item and the view

Clicking anything a layer can identify opens one card in Context: a hero
tile (route globe and 3D model for a flight, the camera for CCTV, headline
figures otherwise), its facts, actions with Cockpit or the orbital view as
the primary one, and a standard set of nearby blocks (weather and local
time, flights, vessels, hazards, alerts) within one radius the user sets.
Aircraft show altitude as a graph. Things that move are followed when
picked, and a card closes when its layer is turned off.

With nothing selected the panel describes the view: the layers that are on
with a breakdown of what each holds, the camera's height, what is in view,
then time, weather and local news. From far out it shows worldwide counts
per layer. A search field in the header narrows whatever the panel shows.

Prototype. Context reads weather and hazard feeds while its panel is closed,
the two 3D previews on a flight card repaint continuously, Follow can show
pressed after tracking has ended elsewhere, and most new strings are fixed
English. Same-named sites are told apart by position, not by a stable id.
This commit is contained in:
Manjunath Paparaju authored and Sameh Khamis committed 2026-11-16 14:58:53 -08:00
1 parent f7f18c2823
commit cc83763452
21 files changed
+6595 -1

No files matched your search

+116
View File
@@ -0,0 +1,116 @@
<script setup>
import { computed, ref, watch } from 'vue';
import { t } from '../../../i18n/index.js';
// A height as a filled graph (an aircraft's altitude, the camera's height):
// each reading since it opened, left to right. The scale fits the readings (never less than about
// 2,000 ft tall), so a climb or descent shows as a slope, and the fill
// fades from the line down to the baseline.
const props = defineProps({
/** The current altitude in metres, or null when unknown. */
altitudeM: { type: Number, default: null },
/** Bumped on each card refresh; a reading is taken on every bump. */
tick: { type: Number, default: 0 },
/** The caption; 'Altitude' when not given. */
label: { type: String, default: '' },
/** 'feet' for aircraft; 'metric' reads in metres and kilometres. */
unit: { type: String, default: 'feet' },
/** Only the caption, the current figure and the line: no scale or change. */
compact: { type: Boolean, default: false },
});
const MAX_READINGS = 450;
const MIN_RANGE_M = 600;
const WIDTH = 100;
const HEIGHT = 36;
const readings = ref([]);
watch(
() => props.tick,
() => {
if (!Number.isFinite(props.altitudeM)) return;
const next = [...readings.value, { at: Date.now(), m: Math.max(0, props.altitudeM) }];
readings.value = next.length > MAX_READINGS ? next.slice(-MAX_READINGS) : next;
},
{ immediate: true },
);
const feet = (m) => Math.round((m * 3.28084) / 100) * 100;
const number = (value) => value.toLocaleString('en-US');
const metric = (m) =>
m >= 100_000 ? `${number(Math.round(m / 1000))} km` : m >= 1000 ? `${(m / 1000).toFixed(1)} km` : `${number(Math.round(m))} m`;
const shown = (m) => (props.unit === 'metric' ? metric(m) : `${number(feet(m))} ft`);
const graph = computed(() => {
const list = readings.value;
if (!list.length) return null;
const last = list[list.length - 1];
const first = list[0];
const span = Math.max(1, last.at - first.at);
// The camera ranges from metres to the whole globe, so its heights are
// drawn on a log scale: each zoom step is a similar rise or fall.
const log = props.unit === 'metric';
const scaled = (m) => (log ? Math.log10(Math.max(1, m)) : m);
const heights = list.map((item) => scaled(item.m));
const high = Math.max(...heights);
const low = Math.min(...heights);
// The least the scale spans: about 2,000 ft for aircraft, half a decade
// for the camera.
const least = log ? 0.5 : MIN_RANGE_M;
const pad = Math.max((least - (high - low)) / 2, (high - low) * 0.15);
const bottom = Math.max(0, low - pad);
const top = Math.max(high + pad, bottom + least);
const x = (at) => WIDTH - ((last.at - at) / span) * WIDTH;
const y = (m) => HEIGHT - ((scaled(m) - bottom) / (top - bottom)) * (HEIGHT - 2) - 1;
// The readings span the full width; a single reading (a card that has
// just opened) draws as a level line instead of a dot.
const points = list.length > 1 ? list.map((item) => [x(item.at), y(item.m)]) : [[0, y(first.m)], [WIDTH, y(first.m)]];
const line = points.map(([px, py], index) => `${index ? 'L' : 'M'}${px.toFixed(2)} ${py.toFixed(2)}`).join(' ');
const moved = last.m - first.m;
const change = props.unit === 'metric' ? (Math.abs(moved) >= Math.max(1, last.m * 0.005) ? moved : 0) : feet(last.m) - feet(first.m);
const changeText = props.unit === 'metric' ? metric(Math.abs(moved)) : `${number(Math.abs(change))} ft`;
const minutes = Math.floor((last.at - first.at) / 60_000);
return {
line,
area: `${line} L${WIDTH} ${HEIGHT} L0 ${HEIGHT} Z`,
headY: y(last.m),
now: shown(last.m),
top: shown(log ? 10 ** top : top),
bottom: shown(log ? 10 ** bottom : bottom),
trend: change > 0 ? 'up' : change < 0 ? 'down' : 'level',
change: change ? `${change > 0 ? '+' : '−'}${changeText}` : t('Level'),
since: minutes >= 1 ? t('Last {n} min', { n: minutes }) : props.unit === 'metric' ? t('Just now') : t('Since selected'),
};
});
</script>
<template>
<figure v-if="graph" class="altitude-graph" :class="{ 'altitude-graph--compact': compact }" :data-trend="graph.trend">
<figcaption class="altitude-graph__head">
<span class="altitude-graph__label">{{ label || t('Altitude') }}</span>
<strong class="altitude-graph__now">{{ graph.now }}</strong>
</figcaption>
<div class="altitude-graph__plot">
<svg :viewBox="`0 0 ${WIDTH} ${HEIGHT}`" preserveAspectRatio="none" role="img" :aria-label="`${label || t('Altitude')} ${graph.now}, ${graph.change}`">
<defs>
<linearGradient id="altitude-graph-fill" gradientUnits="userSpaceOnUse" x1="0" :y1="0" x2="0" :y2="HEIGHT">
<stop offset="0" class="altitude-graph__stop altitude-graph__stop--high" />
<stop offset="0.5" class="altitude-graph__stop altitude-graph__stop--mid" />
<stop offset="1" class="altitude-graph__stop altitude-graph__stop--low" />
</linearGradient>
</defs>
<path class="altitude-graph__area" :d="graph.area" fill="url(#altitude-graph-fill)" />
<path class="altitude-graph__line" :d="graph.line" />
</svg>
<span class="altitude-graph__head-dot" :style="{ top: `${(graph.headY / HEIGHT) * 100}%` }" aria-hidden="true"></span>
<template v-if="!compact">
<span class="altitude-graph__scale" aria-hidden="true">{{ graph.top }}</span>
<span class="altitude-graph__scale altitude-graph__scale--low" aria-hidden="true">{{ graph.bottom }}</span>
</template>
</div>
<p v-if="!compact" class="altitude-graph__foot">
<span>{{ graph.since }}</span>
<span class="altitude-graph__change">{{ graph.change }}</span>
</p>
</figure>
</template>
+100
View File
@@ -0,0 +1,100 @@
<script setup>
import { computed, onBeforeUnmount, ref, watch } from 'vue';
import { storeToRefs } from 'pinia';
import { t } from '../../../i18n/index.js';
import { useCctvStore } from '../../stores/cctv.js';
import { usePanelChromeStore } from '../../stores/panelChrome.js';
// A selected camera's card: a thumbnail of its latest frame, a few facts,
// and a button that opens the full CCTV panel. The frame and facts come from
// the CCTV panel's own store, which follows the camera picked on the map.
const props = defineProps({
/** The camera's id (the card identity's id). */
cameraId: { type: String, default: '' },
});
const { view, frame, sourceBadge } = storeToRefs(useCctvStore());
const chrome = usePanelChromeStore();
const { panels } = storeToRefs(chrome);
const same = computed(() => !props.cameraId || frame.value?.cameraId === props.cameraId);
const src = computed(() => (same.value ? frame.value?.src || frame.value?.currentSrc || '' : ''));
const params = computed(() => {
try {
return new URL(src.value, location.origin).searchParams;
} catch {
return new URLSearchParams();
}
});
const name = computed(() => params.value.get('label') || '');
// The panel's meta line, e.g. "US-290 · HDG 248° · FOV 44° · RANGE 145m · … · TxDOT · …".
const facts = computed(() => {
const parts = String(view.value?.meta || '')
.split(' · ')
.map((p) => p.trim())
.filter(Boolean);
const pick = (re) => parts.find((p) => re.test(p))?.replace(/^(HDG|FOV|RANGE)\s*/, '') || '';
return [
{ label: t('Heading'), value: pick(/^HDG/) },
{ label: t('Field of view'), value: pick(/^FOV/) },
{ label: t('Range'), value: pick(/^RANGE/) },
{ label: t('Operator'), value: parts.find((p) => /DOT|Transportation|Works|City|County/i.test(p)) || '' },
].filter((f) => f.value);
});
// The bigger view: a popup over the map with the same frame, closed by its
// ×, Esc or a click outside.
const big = ref(false);
const onKey = (e) => {
if (e.key === 'Escape') big.value = false;
};
watch(big, (open) => {
if (open) document.addEventListener('keydown', onKey);
else document.removeEventListener('keydown', onKey);
});
onBeforeUnmount(() => document.removeEventListener('keydown', onKey));
function openPanel() {
if (panels.value['cctv-panel']?.collapsed !== false) chrome.act('toggle', 'cctv-panel');
}
</script>
<template>
<section class="cctv-preview">
<div class="cctv-preview__frame" :class="{ 'is-empty': !src }">
<img v-if="src" :src="src" :alt="name || t('Camera frame')" />
<span v-else>{{ t('Acquiring frame…') }}</span>
<span v-if="sourceBadge?.label" class="cctv-preview__badge">{{ sourceBadge.label }}</span>
<button v-if="src" type="button" class="cctv-preview__expand" :aria-label="t('Show a bigger view')" :title="t('Show a bigger view')" @click="big = true">
<span class="material-symbols-outlined" aria-hidden="true">open_in_full</span>
</button>
</div>
<Teleport to="body">
<div v-if="big" class="cctv-popup" role="dialog" :aria-label="name || t('Camera view')" @click.self="big = false">
<figure class="cctv-popup__card">
<header class="cctv-popup__head">
<span class="material-symbols-outlined" aria-hidden="true">videocam</span>
<strong>{{ name || t('Camera view') }}</strong>
<span v-if="sourceBadge?.label" class="cctv-popup__badge">{{ sourceBadge.label }}</span>
<button type="button" class="cctv-popup__close" :aria-label="t('Close')" @click="big = false">
<span class="material-symbols-outlined" aria-hidden="true">close</span>
</button>
</header>
<img :src="src" :alt="name || t('Camera frame')" />
<figcaption v-if="facts.length">
<span v-for="fact in facts" :key="fact.label">{{ fact.label }} <b>{{ fact.value }}</b></span>
</figcaption>
</figure>
</div>
</Teleport>
<dl v-if="facts.length" class="cctv-preview__facts">
<div v-for="fact in facts" :key="fact.label">
<dt>{{ fact.label }}</dt>
<dd>{{ fact.value }}</dd>
</div>
</dl>
<button type="button" class="entity-card__action cctv-preview__more" @click="openPanel">
<span class="material-symbols-outlined" aria-hidden="true">videocam</span>{{ t('More info') }}
</button>
</section>
</template>
+326
View File
@@ -0,0 +1,326 @@
<script setup>
import { computed, nextTick, ref, watch } from 'vue';
import { storeToRefs } from 'pinia';
import { t } from '../../../i18n/index.js';
import { useEntityCardStore } from '../../stores/entityCard.js';
import AltitudeGraph from './AltitudeGraph.vue';
import { contextNeedle, contextSearchText, matchesContextSearch } from '../../contextSearch.js';
import CctvPreview from './CctvPreview.vue';
import { useCctvStore } from '../../stores/cctv.js';
import SpotConditions from './SpotConditions.vue';
import { countryName, nearestCity } from '../../../data/wikidataCities.js';
// The Context panel's card for one thing on the map: what it is, its facts,
// links, actions, and what else is near it. It reads from the entity card
// store, which the globe click, the omnibar and the nearby list all fill.
const store = useEntityCardStore();
const { card, lost, tick } = storeToRefs(store);
// Cameras carry only an id; the CCTV panel's store knows the picked one's name.
const { frame: cctvFrame } = storeToRefs(useCctvStore());
const shownTitle = computed(() => {
const current = card.value;
if (current?.layerId !== 'cctv') return current?.title;
const f = cctvFrame.value;
if (!f || f.cameraId !== current.identity?.id) return current.title;
try {
return new URL(f.src || f.currentSrc, location.origin).searchParams.get('label') || current.title;
} catch {
return current.title;
}
});
function ago(ms) {
const seconds = Math.round(ms / 1000);
if (seconds < 60) return t('{n} s ago', { n: seconds });
const minutes = Math.round(seconds / 60);
if (minutes < 60) return t('{n} min ago', { n: minutes });
const hours = Math.round(minutes / 60);
if (hours < 48) return t('{n} h ago', { n: hours });
return t('{n} d ago', { n: Math.round(hours / 24) });
}
const status = computed(() => {
void tick.value;
const current = card.value;
if (!current) return null;
if (lost.value) return { tone: 'lost', text: t('Out of feed · last reading') };
if (current.observedAgeMs !== null)
return {
tone: current.moving && current.observedAgeMs < 120_000 ? 'live' : 'aged',
text: current.moving
? t('Live · {age}', { age: ago(current.observedAgeMs) })
: ago(current.observedAgeMs),
};
if (current.moving) return { tone: 'live', text: t('Live') };
return null;
});
const position = computed(() => {
const current = card.value;
if (!Number.isFinite(current?.lat) || !Number.isFinite(current?.lon)) return '';
const lat = `${Math.abs(current.lat).toFixed(3)}°${current.lat >= 0 ? 'N' : 'S'}`;
const lon = `${Math.abs(current.lon).toFixed(3)}°${current.lon >= 0 ? 'E' : 'W'}`;
return `${lat} ${lon}`;
});
const distance = (km) =>
km < 1 ? t('{n} m', { n: Math.round(km * 1000) }) : t('{n} km', { n: km < 10 ? km.toFixed(1) : Math.round(km) });
const source = computed(() => {
void tick.value;
return store.sourceOf(card.value);
});
const ageText = computed(() => {
void tick.value;
const age = card.value?.observedAgeMs;
return Number.isFinite(age) ? t('updated {age}', { age: ago(age) }) : '';
});
// The headline figures, as big tiles: the fields the item's kind leads with
// (how high, how fast and which way for an aircraft; a quake's magnitude and
// depth; a fire's power), in that order. The rest stay in the grid. An
// aircraft's altitude is left out: its graph already leads with the figure.
const altitudeGraphed = computed(() => card.value?.kind === 'aircraft' && Number.isFinite(card.value?.altitudeM));
const tiles = computed(() => {
const facts = card.value?.facts || [];
return (card.value?.headline || [])
.filter((field) => !(altitudeGraphed.value && field === 'altitudeM'))
.map((field) => facts.find((fact) => fact.field === field))
.filter(Boolean)
.slice(0, 3);
});
const restFacts = computed(() => {
const shown = new Set(tiles.value.map((fact) => fact.field));
if (altitudeGraphed.value) shown.add('altitudeM');
return (card.value?.facts || []).filter((fact) => !shown.has(fact.field));
});
// A figure split into its number and unit, so the number can lead.
function splitValue(value) {
const match = String(value).match(/^([-−+]?[\d.,]+|M [\d.]+)\s*(.*)$/);
return match ? { number: match[1], unit: match[2] } : { number: String(value), unit: '' };
}
// The line under the name: who runs it and what it is. The layer is already
// named on the line above the title.
const subtitle = computed(() => {
const current = card.value;
if (!current) return '';
const cls = current.aircraftClass;
return [current.operator, cls && cls[0].toUpperCase() + cls.slice(1)].filter(Boolean).join(' · ');
});
// The details grid leaves out what the header already says.
// The Context search narrows them to the ones whose name or value holds its
// text, and looks through every fact, the headline ones included.
const gridFacts = computed(() =>
contextNeedle.value
? (card.value?.facts || []).filter((fact) => matchesContextSearch(t(fact.label), fact.value))
: restFacts.value.filter((fact) => !(card.value?.operator && fact.field === 'operator') && !(card.value?.aircraftClass && fact.field === 'aircraftClass')),
);
// How far along its route the flight is, when both airports are known: the
// share flown (distance from the origin over that plus the distance still to
// go), what is left, and the time to go at its current speed.
const routeProgress = computed(() => {
const current = card.value;
const route = current?.route;
if (!route?.verified || !route.fromAt || !route.toAt) return null;
if (!Number.isFinite(current.lat) || !Number.isFinite(current.lon)) return null;
const km = (a, b) => {
const rad = Math.PI / 180;
const h =
Math.sin(((b.lat - a.lat) * rad) / 2) ** 2 +
Math.cos(a.lat * rad) * Math.cos(b.lat * rad) * Math.sin(((b.lon - a.lon) * rad) / 2) ** 2;
return 12742 * Math.asin(Math.sqrt(h));
};
const here = { lat: current.lat, lon: current.lon };
const flown = km(route.fromAt, here);
const left = km(here, route.toAt);
const share = flown + left > 0 ? flown / (flown + left) : 0;
const speedKmh = Number.isFinite(current.speedMps) ? current.speedMps * 3.6 : null;
const hours = speedKmh && speedKmh > 80 ? left / speedKmh : null;
const eta =
hours === null ? null : hours >= 1 ? `${Math.floor(hours)} h ${Math.round((hours % 1) * 60)} min` : `${Math.max(1, Math.round(hours * 60))} min`;
return {
share: Math.min(1, Math.max(0, share)),
flown: distance(flown),
left: distance(left),
eta,
};
});
// Each airport's city and state (or country), from its position, for the line
// under the progress bar.
const routePlaces = ref({ from: '', to: '' });
async function airportPlace(airport) {
if (!airport) return '';
try {
const found = await nearestCity(airport.lat, airport.lon);
const city = airport.name || found?.name || '';
const region = countryName(found?.country);
return [city, region].filter(Boolean).join(', ');
} catch {
return airport.name || '';
}
}
watch(
() => `${card.value?.route?.fromAt?.code}|${card.value?.route?.toAt?.code}`,
async () => {
const route = card.value?.route;
routePlaces.value = { from: route?.fromAt?.name || '', to: route?.toAt?.name || '' };
if (!route?.fromAt || !route?.toAt) return;
const [from, to] = await Promise.all([airportPlace(route.fromAt), airportPlace(route.toAt)]);
if (card.value?.route?.fromAt?.code === route.fromAt.code) routePlaces.value = { from, to };
},
{ immediate: true },
);
// The hero tile at the top of every card. A camera shows its latest frame.
// Anything else gets a quiet placeholder with its icon and its headline
// figures until it has imagery of its own.
const heroKind = computed(() => (card.value?.layerId === 'cctv' ? 'camera' : 'none'));
// Things that move are read again only after they have gone a fair way, so
// following a jet does not ask for the weather every few seconds.
const settleKm = computed(() => (card.value?.moving ? 25 : 1));
const kindLabel = computed(() => (card.value ? t(card.value.kind) : ''));
// What it is, then the layer it came from, unless the layer's name already
// says what it is ("fire perimeter · Fire Perimeters").
const kindLine = computed(() => {
const current = card.value;
if (!current) return '';
const layer = current.layerName || '';
const plain = (words) => words.toLowerCase().replace(/s\b/g, '');
return plain(layer).includes(plain(current.kind)) ? layer : `${kindLabel.value} · ${layer}`;
});
// A new item starts at the top of the panel, not wherever the last one was
// scrolled to.
watch(
() => card.value?.key,
async (key, previous) => {
if (!key || key === previous) return;
await nextTick();
document
.getElementById('entity-card')
?.closest('[data-rail-scroller]')
?.scrollTo({ top: 0, behavior: 'smooth' });
},
);
</script>
<template>
<Transition name="entity-card">
<section v-if="card" id="entity-card" class="entity-card" :aria-label="t('Selected on the map')" :data-layer="card.layerId">
<div class="entity-hero" :data-hero="heroKind">
<CctvPreview v-if="heroKind === 'camera'" :camera-id="card.identity?.id || ''" />
<!-- No imagery for it yet: its icon, with its headline figures beside it. -->
<div v-else class="entity-hero__placeholder" :class="{ 'entity-hero__placeholder--bare': !tiles.length }">
<span class="material-symbols-outlined entity-hero__glyph" aria-hidden="true">{{ card.icon }}</span>
<div v-if="tiles.length" class="entity-hero__figures">
<div v-for="fact in tiles" :key="fact.field" class="entity-hero__figure">
<strong>{{ splitValue(fact.value).number }}<small v-if="splitValue(fact.value).unit">{{ splitValue(fact.value).unit }}</small></strong>
<span>{{ t(fact.label) }}</span>
</div>
</div>
<span v-else class="entity-hero__kind">{{ kindLabel }}</span>
</div>
</div>
<header class="entity-card__head">
<span class="material-symbols-outlined entity-card__icon" aria-hidden="true">{{ card.icon }}</span>
<div class="entity-card__name">
<span class="entity-card__kind">{{ kindLine }}</span>
<h3 class="entity-card__title">{{ shownTitle }}</h3>
<span v-if="subtitle" class="entity-card__subtitle">{{ subtitle }}</span>
</div>
<button type="button" class="entity-card__close" :aria-label="t('Close card')" :title="t('Close card')" @click="store.clear()">
<span class="material-symbols-outlined" aria-hidden="true">close</span>
</button>
</header>
<div class="entity-card__meta">
<span v-if="status" class="entity-card__status" :class="`entity-card__status--${status.tone}`">{{ status.text }}</span>
<span v-if="position" class="entity-card__where">{{ position }}</span>
</div>
<div v-if="card.warnings?.length" class="entity-card__warning" role="alert">
<span class="material-symbols-outlined" aria-hidden="true">warning</span>
<span>{{ card.warnings.join(' · ') }}</span>
</div>
<div v-if="card.route" class="entity-card__route" :class="{ 'entity-card__route--unverified': !card.route.verified, 'entity-card__route--progress': routeProgress }">
<strong>{{ card.route.from }}</strong>
<span class="entity-card__route-line" :style="routeProgress ? { '--route-share': `${(routeProgress.share * 100).toFixed(1)}%` } : null" aria-hidden="true">
<span class="material-symbols-outlined">flight</span>
</span>
<strong>{{ card.route.to }}</strong>
</div>
<p v-if="routeProgress" class="entity-card__route-stats">
<span>{{ t('{n}% flown', { n: Math.round(routeProgress.share * 100) }) }} · {{ routeProgress.flown }}</span>
<span>{{ routeProgress.left }} {{ t('to go') }}<template v-if="routeProgress.eta"> · ~{{ routeProgress.eta }}</template></span>
</p>
<p v-if="card.route?.verified && (routePlaces.from || routePlaces.to)" class="entity-card__route-places">
<span>{{ routePlaces.from }}</span>
<span>{{ routePlaces.to }}</span>
</p>
<AltitudeGraph v-if="altitudeGraphed" :key="`altitude:${card.key}`" :altitude-m="lost ? null : card.altitudeM" :tick="tick" />
<p
v-if="card.route && !card.route.verified"
class="entity-card__route-note"
:title="t('The scheduled route for this flight number does not match where the plane is; it may be another leg of the same flight.')"
>
<span class="material-symbols-outlined" aria-hidden="true">warning</span>{{ t('Scheduled · unverified: does not match where the plane is') }}
</p>
<div v-if="tiles.length && heroKind !== 'none' && !contextNeedle" class="entity-card__tiles" :style="{ gridTemplateColumns: `repeat(${tiles.length}, minmax(0, 1fr))` }">
<div v-for="fact in tiles" :key="fact.field" class="entity-card__tile">
<span>{{ t(fact.label) }}</span>
<strong>{{ splitValue(fact.value).number }}<small v-if="splitValue(fact.value).unit">{{ splitValue(fact.value).unit }}</small></strong>
</div>
</div>
<p v-if="contextNeedle && !gridFacts.length" class="entity-card__no-match">{{ t('Nothing in this item’s details matches “{text}”.', { text: contextSearchText.trim() }) }}</p>
<section v-if="gridFacts.length" class="entity-card__section">
<h4>{{ contextNeedle ? t('Matching details') : t('Details') }}</h4>
<dl class="entity-card__facts">
<div v-for="fact in gridFacts" :key="fact.field" class="entity-card__fact">
<dt>{{ t(fact.label) }}</dt>
<dd>{{ fact.value }}</dd>
</div>
</dl>
</section>
<div v-if="card.links.length" class="entity-card__links">
<a v-for="link in card.links" :key="link.kind" :href="link.href" target="_blank" rel="noopener noreferrer">{{ t(link.label) }} ↗</a>
</div>
<div class="entity-card__actions">
<!-- On an aircraft or a satellite, Cockpit leads: it is the action people come for. -->
<button v-if="store.canCockpit()" type="button" class="entity-card__action entity-card__action--primary" @click="store.cockpit()">
<span class="material-symbols-outlined" aria-hidden="true">{{ card.layerId === 'satellites' ? 'satellite_alt' : 'flight' }}</span>{{ card.layerId === 'satellites' ? t('Enter orbital view') : t('Enter Cockpit') }}
</button>
<div class="entity-card__action-row">
<button type="button" class="entity-card__action" @click="store.flyTo()">
<span class="material-symbols-outlined" aria-hidden="true">my_location</span>{{ t('Fly to') }}
</button>
<button v-if="store.canFollow()" type="button" class="entity-card__action" :class="{ 'entity-card__action--on': store.isFollowing() }" :aria-pressed="String(store.isFollowing())" @click="store.follow()">
<span class="material-symbols-outlined" aria-hidden="true">navigation</span>{{ store.isFollowing() ? t('Following') : t('Follow') }}
</button>
</div>
<button type="button" class="entity-card__action entity-card__action--ask" @click="store.ask()">
<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.8" aria-hidden="true"><path d="M4 5h16v11H9l-5 4z" /></svg>{{ t('Ask GEV about {name}', { name: shownTitle }) }}
</button>
</div>
<!-- The same blocks for every item, in one order: weather and local
time, then flights, vessels and hazards within the Context radius. -->
<SpotConditions v-if="Number.isFinite(card.lat) && Number.isFinite(card.lon)" :key="card.key" entity :lat="card.lat" :lon="card.lon" :exclude-key="card.key" :settle-km="settleKm" />
<p v-if="source" class="entity-card__source">
<span>{{ t('Source') }}</span> {{ source }}<template v-if="ageText"> · {{ ageText }}</template>
</p>
</section>
</Transition>
</template>
+392
View File
@@ -0,0 +1,392 @@
<script setup>
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { t } from '../../../i18n/index.js';
import { compassName, hazardsNear, regionalBrief, weatherLook } from '../../spotConditions.js';
import { distanceKm } from '../../../data/entityContext.js';
import { CONTEXT_RADIUS_STEPS, contextRadiusKm, setContextRadiusKm } from '../../contextRadius.js';
import { contextNeedle, matchesContextSearch } from '../../contextSearch.js';
import UiSlider from '../../kit/UiSlider.js';
import { useEntityCardStore } from '../../stores/entityCard.js';
import { useOmnibarStore } from '../../stores/omnibar.js';
import { shownLayerName } from '../../layerNames.js';
// Conditions around one spot. For the view when nothing is picked: the
// weather there now, natural hazards near it (earthquakes, tropical storms,
// wildfires), warnings broadcast by things the loaded layers have nearby, and
// the local headlines. For a selected item (`entity`) it is the standard set
// every card shows, in one order: weather and local time, then the flights,
// vessels and hazards nearby, then alerts and whatever else is loaded there.
// Every nearby block looks out to the same distance, set by the radius
// control here. It reads again when the spot moves; the feeds behind it are
// cached.
const props = defineProps({
lat: { type: Number, required: true },
lon: { type: Number, required: true },
/** Show the standard blocks for a selected item. */
entity: { type: Boolean, default: false },
/** The selected item's own key, left out of the nearby lists. */
excludeKey: { type: String, default: '' },
/** How far the spot moves before the weather and hazards are read again. */
settleKm: { type: Number, default: 1 },
});
const store = useEntityCardStore();
const omnibar = useOmnibarStore();
const brief = ref(null);
const hazards = ref([]);
const loading = ref(true);
/** Where the weather and hazards were last read for. */
let readAt = null;
let reading = 0;
/** Hazard reads count apart, so moving the radius never drops a weather read. */
let readingHazards = 0;
let settle = null;
const radiusKm = contextRadiusKm;
const radiusText = computed(() => `${radiusKm.value.toLocaleString()} km`);
const radiusIndex = computed(() => Math.max(0, CONTEXT_RADIUS_STEPS.indexOf(radiusKm.value)));
const pickRadius = (index) => setContextRadiusKm(CONTEXT_RADIUS_STEPS[index]);
async function read(lat, lon) {
if (readAt && distanceKm(readAt, { lat, lon }) <= props.settleKm) return;
readAt = { lat, lon };
const mine = ++reading;
const mineHazards = ++readingHazards;
loading.value = true;
const [nextBrief, nextHazards] = await Promise.all([
regionalBrief(lat, lon),
hazardsNear(lat, lon, radiusKm.value).catch(() => []),
]);
if (reading !== mine) return;
brief.value = nextBrief;
// A radius change meanwhile has its own, newer hazard read.
if (readingHazards === mineHazards) hazards.value = nextHazards;
loading.value = false;
}
watch(
() => `${props.lat},${props.lon}`,
() => {
clearTimeout(settle);
settle = setTimeout(() => void read(props.lat, props.lon), 350);
},
{ immediate: true },
);
// A new radius only re-filters the hazard feeds, which are already cached.
watch(radiusKm, async (km) => {
const at = readAt || { lat: props.lat, lon: props.lon };
const mine = ++readingHazards;
const next = await hazardsNear(at.lat, at.lon, km).catch(() => []);
if (readingHazards !== mine) return;
hazards.value = next;
});
// Warnings from the loaded layers move with their records; read them often.
const tick = ref(0);
let timer = null;
onMounted(() => {
timer = setInterval(() => tick.value++, 4000);
});
onBeforeUnmount(() => {
clearInterval(timer);
clearTimeout(settle);
});
// The Context search narrows every list below to what holds its text.
const searching = computed(() => Boolean(contextNeedle.value));
const alerts = computed(() => {
void tick.value;
return store
.alertsAt(props.lat, props.lon, { radiusKm: radiusKm.value, limit: searching.value ? 40 : 4 })
.filter((alert) => matchesContextSearch(alert.title, alert.text));
});
const shownHazards = computed(() =>
hazards.value.filter((hazard) => matchesContextSearch(hazard.title, hazard.detail, hazardLayers.value[hazard.kind]?.name)).slice(0, searching.value ? 12 : 5),
);
// The standard nearby lists for a selected item, from the layers that are on.
const groups = computed(() => {
void tick.value;
if (!props.entity) return null;
return store.nearbyGroups(props.lat, props.lon, {
radiusKm: radiusKm.value,
limit: searching.value ? 12 : 4,
excludeKey: props.excludeKey,
query: contextNeedle.value,
});
});
const trafficBlocks = computed(() =>
groups.value
? [
{ id: 'flights', icon: 'flight', title: t('Flights within {radius}', { radius: radiusText.value }), none: t('No flights within {radius} from the layers that are on.', { radius: radiusText.value }), ...groups.value.flights },
{ id: 'vessels', icon: 'directions_boat', title: t('Vessels within {radius}', { radius: radiusText.value }), none: t('No vessels within {radius} from the layers that are on.', { radius: radiusText.value }), ...groups.value.vessels },
]
: [],
);
// Local solar time at the spot, from its longitude: no time zone lookup.
const localTime = computed(() => {
void tick.value;
const solar = new Date(Date.now() + (props.lon / 15) * 3_600_000);
return `${String(solar.getUTCHours()).padStart(2, '0')}:${String(solar.getUTCMinutes()).padStart(2, '0')}`;
});
const weather = computed(() => brief.value?.weather || null);
const look = computed(() => weatherLook(weather.value?.weatherCode));
const round = (n) => (Number.isFinite(n) ? Math.round(n) : null);
const weatherFacts = computed(() => {
const now = weather.value;
if (!now) return [];
const facts = [];
if (Number.isFinite(now.windKph)) {
const from = Number.isFinite(now.windDirectionDeg)
? ` ${compassName(now.windDirectionDeg)}`
: '';
facts.push({ label: t('Wind'), value: `${round(now.windKph)} km/h${from}` });
}
if (Number.isFinite(now.cloudCoverPct)) facts.push({ label: t('Cloud'), value: `${round(now.cloudCoverPct)}%` });
if (Number.isFinite(now.visibilityM))
facts.push({
label: t('Visibility'),
value: now.visibilityM >= 10_000 ? `${round(now.visibilityM / 1000)} km` : `${(now.visibilityM / 1000).toFixed(1)} km`,
});
if (Number.isFinite(now.precipitationMm)) facts.push({ label: t('Rain'), value: `${now.precipitationMm.toFixed(1)} mm` });
return facts;
});
const articles = computed(() =>
props.entity ? [] : (brief.value?.articles || []).filter((article) => matchesContextSearch(article.title, article.domain)).slice(0, 3),
);
const distance = (km) => (km < 10 ? `${km.toFixed(1)} km` : `${Math.round(km).toLocaleString()} km`);
function ago(ms) {
if (!Number.isFinite(ms)) return '';
const minutes = Math.max(0, Math.round((Date.now() - ms) / 60_000));
if (minutes < 60) return t('{n} min ago', { n: minutes });
const hours = Math.round(minutes / 60);
if (hours < 48) return t('{n} h ago', { n: hours });
return t('{n} d ago', { n: Math.round(hours / 24) });
}
const host = (article) => article.domain || '';
// The layer each kind of hazard comes from. Picking a hazard turns its layer
// on (when it is off) so the marker and its label are there to select.
const HAZARD_LAYER = {
quake: 'earthquakes',
storm: 'weather-cyclones',
wildfire: 'fire-perimeters',
hotspots: 'local-firms',
};
// Far enough out to see the markers (and pick one), not just the ground.
const HAZARD_RANGE_M = { quake: 120000, storm: 1500000, wildfire: 40000, hotspots: 180000 };
const layerTick = ref(0);
const hazardLayers = computed(() => {
void layerTick.value;
void hazards.value;
const rows = omnibar.controls?.layers() || [];
return Object.fromEntries(
Object.entries(HAZARD_LAYER).map(([kind, id]) => {
const row = rows.find((layer) => layer.id === id);
return [kind, row ? { id, name: shownLayerName(row.name, id), on: Boolean(row.enabled) } : null];
}),
);
});
let layerTimer = 0;
onMounted(() => {
layerTimer = setInterval(() => layerTick.value++, 1500);
});
onBeforeUnmount(() => clearInterval(layerTimer));
function flyTo(hazard) {
const layer = hazardLayers.value[hazard.kind];
if (layer && !layer.on) {
void omnibar.controls?.setLayer(layer.id, true);
setTimeout(() => layerTick.value++, 800);
}
omnibar.runner?.('fly_to_location', {
latitude: hazard.at.lat,
longitude: hazard.at.lon,
query: hazard.title,
viewMode: 'overview',
rangeM: HAZARD_RANGE_M[hazard.kind] ?? 100000,
});
}
const sources = computed(() => {
const list = [];
if (weather.value) list.push('Open-Meteo');
if (hazards.value.some((h) => h.kind === 'quake')) list.push('USGS');
if (hazards.value.some((h) => h.kind === 'storm')) list.push('NOAA NHC');
if (hazards.value.some((h) => h.kind === 'wildfire')) list.push('NIFC WFIGS');
if (hazards.value.some((h) => h.kind === 'hotspots')) list.push('NASA FIRMS');
if (articles.value.length && brief.value?.newsSource) list.push(brief.value.newsSource);
return list.join(' · ');
});
</script>
<template>
<section class="spot-conditions" :aria-label="t('Conditions here')" :aria-busy="String(loading)">
<!-- A selected item leads with the weather and the time there. -->
<template v-if="entity">
<div v-if="weather || entity" class="spot-conditions__weather" :class="{ 'spot-conditions__weather--timed': entity }">
<template v-if="weather">
<span class="material-symbols-outlined spot-conditions__weather-icon" aria-hidden="true">{{ look.icon }}</span>
<div class="spot-conditions__weather-now">
<strong>{{ round(weather.temperatureC) }}°C</strong>
<span>{{ t(look.label) }}<template v-if="Number.isFinite(weather.apparentTemperatureC)"> · {{ t('feels {n}°', { n: round(weather.apparentTemperatureC) }) }}</template></span>
</div>
</template>
<p v-else class="spot-conditions__loading spot-conditions__weather-wait">{{ loading ? t('Reading conditions here…') : t('No weather reading here.') }}</p>
<div v-if="entity" class="spot-conditions__time">
<strong>{{ localTime }}</strong>
<span>{{ t('Local solar time') }}</span>
</div>
<dl v-if="weather" class="spot-conditions__weather-facts">
<div v-for="fact in weatherFacts" :key="fact.label">
<dt>{{ fact.label }}</dt>
<dd>{{ fact.value }}</dd>
</div>
</dl>
</div>
<p v-else-if="loading" class="spot-conditions__loading">{{ t('Reading conditions here…') }}</p>
</template>
<!-- What the view's enabled layers have here. -->
<slot name="after-weather" />
<!-- One distance for every nearby block below. -->
<div class="spot-conditions__radius">
<span class="spot-conditions__radius-label">{{ t('Nearby radius') }}</span>
<UiSlider class="spot-conditions__radius-slider" min="0" :max="CONTEXT_RADIUS_STEPS.length - 1" step="1" :model-value="radiusIndex" :aria-label="t('Nearby radius')" :aria-valuetext="radiusText" :title="t('How far out the nearby lists look')" @update:model-value="pickRadius" />
<output class="spot-conditions__radius-value">{{ radiusText }}</output>
</div>
<div v-for="block in trafficBlocks" v-show="!searching || block.items.length" :key="block.id" class="spot-conditions__block">
<h4>
<span class="material-symbols-outlined" aria-hidden="true">{{ block.icon }}</span>
<span>{{ block.title }}</span>
<span class="spot-conditions__count">{{ block.count }}</span>
</h4>
<ul v-if="block.items.length">
<li v-for="item in block.items" :key="item.key">
<button type="button" @click="store.select(item.identity, { fly: true })">
<span class="spot-conditions__row-main">
<span class="spot-conditions__row-title">{{ item.title }}</span>
</span>
<span class="spot-conditions__row-meta">{{ distance(item.distanceKm) }}</span>
</button>
</li>
</ul>
<p v-else class="spot-conditions__none">{{ block.none }}</p>
</div>
<div v-show="!searching || shownHazards.length" class="spot-conditions__block">
<h4>
<span class="material-symbols-outlined" aria-hidden="true">warning</span>
<span>{{ t('Hazards within {radius}', { radius: radiusText }) }}</span>
<span class="spot-conditions__count" :class="{ 'spot-conditions__count--hot': hazards.length }">{{ loading ? '…' : searching ? shownHazards.length : hazards.length }}</span>
</h4>
<ul v-if="shownHazards.length">
<li v-for="hazard in shownHazards" :key="`${hazard.kind}-${hazard.title}-${hazard.distanceKm}`" :class="`spot-conditions__hazard--${hazard.kind}`">
<button type="button" @click="flyTo(hazard)">
<span class="material-symbols-outlined" aria-hidden="true">{{ hazard.icon }}</span>
<span class="spot-conditions__row-main">
<span class="spot-conditions__row-title">{{ hazard.title }}</span>
<span v-if="hazard.detail || hazard.time" class="spot-conditions__row-detail">{{ [hazard.detail, ago(hazard.time)].filter(Boolean).join(' · ') }}</span>
<span v-if="hazardLayers[hazard.kind]" class="spot-conditions__row-layer" :class="{ 'is-on': hazardLayers[hazard.kind].on }" :title="hazardLayers[hazard.kind].on ? t('Layer on') : t('Turns the layer on')">
<span class="spot-conditions__row-dot" aria-hidden="true"></span>{{ hazardLayers[hazard.kind].name }}
</span>
</span>
<span class="spot-conditions__row-meta">{{ distance(hazard.distanceKm) }} {{ hazard.direction }}</span>
</button>
</li>
</ul>
<p v-else-if="!loading" class="spot-conditions__none">{{ t('No earthquakes, tropical storms or wildfires reported within {radius}.', { radius: radiusText }) }}</p>
</div>
<div v-if="alerts.length" class="spot-conditions__block">
<h4>
<span class="material-symbols-outlined" aria-hidden="true">emergency_home</span>
<span>{{ t('Broadcast alerts within {radius}', { radius: radiusText }) }}</span>
<span class="spot-conditions__count spot-conditions__count--hot">{{ alerts.length }}</span>
</h4>
<ul>
<li v-for="alert in alerts" :key="alert.key" class="spot-conditions__hazard--alert">
<button type="button" @click="store.select(alert.identity, { fly: true })">
<span class="material-symbols-outlined" aria-hidden="true">{{ alert.icon }}</span>
<span class="spot-conditions__row-main">
<span class="spot-conditions__row-title">{{ alert.title }}</span>
<span class="spot-conditions__row-detail">{{ alert.text }}</span>
</span>
<span class="spot-conditions__row-meta">{{ distance(alert.distanceKm) }}</span>
</button>
</li>
</ul>
</div>
<div v-if="groups?.other.length" class="spot-conditions__block">
<h4>
<span class="material-symbols-outlined" aria-hidden="true">layers</span>
<span>{{ t('Also within {radius}', { radius: radiusText }) }}</span>
<span class="spot-conditions__count">{{ groups.other.length }}</span>
</h4>
<ul>
<li v-for="item in groups.other" :key="item.key">
<button type="button" @click="store.select(item.identity, { fly: true })">
<span class="material-symbols-outlined" aria-hidden="true">{{ item.icon }}</span>
<span class="spot-conditions__row-main">
<span class="spot-conditions__row-title">{{ item.title }}</span>
<span class="spot-conditions__row-detail">{{ item.layerName }}</span>
</span>
<span class="spot-conditions__row-meta">{{ distance(item.distanceKm) }}</span>
</button>
</li>
</ul>
</div>
<!-- For the view, the time and weather there come last, above the news. -->
<template v-if="!entity">
<slot name="before-weather" />
<div v-if="weather || entity" class="spot-conditions__weather" :class="{ 'spot-conditions__weather--timed': entity }">
<template v-if="weather">
<span class="material-symbols-outlined spot-conditions__weather-icon" aria-hidden="true">{{ look.icon }}</span>
<div class="spot-conditions__weather-now">
<strong>{{ round(weather.temperatureC) }}°C</strong>
<span>{{ t(look.label) }}<template v-if="Number.isFinite(weather.apparentTemperatureC)"> · {{ t('feels {n}°', { n: round(weather.apparentTemperatureC) }) }}</template></span>
</div>
</template>
<p v-else class="spot-conditions__loading spot-conditions__weather-wait">{{ loading ? t('Reading conditions here…') : t('No weather reading here.') }}</p>
<div v-if="entity" class="spot-conditions__time">
<strong>{{ localTime }}</strong>
<span>{{ t('Local solar time') }}</span>
</div>
<dl v-if="weather" class="spot-conditions__weather-facts">
<div v-for="fact in weatherFacts" :key="fact.label">
<dt>{{ fact.label }}</dt>
<dd>{{ fact.value }}</dd>
</div>
</dl>
</div>
<p v-else-if="loading" class="spot-conditions__loading">{{ t('Reading conditions here…') }}</p>
</template>
<div v-if="articles.length" class="spot-conditions__block">
<h4>
<span class="material-symbols-outlined" aria-hidden="true">newspaper</span>
<span>{{ t('Local news') }}</span>
<span v-if="brief?.newsQuery" class="spot-conditions__query">{{ brief.newsQuery }}</span>
</h4>
<ul>
<li v-for="article in articles" :key="article.url">
<a :href="article.url" target="_blank" rel="noopener noreferrer">
<span class="spot-conditions__row-main">
<span class="spot-conditions__row-title spot-conditions__row-title--wrap">{{ article.title }}</span>
<span class="spot-conditions__row-detail">{{ [host(article), ago(Date.parse(article.publishedAt))].filter(Boolean).join(' · ') }}</span>
</span>
</a>
</li>
</ul>
</div>
<p v-if="sources" class="spot-conditions__source">{{ sources }}</p>
</section>
</template>
+364
View File
@@ -0,0 +1,364 @@
<script setup>
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
import { t } from '../../../i18n/index.js';
// A garden sundial for the middle of the view, drawn in 2.5D: a bronze
// plate seen from above at a slant, its hour lines laid out for the
// latitude, a gnomon whose edge points at the celestial pole, and the
// shadow that gnomon would really cast now, from the sun's true position
// (low-precision formulas, good to a fraction of a degree). At night the
// shadow goes and the plate dims.
const props = defineProps({
lat: { type: Number, required: true },
lon: { type: Number, required: true },
});
const now = ref(Date.now());
let timer = null;
onMounted(() => {
timer = setInterval(() => (now.value = Date.now()), 20_000);
});
onBeforeUnmount(() => clearInterval(timer));
const RAD = Math.PI / 180;
/** The sun's declination and the local hour angle (radians) at a moment. */
function sunNow(lon, when) {
const d = (when - Date.UTC(2000, 0, 1, 12)) / 86_400_000;
const g = (357.529 + 0.98560028 * d) * RAD;
const q = 280.459 + 0.98564736 * d;
const ecliptic = (q + 1.915 * Math.sin(g) + 0.02 * Math.sin(2 * g)) * RAD;
const tilt = (23.439 - 0.00000036 * d) * RAD;
const ra = Math.atan2(Math.cos(tilt) * Math.sin(ecliptic), Math.cos(ecliptic));
const dec = Math.asin(Math.sin(tilt) * Math.sin(ecliptic));
const sidereal = ((18.697374558 + 24.06570982441908 * d) % 24) * 15;
let hour = (sidereal + lon) * RAD - ra;
hour = Math.atan2(Math.sin(hour), Math.cos(hour));
return { dec, hour };
}
/** Unit vector toward the sun in east-north-up for an hour angle and declination. */
function sunVector(phi, dec, hour) {
return {
e: -Math.cos(dec) * Math.sin(hour),
n: Math.sin(dec) * Math.cos(phi) - Math.cos(dec) * Math.cos(hour) * Math.sin(phi),
u: Math.sin(dec) * Math.sin(phi) + Math.cos(dec) * Math.cos(hour) * Math.cos(phi),
};
}
// Drawing: ground x east, y toward the pole the gnomon faces, z up; the
// plate is seen from the south (or north) at a slant, so y shrinks and z
// rises on screen.
const W = 300;
const H = 196;
const CX = 150;
const CY = 104;
const R = 118;
const SLANT = 0.5;
const RISE = 0.62;
const THICK = 9;
// The plate is seen turned a little, from the side the shadow falls on, so
// the gnomon shows a face and never hides its own shadow.
const TURN = 34 * (Math.PI / 180);
let turn = -TURN;
const project = (x, y, z = 0) => {
const rx = x * Math.cos(turn) - y * Math.sin(turn);
const ry = x * Math.sin(turn) + y * Math.cos(turn);
return { x: CX + rx, y: CY - ry * SLANT - z * RISE };
};
const pt = (p) => `${p.x.toFixed(1)},${p.y.toFixed(1)}`;
const dial = computed(() => {
const phi = Math.max(-89, Math.min(89, props.lat)) * RAD;
const south = props.lat < 0;
// y on the plate points toward the gnomon's pole: north, or south below
// the equator; east keeps its side by flipping x with it.
const flip = south ? -1 : 1;
const toPlate = (v) => ({ x: v.e * flip, y: v.n * flip, z: v.u });
// The gnomon's edge points at the elevated pole.
const pole = toPlate({ e: 0, n: Math.cos(phi) * flip, u: Math.abs(Math.sin(phi)) });
// The style starts at the hour lines' centre, south of the plate's middle.
const { dec, hour } = sunNow(props.lon, now.value);
const sunEnu = sunVector(phi, dec, hour);
const sun = toPlate(sunEnu);
// Morning sun on the east throws the shadow west: look from the west.
turn = sun.x > 0 ? TURN : -TURN;
const origin = { x: 0, y: -R * 0.42 };
const across = R * 0.62;
const tip = { x: origin.x + pole.x * across, y: origin.y + pole.y * across, z: pole.z * across };
const foot = { x: tip.x, y: tip.y, z: 0 };
// Hour lines, 6 to 18 local solar time: where the style's shadow falls
// with the sun on the equator at that hour.
const rimHit = (dx, dy) => {
// From the origin along (dx, dy) to the numeral ring (radius 0.84 R).
const ring = R * 0.84;
const b = origin.x * dx + origin.y * dy;
const c = origin.x ** 2 + origin.y ** 2 - ring ** 2;
const s = -b + Math.sqrt(b * b - c);
return { x: origin.x + dx * s, y: origin.y + dy * s };
};
const hours = [];
for (let h = 6; h <= 18; h++) {
const s = toPlate(sunVector(phi, 0, (h - 12) * 15 * RAD));
let dx;
let dy;
if (s.z > 0.02) {
const k = pole.z / s.z;
dx = pole.x - k * s.x;
dy = pole.y - k * s.y;
} else {
dx = -s.x;
dy = -s.y;
}
const len = Math.hypot(dx, dy) || 1;
dx /= len;
dy /= len;
const end = rimHit(dx, dy);
const label = rimHit(dx, dy);
const out = R * 0.08;
hours.push({
h,
from: project(origin.x, origin.y),
to: project(end.x, end.y),
label: project(label.x + dx * out, label.y + dy * out),
major: h % 3 === 0,
});
}
// The sun now, and the shadow of the gnomon's triangle on the plate.
const elevation = Math.asin(Math.max(-1, Math.min(1, sunEnu.u))) / RAD;
let shadow = null;
if (sun.z > 0.03) {
const k = tip.z / sun.z;
let sx = tip.x - k * sun.x;
let sy = tip.y - k * sun.y;
// A low sun throws a long shadow; keep it on the plate.
const reach = Math.hypot(sx - origin.x, sy - origin.y);
const max = R * 1.05;
if (reach > max) {
sx = origin.x + ((sx - origin.x) * max) / reach;
sy = origin.y + ((sy - origin.y) * max) / reach;
}
shadow = [project(origin.x, origin.y), project(foot.x, foot.y), project(sx, sy)].map(pt).join(' ');
}
// The sun lights the plate from its side: the bright spot of the bronze
// sits toward the sun, nearer the middle the higher it stands.
const azimuth = Math.atan2(sun.x, sun.y);
const spread = 0.42 * Math.cos(Math.max(0, elevation) * RAD);
const lit = project(Math.sin(azimuth) * R * spread, Math.cos(azimuth) * R * spread);
const shine = {
cx: `${(50 + ((lit.x - CX) / (2 * R)) * 100).toFixed(1)}%`,
cy: `${(50 + ((lit.y - CY) / (2 * R * SLANT)) * 100).toFixed(1)}%`,
};
// The gnomon is a bronze plate a few units thick: its two faces at
// x = ±w, drawn far face first, and the top edge between them. The face
// turned toward the viewer is the +x one when the turn brings it round.
const w = 2.4;
const faceAt = (dx) =>
[project(origin.x + dx, origin.y), project(foot.x + dx, foot.y), project(tip.x + dx, tip.y, tip.z)].map(pt).join(' ');
const nearSide = Math.sin(turn) < 0 ? 1 : -1;
const near = faceAt(nearSide * w);
const far = faceAt(-nearSide * w);
const top = [
project(origin.x - w, origin.y),
project(tip.x - w, tip.y, tip.z),
project(tip.x + w, tip.y, tip.z),
project(origin.x + w, origin.y),
]
.map(pt)
.join(' ');
const nearLit = sun.z > 0 && Math.sign(sun.x || 1) === nearSide;
const solar = new Date(now.value + (props.lon / 15) * 3_600_000);
const clock = `${String(solar.getUTCHours()).padStart(2, '0')}:${String(solar.getUTCMinutes()).padStart(2, '0')}`;
const compass = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'];
const bearing = (Math.atan2(sunEnu.e, sunEnu.n) / RAD + 360) % 360;
// A small flat compass in the corner, turned to match the plate: each
// cardinal's screen direction from the plate's projection (plate y points
// to the gnomon's pole, x east, both flipped below the equator).
const dir = (e, n) => {
const a = project(0, 0);
const b = project(e * flip * 40, n * flip * 40);
const dx = b.x - a.x;
const dy = b.y - a.y;
const len = Math.hypot(dx, dy) || 1;
return { x: dx / len, y: dy / len };
};
const cardinals = [
{ k: 'N', ...dir(0, 1) },
{ k: 'E', ...dir(1, 0) },
{ k: 'S', ...dir(0, -1) },
{ k: 'W', ...dir(-1, 0) },
];
const sunDir = elevation > 0 ? dir(sunEnu.e, sunEnu.n) : null;
return {
cardinals,
sunDir,
hours,
shadow,
day: elevation > 0,
elevation: Math.round(elevation),
direction: compass[Math.round(bearing / 45) % 8],
shine,
clock,
gnomon: {
near,
far,
top,
nearLit,
edge: [project(origin.x, origin.y), project(tip.x, tip.y, tip.z)],
},
poleLabel: project(0, R * 1.08),
poleText: south ? 'S' : 'N',
};
});
const ROMAN = ['VI', 'VII', 'VIII', 'IX', 'X', 'XI', 'XII', 'I', 'II', 'III', 'IV', 'V', 'VI'];
const plateTop = { cx: CX, cy: CY, rx: R, ry: R * SLANT };
// A HUD tick ring round the plate's edge: every 5°, longer every 30°.
const ticks = Array.from({ length: 72 }, (_, i) => {
const a = (i * 5 * Math.PI) / 180;
const major = i % 6 === 0;
const r1 = R * 0.99;
const r0 = R * (major ? 0.94 : 0.965);
return {
i,
major,
x1: CX + Math.cos(a) * r0,
y1: CY + Math.sin(a) * r0 * SLANT,
x2: CX + Math.cos(a) * r1,
y2: CY + Math.sin(a) * r1 * SLANT,
};
});
const caption = computed(() =>
dial.value.day
? t('Sundial · {time} solar · sun {deg}° {dir}', { time: dial.value.clock, deg: dial.value.elevation, dir: dial.value.direction })
: t('Sundial · {time} solar · sun below the horizon', { time: dial.value.clock }),
);
</script>
<template>
<figure class="sun-dial" :class="{ 'sun-dial--night': !dial.day }">
<svg :viewBox="`0 0 ${W} ${H}`" role="img" :aria-label="caption">
<defs>
<!-- Dark instrument glass, lit cyan toward the sun. -->
<radialGradient id="sun-dial-plate" :cx="dial.shine.cx" :cy="dial.shine.cy" r="85%">
<stop offset="0%" stop-color="#14394a" />
<stop offset="40%" stop-color="#0b2230" />
<stop offset="80%" stop-color="#06131b" />
<stop offset="100%" stop-color="#040b10" />
</radialGradient>
<linearGradient id="sun-dial-rim" x1="0" x2="1">
<stop offset="0%" stop-color="#03080c" />
<stop offset="40%" stop-color="#0d2633" />
<stop offset="60%" stop-color="#0a1d27" />
<stop offset="100%" stop-color="#02060a" />
</linearGradient>
<radialGradient id="sun-dial-glow" :cx="dial.shine.cx" :cy="dial.shine.cy" r="55%">
<stop offset="0%" stop-color="#36dcff" stop-opacity="0.22" />
<stop offset="100%" stop-color="#36dcff" stop-opacity="0" />
</radialGradient>
<linearGradient id="sun-dial-gnomon-lit" x1="0" y1="1" x2="1" y2="0">
<stop offset="0%" stop-color="#11607a" />
<stop offset="100%" stop-color="#8af2ff" />
</linearGradient>
<linearGradient id="sun-dial-gnomon-dark" x1="0" y1="1" x2="1" y2="0">
<stop offset="0%" stop-color="#06202b" />
<stop offset="100%" stop-color="#145066" />
</linearGradient>
<filter id="sun-dial-shadow" x="-20%" y="-20%" width="140%" height="140%">
<feGaussianBlur stdDeviation="0.7" />
</filter>
<filter id="sun-dial-soft" x="-20%" y="-20%" width="140%" height="140%">
<feGaussianBlur stdDeviation="2" />
</filter>
<filter id="sun-dial-line-glow" x="-10%" y="-10%" width="120%" height="120%">
<feGaussianBlur stdDeviation="0.8" result="b" />
<feMerge><feMergeNode in="b" /><feMergeNode in="SourceGraphic" /></feMerge>
</filter>
</defs>
<!-- Ground glow under the plate, then the plate's edge and its top. -->
<ellipse :cx="plateTop.cx" :cy="plateTop.cy + THICK + 6" :rx="plateTop.rx * 1.02" :ry="plateTop.ry" fill="#000" opacity="0.55" filter="url(#sun-dial-soft)" />
<path
:d="`M ${CX - R} ${CY} A ${R} ${R * SLANT} 0 0 0 ${CX + R} ${CY} L ${CX + R} ${CY + THICK} A ${R} ${R * SLANT} 0 0 1 ${CX - R} ${CY + THICK} Z`"
fill="url(#sun-dial-rim)"
stroke="rgba(54, 220, 255, 0.22)"
stroke-width="0.6"
/>
<ellipse v-bind="plateTop" fill="url(#sun-dial-plate)" stroke="rgba(54, 220, 255, 0.55)" stroke-width="0.9" />
<ellipse v-bind="plateTop" fill="url(#sun-dial-glow)" />
<ellipse :cx="CX" :cy="CY" :rx="R * 0.88" :ry="R * 0.88 * SLANT" fill="none" stroke="rgba(54, 220, 255, 0.28)" stroke-width="0.5" />
<ellipse :cx="CX" :cy="CY" :rx="R * 0.62" :ry="R * 0.62 * SLANT" fill="none" stroke="rgba(54, 220, 255, 0.14)" stroke-width="0.5" stroke-dasharray="2 3" />
<g class="sun-dial__ticks">
<line v-for="tick in ticks" :key="tick.i" :x1="tick.x1" :y1="tick.y1" :x2="tick.x2" :y2="tick.y2" :class="{ major: tick.major }" />
</g>
<!-- Hour lines and numerals. -->
<g class="sun-dial__hours">
<line
v-for="line in dial.hours"
:key="`l${line.h}`"
:x1="line.from.x"
:y1="line.from.y"
:x2="line.to.x"
:y2="line.to.y"
:class="{ major: line.major }"
/>
<text v-for="(line, i) in dial.hours" :key="`t${line.h}`" :x="line.label.x" :y="line.label.y + 2.6">{{ ROMAN[i] }}</text>
</g>
<text :x="dial.poleLabel.x" :y="dial.poleLabel.y + 3" class="sun-dial__pole">{{ dial.poleText }}</text>
<!-- The shadow, then the gnomon standing over it. -->
<polygon v-if="dial.shadow" :points="dial.shadow" fill="#000" opacity="0.6" filter="url(#sun-dial-shadow)" />
<polygon :points="dial.gnomon.far" fill="#03141b" />
<polygon :points="dial.gnomon.top" :fill="dial.day ? '#7af0ff' : '#1d5a6b'" stroke="#03141b" stroke-width="0.4" />
<polygon :points="dial.gnomon.near" :fill="dial.gnomon.nearLit ? 'url(#sun-dial-gnomon-lit)' : 'url(#sun-dial-gnomon-dark)'" stroke="rgba(54, 220, 255, 0.5)" stroke-width="0.5" />
<line
:x1="dial.gnomon.edge[0].x"
:y1="dial.gnomon.edge[0].y"
:x2="dial.gnomon.edge[1].x"
:y2="dial.gnomon.edge[1].y"
:stroke="dial.day ? '#b8f8ff' : '#2f7d92'"
stroke-width="1"
stroke-linecap="round"
filter="url(#sun-dial-line-glow)"
/>
<!-- Small compass, turned like the plate. -->
<g class="sun-dial__compass" :transform="`translate(${W - 30} 30)`">
<circle r="15" class="sun-dial__compass-ring" />
<circle r="11" class="sun-dial__compass-inner" />
<line
v-for="c in dial.cardinals"
:key="`t${c.k}`"
:x1="c.x * 12"
:y1="c.y * 12"
:x2="c.x * 15"
:y2="c.y * 15"
class="sun-dial__compass-tick"
/>
<path
:d="`M ${dial.cardinals[0].x * 9.5} ${dial.cardinals[0].y * 9.5} L ${-dial.cardinals[0].y * 2.6} ${dial.cardinals[0].x * 2.6} L ${dial.cardinals[0].y * 2.6} ${-dial.cardinals[0].x * 2.6} Z`"
class="sun-dial__compass-north"
/>
<path
:d="`M ${dial.cardinals[2].x * 9.5} ${dial.cardinals[2].y * 9.5} L ${-dial.cardinals[2].y * 2.6} ${dial.cardinals[2].x * 2.6} L ${dial.cardinals[2].y * 2.6} ${-dial.cardinals[2].x * 2.6} Z`"
class="sun-dial__compass-south"
/>
<circle v-if="dial.sunDir" :cx="dial.sunDir.x * 15" :cy="dial.sunDir.y * 15" r="2.4" class="sun-dial__compass-sun" />
<text
v-for="c in dial.cardinals"
:key="c.k"
:x="c.x * 20"
:y="c.y * 20 + 2.3"
:class="['sun-dial__compass-label', { north: c.k === 'N' }]"
>{{ c.k }}</text>
</g>
</svg>
<figcaption>{{ caption }}</figcaption>
</figure>
</template>
+388
View File
@@ -0,0 +1,388 @@
<script setup>
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { storeToRefs } from 'pinia';
import { contextNeedle, contextSearchText, matchesContextSearch } from '../../contextSearch.js';
import { t } from '../../../i18n/index.js';
import { citiesAround, countryName, nearestCity } from '../../../data/wikidataCities.js';
import { useEntityCardStore } from '../../stores/entityCard.js';
import { useOmnibarStore } from '../../stores/omnibar.js';
import { shownLayerName } from '../../layerNames.js';
import { entityKind } from '../../../data/entityContext.js';
import SpotConditions from './SpotConditions.vue';
import SunDial from './SunDial.vue';
import AltitudeGraph from './AltitudeGraph.vue';
// What the Context panel shows while nothing is picked: where the camera is
// looking (place, region, local solar time, daylight, how wide the view is),
// the towns in it, what the loaded layers have in view closest to the middle
// first, and switches for the most used layers that are off. Any row opens
// that item's card. It reads again when the camera settles, and every few
// seconds so moving things stay current.
const store = useEntityCardStore();
const { view } = storeToRefs(store);
const tick = ref(0);
let timer = null;
onMounted(() => {
timer = setInterval(() => tick.value++, 4000);
});
onBeforeUnmount(() => clearInterval(timer));
const groups = computed(() => {
void tick.value;
void view.value;
return store.inView({ perLayer: contextNeedle.value ? 12 : 3, query: contextNeedle.value });
});
const shownTowns = computed(() => towns.value.filter((town) => matchesContextSearch(town.name)));
const total = computed(() => groups.value.reduce((sum, group) => sum + group.count, 0));
const totalLine = computed(() => {
const things = total.value === 1 ? t('1 thing') : t('{n} things', { n: total.value });
const layers = groups.value.length === 1 ? t('1 layer') : t('{n} layers', { n: groups.value.length });
return t('{things} in view from {layers}', { things, layers });
});
// The city at (or nearest to) the middle of the view, from the bundled cities
// pack: no place service is asked.
const place = ref(null);
let placeFor = '';
watch(
view,
async (current) => {
if (!current) return;
const key = `${current.center.lat.toFixed(2)},${current.center.lon.toFixed(2)}`;
if (key === placeFor) return;
placeFor = key;
try {
const city = await nearestCity(current.center.lat, current.center.lon);
if (placeFor === key) place.value = city ? { name: city.name, state: null, country: countryName(city.country) } : null;
} catch {
if (placeFor === key) place.value = null;
}
},
{ immediate: true },
);
const where = computed(() => {
const at = view.value?.center;
if (!at) return '';
return `${Math.abs(at.lat).toFixed(3)}°${at.lat >= 0 ? 'N' : 'S'} ${Math.abs(at.lon).toFixed(3)}°${at.lon >= 0 ? 'E' : 'W'}`;
});
const height = computed(() => {
const m = view.value?.heightM ?? 0;
return m >= 10_000 ? t('{n} km up', { n: Math.round(m / 1000) }) : t('{n} m up', { n: Math.round(m) });
});
const placeName = computed(() => {
const found = place.value;
if (!found) return t('This view');
return [found.name, found.state || found.country].filter(Boolean).join(', ');
});
// The sun at the middle of the view, from the usual low-precision formula
// (good to a fraction of a degree): its elevation, and the local solar time.
function sunElevation(lat, lon, when) {
const rad = Math.PI / 180;
const d = (when - Date.UTC(2000, 0, 1, 12)) / 86_400_000;
const g = (357.529 + 0.98560028 * d) * rad;
const q = 280.459 + 0.98564736 * d;
const ecliptic = (q + 1.915 * Math.sin(g) + 0.02 * Math.sin(2 * g)) * rad;
const tilt = (23.439 - 0.00000036 * d) * rad;
const ra = Math.atan2(Math.cos(tilt) * Math.sin(ecliptic), Math.cos(ecliptic));
const dec = Math.asin(Math.sin(tilt) * Math.sin(ecliptic));
const sidereal = ((18.697374558 + 24.06570982441908 * d) % 24) * 15;
const hourAngle = (sidereal + lon) * rad - ra;
return (
Math.asin(Math.sin(lat * rad) * Math.sin(dec) + Math.cos(lat * rad) * Math.cos(dec) * Math.cos(hourAngle)) / rad
);
}
// The sundial shows only with the whole globe in view, not zoomed in. It
// goes by the camera's height: a tilted view near the ground sees the
// horizon, so the view's extent reads as the whole globe there too.
const GLOBE_HEIGHT_M = 5_000_000;
const globeView = computed(() => {
const current = view.value;
return Boolean(current?.center) && (current.heightM ?? 0) >= GLOBE_HEIGHT_M;
});
// Local time and daylight at the middle of the view. With the whole globe in
// view they say little, so they are left out there. The camera's height has
// its own graph.
const facts = computed(() => {
void tick.value;
const current = view.value;
if (!current || globeView.value) return [];
const { lat, lon } = current.center;
const now = Date.now();
const solar = new Date(now + (lon / 15) * 3_600_000);
const time = `${String(solar.getUTCHours()).padStart(2, '0')}:${String(solar.getUTCMinutes()).padStart(2, '0')}`;
const sun = sunElevation(lat, lon, now);
const light = sun > 6 ? t('Day') : sun > -6 ? t('Twilight') : t('Night');
return [
{ label: t('Local solar time'), value: time },
{ label: t('Daylight'), value: `${light} · ${t('sun {n}°', { n: Math.round(sun) })}` },
];
});
// A reading of the camera's height each time the view settles, and on the
// timer, for its graph.
const cameraTick = ref(0);
watch([view, tick], () => cameraTick.value++);
// Towns in the view, nearest the middle first.
const towns = ref([]);
let townsFor = '';
watch(
view,
async (current) => {
if (!current || current.heightM > 400_000) {
towns.value = [];
return;
}
const key = `${current.center.lat.toFixed(2)},${current.center.lon.toFixed(2)},${Math.round(current.heightM / 1000)}`;
if (key === townsFor) return;
townsFor = key;
try {
// The most populous places in view; only larger cities from high up.
const found = await citiesAround({
latitude: current.center.lat,
longitude: current.center.lon,
radiusKm: Math.round(Math.min(150, Math.max(15, current.heightM / 1500))),
minPopulation: current.heightM > 60_000 ? 50_000 : 0,
limit: 8,
});
if (townsFor === key) towns.value = found.filter((town) => town.name !== place.value?.name).slice(0, 5);
} catch {
if (townsFor === key) towns.value = [];
}
},
{ immediate: true },
);
const goToTown = (town) =>
omnibar.runner
? omnibar.runner('fly_to_location', { latitude: town.latitude, longitude: town.longitude, query: town.name })
: null;
// What each layer that is on is made of (aircraft: civilian, military and on
// the ground, then by type; vessels by type; and so on): of everything it has
// at globe view, of what is in view once zoomed in. Each split is a bar whose
// segments are its parts.
const SPLIT_COLORS = ['#36dcff', '#ffb547', '#8f9aa3', '#c792ff', '#4be3a0'];
function breakdownOf(layerId, loaded) {
const found = store.breakdown(layerId, globeView.value ? {} : { rect: view.value?.rect });
if (!found) return null;
const basis = globeView.value
? loaded !== null && loaded > found.total
? t('Of {n} read, {total} loaded', { n: found.total.toLocaleString(), total: loaded.toLocaleString() })
: t('Of all {n}', { n: found.total.toLocaleString() })
: t('Of {n} in view', { n: found.total.toLocaleString() });
return {
basis,
splits: found.splits.map((split) => ({
title: t(split.title),
parts: split.parts.map((part, index) => ({
label: t(part.label),
count: part.count.toLocaleString(),
share: `${((part.count / found.total) * 100).toFixed(1)}%`,
color: SPLIT_COLORS[index % SPLIT_COLORS.length],
})),
})),
};
}
// The layers that are on: their state, how many items each holds and how
// many of those are in view, so the card reflects what Data Layers has on.
const liveLayers = computed(() => {
void tick.value;
const inViewCount = Object.fromEntries(groups.value.map((g) => [g.layerId, g.count]));
const now = Date.now();
return store.liveLayers().map((row) => {
const stats = row.stats || {};
const state = stats.error
? { tone: 'error', text: t('Error') }
: stats.loading && !stats.count
? { tone: 'loading', text: t('Loading') }
: stats.stale
? { tone: 'stale', text: t('Stale') }
: { tone: 'live', text: t('Live') };
const age = Number.isFinite(stats.lastUpdate) ? Math.max(0, Math.round((now - stats.lastUpdate) / 1000)) : null;
const updated =
age === null ? '' : age < 60 ? t('{n} s ago', { n: age }) : age < 3600 ? t('{n} min ago', { n: Math.round(age / 60) }) : t('{n} h ago', { n: Math.round(age / 3600) });
return {
id: row.id,
icon: row.icon || '',
name: shownLayerName(row.name, row.id),
state,
total: Number.isFinite(stats.count) ? stats.count : null,
inView: inViewCount[row.id] ?? 0,
updated,
breakdown: breakdownOf(row.id, Number.isFinite(stats.count) ? stats.count : null),
};
});
});
// With the whole globe in view, what a point has nearby says little; the
// panel shows worldwide counts instead, one tile per layer: how many each
// layer that is on has loaded, and the most used layers that are off as
// tiles that turn them on. A count is kept while its layer reloads, so the
// tiles hold steady, and it does not change as the camera moves.
const lastCounts = new Map();
const TILE_ICONS = { cctv: 'videocam', traffic: 'traffic', fires: 'local_fire_department' };
const tileIcon = (id) => TILE_ICONS[id] || entityKind(id).icon;
const worldTiles = computed(() => {
void tick.value;
const on = liveLayers.value
.map((layer) => {
if (layer.total !== null) lastCounts.set(layer.id, layer.total);
return { id: layer.id, name: layer.name, icon: tileIcon(layer.id), on: true, count: lastCounts.get(layer.id) ?? null };
})
.sort((a, b) => (b.count ?? -1) - (a.count ?? -1));
const off = offLayers.value.map((layer) => ({ id: layer.id, name: layer.name, icon: tileIcon(layer.id), on: false, count: null }));
return [...on, ...off].slice(0, 8);
});
function turnOff(layer) {
void omnibar.controls?.setLayer(layer.id, false);
setTimeout(() => tick.value++, 800);
}
// The most used layers that are off, as switches.
const omnibar = useOmnibarStore();
const POPULAR = ['flights', 'ais-live-vessels', 'satellites', 'earthquakes', 'cctv', 'fires', 'traffic', 'weather-cyclones'];
const offLayers = computed(() => {
void tick.value;
return (omnibar.controls?.layers() || [])
.filter((layer) => POPULAR.includes(layer.id) && !layer.enabled)
.sort((a, b) => POPULAR.indexOf(a.id) - POPULAR.indexOf(b.id))
.slice(0, 4)
.map((layer) => ({ id: layer.id, name: shownLayerName(layer.name, layer.id) }));
});
function turnOn(layer) {
void omnibar.controls?.setLayer(layer.id, true);
setTimeout(() => tick.value++, 1500);
}
const distance = (km) =>
km < 1 ? t('{n} m', { n: Math.round(km * 1000) }) : t('{n} km', { n: km < 10 ? km.toFixed(1) : Math.round(km) });
</script>
<template>
<section class="view-context" :aria-label="t('In view')">
<!-- With the whole globe in view there is no place to name. -->
<h3 v-if="globeView" class="view-context__title">{{ t('Globe view') }}</h3>
<template v-else>
<header class="view-context__head">
<span class="material-symbols-outlined view-context__icon" aria-hidden="true">visibility</span>
<div class="view-context__kind">
<span>{{ t('In view') }}</span>
<span class="view-context__sub">{{ t('Nothing selected') }}</span>
</div>
</header>
<h3 class="view-context__title">{{ placeName }}</h3>
<p v-if="place && place.country && place.country !== place.name" class="view-context__region">{{ [place.state !== place.name ? place.state : null, place.country].filter(Boolean).join(' · ') }}</p>
<p v-if="where" class="view-context__where">{{ where }}</p>
</template>
<div v-if="globeView && worldTiles.length" class="view-context__world">
<h4>{{ t('Worldwide now') }}</h4>
<div class="view-context__world-grid">
<component :is="tile.on ? 'div' : 'button'" v-for="tile in worldTiles" :key="tile.id" :type="tile.on ? undefined : 'button'" class="view-context__world-tile" :class="{ 'is-off': !tile.on }" :title="tile.on ? undefined : t('Turn on {name}', { name: tile.name })" @click="tile.on ? undefined : turnOn(tile)">
<span class="material-symbols-outlined" aria-hidden="true">{{ tile.icon }}</span>
<strong>{{ tile.on ? (tile.count === null ? '…' : tile.count.toLocaleString()) : t('Off') }}</strong>
<span>{{ tile.name }}</span>
</component>
</div>
</div>
<!-- The sun dial fills the globe view only while no layer is on; once one is, its counts lead. -->
<SunDial v-if="globeView && !liveLayers.length" :lat="view.center.lat" :lon="view.center.lon" />
<!-- The layers that are on, and what each is made of, lead. -->
<div v-if="liveLayers.length" class="view-context__live">
<h4>{{ t('Layers on') }} <span class="view-context__count">{{ liveLayers.length }}</span></h4>
<ul>
<li v-for="layer in liveLayers" :key="layer.id" class="view-context__live-item">
<div class="view-context__live-row">
<span class="view-context__live-icon" aria-hidden="true">{{ layer.icon }}</span>
<span class="view-context__live-main">
<span class="view-context__live-name">{{ layer.name }}</span>
<span class="view-context__live-meta">
<template v-if="layer.total !== null">{{ t('{n} loaded', { n: layer.total.toLocaleString() }) }} · </template>{{ t('{n} in view', { n: layer.inView }) }}<template v-if="layer.updated"> · {{ layer.updated }}</template>
</span>
</span>
<span class="view-context__live-state" :class="`view-context__live-state--${layer.state.tone}`">{{ layer.state.text }}</span>
<button type="button" class="view-context__live-off" :aria-label="t('Turn off {name}', { name: layer.name })" :title="t('Turn off {name}', { name: layer.name })" @click="turnOff(layer)">
<span class="material-symbols-outlined" aria-hidden="true">close</span>
</button>
</div>
<div v-if="layer.breakdown" class="view-context__split">
<p class="view-context__split-basis">{{ layer.breakdown.basis }}</p>
<div v-for="split in layer.breakdown.splits" :key="split.title" class="view-context__split-set">
<div class="view-context__split-bar" role="img" :aria-label="split.parts.map((part) => `${part.label} ${part.count}`).join(', ')">
<i v-for="part in split.parts" :key="part.label" :style="{ width: part.share, background: `linear-gradient(to right, ${part.color}, ${part.color}99)` }"></i>
</div>
<ul class="view-context__split-legend">
<li v-for="part in split.parts" :key="part.label"><i :style="{ background: part.color }" aria-hidden="true"></i><span>{{ part.label }}</span><strong>{{ part.count }}</strong></li>
</ul>
</div>
</div>
</li>
</ul>
</div>
<AltitudeGraph v-if="Number.isFinite(view?.heightM)" class="view-context__camera" :altitude-m="view.heightM" :tick="cameraTick" :label="t('Camera height')" unit="metric" compact />
<SpotConditions v-if="view?.center && !globeView" :lat="view.center.lat" :lon="view.center.lon">
<template #before-weather>
<div v-if="facts.length" class="view-context__facts">
<div v-for="fact in facts" :key="fact.label" class="view-context__fact">
<span>{{ fact.label }}</span>
<strong>{{ fact.value }}</strong>
</div>
</div>
</template>
<template #after-weather>
<div v-if="groups.length" class="view-context__groups">
<p class="view-context__total">{{ totalLine }}</p>
<div v-for="group in groups" :key="group.layerId" class="view-context__group">
<h4>
<span class="material-symbols-outlined" aria-hidden="true">{{ group.icon }}</span>
<span>{{ group.layerName }}</span>
<span class="view-context__count">{{ group.count }}</span>
</h4>
<ul>
<li v-for="item in group.items" :key="item.key">
<button type="button" @click="store.select(item.identity, { fly: true })">
<span class="view-context__row-title">{{ item.title }}</span>
<span class="view-context__row-meta">{{ distance(item.distanceKm) }}</span>
</button>
</li>
</ul>
</div>
</div>
<p v-else-if="contextNeedle" class="view-context__empty">{{ t('Nothing in view matches “{text}”.', { text: contextSearchText.trim() }) }}</p>
<p v-else-if="liveLayers.length" class="view-context__empty">{{ t('Nothing from the layers that are on is in view here. Zoom out to see more.') }}</p>
<p v-else class="view-context__empty">{{ t('No loaded layer has anything in view. Turn some on in Data Layers.') }}</p>
</template>
</SpotConditions>
<div v-if="shownTowns.length" class="view-context__towns">
<h4>{{ t('Places in view') }}</h4>
<div class="view-context__chips">
<button v-for="town in shownTowns" :key="town.name" type="button" @click="goToTown(town)">{{ town.name }}</button>
</div>
</div>
<div v-if="offLayers.length && !globeView" class="view-context__towns">
<h4>{{ t('Show here') }}</h4>
<div class="view-context__chips">
<button v-for="layer in offLayers" :key="layer.id" type="button" class="view-context__chip--layer" @click="turnOn(layer)">
<span class="material-symbols-outlined" aria-hidden="true">add</span>{{ layer.name }}
</button>
</div>
</div>
<div class="view-context__actions">
<button type="button" class="entity-card__action entity-card__action--ask" @click="store.askAboutView(groups)">
<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.8" aria-hidden="true"><path d="M4 5h16v11H9l-5 4z" /></svg>{{ t("Ask GEV what's here") }}
</button>
</div>
</section>
</template>