Stories: GEV scenes as stories on the live globe

A Stories button (top right) opens Explore: a feed of GEV scenes over
GEV's own Cesium globe, with a pin per story. Explore opens at country
level over the first story and, while idle, flies on from story to story
for a minute. A picked story is framed in the middle of the view; a pin
plays its story on a second click. The Story page plays the scene through
SceneDirector with a timeline, chapters, key moments, sources and
background, then Close (or Back) puts the person's camera, clock, layers,
style and AUTHORING selection back. Open in GEV hands the scene to the
Scenes panel at its current shot.

Stories lists the scenes GEV ships with a camera path (while they are in
the project), the scenes saved with SAVE TO STORIES in AUTHORING, and the
person's other scenes as drafts. The person's own stories live in the
project on this device, so they have no Share; a link to a story that is
not here opens Explore and says so. Each shipped story's
context comes from what GEV knows: what it shows, the place each shot goes,
and each layer's data sources as DATA_SOURCES.md lists them; the Nepal
story carries the event pack's facts and CC BY-NC sources. Card images are
a captured THUMBNAIL or drawn from the keyless Esri World Imagery.

AUTHORING has no scene picker: it starts with no scene, NEW SCENE (or
CAPTURE SHOT) makes one, and Stories' Open in GEV selects one. Before SAVE
TO STORIES it offers topic tags and THUMBNAIL. A scene's stories flag,
storyThumb and storyTags are saved with the project and kept through
export and import.

Only the closed state loads with the page; the screens, styles, story data
and controller load on first open. Stories keeps its place in the query
(one history entry per screen) and holds the share link's hash writes
while open. Keyboard input and voice tools stay with Stories while it is
open. Explore's pins move on every drawn frame without asking for frames;
the idle tour and tile settling are bounded.

All strings are translated in the 13 locales.
This commit is contained in:
Manjunath committed 2026-11-16 20:12:10 +05:30
1 parent da81cf743b
commit 5418438339
77 files changed
+14975 -260

No files matched your search

+119
View File
@@ -0,0 +1,119 @@
const STORIES_PARAMS = ['stories', 'story'];
const wantsStories = () => {
const params = new URLSearchParams(location.search);
return STORIES_PARAMS.some((p) => params.has(p));
};
/**
* Stories, loaded on first use. The controller, the story catalog, the
* screens and their styles are separate chunks, fetched when the person
* opens Stories, follows a Stories link or
* steps into Stories with Back or Forward. Until then the store holds this
* shell, whose calls load the controller and then run.
*
* @param {{viewer: import('cesium').Viewer,
* director: import('../scenes/director.js').SceneDirector,
* store: ReturnType<typeof import('../ui/stores/stories.js').useStoriesStore>,
* onLoadFailed?: () => void,
* loadModules?: () => Promise<[object, object]>}} options `onLoadFailed`
* tells the person a click did nothing because Stories could not load;
* `available` is false where Stories is not offered (an inline embed:
* its URL and history are the host page's);
* `loadModules` fetches the controller, catalog and Stories' styles
* (tests replace it).
*/
export function bootStories({
viewer,
director,
store,
onLoadFailed,
available = true,
loadModules = () =>
Promise.all([
import('./controller.js'),
import('./catalog.js'),
// Stories' screen styles, in place before the screens show, and the
// screens themselves, so opening does not wait on a second fetch.
import('../ui/styles/stories.css'),
import('../ui/views/stories/ExploreScreen.vue'),
import('../ui/views/stories/StoryScreen.vue'),
]),
}) {
store.available = available;
if (!available) {
const off = {
open: async () => {},
openStory: async () => {},
backToExplore: async () => {},
close: () => {},
reframe: () => {},
kind: null,
load: async () => null,
destroy: () => {},
};
store.connect(off, []);
return off;
}
let real = null;
let loading = null;
let destroyed = false;
function load() {
loading ??= loadModules().then(
([{ createStoriesController }, { listStories }]) => {
if (destroyed) return null;
removeEventListener('popstate', onPopState);
real = createStoriesController({
viewer,
director,
store,
});
store.connect(real, listStories());
return real;
},
);
// A failed fetch (offline, or a deploy replaced the chunk) is reported
// once, whatever asked (a click, a link, Back or Forward), and not kept:
// the next attempt tries again.
loading.catch((error) => {
loading = null;
console.warn('Stories could not load', error);
onLoadFailed?.();
});
return loading;
}
// The controller reads a Stories link on creation and opens it.
const onPopState = () => {
if (wantsStories()) load();
};
addEventListener('popstate', onPopState);
if (wantsStories()) load();
const later =
(name) =>
(...args) =>
load().then(
(c) => c?.[name](...args),
() => {}, // reported by load()
);
const shell = {
open: later('open'),
openStory: later('openStory'),
backToExplore: later('backToExplore'),
close: () => real?.close(),
reframe: () => real?.reframe(),
get kind() {
return real?.kind ?? null;
},
/** Resolves to the controller once it has loaded. */
load,
destroy() {
if (destroyed) return;
destroyed = true;
removeEventListener('popstate', onPopState);
real?.destroy();
},
};
store.connect(shell, []);
return shell;
}
+142
View File
@@ -0,0 +1,142 @@
// Stories loads its controller, catalog and engine on first use, not with GEV.
import '../testSupport/registerDom.mjs';
import { registerHooks } from 'node:module';
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createPinia, setActivePinia } from 'pinia';
// Every module Node loads, to see when the Stories chunk arrives.
const loaded = new Set();
registerHooks({
load(url, context, next) {
loaded.add(url);
if (url.endsWith('.css'))
return {
format: 'module',
source: 'export default "";',
shortCircuit: true,
};
if (url.endsWith('.webp'))
return {
format: 'module',
source: `export default ${JSON.stringify(url)};`,
shortCircuit: true,
};
return next(url, context);
},
});
const context = new Proxy(
{},
{ get: (target, name) => target[name] ?? (() => context), set: () => true },
);
globalThis.HTMLCanvasElement.prototype.getContext = (kind) =>
kind === 'webgl' ? null : context;
globalThis.requestAnimationFrame = () => 0;
globalThis.cancelAnimationFrame = () => {};
const { bootStories } = await import('./boot.js');
const { useStoriesStore } = await import('../ui/stores/stories.js');
const viewer = {
scene: {
canvas: document.createElement('canvas'),
postRender: { addEventListener: () => () => {} },
},
camera: {
positionWC: new Cesium.Cartesian3(1, 2, 3),
positionCartographic: { latitude: 0, longitude: 0, height: 2e6 },
heading: 0,
pitch: -1,
roll: 0,
setView() {},
flyTo() {},
flyToBoundingSphere() {},
cancelFlight() {},
},
clock: { currentTime: Cesium.JulianDate.now(), shouldAnimate: false },
};
const director = {
running: false,
stopScene() {},
whenIdle: async () => {},
listShots: () => [],
subscribeSceneClock: () => () => {},
seekScene() {},
styleManager: { runImmediateNavigation: () => true },
};
test('the shell loads the controller on first open, then steps aside', async () => {
setActivePinia(createPinia());
history.replaceState(null, '', '/');
const store = useStoriesStore();
const shell = bootStories({ viewer, director, store });
assert.equal(store.controller, shell);
assert.equal(store.stories.length, 0, 'no catalog until Stories is used');
const engineLoaded = () =>
[...loaded].some((u) =>
/stories\/(controller|catalog|protoEngine)\.js$/.test(u),
);
assert.equal(engineLoaded(), false, 'GEV starts without the Stories chunk');
await shell.open();
assert.equal(engineLoaded(), true);
assert.notEqual(store.controller, shell);
assert.ok(store.stories.length > 0);
assert.equal(store.mode, 'explore');
shell.destroy();
assert.equal(store.mode, 'closed');
});
test('a Stories link loads the controller straight away', async () => {
setActivePinia(createPinia());
history.replaceState(null, '', '/?stories=explore');
const store = useStoriesStore();
const shell = bootStories({ viewer, director, store });
const real = await shell.load();
assert.equal(store.controller, real);
shell.destroy();
history.replaceState(null, '', '/');
});
test('a failed load is reported and the next open tries again', async () => {
setActivePinia(createPinia());
history.replaceState(null, '', '/');
const store = useStoriesStore();
let failures = 0;
let attempts = 0;
const shell = bootStories({
viewer,
director,
store,
onLoadFailed: () => (failures += 1),
// The Stories chunk is unreachable on the first try only.
loadModules: () =>
++attempts === 1
? Promise.reject(new Error('offline'))
: Promise.all([import('./controller.js'), import('./catalog.js')]),
});
await shell.open();
assert.equal(failures, 1);
assert.equal(store.mode, 'closed');
await shell.open();
assert.equal(attempts, 2, 'the failure was not kept');
assert.equal(store.mode, 'explore');
shell.destroy();
});
test('a Stories link that cannot load is reported too', async () => {
setActivePinia(createPinia());
history.replaceState(null, '', '/?story=worldfx%3Afire-tracker');
const store = useStoriesStore();
let failures = 0;
bootStories({
viewer,
director,
store,
onLoadFailed: () => (failures += 1),
loadModules: () => Promise.reject(new Error('offline')),
});
await new Promise((resolve) => setTimeout(resolve, 0));
assert.equal(failures, 1);
history.replaceState(null, '', '/');
});
+340
View File
@@ -0,0 +1,340 @@
import { SCENE_RECIPES } from '../scenes/recipes.js';
import { msg } from '../i18n/index.js';
/**
* Stories are GEV scenes, played on GEV's own Cesium globe: the scenes GEV
* ships (recipes with a camera path) and the scenes the person authored and
* saved to Stories from the AUTHORING panel.
*
* A shipped scene's context is what GEV knows about it: what it shows, where
* each shot goes, and, for every layer it turns on, what the layer shows and
* where its data comes from (as DATA_SOURCES.md records it). The Nepal scene
* adds the event pack's own facts and sources
* (public/events/bhote-koshi-2026/README.md) and marks its key moments by
* the chapters that show them.
*/
/** What each layer a shipped scene turns on shows, and its data sources. */
const LAYER_FACTS = {
flights: {
label: msg('Flights'),
about: msg(
'Aircraft positions come from ADS-B: the OpenSky Network’s worldwide snapshot, with adsb.lol where OpenSky has none.',
),
sources: [
[
'OpenSky Network',
msg(
'Worldwide live-flight snapshot (non-commercial research and education licence)',
),
'https://opensky-network.org/',
],
['adsb.lol', msg('Live-flight fallback (ODbL 1.0)'), 'https://adsb.lol/'],
],
},
satellites: {
label: msg('Satellites'),
about: msg(
'Satellite orbits are propagated from CelesTrak’s current element sets.',
),
sources: [
[
'CelesTrak',
msg('Satellite element sets and catalogue (U.S. government data)'),
'https://celestrak.org/',
],
[
'UCS Satellite Database (5-1-2023)',
msg('Satellite operators, owners and purposes'),
'https://www.ucsusa.org/satellite_database',
],
],
},
earthquakes: {
label: msg('Earthquakes'),
about: msg('Earthquakes come from the U.S. Geological Survey’s live feed.'),
sources: [
[
'USGS',
msg('Earthquake feed (U.S. public domain)'),
'https://earthquake.usgs.gov/',
],
],
},
traffic: {
label: msg('Traffic'),
about: msg('Road traffic; live congestion needs your own TomTom key.'),
sources: [
[
'TomTom',
msg('Live traffic flow, with your own key'),
'https://www.tomtom.com/',
],
],
},
};
/**
* Per shipped scene: what it shows, and where each shot goes (by the shot's
* camera), for shots without a title of their own.
*/
const SCENE_CONTEXT = {
'flights-radar': {
description: msg(
'Live air traffic around the world: the Atlantic, Europe, Japan and San Francisco.',
),
places: [
msg('The Atlantic'),
msg('Western Europe'),
msg('Japan'),
msg('San Francisco Bay Area'),
msg('Pull back over the Atlantic'),
],
},
'orbital-watch': {
description: msg(
'Satellites in orbit, watched from over Florida, Africa, Tokyo and Paris.',
),
places: [
msg('Over Florida'),
msg('Over Africa'),
msg('Over Tokyo'),
msg('Over Paris'),
msg('Pull back over the Atlantic'),
],
},
'thermal-threats': {
description: msg(
'Recent earthquakes in the thermal look: California, Japan, New Zealand and off Portugal.',
),
places: [
msg('California'),
msg('Japan'),
msg('New Zealand'),
msg('Off Portugal'),
],
},
'city-overload': {
description: msg(
'Flights, satellites and traffic together over New York, Los Angeles and London.',
),
places: [
msg('New York'),
msg('New York, closer'),
msg('New York, closer still'),
msg('Los Angeles'),
msg('London'),
],
},
'omniscience-pullback': {
description: msg(
'Every live layer at once, pulling back from Tokyo to the whole planet.',
),
places: [
msg('Tokyo'),
msg('Tokyo, pulling back'),
msg('Japan and East Asia'),
msg('South China Sea'),
msg('The whole globe'),
],
},
'bhote-koshi-nepal-scene': {
description: msg(
'The 26 August 2026 Bhote Koshi outburst flood in Nepal, followed down the valley to Trishuli.',
),
// Where Explore frames it: the Bhote Koshi corridor, not the scene's
// opening whole-globe shot.
area: { lat: 28.13, lon: 85.32, alt: 160000 },
tMinMs: Date.UTC(2026, 7, 26),
tMaxMs: Date.UTC(2026, 7, 27),
// Key moments: the chapters that show them, by their titles.
moments: [
['#ffb45a', msg('Upper Valley Collapse')],
['#50c8ff', msg('Debris-Dammed Lake')],
['#ff7a6b', msg('Second landslide')],
],
sources: [
[
'Vantor Open Data Program',
msg('Historical and post-event satellite imagery (CC BY-NC 4.0)'),
'https://vantor.com/company/open-data-program',
],
[
'GeoPera',
msg('Reconstructed flood path (CC BY-NC 4.0)'),
'https://github.com/geo-pera/bhotekoshi-2026-reconstruction',
],
],
background: msg(
'A visualization of the 26 August 2026 Bhote Koshi outburst flood, not an official hazard model. The historical (2021) and post-event views are Vantor WorldView imagery; the river’s path is GeoPera’s reconstruction. Witness clips link to their original posts, and their capture times are unverified.',
),
},
};
/** A shipped scene's context, from its own entry and its layers' facts. */
function sceneContext(recipe) {
const own = SCENE_CONTEXT[recipe.id] ?? {};
const layers = Object.entries(recipe.layers ?? {})
.filter(([id, on]) => on && LAYER_FACTS[id])
.map(([id]) => LAYER_FACTS[id]);
return {
...(own.area ? { area: own.area } : {}),
...(own.tMinMs != null ? { tMinMs: own.tMinMs, tMaxMs: own.tMaxMs } : {}),
description:
own.description ?? msg('A GEV scene, played on the live globe.'),
places: own.places ?? [],
moments: own.moments ?? [],
// The layers' own names on the legend.
mock: { legend: layers.map((l) => ['dot', '#6be8ff', l.label]) },
sources: [...(own.sources ?? []), ...layers.flatMap((l) => l.sources)],
// Each part is translated on its own, as shown.
background: own.background ?? layers.map((l) => l.about),
};
}
/**
* Where a story's card and pin point, and where Explore flies on a pick. A
* shot tied to an anchor (no lat/lon of its own) shows the whole globe.
*/
const coverOf = (camera) =>
Number.isFinite(camera?.lat) && Number.isFinite(camera?.lon)
? {
lat: camera.lat,
lon: camera.lon,
range: camera.alt ?? 1.6e7,
heading: camera.heading ?? 0,
pitch: camera.pitch ?? -70,
}
: { lat: 20, lon: 0, range: 1.6e7, heading: 0, pitch: -90 };
/** A scene GEV ships, from its recipe. */
function shippedStory(recipe) {
const path = recipe.cameraPath ?? [];
const first = path[0] ?? {
lat: 20,
lon: 0,
alt: 1.6e7,
heading: 0,
pitch: -80,
};
const context = sceneContext(recipe);
let at = 0;
const chapters = path.map((shot, i) => {
const chapter = {
id: `shot-${i + 1}`,
wallMs: at,
shot: i + 1,
title: shot.title ?? context.places[i] ?? null,
caption: '',
};
at += ((shot.duration ?? 4) + (shot.hold ?? 0)) * 1000;
return chapter;
});
const durationMs = Math.max(at, (recipe.durationSec ?? 30) * 1000);
const { places, ...rest } = context;
return {
id: `gev:${recipe.id}`,
sceneId: recipe.id,
kind: 'gev',
live: false,
title: recipe.title,
creator: 'GEV',
tags: Object.entries(recipe.layers ?? {})
.filter(([, on]) => on)
.map(([id]) => id),
durationMs,
cover: coverOf(first),
chapters,
events: [],
places,
...rest,
};
}
/** A saved scene's line under its title: a draft says how to publish it. */
const describe = (scene) =>
scene.draft
? msg(
'A draft, not saved as a story yet. Use SAVE TO STORIES in AUTHORING to save it.',
)
: msg('A scene you made in GEV, played on the live globe.');
/**
* A scene the person saved to Stories (SceneDirector.storyScenes()). Its
* chapters and length come from the director's shots when it opens.
*/
function savedStory(scene) {
return {
id: `gev:${scene.id}`,
sceneId: scene.id,
kind: 'gev',
live: false,
mine: true,
// Not saved with SAVE TO STORIES yet.
draft: !!scene.draft,
title: scene.title,
description: describe(scene),
creator: msg('You'),
// Topics the person picked in AUTHORING, and the card image they
// captured there (drawn from the imagery when there is none).
topics: [...(scene.tags ?? [])],
tags: [...(scene.tags ?? [])],
thumb: scene.thumb ?? '',
durationMs: 0,
cover: coverOf(scene.camera),
chapters: [],
events: [],
sources: [],
background: '',
};
}
let shipped = null;
let installed = () => true;
/**
* Whether a shipped scene is in the person's project (the controller passes
* the director's hasScene()); one that is not does not list.
* @param {(sceneId: string) => boolean} test
*/
export function useInstalledScenes(test) {
installed = typeof test === 'function' ? test : () => true;
}
const saved = new Map();
let savedScenes = () => [];
/**
* Where the person's saved scenes come from (the controller passes the
* director's storyScenes()). The list is read again on every call, so a
* scene saved to Stories shows the next time Explore lists.
* @param {() => Array<{id: string, title: string, camera: object, shotCount: number, thumb?: string, tags?: string[]}>} provider
*/
export function useSavedScenes(provider) {
savedScenes = typeof provider === 'function' ? provider : () => [];
}
/** Every story Explore lists: the person's own first, then GEV's. */
export function listStories() {
shipped ??= SCENE_RECIPES.filter((r) => (r.cameraPath ?? []).length).map(
shippedStory,
);
const shippedIds = new Set(shipped.map((s) => s.sceneId));
// One object per saved scene, kept across calls: the controller fills its
// chapters in place when it opens, and the screens read the same object.
const own = (savedScenes() ?? [])
.filter((scene) => !shippedIds.has(scene.id))
.map((scene) => {
const story = saved.get(scene.id) ?? savedStory(scene);
story.title = scene.title;
story.draft = !!scene.draft;
story.description = describe(scene);
story.cover = coverOf(scene.camera);
story.topics = [...(scene.tags ?? [])];
story.tags = [...(scene.tags ?? [])];
story.thumb = scene.thumb ?? '';
saved.set(scene.id, story);
return story;
});
return [...own, ...shipped.filter((s) => installed(s.sceneId))];
}
export function storyById(id) {
return listStories().find((s) => s.id === id) ?? null;
}
+953
View File
@@ -0,0 +1,953 @@
import * as Cesium from 'cesium';
import { markRaw, toRaw } from 'vue';
import { t } from '../i18n/index.js';
import {
governorRequestRender,
holdContinuousRender,
releaseContinuousRender,
} from '../renderGovernor.js';
import { createGevPlayer, directorSettled } from './gevPlayer.js';
import { drawThumb } from './thumbs.js';
import {
listStories,
storyById,
useInstalledScenes,
useSavedScenes,
} from './catalog.js';
import { anchorStamp } from './storyMeta.js';
import { registerNavigationAuthorityListener } from '../navigationPolicy.js';
const PARAM_STORIES = 'stories';
const PARAM_STORY = 'story';
/**
* Stories: Explore (the story list over the person's own Cesium globe, with
* a pin per story) and the Story player. Every story is a GEV scene played
* through SceneDirector: the scenes GEV ships and the ones the person saved
* to Stories from the AUTHORING panel.
* Leaving Stories puts back the globe, camera and clock the person had.
*
* The share state owns the URL hash, so Stories keeps its place in the query
* (`?stories=explore`, `?story=<id>`) and pushes one history entry per
* screen, so Back steps Story → Explore → GEV. Closing steps back over those
* entries, so Back after Close does not reopen Stories.
*
* @param {{viewer: Cesium.Viewer,
* director: import('../scenes/director.js').SceneDirector,
* store: ReturnType<typeof import('../ui/stores/stories.js').useStoriesStore>}} options
*/
export function createStoriesController({ viewer, director, store }) {
let player = null;
let saved = null;
// The view a Close is about to restore, once a stopping scene has settled.
let pendingView = null;
let removeReadout = null;
let destroyed = false;
// Close steps back over Stories' own entries; the landing popstate is ours.
let closingHistory = false;
// A Back to Explore traversal is on its way.
let steppingBack = false;
// A call made while a traversal is landing runs from the entry it lands on,
// so two traversals never stack (Close after Back to Explore would step
// one entry too far).
let afterTraversal = null;
const traversing = () => steppingBack || closingHistory;
const canvas = viewer.scene.canvas;
// The scenes the person saved to Stories (AUTHORING panel) join the list,
// and a save or removal shows at once.
useSavedScenes(() => [
...(director.storyScenes?.() ?? []),
// The person's other scenes, as drafts only they see.
...(director.draftScenes?.() ?? []).map((scene) => ({
...scene,
draft: true,
})),
]);
// A shipped scene lists only while it is in the person's project (it can
// be deleted, or missing from an imported one).
useInstalledScenes((sceneId) => director.hasScene?.(sceneId) ?? true);
const LIST_CHANGES = new Set([
'stories-changed',
'scene-deleted',
'project-imported',
// A draft appears, changes or goes with its shots.
'shot-captured',
'shot-updated',
'shot-deleted',
// A draft's THUMBNAIL or tags.
'story-details-changed',
]);
const unsubscribeScenes = director.subscribe?.((change) => {
if (!LIST_CHANGES.has(change?.type) || destroyed) return;
store.stories = markRaw(listStories());
if (removePins) {
startPins();
drawThumbs();
if (store.mode === 'explore' && !store.picked && !pressing)
armTour(TOUR_DWELL_MS);
}
});
// ── URL and history ──
// Stories' own entries carry no share hash: the address bar while Stories
// is open names the story, not the person's camera and layers.
function urlFor(params) {
const url = new URL(location.href);
url.searchParams.delete(PARAM_STORIES);
url.searchParams.delete(PARAM_STORY);
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
if (Object.keys(params).length) url.hash = '';
return url.toString();
}
const shareLink = () => director.styleManager?.shareLinkManager;
// Each Stories entry records how many entries Stories has pushed above the
// page it opened from (`depth`) and the depth of the nearest Explore entry
// at or below it (`explore`), so Close and Back to Explore step back the
// right distance whatever was opened in between.
const depth = () => history.state?.gevStories?.depth ?? 0;
const exploreDepth = () => {
const own = history.state?.gevStories?.explore;
if (own != null) return own;
return new URLSearchParams(location.search).has(PARAM_STORIES)
? depth()
: null;
};
function navigate(params, push) {
const url = urlFor(params);
if (url === location.href) return;
const next = depth() + (push ? 1 : 0);
const state = {
...(history.state ?? {}),
gevStories: {
...params,
depth: next,
explore: params[PARAM_STORIES] ? next : exploreDepth(),
},
};
if (push) history.pushState(state, '', url);
else history.replaceState(state, '', url);
}
// Without Stories in the URL: the entry a Stories link landed on.
function clearStoriesUrl() {
const state = { ...(history.state ?? {}) };
delete state.gevStories;
history.replaceState(state, '', urlFor({}));
}
// Steps back over Stories' entries; `landed` runs once the page Stories
// opened from is current (or at once when Stories pushed nothing). A
// traversal that never lands (cross-document, blocked) gives up after 2 s.
const LANDING_LIMIT_MS = 2000;
let landed = null;
let landingTimer = 0;
function finishLanding() {
clearTimeout(landingTimer);
const then = landed;
landed = null;
then?.();
}
function leaveHistory(then = null) {
const steps = depth();
if (steps > 0) {
closingHistory = true;
landed = then;
clearTimeout(landingTimer);
landingTimer = setTimeout(() => {
if (!closingHistory) return;
closingHistory = false;
finishLanding();
const queued = afterTraversal;
afterTraversal = null;
queued?.();
}, LANDING_LIMIT_MS);
history.go(-steps);
} else {
clearStoriesUrl();
then?.();
}
}
const onPopState = () => {
if (destroyed) return;
const queued = afterTraversal;
afterTraversal = null;
try {
handlePopState();
} finally {
queued?.();
}
};
function handlePopState() {
steppingBack = false;
if (closingHistory) {
closingHistory = false;
if (store.mode === 'closed') {
if (new URLSearchParams(location.search).has(PARAM_STORIES))
clearStoriesUrl();
finishLanding();
return;
}
}
const params = new URLSearchParams(location.search);
const id = params.get(PARAM_STORY);
if (id && storyById(id)) controller.openStory(id, { fromHistory: true });
else if (params.has(PARAM_STORIES))
store.mode === 'closed'
? controller.open({ fromHistory: true })
: controller.backToExplore({ fromHistory: true });
else if (store.mode !== 'closed') controller.close({ fromHistory: true });
}
addEventListener('popstate', onPopState);
// ── The person's own view, kept for when Stories closes ──
function saveView() {
const c = viewer.camera;
saved = {
position: c.positionWC.clone(),
heading: c.heading,
pitch: c.pitch,
roll: c.roll,
time: viewer.clock.currentTime.clone(),
animate: viewer.clock.shouldAnimate,
openedAt: Date.now(),
// The share state (layers, style, camera) as it was, for after a GEV
// scene has changed it.
hash: location.hash,
ranScene: false,
// Whether a scene played during this visit, which selects it in
// AUTHORING (ranScene clears once Back to Explore has undone the look).
playedScene: false,
// What AUTHORING had selected: playing a scene selects it there.
authoring: director.selection?.() ?? null,
};
}
function restoreView(saved, { keepCamera = false } = {}) {
if (!saved) return;
if (!keepCamera)
viewer.camera.setView({
destination: saved.position,
orientation: {
heading: saved.heading,
pitch: saved.pitch,
roll: saved.roll,
},
});
// Opened in GEV, the globe stays at the story's moment.
if (keepCamera) return;
restoreClock(saved);
}
/** A running clock carries on as if Stories had never paused it. */
function restoreClock(saved) {
viewer.clock.currentTime = saved.animate
? Cesium.JulianDate.addSeconds(
saved.time,
(Date.now() - saved.openedAt) / 1000,
new Cesium.JulianDate(),
)
: saved.time;
viewer.clock.shouldAnimate = saved.animate;
}
// A GEV scene turns on its own layers and look. Put the person's back by
// handing the share state saved on open to GEV's own restore, the path a
// pasted share link takes.
function restoreShareState(saved) {
if (!saved?.ranScene || !saved.hash) return;
// Directly, not by a hashchange: the share link skips a hash it already
// restored as Back landed, while the scene was still tearing down.
const share = director.styleManager?.shareLinkManager;
if (share?.restore?.(saved.hash.replace(/^#/, ''))) return;
const url = new URL(location.href);
url.hash = saved.hash;
history.replaceState(history.state, '', url.toString());
dispatchEvent(new HashChangeEvent('hashchange'));
}
// ── Explore on the person's globe: a pin per story, kept on its place ──
// Where a story sits: its framed area, else its cover shot.
const areaOf = (s) =>
s.area ?? { lat: s.cover.lat, lon: s.cover.lon, alt: s.cover.range };
let removePins = null;
let places = [];
// Pins follow the camera on every frame it draws. A change in which pins
// show goes through the store (Vue renders them); a move alone is written
// straight to each pin's transform, so a flight does not re-render Explore.
function placePins() {
const occluder = new Cesium.EllipsoidalOccluder(
viewer.scene.globe.ellipsoid,
viewer.camera.positionWC,
);
const rect = canvas.getBoundingClientRect();
const pins = places.map(({ id, at }) => {
const win = Cesium.SceneTransforms.worldToWindowCoordinates(
viewer.scene,
at,
);
const visible = !!win && occluder.isPointVisible(at);
return {
id,
x: rect.left + (win?.x ?? -9999),
y: rect.top + (win?.y ?? -9999),
visible,
};
});
const before = toRaw(store.pins);
const sameSet =
before.length === pins.length &&
pins.every(
(n, i) => n.id === before[i].id && n.visible === before[i].visible,
);
if (!sameSet) {
store.pins = pins;
return;
}
const layer = document.getElementById('pins');
const origin = layer?.getBoundingClientRect();
if (!origin) return;
for (const el of layer.querySelectorAll('.pin[data-id]')) {
const n = pins.find((pin) => pin.id === el.dataset.id);
if (!n) continue;
el.style.transform = `translate(${n.x - origin.left}px, ${n.y - origin.top}px) translate(-50%, -100%)`;
}
// Kept in step for the next render, without telling Vue.
for (let k = 0; k < pins.length; k++)
Object.assign(toRaw(before[k]), pins[k]);
}
function startPins() {
stopPins();
places = listStories().map((s) => {
const { lat, lon } = areaOf(s);
return { id: s.id, at: Cesium.Cartesian3.fromDegrees(lon, lat) };
});
removePins = viewer.scene.postRender.addEventListener(placePins);
governorRequestRender('stories-pins');
}
// ── Explore's idle tour: the globe turns from one story to the next ──
// Once a fly-in or the person's last touch has settled, Explore flies on to
// the next story in the feed every few seconds, at the same country-level
// view it opened at. Never with a story picked or with reduced motion, and
// it stops on its own a minute later. Each flight asks only for its own
// frames, and the tiles of each stop settle as any landing's do.
const TOUR_MS = 60000;
const TOUR_FLIGHT_S = 2.5;
const TOUR_DWELL_MS = 6000;
let tourTimer = 0;
// A press on the globe is under way (a drag): nothing restarts the tour.
let pressing = false;
let tourUntil = 0;
let tourIndex = 0;
const reduceMotion = () =>
globalThis.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches ??
false;
const touring = () =>
store.mode === 'explore' &&
!store.picked &&
!reduceMotion() &&
!destroyed &&
!viewer.isDestroyed?.();
function stopTour() {
clearTimeout(tourTimer);
tourTimer = 0;
}
function tourStep() {
tourTimer = 0;
const list = store.stories ?? [];
if (!touring() || Date.now() > tourUntil || list.length < 2) return;
tourIndex = (tourIndex + 1) % list.length;
const { lat, lon } = areaOf(list[tourIndex]);
flyTo({ lat, lon, alt: START_ALT }, TOUR_FLIGHT_S);
tourTimer = setTimeout(tourStep, TOUR_FLIGHT_S * 1000 + TOUR_DWELL_MS);
}
/** Tour on after `delayMs`, unless Explore is left or a story picked. */
function armTour(delayMs) {
stopTour();
tourTimer = setTimeout(() => {
if (!touring()) return (tourTimer = 0);
tourUntil = Date.now() + TOUR_MS;
tourStep();
}, delayMs);
}
// A touch, drag or wheel on Explore's globe stops the tour; it goes on
// once the person has let go for a while.
// A press stops it outright (a drag can last any time); letting go or a
// wheel turn starts the wait again.
const onExploreInput = (e) => {
pressing = e?.type === 'pointerdown';
if (store.mode !== 'explore' || store.picked) return;
if (pressing) stopTour();
else armTour(TOUR_DWELL_MS);
};
canvas.addEventListener('pointerdown', onExploreInput);
canvas.addEventListener('pointerup', onExploreInput);
canvas.addEventListener('pointercancel', onExploreInput);
canvas.addEventListener('wheel', onExploreInput, { passive: true });
function stopPins() {
stopTour();
stopSettling();
removePins?.();
removePins = null;
store.pins = [];
}
/**
* Where Explore opens and goes back to: country level, straight down over
* the first story in the feed (the whole globe's centre when there is
* none).
*/
const START_ALT = 2.5e6;
const WORLD_CENTRE = { lat: 22, lon: 30 };
function startView() {
const first = store.stories?.[0];
const at = first ? areaOf(first) : WORLD_CENTRE;
return { lat: at.lat, lon: at.lon, alt: START_ALT };
}
// Cesium draws on request, so the finer tiles for a view that has just
// landed would wait for the next change: keep frames coming until they
// have loaded, for at most 10 s.
let tilesTimer = 0;
let removeTiles = null;
function stopSettling() {
clearTimeout(tilesTimer);
tilesTimer = 0;
removeTiles?.();
removeTiles = null;
releaseContinuousRender('stories-tiles');
}
function settleTiles() {
stopSettling();
if (destroyed || viewer.isDestroyed?.()) return;
removeTiles = viewer.scene.postRender.addEventListener(() => {
if (viewer.scene.globe?.tilesLoaded) stopSettling();
});
holdContinuousRender('stories-tiles');
tilesTimer = setTimeout(stopSettling, 10000);
}
function flyTo({ lat, lon, alt }, duration = 1.6) {
// The whole globe straight down; a story's place at an angle, framed in
// the middle of the view rather than under the camera.
if (alt > 2e6) {
viewer.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(lon, lat, alt),
orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 },
duration,
complete: settleTiles,
});
return;
}
viewer.camera.flyToBoundingSphere(
new Cesium.BoundingSphere(Cesium.Cartesian3.fromDegrees(lon, lat), 0),
{
offset: new Cesium.HeadingPitchRange(
0,
Cesium.Math.toRadians(-60),
alt,
),
duration,
complete: settleTiles,
},
);
}
/** A picked story's place, close enough to see it, far enough to place it. */
const pickView = (s) => {
const a = areaOf(s);
return {
lat: a.lat,
lon: a.lon,
alt: Math.min(4e6, Math.max(60000, a.alt ?? 1.6e6)),
};
};
// ── GEV scenes: the camera readout comes from Cesium ──
let lastReadout = 0;
function startCesiumReadout() {
stopCesiumReadout();
removeReadout = viewer.scene.postRender.addEventListener(() => {
const now = performance.now();
if (now - lastReadout < 120) return;
lastReadout = now;
const c = viewer.camera.positionCartographic;
store.camera = {
lat: Cesium.Math.toDegrees(c.latitude),
lon: Cesium.Math.toDegrees(c.longitude),
altKm: Math.round(c.height / 1000),
};
});
}
function stopCesiumReadout() {
removeReadout?.();
removeReadout = null;
}
// A GEV scene's shots as installed (evidence packs add shots to a
// recipe), so chapters and length match what plays.
const untitled = (title, i) =>
!title ||
title === `Shot ${i + 1}` ||
title === t('Shot {n}', { n: i + 1 });
function syncSceneShots(story) {
const shots = director.listShots?.(story.sceneId) ?? [];
if (!shots.length) return;
story.chapters = shots.map((shot, i) => ({
id: shot.id,
wallMs: Math.round(shot.startSec * 1000),
shot: i + 1,
// A shipped scene's untitled shots are named by where they go; a
// title of the person's own stays.
title:
(untitled(shot.title, i) && story.places?.[i]) || shot.title || null,
caption: '',
}));
const last = shots.at(-1);
story.durationMs = Math.round((last.startSec + last.durationSec) * 1000);
// Key moments sit on the chapters that show them.
const fold = (text) =>
String(text ?? '')
.trim()
.toLowerCase();
story.events = (story.moments ?? []).flatMap(([color, label]) => {
const names = new Set([fold(label), fold(t(label))]);
const chapter = story.chapters.find((c) => names.has(fold(c.title)));
return chapter ? [{ color, label, wallMs: chapter.wallMs }] : [];
});
}
function dropPlayer() {
document.body.classList.remove('stories-scene');
stopCesiumReadout();
player?.destroy();
player = null;
}
function onTick(state) {
store.playback = {
wallMs: state.wallMs,
worldMs: state.worldMs,
durationMs: state.durationMs,
playing: state.playing,
exploring: state.exploring,
chapterIndex: state.chapterIndex,
};
if (state.playing) store.bigPlay = false;
}
// A story's tap plays or pauses, and a tap on empty Explore map lets go of
// the picked story; on a phone, touching the map drops the context sheet
// back to its peek.
let downAt = null;
const onDown = (e) => {
downAt = [e.clientX, e.clientY];
if (store.mode === 'story' && innerWidth <= 700 && store.sheet !== 'peek')
store.sheet = 'peek';
};
const onUp = (e) => {
if (!downAt) return;
const moved = Math.hypot(e.clientX - downAt[0], e.clientY - downAt[1]);
downAt = null;
if (moved >= 6) return;
if (store.mode === 'explore') {
if (store.picked) controller.pick(null);
return;
}
if (store.mode !== 'story' || !player) return;
if (store.playback.playing) {
player.pause();
store.bigPlay = true;
} else player.play();
};
canvas.addEventListener('pointerdown', onDown);
canvas.addEventListener('pointerup', onUp);
/** @returns {boolean} False when the camera is not free (Cockpit). */
function enterStories() {
// Stories owns the camera now. The shared navigation claim releases a
// tracked contact, orbit or flight, as a scene's does; Cockpit refuses,
// and the policy shows GEV's own toast for it.
const nav = director.styleManager;
if (nav?.runImmediateNavigation?.('stories', () => true) === false)
return false;
if (director.running) director.stopScene();
viewer.trackedEntity = undefined;
// Reopened while a scene from the last visit is still tearing down: the
// person's view from before that visit is still the one to come back to.
// The address keeps no share hash while Stories is open. Holding writes
// first writes any pending view change, so the saved hash is current.
shareLink()?.holdWrites?.(true);
// That write lands on the current entry; when it is already Stories'
// own (a Stories link, a reload), it carries no share hash.
if (history.state?.gevStories && location.hash)
history.replaceState(
history.state,
'',
location.pathname + location.search,
);
if (pendingView) {
saved = pendingView;
pendingView = null;
} else saveView();
document.body.classList.add('stories-mode');
return true;
}
// ── Card images: drawn once per story place from the base imagery ──
const ESRI_IMAGERY =
/arcgisonline\.com\/arcgis\/rest\/services\/world_imagery/i;
const thumbKeys = new Map();
let drawingThumbs = false;
let thumbsAgain = false;
async function drawThumbs() {
// A list that changes while cards are drawing is drawn again after.
if (drawingThumbs) return void (thumbsAgain = true);
drawingThumbs = true;
thumbsAgain = false;
try {
for (const story of listStories()) {
if (destroyed || store.mode === 'closed') break;
// Drawn only from the keyless Esri World Imagery, whose terms allow
// showing it with its credit; any other imagery leaves the
// placeholder unless the scene has its own image.
const base = viewer.imageryLayers?.get?.(0)?.imageryProvider;
const provider = ESRI_IMAGERY.test(base?.url ?? '') ? base : null;
if (!provider && !story.thumb) {
// A card drawn from Esri earlier goes: its credit is not on
// screen under another imagery.
if (store.thumbs?.[story.id]) {
const { [story.id]: _gone, ...rest } = store.thumbs;
store.thumbs = rest;
}
thumbKeys.delete(story.id);
continue;
}
// The place Explore frames for it, as its pin shows.
const a = areaOf(story);
const c = { lat: a.lat, lon: a.lon, range: a.alt };
const key = story.thumb
? story.thumb.slice(-32)
: `${c.lat},${c.lon},${c.range}`;
if (thumbKeys.get(story.id) === key && store.thumbs?.[story.id])
continue;
// A card image the person captured in AUTHORING wins.
const url = story.thumb || (await drawThumb(provider, c));
if (!url || destroyed) continue;
thumbKeys.set(story.id, key);
store.thumbs = { ...store.thumbs, [story.id]: url };
}
} finally {
drawingThumbs = false;
}
if (thumbsAgain && !destroyed) drawThumbs();
}
// Counts Explore entries, so a scene's late teardown restores the look only
// for the Explore it was left for.
let exploreEntry = 0;
function showExplore() {
// Feed lengths follow the scenes as installed.
for (const s of listStories()) syncSceneShots(s);
store.mode = 'explore';
store.storyId = null;
startPins();
const entry = ++exploreEntry;
const frame = () => {
const s = store.picked && storyById(store.picked);
flyTo(s ? pickView(s) : startView());
// The tour starts from the story the fly-in landed on.
if (!s) {
tourIndex = 0;
armTour(1600 + TOUR_DWELL_MS);
}
// Cards are drawn from the person's own imagery, so after their look
// is back.
drawThumbs();
};
if (!saved?.ranScene) return frame();
// Back from a scene: once it has torn down, the person's own layers,
// style and clock come back before Explore frames the globe, as on
// Close. The address keeps naming only Stories' place.
directorSettled(director).then(() => {
if (entry !== exploreEntry || store.mode !== 'explore' || destroyed)
return;
if (viewer.isDestroyed?.()) return;
const query = location.pathname + location.search;
restoreShareState(saved);
if (location.hash) history.replaceState(history.state, '', query);
restoreClock(saved);
saved.ranScene = false;
frame();
});
}
const controller = {
open({ fromHistory = false } = {}) {
if (!fromHistory && traversing()) {
afterTraversal = () => controller.open();
return;
}
if (store.mode !== 'closed') return;
if (!enterStories()) return;
store.picked = null;
showExplore();
if (!fromHistory) navigate({ [PARAM_STORIES]: 'explore' }, true);
},
close({ fromHistory = false, keepCamera = false } = {}) {
if (store.mode === 'closed') return;
if (!fromHistory && traversing()) {
afterTraversal = () => controller.close({ keepCamera });
return;
}
dropPlayer();
stopPins();
viewer.camera.cancelFlight();
// GEV comes back on screen now; `stories-mode` (keyboard guard, voice
// refusal) stays until the view is back, so nothing acts on GEV under
// a scene that is still tearing down.
document.body.classList.remove('stories-scene');
store.mode = 'closed';
store.storyId = null;
store.picked = null;
store.expanded = false;
const was = saved;
saved = null;
pendingView = was;
// A camera owner that takes over during the wait (the person dragging
// the globe, a layer's focus) keeps the camera: no snap back.
let navigated = false;
const onDrag = () => (navigated = true);
canvas.addEventListener('pointerdown', onDrag);
const stopWatching = registerNavigationAuthorityListener(
globalThis.window,
onDrag,
);
// Wait until the director is idle (a stopped scene, or one still
// tearing down from before a quick reopen, has released its camera,
// layers and look); put the camera and clock back; step history back
// over Stories' entries; then, once that has landed, put the share
// state back and let the address follow the live view again.
const finish = () => {
canvas.removeEventListener('pointerdown', onDrag);
stopWatching();
// Reopened meanwhile (the reopen took `was` over), or torn down.
if (pendingView !== was || destroyed || viewer.isDestroyed?.()) return;
pendingView = null;
document.body.classList.remove('stories-mode');
if (!navigated) restoreView(was, { keepCamera });
// AUTHORING shows what it showed before, unless the person opened
// the story there.
if (!keepCamera && was.playedScene && was.authoring)
director.selectShot?.(was.authoring.sceneId, was.authoring.shotId);
const afterLanding = () => {
// Open in GEV keeps this place and look: the live view is written
// over the earlier entry instead.
if (!keepCamera && !navigated) restoreShareState(was);
shareLink()?.holdWrites?.(false);
};
if (fromHistory) afterLanding();
else leaveHistory(afterLanding);
};
return directorSettled(director).then(finish);
},
pick(id) {
if (store.picked === id) return;
const s = id ? storyById(id) : null;
store.picked = s ? id : null;
flyTo(s ? pickView(s) : startView(), s ? 1.6 : 1.4);
if (s) stopTour();
else armTour(1400 + TOUR_DWELL_MS);
},
/**
* @param {string} id
* @param {{autoplay?: boolean, fromHistory?: boolean, atMs?: number}} [opts]
*/
openStory(id, { autoplay = false, fromHistory = false, atMs = 0 } = {}) {
const story = storyById(id);
if (!story) return;
if (!fromHistory && traversing()) {
afterTraversal = () => controller.openStory(id, { autoplay, atMs });
return;
}
if (store.mode === 'closed' && !enterStories()) return;
dropPlayer();
stopPins();
viewer.camera.cancelFlight();
store.storyId = id;
store.picked = id;
store.mode = 'story';
store.expanded = false;
store.ctxOpen = false;
store.sheet = 'peek';
store.bigPlay = !autoplay;
syncSceneShots(story);
store.playback = {
wallMs: atMs,
worldMs: null,
durationMs: story.durationMs,
playing: false,
exploring: false,
chapterIndex: 0,
};
// A GEV scene plays on the person's own globe and layers.
if (saved) saved.ranScene = saved.playedScene = true;
// The scene's own labels, videos and cards stay visible.
document.body.classList.add('stories-scene');
player = createGevPlayer(director, story, { onTick });
// Related stories show their card images too, after a link.
drawThumbs();
startCesiumReadout();
// Opened paused, a scene frames its first shot (or the moment asked).
if (atMs || !autoplay) player.seek(atMs);
if (autoplay) player.play();
if (!fromHistory) navigate({ [PARAM_STORY]: story.id }, true);
if (!store.hintSeen) {
store.hintSeen = true;
store.flashHint(t('Drag the map to explore · Resume any time'), 4200);
}
},
backToExplore({ fromHistory = false } = {}) {
// A second press while the first is landing does nothing more.
if (!fromHistory && traversing()) return;
dropPlayer();
store.expanded = false;
if (!fromHistory) {
// Back to Explore steps back to the Explore entry this story sits
// on, past any related stories opened since; a story with no
// Explore below it (a link) gets one.
const params = new URLSearchParams(location.search);
const to = exploreDepth();
if (params.has(PARAM_STORY) && to != null && depth() > to) {
steppingBack = true;
// A step that never lands gives up, as Close's does.
setTimeout(() => {
if (!steppingBack) return;
steppingBack = false;
const queued = afterTraversal;
afterTraversal = null;
queued?.();
}, LANDING_LIMIT_MS);
history.go(to - depth());
return;
}
navigate({ [PARAM_STORIES]: 'explore' }, true);
}
showExplore();
},
play: () => player?.play(),
pause: () => player?.pause(),
seek: (ms) => player?.seek(ms),
resume: () => player?.resume(),
focusEvent: (event) => player?.focus(event),
get kind() {
return player ? 'gev' : null;
},
/** Layout changed (panel width, sheet, feed size): place the pins again. */
reframe() {
if (removePins) governorRequestRender('stories-layout');
},
/**
* A GEV scene leaves Stories for GEV's own Scenes panel: the globe stays
* where the story was, and the scene and its current shot are selected
* there for authoring.
*/
async openInGev() {
const s = player?.story;
if (!s) return;
const atMs = store.playback.wallMs;
const shotId = s.chapters[store.playback.chapterIndex]?.id ?? null;
player.pause();
// After Close has settled: the scene's teardown restores GEV's look
// and panels, which would fold the Scenes panel again.
await controller.close({ keepCamera: true });
director.selectShot?.(s.sceneId, shotId);
director.styleManager?.setPanelCollapsed?.('scene-panel', false, {
explicit: true,
});
store.hostedToast = {
id: s.id,
title: s.title,
atMs,
when: anchorStamp(s, atMs, null),
};
},
/** The Stories place only: not the sender's camera, layers or style. */
shareLink() {
const here = new URL(location.href);
const url = new URL(here.pathname, here.origin);
for (const key of [PARAM_STORIES, PARAM_STORY])
if (here.searchParams.has(key))
url.searchParams.set(key, here.searchParams.get(key));
return url.toString();
},
destroy() {
if (destroyed) return;
controller.close();
destroyed = true;
// Torn down mid-close: what the close would undo once settled is
// undone now (keyboard and voice guard, held share writes).
document.body.classList.remove('stories-mode', 'stories-scene');
shareLink()?.holdWrites?.(false);
unsubscribeScenes?.();
useSavedScenes(null);
useInstalledScenes(null);
removeEventListener('popstate', onPopState);
canvas.removeEventListener('pointerdown', onDown);
canvas.removeEventListener('pointerdown', onExploreInput);
canvas.removeEventListener('pointerup', onExploreInput);
canvas.removeEventListener('pointercancel', onExploreInput);
canvas.removeEventListener('wheel', onExploreInput);
stopTour();
canvas.removeEventListener('pointerup', onUp);
},
};
// A shared link opens where it points once GEV has finished loading.
const params = new URLSearchParams(location.search);
if (params.has(PARAM_STORY) || params.has(PARAM_STORIES)) {
const id = params.get(PARAM_STORY);
const started = Date.now();
const whenReady = () => {
if (destroyed) return;
const loading = document.getElementById('loading-screen');
if (
loading &&
!loading.classList.contains('hidden') &&
Date.now() - started < 30000
) {
setTimeout(whenReady, 300);
return;
}
// A reload, or Back/Forward into a Stories entry: its history is
// already Stories' own, so open it as it stands.
if (history.state?.gevStories) {
// GEV's boot wrote its share hash onto the entry: Stories' entries
// carry none.
const own = Object.fromEntries(
[...params].filter(([k]) => k === PARAM_STORIES || k === PARAM_STORY),
);
history.replaceState(history.state, '', urlFor(own));
if (id && storyById(id))
controller.openStory(id, { fromHistory: true });
else {
controller.open({ fromHistory: true });
if (id) store.flashToast(t('That story is not available here'));
}
return;
}
// A new link: Explore sits under a story it opens, so Back lands there.
const landing = { stories: 'explore', depth: 0, explore: 0 };
history.replaceState(
{ ...(history.state ?? {}), gevStories: landing },
'',
urlFor({ [PARAM_STORIES]: 'explore' }),
);
if (id && storyById(id)) controller.openStory(id);
else {
controller.open({ fromHistory: true });
// A story saved on someone else's device, or no longer here.
if (id) store.flashToast(t('That story is not available here'));
}
};
setTimeout(whenReady, 300);
}
if (import.meta.env?.DEV) globalThis.__gevStories = { viewer, controller };
return controller;
}
+787
View File
@@ -0,0 +1,787 @@
// The Stories controller: what it leaves behind in history and on GEV's
// globe when Stories opens and closes.
import '../testSupport/registerDom.mjs';
import { registerHooks } from 'node:module';
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createPinia, setActivePinia } from 'pinia';
registerHooks({
load(url, context, next) {
if (url.endsWith('.webp'))
return {
format: 'module',
source: `export default ${JSON.stringify(url)};`,
shortCircuit: true,
};
return next(url, context);
},
});
const context = new Proxy(
{},
{ get: (target, name) => target[name] ?? (() => context), set: () => true },
);
globalThis.HTMLCanvasElement.prototype.getContext = (kind) =>
kind === 'webgl' ? null : context;
globalThis.requestAnimationFrame = () => 0;
globalThis.cancelAnimationFrame = () => {};
const { createStoriesController } = await import('./controller.js');
const { COCKPIT_REFUSAL_NOUNS } = await import('../navigationPolicy.js');
const { useStoriesStore } = await import('../ui/stores/stories.js');
const { listStories } = await import('./catalog.js');
function fakeViewer() {
const position = new Cesium.Cartesian3(1, 2, 3);
return {
scene: {
canvas: document.createElement('canvas'),
postRender: { addEventListener: () => () => {} },
preRender: {
listeners: new Set(),
addEventListener(fn) {
this.listeners.add(fn);
return () => this.listeners.delete(fn);
},
},
},
camera: {
positionWC: position,
positionCartographic: { latitude: 0.5, longitude: 0.2, height: 2e6 },
heading: 0,
pitch: -1,
roll: 0,
views: [],
setView(v) {
this.views.push(v);
},
cancelFlight() {},
flyTo() {},
flyToBoundingSphere() {},
rotations: 0,
rotate() {
this.rotations += 1;
},
},
clock: {
currentTime: Cesium.JulianDate.fromDate(new Date(Date.UTC(2026, 0, 1))),
shouldAnimate: false,
},
trackedEntity: undefined,
};
}
function fakeDirector({ refuse = false } = {}) {
const claims = [];
return {
claims,
running: false,
stops: 0,
stopScene() {
this.stops += 1;
},
whenIdle() {
return new Promise((resolve) => {
const check = () => (this.running ? setTimeout(check, 10) : resolve());
check();
});
},
listShots: () => [],
subscribeSceneClock: () => () => {},
seekScene() {},
startScene: async () => ({ started: true }),
selected: [],
selectShot(sceneId, shotId) {
this.selected.push([sceneId, shotId]);
return true;
},
styleManager: {
runImmediateNavigation: (noun) => {
claims.push(noun);
return !refuse;
},
panels: [],
setPanelCollapsed(id, collapsed) {
this.panels.push([id, collapsed]);
},
shareLinkManager: {
restored: [],
restore(hash) {
this.restored.push(hash);
return true;
},
},
},
};
}
function setup(options = {}) {
setActivePinia(createPinia());
history.replaceState(null, '', '/?x=1#v=2&lat=1');
const store = useStoriesStore();
const viewer = fakeViewer();
const director = fakeDirector(options);
const controller = createStoriesController({ viewer, director, store });
store.connect(controller, listStories());
return { store, viewer, director, controller };
}
test('Close steps back over every entry Stories pushed', async () => {
const { controller } = setup();
const steps = [];
const go = history.go;
history.go = (n) => steps.push(n);
try {
controller.open();
assert.equal(history.state.gevStories.depth, 1);
controller.openStory('gev:flights-radar');
assert.equal(history.state.gevStories.depth, 2);
await controller.close();
// Back after Close would otherwise land on ?story=… and reopen it.
assert.deepEqual(steps, [-2]);
} finally {
history.go = go;
controller.destroy();
}
});
test('Close from a Stories link clears Stories from the URL in place', async () => {
const { controller } = setup();
history.replaceState(null, '', '/?stories=explore#v=2');
controller.open({ fromHistory: true });
await controller.close();
assert.equal(new URL(location.href).searchParams.has('stories'), false);
assert.equal(location.hash, '#v=2');
controller.destroy();
});
test('Cockpit keeps the camera: Stories does not open', () => {
const { controller, store, director } = setup({ refuse: true });
controller.open();
assert.equal(store.mode, 'closed');
assert.equal(director.stops, 0);
// The navigation policy shows the refusal; it needs a sentence for the noun.
assert.deepEqual(director.claims, ['stories']);
assert.ok(COCKPIT_REFUSAL_NOUNS.includes('stories'));
controller.destroy();
});
test('reopening while a scene tears down keeps the view from before Stories', async () => {
const { controller, viewer, director } = setup();
const before = viewer.camera.positionWC;
controller.open();
controller.openStory('gev:bhote-koshi-nepal-scene');
director.running = true;
const closing = controller.close();
// The scene has moved the camera; the person opens Stories again at once.
viewer.camera.positionWC = new Cesium.Cartesian3(9, 9, 9);
controller.open();
director.running = false;
await closing;
assert.equal(
viewer.camera.views.length,
0,
'no restore under the reopened Stories',
);
await controller.close();
const { x, y, z } = viewer.camera.views.at(-1).destination;
assert.deepEqual({ x, y, z }, { x: before.x, y: before.y, z: before.z });
controller.destroy();
});
test('after a GEV scene, the person’s view comes back once the scene has torn down', async () => {
const { controller, viewer, director } = setup();
controller.open();
controller.openStory('gev:bhote-koshi-nepal-scene');
director.running = true;
const closing = controller.close();
assert.equal(viewer.camera.views.length, 0, 'not under the stopping scene');
setTimeout(() => (director.running = false), 120);
await closing;
assert.equal(viewer.camera.views.length, 1);
controller.destroy();
});
test('a share link carries the story, not the sender’s camera and layers', () => {
const { controller } = setup();
controller.open();
controller.openStory('gev:flights-radar');
const link = new URL(controller.shareLink());
assert.equal(link.searchParams.get('story'), 'gev:flights-radar');
assert.equal(link.hash, '');
assert.equal(link.searchParams.has('x'), false, 'no other query parameters');
controller.destroy();
});
/** Record history.go calls instead of traversing. */
function recordGo(t) {
const steps = [];
const go = history.go;
history.go = (n) => steps.push(n);
t.after(() => {
history.go = go;
});
return steps;
}
test('Back to Explore after a related story steps past both stories', (t) => {
const { controller } = setup();
const steps = recordGo(t);
controller.open();
controller.openStory('gev:flights-radar');
controller.openStory('gev:orbital-watch'); // a related story
assert.equal(history.state.gevStories.depth, 3);
assert.equal(history.state.gevStories.explore, 1);
controller.backToExplore();
// A second click before the traversal lands does nothing more.
controller.backToExplore();
assert.deepEqual(steps, [-2]);
controller.destroy();
});
test('a second Close after a quick reopen still waits for the scene to tear down', async () => {
const { controller, viewer, director } = setup();
controller.open();
controller.openStory('gev:bhote-koshi-nepal-scene');
director.running = true;
controller.close();
controller.open(); // reopened while the scene is still stopping
const closing = controller.close(); // Explore: no GEV story on screen
assert.ok(closing, 'this Close waits too');
assert.equal(viewer.camera.views.length, 0, 'nothing restored yet');
setTimeout(() => (director.running = false), 120);
await closing;
assert.equal(viewer.camera.views.length, 1);
controller.destroy();
});
test('a reload of a Stories entry keeps its history; Close steps all of it back', async (t) => {
setActivePinia(createPinia());
history.replaceState(
{ gevStories: { story: 'gev:flights-radar', depth: 2, explore: 1 } },
'',
'/?story=gev%3Aflights-radar',
);
const steps = recordGo(t);
const store = useStoriesStore();
const controller = createStoriesController({
viewer: fakeViewer(),
director: fakeDirector(),
store,
});
store.connect(controller, listStories());
await new Promise((resolve) => setTimeout(resolve, 400));
assert.equal(store.storyId, 'gev:flights-radar');
assert.equal(history.state.gevStories.depth, 2, 'no extra entry pushed');
await controller.close();
assert.deepEqual(steps, [-2]);
controller.destroy();
});
test('a new story link puts Explore under the story', async (t) => {
setActivePinia(createPinia());
history.replaceState(null, '', '/?story=gev%3Aflights-radar');
const steps = recordGo(t);
const store = useStoriesStore();
const controller = createStoriesController({
viewer: fakeViewer(),
director: fakeDirector(),
store,
});
store.connect(controller, listStories());
await new Promise((resolve) => setTimeout(resolve, 400));
assert.equal(store.storyId, 'gev:flights-radar');
assert.deepEqual(history.state.gevStories, {
story: 'gev:flights-radar',
depth: 1,
explore: 0,
});
controller.backToExplore();
assert.deepEqual(steps, [-1]);
controller.destroy();
});
test('Open in GEV hands a GEV scene to the Scenes panel at its current shot', async () => {
const { controller, store, director, viewer } = setup();
controller.open();
controller.openStory('gev:bhote-koshi-nepal-scene');
store.playback = { ...store.playback, chapterIndex: 0 };
const shotId =
store.byId('gev:bhote-koshi-nepal-scene').chapters[0]?.id ?? null;
await controller.openInGev();
assert.equal(store.mode, 'closed');
assert.equal(
viewer.camera.views.length,
0,
'the globe stays where the story was',
);
assert.deepEqual(director.selected, [['bhote-koshi-nepal-scene', shotId]]);
assert.deepEqual(director.styleManager.panels, [['scene-panel', false]]);
controller.destroy();
});
const tick = (ms = 30) => new Promise((resolve) => setTimeout(resolve, ms));
test('Close while Back to Explore is landing steps back only the rest of the way', async (t) => {
const { controller } = setup();
const steps = recordGo(t);
controller.open();
controller.openStory('gev:flights-radar');
controller.backToExplore();
controller.close(); // before the Back has landed
assert.deepEqual(steps, [-1], 'Close waits for the Back to land');
// The Back lands on the Explore entry.
history.replaceState(
{ gevStories: { stories: 'explore', depth: 1, explore: 1 } },
'',
'/?stories=explore',
);
dispatchEvent(new PopStateEvent('popstate'));
await tick();
assert.deepEqual(steps, [-1, -1], 'two entries in all, as Stories pushed');
controller.destroy();
});
test('history steps back only after the scene has torn down', async (t) => {
const { controller, director } = setup();
const steps = recordGo(t);
controller.open();
controller.openStory('gev:bhote-koshi-nepal-scene');
director.running = true;
const closing = controller.close();
await tick(60);
assert.deepEqual(steps, [], 'no traversal while the scene is stopping');
director.running = false;
await closing;
assert.deepEqual(steps, [-2]);
controller.destroy();
});
test('Back out of Stories after a scene puts the share state back directly', async () => {
const { controller, director } = setup();
controller.open();
controller.openStory('gev:bhote-koshi-nepal-scene');
// Back has already landed on the page Stories opened from.
await controller.close({ fromHistory: true });
assert.deepEqual(director.styleManager.shareLinkManager.restored, [
'v=2&lat=1',
]);
controller.destroy();
});
/** Land a recorded traversal: the page Stories opened from becomes current. */
function land(hash = '#v=2&lat=1') {
history.replaceState(null, '', `/?x=1${hash}`);
dispatchEvent(new PopStateEvent('popstate'));
}
test('Close after a GEV scene puts the share state back once the step back lands', async (t) => {
const { controller, director } = setup();
const steps = recordGo(t);
const restored = director.styleManager.shareLinkManager.restored;
controller.open();
controller.openStory('gev:bhote-koshi-nepal-scene');
await controller.close();
assert.deepEqual(steps, [-2]);
assert.deepEqual(restored, [], 'not before the landing');
land();
assert.deepEqual(restored, ['v=2&lat=1']);
controller.destroy();
});
test('Open in GEV steps back over Stories without putting the old view back', async (t) => {
const { controller, director, viewer } = setup();
const steps = recordGo(t);
controller.open();
controller.openStory('gev:bhote-koshi-nepal-scene');
await controller.openInGev();
assert.deepEqual(steps, [-2], 'Back never reopens Stories');
land();
assert.deepEqual(director.styleManager.shareLinkManager.restored, []);
assert.equal(viewer.camera.views.length, 0);
controller.destroy();
});
test('a drag on the globe while a scene tears down keeps the camera where it went', async () => {
const { controller, viewer, director } = setup();
controller.open();
controller.openStory('gev:bhote-koshi-nepal-scene');
director.running = true;
const closing = controller.close();
viewer.scene.canvas.dispatchEvent(new Event('pointerdown'));
director.running = false;
await closing;
assert.equal(viewer.camera.views.length, 0, 'no snap back');
controller.destroy();
});
test('a step back that never lands gives up and runs what was waiting', async (t) => {
const { controller, store } = setup();
recordGo(t);
controller.open();
controller.openStory('gev:flights-radar');
await controller.close(); // no popstate will come
controller.open(); // queued behind the traversal
assert.equal(store.mode, 'closed');
await new Promise((resolve) => setTimeout(resolve, 2200));
assert.equal(store.mode, 'explore', 'opened once the traversal gave up');
controller.destroy();
});
test('a reloaded Stories entry drops the share hash GEV wrote on boot', async () => {
setActivePinia(createPinia());
history.replaceState(
{ gevStories: { stories: 'explore', depth: 1, explore: 1 } },
'',
'/?stories=explore#v=2&lat=7',
);
const store = useStoriesStore();
const controller = createStoriesController({
viewer: fakeViewer(),
director: fakeDirector(),
store,
});
store.connect(controller, listStories());
await new Promise((resolve) => setTimeout(resolve, 400));
assert.equal(store.mode, 'explore');
assert.equal(location.hash, '');
assert.equal(new URL(location.href).searchParams.get('stories'), 'explore');
controller.destroy();
});
test('a scene saved to Stories from AUTHORING joins the list at once', () => {
setActivePinia(createPinia());
history.replaceState(null, '', '/');
const store = useStoriesStore();
const director = fakeDirector();
let listener = null;
let mine = [];
director.subscribe = (fn) => {
listener = fn;
return () => (listener = null);
};
director.storyScenes = () => mine;
const controller = createStoriesController({
viewer: fakeViewer(),
director,
store,
});
store.connect(controller, listStories());
assert.equal(store.byId('gev:my-scene'), null);
mine = [
{
id: 'my-scene',
title: 'Harbour at dawn',
camera: { lat: 51.5, lon: -0.1, alt: 2000, heading: 0, pitch: -30 },
shotCount: 2,
},
];
listener({ type: 'stories-changed' });
const story = store.byId('gev:my-scene');
assert.equal(story?.title, 'Harbour at dawn');
assert.equal(story.mine, true);
assert.equal(store.stories[0].id, 'gev:my-scene', 'the person’s own first');
mine = [];
listener({ type: 'stories-changed' });
assert.equal(store.byId('gev:my-scene'), null, 'removed from Stories');
controller.destroy();
assert.equal(listener, null, 'unsubscribed');
});
test('Back to Explore after a scene puts the look back once the scene has torn down, then frames Explore', async () => {
const { controller, viewer, director } = setup();
const flights = [];
viewer.camera.flyTo = (f) => flights.push(f);
viewer.camera.flyToBoundingSphere = (f) => flights.push(f);
const share = director.styleManager.shareLinkManager;
// GEV's restore writes the hash it applies; Explore's address drops it.
share.restore = function (hash) {
this.restored.push(hash);
history.replaceState(history.state, '', `${location.search}#${hash}`);
return true;
};
controller.open();
controller.openStory('gev:bhote-koshi-nepal-scene');
director.running = true;
flights.length = 0;
controller.backToExplore({ fromHistory: true });
await tick(30);
assert.deepEqual(share.restored, [], 'not under the stopping scene');
assert.equal(flights.length, 0, 'Explore waits for the scene');
director.running = false;
await tick(40);
assert.deepEqual(share.restored, ['v=2&lat=1']);
assert.equal(location.hash, '', 'the address names only Stories');
assert.equal(flights.length, 1, 'then Explore frames the globe');
// A later Back to Explore with no scene in between restores nothing more.
controller.openStory('gev:bhote-koshi-nepal-scene');
controller.pause();
controller.backToExplore({ fromHistory: true });
await tick(40);
assert.equal(share.restored.length, 2, 'each scene is undone once');
controller.destroy();
});
test('a story opened while the scene tears down is not undone by the late restore', async () => {
const { controller, director } = setup();
controller.open();
controller.openStory('gev:bhote-koshi-nepal-scene');
director.running = true;
controller.backToExplore({ fromHistory: true });
controller.openStory('gev:flights-radar');
director.running = false;
await tick(40);
assert.deepEqual(director.styleManager.shareLinkManager.restored, []);
controller.destroy();
});
test('Explore tours from story to story once idle, stops on a pick or a touch, and on Close', async (t) => {
t.mock.timers.enable({ apis: ['setTimeout', 'Date'] });
const { controller, viewer, store } = setup();
const flights = [];
viewer.camera.flyTo = (f) => flights.push(f);
viewer.camera.flyToBoundingSphere = (f) => flights.push(f);
controller.open();
assert.equal(flights.length, 1, 'the fly-in to the first story');
t.mock.timers.tick(7000);
assert.equal(flights.length, 1, 'a moment on the first story');
t.mock.timers.tick(1000);
assert.equal(flights.length, 2, 'then on to the next');
t.mock.timers.tick(8500);
assert.equal(flights.length, 3, 'and the next');
// A press holds the tour however long the drag lasts; letting go starts
// the wait again.
viewer.scene.canvas.dispatchEvent(new Event('pointerdown'));
t.mock.timers.tick(20000);
assert.equal(flights.length, 3, 'nothing flies under a drag');
viewer.scene.canvas.dispatchEvent(new Event('pointerup'));
t.mock.timers.tick(5000);
assert.equal(flights.length, 3);
t.mock.timers.tick(1500);
assert.equal(flights.length, 4);
// A picked story stops it.
controller.pick(store.stories[0].id);
const picked = flights.length;
t.mock.timers.tick(30000);
assert.equal(flights.length, picked);
// Unpicked, it tours again, for a minute at most.
controller.pick(null);
for (let i = 0; i < 24; i++) t.mock.timers.tick(5000);
const after = flights.length;
assert.ok(after > picked + 3, 'touring again');
for (let i = 0; i < 12; i++) t.mock.timers.tick(5000);
assert.equal(flights.length, after, 'stopped on its own');
controller.pick(null);
controller.destroy();
});
test('a new Explore link keeps the address free of the share hash GEV writes as Stories opens', async () => {
setActivePinia(createPinia());
history.replaceState(null, '', '/?stories=explore');
const store = useStoriesStore();
const director = fakeDirector();
// Holding writes first writes the view change still waiting.
director.styleManager.shareLinkManager.holdWrites = (held) => {
if (held) history.replaceState(history.state, '', `${location.search}#v=2`);
};
const controller = createStoriesController({
viewer: fakeViewer(),
director,
store,
});
store.connect(controller, listStories());
await tick(400);
assert.equal(store.mode, 'explore');
assert.equal(location.hash, '');
assert.equal(location.search, '?stories=explore');
controller.destroy();
});
test('a saved scene’s topics become Explore chips, and its captured card image is used', async () => {
const { metaFor, topicsOf } = await import('./storyMeta.js');
setActivePinia(createPinia());
history.replaceState(null, '', '/');
const store = useStoriesStore();
const director = fakeDirector();
director.subscribe = () => () => {};
director.storyScenes = () => [
{
id: 'harbour',
title: 'Harbour at dawn',
camera: { lat: 51.5, lon: -0.1, alt: 2000 },
shotCount: 1,
thumb: 'data:image/jpeg;base64,BBBB',
tags: ['Maritime', 'Floods'],
},
];
const controller = createStoriesController({
viewer: fakeViewer(),
director,
store,
});
store.connect(controller, listStories());
const story = store.byId('gev:harbour');
assert.deepEqual(metaFor(story).topics, ['Maritime', 'Floods']);
const chips = topicsOf(store.stories);
assert.ok(chips.includes('Maritime') && chips.includes('Floods'));
assert.ok(
chips.indexOf('Floods') < chips.indexOf('Maritime'),
'in AUTHORING’s tag order',
);
controller.open();
await tick(20);
assert.equal(store.thumbs['gev:harbour'], 'data:image/jpeg;base64,BBBB');
controller.destroy();
});
test('Close after a story puts AUTHORING’s own selection back; Open in GEV keeps the story’s', async () => {
const { controller, director } = setup();
director.selection = () => ({ sceneId: null, shotId: null });
controller.open();
controller.openStory('gev:flights-radar');
await controller.close({ fromHistory: true });
assert.deepEqual(director.selected.at(-1), [null, null], 'back to none');
director.selected.length = 0;
controller.open();
controller.openStory('gev:flights-radar');
await controller.openInGev();
assert.deepEqual(
director.selected.map(([sceneId]) => sceneId),
['flights-radar'],
'the story’s scene, nothing put back',
);
controller.destroy();
});
test('a built-in scene no longer in the project does not list; an unknown story link says so', async () => {
setActivePinia(createPinia());
history.replaceState(null, '', '/?story=gev%3Asomeone-elses');
const store = useStoriesStore();
const director = fakeDirector();
director.hasScene = (id) => id !== 'flights-radar';
const toasts = [];
store.flashToast = (text) => toasts.push(text);
const controller = createStoriesController({
viewer: fakeViewer(),
director,
store,
});
store.connect(controller, listStories());
assert.equal(store.byId('gev:flights-radar'), null);
assert.ok(store.byId('gev:orbital-watch'));
await tick(400);
assert.equal(store.mode, 'explore');
assert.equal(toasts.length, 1, 'the person is told');
controller.destroy();
assert.equal(document.body.classList.contains('stories-mode'), false);
});
test('Close after Back to Explore still puts AUTHORING’s selection back', async () => {
const { controller, director } = setup();
director.selection = () => ({ sceneId: null, shotId: null });
controller.open();
controller.openStory('gev:flights-radar');
controller.backToExplore({ fromHistory: true });
await tick(40);
await controller.close({ fromHistory: true });
assert.deepEqual(director.selected.at(-1), [null, null]);
controller.destroy();
});
test('the person’s unsaved scenes list as drafts, which cannot be shared', () => {
setActivePinia(createPinia());
history.replaceState(null, '', '/');
const store = useStoriesStore();
const director = fakeDirector();
director.subscribe = () => () => {};
director.draftScenes = () => [
{
id: 'sketch',
title: 'Sketch',
camera: { lat: 1, lon: 2, alt: 3000 },
shotCount: 1,
thumb: '',
tags: [],
},
];
const controller = createStoriesController({
viewer: fakeViewer(),
director,
store,
});
store.connect(controller, listStories());
const draft = store.byId('gev:sketch');
assert.equal(draft?.draft, true);
assert.equal(draft.mine, true, 'local only: no Share');
controller.destroy();
});
test('under imagery other than Esri, a card drawn from Esri earlier is dropped', async () => {
const { controller, viewer, store } = setup();
viewer.imageryLayers = {
get: () => ({
imageryProvider: { url: 'https://tile.openstreetmap.org/' },
}),
};
store.thumbs = { 'gev:flights-radar': 'data:image/jpeg;base64,ESRI' };
controller.open();
await tick(20);
assert.equal(store.thumbs['gev:flights-radar'], undefined);
controller.destroy();
});
test('the tour waits again after a wheel turn or a cancelled press, and a list change during a drag does not restart it', async (t) => {
t.mock.timers.enable({ apis: ['setTimeout', 'Date'] });
const { controller, viewer, director } = setup();
let listener = null;
director.subscribe = (fn) => ((listener = fn), () => {});
const flights = [];
viewer.camera.flyTo = (f) => flights.push(f);
viewer.camera.flyToBoundingSphere = (f) => flights.push(f);
controller.destroy();
const store = useStoriesStore();
const again = createStoriesController({ viewer, director, store });
store.connect(again, listStories());
again.open();
const canvas = viewer.scene.canvas;
for (const type of ['wheel', 'pointercancel']) {
const before = flights.length;
canvas.dispatchEvent(new Event(type));
t.mock.timers.tick(5900);
assert.equal(flights.length, before, `${type}: waits`);
t.mock.timers.tick(200);
assert.equal(flights.length, before + 1, `${type}: then tours`);
}
canvas.dispatchEvent(new Event('pointerdown'));
listener({ type: 'stories-changed' });
const held = flights.length;
t.mock.timers.tick(30000);
assert.equal(flights.length, held, 'nothing flies under the drag');
again.destroy();
});
test('teardown mid-close lets the share link write again', () => {
const { controller, director } = setup();
const held = [];
director.styleManager.shareLinkManager.holdWrites = (on) => held.push(on);
controller.open();
controller.destroy();
assert.equal(held.at(-1), false);
});
test('place names name only a shipped scene’s untitled shots', () => {
const { controller, director, store } = setup();
director.listShots = () => [
{ id: 'a', title: 'Shot 1', startSec: 0, durationSec: 5 },
{ id: 'b', title: 'Over the harbour', startSec: 5, durationSec: 5 },
];
controller.openStory('gev:flights-radar');
const story = store.byId('gev:flights-radar');
assert.deepEqual(
story.chapters.map((c) => c.title),
['The Atlantic', 'Over the harbour'],
);
controller.destroy();
});
+46
View File
@@ -0,0 +1,46 @@
/** Index of the chapter playing at a wall position (milliseconds). */
export function chapterAt(story, w) {
let k = 0;
story.chapters.forEach((c, i) => {
if (w >= c.wallMs) k = i;
});
return k;
}
/**
* Where GEV's credit line sits while Stories is open: inside the map's bottom
* left, clear of Explore's desktop feed when that covers the map's left side
* (on a phone the feed is a sheet below the map). Null when there is no map,
* so GEV's own placement applies.
* @param {{map?: DOMRect|null, feed?: DOMRect|null, width: number, height: number}} view
* @returns {{bottom: number, left: number} | null} Pixels from the window's bottom and left.
*/
export function creditPlacement({ map, feed, width, height }) {
if (!map?.width) return null;
const besideFeed =
!!feed?.width &&
feed.left <= map.left + 1 &&
feed.right < map.right &&
feed.top < map.bottom - 1 &&
feed.bottom >= map.bottom - 1;
const gap = width <= 700 ? 10 : 24;
return {
bottom: Math.max(0, height - map.bottom) + 6,
left: besideFeed ? feed.right + 14 : map.left + gap,
};
}
/**
* Where the Stories button sits: just left of the leftmost visible control
* in GEV's top-right corner — the ACTIVE STYLE readout in GEV, the account
* avatar (with or beside the readout) in GEV Hosted — top-aligned with it.
* @param {Array<DOMRect|null|undefined>} corner The corner controls' boxes.
* @param {number} width The window's width.
* @returns {{top: number, right: number}} Pixels from the top and right.
*/
export function entryPlacement(corner, width) {
const shown = corner.filter((r) => r && r.width > 0 && r.height > 0);
if (!shown.length) return { top: 14, right: 14 };
const left = shown.reduce((a, b) => (b.left < a.left ? b : a));
return { top: left.top, right: width - left.left + 10 };
}
+3
View File
@@ -0,0 +1,3 @@
/** GEV eye logo as an SVG symbol, referenced as `<use href="#gevLogo">`. */
export const GEV_LOGO_SYMBOL =
'<symbol id="gevLogo" viewBox="180 120 775 520"><path fill="#4454727a" stroke="#48b" stroke-width="10" fill-rule="evenodd" d="M567.5,623c-163.183,0-303.026-99.084-361.823-239.922C257.508,238.76,401.037,135,570,135c166.451,0,308.222,100.7,361.954,241.667C874.771,520.905,733.152,623,567.5,623ZM567,156c124.816,0,226,101.184,226,226S691.816,608,567,608,341,506.816,341,382,442.184,156,567,156ZM816,256.213A272.836,272.836,0,0,1,846,381M793.574,488.677a249.545,249.545,0,0,0,3.239-208.3A303.384,303.384,0,0,0,816,256.213a274.468,274.468,0,0,1-1.516,252.475q-0.927,1.758-1.88,3.5-1.632-2.238-3.306-4.446Q801.826,497.884,793.574,488.677ZM345.5,490.85q-8.055,9.164-15.37,18.966a274.353,274.353,0,0,1-3.748-250.343q7.347,10.012,15.469,19.393A249.512,249.512,0,0,0,345.5,490.85Z"/><path fill="#00f6ff" stroke="#000" stroke-width="1" fill-rule="evenodd" d="M568,179.985c107.678,0,194.968,88.655,194.968,198.015S675.678,576.015,568,576.015,373.032,487.36,373.032,378,460.322,179.985,568,179.985Z"/><path fill="none" stroke="#00f6ff" stroke-width="6.99" stroke-linecap="round" fill-rule="evenodd" d="M569.5,499.831A120.331,120.331,0,1,1,689.831,379.5,120.33,120.33,0,0,1,569.5,499.831Zm65.1-50.585c1.225-.4,3.268-2.858,4.492-3.677s3.268-4.083,3.675-5.717,1.227-4.495,1.634-6.126a36.015,36.015,0,0,0,.818-6.135,14.639,14.639,0,0,0-.407-2.855l-3.266,6.127s-4.9,2.04-5.315,3.674-0.817,4.088-.817,4.088a61.248,61.248,0,0,0-2.45,6.133C632.554,446.388,633.372,449.66,634.6,449.246ZM461.011,377.072c0.72-1.105,1.928-6.276,1.6-7.894-0.411-2.037,1.225-6.94,1.225-9.392s4.083-7.358,4.9-9.4,4.491-7.349,6.535-10.623-0.4-2.038-2.449-.809,1.225-3.274,2.449-4.086,8.172-5.72,8.172-5.72,2.449-2.454-.409-7.762c-2.211-4.1,0-4.5,0-6.128a2.43,2.43,0,0,0-1.28-.223c2.129-2.952,4.408-5.788,6.811-8.512A108.871,108.871,0,0,0,494.612,458.6a0.454,0.454,0,0,1,.683-0.363c2.043,0.819,2.449-.4,4.085-0.4s4.086-2.043,4.086-2.043l-1.641-4.9,1.641-6.126,2.041-5.717s0-4.095-2.041-4.5-5.722-4.081-6.946-4.081a10.018,10.018,0,0,1-4.491-1.636c-1.227-.813-3.677-1.634-4.5-2.857a31.144,31.144,0,0,1-2.858-5.314c-0.816-2.039-.409-2.039-3.681-5.715s-2.452-2.863-4.9-4.093-3.265-2.443-5.308-3.263a13.378,13.378,0,0,1-4.5-2.857,4.884,4.884,0,0,0-2.711-1.519,110.041,110.041,0,0,1-2.595-23.808C460.98,378.618,461,377.84,461.011,377.072Zm35.743-78.7a13.8,13.8,0,0,0-1.051,2.589c-0.408,1.638,2.864.416,2.864,0.416L502.239,303l4.5-1.631a13.741,13.741,0,0,1,4.083-4.5c2.857-2.043,2.454-2.452,3.677-4.084s0-.006,5.314-5.732,8.167-5.718,8.167-5.718,1.915-2.1,3.244-3.895A108.986,108.986,0,0,0,496.754,298.368Zm41.024,56.1c-1.224.82-5.715,3.272-6.944,5.315a22.681,22.681,0,0,0-2.859,6.535,31.042,31.042,0,0,0-.408,6.538c0,2.854-.41,4.5,0,6.949s4.5,8.568,6.128,10.623c1.63,2.038,3.674,4.483,5.719,5.713a47.235,47.235,0,0,1,4.9,3.674,4.03,4.03,0,0,0,4.9,1.223c3.272-1.223,6.538-1.223,9.4-2.853s7.353-3.685,7.353-1.231,1.632,4.084,4.082,3.272,6.539-2.858,6.13,0S577,406.764,577,408.4s-0.4,3.265.818,4.495,4.5,3.265,4.5,4.49,0.409,5.311,1.229,6.946,1.639,4.08.823,5.724-2.434,6.123-2.434,6.123-0.779,3.676-.37,4.9a12.683,12.683,0,0,0,3.332,4.906c2.043,2.042,1.771,4.492,2.994,6.124s2.993,6.539,2.993,6.539l1.236,4.088v3.677s7.966-1.231,9.591-1.64a30.673,30.673,0,0,0,8.618-4.9c1.636-1.632,1.311-2.856,3.349-4.488s5.762-4.5,5.762-4.5l-0.387-6.126,4.914-6.544,3.684-3.677s3.267-4.484,2.865-6.128c-0.413-1.628-1.231-9.8-1.231-9.8a37.972,37.972,0,0,1,2.863-5.313c1.224-1.634,1.227-3.678,3.679-5.719a33.109,33.109,0,0,0,5.306-6.126c1.229-1.634,3.681-4.9,4.5-6.127a21.871,21.871,0,0,0,1.635-4.894l-7.355,1.216c-2.45-4.082-9.392-13.073-10.621-15.112a37.04,37.04,0,0,1-2.861-7.76c-0.4-1.634-2.445-6.131-2.856-7.356s-3.27-4.908-4.088-6.128-3.675-2.043-5.309-3.268-11.843-3.27-11.843-3.27-3.129-1.991-4.088-1.226c-4.083,3.269-13.48,1.226-15.523.415s-3.269-2.041-3.269-3.272-1.835-7.143-1.835-7.143-3.985.705-5.213,0.705a20.333,20.333,0,0,1-4.442-1.276s-4.055.379-5.693,1.2a61.205,61.205,0,0,1-6.115,2.438,36.488,36.488,0,0,1-4.488.814c-3.671-1.636-6.529,2.45-7.352,4.079s-2.445,2.454-2.445,4.084S539,353.659,537.778,354.471Zm18.191-54.739-3.128-4.5-3.727,2.045V304.5l-3.839-1.5-1.715,3.674,1.685,2.452L549.114,305v4.129l8.478-1.636,3.164-2.449Zm71.15-12.676c-1.669.869-4.808,3.094-6,1.894-1.227-1.218-4.086-3.423-4.086-3.423,2.448-1.636-4.9-5.212-4.9-5.212l-8.576-1.022h-6.125c-1.227,0-3.681.825-5.723,0.825s-6.943,3.583-8.577,3.994-5.314,2.5-6.944,2.5-4.088,3.086-4.088,3.086-2.856,5.218-.4,4.4,5.717-.858,6.122.367,1.227,3.242,1.636,4.471,6.131,1.618,6.131,1.618a18.551,18.551,0,0,1,2.038-3.683c1.227-1.634,2.452-3.675,2.452-3.675s2.044,4.082,2.452,5.3-0.818,4.908-.818,4.908-4.491,2.852-5.716,2.852-8.175-6.126-8.175-6.126a25.4,25.4,0,0,0-4.489,2.043c-2.856,2.861-5.717,5.31-5.717,5.31a17.057,17.057,0,0,0-4.081,2.046c-1.629,1.222-5.138,1.487-6.117,2.854-2.039,2.863.84,4.9,0.84,4.9l-2.408,3.271-1.548,1.225-5.553,1.221-2.751.616c0.4,1.227,1.258,5.105,1.258,5.105s-1.87,6.943,0,6.943c0,0,4.276,1.64,5.5,1.64s2.625,0.4,4.265-1.227a59.861,59.861,0,0,0,5.156-6.538,8.0Line truncated
+143
View File
@@ -0,0 +1,143 @@
import { chapterAt } from './format.js';
/** Longest Stories waits for a scene to tear down before going on anyway. */
export const SETTLE_LIMIT_MS = 15000;
/**
* Resolves once the director is idle: no run, and every LOAD, seek and
* interaction settled (SceneDirector.whenIdle). A teardown that never
* finishes is given SETTLE_LIMIT_MS, so a stuck scene cannot leave Stories
* unable to close; that case is logged.
* @param {import('../scenes/director.js').SceneDirector} director
*/
export function directorSettled(director) {
let timer = 0;
const limit = new Promise((resolve) => {
timer = setTimeout(() => {
console.warn('Stories: the scene did not finish tearing down; going on');
resolve();
}, SETTLE_LIMIT_MS);
});
// A failure to wait counts as settled: the view still comes back.
const idle = Promise.resolve()
.then(() => director.whenIdle())
.catch(() => {});
return Promise.race([idle, limit]).finally(() => clearTimeout(timer));
}
/**
* Plays a scene GEV already ships through SceneDirector, the way the Scene
* panel plays it, and reports the scene clock in the shape the Stories
* timeline reads. SceneDirector has no pause: pausing seeks to the current
* moment (which stops the run and frames it), and playing again starts the
* run at the shot that moment is in.
*
* @param {import('../scenes/director.js').SceneDirector} director
* @param {object} story A catalog story of kind 'gev'.
* @param {{onTick?: (state: object) => void}} [hooks]
*/
export function createGevPlayer(director, story, hooks = {}) {
const sceneId = story.sceneId;
let wallMs = 0;
let durationMs = story.durationMs;
let playing = false;
let shotIndex = 0;
let destroyed = false;
// Each Play, Pause, Seek and Destroy takes a new number; a Play that waited
// for a teardown or a start goes ahead only if nothing came after it.
let request = 0;
const state = () => ({
wallMs,
worldMs: null,
durationMs,
playing,
exploring: false,
chapterIndex: Math.min(shotIndex, story.chapters.length - 1),
});
const tick = () => {
if (!destroyed) hooks.onTick?.(state());
};
const unsubscribe = director.subscribeSceneClock((snap) => {
if (destroyed || !snap || snap.sceneId !== sceneId) return;
if (snap.sceneDurationSec) durationMs = snap.sceneDurationSec * 1000;
wallMs = (snap.sceneElapsedSec ?? 0) * 1000;
shotIndex = snap.shotIndex ?? shotIndex;
playing = !!snap.running && !snap.seeking;
if (!playing && wallMs >= durationMs - 250) wallMs = durationMs;
tick();
});
// A run from the previous story may still be releasing the camera.
async function idle() {
if (!director.running) return;
director.stopScene();
await directorSettled(director);
}
return {
kind: 'gev',
story,
get state() {
return state();
},
async play() {
const mine = ++request;
await idle();
if (destroyed || mine !== request || director.running) return;
if (wallMs >= durationMs - 250) {
wallMs = 0;
shotIndex = 0;
}
const shots = director.listShots(sceneId);
const afterShotId =
shotIndex > 0 ? (shots[shotIndex - 1]?.id ?? null) : null;
playing = true;
tick();
const result = await director.startScene(sceneId, {
single: true,
afterShotId,
preview: true,
});
if (destroyed) return;
if (mine !== request) {
// Paused or scrubbed while the run was starting: that wins.
if (result?.started)
director.seekScene(sceneId, durationMs ? wallMs / durationMs : 0);
return;
}
if (!result?.started) {
playing = false;
tick();
}
},
pause() {
request += 1;
playing = false;
director.seekScene(sceneId, durationMs ? wallMs / durationMs : 0);
tick();
},
seek(ms) {
request += 1;
wallMs = Math.max(0, Math.min(durationMs, ms));
shotIndex = chapterAt(story, wallMs);
playing = false;
director.seekScene(sceneId, durationMs ? wallMs / durationMs : 0);
tick();
},
resume() {
return this.play();
},
/** A key moment: go to that point of the scene. */
focus(event) {
if (event?.wallMs != null) this.seek(event.wallMs);
},
destroy() {
request += 1;
destroyed = true;
unsubscribe?.();
director.stopScene();
},
};
}
+95
View File
@@ -0,0 +1,95 @@
// A GEV scene's Play waits for the last run to tear down and for the new run
// to start; a Pause, Seek or Destroy meanwhile must win.
import test from 'node:test';
import assert from 'node:assert/strict';
import { createGevPlayer } from './gevPlayer.js';
const story = {
sceneId: 'scene-1',
durationMs: 60000,
chapters: [{ wallMs: 0 }, { wallMs: 30000 }],
};
/** A director whose start resolves when the test says so. */
function deferredDirector({ running = false } = {}) {
const calls = [];
let release = null;
const director = {
running,
calls,
listShots: () => [{ id: 'a' }, { id: 'b' }],
subscribeSceneClock: () => () => {},
stopScene: () => calls.push('stop'),
whenIdle() {
return new Promise((resolve) => {
const check = () => (this.running ? setTimeout(check, 10) : resolve());
check();
});
},
seekScene: (id, f) => calls.push(`seek ${f}`),
startScene: () => {
calls.push('start');
return new Promise((resolve) => {
release = () => {
director.running = true;
resolve({ started: true });
};
});
},
finishStart: () => release?.(),
};
return director;
}
const turns = async (n = 4) => {
for (let i = 0; i < n; i++) await Promise.resolve();
};
test('Pause straight after Play stops the Play from starting', async () => {
const director = deferredDirector();
const states = [];
const player = createGevPlayer(director, story, {
onTick: (s) => states.push(s.playing),
});
const playing = player.play();
player.pause();
await playing;
assert.equal(director.calls.includes('start'), false);
assert.equal(states.at(-1), false);
});
test('a Seek during the last run’s teardown cancels the waiting Play', async () => {
const director = deferredDirector({ running: true });
const player = createGevPlayer(director, story);
const playing = player.play();
player.seek(30000);
director.running = false; // the old run finishes tearing down
await playing;
assert.equal(director.calls.includes('start'), false);
assert.equal(player.state.playing, false);
assert.equal(player.state.wallMs, 30000);
});
test('a Pause while the run is starting is applied once it has started', async () => {
const director = deferredDirector();
const player = createGevPlayer(director, story);
const playing = player.play();
await turns();
assert.deepEqual(director.calls, ['start']);
player.pause();
director.finishStart();
await playing;
// Pause seeks once when pressed, and again after the late start.
assert.equal(director.calls.filter((c) => c.startsWith('seek')).length, 2);
assert.equal(player.state.playing, false);
});
test('Destroy cancels a waiting Play', async () => {
const director = deferredDirector({ running: true });
const player = createGevPlayer(director, story);
const playing = player.play();
player.destroy();
director.running = false;
await playing;
assert.equal(director.calls.includes('start'), false);
});
+38
View File
@@ -0,0 +1,38 @@
/**
* While Stories is open its screens own the keyboard. A key pressed inside
* Stories reaches Stories' controls and stops at its root, before GEV's
* document-level shortcuts; a key pressed anywhere else (nothing focused, or
* a hidden GEV control) stops at the window, so nothing behind Stories acts
* on it, unless it is one of a playing GEV scene's own on-globe controls.
* Listeners on the window itself (Stories' own Escape and "/") still
* run. Capture-phase listeners on the document run before the root and check
* `body.stories-mode` themselves (hold Space to talk, focus traps).
* @param {{root: HTMLElement, isOpen: () => boolean, win?: Window}} options
* @returns {() => void} Removes the guard.
*/
export function guardStoriesKeyboard({ root, isOpen, win = window }) {
const types = ['keydown', 'keyup', 'keypress'];
// A GEV scene playing in Stories keeps its own controls (the A/B slider,
// an embedded player's card): their keys reach them as outside Stories.
const sceneControl = (target) =>
root.ownerDocument.body.classList.contains('stories-scene') &&
!!target?.closest?.('[data-globe-overlay]');
const outside = (event) => {
if (!isOpen() || root.contains(event.target)) return;
if (sceneControl(event.target)) return;
event.stopPropagation();
};
const inside = (event) => {
if (isOpen()) event.stopPropagation();
};
for (const type of types) {
win.addEventListener(type, outside, true);
root.addEventListener(type, inside);
}
return () => {
for (const type of types) {
win.removeEventListener(type, outside, true);
root.removeEventListener(type, inside);
}
};
}
+76
View File
@@ -0,0 +1,76 @@
// While Stories is open, GEV's document-level keys stay quiet behind it.
import '../testSupport/registerDom.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import { guardStoriesKeyboard } from './keyboard.js';
function page() {
document.body.innerHTML =
'<div id="gev-stories"><button id="inside"></button></div><button id="gev"></button>';
const root = document.getElementById('gev-stories');
const heard = [];
const gev = (event) => heard.push(`gev ${event.key}`);
document.addEventListener('keydown', gev);
const own = (event) => heard.push(`stories ${event.key}`);
document.getElementById('inside').addEventListener('keydown', own);
const windowOwn = (event) => heard.push(`window ${event.key}`);
window.addEventListener('keydown', windowOwn, true);
const press = (id, key) =>
document
.getElementById(id)
.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true }));
const cleanup = () => {
document.removeEventListener('keydown', gev);
window.removeEventListener('keydown', windowOwn, true);
};
return { root, heard, press, cleanup };
}
test('keys in Stories reach Stories and stop there; keys elsewhere reach nothing behind it', () => {
const { root, heard, press, cleanup } = page();
let open = true;
const remove = guardStoriesKeyboard({ root, isOpen: () => open });
press('inside', '3');
press('gev', 'o');
assert.deepEqual(heard, ['window 3', 'stories 3', 'window o']);
// Closed, GEV hears its keys again.
open = false;
heard.length = 0;
press('gev', 'o');
assert.deepEqual(heard, ['window o', 'gev o']);
remove();
cleanup();
});
test('removing the guard lets every key through', () => {
const { root, heard, press, cleanup } = page();
const remove = guardStoriesKeyboard({ root, isOpen: () => true });
remove();
press('inside', 'h');
assert.deepEqual(heard, ['window h', 'stories h', 'gev h']);
cleanup();
});
test("a playing GEV scene's own on-globe controls keep their keys", () => {
const { root, heard, cleanup } = page();
document.body.insertAdjacentHTML(
'beforeend',
'<div data-globe-overlay><button id="slider"></button></div>',
);
const slider = document.getElementById('slider');
slider.addEventListener('keydown', (e) => heard.push(`slider ${e.key}`));
const remove = guardStoriesKeyboard({ root, isOpen: () => true });
document.body.classList.add('stories-scene');
slider.dispatchEvent(
new KeyboardEvent('keydown', { key: 'ArrowRight', bubbles: true }),
);
assert.ok(heard.includes('slider ArrowRight'));
document.body.classList.remove('stories-scene');
heard.length = 0;
slider.dispatchEvent(
new KeyboardEvent('keydown', { key: 'ArrowRight', bubbles: true }),
);
assert.deepEqual(heard, ['window ArrowRight'], 'no scene: GEV stays quiet');
remove();
cleanup();
});
+150
View File
@@ -0,0 +1,150 @@
import { msg, t, translateKnown } from '../i18n/index.js';
import { STORY_TAGS } from '../scenes/storyTags.js';
/**
* What Explore and the Story page show around a story beyond the catalog:
* topics and region for the feed's chips and filters, the clock and chapter
* stamps, the legend and the "right now" facts.
*/
export const fmtDur = (ms) => {
const s = Math.round(ms / 1000);
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
};
export const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
/**
* Topics, region and searchable places per shipped story. Topics use the
* AUTHORING tag names (src/scenes/storyTags.js) and follow the layers each
* scene turns on.
*/
export const META = {
'gev:bhote-koshi-nepal-scene': {
topics: ['Floods'],
region: 'South Asia',
place: 'Nepal Bhote Koshi river',
},
'gev:flights-radar': {
topics: ['Flights'],
region: 'Global',
place: 'Atlantic Europe Japan San Francisco',
},
'gev:orbital-watch': {
topics: ['Space'],
region: 'Global',
place: 'Florida Africa Tokyo Paris Atlantic',
},
'gev:thermal-threats': {
topics: ['Earthquakes'],
region: 'Global',
place: 'California Japan New Zealand Portugal',
},
'gev:city-overload': {
topics: ['Flights', 'Space', 'Infrastructure'],
region: 'Global',
place: 'New York Los Angeles London',
},
'gev:omniscience-pullback': {
topics: ['Flights', 'Space', 'Earthquakes', 'Infrastructure'],
region: 'Global',
place: 'Tokyo Japan East Asia South China Sea',
},
};
export const FILTERS = [
[
'region',
msg('Region'),
[
['Europe', msg('Europe')],
['Middle East', msg('Middle East')],
['South Asia', msg('South Asia')],
['North America', msg('North America')],
['East Asia', msg('East Asia')],
['Global', msg('Global')],
],
],
[
'length',
msg('Length'),
[
['short', msg('Under 1 min')],
['long', msg('1 min or more')],
],
],
];
/**
* A story's topics, region and place: the topics the person picked for it,
* then the shipped META.
*/
export function metaFor(s) {
const m = META[s.id] ?? { topics: [], region: 'Global', place: '' };
const topics = [...new Set([...(s.topics ?? []), ...m.topics])];
return { ...m, topics };
}
/** The topics the stories carry, in AUTHORING's tag order. */
export function topicsOf(stories) {
const order = (topic) => {
const i = STORY_TAGS.indexOf(topic);
return i < 0 ? STORY_TAGS.length : i;
};
return [...new Set(stories.flatMap((s) => metaFor(s).topics))].sort(
(a, b) => order(a) - order(b),
);
}
/** The clock overlay: big line and small line. */
export function clockText(s, wallMs, worldMs, chapterIndex) {
return {
big: t('Shot {n} of {total}', {
n: chapterIndex + 1,
total: s.chapters.length,
}),
small: t('GEV scene'),
};
}
/**
* A story's own text (title, caption, label, source…) in the page's
* language. Shipped stories carry English marked with msg(); a scene the
* person named shows as they named it.
*/
export const storyText = (text) => (text ? translateKnown(text) : '');
/**
* A chapter's title in the page's language: a scene's shot titles come from
* the director already in it.
*/
export function chapterTitle(story, c) {
return c.title ?? t('Shot {n}', { n: c.shot });
}
/** The story's time window as the feed shows it. */
export function windowText() {
return t('GEV scene');
}
/** Stamp for a chapter or key moment: its place on the scene's clock. */
export function anchorStamp(s, wallMs) {
return fmtDur(wallMs);
}
/** Legend entries [shape, colour, label]. */
export function layersFor(s) {
if (s.mock?.legend?.length) return s.mock.legend;
return (s.tags ?? []).map((tag) => ['dot', '#e8eaed', tag]);
}
/** "Right now" facts per story (prototype nowFacts): [value, label, warn]. */
export function nowFacts(s, worldMs, wallMs = 0) {
const out = [[String(s.chapters.length), msg('Shots')]];
if (s.tags?.length) out.push([String(s.tags.length), msg('Layers on')]);
return out;
}
/** A chapter's stamp in lists: its place on the scene's clock. */
export function chapterStamp(s, c) {
return fmtDur(c.wallMs);
}
+102
View File
@@ -0,0 +1,102 @@
import * as Cesium from 'cesium';
/**
* Story card images, drawn from the imagery GEV is already showing: the
* base layer's tiles around a story's place, cropped to the card. No other
* host is asked, and the imagery is the one GEV credits on screen.
*/
const WIDTH = 320;
const HEIGHT = 180;
const TILE_TRIES = 4;
/** A zoom level that frames `range` metres of view, within the provider's. */
export function thumbLevel(range, provider) {
const level = Math.round(Math.log2(4e7 / Math.max(range || 1.6e7, 1)));
const max = Number.isFinite(provider?.maximumLevel)
? provider.maximumLevel
: 18;
const min = Number.isFinite(provider?.minimumLevel)
? provider.minimumLevel
: 0;
return Math.max(min, Math.min(max, Math.max(1, level)));
}
async function tile(provider, x, y, level) {
for (let i = 0; i < TILE_TRIES; i++) {
// undefined: the request was throttled; ask again shortly.
const image = await provider.requestImage(x, y, level);
if (image) return image;
await new Promise((resolve) => setTimeout(resolve, 250 * (i + 1)));
}
return null;
}
/**
* A card image for a place, or '' when the imagery cannot be read (a provider
* without tiles, a failed request, imagery the browser will not let a page
* copy).
* @param {object} provider A Cesium ImageryProvider.
* @param {{lat: number, lon: number, range?: number}} cover
* @returns {Promise<string>}
*/
export async function drawThumb(provider, cover) {
try {
const scheme = provider?.tilingScheme;
if (!scheme || typeof provider.requestImage !== 'function') return '';
const level = thumbLevel(cover.range, provider);
const where = Cesium.Cartographic.fromDegrees(cover.lon, cover.lat);
const at = scheme.positionToTileXY(where, level);
if (!at) return '';
const rect = scheme.tileXYToRectangle(at.x, at.y, level);
// Where the place sits inside its tile, 0..1 from the top left.
const u = (where.longitude - rect.west) / rect.width;
const v = (rect.north - where.latitude) / rect.height;
// A 2 × 2 block of tiles with the place in its middle tile quarter.
const x0 = u < 0.5 ? at.x - 1 : at.x;
const y0 = v < 0.5 ? at.y - 1 : at.y;
const nx = scheme.getNumberOfXTilesAtLevel(level);
const ny = scheme.getNumberOfYTilesAtLevel(level);
const size = 256;
const canvas = document.createElement('canvas');
canvas.width = WIDTH;
canvas.height = HEIGHT;
const ctx = canvas.getContext('2d');
if (!ctx) return '';
ctx.fillStyle = '#0b1620';
ctx.fillRect(0, 0, WIDTH, HEIGHT);
// The place's pixel in the block, kept at the card's centre.
const px = (at.x - x0 + u) * size;
const py = (at.y - y0 + v) * size;
const ox = WIDTH / 2 - px;
const oy = HEIGHT / 2 - py;
let drawn = 0;
await Promise.all(
[0, 1].flatMap((dy) =>
[0, 1].map(async (dx) => {
const ty = y0 + dy;
if (ty < 0 || ty >= ny) return;
const tx = (((x0 + dx) % nx) + nx) % nx;
const image = await tile(provider, tx, ty, level);
if (!image) return;
// Cesium hands bitmaps over flipped for the GPU; turn them back.
const flipped =
typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap;
const top = oy + dy * size;
if (flipped) {
ctx.save();
ctx.translate(0, top + size);
ctx.scale(1, -1);
ctx.drawImage(image, ox + dx * size, 0, size + 1, size + 1);
ctx.restore();
} else ctx.drawImage(image, ox + dx * size, top, size + 1, size + 1);
drawn += 1;
}),
),
);
if (!drawn) return '';
return canvas.toDataURL('image/jpeg', 0.82);
} catch (error) {
console.warn('Stories: no card image for this story', error);
return '';
}
}
+68
View File
@@ -0,0 +1,68 @@
import '../testSupport/registerDom.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { drawThumb, thumbLevel } from './thumbs.js';
function fakeProvider(images = true) {
const asked = [];
return {
asked,
tilingScheme: new Cesium.WebMercatorTilingScheme(),
maximumLevel: 10,
requestImage(x, y, level) {
asked.push([x, y, level]);
return Promise.resolve(images ? {} : undefined);
},
};
}
function fakeCanvas(t) {
const drawn = [];
const original = document.createElement.bind(document);
t.mock.method(document, 'createElement', (name) => {
const el = original(name);
if (name === 'canvas') {
el.getContext = () => ({
fillRect() {},
drawImage: (...args) => drawn.push(args),
});
el.toDataURL = () => 'data:image/jpeg;base64,AAAA';
}
return el;
});
return drawn;
}
test('a story’s range picks a zoom level within the provider’s', () => {
assert.equal(thumbLevel(1.6e7, { maximumLevel: 10 }), 1);
assert.equal(thumbLevel(160000, { maximumLevel: 10 }), 8);
assert.equal(thumbLevel(500, { maximumLevel: 10 }), 10);
});
test('a card is drawn from the 2 × 2 tiles around the place', async (t) => {
const drawn = fakeCanvas(t);
const provider = fakeProvider();
const url = await drawThumb(provider, {
lat: 28.05,
lon: 85.6,
range: 160000,
});
assert.equal(url, 'data:image/jpeg;base64,AAAA');
assert.equal(provider.asked.length, 4);
assert.ok(provider.asked.every(([, , level]) => level === 8));
assert.equal(drawn.length, 4);
});
test('no imagery, no card: the placeholder stays', async (t) => {
fakeCanvas(t);
t.mock.timers.enable({ apis: ['setTimeout'] });
const provider = fakeProvider(false);
const pending = drawThumb(provider, { lat: 0, lon: 0, range: 1.6e7 });
for (let i = 0; i < 20; i++) {
await Promise.resolve();
t.mock.timers.tick(1000);
}
assert.equal(await pending, '');
assert.equal(await drawThumb({}, { lat: 0, lon: 0 }), '');
});