Merge main into german/i18n-plurals-context

This commit is contained in:
German Khokhlov committed 2026-11-17 19:29:53 +04:00
commit 64b9cef14b
209 files changed
+35415 -701

No files matched your search

+178 -5
View File
@@ -1,5 +1,5 @@
<script setup>
import { computed } from 'vue';
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { storeToRefs } from 'pinia';
import { t } from '../../i18n/index.js';
import RailPanel from '../rail/RailPanel.vue';
@@ -7,18 +7,25 @@ import { vClassToggle } from '../rail/classToggle.js';
import { useCockpitStore } from '../stores/cockpit.js';
import { useBhoteKoshiPanelStore } from '../stores/bhoteKoshiPanel.js';
import { useContextStore } from '../stores/context.js';
import { usePanelChromeStore } from '../stores/panelChrome.js';
import { useEntityCardStore } from '../stores/entityCard.js';
import { useSceneStore } from '../stores/scenes.js';
import AwarenessPanel from './panels/AwarenessPanel.vue';
import BhoteKoshiPanel from './panels/BhoteKoshiPanel.vue';
import EntityCard from './panels/EntityCard.vue';
import ViewContext from './panels/ViewContext.vue';
import MissionDetail from './panels/MissionDetail.vue';
import MissionRoster from './panels/MissionRoster.vue';
import RadioPanel from './panels/RadioPanel.vue';
import UiButton from '../kit/UiButton.vue';
import { cockpitEntryFace } from '../cockpitPresentation.js';
import { LAYER_TABS, TAB_AFFECTS, activeTab, availableTabs, contextReady, enabledLayerIds, setEnabledLayers, tabTarget } from '../contextLayerTabs.js';
import { shownLayerName } from '../layerNames.js';
import { closeContextSearch, contextSearchOpen, contextSearchText } from '../contextSearch.js';
// ContextControls presents the mode switch and the nearby sites search and
// publishes them; until it does, the panel shows its initial markup.
const { view: ctx } = storeToRefs(useContextStore());
const { view: ctx, awareness } = storeToRefs(useContextStore());
const { presence: cockpit } = storeToRefs(useCockpitStore());
// The entry names the subject it would ride (cockpitEntryFace).
const entry = computed(() =>
@@ -29,6 +36,133 @@ const { panel: bhotePanel } = storeToRefs(useBhoteKoshiPanelStore());
// The Scene runtime chip SceneControls presents while a scene plays.
const { panel: scenePanel } = storeToRefs(useSceneStore());
const sceneRuntime = computed(() => scenePanel.value?.runtime ?? '');
// Context is one card for whatever was picked; until something is, it says how.
const entityCards = useEntityCardStore();
const { card: entityCard } = storeToRefs(entityCards);
const contactsSubject = computed(() =>
ctx.value?.flightsActive ? awareness.value?.subjectIdentity : null,
);
const contactsMatchCard = computed(() => {
const card = entityCard.value;
const subject = contactsSubject.value;
return Boolean(
card?.kind === 'aircraft' &&
subject?.layerId === card.layerId &&
String(subject.id) === String(card.identity.id),
);
});
watch(
[() => contactsSubject.value?.layerId, () => contactsSubject.value?.id],
([layerId, id]) => {
if (!['flights', 'military'].includes(layerId) || !id || contactsMatchCard.value) return;
// Contacts has already picked whom to follow. Only update the Inspector.
entityCards.select({ layerId, id, label: awareness.value?.subjectLabel }, { follow: false });
},
);
// Layer tabs: settings for the layers that are on, beside the card.
let layerTimer = null;
const readLayers = () => {
const rows = entityCards.liveLayers();
layerNames.value = Object.fromEntries(rows.map((row) => [row.id, shownLayerName(row.name, row.id)]));
setEnabledLayers(rows.map((row) => row.id));
};
const paneRefs = {};
const setPane = (id) => (el) => {
if (el) {
paneRefs[id] = el;
const target = tabTarget(id);
if (target instanceof HTMLElement && target.parentElement !== el) el.appendChild(target);
}
};
// Turning Radio or Launches on asks for the main tab, where they show.
const showView = () => (activeTab.value = 'view');
onMounted(() => {
globalThis.addEventListener?.('gev:context-show-view', showView);
contextReady.value = true;
readLayers();
layerTimer = setInterval(readLayers, 1500);
});
onBeforeUnmount(() => {
globalThis.removeEventListener?.('gev:context-show-view', showView);
clearInterval(layerTimer);
contextReady.value = false;
// A later mount starts as the button says: not expanded, no tab classes.
setDocked(false);
for (const tab of LAYER_TABS) globalThis.document?.body.classList.remove(`ctx-tab-${tab.id}`);
});
watch(availableTabs, (tabs) => {
for (const tab of LAYER_TABS)
globalThis.document?.body.classList.toggle(`ctx-tab-${tab.id}`, tabs.some((x) => x.id === tab.id));
if (activeTab.value === 'props' && !tabs.length) activeTab.value = 'view';
});
// Picking something shows its card.
watch(entityCard, (next, prev) => {
if (next && next?.key !== prev?.key) activeTab.value = 'view';
});
// The two tabs swap with the arrow keys, and focus follows (tabs pattern).
function switchTab() {
activeTab.value = activeTab.value === 'view' ? 'props' : 'view';
void nextTick(() => globalThis.document?.getElementById(`context-tab-btn-${activeTab.value}`)?.focus());
}
const isShown = (id) => availableTabs.value.some((tab) => tab.id === id);
// The names of the layers a section's settings act on.
const layerNames = ref({});
// Each layer gets a steady colour of its own for its dot.
const DOT_COLORS = ['#36dcff', '#4be3a0', '#ffb547', '#c792ff', '#ff7a45', '#ff6b9a', '#9ad7ff', '#e6e36b'];
const dotColor = (layer) => {
let h = 0;
for (const ch of layer) h = (h * 31 + ch.charCodeAt(0)) >>> 0;
return DOT_COLORS[h % DOT_COLORS.length];
};
const affects = (id) => {
void enabledLayerIds.value;
const ids = TAB_AFFECTS[id]?.(enabledLayerIds.value) ?? [];
return ids.map((layer) => ({ id: layer, name: layerNames.value[layer] || layer, color: dotColor(layer) }));
};
// Search in the header: a field that narrows what Context is showing, the
// selected item's details and every list of what is nearby or in view.
const searchInput = ref(null);
function toggleSearch() {
if (contextSearchOpen.value) return closeContextSearch();
contextSearchOpen.value = true;
activeTab.value = 'view';
void nextTick(() => searchInput.value?.focus());
}
const searchHint = computed(() =>
entityCard.value ? t('Search {name} and nearby', { name: entityCard.value.title }) : t('Search what is in view'),
);
// Expanded, Context becomes a full-height column over the right edge of the
// screen, with the globe left as it is underneath. It shrinks back when the
// panel closes.
const docked = ref(false);
const { panels: chromePanels } = storeToRefs(usePanelChromeStore());
// The phone layout and Cockpit have no room for the column: either one
// arriving lets it go.
let bodyWatch = null;
function setDocked(next) {
docked.value = next;
const body = globalThis.document?.body;
body?.classList.toggle('context-docked', next);
bodyWatch?.disconnect();
bodyWatch = null;
if (next && body && globalThis.MutationObserver) {
bodyWatch = new MutationObserver(() => {
if (body.classList.contains('mobile-shell') || body.classList.contains('cockpit-mode')) setDocked(false);
});
bodyWatch.observe(body, { attributes: true, attributeFilter: ['class'] });
}
}
// Only an open panel reads what is picked and in view; closed, it does no work.
const contextOpen = computed(() => chromePanels.value['global-context-panel']?.collapsed === false);
watch(
() => chromePanels.value['global-context-panel']?.collapsed,
(collapsed) => {
if (collapsed && docked.value) setDocked(false);
},
);
</script>
<template>
@@ -46,8 +180,42 @@ const sceneRuntime = computed(() => scenePanel.value?.runtime ?? '');
<template #badge><span id="recent-imagery-panel-count" :aria-label="t('Imagery days in the box')"></span></template>
<div id="recent-imagery-panel-body" class="ui-scroll" data-rail-scroller></div>
</RailPanel>
<RailPanel id="global-context-panel" start-collapsed v-class-toggle="{ ...(ctx && { 'context-enabled': ctx.enabled }) }" :data-context-mode="ctx?.mode" :title="t('CONTEXT')" sideways scroll rail-scroller>
<RailPanel id="global-context-panel" start-collapsed v-class-toggle="{ ...(ctx && { 'context-enabled': ctx.enabled }) }" :data-context-mode="ctx?.mode" :data-context-tab="activeTab" :title="t('CONTEXT')" sideways scroll rail-scroller>
<template #actions>
<button type="button" class="context-dock-btn" :aria-pressed="String(contextSearchOpen)" :aria-label="contextSearchOpen ? t('Close Context search') : t('Search in Context')" :title="contextSearchOpen ? t('Close search') : t('Search in Context')" @click="toggleSearch">
<span class="material-symbols-outlined" aria-hidden="true">search</span>
</button>
<button type="button" class="context-dock-btn" :aria-pressed="String(docked)" :aria-label="docked ? t('Shrink Context back to a panel') : t('Expand Context to a full-height column')" :title="docked ? t('Shrink') : t('Expand')" @click="setDocked(!docked)">
<span class="material-symbols-outlined" aria-hidden="true">{{ docked ? 'close_fullscreen' : 'open_in_full' }}</span>
</button>
</template>
<div class="cyber-panel-body ui-scroll" data-rail-scroller>
<div v-if="contextSearchOpen" class="context-search" role="search">
<span class="material-symbols-outlined" aria-hidden="true">search</span>
<input ref="searchInput" v-model="contextSearchText" type="search" class="context-search__input" :placeholder="searchHint" :aria-label="searchHint" autocomplete="off" spellcheck="false" @keydown.esc.stop="closeContextSearch" />
<button v-if="contextSearchText" type="button" class="context-search__clear" :aria-label="t('Clear search')" :title="t('Clear search')" @click="contextSearchText = ''; searchInput?.focus()">
<span class="material-symbols-outlined" aria-hidden="true">close</span>
</button>
</div>
<div v-if="availableTabs.length" class="context-tabs" role="tablist" :aria-label="t('Context tabs')">
<button id="context-tab-btn-view" type="button" role="tab" class="context-tabs__tab" :class="{ active: activeTab === 'view' }" :aria-selected="String(activeTab === 'view')" aria-controls="context-tab-view" :tabindex="activeTab === 'view' ? 0 : -1" @click="activeTab = 'view'" @keydown.left.prevent="switchTab" @keydown.right.prevent="switchTab">
<span class="material-symbols-outlined" aria-hidden="true">visibility</span><span class="context-tabs__label">{{ t('Inspector') }}</span>
</button>
<button id="context-tab-btn-props" type="button" role="tab" class="context-tabs__tab" :class="{ active: activeTab === 'props' }" :aria-selected="String(activeTab === 'props')" aria-controls="context-tab-props" :tabindex="activeTab === 'props' ? 0 : -1" @click="activeTab = 'props'" @keydown.left.prevent="switchTab" @keydown.right.prevent="switchTab">
<span class="material-symbols-outlined" aria-hidden="true">tune</span><span class="context-tabs__label">{{ t('Properties') }}</span>
</button>
</div>
<!-- Properties: settings of the layers that are on, one section each. -->
<div id="context-tab-props" class="context-props" :hidden="activeTab !== 'props'" role="tabpanel" aria-labelledby="context-tab-btn-props">
<section v-for="tab in LAYER_TABS" v-show="isShown(tab.id)" :key="tab.id" class="context-props__section">
<h4 class="context-props__heading"><span class="material-symbols-outlined" aria-hidden="true">{{ tab.icon }}</span>{{ t(tab.label) }}</h4>
<ul v-if="affects(tab.id).length" class="context-props__layers">
<li v-for="layer in affects(tab.id)" :key="layer.id"><i :style="{ background: layer.color }" aria-hidden="true"></i>{{ layer.name }}</li>
</ul>
<div :id="`context-tab-${tab.id}`" :ref="setPane(tab.id)" class="context-tab-pane"></div>
</section>
</div>
<RadioPanel />
<div class="global-context-modes" role="tablist" :aria-label="t('Context mode')">
<button id="global-context-flights-btn" class="context-mode-button" v-class-toggle="{ active: ctx?.flightsActive }" type="button" role="tab" tabindex="0" :aria-selected="String(ctx?.flightsActive ?? false)" :aria-disabled="ctx && String(ctx.busy)" :aria-busy="ctx && String(ctx.busy)" aria-controls="context-flights-view" :aria-label="t('CONTACTS')" :title="t('Cycles the nearest contacts of whatever type you select — planes, vessels, installations. Satellites track independently.')">
<span class="material-symbols-outlined" aria-hidden="true">radar</span>
@@ -71,7 +239,7 @@ const sceneRuntime = computed(() => scenePanel.value?.runtime ?? '');
<button id="installations-search-btn" class="panel-layer-toggle" type="button" :aria-disabled="ctx && String(ctx.installationsBusy)" :aria-busy="ctx && String(ctx.installationsBusy)">{{ t('SEARCH NEARBY SITES') }}</button>
<UiButton id="tr3b-toggle" class="tr3b-toggle" :pressed="!!cockpit?.tr3b?.converted" :hidden="!cockpit?.tr3b" :aria-label="t('Reclassify tracked contact as TR-3B')" :title="cockpit?.tr3b?.converted ? t('Restore real aircraft') : t('Reclassify as TR-3B')">🛸</UiButton>
</div>
<AwarenessPanel />
<AwarenessPanel v-if="!contactsMatchCard" />
</section>
<section id="context-missions-view" class="context-mode-view" role="tabpanel" aria-labelledby="global-context-missions-btn" :hidden="!ctx?.missionsActive">
<div id="space-mission-panel-host">
@@ -79,7 +247,12 @@ const sceneRuntime = computed(() => scenePanel.value?.runtime ?? '');
<MissionDetail />
</div>
</section>
<RadioPanel />
<div v-if="contextOpen" v-show="activeTab === 'view'" id="context-tab-view" role="tabpanel" aria-labelledby="context-tab-btn-view" :class="{ 'context-searching': contextSearchOpen && contextSearchText.trim() }">
<EntityCard :with-contacts="contactsMatchCard">
<AwarenessPanel v-if="contactsMatchCard" compact />
</EntityCard>
<ViewContext v-if="!entityCard" />
</div>
</div>
</RailPanel>
<BhoteKoshiPanel />
+19 -3
View File
@@ -5,6 +5,7 @@ import UiButton from '../kit/UiButton.vue';
import RailPanel from '../rail/RailPanel.vue';
import { useSceneSharingStore } from '../stores/sceneSharing.js';
import { useSceneStore } from '../stores/scenes.js';
import { STORY_TAG_LIMIT, STORY_TAGS } from '../../scenes/storyTags.js';
import { vClassToggle } from '../rail/classToggle.js';
import SceneDialog from './panels/SceneDialog.vue';
import SceneOptions from './SceneOptions.vue';
@@ -24,8 +25,14 @@ const { toolbar, dialog } = storeToRefs(useSceneSharingStore());
// SceneControls presents the Scene panel's buttons, status and progress and
// answers the buttons through the store.
const scenes = useSceneStore();
const { panel: scene } = storeToRefs(scenes);
const { panel: scene, currentScene } = storeToRefs(scenes);
const off = (name) => scene.value?.disabled[name] ?? false;
// The current scene's Stories tags; a chip not yet on is off at the limit.
const tagOn = (tag) => currentScene.value?.storyTags?.includes(tag) ?? false;
const tagOff = (tag) =>
off('tags') ||
(!tagOn(tag) &&
(currentScene.value?.storyTags?.length ?? 0) >= STORY_TAG_LIMIT);
// The hidden file input is the IMPORT button's chooser, open only while an
// owner presents the panel. It is cleared once the import settles, so the same
// file can be chosen again, unless the owner went away meanwhile.
@@ -87,6 +94,15 @@ async function importChosen(event) {
<UiButton id="scene-next-btn" type="button" :disabled="off('next')" @click="scenes.act('next')" class="gev-action-button scene-btn" :title="t('Play the shot after the selected one, moving on to the next scene when needed')">{{ t('NEXT') }}</UiButton>
</div>
<p class="scene-step-heading">{{ t('SAVE & SHARE') }}</p>
<div class="scene-controls scene-tag-chips" role="group" :aria-label="t('Stories tags')">
<UiButton v-for="tag in STORY_TAGS" :key="tag" type="button" class="scene-tag-chip" :pressed="tagOn(tag)" pressed-class="active" :disabled="tagOff(tag)" @click="scenes.act('tag', tag)">{{ t(tag) }}</UiButton>
</div>
<div class="scene-controls scene-story-controls">
<img v-if="currentScene?.storyThumb" id="scene-thumb-preview" class="scene-thumb-preview" :src="currentScene.storyThumb" :alt="t('Story thumbnail')" width="64" height="36" />
<span v-else class="scene-thumb-preview scene-thumb-empty" aria-hidden="true"></span>
<UiButton id="scene-thumb-btn" type="button" :disabled="off('thumb')" @click="scenes.act('thumb')" class="gev-action-button scene-btn" :title="t('Use the current view as the Stories card image')">{{ t('THUMBNAIL') }}</UiButton>
<UiButton id="scene-stories-btn" type="button" :disabled="off('stories')" @click="scenes.act('stories')" class="gev-action-button scene-btn" :title="scene?.inStories ? t('Take this scene off the Stories page') : t('Show this scene on the Stories page')">{{ scene?.inStories ? t('REMOVE FROM STORIES') : t('SAVE TO STORIES') }}</UiButton>
</div>
<div class="scene-controls scene-file-controls">
<UiButton id="scene-export-btn" type="button" :disabled="off('export')" @click="scenes.act('export')" class="gev-action-button scene-btn" :title="t('Download every scene as a JSON file you can import later')">{{ t('EXPORT') }}</UiButton>
<UiButton id="scene-import-btn" type="button" :disabled="off('import')" @click="chooseImport($refs.sceneFile)" class="gev-action-button scene-btn" :title="t('Load scenes from an exported JSON file')">{{ t('IMPORT') }}</UiButton>
@@ -94,8 +110,8 @@ async function importChosen(event) {
<input ref="sceneFile" type="file" id="scene-import-file" accept="application/json,.json" hidden @change="importChosen" />
</div>
<div v-if="toolbar" data-director-authoring class="scene-controls">
<UiButton type="button" class="gev-action-button scene-btn" :title="t('Edit anchors, data packs and shot details')" @click="toolbar.edit()">{{ t('EDIT DETAILS') }}</UiButton>
<UiButton type="button" class="gev-action-button scene-btn" :title="t('Download this scene as JSON or an asset bundle')" @click="toolbar.share()">{{ t('SHARE SCENE') }}</UiButton>
<UiButton type="button" class="gev-action-button scene-btn" :disabled="off('details')" :title="t('Edit anchors, data packs and shot details')" @click="toolbar.edit()">{{ t('EDIT DETAILS') }}</UiButton>
<UiButton type="button" class="gev-action-button scene-btn" :disabled="off('share')" :title="t('Download this scene as JSON or an asset bundle')" @click="toolbar.share()">{{ t('SHARE SCENE') }}</UiButton>
</div>
<div class="scene-progress">
<div id="scene-progress-fill" :style="scene ? { width: `${scene.progress}%` } : undefined">{{ scene?.progress ?? 0 }}%</div>
+362
View File
@@ -0,0 +1,362 @@
<script setup>
import {
computed,
defineAsyncComponent,
nextTick,
onBeforeUnmount,
onMounted,
ref,
watch,
} from 'vue';
import { storeToRefs } from 'pinia';
import { t } from '../../i18n/index.js';
import { useStoriesStore } from '../stores/stories.js';
import { GEV_LOGO_SYMBOL } from '../../stories/gevLogo.js';
import {
cornerControls,
creditPlacement,
entryPlacement,
} from '../../stories/format.js';
import { guardStoriesKeyboard } from '../../stories/keyboard.js';
// The screens, their styles and the story data load with Stories (see
// src/stories/boot.js); only the button, popup and toast load with GEV.
const ExploreScreen = defineAsyncComponent(
() => import('./stories/ExploreScreen.vue'),
);
const StoryScreen = defineAsyncComponent(
() => import('./stories/StoryScreen.vue'),
);
/**
* GEV Stories, as the Stories prototype lays it out: a Stories button in
* GEV's top-right row, Explore (the globe beside the story feed) and the
* Story page. Both show GEV's own Cesium globe through their map areas.
*/
const store = useStoriesStore();
const { mode, storyId, toast, openedToast } = storeToRefs(store);
const story = computed(() => (storyId.value ? store.byId(storyId.value) : null));
const reduceMotion = () =>
globalThis.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
// ── Entry: in GEV's top-right row, left of what sits in the corner ──
// GEV has its ACTIVE STYLE readout there; an element marked with
// data-stories-corner (with or beside the readout) can come after Stories
// mounts (cornerControls).
// GEV's phone layout shows neither; the button then sits under this column.
const COLUMN = 'corner-actions';
const entry = ref({ top: 14, right: 14 });
function placeEntry() {
entry.value = entryPlacement(
cornerControls(document).map((el) => el.getBoundingClientRect()),
innerWidth,
document.getElementById(COLUMN)?.getBoundingClientRect() ?? null,
);
}
let entryTries = 0;
let entryTimer = 0;
let cornerObserver = null;
const observed = new Set();
// A body class can move the corner without resizing it, which a
// ResizeObserver does not see.
let bodyObserver = null;
function watchCorner() {
placeEntry();
if (!bodyObserver && globalThis.MutationObserver) {
bodyObserver = new MutationObserver(placeEntry);
bodyObserver.observe(document.body, {
attributes: true,
attributeFilter: ['class'],
});
}
if (globalThis.ResizeObserver) cornerObserver ??= new ResizeObserver(placeEntry);
for (const el of [
...cornerControls(document),
document.getElementById(COLUMN),
]) {
if (el && cornerObserver && !observed.has(el)) {
cornerObserver.observe(el);
observed.add(el);
}
}
// Keep looking for a while for a control that mounts late.
if (++entryTries < 20)
entryTimer = setTimeout(watchCorner, 1000);
}
// ── GEV's required credit line: bottom left of the map, at every size ──
// A playing GEV scene turns on GEV's recording mode, whose rule drops the
// credit to the window's bottom edge, under the Stories timeline. Measure
// the map instead and pin the credit just inside it, playing or not.
let creditSlot = null;
let creditObserver = null;
let creditFrame = 0;
let creditTries = 0;
function placeCredit() {
const root = document.documentElement.style;
const at = creditPlacement({
map: creditSlot?.getBoundingClientRect(),
feed: document.querySelector('#gev-stories .ex-feed')?.getBoundingClientRect(),
width: innerWidth,
height: innerHeight,
});
if (!at) {
root.removeProperty('--gs-credit-bottom');
root.removeProperty('--gs-credit-left');
return;
}
root.setProperty('--gs-credit-bottom', `${at.bottom}px`);
root.setProperty('--gs-credit-left', `${at.left}px`);
}
function watchCredit() {
cancelAnimationFrame(creditFrame);
creditObserver?.disconnect();
creditSlot = null;
if (mode.value === 'closed') {
creditTries = 0;
placeCredit();
return;
}
creditSlot = document.querySelector('#gev-stories .map-slot');
if (!creditSlot) {
if (++creditTries < 120) creditFrame = requestAnimationFrame(watchCredit);
return;
}
creditTries = 0;
placeCredit();
if (globalThis.ResizeObserver) {
creditObserver = new ResizeObserver(placeCredit);
creditObserver.observe(creditSlot);
const feed = document.querySelector('#gev-stories .ex-feed');
if (feed) creditObserver.observe(feed);
}
}
// ── One onboarding popup in GEV ──
const POP_KEY = 'gevStoriesPopSeen';
const popOpen = ref(false);
function readPopSeen() {
try {
return localStorage.getItem(POP_KEY) === '1';
} catch {
return store.popSeen;
}
}
function markPopSeen() {
store.popSeen = true;
popOpen.value = false;
try {
localStorage.setItem(POP_KEY, '1');
} catch {
/* storage off: the popup comes back next visit */
}
}
function openExplore() {
markPopSeen();
store.controller.open();
}
// ── Opened in GEV: a toast that leads back to the story ──
let openedTimer = 0;
watch(openedToast, (v) => {
clearTimeout(openedTimer);
if (v) openedTimer = setTimeout(() => (openedToast.value = null), 6000);
});
function backToStory() {
const v = openedToast.value;
openedToast.value = null;
if (v) store.controller.openStory(v.id, { atMs: v.atMs });
}
const openedWhen = computed(() => openedToast.value?.when ?? '');
// ── Card-to-map morph: Play grows the card into the story; Back folds it home ──
const appEl = ref(null);
const rootEl = ref(null);
let unguardKeys = null;
function ghost(id, rect) {
const g = document.createElement('div');
g.className = 'morph';
// Without a picture the ghost keeps the cards' placeholder look (CSS).
const thumb = store.thumbs?.[id] || '';
if (thumb) g.style.background = `#04070a url("${thumb}") center / cover no-repeat`;
Object.assign(g.style, rect);
appEl.value?.appendChild(g);
return g;
}
const rectOf = (el) => {
const r = el.getBoundingClientRect();
return { left: `${r.left}px`, top: `${r.top}px`, width: `${r.width}px`, height: `${r.height}px` };
};
async function playFromExplore({ id, from }) {
if (reduceMotion() || !from?.offsetWidth) {
store.controller.openStory(id, { autoplay: true });
return;
}
const a = rectOf(from);
const g = ghost(id, a);
store.controller.openStory(id, { autoplay: true });
await nextTick();
const map = document.getElementById('stMap');
if (!map) {
g.remove();
return;
}
const b = rectOf(map);
g.animate(
[
{ ...a, borderRadius: '9px', opacity: 1 },
{ ...b, borderRadius: '0px', opacity: 1, offset: 0.8 },
{ ...b, borderRadius: '0px', opacity: 0 },
],
{ duration: 640, easing: 'cubic-bezier(.2,.9,.2,1)' },
).onfinish = () => g.remove();
}
async function backFromStory() {
const id = storyId.value;
const map = document.getElementById('stMap');
if (reduceMotion() || !map?.offsetWidth) {
store.controller.backToExplore();
return;
}
const a = rectOf(map);
const g = ghost(id, a);
store.picked = id;
store.controller.backToExplore();
await nextTick();
await new Promise((r) => requestAnimationFrame(r));
const card = document.querySelector(`#gev-stories .card[data-id="${CSS.escape(id)}"]`);
card?.scrollIntoView({ block: 'nearest' });
const dst = card?.querySelector('.thumb');
if (!dst?.offsetWidth) {
g.remove();
return;
}
g.animate(
[
{ ...a, borderRadius: '0px', opacity: 1 },
{ ...rectOf(dst), borderRadius: '9px', opacity: 1 },
],
{ duration: 560, easing: 'cubic-bezier(.2,.9,.2,1)' },
).onfinish = () => {
g.remove();
card.classList.remove('flash');
void card.offsetWidth;
card.classList.add('flash');
};
}
// ── Escape closes the topmost open layer, then steps back ──
function onKey(e) {
if (e.key !== 'Escape' || mode.value === 'closed' || e.defaultPrevented) return;
const target = e.target;
if (target?.type === 'search' && target.value) return;
const q = (sel) => document.querySelector(`#gev-stories ${sel}`);
e.preventDefault();
if (q('#exFilter')) q('#exFilterBtn')?.click();
else if (store.ctxOpen) store.ctxOpen = false;
else if (store.expanded) {
store.expanded = false;
store.controller.reframe();
} else if (mode.value === 'story') backFromStory();
else store.controller.close();
}
onMounted(() => {
watchCorner();
addEventListener('resize', placeEntry);
addEventListener('resize', placeCredit);
addEventListener('keydown', onKey, true);
unguardKeys = guardStoriesKeyboard({
root: rootEl.value,
// Until Close has put the view back, too (stories-mode stays till then).
isOpen: () =>
mode.value !== 'closed' ||
document.body.classList.contains('stories-mode'),
});
popOpen.value = !readPopSeen();
watchCredit();
});
onBeforeUnmount(() => {
clearTimeout(entryTimer);
clearTimeout(openedTimer);
cancelAnimationFrame(creditFrame);
cornerObserver?.disconnect();
bodyObserver?.disconnect();
creditObserver?.disconnect();
creditSlot = null;
placeCredit();
removeEventListener('resize', placeEntry);
removeEventListener('resize', placeCredit);
removeEventListener('keydown', onKey, true);
unguardKeys?.();
});
let returnFocus = null;
watch(mode, (m, previous) => {
if (m === 'closed') {
requestAnimationFrame(placeEntry);
nextTick(() => {
if (mode.value !== 'closed') return;
const entry = rootEl.value?.querySelector('#hStories');
const target = returnFocus?.isConnected && returnFocus !== document.body
? returnFocus
: entry;
target?.focus({ preventScroll: true });
returnFocus = null;
});
} else {
if (previous === 'closed') returnFocus = document.activeElement;
popOpen.value = false;
}
});
// Each screen (and each story, keyed) mounts its own map slot.
watch([mode, storyId], () => nextTick(watchCredit));
</script>
<template>
<div id="gev-stories" ref="rootEl">
<svg width="0" height="0" style="position: absolute" aria-hidden="true" v-html="GEV_LOGO_SYMBOL"></svg>
<!-- GEV: the Stories entry, its first-visit popup and the Opened-in-GEV toast -->
<template v-if="mode === 'closed' && store.available">
<button
id="hStories"
class="tbtn accent gs-entry"
:class="{ 'gs-entry-compact': entry.compact }"
type="button"
:aria-label="entry.compact ? t('Stories') : undefined"
:style="{ top: `${entry.top}px`, right: `${entry.right}px` }"
@click="openExplore"
>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"><rect x="3" y="5" width="18" height="14" rx="3" /><path d="M10 9.5v5l4.5-2.5z" fill="currentColor" /></svg>
<span>{{ t('Stories') }}</span>
</button>
<div
v-if="popOpen"
id="hPop"
class="h-pop gs-pop"
role="region"
aria-labelledby="hPopT"
:style="{ top: `${entry.top + 52}px`, right: `${Math.max(12, entry.right - 40)}px` }"
>
<span class="k">{{ t('NEW') }}</span>
<h2 id="hPopT">{{ t('GEV Stories') }}</h2>
<p>{{ t('Curated, interactive views of what is happening on Earth. Play one, take over the map whenever you like, then pick the story back up.') }}</p>
<div class="row">
<button class="tbtn solid" type="button" @click="openExplore">{{ t('Browse stories') }}</button>
<button class="tbtn" type="button" @click="markPopSeen">{{ t('Not now') }}</button>
</div>
</div>
<div v-if="openedToast" id="hToast" class="h-toast glass gs-opened-toast" role="status">
<b>{{ t('Opened in GEV') }}</b>
<span>{{ openedToast.title }} · {{ openedWhen }}</span>
<button class="tbtn" type="button" @click="backToStory">{{ t('Back to story') }}</button>
</div>
</template>
<div v-if="mode !== 'closed'" ref="appEl" class="app">
<ExploreScreen v-if="mode === 'explore'" @play="playFromExplore" />
<StoryScreen v-if="mode === 'story' && story" :key="story.id" :story="story" @back="backFromStory" />
<div v-if="toast" id="uxToast" class="ux-toast" role="status" aria-live="polite">{{ toast }}</div>
</div>
</div>
</template>
+2
View File
@@ -10,6 +10,7 @@ import CockpitView from './CockpitView.vue';
import SceneChromeView from './SceneChromeView.vue';
import ProviderSettingsView from './ProviderSettingsView.vue';
import IntelHudView from './IntelHudView.vue';
import StoriesView from './StoriesView.vue';
/**
* Application views by name. A page places each one with a host element,
@@ -26,6 +27,7 @@ export const APPLICATION_VIEWS = Object.freeze({
context: ContextView,
welcome: WelcomeView,
'intel-hud': IntelHudView,
stories: StoriesView,
});
const mounted = new WeakMap();
+130
View File
@@ -0,0 +1,130 @@
<script setup>
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { aircraftModelSpec, fleetModelSet, fleetModelSetLoading } from '../../../data/fleetModels.js';
import { t } from '../../../i18n/index.js';
import { useEntityCardStore } from '../../stores/entityCard.js';
import PreviewHud from './PreviewHud.vue';
// The selected aircraft's own model, turning slowly at the top of its card:
// the same fleet model the globe draws for its type, from the bytes loaded at
// startup, so nothing is fetched when a card opens. The renderer draws it in
// a small scene of its own (the `cardPreviews` hook); this tile lays the
// callouts and HUD over it. As it turns it changes look: a whole rotation as
// it is, then a short wireframe scan, then round again.
//
// While it turns, one callout at a time sits in the frame's top-left corner,
// HUD-style, telling something worked out about the flight (phase, flight
// level, Mach, what its squawk means, signal age). Each runs three states:
// enter 0-2.3 s the label and value slide in;
// hold 2.3-5.2 s a thin timer under the value fills;
// exit 5.2-6.2 s the text fades; a short gap, then the next one.
const props = defineProps({
/** `{typeCode, category, callsign}`: what picks the aircraft's fleet model. */
aircraft: { type: Object, default: null },
/** The aircraft's heading, so the turntable starts facing its way. */
heading: { type: Number, default: 0 },
/** `[{label, value}]` figures to call out, in order. */
callouts: { type: Array, default: () => [] },
/** Whether the tile is the one showing; a hidden one stops drawing. */
active: { type: Boolean, default: true },
});
const emit = defineEmits(['failed', 'cycle']);
const store = useEntityCardStore();
const host = ref(null);
const failed = ref(false);
watch(failed, (now) => now && emit('failed'));
const phase = ref('plain');
let preview = null;
// One callout's whole life: enter 2.3 s + hold 2.9 s + exit 1.0 s + 0.3 s gap.
const CYCLE_MS = 6500;
const CALLOUT_TIMING = { enter: 2300, leave: 1000 };
const page = ref(0);
let cycle = null;
const shown = computed(() => {
const list = props.callouts;
if (!list.length) return null;
const index = page.value % list.length;
return { ...list[index], index, total: list.length };
});
const pad = (n) => String(n).padStart(2, '0');
/** The fleet model's spec and bytes, or null when it has none. */
function fleetModel(set, aircraft) {
if (!set || !aircraft) return null;
const spec = aircraftModelSpec(set, aircraft);
const gltf = set.bytes.get(spec.model);
return gltf ? { gltf, basePath: spec.url } : null;
}
let showing = 0;
async function show() {
preview?.destroy();
preview = null;
phase.value = 'plain';
const asked = ++showing;
// A card opened before the Flights layer's model set has loaded waits for
// that load rather than giving up.
let set = fleetModelSet();
if (!set) set = await fleetModelSetLoading()?.catch(() => null);
if (asked !== showing) return;
const previews = store.previews();
const model = fleetModel(set, props.aircraft);
if (!previews?.model || !model || !host.value) {
failed.value = true;
return;
}
preview = previews.model(
host.value,
{ ...model, heading: props.heading },
{
onPhase: (next) => (phase.value = next),
onCycle: (ms) => emit('cycle', ms),
onFailed: () => (failed.value = true),
},
);
preview.setActive(props.active);
}
onMounted(() => {
show();
// Under reduced motion the first set of callouts stays.
const still = globalThis.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches;
if (!still) cycle = setInterval(() => page.value++, CYCLE_MS);
});
watch(
() => {
const a = props.aircraft;
return `${a?.typeCode ?? ''}|${a?.category ?? ''}|${a?.callsign ?? ''}`;
},
show,
);
watch(
() => props.active,
(active) => preview?.setActive(active),
);
onBeforeUnmount(() => {
showing++;
clearInterval(cycle);
preview?.destroy();
preview = null;
});
</script>
<template>
<div v-if="!failed" class="aircraft-hero">
<div ref="host" class="aircraft-hero__scene" aria-hidden="true"></div>
<PreviewHud variant="model" />
<Transition name="aircraft-hero-legend">
<p v-if="phase === 'scan'" class="aircraft-hero__scan" aria-hidden="true">{{ t('Scanning') }}</p>
</Transition>
<Transition name="aircraft-hero-callout" mode="out-in" :duration="CALLOUT_TIMING">
<div v-if="shown" :key="page" class="aircraft-hero__callout">
<span class="aircraft-hero__label">{{ shown.label }}<em>{{ pad(shown.index + 1) }} / {{ pad(shown.total) }}</em></span>
<strong class="aircraft-hero__value">{{ shown.value }}</strong>
<i class="aircraft-hero__timer" aria-hidden="true"></i>
</div>
</Transition>
</div>
</template>
+133
View File
@@ -0,0 +1,133 @@
<script setup>
import { computed, ref, watch } from 'vue';
import { formatNumber, t } from '../../../i18n/index.js';
// A figure as a filled graph (an aircraft's altitude, the camera's height, a
// satellite's altitude and speed):
// 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 on a log
* scale (the camera); 'km' is a height in kilometres and 'km/s' a speed
* (given in m/s), both on a straight scale (a satellite).
*/
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) => formatNumber(value, { maximumFractionDigits: 1 });
const metric = (m) =>
m >= 100_000
? t('{n} km', { n: number(Math.round(m / 1000)) })
: m >= 1000
? t('{n} km', { n: formatNumber(m / 1000, { minimumFractionDigits: 1, maximumFractionDigits: 1 }) })
: t('{n} m', { n: number(Math.round(m)) });
const SHOW = {
metric,
km: (m) => t('{n} km', { n: number(Math.round(m / 100) / 10) }),
'km/s': (m) => t('{n} km/s', { n: formatNumber(m / 1000, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) }),
};
const shown = (m) => (SHOW[props.unit] || ((value) => t('{n} ft', { n: number(feet(value)) })))(m);
/** The least each scale spans, so a steady figure still reads as a line. */
const LEAST = { feet: MIN_RANGE_M, km: 2000, 'km/s': 20 };
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 : LEAST[props.unit] || 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 feetScale = !SHOW[props.unit];
const change = feetScale ? feet(last.m) - feet(first.m) : Math.abs(moved) >= Math.max(1, last.m * (props.unit === 'metric' ? 0.005 : 0.0005)) ? moved : 0;
const changeText = feetScale ? t('{n} ft', { n: number(Math.abs(change)) }) : shown(Math.abs(moved));
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', { context: 'altitude' }),
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>
+3 -2
View File
@@ -8,6 +8,7 @@ import AwarenessNames from './AwarenessNames.vue';
// The Contacts panel inside Context. The Contacts layer publishes its view
// (standby, results or empty); until it does, the panel shows its initial
// markup. Buttons call the layer's navigation as the person's own.
const props = defineProps({ compact: Boolean });
const { awareness: view, awarenessLayer: layer } = storeToRefs(useContextStore());
const user = { origin: 'user' };
const root = ref(null);
@@ -58,8 +59,8 @@ onUpdated(() => {
<span>{{ view.text }}</span>
</div>
<template v-else-if="view.kind === 'results'">
<div class="military-awareness-subject">{{ view.subject }}</div>
<a v-if="view.photo && view.photo.src !== failedPhoto" class="military-awareness-photo" :href="view.photo.link" target="_blank" rel="noopener">
<div v-if="!props.compact" class="military-awareness-subject">{{ view.subject }}</div>
<a v-if="!props.compact && view.photo && view.photo.src !== failedPhoto" class="military-awareness-photo" :href="view.photo.link" target="_blank" rel="noopener">
<img :src="view.photo.src" :width="view.photo.width ?? undefined" :height="view.photo.height ?? undefined" alt="" @error="fail" />
<small v-if="view.photo.credit">{{ view.photo.credit }}</small>
</a>
+102
View File
@@ -0,0 +1,102 @@
<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(() => {
// The panel's line belongs to the camera it shows, which may be another.
if (!same.value) return [];
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>
+8 -2
View File
@@ -6,6 +6,7 @@ import { vPanelState } from '../../rail/panelState.js';
import { vClassToggle } from '../../rail/classToggle.js';
import PanelCollapseButton from '../../rail/PanelCollapseButton.vue';
import UiPanelEdge from '../../kit/UiPanelEdge.vue';
import { availableTabs, tabTarget } from '../../contextLayerTabs.js';
import UiSegmented from '../../kit/UiSegmented.vue';
import UiSlider from '../../kit/UiSlider.js';
import { useDisplayStore } from '../../stores/display.js';
@@ -20,6 +21,11 @@ import VisualPresets from './VisualPresets.vue';
// Draw and Import live in UTILITIES (LayerPanelsView).
const display = useDisplayStore();
const { view, models3d, parameters, cockpitPortal, groups, sky } = storeToRefs(display);
// Cockpit takes these controls first; otherwise, while a layer they act on is
// on, they move into that layer's tab in Context.
const inContext = (id) => availableTabs.value.some((tab) => tab.id === id);
const detectionTarget = computed(() => cockpitPortal.value?.detection ?? (inContext('labels') ? tabTarget('labels') : null));
const modelsTarget = computed(() => cockpitPortal.value?.models3d ?? (inContext('aircraft') ? tabTarget('aircraft') : null));
// A control's change goes to its owner (DisplayBindings).
const act = (name, ...args) => display.act(name, ...args);
const pct = (value) => `${value}%`;
@@ -122,7 +128,7 @@ const allocationOptions = computed(() => [
</div>
</div>
</Teleport>
<Teleport :to="cockpitPortal?.detection ?? 'body'" :disabled="!cockpitPortal?.detection">
<Teleport :to="detectionTarget ?? 'body'" :disabled="!detectionTarget">
<div class="pp-toggle-group">
<UiButton class="pp-toggle-btn" :class="{ active: detectButton?.active, panoptic: detectButton?.panoptic }" :pressed="detectButton?.pressed ?? false" id="detection-toggle" @click="act('cycleDetection')" :title="t('Detection Overlay (D)')" :aria-label="detectButton?.ariaLabel ?? t('Detection overlay')">
<span class="pp-icon">&#x25A3;</span>
@@ -160,7 +166,7 @@ const allocationOptions = computed(() => [
<div id="param-sliders"><StyleParameterRows v-if="parameters" :key="parameters.style" :rows="parameters.rows" :on-input="(name, value) => act('setStyleParameter', name, value)" /></div>
</div>
</Teleport>
<Teleport :to="cockpitPortal?.models3d ?? 'body'" :disabled="!cockpitPortal?.models3d">
<Teleport :to="modelsTarget ?? 'body'" :disabled="!modelsTarget">
<div class="pp-toggle-group">
<!-- 3D aircraft is DEFAULT-ON in Proximity (owner directive 2026-08-22), so the
button ships lit and the mode row ships open — the same markup-carries-the-default
+490
View File
@@ -0,0 +1,490 @@
<script setup>
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { storeToRefs } from 'pinia';
import { formatNumber, t } from '../../../i18n/index.js';
import { factFigure, factLabel, factValue, sayWords, useEntityCardStore } from '../../stores/entityCard.js';
import AircraftModelHero from './AircraftModelHero.vue';
import SatelliteGroundView from './SatelliteGroundView.vue';
import FlightCockpitView from './FlightCockpitView.vue';
import AltitudeGraph from './AltitudeGraph.vue';
import { contextNeedle, contextSearchText, matchesContextSearch } from '../../contextSearch.js';
import RouteGlobe from './RouteGlobe.vue';
import CctvPreview from './CctvPreview.vue';
import { useCctvStore } from '../../stores/cctv.js';
import SpotConditions from './SpotConditions.vue';
import { shownLayerName } from '../../layerNames.js';
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 props = defineProps({
/** Contacts follows this same aircraft, and its list sits inside the card. */
withContacts: Boolean,
});
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?.titleWords) return sayWords(current.titleWords, current.title);
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: formatNumber(Math.round(km * 1000)) })
: t('{n} km', { n: formatNumber(km < 10 ? Number(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));
// A satellite graphs its altitude and its speed, and leaves both out of the
// tiles and the grid.
const orbitGraphed = computed(() => card.value?.kind === 'satellite' && Number.isFinite(card.value?.altitudeM));
const graphedFields = computed(() => (orbitGraphed.value ? ['altitudeM', 'speedMps'] : altitudeGraphed.value ? ['altitudeM'] : []));
const tiles = computed(() => {
const facts = card.value?.facts || [];
return (card.value?.headline || [])
.filter((field) => !graphedFields.value.includes(field))
.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));
for (const field of graphedFields.value) shown.add(field);
return (card.value?.facts || []).filter((fact) => !shown.has(fact.field));
});
// What the turning model's callout says: what can be worked out about the
// flight (its phase, flight level, Mach, what its squawk means, how fresh its
// signal is), which the facts below don't already show.
const callouts = computed(() =>
(card.value?.insights || []).map((item) => ({ label: t(item.label), value: sayWords(item.words, item.value) })),
);
// 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;
const clsName = current.aircraftClassName ? t(current.aircraftClassName) : cls && cls[0].toUpperCase() + cls.slice(1);
return [current.operator, clsName].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(factLabel(fact), factValue(fact), 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
? t('{h} h {m} min', { h: Math.floor(hours), m: Math.round((hours % 1) * 60) })
: t('{n} min', { n: Math.max(1, Math.round(hours * 60)) });
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)]);
// Only for the same route still: another flight from the same airport
// may have taken the card meanwhile.
const now = card.value?.route;
if (now?.fromAt?.code === route.fromAt.code && now?.toAt?.code === route.toAt.code) routePlaces.value = { from, to };
},
{ immediate: true },
);
// The hero tile at the top of every card. A flight shows its photo, its route
// on a small globe, its 3D model and the view from its cockpit; a vessel, its
// photo; a satellite, the ground beneath it; a camera, its latest frame.
// The globe, model and cockpit view are the renderer's (`store.previews()`).
// Anything else gets a quiet placeholder with its icon and its headline
// figures until it has imagery of its own. Previews stay mounted so switching
// shows the next one at once.
const routeFailed = ref(false);
const routeKnown = computed(() => Boolean(card.value?.route?.fromAt && card.value?.route?.toAt) && !routeFailed.value);
const modelFailed = ref(false);
const cockpitFailed = ref(false);
const hasPosition = computed(() => Number.isFinite(card.value?.lat) && Number.isFinite(card.value?.lon));
const cockpitKnown = computed(() => card.value?.kind === 'aircraft' && hasPosition.value && !cockpitFailed.value);
const modelKnown = computed(() => Boolean(card.value?.aircraftModel) && !modelFailed.value);
const preview = ref(null);
// The photo the item's layer looked up (Planespotters for a tracked
// airliner, Open Vessel Photos for a selected vessel), with its credit.
const failedPhoto = ref('');
const photo = computed(() => {
const found = card.value?.photo;
if (!found?.src || found.src === failedPhoto.value) return null;
const { photographer, licence } = found;
const credit = licence
? photographer
? t('Photo: {photographer} · {licence}', { photographer, licence })
: t('Photo · {licence}', { licence })
: photographer
? t('Photo © {photographer}', { photographer })
: '';
return { ...found, credit };
});
const photoAvailable = computed(() => Boolean(photo.value));
const onPhotoError = (event) => (failedPhoto.value = event.currentTarget.getAttribute('src'));
watch(() => props.withContacts, () => (preview.value = null));
// The model and the cockpit view take turns: after each of the model's
// cycles, the view ahead from the cockpit shows for as long as that cycle
// took. It is made only once it is first needed. A manual selection holds the
// preview until another view or another item is selected.
const modelTurn = ref('model');
const cockpitMade = ref(false);
const activeFlightPreview = computed(() => {
const chosen = preview.value;
if (photoAvailable.value && (chosen === null || chosen === 'photo')) return 'photo';
if (cockpitKnown.value && (chosen === 'cockpit' || modelTurn.value === 'other')) return 'cockpit';
if (routeKnown.value && (chosen !== 'model' || !modelKnown.value)) return 'route';
if (modelKnown.value) return 'model';
return photoAvailable.value ? 'photo' : null;
});
let turnTimer = 0;
function onCockpitFailed() {
cockpitFailed.value = true;
if (preview.value === 'cockpit') preview.value = null;
clearTimeout(turnTimer);
modelTurn.value = 'model';
}
function showOtherView(ms) {
if (preview.value !== null || !hasPosition.value) return;
if (!cockpitKnown.value || activeFlightPreview.value === 'photo') return;
clearTimeout(turnTimer);
modelTurn.value = 'other';
cockpitMade.value = true;
turnTimer = setTimeout(() => (modelTurn.value = 'model'), Math.min(Math.max(ms, 4000), 30000));
}
const heroKind = computed(() => {
if (card.value?.kind === 'aircraft' && (photoAvailable.value || routeKnown.value || modelKnown.value)) return 'flight';
if (card.value?.kind === 'vessel' && photoAvailable.value) return 'photo';
if (card.value?.layerId === 'satellites' && hasPosition.value) return 'satellite';
if (card.value?.layerId === 'cctv') return 'camera';
return 'none';
});
// The route globe has no cycle of its own: it shows for ROUTE_TURN_MS,
// then the cockpit view shows for as long, and round again.
const ROUTE_TURN_MS = 20_000;
let routeTimer = 0;
watch(
[heroKind, activeFlightPreview, preview, cockpitKnown, () => card.value?.key],
() => {
clearTimeout(routeTimer);
// Under reduced motion the views do not swap by themselves (the model
// shows no scan there either, so it never hands over).
if (globalThis.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches) return;
if (preview.value === null && cockpitKnown.value && heroKind.value === 'flight' && activeFlightPreview.value === 'route')
routeTimer = setTimeout(() => showOtherView(ROUTE_TURN_MS), ROUTE_TURN_MS);
},
{ immediate: true },
);
// Picking a preview shows it at once, ending the cockpit view's turn.
function choosePreview(which) {
clearTimeout(turnTimer);
modelTurn.value = 'model';
preview.value = which;
if (which === 'cockpit') cockpitMade.value = true;
}
onBeforeUnmount(() => {
clearTimeout(turnTimer);
clearTimeout(routeTimer);
});
watch(
() => card.value?.key,
() => {
preview.value = null;
routeFailed.value = false;
modelFailed.value = false;
cockpitFailed.value = false;
clearTimeout(turnTimer);
modelTurn.value = 'model';
cockpitMade.value = false;
},
);
// 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, '');
const shown = shownLayerName(layer, current.layerId);
return plain(layer).includes(plain(current.kind)) ? shown : `${kindLabel.value} · ${shown}`;
});
// 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">
<template v-if="heroKind === 'flight'">
<a
v-if="photoAvailable"
:key="photo.src"
class="entity-hero__layer entity-hero__photo"
:class="{ 'is-shown': activeFlightPreview === 'photo' }"
:href="photo.link || undefined"
target="_blank"
rel="noopener"
>
<img :src="photo.src" :alt="t('Photo of {name}', { name: shownTitle })" v-on="{ error: onPhotoError }" />
<small v-if="photo.credit">{{ photo.credit }}</small>
</a>
<RouteGlobe v-if="routeKnown" :key="`route-${card.key}`" class="entity-hero__layer" :class="{ 'is-shown': activeFlightPreview === 'route' }" :active="activeFlightPreview === 'route'" :from="card.route.fromAt" :to="card.route.toAt" :at="{ lat: card.lat, lon: card.lon }" @failed="routeFailed = true" />
<AircraftModelHero v-if="modelKnown" :key="card.key" class="entity-hero__layer" :class="{ 'is-shown': activeFlightPreview === 'model' }" :active="activeFlightPreview === 'model'" :aircraft="card.aircraftModel" :heading="card.heading || 0" :callouts="callouts" @failed="modelFailed = true" @cycle="showOtherView" />
<FlightCockpitView v-if="cockpitMade && cockpitKnown" :key="`cockpit-${card.key}`" class="entity-hero__layer" :class="{ 'is-shown': activeFlightPreview === 'cockpit' }" :active="activeFlightPreview === 'cockpit'" :lat="card.lat" :lon="card.lon" :altitude-m="card.altitudeM" :heading="card.heading" :speed-mps="card.speedMps" @failed="onCockpitFailed" />
<div v-if="cockpitKnown || (routeKnown && modelKnown) || (photoAvailable && (routeKnown || modelKnown))" class="entity-card__preview-switch" role="group" :aria-label="t('Preview')">
<button v-if="photoAvailable" type="button" :class="{ active: activeFlightPreview === 'photo' }" :aria-pressed="String(activeFlightPreview === 'photo')" :aria-label="t('Photos')" :title="t('Photos')" @click="choosePreview('photo')"><span class="material-symbols-outlined" aria-hidden="true">photo_camera</span></button>
<button v-if="routeKnown" type="button" :class="{ active: activeFlightPreview === 'route' }" :aria-pressed="String(activeFlightPreview === 'route')" :aria-label="t('Route')" :title="t('Route')" @click="choosePreview('route')"><span class="material-symbols-outlined" aria-hidden="true">timeline</span></button>
<button v-if="modelKnown" type="button" :class="{ active: activeFlightPreview === 'model' }" :aria-pressed="String(activeFlightPreview === 'model')" :title="t('3D model')" @click="choosePreview('model')">{{ t('3D') }}</button>
<button v-if="cockpitKnown" type="button" :class="{ active: activeFlightPreview === 'cockpit' }" :aria-pressed="String(activeFlightPreview === 'cockpit')" :aria-label="t('Cockpit view')" :title="t('Cockpit view')" @click="choosePreview('cockpit')"><span class="material-symbols-outlined" aria-hidden="true">visibility</span></button>
</div>
</template>
<a v-else-if="heroKind === 'photo'" :key="photo.src" class="entity-hero__layer entity-hero__photo is-shown" :href="photo.link || undefined" target="_blank" rel="noopener">
<img :src="photo.src" :alt="t('Photo of {name}', { name: shownTitle })" v-on="{ error: onPhotoError }" />
<small v-if="photo.credit">{{ photo.credit }}</small>
</a>
<SatelliteGroundView v-else-if="heroKind === 'satellite'" :key="`ground-${card.key}`" class="entity-hero__layer is-shown" active :lat="card.lat" :lon="card.lon" />
<CctvPreview v-else-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': props.withContacts || !tiles.length }">
<span class="material-symbols-outlined entity-hero__glyph" aria-hidden="true">{{ card.icon }}</span>
<div v-if="!props.withContacts && tiles.length" class="entity-hero__figures">
<div v-for="fact in tiles" :key="fact.field" class="entity-hero__figure">
<strong>{{ factFigure(fact).number }}<small v-if="factFigure(fact).unit">{{ factFigure(fact).unit }}</small></strong>
<span>{{ factLabel(fact) }}</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.map((warning, index) => sayWords(card.warningWords?.[index], warning)).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" v-show="!props.withContacts" :key="`altitude:${card.key}`" :altitude-m="lost ? null : card.altitudeM" :tick="tick" />
<template v-if="orbitGraphed">
<AltitudeGraph :key="`orbit-altitude:${card.key}`" :altitude-m="lost ? null : card.altitudeM" :tick="tick" unit="km" />
<AltitudeGraph v-if="Number.isFinite(card.speedMps)" :key="`orbit-speed:${card.key}`" :altitude-m="lost ? null : card.speedMps" :tick="tick" unit="km/s" :label="t('Speed')" />
</template>
<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="!props.withContacts && 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>{{ factLabel(fact) }}</span>
<strong>{{ factFigure(fact).number }}<small v-if="factFigure(fact).unit">{{ factFigure(fact).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>{{ factLabel(fact) }}</dt>
<dd>{{ factValue(fact) }}</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" data-entity-cockpit-entry @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>
<slot />
<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" :with-contacts="props.withContacts" />
<p v-if="source" class="entity-card__source">
<span>{{ t('Source') }}</span> {{ source }}<template v-if="ageText"> · {{ ageText }}</template>
</p>
</section>
</Transition>
</template>
+85
View File
@@ -0,0 +1,85 @@
<script setup>
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { formatNumber, t } from '../../../i18n/index.js';
import { ESRI_IMAGERY_CREDIT } from '../../../maps/attribution.js';
import { useEntityCardStore } from '../../stores/entityCard.js';
import PreviewHud from './PreviewHud.vue';
// What the crew sees: the view ahead from the aircraft's own position,
// height and heading, a little nose down, over Esri World Imagery. The
// renderer draws it (the `cardPreviews` hook) only when asked: a still,
// moved along with the craft while it shows. It takes turns with the turning
// model. Speed and altitude ride on tapes either side, as on a head-up
// display: the ticks roll as the figures change, with the figure boxed in
// the middle. Its credit line sits in the corner.
const props = defineProps({
lat: { type: Number, default: null },
lon: { type: Number, default: null },
/** Height above the ellipsoid, metres. */
altitudeM: { type: Number, default: null },
/** Degrees from north. */
heading: { type: Number, default: null },
/** Ground speed, metres a second. */
speedMps: { type: Number, default: null },
/** Whether the view is the one showing. */
active: { type: Boolean, default: false },
});
const emit = defineEmits(['failed']);
const store = useEntityCardStore();
const host = ref(null);
let preview = null;
const craft = () => ({ lat: props.lat, lon: props.lon, altitudeM: props.altitudeM, heading: props.heading });
onMounted(() => {
const previews = store.previews();
if (!previews?.cockpit || !host.value) {
emit('failed');
return;
}
preview = previews.cockpit(host.value, craft(), { onFailed: () => emit('failed') });
preview.setActive(props.active);
});
// While it shows, the view keeps up with the craft as the card refreshes.
watch(
() => [props.lat, props.lon, props.altitudeM, props.heading],
() => preview?.update(craft()),
);
watch(
() => props.active,
(active) => preview?.setActive(active),
);
onBeforeUnmount(() => {
preview?.destroy();
preview = null;
});
// The tapes: one tick every 10 kt and every 100 ft, 8 px apart; the ticks
// roll by the remainder, so a change in the figure moves them.
const TICK_PX = 8;
const knots = computed(() => (Number.isFinite(props.speedMps) ? Math.round(props.speedMps * 1.94384) : null));
const altFeet = computed(() => (Number.isFinite(props.altitudeM) ? Math.round(props.altitudeM * 3.28084) : null));
const feet = computed(() => (altFeet.value === null ? '' : t('{n} ft', { n: formatNumber(Math.round(altFeet.value / 100) * 100) })));
const roll = (value, per) => (value === null ? 0 : ((value % per) / per) * TICK_PX);
const speedRoll = computed(() => `${roll(knots.value, 10)}px`);
const altRoll = computed(() => `${roll(altFeet.value, 100)}px`);
const course = computed(() => (Number.isFinite(props.heading) ? `${String(Math.round(props.heading) % 360).padStart(3, '0')}°` : ''));
</script>
<template>
<div class="flight-cockpit" aria-hidden="true">
<div ref="host" class="flight-cockpit__scene"></div>
<PreviewHud variant="cockpit" :running="active" />
<span class="flight-cockpit__horizon"><i></i></span>
<span v-if="knots !== null" class="flight-cockpit__tape flight-cockpit__tape--speed">
<i class="flight-cockpit__ticks" :style="{ backgroundPositionY: speedRoll }"></i>
<b>{{ formatNumber(knots) }}</b><em>{{ t('KT') }}</em>
</span>
<span v-if="altFeet !== null" class="flight-cockpit__tape flight-cockpit__tape--alt">
<i class="flight-cockpit__ticks" :style="{ backgroundPositionY: altRoll }"></i>
<b>{{ formatNumber(altFeet) }}</b><em>{{ t('FT') }}</em>
</span>
<span class="flight-cockpit__label">{{ t('Cockpit view') }}<strong>{{ [feet, course].filter(Boolean).join(' · ') }}</strong></span>
<span class="flight-cockpit__credit">{{ ESRI_IMAGERY_CREDIT }}</span>
</div>
</template>
+1 -1
View File
@@ -11,6 +11,6 @@ const optional = (value) => value ?? undefined;
<template>
<Teleport to="body">
<div v-for="split in splits" :key="split.key" :id="optional(split.view.id)" :hidden="split.view.hidden"><span class="before" :title="optional(split.view.beforeTitle)">{{ split.view.beforeLabel }}</span><button type="button" :class="optional(split.view.handleClass)" role="slider" :aria-label="optional(split.view.ariaLabel)" aria-valuemin="0" aria-valuemax="100" aria-orientation="horizontal" :aria-valuenow="split.view.valueNow" :aria-valuetext="split.view.valueText" @pointerdown="split.controls.pointerdown($event)" @pointermove="split.controls.pointermove($event)" @pointerup="split.controls.pointerup($event)" @pointercancel="split.controls.pointerup($event)" @keydown="split.controls.keydown($event)">↔</button><span class="after" :title="optional(split.view.afterTitle)">{{ split.view.afterLabel }}</span></div>
<div v-for="split in splits" :key="split.key" :id="optional(split.view.id)" data-globe-overlay :hidden="split.view.hidden"><span class="before" :title="optional(split.view.beforeTitle)">{{ split.view.beforeLabel }}</span><button type="button" :class="optional(split.view.handleClass)" role="slider" :aria-label="optional(split.view.ariaLabel)" aria-valuemin="0" aria-valuemax="100" aria-orientation="horizontal" :aria-valuenow="split.view.valueNow" :aria-valuetext="split.view.valueText" @pointerdown="split.controls.pointerdown($event)" @pointermove="split.controls.pointermove($event)" @pointerup="split.controls.pointerup($event)" @pointercancel="split.controls.pointerup($event)" @keydown="split.controls.keydown($event)">↔</button><span class="after" :title="optional(split.view.afterTitle)">{{ split.view.afterLabel }}</span></div>
</Teleport>
</template>
+93
View File
@@ -0,0 +1,93 @@
<script setup>
import { onBeforeUnmount, onMounted, ref, watch } from 'vue';
// Small moving HUD marks laid over a card's preview, for look only: corner
// brackets, a ruler down the right edge with a marker riding it, a tick
// scale crawling along the bottom, a signal meter and a blinking dot at the
// top right, and a slow dashed ring round the centre with its four ticks.
// The ground view instead lays a square grid over the image, with cells lit
// one by one at random, each fading as the next lights, and a scan line
// sweeping down. Nothing here takes the pointer or says
// anything; it all stops under reduced motion.
const props = defineProps({
/** 'model' over the turning craft, 'ground' over the view beneath. */
variant: { type: String, default: 'model' },
/** Whether the preview is showing; the grid scan steps only while it is. */
running: { type: Boolean, default: true },
});
const CELL = 22;
const STEP_MS = 260;
const TRAIL = 4;
const root = ref(null);
const grid = ref({ cols: 0, rows: 0, left: 0, top: 0 });
const cells = ref([]);
let timer = 0;
let lit = [];
let serial = 0;
function measure() {
const box = root.value?.getBoundingClientRect();
if (!box?.width) return false;
const cols = Math.floor(box.width / CELL);
const rows = Math.floor(box.height / CELL);
// The grid is centred in the view.
grid.value = { cols, rows, left: (box.width - cols * CELL) / 2, top: (box.height - rows * CELL) / 2 };
return cols > 0 && rows > 0;
}
// Each step lights a random cell (never the one just lit) and dims the
// ones before it, so a few faint cells fade out behind the newest.
function step() {
if (!grid.value.cols && !measure()) return;
const { cols, rows, left, top } = grid.value;
let col;
let row;
do {
col = Math.floor(Math.random() * cols);
row = Math.floor(Math.random() * rows);
} while (cols * rows > 1 && lit[0]?.col === col && lit[0]?.row === row);
lit = [{ key: ++serial, col, row }, ...lit].slice(0, TRAIL);
cells.value = lit.map((cell, back) => ({
key: cell.key,
x: left + cell.col * CELL,
y: top + cell.row * CELL,
fade: 1 - back / TRAIL,
}));
}
function sync() {
clearInterval(timer);
timer = 0;
const still = globalThis.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches;
if (props.variant === 'ground' && props.running && !still) {
measure();
timer = setInterval(step, STEP_MS);
}
}
onMounted(sync);
watch(() => props.running, sync);
onBeforeUnmount(() => clearInterval(timer));
</script>
<template>
<div ref="root" class="preview-hud" :class="`preview-hud--${variant}`" aria-hidden="true">
<template v-if="variant === 'ground'">
<span class="preview-hud__grid" :style="{ left: `${grid.left}px`, top: `${grid.top}px`, width: `${grid.cols * CELL}px`, height: `${grid.rows * CELL}px` }"></span>
<i v-for="cell in cells" :key="cell.key" class="preview-hud__cell" :style="{ transform: `translate(${cell.x}px, ${cell.y}px)`, opacity: cell.fade }"></i>
</template>
<i class="preview-hud__corner preview-hud__corner--tl"></i>
<i class="preview-hud__corner preview-hud__corner--tr"></i>
<i class="preview-hud__corner preview-hud__corner--bl"></i>
<i class="preview-hud__corner preview-hud__corner--br"></i>
<span class="preview-hud__ruler"><i></i></span>
<span class="preview-hud__scale"></span>
<span class="preview-hud__meter"><i></i><i></i><i></i><i></i><b></b></span>
<svg class="preview-hud__ring" viewBox="-100 -100 200 200">
<circle r="92" class="preview-hud__dash" />
<path d="M0 -100 V-90 M0 90 V100 M-100 0 H-90 M90 0 H100" class="preview-hud__ticks" />
</svg>
<span v-if="variant === 'ground'" class="preview-hud__sweep"></span>
</div>
</template>
+97
View File
@@ -0,0 +1,97 @@
<script setup>
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { msg, t } from '../../../i18n/index.js';
import { useEntityCardStore } from '../../stores/entityCard.js';
// A flight's route on a small globe of its own at the top of its card: the
// great circle from origin to destination, solid where it has flown and
// dashed ahead, the two airports marked with their codes, and a plane where
// the craft is now, pointing at the destination. The renderer draws it (the
// `cardPreviews` hook); this tile lays the compass over it. The card names
// the airports' cities under its progress bar.
const props = defineProps({
/** `{code, lat, lon}` of the origin airport. */
from: { type: Object, required: true },
/** `{code, lat, lon}` of the destination airport. */
to: { type: Object, required: true },
/** The craft's position now. */
at: { type: Object, default: null },
/** Whether the tile is the one showing; a hidden one stops drawing. */
active: { type: Boolean, default: true },
});
const emit = defineEmits(['failed']);
const store = useEntityCardStore();
const host = ref(null);
const failed = ref(false);
let preview = null;
// A globe that cannot draw tells the card, which then shows another view.
watch(failed, (now) => {
if (!now) return;
preview?.destroy();
preview = null;
emit('failed');
});
const place = (p) => ({ code: p?.code || '', lat: Number(p?.lat), lon: Number(p?.lon) });
const at = () =>
props.at && Number.isFinite(props.at.lat) && Number.isFinite(props.at.lon) ? { lat: props.at.lat, lon: props.at.lon } : null;
const route = () => ({ from: place(props.from), to: place(props.to), at: at() });
/** The initial bearing (degrees from north) of the great circle a → b. */
function bearing(a, b) {
const rad = Math.PI / 180;
const y = Math.sin((b.lon - a.lon) * rad) * Math.cos(b.lat * rad);
const x = Math.cos(a.lat * rad) * Math.sin(b.lat * rad) - Math.sin(a.lat * rad) * Math.cos(b.lat * rad) * Math.cos((b.lon - a.lon) * rad);
return (Math.atan2(y, x) / rad + 360) % 360;
}
// The compass: the view is north up, so N sits at the top; a cyan needle
// shows the course to the destination, with its bearing in degrees.
const course = computed(() => Math.round(bearing(at() || props.from, props.to)) % 360);
const POINTS = [msg('N'), msg('NE'), msg('E'), msg('SE'), msg('S'), msg('SW'), msg('W'), msg('NW')];
const courseLabel = computed(() => `${String(course.value).padStart(3, '0')}° ${t(POINTS[Math.round(course.value / 45) % 8])}`);
onMounted(() => {
const previews = store.previews();
if (!previews?.route || !host.value) {
failed.value = true;
return;
}
preview = previews.route(host.value, route(), { onFailed: () => (failed.value = true) });
preview.setActive(props.active);
});
// Watched as strings: a fresh object each card refresh would count as a
// change every two seconds.
watch(
() => `${props.from?.code}|${props.to?.code}|${props.at?.lat?.toFixed?.(4)}|${props.at?.lon?.toFixed?.(4)}`,
() => preview?.update(route()),
);
watch(
() => props.active,
(active) => preview?.setActive(active),
);
onBeforeUnmount(() => {
preview?.destroy();
preview = null;
});
</script>
<template>
<div v-if="!failed" class="route-globe">
<div ref="host" class="route-globe__scene" aria-hidden="true"></div>
<div class="route-globe__compass" :title="t('Course to {code}: {course}', { code: to.code, course: courseLabel })">
<svg viewBox="-24 -24 48 48" aria-hidden="true">
<circle r="19" class="route-globe__compass-ring" />
<g class="route-globe__compass-ticks">
<line v-for="deg in [0, 45, 90, 135, 180, 225, 270, 315]" :key="deg" :transform="`rotate(${deg})`" y1="-19" :y2="deg % 90 ? -16.5 : -15" />
</g>
<text y="-9.5" class="route-globe__compass-n">{{ t('N') }}</text>
<g :transform="`rotate(${course})`" class="route-globe__compass-needle">
<path d="M0 -14 L3 2 L0 0 L-3 2 Z" />
</g>
<circle r="1.6" class="route-globe__compass-hub" />
</svg>
<span>{{ courseLabel }}</span>
</div>
</div>
</template>
+106
View File
@@ -0,0 +1,106 @@
<script setup>
import { computed, ref, watch } from 'vue';
import { t } from '../../../i18n/index.js';
import { nearestCity } from '../../../data/wikidataCities.js';
import { ESRI_IMAGERY_CREDIT, ESRI_TILES } from '../../../maps/attribution.js';
import PreviewHud from './PreviewHud.vue';
// What lies under a satellite: a dark, grey top-down image of the ground at
// the point beneath it, with rings on that spot. It is a still taken each
// time the view comes round, and its tiles load only while it shows (the craft moves several kilometres a second, so
// a live view would only blur), and it drifts in slowly while it shows.
// Near a town it looks close in, at street-block scale; over open water or
// empty land, where a close view would be a blank, it stands well back so
// coasts and terrain show. The image is Esri World Imagery, the app's
// keyless basemap, from its classic tile endpoint; its credit line sits in
// the corner.
const props = defineProps({
lat: { type: Number, default: null },
lon: { type: Number, default: null },
/** Whether the view is the one showing; each showing takes a new still. */
active: { type: Boolean, default: false },
});
const CLOSE_ZOOM = 13;
const WIDE_ZOOM = 4;
const TILE = 256;
/** The spot the still was taken at, how close it looks and what is near. */
const spot = ref(null);
let taking = 0;
async function take() {
if (!Number.isFinite(props.lat) || !Number.isFinite(props.lon)) return;
const lat = props.lat;
const lon = props.lon;
const turn = ++taking;
spot.value = null;
let city = null;
try {
city = await nearestCity(lat, lon, { radiusKm: 40, nearKm: 15 });
} catch {
city = null;
}
if (turn !== taking) return;
spot.value = { lat, lon, zoom: city ? CLOSE_ZOOM : WIDE_ZOOM, near: city?.name || '' };
}
watch(
() => props.active,
(now) => now && take(),
{ immediate: true },
);
// Web Mercator tile position of the spot, in tiles.
const at = computed(() => {
if (!spot.value) return null;
const n = 2 ** spot.value.zoom;
const lat = Math.max(-85, Math.min(85, spot.value.lat));
const x = ((spot.value.lon + 180) / 360) * n;
const rad = (lat * Math.PI) / 180;
const y = ((1 - Math.log(Math.tan(rad) + 1 / Math.cos(rad)) / Math.PI) / 2) * n;
return { x, y, n, zoom: spot.value.zoom };
});
// A 3 by 3 block of tiles round the spot, placed so the spot is at the centre.
const tiles = computed(() => {
const here = at.value;
if (!here) return [];
const cx = Math.floor(here.x);
const cy = Math.floor(here.y);
const list = [];
for (let dy = -1; dy <= 1; dy++)
for (let dx = -1; dx <= 1; dx++) {
const y = cy + dy;
if (y < 0 || y >= here.n) continue;
const x = (((cx + dx) % here.n) + here.n) % here.n;
list.push({
key: `${x}/${y}`,
src: ESRI_TILES.replace('{z}', here.zoom).replace('{y}', y).replace('{x}', x),
left: (cx + dx - here.x) * TILE,
top: (cy + dy - here.y) * TILE,
});
}
return list;
});
const where = computed(() => {
if (!spot.value) return '';
const { lat, lon } = spot.value;
return `${Math.abs(lat).toFixed(2)}°${lat >= 0 ? 'N' : 'S'} ${Math.abs(lon).toFixed(2)}°${lon >= 0 ? 'E' : 'W'}`;
});
</script>
<template>
<div class="satellite-ground" aria-hidden="true">
<div :key="where" class="satellite-ground__map" :class="{ 'is-drifting': active }">
<img v-for="tile in active ? tiles : []" :key="tile.key" class="satellite-ground__tile" :src="tile.src" alt="" draggable="false" :style="{ transform: `translate(${tile.left}px, ${tile.top}px)` }" />
</div>
<svg class="satellite-ground__rings" viewBox="-100 -100 200 200">
<circle r="88" class="satellite-ground__ring satellite-ground__ring--outer" />
<circle r="56" class="satellite-ground__ring satellite-ground__ring--middle" />
<circle r="34" class="satellite-ground__ring satellite-ground__ring--inner" />
</svg>
<PreviewHud variant="ground" :running="active" />
<span class="satellite-ground__label">{{ spot?.near ? t('Over {place}', { place: spot.near }) : t('Below') }}<strong>{{ where }}</strong></span>
<span class="satellite-ground__credit">{{ ESRI_IMAGERY_CREDIT }}</span>
</div>
</template>
+428
View File
@@ -0,0 +1,428 @@
<script setup>
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { formatNumber, onLocaleChange, 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 { sayWords, 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 },
withContacts: Boolean,
/** 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(() => t('{n} km', { n: formatNumber(radiusKm.value) }));
const radiusIndex = computed(() => Math.max(0, CONTEXT_RADIUS_STEPS.indexOf(radiusKm.value)));
const pickRadius = (index) => setContextRadiusKm(CONTEXT_RADIUS_STEPS[index]);
// Satellite fire hits come only while the FIRMS layer is on (spotConditions.js).
const firesOn = () =>
Boolean((omnibar.controls?.layers() || []).find((layer) => layer.id === HAZARD_LAYER.hotspots)?.enabled);
async function read(lat, lon, { force = false } = {}) {
if (!force && readAt && distanceKm(readAt, { lat, lon }) <= props.settleKm) return;
readAt = { lat, lon };
const mine = ++reading;
const mineHazards = ++readingHazards;
// A forced re-read keeps what is shown until the new reading lands.
if (!force) loading.value = true;
const [nextBrief, nextHazards] = await Promise.all([
regionalBrief(lat, lon, store.readBrief, { force }),
hazardsNear(lat, lon, radiusKm.value, { fires: firesOn(), force }).catch(() => []),
]);
if (reading !== mine) return;
if (nextBrief || !force) 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.
async function rereadHazards(km) {
const at = readAt || { lat: props.lat, lon: props.lon };
const mine = ++readingHazards;
const next = await hazardsNear(at.lat, at.lon, km, { fires: firesOn() }).catch(() => []);
if (readingHazards !== mine) return;
hazards.value = next;
}
watch(radiusKm, (km) => void rereadHazards(km));
// A spot that stays put (a parked selection, a still view) reads its weather,
// news and hazards again once the kept copies are old.
const REREAD_MS = 5 * 60_000;
let rereadTimer = 0;
onMounted(() => {
rereadTimer = setInterval(() => void read(props.lat, props.lon, { force: true }), REREAD_MS);
});
onBeforeUnmount(() => clearInterval(rereadTimer));
// Hazard rows are worded as they are read, so a new language reads them again.
const stopLocale = onLocaleChange(() => void rereadHazards(radiusKm.value));
// 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);
stopLocale();
});
// 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, sayWords(alert.words, alert.text), 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 merged card gets these cohorts and their coverage from Awareness.
const CONTACT_LAYERS = ['flights', 'military', 'ais-live-vessels', 'military-installations'];
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,
excludeLayers: props.withContacts ? CONTACT_LAYERS : undefined,
query: contextNeedle.value,
});
});
const trafficBlocks = computed(() => {
if (!groups.value) return [];
if (props.withContacts)
return groups.value.flights.count
? [{ id: 'local-adsb', icon: 'flight', title: t('Local ADS-B'), ...groups.value.flights }]
: [];
return [
{ 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 speed = t('{n} km/h', { n: formatNumber(round(now.windKph)) });
facts.push({
label: t('Wind'),
value: Number.isFinite(now.windDirectionDeg) ? t('{speed} {direction}', { speed, direction: t(compassName(now.windDirectionDeg)) }) : speed,
});
}
if (Number.isFinite(now.cloudCoverPct)) facts.push({ label: t('Cloud'), value: t('{n}%', { n: formatNumber(round(now.cloudCoverPct)) }) });
if (Number.isFinite(now.visibilityM))
facts.push({
label: t('Visibility'),
value: t('{n} km', {
n: formatNumber(now.visibilityM >= 10_000 ? round(now.visibilityM / 1000) : Number((now.visibilityM / 1000).toFixed(1))),
}),
});
if (Number.isFinite(now.precipitationMm))
facts.push({
label: t('Rain'),
value: t('{n} mm', { n: formatNumber(now.precipitationMm, { minimumFractionDigits: 1, maximumFractionDigits: 1 }) }),
});
return facts;
});
const articles = computed(() =>
props.entity ? [] : (brief.value?.articles || []).filter((article) => matchesContextSearch(article.title, article.domain)).slice(0, 3),
);
const distance = (km) =>
t('{n} km', { n: km < 10 ? formatNumber(km, { minimumFractionDigits: 1, maximumFractionDigits: 1 }) : formatNumber(Math.round(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];
}),
);
});
// Turning FIRMS on or off adds or drops its fire hits at once.
watch(
() => Boolean(hazardLayers.value.hotspots?.on),
() => void rereadHazards(radiusKm.value),
);
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) }} {{ t(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">{{ sayWords(alert.words, 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">{{ shownLayerName(item.layerName, item.layerId) }}</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: t(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">{{ t(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' }]"
>{{ t(c.k) }}</text>
</g>
</svg>
<figcaption>{{ caption }}</figcaption>
</figure>
</template>
+412
View File
@@ -0,0 +1,412 @@
<script setup>
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { storeToRefs } from 'pinia';
import { contextNeedle, contextSearchText, matchesContextSearch } from '../../contextSearch.js';
import { formatNumber, t, tn } 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();
// What a moving item is doing, as the layer's own display shows it (transit
// vehicles report it): an icon on its row, its words on hover.
const MOTION_STATES = {
moving: { icon: 'play_arrow', label: () => t('Moving') },
stopped: { icon: 'pause', label: () => t('Stopped', { context: 'vehicle motion' }) },
waiting: { icon: 'schedule', label: () => t('Waiting for update') },
'no-fix': { icon: 'location_off', label: () => t('No recent fix') },
};
const motionOf = (item) => MOTION_STATES[item.identity?.record?.motion] || null;
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 = tn(total.value, '{count} thing', '{count} things');
const layers = tn(groups.value.length, '{count} layer', '{count} layers');
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: formatNumber(Math.round(m / 1000)) })
: t('{n} m up', { n: formatNumber(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) {
// Forget the last place too, so coming back down reads it again.
townsFor = '';
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: formatNumber(found.total), total: formatNumber(loaded) })
: t('Of all {n}', { n: formatNumber(found.total) })
: t('Of {n} in view', { n: formatNumber(found.total) });
return {
basis,
splits: found.splits.map((split) => ({
title: t(split.title),
parts: split.parts.map((part, index) => ({
label: t(part.label),
count: formatNumber(part.count),
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: formatNumber(Math.round(km * 1000)) })
: t('{n} km', { n: formatNumber(km < 10 ? Number(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 ? '…' : formatNumber(tile.count)) : 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: formatNumber(layer.total) }) }} · </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>{{ shownLayerName(group.layerName, group.layerId) }}</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
v-if="motionOf(item)"
class="material-symbols-outlined view-context__row-motion"
:data-motion="item.identity.record.motion"
:title="motionOf(item).label()"
role="img"
:aria-label="motionOf(item).label()"
>{{ motionOf(item).icon }}</span>
<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>
+765
View File
@@ -0,0 +1,765 @@
<script setup>
import {
computed,
nextTick,
onBeforeUnmount,
onMounted,
ref,
watch,
} from 'vue';
import { storeToRefs } from 'pinia';
import { t, tn } from '../../../i18n/index.js';
import { useStoriesStore } from '../../stores/stories.js';
import {
FILTERS,
clamp,
fmtDur,
layersFor,
metaFor,
topicsOf,
storyText,
windowText,
} from '../../../stories/storyMeta.js';
import StoriesHeader from './StoriesHeader.vue';
/**
* Explore (prototype `.scr-explore`): the feed beside GEV's Cesium globe,
* which shows through the map area and takes input where nothing of
* Stories sits on it.
*/
const emit = defineEmits(['play']);
const store = useStoriesStore();
const { query, chips, sort, filters, picked, pins, feedSnap } =
storeToRefs(store);
const all = computed(() => store.stories);
// A story's card picture, when there is one; otherwise the card shows its
// placeholder (CSS), never a broken image.
const thumbFor = (s) => (s && store.thumbs?.[s.id]) || '';
const titleOf = (s) => storyText(s.title);
const layerNames = (s) => layersFor(s).map((l) => storyText(l[2]));
// What a story is found by in the feed's search, in the page's language.
function searchText(s) {
const m = metaFor(s);
return [
titleOf(s),
s.creator,
windowText(s),
m.region,
m.place,
...m.topics,
...layerNames(s),
]
.join(' ')
.toLowerCase();
}
const shown = computed(() => {
const words = query.value.toLowerCase().split(/\s+/).filter(Boolean);
const f = filters.value;
const list = all.value.filter((s) => {
const m = metaFor(s);
const txt = searchText(s);
if (words.some((w) => !txt.includes(w))) return false;
if (chips.value.length && !chips.value.some((c) => m.topics.includes(c)))
return false;
if (f.region?.length && !f.region.includes(m.region)) return false;
if (
f.length?.length &&
!f.length.includes(s.durationMs < 60000 ? 'short' : 'long')
)
return false;
return true;
});
const end = (s) => s.tMaxMs ?? 0;
const by = {
new: (a, b) => end(b) - end(a),
long: (a, b) => b.durationMs - a.durationMs,
az: (a, b) => titleOf(a).localeCompare(titleOf(b)),
}[sort.value];
return [...list].sort(by);
});
const shownIds = computed(() => new Set(shown.value.map((s) => s.id)));
const count = computed(() =>
shown.value.length === all.value.length
? `${all.value.length}`
: `${shown.value.length}/${all.value.length}`,
);
// ── Chips and filters ──
// Every story is a GEV scene: a "made with" filter would not narrow anything.
// The topic chips and region choices are the ones the stories carry, so
// none of them narrows the feed to nothing.
const topics = computed(() => topicsOf(all.value));
const filterGroups = computed(() =>
FILTERS.map(([key, label, opts]) => {
if (key !== 'region') return [key, label, opts];
const regions = new Set(all.value.map((s) => metaFor(s).region));
return [key, label, opts.filter(([value]) => regions.has(value))];
}).filter(([, , opts]) => opts.length > 1),
);
function toggleChip(c) {
if (!c) chips.value = [];
else if (chips.value.includes(c))
chips.value = chips.value.filter((x) => x !== c);
else chips.value = [...chips.value, c];
}
const filterOpen = ref(false);
const filterCount = computed(() =>
filterGroups.value.reduce(
(n, [key]) => n + (filters.value[key]?.length ?? 0),
0,
),
);
function toggleFilter(key, value, on) {
const list = filters.value[key] ?? [];
filters.value = {
...filters.value,
[key]: on ? [...list, value] : list.filter((v) => v !== value),
};
}
function clearFilters() {
filters.value = { region: [], length: [] };
}
function resetAll() {
clearFilters();
chips.value = [];
query.value = '';
filterOpen.value = false;
}
const filterEl = ref(null);
const filterBtn = ref(null);
function onDocDown(e) {
if (
filterOpen.value &&
!filterEl.value?.contains(e.target) &&
!filterBtn.value?.contains(e.target)
)
filterOpen.value = false;
}
// ── Search ──
const searchEl = ref(null);
function onSearchKey(e) {
if (e.key === 'Escape') {
query.value = '';
e.target.blur();
e.preventDefault();
} else if (e.key === 'Enter') {
const first = shown.value[0];
if (first) pick(first.id);
}
}
function onSlash(e) {
if (
e.key === '/' &&
!/INPUT|TEXTAREA|SELECT/.test(document.activeElement?.tagName ?? '')
) {
e.preventDefault();
searchEl.value?.focus();
}
}
function headerSearch() {
if (feedSnap.value === 'map') setFeed('split');
searchEl.value?.focus();
}
// ── Picking and playing ──
const feedEl = ref(null);
function pick(id) {
if (picked.value === id) return;
if (innerWidth <= 720 && feedSnap.value === 'list') setFeed('split');
store.controller.pick(id);
nextTick(() =>
feedEl.value
?.querySelector(`.card[data-id="${CSS.escape(id)}"]`)
?.scrollIntoView({ block: 'nearest', behavior: 'smooth' }),
);
}
function play(id, from) {
emit('play', { id, from });
}
function onCardKey(e, s) {
if ((e.key === 'Enter' || e.key === ' ') && e.target === e.currentTarget) {
e.preventDefault();
if (picked.value === s.id)
play(s.id, e.currentTarget.querySelector('.thumb'));
else pick(s.id);
}
}
// The pin last clicked: a pin plays on its own second click, so a story
// picked from the feed first shows its play button on the pin.
let armedPin = null;
watch(picked, (id) => {
if (id !== armedPin) armedPin = null;
});
function onPin(e, id) {
if (picked.value === id && armedPin === id)
play(id, e.currentTarget.querySelector('.pin-thumb'));
else {
armedPin = id;
if (picked.value !== id) pick(id);
}
}
const pickedStory = computed(() =>
picked.value ? store.byId(picked.value) : null,
);
// ── Pins: projected into the map area ──
const placedPins = computed(() =>
pins.value.map((p) => ({
...p,
story: store.byId(p.id),
style: {
transform: `translate(${p.x}px, ${p.y}px) translate(-50%, -100%)`,
},
})),
);
// ── Phone: drag the list header to trade globe space for list space ──
const FEED = { map: 0.3, split: 0.56, list: 0.86 };
const FEED_ORDER = ['map', 'split', 'list'];
const bodyEl = ref(null);
const dragging = ref(false);
const feedH = ref(null);
function setFeed(snap) {
feedSnap.value = snap;
feedH.value = null;
setTimeout(() => store.controller.reframe(), 320);
}
let fd = null;
function onHeadDown(e) {
if (innerWidth > 720 || e.target.closest('.fh-tools')) return;
try {
e.currentTarget.setPointerCapture(e.pointerId);
} catch {
/* nothing to capture */
}
const body = bodyEl.value;
fd = {
y: e.clientY,
frac: body.querySelector('.ex-feed').offsetHeight / body.clientHeight,
H: body.clientHeight,
lastY: e.clientY,
lastT: performance.now(),
v: 0,
moved: false,
};
}
function onHeadMove(e) {
if (!fd) return;
const dy = e.clientY - fd.y;
if (!fd.moved && Math.abs(dy) > 4) {
fd.moved = true;
dragging.value = true;
}
if (!fd.moved) return;
feedH.value = clamp(fd.frac - dy / fd.H, 0.18, 0.9);
const now = performance.now();
fd.v = (e.clientY - fd.lastY) / Math.max(1, now - fd.lastT);
fd.lastY = e.clientY;
fd.lastT = now;
}
function onHeadUp() {
if (!fd) return;
if (fd.moved) {
const f = feedH.value ?? FEED[feedSnap.value];
let snap;
if (fd.v < -0.5) snap = f < FEED.split ? 'split' : 'list';
else if (fd.v > 0.5) snap = f > FEED.split ? 'split' : 'map';
else
snap = FEED_ORDER.reduce((a, b) =>
Math.abs(FEED[b] - f) < Math.abs(FEED[a] - f) ? b : a,
);
dragging.value = false;
setFeed(snap);
} else setFeed(FEED_ORDER[(FEED_ORDER.indexOf(feedSnap.value) + 1) % 3]);
fd = null;
}
function onGripKey(e) {
const i = FEED_ORDER.indexOf(feedSnap.value);
if (e.key === 'ArrowUp') {
e.preventDefault();
setFeed(FEED_ORDER[Math.min(2, i + 1)]);
} else if (e.key === 'ArrowDown') {
e.preventDefault();
setFeed(FEED_ORDER[Math.max(0, i - 1)]);
} else if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
setFeed(FEED_ORDER[(i + 1) % 3]);
}
}
// Desktop and tablet: drag the feed's right edge to widen it, up to 50 px
// past its default; double-click puts it back.
const FEED_W = 340;
const FEED_W_MAX = FEED_W + 50;
const FEED_W_MIN = 280;
const feedW = ref(FEED_W);
try {
const saved = +localStorage.getItem('gevFeedW');
if (saved) feedW.value = clamp(saved, FEED_W_MIN, FEED_W_MAX);
} catch {
/* storage off: the default width */
}
// The feed sits over the map on desktop: a new width moves the free part of
// the map, which a resize of the map itself would not report.
watch(feedW, () => nextTick(() => store.controller.reframe()));
const resizing = ref(false);
let rw = null;
function setFeedW(px) {
feedW.value = Math.round(clamp(px, FEED_W_MIN, FEED_W_MAX));
try {
localStorage.setItem('gevFeedW', feedW.value);
} catch {
/* storage off: the width lasts this visit */
}
}
function onResizeDown(e) {
try {
e.currentTarget.setPointerCapture(e.pointerId);
} catch {
/* nothing to capture */
}
rw = { x: e.clientX, w: feedW.value };
resizing.value = true;
e.preventDefault();
}
function onResizeMove(e) {
if (rw) setFeedW(rw.w + (e.clientX - rw.x));
}
function onResizeUp() {
rw = null;
resizing.value = false;
}
function onResizeKey(e) {
const d = { ArrowRight: 10, ArrowLeft: -10 }[e.key];
if (!d) return;
e.preventDefault();
setFeedW(feedW.value + d);
}
function onResizeReset() {
feedW.value = FEED_W;
try {
localStorage.removeItem('gevFeedW');
} catch {
/* storage off */
}
}
const bodyStyle = computed(() => ({
'--feed-h': `${(feedH.value ?? FEED[feedSnap.value]) * 100}%`,
...(innerWidth > 720
? {
'--feedw': `${feedW.value}px`,
gridTemplateColumns: `${feedW.value}px minmax(0, 1fr)`,
}
: {}),
}));
onMounted(() => {
document.addEventListener('pointerdown', onDocDown);
// On the window: the Stories keyboard guard stops keys before the document.
addEventListener('keydown', onSlash, true);
});
onBeforeUnmount(() => {
document.removeEventListener('pointerdown', onDocDown);
removeEventListener('keydown', onSlash, true);
});
defineExpose({
cardThumb: (id) =>
feedEl.value?.querySelector(`.card[data-id="${CSS.escape(id)}"]`),
});
</script>
<template>
<section
id="scrExplore"
class="scr scr-explore"
:aria-label="t('GEV Stories explore')"
>
<StoriesHeader
screen="explore"
@back="store.controller.close()"
@home="store.controller.close()"
@search="headerSearch"
/>
<div
id="exBody"
ref="bodyEl"
class="ex-body"
:class="{ 'feed-dragging': dragging }"
data-side="left"
:style="bodyStyle"
>
<div
class="ex-feed-resize"
:class="{ on: resizing }"
role="separator"
aria-orientation="vertical"
:aria-label="t('Resize story list')"
:aria-valuenow="feedW"
:aria-valuemin="FEED_W_MIN"
:aria-valuemax="FEED_W_MAX"
tabindex="0"
:style="{ left: `${feedW - 5}px` }"
@pointerdown="onResizeDown"
@pointermove="onResizeMove"
@pointerup="onResizeUp"
@pointercancel="onResizeUp"
@dblclick="onResizeReset"
@keydown="onResizeKey"
></div>
<aside class="ex-feed" :aria-label="t('Stories')">
<div class="ex-feed-top">
<div
id="feedHead"
class="ex-feed-head"
@pointerdown="onHeadDown"
@pointermove="onHeadMove"
@pointerup="onHeadUp"
@pointercancel="onHeadUp"
>
<button
id="feedGrip"
class="feed-grip"
type="button"
:aria-label="t('Story list size. Drag, or press to change')"
@keydown="onGripKey"
></button>
<h1>{{ t('GEV Stories') }}</h1>
<span
id="exCount"
:aria-label="
tn(
all.length,
'{n} of {count} story',
'{n} of {count} stories',
{
n: shown.length,
},
)
"
>{{ count }}</span
>
<div class="fh-tools">
<label class="sr" for="exSort">{{ t('Sort stories') }}</label>
<select id="exSort" v-model="sort" class="fh-sort">
<option value="new">{{ t('Newest') }}</option>
<option value="long">{{ t('Longest') }}</option>
<option value="az">{{ t('A–Z') }}</option>
</select>
<button
id="exFilterBtn"
ref="filterBtn"
type="button"
class="fh-filter"
:class="{ on: filterCount }"
:aria-expanded="filterOpen"
aria-controls="exFilter"
:aria-label="
filterCount
? tn(filterCount, '{count} filter on', '{count} filters on')
: t('Filters')
"
@click.stop="filterOpen = !filterOpen"
>
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.9"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M4 6h16M7 12h10M10 18h4" />
</svg>
<b v-if="filterCount" id="exFilterN">{{ filterCount }}</b>
</button>
</div>
</div>
<div id="exTools" class="ex-tools" @pointerdown.stop @wheel.stop>
<div class="fh-search m-only-search" role="search">
<label class="sr" for="exQm">{{ t('Search stories') }}</label>
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
aria-hidden="true"
>
<circle cx="11" cy="11" r="6.5" />
<path d="m16 16 4.5 4.5" />
</svg>
<input
id="exQm"
ref="searchEl"
v-model="query"
class="ex-q"
type="search"
:placeholder="t('Search stories, places, creators')"
autocomplete="off"
@keydown="onSearchKey"
/>
<button
v-if="query"
type="button"
class="ex-qx"
:aria-label="t('Clear search')"
@click="
query = '';
searchEl?.focus();
"
>
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2.2"
stroke-linecap="round"
aria-hidden="true"
>
<path d="M6 6l12 12M18 6 6 18" />
</svg>
</button>
<kbd class="hide-m">/</kbd>
</div>
<div class="fh-row">
<div
id="exChips"
class="fh-chips"
role="group"
:aria-label="t('Topics')"
>
<button
type="button"
class="chip"
:aria-pressed="!chips.length"
@click="toggleChip('')"
>{{ t('All') }}</button
>
<button
v-for="c in topics"
:key="c"
type="button"
class="chip"
:aria-pressed="chips.includes(c)"
@click="toggleChip(c)"
>{{ t(c) }}</button
>
</div>
</div>
<div
v-if="filterOpen"
id="exFilter"
ref="filterEl"
class="ex-filter"
role="dialog"
:aria-label="t('Filter stories')"
>
<fieldset v-for="[key, label, opts] in filterGroups" :key="key">
<legend>{{ t(label) }}</legend>
<label v-for="[value, text] in opts" :key="value" class="fopt">
<input
type="checkbox"
:checked="filters[key]?.includes(value)"
@change="toggleFilter(key, value, $event.target.checked)"
/>
<span>{{ t(text) }}</span>
</label>
</fieldset>
<div class="fact">
<button type="button" class="tbtn" @click="clearFilters">{{
t('Clear')
}}</button>
<button
type="button"
class="tbtn solid"
@click="
filterOpen = false;
filterBtn?.focus();
"
>
{{
tn(
shown.length,
'Show {count} story',
'Show {count} stories',
)
}}
</button>
</div>
</div>
</div>
</div>
<ul id="feed" ref="feedEl" class="feed">
<li v-if="!shown.length" class="feed-empty">
<b>{{ t('No stories match') }}</b>
<span>{{ t('Try another word or clear the filters.') }}</span>
<button type="button" class="tbtn" @click="resetAll">{{
t('Clear all')
}}</button>
</li>
<li v-for="s in shown" :key="s.id">
<div
class="card"
role="button"
tabindex="0"
:data-id="s.id"
:aria-pressed="picked === s.id"
@click="pick(s.id)"
@keydown="onCardKey($event, s)"
>
<span class="thumb">
<img
v-if="thumbFor(s)"
:src="thumbFor(s)"
alt=""
loading="lazy"
/>
<span class="chip">{{
s.draft ? t('DRAFT') : t('STORY')
}}</span>
<span class="dur">{{ fmtDur(s.durationMs) }}</span>
<button
class="thumb-play"
type="button"
:aria-label="t('Play {title}', { title: titleOf(s) })"
@click.stop="play(s.id, $event.currentTarget.parentElement)"
>
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M9 6.5v11l9-5.5z" fill="currentColor" />
</svg>
</button>
</span>
<span class="c-title">{{ titleOf(s) }}</span>
<span class="c-meta">{{ s.creator }} · {{ windowText(s) }}</span>
<span class="c-layers"
><span v-for="l in layerNames(s)" :key="l">{{ l }}</span></span
>
<span class="c-play">
<button
class="tbtn solid"
type="button"
@click.stop="
play(
s.id,
$event.currentTarget
.closest('.card')
.querySelector('.thumb'),
)
"
>
<svg viewBox="0 0 24 24" fill="currentColor">
<path d="M7 4.5v15l12.5-7.5z" /></svg
>{{ t('Play story') }}
</button>
</span>
</div>
</li>
</ul>
</aside>
<div class="ex-map">
<div class="map-slot"></div>
<div id="pins" class="pins">
<button
v-for="p in placedPins"
:key="p.id"
class="pin"
:class="{ out: !shownIds.has(p.id), hidden: !p.visible }"
type="button"
:data-id="p.id"
:aria-pressed="picked === p.id"
:aria-label="t('Preview {title}', { title: titleOf(p.story) })"
:style="p.style"
@click="onPin($event, p.id)"
>
<span
class="pin-thumb"
:data-preview="t('Click to preview')"
:data-play="t('Click to play')"
:data-tap="t('Tap to play')"
:data-play-short="t('Play')"
><img v-if="thumbFor(p.story)" :src="thumbFor(p.story)" alt=""
/></span>
<span class="pin-lbl">{{ titleOf(p.story).split(':')[0] }}</span>
<span class="pin-dot"></span>
</button>
</div>
<div class="ex-msearch glass" role="search">
<label class="sr" for="exQ">{{ t('Search stories') }}</label>
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
aria-hidden="true"
>
<circle cx="11" cy="11" r="6.5" />
<path d="m16 16 4.5 4.5" />
</svg>
<input
id="exQ"
v-model="query"
class="ex-q"
type="search"
:placeholder="t('Search stories, places, creators')"
autocomplete="off"
@keydown="onSearchKey"
/>
<button
v-if="query"
type="button"
class="ex-qx"
:aria-label="t('Clear search')"
@click="query = ''"
>
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2.2"
stroke-linecap="round"
aria-hidden="true"
>
<path d="M6 6l12 12M18 6 6 18" />
</svg>
</button>
<kbd>/</kbd>
</div>
<div
v-if="pickedStory"
id="exPreview"
class="ex-preview glass"
aria-live="polite"
>
<span class="k"><i></i>{{ t('PREVIEW') }}</span>
<h2>{{ titleOf(pickedStory) }}</h2>
<span class="c-meta"
>{{ pickedStory.creator }} · {{ windowText(pickedStory) }}</span
>
<span class="c-layers"
><span v-for="l in layerNames(pickedStory)" :key="l">{{
l
}}</span></span
>
<button
class="tbtn solid"
type="button"
@click="play(pickedStory.id, null)"
>
<svg viewBox="0 0 24 24" fill="currentColor">
<path d="M7 4.5v15l12.5-7.5z" /></svg
>{{ t('Play story') }}
</button>
</div>
<div v-else class="ex-hint glass">{{
t('Pick a story or a pin to preview it here')
}}</div>
</div>
</div>
</section>
</template>
+192
View File
@@ -0,0 +1,192 @@
<script setup>
import {
computed,
nextTick,
onBeforeUnmount,
onMounted,
ref,
watch,
} from 'vue';
import { t } from '../../../i18n/index.js';
import { useStoriesStore } from '../../stores/stories.js';
/**
* The Stories top bar (prototype `.h-top.s-head`): back, GEV logo and
* wordmark, breadcrumb, the phone title (scrolls when it is too long) and
* the right-hand buttons.
*/
const props = defineProps({
screen: { type: String, required: true },
title: { type: String, default: '' },
});
const emit = defineEmits(['back', 'home', 'crumb', 'search']);
const store = useStoriesStore();
// A scene saved on this device only: a link to it opens nothing elsewhere.
const localOnly = computed(
() =>
!!store.byId(props.screen === 'story' ? store.storyId : store.picked)?.mine,
);
async function share() {
const what = props.screen === 'story' ? t('Story') : t('Stories');
const url = store.controller.shareLink();
try {
await navigator.clipboard.writeText(url);
store.flashToast(t('{what} link copied', { what }));
} catch {
store.flashToast(t('Copy this link: {url}', { url }), 4000);
}
}
// Long titles scroll gently so the whole name can be read.
const mtitle = ref(null);
const back = ref(null);
const trail = ref(null);
let observer = null;
function fitTitle() {
const el = mtitle.value;
const sp = el?.firstElementChild;
if (!sp) return;
const over = sp.scrollWidth - el.clientWidth;
el.classList.toggle('marquee', over > 4);
el.style.setProperty('--mq', `${-(over + 22)}px`);
el.style.setProperty('--mq-dur', `${Math.max(5, (over + 22) / 22)}s`);
}
onMounted(() => {
const target = back.value?.getClientRects().length
? back.value
: trail.value?.querySelector('button');
target?.focus({ preventScroll: true });
if (globalThis.ResizeObserver && mtitle.value) {
observer = new ResizeObserver(fitTitle);
observer.observe(mtitle.value);
}
fitTitle();
});
watch(
() => props.title,
() => nextTick(fitTitle),
);
onBeforeUnmount(() => observer?.disconnect());
</script>
<template>
<header class="h-top s-head">
<button
ref="back"
class="s-back glass"
type="button"
:aria-label="
screen === 'story' ? t('Back to stories') : t('Back to the globe')
"
@click="emit('back')"
>
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M15 6l-6 6 6 6" />
</svg>
</button>
<div class="h-brand">
<div class="h-brand-row">
<button
class="s-home"
type="button"
:aria-label="t('Back to the globe')"
@click="emit('home')"
>
<svg class="eye" viewBox="0 0 775 520" aria-hidden="true">
<use href="#gevLogo" />
</svg>
</button>
<span class="h-word" translate="no">GOD'S EYE <b>VIEW</b></span>
</div>
<nav ref="trail" class="h-tag s-trail" :aria-label="t('Breadcrumb')">
<template v-if="screen === 'explore'">
<button type="button" @click="emit('home')">{{ t('Globe') }}</button>
<span aria-hidden="true">/</span>
<b>{{ t('Stories') }}</b>
</template>
<template v-else>
<button type="button" @click="emit('crumb')">{{
t('Stories')
}}</button>
<span aria-hidden="true">/</span>
<b>{{ title }}</b>
</template>
</nav>
</div>
<span ref="mtitle" class="s-mtitle glass"
><span>{{ screen === 'explore' ? t('Stories') : title }}</span></span
>
<div class="h-right">
<button
v-if="screen === 'explore'"
class="s-msearch ibtn"
type="button"
:aria-label="t('Search')"
@click="emit('search')"
>
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
>
<circle cx="11" cy="11" r="6.5" />
<path d="m16 16 4.5 4.5" />
</svg>
</button>
<button
v-if="!localOnly"
class="tbtn hide-m"
type="button"
:aria-label="t('Share')"
@click="share"
>
<span class="share-icon" aria-hidden="true">&#x1F517;</span>
<span>{{ t('Share') }}</span>
</button>
<button
v-if="screen === 'explore'"
class="tbtn accent hide-m"
type="button"
@click="emit('home')"
>
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.8"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M19 12H5M11 6l-6 6 6 6" />
</svg>
<span>{{ t('Back to GEV') }}</span>
</button>
<button
v-else
class="tbtn accent hide-m gs-back-stories"
type="button"
@click="emit('crumb')"
>
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.8"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M19 12H5M11 6l-6 6 6 6" />
</svg>
<span>{{ t('GEV Stories') }}</span>
</button>
</div>
</header>
</template>
+412
View File
@@ -0,0 +1,412 @@
<script setup>
import { computed, ref } from 'vue';
import { storeToRefs } from 'pinia';
import { t, tn } from '../../../i18n/index.js';
import { useStoriesStore } from '../../stores/stories.js';
import { chapterAt } from '../../../stories/format.js';
import {
anchorStamp,
chapterStamp,
chapterTitle,
clamp,
nowFacts,
storyText,
windowText,
} from '../../../stories/storyMeta.js';
/**
* The context panel (prototype `.st-ctx`): docked on the right on desktop,
* a sheet that peeks above the timeline on a phone. It shows what a GEV
* scene carries: right-now facts, chapters, key moments, sources and
* background, with a search over its chapters, key moments and sources.
*/
const props = defineProps({
story: { type: Object, required: true },
nudge: Boolean,
});
const emit = defineEmits(['chapter', 'anchor', 'open', 'hide']);
const store = useStoriesStore();
const { playback, sheet } = storeToRefs(store);
const k = computed(() => chapterAt(props.story, playback.value.wallMs));
const chTitle = (c) => chapterTitle(props.story, c);
const events = computed(() => props.story.events ?? []);
// The background in the page's language: one text, or parts (a shipped
// scene's layers) translated one by one.
const background = computed(() =>
[]
.concat(props.story.background || [])
.map((part) => storyText(part))
.join(' '),
);
const stamp = (ms) => anchorStamp(props.story, ms);
const facts = computed(() => nowFacts(props.story));
const peekFacts = computed(() => facts.value.slice(0, 3));
const sheetSum = computed(
() =>
`${k.value + 1}/${props.story.chapters.length} · ${chTitle(props.story.chapters[k.value])} · ${tn(props.story.sources.length, '{count} source', '{count} sources')}`,
);
const titleOf = (s) => storyText(s.title);
const related = computed(() =>
store.stories.filter((x) => x.id !== props.story.id).slice(0, 3),
);
// A related story's card picture, when there is one (CSS draws a placeholder).
const thumbOf = (s) => store.thumbs?.[s.id] || '';
// ── Search this story: its chapters, key moments and sources ──
const GLYPH = { ch: '#', ev: '•', src: '↗' };
const query = ref('');
const active = ref(-1);
const results = computed(() => {
const q = query.value.trim().toLowerCase();
if (!q) return null;
const hit = (x) => `${x.title} ${x.sub}`.toLowerCase().includes(q);
const chs = props.story.chapters
.map((c, i) => ({
type: 'ch',
k: i,
title: chTitle(c),
sub: `${t('Chapter {n}', { n: i + 1 })} · ${chapterStamp(props.story, c)}`,
}))
.filter(hit);
const evs = events.value
.map((ev, i) => ({
type: 'ev',
k: i,
ev,
title: storyText(ev.label),
sub: `${t('Key moments')} · ${stamp(ev.wallMs)}`,
}))
.filter(hit);
const srcs = props.story.sources
.map((x) => ({
type: 'src',
href: x[2],
title: storyText(x[0]),
sub: storyText(x[1]),
}))
.filter(hit);
return [...chs, ...evs, ...srcs].slice(0, 9);
});
function onQuery() {
active.value = results.value?.length ? 0 : -1;
}
function choose(x) {
if (!x) return;
query.value = '';
if (x.type === 'ch') emit('chapter', x.k);
else if (x.type === 'ev') emit('anchor', x.ev);
else if (x.type === 'src' && x.href && x.href !== '#')
window.open(x.href, '_blank', 'noopener');
}
function onSearchKey(e) {
const list = results.value ?? [];
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
e.preventDefault();
if (!list.length) return;
active.value =
(active.value + (e.key === 'ArrowDown' ? 1 : -1) + list.length) %
list.length;
} else if (e.key === 'Enter') {
e.preventDefault();
choose(list[active.value]);
} else if (e.key === 'Escape') query.value = '';
}
// ── Phone sheet: follows the finger, snaps to peek / half / full ──
const SNAPS = ['peek', 'half', 'full'];
const el = ref(null);
const dragH = ref(null);
const dragging = ref(false);
let sd = null;
function heights() {
const H = el.value?.closest('.st-body')?.clientHeight || innerHeight;
return { peek: 100, half: H * 0.54, full: H * 0.88, H };
}
function setSheet(s) {
sheet.value = s;
dragH.value = null;
setTimeout(() => store.controller.reframe(), 320);
}
function onHandleDown(e) {
if (innerWidth > 720) return;
try {
e.currentTarget.setPointerCapture(e.pointerId);
} catch {
/* nothing to capture */
}
sd = {
y: e.clientY,
h: el.value.offsetHeight,
lastY: e.clientY,
lastT: performance.now(),
v: 0,
moved: false,
};
}
function onHandleMove(e) {
if (!sd) return;
const dy = e.clientY - sd.y;
if (!sd.moved && Math.abs(dy) > 4) {
sd.moved = true;
dragging.value = true;
}
if (!sd.moved) return;
dragH.value = clamp(sd.h - dy, 100, heights().H * 0.92);
const now = performance.now();
sd.v = (e.clientY - sd.lastY) / Math.max(1, now - sd.lastT);
sd.lastY = e.clientY;
sd.lastT = now;
}
let justDragged = false;
function onHandleUp() {
if (!sd) return;
if (sd.moved) {
const hs = heights();
const h = dragH.value ?? hs[sheet.value];
let target;
if (sd.v < -0.5) target = h < hs.half ? 'half' : 'full';
else if (sd.v > 0.5) target = h > hs.half ? 'half' : 'peek';
else
target = SNAPS.reduce((a, b) =>
Math.abs(hs[b] - h) < Math.abs(hs[a] - h) ? b : a,
);
dragging.value = false;
justDragged = true;
setSheet(target);
}
sd = null;
}
function onHandleClick() {
if (justDragged) {
justDragged = false;
return;
}
setSheet(SNAPS[(SNAPS.indexOf(sheet.value) + 1) % 3]);
}
function onHandleKey(e) {
const i = SNAPS.indexOf(sheet.value);
if (e.key === 'ArrowUp') {
e.preventDefault();
setSheet(SNAPS[Math.min(2, i + 1)]);
} else if (e.key === 'ArrowDown') {
e.preventDefault();
setSheet(SNAPS[Math.max(0, i - 1)]);
}
}
defineExpose({ dragging });
</script>
<template>
<aside
id="stCtx"
ref="el"
class="st-ctx"
:class="{ nudge }"
:aria-label="t('Context')"
:style="dragH != null ? { height: `${dragH}px` } : null"
>
<button
id="sheetHandle"
class="sheet-handle"
type="button"
:aria-expanded="sheet !== 'peek'"
:aria-label="
sheet === 'peek'
? t('Context. Swipe up or press to open')
: t('Context. Swipe down or press to close')
"
@pointerdown="onHandleDown"
@pointermove="onHandleMove"
@pointerup="onHandleUp"
@pointercancel="onHandleUp"
@click="onHandleClick"
@keydown="onHandleKey"
>
<span class="pk-top">
<span class="lbl">{{ t('Context') }}</span>
<span id="sheetSum" class="sum">{{ sheetSum }}</span>
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M6 15l6-6 6 6" />
</svg>
</span>
<span id="peekFacts" class="pk-facts" aria-hidden="true">
<span v-for="f in peekFacts" :key="f[1]"
><b :class="{ warn: f[2] }">{{ f[0] }}</b
>{{ t(f[1]) }}</span
>
</span>
</button>
<div class="cx-search-wrap">
<div class="cx-search">
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
aria-hidden="true"
>
<circle cx="11" cy="11" r="6.5" />
<path d="m16 16 4.5 4.5" />
</svg>
<input
id="cxQ"
v-model="query"
type="search"
:placeholder="t('Search this story')"
autocomplete="off"
spellcheck="false"
:aria-label="t('Search this story')"
role="combobox"
:aria-expanded="!!results"
aria-controls="cxResults"
@input="onQuery"
@keydown="onSearchKey"
/>
<button
class="cx-ic"
type="button"
disabled
:aria-label="t('Voice search (not in this build)')"
:title="t('Voice search (not in this build)')"
>
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.9"
stroke-linecap="round"
>
<rect x="9" y="3" width="6" height="11" rx="3" />
<path d="M5.5 11a6.5 6.5 0 0 0 13 0M12 17.5V21" />
</svg>
</button>
</div>
<ul
v-if="results"
id="cxResults"
class="cx-results"
role="listbox"
:aria-label="t('Search results')"
>
<li v-for="(x, i) in results" :key="`${x.type}:${x.k ?? x.title}`">
<button
type="button"
role="option"
:aria-selected="i === active"
@click="choose(x)"
>
<span class="ic" aria-hidden="true">{{ GLYPH[x.type] }}</span>
<span
><b>{{ x.title }}</b
><span class="sub">{{ x.sub }}</span></span
>
</button>
</li>
<li v-if="!results.length" class="empty">{{
t('Nothing in this story matches.')
}}</li>
</ul>
</div>
<div id="cxScroll" class="cx-scroll">
<div class="cx-sec cx-chapters">
<div class="cx-h">{{ t('Chapters') }}</div>
<ul class="cx-list">
<li v-for="(c, i) in story.chapters" :key="c.id">
<a href="#" @click.prevent="emit('chapter', i)"
>{{ i + 1 }}. {{ chTitle(c) }}</a
>
<span
>{{ chapterStamp(story, c)
}}{{ i === k ? ` · ${t('now')}` : '' }}</span
>
</li>
</ul>
</div>
<div class="cx-sec">
<div class="cx-h">
{{ t('About') }}
<button
class="tbtn cx-close"
type="button"
style="height: 28px; padding: 0 8px"
@click="emit('hide')"
>{{ t('Close') }}</button
>
</div>
<p class="cx-p">
<b>{{ titleOf(story) }}</b
><br />{{ t('by {creator}', { creator: story.creator }) }} ·
{{ windowText(story) }}
</p>
<p v-if="story.description" class="cx-p">{{
storyText(story.description)
}}</p>
</div>
<div v-if="events.length" class="cx-sec">
<div class="cx-h">{{ t('Key moments') }}</div>
<ul class="cx-anchors">
<li v-for="(ev, i) in events" :key="i">
<button
type="button"
:class="{ past: playback.wallMs >= ev.wallMs }"
@click="emit('anchor', ev)"
>
<span class="tchip">{{ stamp(ev.wallMs) }}</span>
<span class="al"
><i :style="{ background: ev.color }"></i
>{{ storyText(ev.label) }}</span
>
</button>
</li>
</ul>
</div>
<div v-if="story.sources.length" class="cx-sec">
<div class="cx-h">{{ t('Sources') }}</div>
<ul class="cx-list">
<li v-for="src in story.sources" :key="src[0]">
<a :href="src[2] || '#'" target="_blank" rel="noopener"
>{{ storyText(src[0]) }} ↗</a
>
<span>{{ storyText(src[1]) }}</span>
</li>
</ul>
</div>
<div v-if="background" class="cx-sec">
<div class="cx-h">{{ t('Background') }}</div>
<p class="cx-p">{{ background }}</p>
</div>
<div class="cx-sec">
<div class="cx-h">{{ t('Related stories') }}</div>
<div class="cx-related">
<button
v-for="x in related"
:key="x.id"
type="button"
@click="emit('open', x.id)"
>
<span class="thumb"
><img v-if="thumbOf(x)" :src="thumbOf(x)" alt="" loading="lazy"
/></span>
<span
><b>{{ titleOf(x) }}</b
><span class="c-meta">{{ windowText(x) }}</span></span
>
</button>
</div>
</div>
</div>
</aside>
</template>
+53
View File
@@ -0,0 +1,53 @@
<script setup>
import { computed } from 'vue';
import { t } from '../../../i18n/index.js';
import { useStoriesStore } from '../../stores/stories.js';
/**
* The right rail over the story map (prototype `.ov-rail`): Open in GEV (it
* opens the scene in GEV's Scenes panel) and Share.
*/
const store = useStoriesStore();
// A scene saved on this device only: a link to it opens nothing elsewhere.
const localOnly = computed(() => !!store.byId(store.storyId)?.mine);
async function share() {
const url = store.controller.shareLink();
try {
await navigator.clipboard.writeText(url);
store.flashHint(t('Story link copied'), 1800);
} catch {
store.flashHint(url, 2600);
}
}
</script>
<template>
<div id="ovRail" class="ov ov-rail">
<!-- The scene opens in GEV's Scenes panel. -->
<button
id="railGev"
class="rail-btn rail-gev"
type="button"
:aria-label="t('Open this moment in GEV')"
@click="store.controller.openInGev()"
>
<span class="ic"
><svg class="eye" viewBox="0 0 775 520" aria-hidden="true">
<use href="#gevLogo" /></svg></span
>{{ t('Open') }}
</button>
<button
v-if="!localOnly"
id="railShare"
class="rail-btn"
type="button"
:aria-label="t('Share this story')"
@click="share"
>
<span class="ic"
><span class="share-icon" aria-hidden="true">&#x1F517;</span></span
>{{ t('Share') }}
</button>
</div>
</template>
+614
View File
@@ -0,0 +1,614 @@
<script setup>
import {
computed,
nextTick,
onBeforeUnmount,
onMounted,
ref,
watch,
} from 'vue';
import { storeToRefs } from 'pinia';
import { formatNumber, t } from '../../../i18n/index.js';
import { useStoriesStore } from '../../stores/stories.js';
import { chapterAt } from '../../../stories/format.js';
import {
chapterTitle,
clamp,
clockText,
layersFor,
nowFacts,
storyText,
} from '../../../stories/storyMeta.js';
import StoriesHeader from './StoriesHeader.vue';
import StoryTimeline from './StoryTimeline.vue';
import StoryContext from './StoryContext.vue';
import StoryRail from './StoryRail.vue';
/**
* One story (prototype `.scr-story`): a GEV scene playing on GEV's Cesium
* globe, which shows through the map area.
*/
const props = defineProps({ story: { type: Object, required: true } });
const emit = defineEmits(['back']);
const store = useStoriesStore();
const {
playback,
expanded,
ctxOpen,
sheet,
contextWidth,
camera,
hint,
bigPlay,
} = storeToRefs(store);
const titleOf = (s) => storyText(s.title);
const title = computed(() => titleOf(props.story));
const k = computed(() => chapterAt(props.story, playback.value.wallMs));
const chapter = computed(() => props.story.chapters[k.value]);
const chTitle = (c) => chapterTitle(props.story, c);
const clock = computed(() => clockText(props.story, k.value));
const layers = computed(() => layersFor(props.story));
const facts = computed(() => nowFacts(props.story));
const posText = computed(() => {
const { lat, lon, altKm } = camera.value;
return {
pos: `${Math.abs(lat).toFixed(2)}°${lat >= 0 ? 'N' : 'S'} ${Math.abs(lon).toFixed(2)}°${lon >= 0 ? 'E' : 'W'}`,
// ALT and KM are HUD codes, as in GEV's own readout; the number follows
// the page's language.
alt: ` · ALT ${formatNumber(altKm)} KM`,
};
});
const legendStyle = (l) =>
l[0] === 'dash'
? { borderTop: `2px dashed ${l[1]}` }
: l[0] === 'line'
? { borderTopColor: l[1] }
: { background: l[1] };
const legendClass = (l) => (l[0] === 'dot' ? 'dot' : l[0] === 'sq' ? 'sq' : '');
// ── Navigation within the story ──
const timelineRef = ref(null);
function goChapter(i) {
store.controller.seek(props.story.chapters[i].wallMs + 1);
}
function goAnchor(ev) {
store.controller.focusEvent(ev);
if (innerWidth <= 720) sheet.value = 'half';
}
function bigPlayClick() {
bigPlay.value = false;
store.controller.play();
}
// ── Story card: Chapter · On the map · Right now ──
const page = ref(0);
const cardMin = ref(false);
const cardDragging = ref(false);
const trackEl = ref(null);
const cardEl = ref(null);
const pgEls = ref([]);
const trackHeight = ref(null);
const dragOffset = ref(null);
function sizeCard() {
const pg = pgEls.value[page.value];
if (pg) trackHeight.value = pg.offsetHeight;
}
function setPage(p) {
page.value = clamp(p, 0, 2);
dragOffset.value = null;
requestAnimationFrame(sizeCard);
}
const trackStyle = computed(() => ({
transform:
dragOffset.value != null
? `translateX(${dragOffset.value}px)`
: `translateX(${-page.value * 100}%)`,
height: trackHeight.value ? `${trackHeight.value}px` : null,
}));
let pd = null;
function onCardDown(e) {
if (e.target.closest('#pgDots, .pg-min, .pg-mini') || cardMin.value) return;
e.stopPropagation();
pd = {
x: e.clientX,
y: e.clientY,
w: cardEl.value.offsetWidth,
t: performance.now(),
moved: false,
};
try {
cardEl.value.setPointerCapture(e.pointerId);
} catch {
/* nothing to capture */
}
}
function onCardMove(e) {
if (!pd) return;
const dx = e.clientX - pd.x;
if (
!pd.moved &&
Math.abs(dx) > 6 &&
Math.abs(dx) > Math.abs(e.clientY - pd.y)
) {
pd.moved = true;
cardDragging.value = true;
}
if (!pd.moved) return;
// Rubber band at the ends.
const ends = (page.value === 0 && dx > 0) || (page.value === 2 && dx < 0);
dragOffset.value = -page.value * pd.w + (ends ? dx * 0.3 : dx);
}
function onCardUp(e) {
if (!pd) return;
if (pd.moved) {
const dx = e.clientX - pd.x;
const fast = Math.abs(dx) / Math.max(1, performance.now() - pd.t) > 0.4;
cardDragging.value = false;
setPage(
page.value + (Math.abs(dx) > pd.w * 0.25 || fast ? (dx < 0 ? 1 : -1) : 0),
);
}
pd = null;
}
function onCardKey(e) {
if (e.key === 'ArrowRight') setPage(page.value + 1);
else if (e.key === 'ArrowLeft') setPage(page.value - 1);
}
const minBtn = ref(null);
const miniBtn = ref(null);
function setCardMin(on) {
cardMin.value = on;
if (!on) requestAnimationFrame(sizeCard);
}
// The card shows for a few seconds at each chapter (new info), then folds
// to its pill so the map has room (prototype, on every screen size here).
let cardTimer = 0;
function cardPeek() {
clearTimeout(cardTimer);
setCardMin(false);
cardTimer = setTimeout(() => {
if (!cardHover) setCardMin(true);
}, 5000);
}
// The card stays open while the pointer is on it, then folds a moment later.
let cardHover = false;
function onCardEnter() {
cardHover = true;
clearTimeout(cardTimer);
}
function onCardLeave() {
cardHover = false;
if (!cardMin.value) cardTimer = setTimeout(() => setCardMin(true), 2500);
}
watch(k, () => cardPeek());
let cardObserver = null;
// ── Phone: controls fade in expanded full screen while playing ──
const controlsHidden = ref(false);
let pokeTimer = 0;
function pokeControls() {
controlsHidden.value = false;
clearTimeout(pokeTimer);
if (expanded.value && playback.value.playing && innerWidth <= 720)
pokeTimer = setTimeout(() => (controlsHidden.value = true), 3000);
}
watch([expanded, () => playback.value.playing], pokeControls);
function onSectionMove(e) {
if (e.pointerType !== 'mouse' || controlsHidden.value) pokeControls();
}
// ── Phone: the first play shows that the context can be pulled up ──
const sheetHint = ref(false);
const nudge = ref(false);
let hintTimers = [];
watch(
() => playback.value.playing,
(on) => {
if (!on || store.sheetHintSeen) return;
hintTimers.push(
setTimeout(() => {
if (store.sheetHintSeen || innerWidth > 720 || sheet.value !== 'peek')
return;
store.sheetHintSeen = true;
sheetHint.value = true;
nudge.value = true;
hintTimers.push(setTimeout(() => (nudge.value = false), 2400));
hintTimers.push(setTimeout(() => (sheetHint.value = false), 5200));
}, 1500),
);
},
);
watch(sheet, () => (sheetHint.value = false));
// ── Desktop: drag the context panel's left edge to resize ──
const resizing = ref(false);
const limits = () => [260, Math.max(280, Math.min(640, innerWidth - 420))];
function setCtxW(px) {
const [a, b] = limits();
contextWidth.value = Math.round(clamp(px, a, b));
try {
localStorage.setItem('gevCtxW', contextWidth.value);
} catch {
/* storage off: the width lasts this visit */
}
}
let rd = null;
function onResizeDown(e) {
try {
e.currentTarget.setPointerCapture(e.pointerId);
} catch {
/* nothing to capture */
}
rd = {
x: e.clientX,
w: document.getElementById('stCtx')?.offsetWidth ?? 340,
};
resizing.value = true;
e.preventDefault();
}
function onResizeMove(e) {
if (rd) setCtxW(rd.w + (rd.x - e.clientX));
}
function onResizeUp() {
if (!rd) return;
rd = null;
resizing.value = false;
store.controller.reframe();
}
function onResizeReset() {
contextWidth.value = 0;
try {
localStorage.removeItem('gevCtxW');
} catch {
/* storage off */
}
store.controller.reframe();
}
function onResizeKey(e) {
const d = { ArrowLeft: 24, ArrowRight: -24 }[e.key];
if (!d) return;
e.preventDefault();
setCtxW((document.getElementById('stCtx')?.offsetWidth ?? 340) + d);
store.controller.reframe();
}
const sectionStyle = computed(() =>
contextWidth.value && !expanded.value
? { '--ctxw': `${contextWidth.value}px` }
: null,
);
onMounted(() => {
try {
const v = +localStorage.getItem('gevCtxW');
if (v) contextWidth.value = v;
} catch {
/* storage off */
}
if (globalThis.ResizeObserver && cardEl.value) {
cardObserver = new ResizeObserver(sizeCard);
cardObserver.observe(cardEl.value);
}
nextTick(sizeCard);
cardPeek();
});
onBeforeUnmount(() => {
clearTimeout(cardTimer);
clearTimeout(pokeTimer);
hintTimers.forEach(clearTimeout);
cardObserver?.disconnect();
});
watch(
() => props.story.id,
() => {
page.value = 0;
cardMin.value = false;
nextTick(sizeCard);
},
);
watch([k, page], () => nextTick(sizeCard));
</script>
<template>
<section
id="scrStory"
class="scr scr-story"
:class="{
expanded,
'ctx-open': ctxOpen,
'ctx-sized': !!contextWidth,
'controls-hidden': controlsHidden,
'sheet-hinting': sheetHint,
'ctx-resizing': resizing,
}"
:aria-label="t('GEV Story')"
:data-sheet="sheet"
data-chapters="timeline"
:style="sectionStyle"
@pointerdown="pokeControls"
@pointermove="onSectionMove"
@keydown="pokeControls"
>
<StoriesHeader
screen="story"
:title="title"
@back="emit('back')"
@crumb="emit('back')"
@home="store.controller.close()"
/>
<div class="st-body">
<aside class="st-chapters" :aria-label="t('Chapters')">
<div class="ch-credit">
<span class="label"
><span class="chip">{{
story.draft ? t('DRAFT') : t('STORY')
}}</span></span
>
<div class="t">{{ title }}</div>
<div class="c-meta">{{
t('by {creator}', { creator: story.creator })
}}</div>
</div>
<ol class="ch-list">
<li v-for="(c, i) in story.chapters" :key="c.id">
<button
class="ch-item"
:class="{ done: i < k }"
type="button"
:aria-current="i === k ? 'step' : undefined"
@click="goChapter(i)"
>
<span class="n">{{ i + 1 }}</span
><span
><b>{{ chTitle(c) }}</b></span
>
</button>
</li>
</ol>
</aside>
<div class="st-main">
<div id="stMap" class="st-map">
<div class="map-slot"></div>
<div
id="ovChapter"
ref="cardEl"
class="ov ov-chapter glass"
:class="{ min: cardMin, dragging: cardDragging }"
role="region"
aria-roledescription="carousel"
:aria-label="t('Story card')"
tabindex="0"
@pointerdown="onCardDown"
@pointermove="onCardMove"
@pointerup="onCardUp"
@pointercancel="onCardUp"
@keydown="onCardKey"
@focusin="!cardMin && cardPeek()"
@mouseenter="onCardEnter"
@mouseleave="onCardLeave"
>
<div
id="pgTrack"
ref="trackEl"
class="pg-track"
:style="trackStyle"
>
<section
:ref="(el) => (pgEls[0] = el)"
class="pg"
aria-roledescription="slide"
:aria-label="t('Chapter')"
:aria-hidden="page !== 0"
aria-live="polite"
>
<div class="k">{{
t('CHAPTER {n} / {total}', {
n: k + 1,
total: story.chapters.length,
})
}}</div>
<div class="t">{{ chTitle(chapter) }}</div>
<div v-if="chapter.caption" class="c">{{
storyText(chapter.caption)
}}</div>
</section>
<section
:ref="(el) => (pgEls[1] = el)"
class="pg"
aria-roledescription="slide"
:aria-label="t('On the map')"
:aria-hidden="page !== 1"
>
<div class="k">{{ t('ON THE MAP') }}</div>
<div class="pg-legend">
<span v-for="l in layers" :key="l[2]"
><i :class="legendClass(l)" :style="legendStyle(l)"></i
>{{ storyText(l[2]) }}</span
>
</div>
</section>
<section
:ref="(el) => (pgEls[2] = el)"
class="pg"
aria-roledescription="slide"
:aria-label="t('Right now')"
:aria-hidden="page !== 2"
>
<div class="k">{{ t('RIGHT NOW') }} · {{ clock.big }}</div>
<div class="pg-facts">
<div v-for="f in facts" :key="f[1]"
><b :class="{ warn: f[2] }">{{ f[0] }}</b
><span>{{ t(f[1]) }}</span></div
>
</div>
</section>
</div>
<button
id="pgMin"
ref="minBtn"
class="pg-min"
type="button"
:aria-label="t('Minimise card')"
:aria-expanded="!cardMin"
@click.stop="
setCardMin(true);
nextTick(() => miniBtn?.focus());
"
>
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2.2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M6 15l6-6 6 6" />
</svg>
</button>
<button
id="pgMini"
ref="miniBtn"
class="pg-mini"
type="button"
:aria-label="t('Expand card')"
@click.stop="
setCardMin(false);
cardPeek();
nextTick(() => minBtn?.focus());
"
>
<b>{{ k + 1 }}/{{ story.chapters.length }}</b
><span>{{ chTitle(chapter) }}</span>
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2.2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M6 9l6 6 6-6" />
</svg>
</button>
<div
id="pgDots"
class="pg-dots"
role="group"
:aria-label="t('Card pages')"
>
<button
v-for="(lbl, i) in [
t('Chapter'),
t('On the map'),
t('Right now'),
]"
:key="i"
type="button"
:aria-label="lbl"
:aria-current="String(i === page)"
@click="setPage(i)"
></button>
</div>
</div>
<div id="ovClock" class="ov ov-clock">
<b>{{ clock.big }}</b
><span>{{ t(clock.small) }}</span>
<span class="pos"
>{{ posText.pos }}<i>{{ posText.alt }}</i></span
>
</div>
<div id="ovLegend" class="ov ov-legend">
<span v-for="l in layers" :key="l[2]" class="glass"
><i :class="legendClass(l)" :style="legendStyle(l)"></i
>{{ storyText(l[2]) }}</span
>
</div>
<div
v-if="bigPlay && !playback.playing"
id="ovPlay"
class="ov ov-play"
>
<button
id="btnBigPlay"
type="button"
:aria-label="t('Play story')"
@click="bigPlayClick"
>
<svg viewBox="0 0 24 24" fill="currentColor">
<path
d="M8 5.7v12.6c0 .9 1 1.4 1.7.9l9.7-6.3a1.1 1.1 0 0 0 0-1.8L9.7 4.8C9 4.3 8 4.8 8 5.7Z"
/>
</svg>
</button>
</div>
<button
id="btnCtx"
class="ov ov-ctxbtn tbtn"
type="button"
:aria-pressed="ctxOpen"
@click="ctxOpen = !ctxOpen"
>
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.8"
>
<rect x="4" y="4" width="16" height="16" rx="3" />
<path d="M14 4v16" />
</svg>
<span>{{ t('Context') }}</span>
</button>
<div v-if="hint" id="ovHint" class="ov ov-hint glass">{{ hint }}</div>
<StoryRail />
</div>
<StoryTimeline ref="timelineRef" :story="story" @anchor="goAnchor" />
</div>
<div
id="ctxResize"
class="ctx-resize"
role="separator"
aria-orientation="vertical"
:aria-label="t('Resize context panel')"
:aria-valuenow="contextWidth || undefined"
tabindex="0"
@pointerdown="onResizeDown"
@pointermove="onResizeMove"
@pointerup="onResizeUp"
@pointercancel="onResizeUp"
@dblclick="onResizeReset"
@keydown="onResizeKey"
></div>
<StoryContext
:story="story"
:nudge="nudge"
@chapter="goChapter"
@anchor="goAnchor"
@open="(id) => store.controller.openStory(id, { autoplay: true })"
@hide="ctxOpen = false"
/>
<div
v-if="sheetHint"
id="sheetHint"
class="sheet-hint"
aria-hidden="true"
>
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2.4"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M12 19V5M6 11l6-6 6 6" />
</svg>
{{ t('Swipe up for context') }}
</div>
</div>
</section>
</template>
+462
View File
@@ -0,0 +1,462 @@
<script setup>
import { computed, onMounted, ref, watch } from 'vue';
import { storeToRefs } from 'pinia';
import { t } from '../../../i18n/index.js';
import { useStoriesStore } from '../../stores/stories.js';
import { chapterAt } from '../../../stories/format.js';
import {
chapterTitle,
clamp,
clockText,
fmtDur,
storyText,
} from '../../../stories/storyMeta.js';
/**
* The story timeline (prototype `.timeline`): chapter segments with
* magnetic ticks, key-moment pips, a scrub bubble and expand.
* Positions are wall milliseconds on the GEV scene's own clock.
*/
const props = defineProps({ story: { type: Object, required: true } });
const emit = defineEmits(['anchor']);
const store = useStoriesStore();
const { playback, expanded } = storeToRefs(store);
const dur = computed(
() => playback.value.durationMs || props.story.durationMs || 1,
);
const previewMs = ref(null);
const tNow = computed(() => previewMs.value ?? playback.value.wallMs);
const pct = computed(() => clamp((tNow.value / dur.value) * 100, 0, 100));
const k = computed(() => chapterAt(props.story, tNow.value));
const chapters = computed(() => props.story.chapters);
const chTitle = (c) => chapterTitle(props.story, c);
const events = computed(() => props.story.events ?? []);
const seek = (ms) => store.controller.seek(clamp(ms, 0, dur.value - 10));
// ── Play button: pause while playing, otherwise play ──
const ICON = {
pause:
'<rect x="6.5" y="5" width="4" height="14" rx="1.4"/><rect x="13.5" y="5" width="4" height="14" rx="1.4"/>',
play: '<path d="M8 5.7v12.6c0 .9 1 1.4 1.7.9l9.7-6.3a1.1 1.1 0 0 0 0-1.8L9.7 4.8C9 4.3 8 4.8 8 5.7Z"/>',
};
const playMode = computed(() => (playback.value.playing ? 'pause' : 'play'));
function togglePlay() {
if (playback.value.playing) store.controller.pause();
else store.controller.play();
}
// ── Segments ──
const segs = computed(() =>
chapters.value.map((c, i) => {
const a = (c.wallMs / dur.value) * 100;
const next =
i + 1 < chapters.value.length ? chapters.value[i + 1].wallMs : dur.value;
const b = (next / dur.value) * 100;
const fill =
clamp((tNow.value - c.wallMs) / (next - c.wallMs || 1), 0, 1) * 100;
return {
i,
style: {
left: `calc(${a}% + ${i ? 2 : 0}px)`,
width: `calc(${b - a}% - ${i ? 2 : 0}px - ${i + 1 < chapters.value.length ? 2 : 0}px)`,
},
fill: `${fill}%`,
};
}),
);
// ── Readout ──
const clock = computed(() => clockText(props.story, k.value));
const stampAt = (ms) => fmtDur(ms);
const headTime = computed(() => `${fmtDur(tNow.value)} / ${fmtDur(dur.value)}`);
// ── Scrubbing: preview locally, seek the globe once on release ──
const track = ref(null);
const scrubbing = computed(() => previewMs.value !== null);
const snap = ref(-1);
const hovered = ref(-1);
const ghost = ref(0);
const bubbleAt = ref(null);
let sc = null;
let pipSnap = -1;
const haptic = () => {
try {
navigator.vibrate?.(3);
} catch {
/* no haptics here */
}
};
function trackAt(clientX) {
const r = track.value.getBoundingClientRect();
const width = r.width || 1;
let u = clamp((clientX - r.left) / width, 0, 1);
let snapped = -1;
chapters.value.forEach((c, i) => {
if (i && Math.abs(u - c.wallMs / dur.value) * width < 9) {
u = c.wallMs / dur.value;
snapped = i;
}
});
return { t: u * dur.value, snapped };
}
function scrubTo(target) {
const w = track.value.getBoundingClientRect().width || 1;
let tt = clamp(target, 0, dur.value - 10);
let snapped = -1;
chapters.value.forEach((c, i) => {
if (i && (Math.abs(tt - c.wallMs) / dur.value) * w < 6) {
tt = c.wallMs;
snapped = i;
}
});
let pip = -1;
if (snapped < 0)
events.value.forEach((ev, i) => {
if ((Math.abs(tt - ev.wallMs) / dur.value) * w < 5) {
tt = ev.wallMs;
pip = i;
}
});
if (pip >= 0 && pip !== pipSnap) haptic();
pipSnap = pip;
if (pip >= 0) snapped = -2 - pip;
const ch = chapterAt(props.story, tt);
if (sc && ch !== sc.ch) {
haptic();
sc.ch = ch;
}
previewMs.value = tt;
snap.value = snapped;
bubbleAt.value = tt;
}
function onDown(e) {
if (sc || e.button !== 0 || e.target.closest('.tl-pip')) return;
try {
track.value.setPointerCapture(e.pointerId);
} catch {
/* nothing to capture */
}
const r = trackAt(e.clientX);
sc = {
pointerId: e.pointerId,
lastX: e.clientX,
lastT: performance.now(),
ch: chapterAt(props.story, r.t),
at: r.t,
};
scrubTo(r.t);
}
function onMove(e) {
if (!scrubbing.value) {
if (e.target.closest('.tl-pip')) return;
const r = trackAt(e.clientX);
ghost.value = (r.t / dur.value) * 100;
hovered.value = chapterAt(props.story, r.t);
snap.value = r.snapped;
if (r.snapped < 0) {
const w = track.value.clientWidth || 1;
const i = events.value.findIndex(
(ev) => (Math.abs(ev.wallMs - r.t) / dur.value) * w < 5,
);
if (i >= 0) snap.value = -2 - i;
}
bubbleAt.value = r.t;
return;
}
if (sc.pointerId !== e.pointerId) return;
// Slow drags are fine, fast drags coarse.
const now = performance.now();
const dx = e.clientX - sc.lastX;
const dtm = Math.max(1, now - sc.lastT);
const w = track.value.getBoundingClientRect().width || 1;
const gain = clamp(0.25 + (Math.abs(dx) / dtm) * 1.1, 0.25, 2.5);
sc.at = clamp(sc.at + (dx / w) * dur.value * gain, 0, dur.value - 10);
scrubTo(sc.at);
sc.lastX = e.clientX;
sc.lastT = now;
}
function finishScrub(e) {
if (sc?.pointerId !== e.pointerId) return;
const at = previewMs.value;
sc = null;
previewMs.value = null;
snap.value = -1;
pipSnap = -1;
if (e.type === 'pointerup') seek(at);
else bubbleAt.value = null;
}
function onLeave() {
if (scrubbing.value) return;
ghost.value = 0;
hovered.value = -1;
snap.value = -1;
bubbleAt.value = null;
}
// The bubble follows the knob while playing and the pointer while hovering.
const bubbleT = computed(() => bubbleAt.value ?? tNow.value);
const bubbleK = computed(() => chapterAt(props.story, bubbleT.value));
const bubbleClock = computed(() => clockText(props.story, bubbleK.value));
const bubbleEm = computed(() => {
if (snap.value >= 0) return { text: t('Chapter start'), color: null };
if (snap.value <= -2) {
const ev = events.value[-2 - snap.value];
return ev ? { text: storyText(ev.label), color: ev.color } : null;
}
return null;
});
const bubbleEl = ref(null);
const bubbleStyle = computed(() => {
const w = track.value?.clientWidth || 1;
const half = (bubbleEl.value?.offsetWidth || 120) / 2;
const x = (bubbleT.value / dur.value) * w;
const bx = clamp(x, half, Math.max(half, w - half));
return {
left: `${bx}px`,
'--caret': `${clamp(x - bx + half, 8, half * 2 - 8)}px`,
};
});
// The bubble's picture: the story's card picture, when it has one.
const prevSrc = computed(() => store.thumbs?.[props.story.id] || '');
const prevCanvas = ref(null);
function drawPreview() {
const cv = prevCanvas.value;
const src = prevSrc.value;
if (!cv || !src) return;
const img = new Image();
img.onload = () =>
cv.getContext('2d')?.drawImage(img, 0, 0, cv.width, cv.height);
img.src = src;
}
watch(prevSrc, drawPreview, { flush: 'post' });
onMounted(drawPreview);
// ── Key moments ──
const tip = ref(null);
function tipFor(i) {
const ev = events.value[i];
if (!ev) return;
const w = track.value?.clientWidth || 1;
tip.value = {
ev,
left: clamp((ev.wallMs / dur.value) * w, 90, Math.max(90, w - 90)),
};
}
function pipClick(i) {
haptic();
emit('anchor', events.value[i]);
setTimeout(() => (tip.value = null), 900);
}
// ── Keyboard on the track ──
function goChapter(i) {
seek(chapters.value[i].wallMs + 1);
}
// Previous goes to the start of this chapter first, like a video player.
function stepChapter(d) {
const kk = k.value;
const list = chapters.value;
if (d > 0 && kk === list.length - 1) {
seek(dur.value);
return;
}
const to =
d > 0
? Math.min(list.length - 1, kk + 1)
: tNow.value - list[kk].wallMs > 1500
? kk
: Math.max(0, kk - 1);
goChapter(to);
}
function onKey(e) {
if (e.target !== track.value) return;
// A key the timeline handles is the timeline's alone.
const handled = () => {
e.preventDefault();
e.stopPropagation();
};
let tt = tNow.value;
if (e.shiftKey && (e.key === 'ArrowRight' || e.key === 'ArrowLeft')) {
stepChapter(e.key === 'ArrowRight' ? 1 : -1);
handled();
return;
}
if (e.key === 'PageUp') tt += dur.value / 10;
else if (e.key === 'PageDown') tt -= dur.value / 10;
else if (/^[0-9]$/.test(e.key)) tt = dur.value * (+e.key / 10);
else if (e.key === 'ArrowRight' || e.key === 'ArrowUp') tt += 2000;
else if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') tt -= 2000;
else if (e.key === 'Home') tt = 0;
else if (e.key === 'End') tt = dur.value;
else if (e.key === ']') {
goChapter(Math.min(chapters.value.length - 1, k.value + 1));
handled();
return;
} else if (e.key === '[') {
goChapter(Math.max(0, k.value - 1));
handled();
return;
} else if (e.key === ' ' || e.key === 'Enter') {
togglePlay();
handled();
return;
} else return;
handled();
seek(tt);
}
// ── Expand ──
function toggleExpand() {
store.expanded = !store.expanded;
store.ctxOpen = false;
setTimeout(() => store.controller.reframe(), 320);
}
defineExpose({ goChapter });
</script>
<template>
<div id="timeline" class="timeline">
<button
id="tlPlay"
class="tl-play"
type="button"
:aria-label="playMode === 'pause' ? t('Pause') : t('Play')"
@click="togglePlay"
>
<svg
id="tlIcon"
viewBox="0 0 24 24"
fill="currentColor"
v-html="ICON[playMode]"
></svg>
</button>
<div
id="tlTrack"
ref="track"
class="tl-track"
:class="{ dragging: scrubbing, 'on-pip': !!tip }"
role="slider"
tabindex="0"
:aria-label="t('Story time')"
aria-valuemin="0"
aria-valuemax="100"
:aria-valuenow="Math.round(pct)"
:aria-valuetext="`${clock.big}, ${t('chapter')} ${k + 1}: ${chTitle(chapters[k])}`"
@pointerdown="onDown"
@pointermove="onMove"
@pointerup="finishScrub"
@pointercancel="finishScrub"
@lostpointercapture="finishScrub"
@pointerleave="onLeave"
@keydown="onKey"
>
<div id="tlTicks">
<span
v-for="s in segs"
:key="s.i"
class="tl-seg"
:class="{ now: s.i === k, hov: s.i === hovered, snap: s.i === snap }"
:data-k="s.i"
:style="s.style"
><i :style="{ width: s.fill }"></i
></span>
</div>
<div
id="tlGhost"
class="tl-ghost"
:style="{ width: `${ghost}%` }"
aria-hidden="true"
></div>
<div id="tlHead" class="tl-head" aria-hidden="true">
<span id="tlHeadCh"
><b>{{ k + 1 }}</b
>/{{ chapters.length }} · {{ chTitle(chapters[k]) }}</span
>
<span id="tlHeadTime">{{ headTime }}</span>
</div>
<div id="tlPips" role="group" :aria-label="t('Key moments')">
<button
v-for="(ev, i) in events"
:key="i"
type="button"
class="tl-pip"
:class="{ snap: snap === -2 - i }"
:data-e="i"
:aria-label="t('Key moment: {label}', { label: storyText(ev.label) })"
:style="{ left: `${(ev.wallMs / dur) * 100}%`, color: ev.color }"
@pointerdown.stop
@pointerover="tipFor(i)"
@pointerout="tip = null"
@focus="tipFor(i)"
@blur="tip = null"
@click.stop="pipClick(i)"
@keydown.space.stop
@keydown.enter.stop
>
<i :style="{ background: ev.color }"></i>
</button>
</div>
<div
v-if="tip"
id="tlTip"
class="tl-tip"
role="tooltip"
:style="{ left: `${tip.left}px` }"
>
<i :style="{ background: tip.ev.color }"></i
><b>{{ storyText(tip.ev.label) }}</b
><span>{{ stampAt(tip.ev.wallMs) }}</span>
</div>
<div class="tl-knob" :style="{ left: `${pct}%` }"></div>
<div
id="tlBubble"
ref="bubbleEl"
class="tl-bubble"
:data-snap="snap >= 0 ? 'ch' : snap <= -2 ? 'pip' : ''"
:style="bubbleStyle"
>
<canvas
v-if="prevSrc"
id="tlPrev"
ref="prevCanvas"
width="320"
height="180"
aria-hidden="true"
></canvas>
<div id="tlBubbleTxt">
<b>{{ bubbleK + 1 }} · {{ chTitle(chapters[bubbleK]) }}</b>
<span class="tt">{{ bubbleClock.big }}</span>
<em
v-if="bubbleEm"
:style="bubbleEm.color ? { color: bubbleEm.color } : null"
>{{ bubbleEm.text }}</em
>
</div>
</div>
</div>
<span id="tlTime" class="tl-time" aria-hidden="true">
<span class="tt-c">{{ headTime }}</span>
</span>
<button
id="stExpand"
class="tl-vol"
type="button"
:aria-label="expanded ? t('Exit expanded map') : t('Expand map')"
:aria-pressed="expanded"
@click="toggleExpand"
>
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.9"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M4 9V4h5M15 4h5v5M20 15v5h-5M9 20H4v-5" />
</svg>
</button>
</div>
</template>