Stories: reach the globe through the renderer's ports

Main now keeps Cesium behind the renderer contract, so Stories stops
reaching Cesium and the viewer directly.

- Camera: flights, the -60 degree story framing, cancel, the pose saved
  on open and put back on Close go through the camera port; a follow is
  released with stopFollowing.
- Pins: placed in the frame port's postRender from the query port's
  projection and horizon test, still written straight to each pin's
  transform on every drawn frame.
- Tile settling: a continuous-render hold until the globe port reports
  the base settled, for at most 10 s.
- Clock: Close and Back to Explore put back the page's world clock (live,
  or the time it showed, playing on), and leave a clock that is still
  where it should be alone.
- Card images: drawn from Esri World Imagery's own Web Mercator tiles
  while the Esri map stack is active, read as images; no Cesium imagery
  provider is touched.
- THUMBNAIL: the director hands captureStoryThumb the frame port and the
  renderer's canvas, so the scene document's module stays renderer-free.
- Credits: Stories places and keeps visible the application's credit
  line (#gev-credits) and its list as well as the renderer's own display.
- Tests fake the ports instead of a Cesium viewer, and cover pins per
  frame, the flights, the settling bound and the clock restore; the
  share link tests Stories added build their manager over a camera port.
This commit is contained in:
Manjunath committed 2026-11-16 20:43:53 +05:30
1 parent 9e9ce1db22
commit b8e622aac8
15 files changed
+695 -376

No files matched your search

+1 -1
View File
@@ -11,7 +11,7 @@ const wantsStories = () => {
* 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,
* @param {{viewer: object,
* director: import('../scenes/director.js').SceneDirector,
* store: ReturnType<typeof import('../ui/stores/stories.js').useStoriesStore>,
* onEnter?: () => void,
+24 -14
View File
@@ -3,7 +3,6 @@ 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.
@@ -38,24 +37,35 @@ 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: () => () => {} },
},
const { bindRenderer } = await import('../render/rendererOf.js');
// The scene object, bound to a renderer double with the ports Stories uses.
const viewer = { isDestroyed: () => false };
bindRenderer(viewer, {
canvas: document.createElement('canvas'),
camera: {
positionWC: new Cesium.Cartesian3(1, 2, 3),
positionCartographic: { latitude: 0, longitude: 0, height: 2e6 },
heading: 0,
pitch: -1,
roll: 0,
pose: () => ({
position: { x: 1, y: 2, z: 3 },
heading: 0,
pitch: -1,
roll: 0,
lon: 0,
lat: 0,
height: 2e6,
}),
setView() {},
flyTo() {},
flyToBoundingSphere() {},
flyToBounds() {},
cancelFlight() {},
},
clock: { currentTime: Cesium.JulianDate.now(), shouldAnimate: false },
};
frame: {
on: () => () => {},
requestRender() {},
holdContinuous: () => () => {},
},
query: { project: () => null, isOccluded: () => true },
globe: { isSettled: () => true },
});
const director = {
running: false,
stopScene() {},
+22 -22
View File
@@ -1,7 +1,7 @@
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
* Stories are GEV scenes, played on GEV's own globe: the scenes GEV
* ships (recipes with a camera path) and the scenes the person authored and
* saved to Stories from the AUTHORING panel.
*
@@ -262,25 +262,25 @@ const describe = (scene) =>
* 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) {
function savedStory(entry) {
return {
id: `gev:${scene.id}`,
sceneId: scene.id,
id: `gev:${entry.id}`,
sceneId: entry.id,
kind: 'gev',
live: false,
mine: true,
// Not saved with SAVE TO STORIES yet.
draft: !!scene.draft,
title: scene.title,
description: describe(scene),
draft: !!entry.draft,
title: entry.title,
description: describe(entry),
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 ?? '',
topics: [...(entry.tags ?? [])],
tags: [...(entry.tags ?? [])],
thumb: entry.thumb ?? '',
durationMs: 0,
cover: coverOf(scene.camera),
cover: coverOf(entry.camera),
chapters: [],
events: [],
sources: [],
@@ -319,17 +319,17 @@ export function listStories() {
// 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);
.filter((entry) => !shippedIds.has(entry.id))
.map((entry) => {
const story = saved.get(entry.id) ?? savedStory(entry);
story.title = entry.title;
story.draft = !!entry.draft;
story.description = describe(entry);
story.cover = coverOf(entry.camera);
story.topics = [...(entry.tags ?? [])];
story.tags = [...(entry.tags ?? [])];
story.thumb = entry.thumb ?? '';
saved.set(entry.id, story);
return story;
});
return [...own, ...shipped.filter((s) => installed(s.sceneId))];
+130 -83
View File
@@ -1,4 +1,3 @@
import * as Cesium from 'cesium';
import { markRaw, toRaw } from 'vue';
import { t } from '../i18n/index.js';
import {
@@ -16,6 +15,16 @@ import {
} from './catalog.js';
import { anchorStamp } from './storyMeta.js';
import { registerNavigationAuthorityListener } from '../navigationPolicy.js';
import {
canvasOf,
findCamera,
findFrame,
findGlobe,
findQuery,
} from '../render/rendererOf.js';
import { fromDegrees } from '../geo/ellipsoid.js';
import { stopFollowing } from '../data/followed.js';
import { worldClock } from '../time/worldClock.js';
const PARAM_STORIES = 'stories';
const PARAM_STORY = 'story';
@@ -35,23 +44,33 @@ function storyTime(params) {
}
/**
* Stories: Explore (the story list over the person's own Cesium globe, with
* Stories: Explore (the story list over the person's own 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.
* Leaving Stories puts back the globe, camera and world clock the person had.
* The globe is reached only through the renderer's ports (`rendererOf.js`).
*
* 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,
* @param {{viewer: object,
* director: import('../scenes/director.js').SceneDirector,
* store: ReturnType<typeof import('../ui/stores/stories.js').useStoriesStore>,
* onEnter?: () => void}} options
* onEnter?: () => void,
* clock?: typeof worldClock}} options `viewer` is the scene object the
* renderer is bound to; `clock` is the page's world clock (tests replace
* it).
*/
export function createStoriesController({ viewer, director, store, onEnter }) {
export function createStoriesController({
viewer,
director,
store,
onEnter,
clock = worldClock,
}) {
let player = null;
let saved = null;
// The view a Close is about to restore, once a stopping scene has settled.
@@ -75,7 +94,10 @@ export function createStoriesController({ viewer, director, store, onEnter }) {
// one entry too far).
let afterTraversal = null;
const traversing = () => steppingBack || closingHistory;
const canvas = viewer.scene.canvas;
const canvas = canvasOf(viewer);
// The renderer's ports, asked for as they are used.
const camera = () => findCamera(viewer);
const frame = () => findFrame(viewer);
// The scenes the person saved to Stories (AUTHORING panel) join the list,
// and a save or removal shows at once.
@@ -240,14 +262,20 @@ export function createStoriesController({ viewer, director, store, onEnter }) {
// ── The person's own view, kept for when Stories closes ──
function saveView() {
const c = viewer.camera;
const pose = camera()?.pose();
const world = clock.getState();
saved = {
position: c.positionWC.clone(),
heading: c.heading,
pitch: c.pitch,
roll: c.roll,
time: viewer.clock.currentTime.clone(),
animate: viewer.clock.shouldAnimate,
position: pose ? { ...pose.position } : null,
heading: pose?.heading ?? 0,
pitch: pose?.pitch ?? -Math.PI / 2,
roll: pose?.roll ?? 0,
clock: {
live: world.live,
timeMs: world.timeMs,
playing: world.playing,
rate: world.rate,
stepping: world.stepping,
},
openedAt: Date.now(),
// Story history entries have no hash. Capture the live globe state.
hash: shareLink()?.snapshotHash?.() ?? location.hash,
@@ -262,8 +290,8 @@ export function createStoriesController({ viewer, director, store, onEnter }) {
function restoreView(saved, { keepCamera = false } = {}) {
if (!saved) return;
if (!keepCamera)
viewer.camera.setView({
if (!keepCamera && saved.position)
camera()?.setView({
destination: saved.position,
orientation: {
heading: saved.heading,
@@ -276,16 +304,32 @@ export function createStoriesController({ viewer, director, store, onEnter }) {
restoreClock(saved);
}
/** A running clock carries on as if Stories had never paused it. */
/**
* The world clock as the person left it: live stays live, and a playing
* clock carries on as if Stories had never paused it. A clock still where
* it should be is left alone, so its layers see no jump.
*/
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;
const was = saved?.clock;
if (!was) return;
const now = clock.getState();
if (was.live) {
if (!now.live) clock.goLive();
return;
}
const at = was.playing
? was.timeMs + (Date.now() - saved.openedAt) * was.rate
: was.timeMs;
if (
!now.live &&
now.playing === was.playing &&
Math.abs(now.timeMs - at) < 1000
)
return;
if (!was.playing) clock.pause();
clock.seek(at);
if (was.playing && !now.playing)
clock.play({ rate: was.rate, continuous: !was.stepping });
}
// A GEV scene turns on its own layers and look. Put the person's back by
@@ -313,17 +357,12 @@ export function createStoriesController({ viewer, director, store, onEnter }) {
// 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 query = findQuery(viewer);
if (!query) return;
const rect = canvas.getBoundingClientRect();
const pins = places.map(({ id, at }) => {
const win = Cesium.SceneTransforms.worldToWindowCoordinates(
viewer.scene,
at,
);
const visible = !!win && occluder.isPointVisible(at);
const win = query.project(at);
const visible = !!win && !query.isOccluded(at);
return {
id,
x: rect.left + (win?.x ?? -9999),
@@ -357,9 +396,9 @@ export function createStoriesController({ viewer, director, store, onEnter }) {
stopPins();
places = listStories().map((s) => {
const { lat, lon } = areaOf(s);
return { id: s.id, at: Cesium.Cartesian3.fromDegrees(lon, lat) };
return { id: s.id, at: fromDegrees(lon, lat) };
});
removePins = viewer.scene.postRender.addEventListener(placePins);
removePins = frame()?.on('postRender', placePins) ?? (() => {});
governorRequestRender('stories-pins');
}
// ── Explore's idle tour: the globe turns from one story to the next ──
@@ -441,7 +480,7 @@ export function createStoriesController({ viewer, director, store, onEnter }) {
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
// The globe 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;
@@ -456,34 +495,35 @@ export function createStoriesController({ viewer, director, store, onEnter }) {
function settleTiles() {
stopSettling();
if (destroyed || viewer.isDestroyed?.()) return;
removeTiles = viewer.scene.postRender.addEventListener(() => {
if (viewer.scene.globe?.tilesLoaded) stopSettling();
});
removeTiles =
frame()?.on('postRender', () => {
if (findGlobe(viewer)?.isSettled('base') === true) stopSettling();
}) ?? null;
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.
const port = camera();
if (!port) return;
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,
});
port.flyTo(
{ lon, lat, height: alt },
{
orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 },
durationS: duration,
onComplete: settleTiles,
},
);
return;
}
viewer.camera.flyToBoundingSphere(
new Cesium.BoundingSphere(Cesium.Cartesian3.fromDegrees(lon, lat), 0),
port.flyToBounds(
{ center: fromDegrees(lon, lat), radius: 0 },
{
offset: new Cesium.HeadingPitchRange(
0,
Cesium.Math.toRadians(-60),
alt,
),
duration,
complete: settleTiles,
offset: { heading: 0, pitch: (-60 * Math.PI) / 180, range: alt },
durationS: duration,
onComplete: settleTiles,
},
);
}
@@ -497,23 +537,25 @@ export function createStoriesController({ viewer, director, store, onEnter }) {
};
};
// ── GEV scenes: the camera readout comes from Cesium ──
// ── GEV scenes: the camera readout comes from the renderer's camera ──
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 startCameraReadout() {
stopCameraReadout();
removeReadout =
frame()?.on('postRender', () => {
const now = performance.now();
if (now - lastReadout < 120) return;
lastReadout = now;
const pose = camera()?.pose();
if (!pose) return;
store.camera = {
lat: pose.lat,
lon: pose.lon,
altKm: Math.round(pose.height / 1000),
};
}) ?? null;
}
function stopCesiumReadout() {
function stopCameraReadout() {
removeReadout?.();
removeReadout = null;
}
@@ -553,7 +595,7 @@ export function createStoriesController({ viewer, director, store, onEnter }) {
function dropPlayer() {
document.body.classList.remove('stories-scene');
stopCesiumReadout();
stopCameraReadout();
player?.destroy();
player = null;
}
@@ -606,7 +648,7 @@ export function createStoriesController({ viewer, director, store, onEnter }) {
if (nav?.runImmediateNavigation?.('stories', () => true) === false)
return false;
if (director.running) director.stopScene();
viewer.trackedEntity = undefined;
stopFollowing(viewer);
// 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
@@ -631,8 +673,7 @@ export function createStoriesController({ viewer, director, store, onEnter }) {
}
// ── Card images: drawn once per story place from the base imagery ──
const ESRI_IMAGERY =
/arcgisonline\.com\/arcgis\/rest\/services\/world_imagery/i;
const ESRI_STACK = 'esri-imagery';
const thumbKeys = new Map();
let drawingThumbs = false;
let thumbsAgain = false;
@@ -647,9 +688,10 @@ export function createStoriesController({ viewer, director, store, onEnter }) {
// 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) {
const esri =
director.styleManager?.mapStackController?.getActiveId?.() ===
ESRI_STACK;
if (!esri && !story.thumb) {
// A card drawn from Esri earlier goes: its credit is not on
// screen under another imagery.
if (store.thumbs?.[story.id]) {
@@ -668,7 +710,7 @@ export function createStoriesController({ viewer, director, store, onEnter }) {
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));
const url = story.thumb || (await drawThumb(c));
if (!url || destroyed) continue;
thumbKeys.set(story.id, key);
store.thumbs = { ...store.thumbs, [story.id]: url };
@@ -745,7 +787,7 @@ export function createStoriesController({ viewer, director, store, onEnter }) {
const generation = ++closeGeneration;
dropPlayer();
stopPins();
viewer.camera.cancelFlight();
camera()?.cancelFlight();
// Close the Stories screens now and keep their input guard until the
// scene and share view have finished restoring.
document.body.classList.remove('stories-scene');
@@ -791,7 +833,12 @@ export function createStoriesController({ viewer, director, store, onEnter }) {
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);
if (!keepCamera && !navigated) {
restoreShareState(was);
// A shared world time arrives paused: a clock that was playing
// plays on, as on Back to Explore.
restoreClock(was);
}
shareLink()?.holdWrites?.(false);
document.body.classList.remove('stories-mode');
};
@@ -824,7 +871,7 @@ export function createStoriesController({ viewer, director, store, onEnter }) {
if (store.mode === 'closed' && !enterStories()) return;
dropPlayer();
stopPins();
viewer.camera.cancelFlight();
camera()?.cancelFlight();
store.storyId = id;
store.picked = id;
store.mode = 'story';
@@ -851,7 +898,7 @@ export function createStoriesController({ viewer, director, store, onEnter }) {
player = createGevPlayer(director, story, { onTick });
// Related stories show their card images too, after a link.
drawThumbs();
startCesiumReadout();
startCameraReadout();
// Opened paused, a scene frames its first shot (or the moment asked).
if (atMs || !autoplay) player.seek(atMs);
if (autoplay) player.play();
@@ -974,7 +1021,7 @@ export function createStoriesController({ viewer, director, store, onEnter }) {
afterTraversal = landed = null;
dropPlayer();
stopPins();
viewer.camera.cancelFlight();
camera()?.cancelFlight();
store.mode = 'closed';
store.storyId = null;
store.picked = null;
+244 -95
View File
@@ -4,9 +4,9 @@ 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';
import { createStateChannel } from '../app/stateChannel.js';
import { bindRenderer } from '../render/rendererOf.js';
registerHooks({
load(url, context, next) {
@@ -33,44 +33,104 @@ 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);
},
},
/**
* The scene object Stories is handed, bound to a renderer double with the
* ports Stories uses: the camera, the frame loop (postRender listeners run
* on `draw()`), screen projection with the horizon test, and the globe's
* settling. The doubles are returned beside it for the tests to drive.
*/
function fakeScene() {
const canvas = document.createElement('canvas');
const camera = {
position: { x: 1, y: 2, z: 3 },
views: [],
flights: [],
cancels: 0,
pose() {
return {
position: { ...this.position },
heading: 0,
pitch: -1,
roll: 0,
lon: 11.46,
lat: 28.65,
height: 2e6,
};
},
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;
},
setView(v) {
this.views.push(v);
},
clock: {
currentTime: Cesium.JulianDate.fromDate(new Date(Date.UTC(2026, 0, 1))),
shouldAnimate: false,
cancelFlight() {
this.cancels += 1;
},
flyTo(destination, options) {
this.flights.push({ destination, ...options });
},
flyToBounds(sphere, options) {
this.flights.push({ sphere, ...options });
},
trackedEntity: undefined,
};
const frame = {
listeners: new Set(),
requests: [],
on(phase, fn) {
assert.equal(phase, 'postRender');
this.listeners.add(fn);
return () => this.listeners.delete(fn);
},
draw() {
for (const fn of [...this.listeners]) fn({});
},
requestRender(reason) {
this.requests.push(reason);
},
holdContinuous: () => () => {},
};
const query = {
hidden: new Set(),
project: ({ x, y }) => ({ x: x / 1e5, y: y / 1e5 }),
isOccluded(at) {
return this.hidden.has(at);
},
};
const globe = { settled: false, isSettled: () => globe.settled };
const viewer = { isDestroyed: () => false };
bindRenderer(viewer, { canvas, camera, frame, query, globe });
return { viewer, camera, frame, query, globe, canvas };
}
/** A world clock double: its state, and the calls made on it. */
function fakeClock(state = {}) {
const calls = [];
const clock = {
calls,
state: {
live: true,
timeMs: Date.UTC(2026, 0, 1),
playing: false,
rate: 1,
stepping: false,
...state,
},
getState: () => ({ ...clock.state }),
goLive() {
calls.push(['goLive']);
Object.assign(clock.state, { live: true, playing: false });
},
seek(ms) {
calls.push(['seek', ms]);
Object.assign(clock.state, { live: false, timeMs: ms });
},
pause() {
calls.push(['pause']);
clock.state.playing = false;
},
play(options) {
calls.push(['play', options]);
clock.state.playing = true;
},
};
return clock;
}
function fakeDirector({ refuse = false } = {}) {
@@ -122,16 +182,18 @@ function setup(options = {}) {
setActivePinia(createPinia());
history.replaceState(null, '', '/?x=1#v=2&lat=1');
const store = useStoriesStore();
const viewer = fakeViewer();
const scene = fakeScene();
const clock = options.clock ?? fakeClock();
const director = fakeDirector(options);
const controller = createStoriesController({
viewer,
viewer: scene.viewer,
director,
store,
onEnter: options.onEnter,
clock,
});
store.connect(controller, listStories());
return { store, viewer, director, controller };
return { ...scene, clock, store, director, controller };
}
test('Close steps back over every entry Stories pushed', async () => {
@@ -185,42 +247,38 @@ test('Cockpit keeps the camera: Stories does not open', () => {
});
test('reopening while a scene tears down keeps the view from before Stories', async () => {
const { controller, viewer, director, store } = setup();
const before = viewer.camera.positionWC;
const { controller, director, store, camera } = setup();
const before = { ...camera.position };
controller.open();
controller.openStory('gev:bhote-koshi-nepal-scene');
director.running = true;
const toast = store.hostedToast;
const closing = controller.openInGev();
// The scene has moved the camera; the person opens Stories again at once.
viewer.camera.positionWC = new Cesium.Cartesian3(9, 9, 9);
camera.position = { x: 9, y: 9, z: 9 };
controller.open();
director.running = false;
await closing;
assert.deepEqual(director.selected, []);
assert.deepEqual(director.styleManager.panels, []);
assert.equal(store.hostedToast, toast);
assert.equal(
viewer.camera.views.length,
0,
'no restore under the reopened Stories',
);
assert.equal(camera.views.length, 0, 'no restore under the reopened Stories');
await controller.close();
const { x, y, z } = viewer.camera.views.at(-1).destination;
const { x, y, z } = 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();
const { controller, director, camera } = 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');
assert.equal(camera.views.length, 0, 'not under the stopping scene');
setTimeout(() => (director.running = false), 120);
await closing;
assert.equal(viewer.camera.views.length, 1);
assert.equal(camera.views.length, 1);
controller.destroy();
});
@@ -294,7 +352,7 @@ test('Back to Explore after a related story steps past both stories', (t) => {
});
test('a second Close after a quick reopen still waits for the scene to tear down', async () => {
const { controller, viewer, director } = setup();
const { controller, director, camera } = setup();
controller.open();
controller.openStory('gev:bhote-koshi-nepal-scene');
director.running = true;
@@ -302,10 +360,10 @@ test('a second Close after a quick reopen still waits for the scene to tear down
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');
assert.equal(camera.views.length, 0, 'nothing restored yet');
setTimeout(() => (director.running = false), 120);
await Promise.all([first, closing]);
assert.equal(viewer.camera.views.length, 1);
assert.equal(camera.views.length, 1);
controller.destroy();
});
@@ -319,7 +377,7 @@ test('a reload of a Stories entry keeps its history; Close steps all of it back'
const steps = recordGo(t);
const store = useStoriesStore();
const controller = createStoriesController({
viewer: fakeViewer(),
viewer: fakeScene().viewer,
director: fakeDirector(),
store,
});
@@ -340,7 +398,7 @@ test('a new story link puts Explore under the story', async (t) => {
const steps = recordGo(t);
const store = useStoriesStore();
const controller = createStoriesController({
viewer: fakeViewer(),
viewer: fakeScene().viewer,
director: fakeDirector(),
store,
});
@@ -361,7 +419,7 @@ test('a new story link puts Explore under the story', async (t) => {
});
test('Open in GEV hands a GEV scene to the Scenes panel at its current shot', async () => {
const { controller, store, director, viewer } = setup();
const { controller, store, director, camera } = setup();
controller.open();
controller.openStory('gev:bhote-koshi-nepal-scene');
store.playback = { ...store.playback, chapterIndex: 0 };
@@ -369,11 +427,7 @@ test('Open in GEV hands a GEV scene to the Scenes panel at its current shot', as
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.equal(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();
@@ -435,7 +489,7 @@ function land(hash = '#v=2&lat=1') {
}
test('a second browser Back during scene teardown supersedes the Stories restore', async () => {
const { controller, director, store, viewer } = setup();
const { controller, director, store, camera } = setup();
const share = director.styleManager.shareLinkManager;
const holds = [];
share.holdWrites = (held) => holds.push(held);
@@ -449,7 +503,7 @@ test('a second browser Back during scene teardown supersedes the Stories restore
director.running = false;
await tick(0);
assert.equal(location.hash, '#v=2&lat=2');
assert.equal(viewer.camera.views.length, 0);
assert.equal(camera.views.length, 0);
assert.deepEqual(share.restored, []);
assert.deepEqual(director.selected, []);
assert.deepEqual(holds, [true, false]);
@@ -474,7 +528,7 @@ test('Close after a GEV scene puts the share state back once the step back lands
});
test('Open in GEV steps back over Stories without putting the old view back', async (t) => {
const { controller, director, viewer } = setup();
const { controller, director, camera } = setup();
const steps = recordGo(t);
controller.open();
controller.openStory('gev:bhote-koshi-nepal-scene');
@@ -482,20 +536,20 @@ test('Open in GEV steps back over Stories without putting the old view back', as
assert.deepEqual(steps, [-2], 'Back never reopens Stories');
land();
assert.deepEqual(director.styleManager.shareLinkManager.restored, []);
assert.equal(viewer.camera.views.length, 0);
assert.equal(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();
const { controller, director, camera, canvas } = setup();
controller.open();
controller.openStory('gev:bhote-koshi-nepal-scene');
director.running = true;
const closing = controller.close();
viewer.scene.canvas.dispatchEvent(new Event('pointerdown'));
canvas.dispatchEvent(new Event('pointerdown'));
director.running = false;
await closing;
assert.equal(viewer.camera.views.length, 0, 'no snap back');
assert.equal(camera.views.length, 0, 'no snap back');
controller.destroy();
});
@@ -521,7 +575,7 @@ test('a reloaded Stories entry drops the share hash GEV wrote on boot', async ()
);
const store = useStoriesStore();
const controller = createStoriesController({
viewer: fakeViewer(),
viewer: fakeScene().viewer,
director: fakeDirector(),
store,
});
@@ -558,7 +612,7 @@ test('a scene saved to Stories from AUTHORING joins the list at once', () => {
};
director.storyScenes = () => mine;
const controller = createStoriesController({
viewer: fakeViewer(),
viewer: fakeScene().viewer,
director,
store,
});
@@ -585,11 +639,11 @@ test('a scene saved to Stories from AUTHORING joins the list at once', () => {
});
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 { controller, director, camera } = setup();
history.replaceState(null, '', '/');
const flights = [];
viewer.camera.flyTo = (f) => flights.push(f);
viewer.camera.flyToBoundingSphere = (f) => flights.push(f);
camera.flyTo = (f) => flights.push(f);
camera.flyToBounds = (f) => flights.push(f);
const share = director.styleManager.shareLinkManager;
const original = 'v=2&lat=1&style=normal';
share.snapshotHash = () => original;
@@ -641,10 +695,10 @@ test('a story opened while the scene tears down is not undone by the late restor
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 { controller, store, camera, canvas } = setup();
const flights = [];
viewer.camera.flyTo = (f) => flights.push(f);
viewer.camera.flyToBoundingSphere = (f) => flights.push(f);
camera.flyTo = (f) => flights.push(f);
camera.flyToBounds = (f) => flights.push(f);
controller.open();
assert.equal(flights.length, 1, 'the fly-in to the first story');
t.mock.timers.tick(7000);
@@ -655,10 +709,10 @@ test('Explore tours from story to story once idle, stops on a pick or a touch, a
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'));
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'));
canvas.dispatchEvent(new Event('pointerup'));
t.mock.timers.tick(5000);
assert.equal(flights.length, 3);
t.mock.timers.tick(1500);
@@ -696,7 +750,7 @@ test('a new Explore link keeps the address free of the share hash GEV writes as
if (held) history.replaceState(history.state, '', `${location.search}#v=2`);
};
const controller = createStoriesController({
viewer: fakeViewer(),
viewer: fakeScene().viewer,
director,
store,
});
@@ -732,7 +786,7 @@ test('a saved scene’s topics become Explore chips, and its captured card image
},
];
const controller = createStoriesController({
viewer: fakeViewer(),
viewer: fakeScene().viewer,
director,
store,
});
@@ -779,7 +833,7 @@ test('a built-in scene no longer in the project does not list; an unknown story
const toasts = [];
store.flashToast = (text) => toasts.push(text);
const controller = createStoriesController({
viewer: fakeViewer(),
viewer: fakeScene().viewer,
director,
store,
});
@@ -824,7 +878,7 @@ test('unsaved scenes appear as local drafts and disappear when deleted', () => {
director.subscribe = channel.subscribe;
director.draftScenes = () => drafts;
const controller = createStoriesController({
viewer: fakeViewer(),
viewer: fakeScene().viewer,
director,
store,
});
@@ -840,12 +894,8 @@ test('unsaved scenes appear as local drafts and disappear when deleted', () => {
});
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/' },
}),
};
const { controller, director, store } = setup();
director.styleManager.mapStackController = { getActiveId: () => 'osm' };
store.thumbs = { 'gev:flights-radar': 'data:image/jpeg;base64,ESRI' };
controller.open();
await tick(20);
@@ -855,18 +905,17 @@ test('under imagery other than Esri, a card drawn from Esri earlier is dropped',
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();
const { controller, viewer, director, camera, canvas } = 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);
camera.flyTo = (f) => flights.push(f);
camera.flyToBounds = (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));
@@ -885,12 +934,12 @@ test('the tour waits again after a wheel turn or a cancelled press, and a list c
test('teardown mid-close releases share writes and cancels a queued reopen', async (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
const { controller, director, store, viewer } = setup();
const { controller, director, store, camera } = setup();
recordGo(t);
const held = [];
director.styleManager.shareLinkManager.holdWrites = (on) => held.push(on);
let flights = 0;
viewer.camera.flyTo = () => flights++;
camera.flyTo = () => flights++;
controller.open();
await controller.close();
controller.open(); // queued until the Close traversal lands
@@ -925,7 +974,7 @@ test('new navigation cancels a delayed initial story link', async (t) => {
history.replaceState(null, '', '/?story=gev%3Aflights-radar');
const store = useStoriesStore();
const controller = createStoriesController({
viewer: fakeViewer(),
viewer: fakeScene().viewer,
director: fakeDirector(),
store,
});
@@ -990,3 +1039,103 @@ test('an earlier Back timeout cannot release a later traversal', async (t) => {
controller.destroy();
}
});
test('Explore’s pins follow the camera on every frame drawn, moved in place', () => {
const { controller, store, frame, query } = setup();
controller.open();
assert.equal(frame.listeners.size, 1, 'one postRender listener');
frame.draw();
const pins = store.pins;
assert.equal(pins.length, store.stories.length);
assert.ok(pins.every((pin) => pin.visible));
// Vue renders the pins once; a move alone writes each pin's transform.
const layer = document.createElement('div');
layer.id = 'pins';
for (const pin of pins) {
const el = document.createElement('div');
el.className = 'pin';
el.dataset.id = pin.id;
layer.append(el);
}
document.body.append(layer);
try {
query.project = ({ x, y }) => ({ x: x / 1e5 + 40, y: y / 1e5 + 10 });
frame.draw();
assert.equal(store.pins, pins, 'the same pins: no Vue render');
const first = layer.querySelector(`.pin[data-id="${pins[0].id}"]`);
assert.match(first.style.transform, /^translate\(/);
// A pin going behind the horizon changes the set: Vue renders it.
let once = true;
query.isOccluded = () => {
const behind = once;
once = false;
return behind;
};
frame.draw();
assert.notEqual(store.pins, pins);
assert.equal(store.pins[0].visible, false);
} finally {
layer.remove();
controller.close();
}
assert.equal(frame.listeners.size, 0, 'no frame work once Stories closes');
controller.destroy();
});
test('Explore frames country level straight down, a picked story at −60°, and tiles settle for at most 10 s', (t) => {
t.mock.timers.enable({ apis: ['setTimeout', 'Date'] });
const { controller, store, camera, frame, globe } = setup();
controller.open();
const open = camera.flights.at(-1);
assert.equal(open.destination.height, 2.5e6);
assert.deepEqual(open.orientation, {
heading: 0,
pitch: -Math.PI / 2,
roll: 0,
});
controller.pick(store.stories[0].id);
const picked = camera.flights.at(-1);
assert.equal(picked.sphere.radius, 0);
assert.equal(picked.offset.heading, 0);
assert.ok(Math.abs(picked.offset.pitch + Math.PI / 3) < 1e-12);
assert.ok(picked.offset.range >= 60000 && picked.offset.range <= 4e6);
// Landing keeps frames coming until the globe has settled...
picked.onComplete();
assert.equal(frame.listeners.size, 2, 'pins and settling');
frame.draw();
assert.equal(frame.listeners.size, 2, 'not settled yet');
globe.settled = true;
frame.draw();
assert.equal(frame.listeners.size, 1, 'settled: only the pins listen');
// ...and for 10 s at most.
globe.settled = false;
picked.onComplete();
assert.equal(frame.listeners.size, 2);
t.mock.timers.tick(10000);
assert.equal(frame.listeners.size, 1, 'given up after 10 s');
controller.destroy();
});
test('Close puts back the world clock the person had, and the camera readout follows a story', async () => {
const clock = fakeClock({
live: false,
playing: false,
timeMs: Date.UTC(2025, 5, 1),
});
const { controller, store, frame, camera } = setup({ clock });
controller.open();
controller.openStory('gev:bhote-koshi-nepal-scene');
frame.draw();
assert.deepEqual(store.camera, { lat: 28.65, lon: 11.46, altKm: 2000 });
// A scene moved the world clock.
clock.state = { ...clock.state, live: true };
await controller.close();
assert.equal(camera.views.length, 1);
assert.deepEqual(clock.calls, [['pause'], ['seek', Date.UTC(2025, 5, 1)]]);
// A clock left where it was is not touched.
clock.calls.length = 0;
controller.open();
await controller.close();
assert.deepEqual(clock.calls, []);
controller.destroy();
});
+79 -56
View File
@@ -1,30 +1,62 @@
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.
* Story card images, drawn from the imagery GEV is already showing: the Esri
* World Imagery tiles around a story's place, cropped to the card. They are
* the same tiles, from the same host, that GEV's Esri map draws (and credits
* on screen); no other host is asked.
*/
const WIDTH = 320;
const HEIGHT = 180;
const TILE_TRIES = 4;
const TILE_SIZE = 256;
const TILE_TRIES = 3;
/** A zoom level that frames `range` metres of view, within the provider's. */
export function thumbLevel(range, provider) {
/** Esri World Imagery's tiles: Web Mercator, as GEV's Esri map draws them. */
export const ESRI_TILE_URL =
'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}';
const ESRI_MAX_LEVEL = 19;
/** A zoom level that frames `range` metres of view, within the imagery's. */
export function thumbLevel(
range,
{ minLevel = 0, maxLevel = ESRI_MAX_LEVEL } = {},
) {
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)));
return Math.max(minLevel, Math.min(maxLevel, Math.max(1, level)));
}
async function tile(provider, x, y, level) {
/**
* Where a place sits in the Web Mercator tile grid at `level`, in tiles from
* the top left (the whole part names the tile, the rest is inside it).
* @returns {{x: number, y: number}}
*/
export function tilePosition(lon, lat, level) {
const n = 2 ** level;
const clamped = Math.max(-85.05112878, Math.min(85.05112878, lat));
const phi = (clamped * Math.PI) / 180;
const x = ((((lon + 180) / 360) % 1) + 1) % 1;
const y = (1 - Math.log(Math.tan(phi) + 1 / Math.cos(phi)) / Math.PI) / 2;
return { x: x * n, y: Math.min(Math.max(y, 0), 1 - 1e-12) * n };
}
const tileUrl = (x, y, level) =>
ESRI_TILE_URL.replace('{z}', String(level))
.replace('{y}', String(y))
.replace('{x}', String(x));
/** One tile as an image the canvas may read back, or null. */
function loadImage(url) {
return new Promise((resolve) => {
const image = new Image();
image.crossOrigin = 'anonymous';
image.decoding = 'async';
image.onload = () => resolve(image);
image.onerror = () => resolve(null);
image.src = url;
});
}
async function tile(loadTile, 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);
const image = await loadTile(tileUrl(x, y, level), { x, y, level });
if (image) return image;
await new Promise((resolve) => setTimeout(resolve, 250 * (i + 1)));
}
@@ -32,31 +64,28 @@ async function tile(provider, x, y, level) {
}
/**
* 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.
* A card image for a place, or '' when the imagery cannot be read (a failed
* request, imagery the browser will not let a page copy).
* @param {{lat: number, lon: number, range?: number}} cover
* @param {{loadTile?: (url: string, tile: {x: number, y: number, level: number}) =>
* Promise<CanvasImageSource | null>}} [options] `loadTile` fetches one tile
* (tests replace it).
* @returns {Promise<string>}
*/
export async function drawThumb(provider, cover) {
export async function drawThumb(cover, { loadTile = loadImage } = {}) {
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);
if (!Number.isFinite(cover?.lat) || !Number.isFinite(cover?.lon)) return '';
const level = thumbLevel(cover.range);
const at = tilePosition(cover.lon, cover.lat, level);
const tx = Math.floor(at.x);
const ty = Math.floor(at.y);
// 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;
const u = at.x - tx;
const v = at.y - ty;
// 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 x0 = u < 0.5 ? tx - 1 : tx;
const y0 = v < 0.5 ? ty - 1 : ty;
const n = 2 ** level;
const canvas = document.createElement('canvas');
canvas.width = WIDTH;
canvas.height = HEIGHT;
@@ -65,30 +94,24 @@ export async function drawThumb(provider, cover) {
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;
const ox = WIDTH / 2 - (tx - x0 + u) * TILE_SIZE;
const oy = HEIGHT / 2 - (ty - y0 + v) * TILE_SIZE;
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);
const y = y0 + dy;
if (y < 0 || y >= n) return;
const x = (((x0 + dx) % n) + n) % n;
const image = await tile(loadTile, x, y, 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);
ctx.drawImage(
image,
ox + dx * TILE_SIZE,
oy + dy * TILE_SIZE,
TILE_SIZE + 1,
TILE_SIZE + 1,
);
drawn += 1;
}),
),
+49 -24
View File
@@ -1,18 +1,21 @@
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';
import {
ESRI_TILE_URL,
drawThumb,
thumbLevel,
tilePosition,
} from './thumbs.js';
function fakeProvider(images = true) {
/** Tiles as Esri would answer them, each request recorded. */
function fakeTiles(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);
loadTile(url, tile) {
asked.push({ url, ...tile });
return Promise.resolve(images ? {} : null);
},
};
}
@@ -34,35 +37,57 @@ function fakeCanvas(t) {
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 story’s range picks a zoom level within the imagery’s', () => {
assert.equal(thumbLevel(1.6e7, { maxLevel: 10 }), 1);
assert.equal(thumbLevel(160000, { maxLevel: 10 }), 8);
assert.equal(thumbLevel(500, { maxLevel: 10 }), 10);
assert.equal(thumbLevel(1), 19, 'Esri’s deepest level by default');
});
test('a card is drawn from the 2 × 2 tiles around the place', async (t) => {
test('a place sits in the Web Mercator tile grid as the map draws it', () => {
assert.deepEqual(tilePosition(0, 0, 1), { x: 1, y: 1 });
const { x, y } = tilePosition(-180, 85.05112878, 3);
assert.equal(x, 0);
assert.ok(Math.abs(y) < 1e-6);
const nepal = tilePosition(85.6, 28.05, 8);
assert.equal(Math.floor(nepal.x), 188);
assert.equal(Math.floor(nepal.y), 107);
});
test('a card is drawn from the 2 × 2 Esri 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,
});
const tiles = fakeTiles();
const url = await drawThumb(
{ lat: 28.05, lon: 85.6, range: 160000 },
{ loadTile: tiles.loadTile },
);
assert.equal(url, 'data:image/jpeg;base64,AAAA');
assert.equal(provider.asked.length, 4);
assert.ok(provider.asked.every(([, , level]) => level === 8));
assert.equal(tiles.asked.length, 4);
assert.ok(tiles.asked.every(({ level }) => level === 8));
// Only Esri World Imagery's own tiles, as GEV's Esri map asks for them.
for (const { url, x, y } of tiles.asked)
assert.equal(
url,
ESRI_TILE_URL.replace('{z}', '8')
.replace('{y}', String(y))
.replace('{x}', String(x)),
);
assert.match(ESRI_TILE_URL, /^https:\/\/services\.arcgisonline\.com\//);
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 });
const tiles = fakeTiles(false);
const pending = drawThumb(
{ lat: 0, lon: 0, range: 1.6e7 },
{ loadTile: tiles.loadTile },
);
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 }), '');
assert.equal(await drawThumb({}), '');
});