mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-17 00:32:21 +00:00
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:
1 parent
da81cf743b
commit
5418438339
77 files changed
+14975
-260
No files matched your search
+303
-19
@@ -67,6 +67,8 @@ import {
|
||||
SceneDocumentError,
|
||||
} from '../director/document.js';
|
||||
import { sceneSaveFailureReason } from './sceneSaveError.js';
|
||||
import { STORY_TAG_LIMIT, STORY_TAGS } from './storyTags.js';
|
||||
import { captureStoryThumb } from './storyThumb.js';
|
||||
|
||||
/** @constant {string} localStorage key for the serialized project */
|
||||
const STORAGE_KEY = 'godsEyeView.sceneProject.v2';
|
||||
@@ -177,8 +179,10 @@ export class SceneDirector {
|
||||
this._lastRunJson = '';
|
||||
|
||||
this._project = this._loadProject();
|
||||
this._selectedSceneId = this._project.scenes[0]?.id || null;
|
||||
this._selectedShotId = this._project.scenes[0]?.shots[0]?.id || null;
|
||||
// Authoring starts with no scene: the built-in scenes stay in the project
|
||||
// (Stories plays them) but only NEW SCENE or selectShot makes one current.
|
||||
this._selectedSceneId = null;
|
||||
this._selectedShotId = null;
|
||||
/** @type {string|null} Scene whose layer state most recently landed. */
|
||||
this._loadedSceneId = null;
|
||||
|
||||
@@ -220,6 +224,9 @@ export class SceneDirector {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Upgrading a pack selects its scene; on load nothing is selected.
|
||||
this._selectedSceneId = null;
|
||||
this._selectedShotId = null;
|
||||
}
|
||||
this._initUI();
|
||||
// A status the director wrote itself follows the language; one it was
|
||||
@@ -443,11 +450,6 @@ export class SceneDirector {
|
||||
hasRun: !!this._lastRunJson,
|
||||
}),
|
||||
actions: {
|
||||
selectScene: (id) => {
|
||||
this._selectedSceneId = id;
|
||||
this._selectedShotId = this._getSelectedScene()?.shots[0]?.id || null;
|
||||
this._renderShotList();
|
||||
},
|
||||
selectShot: (id) => {
|
||||
this._selectedShotId = id;
|
||||
this._publish({ type: 'selection-changed' });
|
||||
@@ -461,6 +463,9 @@ export class SceneDirector {
|
||||
},
|
||||
create: (name) => this._createScene(name),
|
||||
deleteScene: () => this._deleteSelectedScene(),
|
||||
stories: () => this._toggleSelectedSceneInStories(),
|
||||
thumb: () => this.captureSceneThumb(),
|
||||
tag: (tag) => this._toggleSelectedSceneTag(tag),
|
||||
capture: () => this.captureShot(),
|
||||
update: () => this.updateSelectedShot(),
|
||||
start: (id) => this.startScene(id),
|
||||
@@ -476,12 +481,16 @@ export class SceneDirector {
|
||||
});
|
||||
}
|
||||
|
||||
/** Rebuild the scene dropdown options and sync the selected value. */
|
||||
/**
|
||||
* Keep the selection on an existing scene, or on none, and present the
|
||||
* scene's name.
|
||||
*/
|
||||
_renderSceneSelect() {
|
||||
if (
|
||||
!this._project.scenes.some((scene) => scene.id === this._selectedSceneId)
|
||||
) {
|
||||
this._selectedSceneId = this._project.scenes[0]?.id || null;
|
||||
this._selectedSceneId = null;
|
||||
this._selectedShotId = null;
|
||||
}
|
||||
this._publish({ type: 'scene-options-changed' });
|
||||
}
|
||||
@@ -544,7 +553,10 @@ export class SceneDirector {
|
||||
this._publish({ type: 'scene-created', scene });
|
||||
}
|
||||
|
||||
/** Delete the currently selected scene after user confirmation. Resets to defaults if empty. */
|
||||
/**
|
||||
* Delete the currently selected scene after user confirmation and select
|
||||
* none. Resets to defaults if empty.
|
||||
*/
|
||||
_deleteSelectedScene() {
|
||||
const scene = this._getSelectedScene();
|
||||
if (!scene) return;
|
||||
@@ -557,10 +569,106 @@ export class SceneDirector {
|
||||
this._project = createDefaultProject();
|
||||
}
|
||||
|
||||
this._selectedSceneId = this._project.scenes[0]?.id || null;
|
||||
this._selectedShotId = this._project.scenes[0]?.shots[0]?.id || null;
|
||||
// Authoring goes back to no scene.
|
||||
this._selectedSceneId = null;
|
||||
this._selectedShotId = null;
|
||||
this._saveProject();
|
||||
this._publish({ type: 'scene-deleted', scene });
|
||||
if (scene.stories) this._publish({ type: 'stories-changed' });
|
||||
}
|
||||
|
||||
/** SAVE TO STORIES / REMOVE FROM STORIES for the selected scene. */
|
||||
_toggleSelectedSceneInStories() {
|
||||
const scene = this._getSelectedScene();
|
||||
if (!scene) return;
|
||||
const on = !scene.stories;
|
||||
if (!this.setSceneInStories(scene.id, on)) return;
|
||||
this._updateStatus(() =>
|
||||
on ? t('Saved to Stories') : t('Removed from Stories'),
|
||||
);
|
||||
}
|
||||
|
||||
/** A tag chip: add the tag to the selected scene, or take it off. */
|
||||
_toggleSelectedSceneTag(tag) {
|
||||
const scene = this._getSelectedScene();
|
||||
if (!scene || !STORY_TAGS.includes(tag)) return;
|
||||
const tags = scene.storyTags ?? [];
|
||||
const next = tags.includes(tag)
|
||||
? tags.filter((item) => item !== tag)
|
||||
: [...tags, tag];
|
||||
// The panel disables the other chips once a scene has the most tags.
|
||||
this.setSceneStoryTags(scene.id, next);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the tags a scene shows on its Stories card.
|
||||
* @param {string} sceneId
|
||||
* @param {string[]} tags Keys from STORY_TAGS, at most STORY_TAG_LIMIT.
|
||||
* @returns {boolean} False when the scene does not exist or a tag is not
|
||||
* one of STORY_TAGS.
|
||||
*/
|
||||
setSceneStoryTags(sceneId, tags) {
|
||||
const scene = this._project.scenes.find(({ id }) => id === sceneId);
|
||||
const next = [...new Set(tags)];
|
||||
if (
|
||||
!scene ||
|
||||
next.length > STORY_TAG_LIMIT ||
|
||||
!next.every((tag) => STORY_TAGS.includes(tag))
|
||||
)
|
||||
return false;
|
||||
if (next.length) scene.storyTags = next;
|
||||
else delete scene.storyTags;
|
||||
this._saveProject();
|
||||
this._publish({ type: 'story-details-changed', scene });
|
||||
if (scene.stories) this._publish({ type: 'stories-changed' });
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* THUMBNAIL: keep the globe as drawn now as the selected scene's
|
||||
* Stories card image.
|
||||
* @returns {Promise<boolean>} Whether a thumbnail was stored.
|
||||
*/
|
||||
async captureSceneThumb() {
|
||||
const scene = this._getSelectedScene();
|
||||
if (!scene || this._destroyed) return false;
|
||||
let thumb;
|
||||
try {
|
||||
thumb = await captureStoryThumb(this.viewer, {
|
||||
createCanvas: () => document.createElement('canvas'),
|
||||
});
|
||||
} catch (error) {
|
||||
console.warn('[Scenes] Could not capture the thumbnail:', error);
|
||||
if (!this._destroyed)
|
||||
this._updateStatus(() => t('Thumbnail could not be captured'));
|
||||
return false;
|
||||
}
|
||||
// The scene may have gone while the frame was drawn.
|
||||
if (this._destroyed || !this._project.scenes.includes(scene)) return false;
|
||||
return this.setSceneStoryThumb(scene.id, thumb);
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a scene's Stories card thumbnail.
|
||||
* @param {string} sceneId
|
||||
* @param {string} thumb A JPEG or PNG data URL (see storyThumb.js).
|
||||
* @returns {boolean} False when the scene does not exist.
|
||||
*/
|
||||
setSceneStoryThumb(sceneId, thumb) {
|
||||
const scene = this._project.scenes.find(({ id }) => id === sceneId);
|
||||
if (!scene) return false;
|
||||
const previous = scene.storyThumb;
|
||||
scene.storyThumb = thumb;
|
||||
if (!this._saveProject()) {
|
||||
// An invalid or oversized image is not kept; the save error is shown.
|
||||
if (previous === undefined) delete scene.storyThumb;
|
||||
else scene.storyThumb = previous;
|
||||
return false;
|
||||
}
|
||||
this._publish({ type: 'story-details-changed', scene });
|
||||
if (scene.stories) this._publish({ type: 'stories-changed' });
|
||||
this._updateStatus(() => t('Thumbnail captured'));
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -976,17 +1084,23 @@ export class SceneDirector {
|
||||
|
||||
/**
|
||||
* Capture the current camera position, visual state, and layer states as a
|
||||
* new shot appended to the selected scene. No-op if no scene is selected.
|
||||
* new shot appended to the selected scene, creating a scene first when none
|
||||
* is selected.
|
||||
*/
|
||||
captureShot() {
|
||||
const scene = this._getSelectedScene();
|
||||
if (!scene) return;
|
||||
|
||||
const camera = this.styleManager.getCameraState();
|
||||
if (!camera) {
|
||||
this._updateStatus(() => t('Cannot capture shot: camera not ready'));
|
||||
return;
|
||||
}
|
||||
// With no scene, start one first, as NEW SCENE does.
|
||||
if (!this._getSelectedScene())
|
||||
this._createScene(
|
||||
// i18n-ignore: stored English, like _createScene's own fallback.
|
||||
`Scene ${this._project.scenes.length + 1}`,
|
||||
);
|
||||
const scene = this._getSelectedScene();
|
||||
if (!scene) return;
|
||||
|
||||
const shot = normalizeShot(
|
||||
{
|
||||
@@ -1006,6 +1120,7 @@ export class SceneDirector {
|
||||
this._selectedShotId = shot.id;
|
||||
const saved = this._saveProject();
|
||||
this._shotOutcome('shot-captured', scene, shot);
|
||||
if (scene.stories) this._publish({ type: 'stories-changed' });
|
||||
if (saved) {
|
||||
this._updateStatus(() =>
|
||||
t('Captured: {scene} / {shot}', {
|
||||
@@ -1041,6 +1156,8 @@ export class SceneDirector {
|
||||
|
||||
const saved = this._saveProject();
|
||||
this._shotOutcome('shot-updated', scene, shot);
|
||||
if (scene.stories && scene.shots[0] === shot)
|
||||
this._publish({ type: 'stories-changed' });
|
||||
if (saved) {
|
||||
this._updateStatus(() =>
|
||||
t('Updated: {scene} / {shot}', {
|
||||
@@ -1063,8 +1180,12 @@ export class SceneDirector {
|
||||
const index = scene.shots.indexOf(shot);
|
||||
scene.shots = scene.shots.filter((item) => item.id !== shot.id);
|
||||
this._selectedShotId = scene.shots[0]?.id || null;
|
||||
const inStories = !!scene.stories;
|
||||
// A scene without shots has nothing to show in Stories.
|
||||
if (!scene.shots.length) delete scene.stories;
|
||||
this._saveProject();
|
||||
this._shotOutcome('shot-deleted', scene, shot, index);
|
||||
if (inStories) this._publish({ type: 'stories-changed' });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1526,6 +1647,25 @@ export class SceneDirector {
|
||||
return this._clock.publish(scene, shot, sceneElapsedSec, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves once no run is in progress and every LOAD, seek and interaction
|
||||
* tracked so far has settled, including work started while waiting. Callers
|
||||
* that put a view back after a scene (Stories' Close) wait on this rather
|
||||
* than on `running`, which a LOAD never sets.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async whenIdle() {
|
||||
for (;;) {
|
||||
await this._waitForRunIdle();
|
||||
const pending = [...(this._pendingWork || [])];
|
||||
if (!pending.length) {
|
||||
if (!this._running) return;
|
||||
continue;
|
||||
}
|
||||
await Promise.allSettled(pending);
|
||||
}
|
||||
}
|
||||
|
||||
/** Wait for an interrupted run to release camera and layer ownership. */
|
||||
_waitForRunIdle() {
|
||||
if (!this._running) return Promise.resolve();
|
||||
@@ -1794,6 +1934,140 @@ export class SceneDirector {
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* One scene's shots in play order with their display titles and where each
|
||||
* starts on the scene clock, for callers that show or resume a scene by
|
||||
* shot (Stories).
|
||||
* @param {string} sceneId
|
||||
* @returns {Array<{id: string, title: string, startSec: number, durationSec: number}>}
|
||||
*/
|
||||
listShots(sceneId) {
|
||||
const scene = this._project.scenes.find(({ id }) => id === sceneId);
|
||||
return (scene?.shots ?? []).map((shot) => {
|
||||
const timing = this._sceneTimingForShot(scene, shot);
|
||||
return {
|
||||
id: shot.id,
|
||||
title: displayShotTitle(shot.title, shot, scene),
|
||||
startSec: timing.startElapsedSec,
|
||||
durationSec: timing.durationSec,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Select a scene and one of its shots in the Scenes panel, as picking them
|
||||
* there does (Stories' "Open in GEV" hands a story over for authoring).
|
||||
* @param {string} sceneId
|
||||
* @param {string|null} [shotId] Defaults to the scene's first shot.
|
||||
* @returns {boolean} False when the scene is not installed.
|
||||
*/
|
||||
selectShot(sceneId, shotId = null) {
|
||||
// No scene: AUTHORING goes back to "No scene yet".
|
||||
if (sceneId == null) {
|
||||
this._selectedSceneId = null;
|
||||
this._selectedShotId = null;
|
||||
this._renderSceneSelect();
|
||||
this._renderShotList();
|
||||
return true;
|
||||
}
|
||||
const scene = this._project.scenes.find(({ id }) => id === sceneId);
|
||||
if (!scene) return false;
|
||||
this._selectedSceneId = scene.id;
|
||||
this._selectedShotId = scene.shots.some(({ id }) => id === shotId)
|
||||
? shotId
|
||||
: (scene.shots[0]?.id ?? null);
|
||||
this._renderSceneSelect();
|
||||
this._renderShotList();
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the project has this scene (a built-in can be deleted, or be
|
||||
* missing from an imported project).
|
||||
* @param {string} sceneId
|
||||
* @returns {boolean}
|
||||
*/
|
||||
hasScene(sceneId) {
|
||||
return this._project.scenes.some(
|
||||
({ id, shots }) => id === sceneId && shots.length > 0,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The scene and shot AUTHORING has selected, for putting back after
|
||||
* playback (Stories plays a scene by selecting it).
|
||||
* @returns {{sceneId: string|null, shotId: string|null}}
|
||||
*/
|
||||
selection() {
|
||||
return {
|
||||
sceneId: this._selectedSceneId ?? null,
|
||||
shotId: this._selectedShotId ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Publish a scene to the Stories page, or take it off.
|
||||
* @param {string} sceneId
|
||||
* @param {boolean} on
|
||||
* @returns {boolean} False when the scene does not exist, or has no shots
|
||||
* and `on` is true.
|
||||
*/
|
||||
setSceneInStories(sceneId, on) {
|
||||
const scene = this._project.scenes.find(({ id }) => id === sceneId);
|
||||
if (!scene || (on && !scene.shots.length)) return false;
|
||||
if (on) scene.stories = true;
|
||||
else delete scene.stories;
|
||||
this._saveProject();
|
||||
this._publish({ type: 'stories-changed' });
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* The scenes published to Stories that have a shot, in project order.
|
||||
* `camera` is the first shot's camera as captured; `thumb` is the card
|
||||
* thumbnail's data URL ('' when none was captured) and `tags` its tags.
|
||||
* @returns {Array<{id: string, title: string, camera: object, shotCount: number, thumb: string, tags: string[]}>}
|
||||
*/
|
||||
storyScenes() {
|
||||
return this._project.scenes
|
||||
.filter((scene) => scene.stories === true && scene.shots.length > 0)
|
||||
.map((scene) => ({
|
||||
id: scene.id,
|
||||
title: displaySceneTitle(scene),
|
||||
camera: deepClone(scene.shots[0].camera),
|
||||
shotCount: scene.shots.length,
|
||||
thumb: scene.storyThumb ?? '',
|
||||
tags: [...(scene.storyTags ?? [])],
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* The person's own scenes that are not on the Stories page, with a shot:
|
||||
* Stories lists them as drafts, visible only here, so a scene made in
|
||||
* AUTHORING can always be opened again from Stories.
|
||||
* @returns {Array<{id: string, title: string, camera: object, shotCount: number, thumb: string, tags: string[]}>}
|
||||
*/
|
||||
draftScenes() {
|
||||
const builtIn = new Set(
|
||||
[...SCENE_RECIPES, ...SCENE_APPEND_RECIPES].map(({ id }) => id),
|
||||
);
|
||||
return this._project.scenes
|
||||
.filter(
|
||||
(scene) =>
|
||||
scene.stories !== true &&
|
||||
scene.shots.length > 0 &&
|
||||
!builtIn.has(scene.id),
|
||||
)
|
||||
.map((scene) => ({
|
||||
id: scene.id,
|
||||
title: displaySceneTitle(scene),
|
||||
camera: deepClone(scene.shots[0].camera),
|
||||
shotCount: scene.shots.length,
|
||||
thumb: scene.storyThumb ?? '',
|
||||
tags: [...(scene.storyTags ?? [])],
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a scene by id, exact title, or case-insensitive title substring.
|
||||
* @param {string} query - Scene id or (partial) title.
|
||||
@@ -2203,13 +2477,23 @@ export class SceneDirector {
|
||||
),
|
||||
);
|
||||
this._storageReadError = null;
|
||||
this._selectedSceneId =
|
||||
selection?.sceneId || project.scenes[0]?.id || null;
|
||||
// Keep authoring on the named or current scene, else the first scene
|
||||
// that is not a built-in one, else none.
|
||||
const builtIn = new Set(SCENE_RECIPES.map(({ id }) => id));
|
||||
const selected =
|
||||
project.scenes.find(({ id }) => id === selection?.sceneId) ||
|
||||
project.scenes.find(({ id }) => id === this._selectedSceneId) ||
|
||||
project.scenes.find(({ id }) => !builtIn.has(id)) ||
|
||||
null;
|
||||
this._selectedSceneId = selected?.id ?? null;
|
||||
this._selectedShotId =
|
||||
selection?.shotId || project.scenes[0]?.shots[0]?.id || null;
|
||||
selected?.shots.find(({ id }) => id === selection?.shotId)?.id ||
|
||||
selected?.shots[0]?.id ||
|
||||
null;
|
||||
this._loadedSceneId = null;
|
||||
const saved = this._saveProject();
|
||||
this._publish({ type: 'project-imported', project });
|
||||
this._publish({ type: 'stories-changed' });
|
||||
if (saved)
|
||||
this._updateStatus(() => t('Imported {file}', { file: file.name }));
|
||||
return true;
|
||||
|
||||
@@ -19,8 +19,10 @@ import test from 'node:test';
|
||||
|
||||
import { LayerLifecycle } from '../data/lifecycle.js';
|
||||
import { SceneDirector } from './director.js';
|
||||
import { stringifySceneDocument } from '../director/document.js';
|
||||
import { SCENE_TRACKING_PARAM_KEYS } from './scenePolicy.js';
|
||||
import { SCENE_RECIPES, getSceneAppendRecipeById } from './recipes.js';
|
||||
import { STORY_TAGS } from './storyTags.js';
|
||||
|
||||
const NEPAL_ORIGINAL_SHOT_TITLES = [
|
||||
'Global Incident Context',
|
||||
@@ -719,8 +721,9 @@ test('a legacy three-shot Nepal browser project bootstraps to the current 25-sho
|
||||
for (const shot of scene.shots.slice(0, 8)) {
|
||||
assert.equal(scene.appliedShotPacks[0].shotBindings[shot.title], shot.id);
|
||||
}
|
||||
assert.equal(director._selectedSceneId, scene.id);
|
||||
assert.equal(director._selectedShotId, scene.shots[0].id);
|
||||
// The upgrade selects nothing: authoring starts with no scene.
|
||||
assert.equal(director._selectedSceneId, null);
|
||||
assert.equal(director._selectedShotId, null);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
@@ -1798,6 +1801,7 @@ test('Scene snapshots are immutable and editing outcomes retain the affected sho
|
||||
const { director, restore } = makeDirector();
|
||||
try {
|
||||
director._activeRun = null;
|
||||
director.selectShot('scene-1');
|
||||
const seen = [];
|
||||
const unsubscribe = director.subscribe((notification) => seen.push(notification));
|
||||
assert.equal(seen[0].initial, true);
|
||||
@@ -2029,3 +2033,564 @@ test('a caught run failure resolves as run-failed, not success (#971)', async ()
|
||||
);
|
||||
} finally { console.warn = warn; await director.destroy(); restore(); }
|
||||
});
|
||||
test('listShots gives a scene its shots in order, each starting where the last ends', () => {
|
||||
const { director, restore } = makeDirector();
|
||||
try {
|
||||
const scene = director._project.scenes[0];
|
||||
const shots = director.listShots(scene.id);
|
||||
assert.deepEqual(
|
||||
shots.map((s) => s.id),
|
||||
scene.shots.map((s) => s.id),
|
||||
);
|
||||
assert.equal(shots[0].startSec, 0);
|
||||
for (let i = 1; i < shots.length; i++)
|
||||
assert.equal(
|
||||
shots[i].startSec,
|
||||
shots[i - 1].startSec + shots[i - 1].durationSec,
|
||||
);
|
||||
assert.ok(shots.every((s) => typeof s.title === 'string' && s.title));
|
||||
assert.deepEqual(director.listShots('no-such-scene'), []);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('selectShot selects a scene and shot for authoring, falling back to the first shot', () => {
|
||||
const { director, restore } = makeDirector();
|
||||
try {
|
||||
const scene = director._project.scenes.at(-1);
|
||||
const last = scene.shots.at(-1);
|
||||
assert.equal(director.selectShot(scene.id, last.id), true);
|
||||
assert.equal(director._selectedSceneId, scene.id);
|
||||
assert.equal(director._selectedShotId, last.id);
|
||||
assert.equal(director.selectShot(scene.id, 'no-such-shot'), true);
|
||||
assert.equal(director._selectedShotId, scene.shots[0].id);
|
||||
assert.equal(director.selectShot('no-such-scene'), false);
|
||||
assert.deepEqual(director.selection(), {
|
||||
sceneId: scene.id,
|
||||
shotId: scene.shots[0].id,
|
||||
});
|
||||
assert.equal(director.hasScene(scene.id), true);
|
||||
assert.equal(director.hasScene('no-such-scene'), false);
|
||||
// No scene: back to "No scene yet".
|
||||
assert.equal(director.selectShot(null), true);
|
||||
assert.deepEqual(director.selection(), { sceneId: null, shotId: null });
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('whenIdle waits for tracked work, including work started while waiting', async () => {
|
||||
const { director, restore } = makeDirector();
|
||||
try {
|
||||
let first;
|
||||
let second;
|
||||
director._trackWork(new Promise((resolve) => (first = resolve)));
|
||||
let idle = false;
|
||||
const waiting = director.whenIdle().then(() => (idle = true));
|
||||
await settle();
|
||||
director._trackWork(new Promise((resolve) => (second = resolve)));
|
||||
first();
|
||||
await settle();
|
||||
assert.equal(idle, false, 'the later work is still pending');
|
||||
second();
|
||||
await waiting;
|
||||
assert.equal(idle, true);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
/** Record the change types a director publishes. */
|
||||
function recordChanges(director) {
|
||||
const types = [];
|
||||
director.subscribe(({ change }) => {
|
||||
if (change?.type) types.push(change.type);
|
||||
});
|
||||
return types;
|
||||
}
|
||||
|
||||
const savedProject = () =>
|
||||
JSON.parse(localStorage.getItem('godsEyeView.sceneProject.v2'));
|
||||
|
||||
test('setSceneInStories saves the flag, publishes, and storyScenes lists the scene', () => {
|
||||
const { director, restore } = makeDirector();
|
||||
try {
|
||||
const changes = recordChanges(director);
|
||||
const scene = director._project.scenes[0];
|
||||
assert.deepEqual(director.storyScenes(), []);
|
||||
assert.equal(director.setSceneInStories(scene.id, true), true);
|
||||
assert.equal(savedProject().scenes[0].stories, true);
|
||||
assert.ok(changes.includes('stories-changed'));
|
||||
assert.deepEqual(director.storyScenes(), [
|
||||
{
|
||||
id: scene.id,
|
||||
title: 'Fixture Scene',
|
||||
camera: {
|
||||
lat: 10,
|
||||
lon: 20,
|
||||
alt: 500000,
|
||||
heading: 0,
|
||||
pitch: -40,
|
||||
roll: 0,
|
||||
},
|
||||
shotCount: 2,
|
||||
thumb: '',
|
||||
tags: [],
|
||||
},
|
||||
]);
|
||||
// The camera is a copy; editing it leaves the project alone.
|
||||
director.storyScenes()[0].camera.lat = 0;
|
||||
assert.equal(scene.shots[0].camera.lat, 10);
|
||||
|
||||
changes.length = 0;
|
||||
assert.equal(director.setSceneInStories(scene.id, false), true);
|
||||
assert.equal(Object.hasOwn(savedProject().scenes[0], 'stories'), false);
|
||||
assert.deepEqual(changes, ['stories-changed']);
|
||||
assert.deepEqual(director.storyScenes(), []);
|
||||
assert.equal(director.setSceneInStories('no-such-scene', true), false);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('draftScenes lists the person’s own scenes with shots that are not on the Stories page', () => {
|
||||
const { director, restore } = makeDirector();
|
||||
try {
|
||||
const scene = director._project.scenes[0];
|
||||
// The fixture scene is the person's own: a draft until saved.
|
||||
assert.deepEqual(
|
||||
director.draftScenes().map(({ id }) => id),
|
||||
[scene.id],
|
||||
);
|
||||
director.setSceneInStories(scene.id, true);
|
||||
assert.deepEqual(director.draftScenes(), [], 'saved: no longer a draft');
|
||||
director.setSceneInStories(scene.id, false);
|
||||
// A built-in scene is never a draft.
|
||||
scene.id = 'flights-radar';
|
||||
assert.deepEqual(director.draftScenes(), []);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('a scene without shots cannot be saved to Stories', () => {
|
||||
const project = structuredClone(PROJECT_FIXTURE);
|
||||
project.scenes.push({ id: 'empty', title: 'Empty', shots: [] });
|
||||
const { director, restore } = makeDirector({ project });
|
||||
try {
|
||||
const changes = recordChanges(director);
|
||||
assert.equal(director.setSceneInStories('empty', true), false);
|
||||
assert.equal(Object.hasOwn(director._project.scenes[1], 'stories'), false);
|
||||
assert.equal(changes.includes('stories-changed'), false);
|
||||
// Taking it off is always allowed.
|
||||
assert.equal(director.setSceneInStories('empty', false), true);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('the Stories flag survives a reload and an export/import round trip', async () => {
|
||||
const project = structuredClone(PROJECT_FIXTURE);
|
||||
project.scenes.push({
|
||||
id: 'scene-2',
|
||||
title: 'Second',
|
||||
shots: PROJECT_FIXTURE.scenes[0].shots.map((shot) => ({
|
||||
...structuredClone(shot),
|
||||
id: `${shot.id}-2`,
|
||||
})),
|
||||
});
|
||||
const first = makeDirector({ project });
|
||||
let saved;
|
||||
try {
|
||||
first.director.setSceneInStories('scene-2', true);
|
||||
saved = localStorage.getItem('godsEyeView.sceneProject.v2');
|
||||
} finally {
|
||||
first.restore();
|
||||
}
|
||||
const { director, restore } = makeDirector({
|
||||
storage: { 'godsEyeView.sceneProject.v2': saved },
|
||||
});
|
||||
try {
|
||||
assert.deepEqual(
|
||||
director.storyScenes().map((s) => s.id),
|
||||
['scene-2'],
|
||||
);
|
||||
const exported = stringifySceneDocument(director._project);
|
||||
director.setSceneInStories('scene-2', false);
|
||||
const changes = recordChanges(director);
|
||||
assert.equal(
|
||||
await director.importProjectFile({
|
||||
name: 'scenes.json',
|
||||
text: async () => exported,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.ok(changes.includes('stories-changed'));
|
||||
assert.deepEqual(
|
||||
director.storyScenes().map((s) => s.id),
|
||||
['scene-2'],
|
||||
);
|
||||
assert.equal(savedProject().scenes[1].stories, true);
|
||||
assert.equal(Object.hasOwn(savedProject().scenes[0], 'stories'), false);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('projects saved before the Stories flag still load, and a malformed flag is refused', async () => {
|
||||
const { director, restore } = makeDirector();
|
||||
try {
|
||||
assert.equal(Object.hasOwn(director._project.scenes[0], 'stories'), false);
|
||||
const project = structuredClone(PROJECT_FIXTURE);
|
||||
project.scenes[0].stories = 'yes';
|
||||
const before = director._project;
|
||||
await director.importProjectFile({
|
||||
name: 'bad.json',
|
||||
text: async () => JSON.stringify(project),
|
||||
});
|
||||
assert.equal(director._project, before);
|
||||
assert.match(director._presentation.status, /stories: expected true/);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('deleting a scene or its last shot in Stories publishes stories-changed', () => {
|
||||
const project = structuredClone(PROJECT_FIXTURE);
|
||||
project.scenes.push({
|
||||
id: 'scene-2',
|
||||
title: 'Second',
|
||||
shots: [
|
||||
{ ...structuredClone(PROJECT_FIXTURE.scenes[0].shots[0]), id: 'only' },
|
||||
],
|
||||
});
|
||||
const { director, restore } = makeDirector({ project });
|
||||
try {
|
||||
director.setSceneInStories('scene-1', true);
|
||||
director.setSceneInStories('scene-2', true);
|
||||
const changes = recordChanges(director);
|
||||
director.deleteShot('scene-2', 'only');
|
||||
assert.ok(changes.includes('stories-changed'));
|
||||
assert.equal(Object.hasOwn(director._project.scenes[1], 'stories'), false);
|
||||
assert.deepEqual(
|
||||
director.storyScenes().map((s) => s.id),
|
||||
['scene-1'],
|
||||
);
|
||||
|
||||
changes.length = 0;
|
||||
director.selectShot('scene-1');
|
||||
director._deleteSelectedScene();
|
||||
assert.ok(changes.includes('scene-deleted'));
|
||||
assert.ok(changes.includes('stories-changed'));
|
||||
assert.deepEqual(director.storyScenes(), []);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('authoring selects no scene on load, with or without a saved project', () => {
|
||||
for (const options of [{}, { storage: {} }]) {
|
||||
const { director, restore } = makeDirector(options);
|
||||
try {
|
||||
assert.ok(
|
||||
director._project.scenes.length > 0,
|
||||
'the scenes stay in the project',
|
||||
);
|
||||
assert.equal(director._selectedSceneId, null);
|
||||
assert.equal(director._selectedShotId, null);
|
||||
assert.equal(director._getSelectedScene(), null);
|
||||
director._renderSceneSelect();
|
||||
assert.equal(
|
||||
director._selectedSceneId,
|
||||
null,
|
||||
'nothing falls back to the first scene',
|
||||
);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('capture with no scene starts a new scene and captures into it', () => {
|
||||
const { director, restore } = makeDirector();
|
||||
try {
|
||||
const changes = recordChanges(director);
|
||||
const before = director._project.scenes.length;
|
||||
director.captureShot();
|
||||
assert.equal(director._project.scenes.length, before + 1);
|
||||
const scene = director._project.scenes.at(-1);
|
||||
assert.equal(scene.title, `Scene ${before + 1}`);
|
||||
assert.equal(director._selectedSceneId, scene.id);
|
||||
assert.equal(scene.shots.length, 1);
|
||||
assert.equal(director._selectedShotId, scene.shots[0].id);
|
||||
assert.deepEqual(
|
||||
changes.filter((type) =>
|
||||
['scene-created', 'shot-captured'].includes(type),
|
||||
),
|
||||
['scene-created', 'shot-captured'],
|
||||
);
|
||||
assert.equal(savedProject().scenes.at(-1).shots.length, 1);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('capture with no scene and no camera creates nothing', () => {
|
||||
const { director, styleManager, restore } = makeDirector();
|
||||
try {
|
||||
styleManager.getCameraState = () => null;
|
||||
const before = director._project.scenes.length;
|
||||
director.captureShot();
|
||||
assert.equal(director._project.scenes.length, before);
|
||||
assert.equal(director._selectedSceneId, null);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('deleting the current scene selects none', () => {
|
||||
const project = structuredClone(PROJECT_FIXTURE);
|
||||
project.scenes.push({ id: 'scene-2', title: 'Second', shots: [] });
|
||||
const { director, restore } = makeDirector({ project });
|
||||
try {
|
||||
director.selectShot('scene-2');
|
||||
director._deleteSelectedScene();
|
||||
assert.equal(director._selectedSceneId, null);
|
||||
assert.equal(director._selectedShotId, null);
|
||||
assert.deepEqual(
|
||||
director._project.scenes.map(({ id }) => id),
|
||||
['scene-1'],
|
||||
);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('an import keeps the current scene, else picks a non-built-in scene, else none', async () => {
|
||||
const { director, restore } = makeDirector();
|
||||
try {
|
||||
const exported = stringifySceneDocument(director._project);
|
||||
const file = { name: 'scenes.json', text: async () => exported };
|
||||
assert.equal(await director.importProjectFile(file), true);
|
||||
assert.equal(director._selectedSceneId, 'scene-1', 'the authored scene');
|
||||
const builtIn = JSON.stringify({
|
||||
version: 6,
|
||||
scenes: [
|
||||
{
|
||||
...structuredClone(PROJECT_FIXTURE.scenes[0]),
|
||||
id: SCENE_RECIPES[0].id,
|
||||
},
|
||||
],
|
||||
});
|
||||
assert.equal(
|
||||
await director.importProjectFile({
|
||||
name: 'b.json',
|
||||
text: async () => builtIn,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
director._selectedSceneId,
|
||||
null,
|
||||
'a built-in scene is never picked',
|
||||
);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
const THUMB = 'data:image/jpeg;base64,/9j/AAAA';
|
||||
|
||||
test('story thumbnail and tags are saved, listed and announced for a scene in Stories', () => {
|
||||
const { director, restore } = makeDirector();
|
||||
try {
|
||||
const changes = recordChanges(director);
|
||||
assert.equal(director.setSceneStoryThumb('scene-1', THUMB), true);
|
||||
assert.equal(
|
||||
director.setSceneStoryTags('scene-1', ['Floods', 'Climate']),
|
||||
true,
|
||||
);
|
||||
assert.equal(savedProject().scenes[0].storyThumb, THUMB);
|
||||
assert.deepEqual(savedProject().scenes[0].storyTags, ['Floods', 'Climate']);
|
||||
assert.equal(
|
||||
changes.filter((type) => type === 'story-details-changed').length,
|
||||
2,
|
||||
);
|
||||
assert.equal(
|
||||
changes.includes('stories-changed'),
|
||||
false,
|
||||
'not in Stories yet',
|
||||
);
|
||||
|
||||
director.setSceneInStories('scene-1', true);
|
||||
assert.equal(director.storyScenes()[0].thumb, THUMB);
|
||||
assert.deepEqual(director.storyScenes()[0].tags, ['Floods', 'Climate']);
|
||||
director.storyScenes()[0].tags.push('Space');
|
||||
assert.deepEqual(director._project.scenes[0].storyTags, [
|
||||
'Floods',
|
||||
'Climate',
|
||||
]);
|
||||
|
||||
changes.length = 0;
|
||||
director.setSceneStoryThumb('scene-1', 'data:image/png;base64,AAAA');
|
||||
assert.ok(changes.includes('stories-changed'));
|
||||
changes.length = 0;
|
||||
director.selectShot('scene-1');
|
||||
director._toggleSelectedSceneTag('Floods');
|
||||
assert.ok(changes.includes('stories-changed'));
|
||||
assert.deepEqual(director.storyScenes()[0].tags, ['Climate']);
|
||||
director._toggleSelectedSceneTag('Climate');
|
||||
assert.equal(
|
||||
Object.hasOwn(director._project.scenes[0], 'storyTags'),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(director.storyScenes()[0].tags, []);
|
||||
|
||||
// Unknown tags, more than five, or no such scene are refused.
|
||||
assert.equal(director.setSceneStoryTags('scene-1', ['Nope']), false);
|
||||
assert.equal(
|
||||
director.setSceneStoryTags('scene-1', STORY_TAGS.slice(0, 6)),
|
||||
false,
|
||||
);
|
||||
assert.equal(director.setSceneStoryTags('no-such-scene', []), false);
|
||||
assert.equal(director.setSceneStoryThumb('no-such-scene', THUMB), false);
|
||||
director.setSceneStoryTags('scene-1', STORY_TAGS.slice(0, 5));
|
||||
director._toggleSelectedSceneTag(STORY_TAGS[5]);
|
||||
assert.equal(director._project.scenes[0].storyTags.length, 5);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('an invalid thumbnail is not kept and the save error is shown', () => {
|
||||
const { director, restore } = makeDirector();
|
||||
try {
|
||||
// A thumbnail may pass the usual 65,536-character text limit.
|
||||
const large = `data:image/jpeg;base64,${'A'.repeat(200000)}`;
|
||||
assert.equal(director.setSceneStoryThumb('scene-1', large), true);
|
||||
assert.equal(savedProject().scenes[0].storyThumb, large);
|
||||
director.setSceneStoryThumb('scene-1', THUMB);
|
||||
assert.equal(
|
||||
director.setSceneStoryThumb('scene-1', 'https://example.com/a.jpg'),
|
||||
false,
|
||||
);
|
||||
assert.equal(director._project.scenes[0].storyThumb, THUMB);
|
||||
assert.match(director._presentation.status, /Scene not saved/);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('story thumbnail and tags survive a reload and an export/import round trip', async () => {
|
||||
const first = makeDirector();
|
||||
let saved;
|
||||
try {
|
||||
first.director.setSceneStoryThumb('scene-1', THUMB);
|
||||
first.director.setSceneStoryTags('scene-1', ['Storms']);
|
||||
saved = localStorage.getItem('godsEyeView.sceneProject.v2');
|
||||
} finally {
|
||||
first.restore();
|
||||
}
|
||||
const { director, restore } = makeDirector({
|
||||
storage: { 'godsEyeView.sceneProject.v2': saved },
|
||||
});
|
||||
try {
|
||||
const scene = director._project.scenes.find(({ id }) => id === 'scene-1');
|
||||
assert.equal(scene.storyThumb, THUMB);
|
||||
assert.deepEqual(scene.storyTags, ['Storms']);
|
||||
const exported = stringifySceneDocument(director._project);
|
||||
director.setSceneStoryTags('scene-1', []);
|
||||
director.setSceneStoryThumb('scene-1', 'data:image/png;base64,AAAA');
|
||||
assert.equal(
|
||||
await director.importProjectFile({
|
||||
name: 'scenes.json',
|
||||
text: async () => exported,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(director._project.scenes[0].storyThumb, THUMB);
|
||||
assert.deepEqual(director._project.scenes[0].storyTags, ['Storms']);
|
||||
assert.equal(savedProject().scenes[0].storyThumb, THUMB);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('imports with a malformed thumbnail or tags are refused', async () => {
|
||||
const { director, restore } = makeDirector();
|
||||
try {
|
||||
const before = director._project;
|
||||
for (const [field, value, reason] of [
|
||||
[
|
||||
'storyThumb',
|
||||
'data:image/gif;base64,AAAA',
|
||||
/storyThumb: expected a JPEG or PNG data URL/,
|
||||
],
|
||||
[
|
||||
'storyThumb',
|
||||
`data:image/jpeg;base64,${'A'.repeat(300000)}`,
|
||||
/storyThumb/,
|
||||
],
|
||||
[
|
||||
'storyTags',
|
||||
['Floods', 'Floods'],
|
||||
/storyTags: expected at most 5 different Stories tags/,
|
||||
],
|
||||
['storyTags', ['Volcanoes'], /storyTags/],
|
||||
['storyTags', STORY_TAGS.slice(0, 6), /storyTags/],
|
||||
]) {
|
||||
const project = structuredClone(PROJECT_FIXTURE);
|
||||
project.scenes[0][field] = value;
|
||||
await director.importProjectFile({
|
||||
name: 'bad.json',
|
||||
text: async () => JSON.stringify(project),
|
||||
});
|
||||
assert.equal(director._project, before, field);
|
||||
assert.match(director._presentation.status, reason);
|
||||
}
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('THUMBNAIL stores the frame read in postRender on the selected scene', async () => {
|
||||
const { director, viewer, restore } = makeDirector();
|
||||
const createElement = document.createElement;
|
||||
try {
|
||||
assert.equal(
|
||||
await director.captureSceneThumb(),
|
||||
false,
|
||||
'no scene, no capture',
|
||||
);
|
||||
director.selectShot('scene-1');
|
||||
const listeners = new Set();
|
||||
viewer.scene = {
|
||||
canvas: { width: 640, height: 360 },
|
||||
postRender: {
|
||||
addEventListener(listener) {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
},
|
||||
},
|
||||
requestRender: () => [...listeners].forEach((listener) => listener()),
|
||||
};
|
||||
document.createElement = () => ({
|
||||
getContext: () => ({ drawImage() {} }),
|
||||
toDataURL: () => THUMB,
|
||||
});
|
||||
assert.equal(await director.captureSceneThumb(), true);
|
||||
assert.equal(director._project.scenes[0].storyThumb, THUMB);
|
||||
assert.equal(director._presentation.status, 'Thumbnail captured');
|
||||
|
||||
viewer.scene = null;
|
||||
assert.equal(await director.captureSceneThumb(), false);
|
||||
assert.equal(
|
||||
director._presentation.status,
|
||||
'Thumbnail could not be captured',
|
||||
);
|
||||
} finally {
|
||||
document.createElement = createElement;
|
||||
restore();
|
||||
}
|
||||
});
|
||||
@@ -8,6 +8,8 @@ import {
|
||||
decodeBloomIntensity,
|
||||
} from '../bloom.js';
|
||||
import { RETIRED_STYLES } from '../visualStylePolicy.js';
|
||||
import { isStoryTagList } from './storyTags.js';
|
||||
import { isStoryThumb } from './storyThumb.js';
|
||||
|
||||
/** @constant {number} Current schema version for project migration */
|
||||
export const PROJECT_VERSION = SCENE_DOCUMENT_VERSION;
|
||||
@@ -359,6 +361,15 @@ export function normalizeProject(rawProject) {
|
||||
title: scene?.title || `Scene ${sceneIdx + 1}`,
|
||||
...(scene?.dataPacks ? { dataPacks: deepClone(scene.dataPacks) } : {}),
|
||||
...(scene?.anchors ? { anchors: deepClone(scene.anchors) } : {}),
|
||||
// Published to the Stories page.
|
||||
...(scene?.stories === true ? { stories: true } : {}),
|
||||
// The Stories card's thumbnail and tags.
|
||||
...(isStoryThumb(scene?.storyThumb)
|
||||
? { storyThumb: scene.storyThumb }
|
||||
: {}),
|
||||
...(isStoryTagList(scene?.storyTags) && scene.storyTags.length
|
||||
? { storyTags: [...scene.storyTags] }
|
||||
: {}),
|
||||
releaseLayerIds: [
|
||||
...new Set(
|
||||
(Array.isArray(scene?.releaseLayerIds)
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
/** The tags a scene saved to Stories can carry, and their limits. */
|
||||
|
||||
// Marks each English key for translation without loading the i18n runtime
|
||||
// into the scene document validator; the panel shows them through t().
|
||||
const msg = (text) => text;
|
||||
|
||||
/** Tag keys in display order; stored in English on `scene.storyTags`. */
|
||||
export const STORY_TAGS = Object.freeze([
|
||||
msg('Floods'),
|
||||
msg('Wildfires'),
|
||||
msg('Storms'),
|
||||
msg('Earthquakes'),
|
||||
msg('Flights'),
|
||||
msg('Maritime'),
|
||||
msg('Space'),
|
||||
msg('Conflict'),
|
||||
msg('Infrastructure'),
|
||||
msg('Climate'),
|
||||
]);
|
||||
|
||||
/** At most this many tags per scene. */
|
||||
export const STORY_TAG_LIMIT = 5;
|
||||
|
||||
/**
|
||||
* Whether `tags` is a valid `storyTags` value: unique keys from STORY_TAGS,
|
||||
* at most STORY_TAG_LIMIT of them.
|
||||
* @param {unknown} tags
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isStoryTagList(tags) {
|
||||
return (
|
||||
Array.isArray(tags) &&
|
||||
tags.length <= STORY_TAG_LIMIT &&
|
||||
new Set(tags).size === tags.length &&
|
||||
tags.every((tag) => STORY_TAGS.includes(tag))
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* A scene's Stories card thumbnail: captured from the globe, stored as a data
|
||||
* URL. The scene document validates with this module, so it reaches no
|
||||
* browser globals; callers hand it the viewer and a canvas factory.
|
||||
*/
|
||||
|
||||
export const STORY_THUMB_WIDTH = 320;
|
||||
export const STORY_THUMB_HEIGHT = 180;
|
||||
export const STORY_THUMB_QUALITY = 0.82;
|
||||
/** Longest `storyThumb` a scene document accepts, in characters. */
|
||||
export const STORY_THUMB_MAX_LENGTH = 300000;
|
||||
|
||||
const STORY_THUMB_PATTERN =
|
||||
/^data:image\/(?:jpeg|png);base64,[A-Za-z0-9+/]+={0,2}$/;
|
||||
|
||||
/**
|
||||
* Whether `value` is a valid `storyThumb`: a base64 JPEG or PNG data URL of
|
||||
* at most STORY_THUMB_MAX_LENGTH characters.
|
||||
* @param {unknown} value
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isStoryThumb(value) {
|
||||
return (
|
||||
typeof value === 'string' &&
|
||||
value.length <= STORY_THUMB_MAX_LENGTH &&
|
||||
STORY_THUMB_PATTERN.test(value)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The centred part of a `width`×`height` source with the target's aspect.
|
||||
* @returns {{x: number, y: number, width: number, height: number}}
|
||||
*/
|
||||
export function centreCrop(
|
||||
width,
|
||||
height,
|
||||
targetWidth = STORY_THUMB_WIDTH,
|
||||
targetHeight = STORY_THUMB_HEIGHT,
|
||||
) {
|
||||
const aspect = targetWidth / targetHeight;
|
||||
const cropWidth = Math.min(width, height * aspect);
|
||||
const cropHeight = Math.min(height, width / aspect);
|
||||
return {
|
||||
x: Math.round((width - cropWidth) / 2),
|
||||
y: Math.round((height - cropHeight) / 2),
|
||||
width: Math.round(cropWidth),
|
||||
height: Math.round(cropHeight),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw the centre crop of `source` into a STORY_THUMB_WIDTH×HEIGHT JPEG data
|
||||
* URL, halving in steps so a large canvas downscales smoothly.
|
||||
* @param {HTMLCanvasElement} source
|
||||
* @param {() => HTMLCanvasElement} createCanvas Makes an empty canvas.
|
||||
* @returns {string}
|
||||
*/
|
||||
export function encodeStoryThumb(source, createCanvas) {
|
||||
const crop = centreCrop(source.width, source.height);
|
||||
if (!crop.width || !crop.height) throw new Error('Nothing to capture');
|
||||
let image = source;
|
||||
let area = crop;
|
||||
// Halve until one more halving would undershoot the target.
|
||||
while (area.width / 2 >= STORY_THUMB_WIDTH) {
|
||||
const step = createCanvas();
|
||||
step.width = Math.round(area.width / 2);
|
||||
step.height = Math.round(area.height / 2);
|
||||
const context = step.getContext('2d');
|
||||
context.imageSmoothingQuality = 'high';
|
||||
context.drawImage(
|
||||
image,
|
||||
area.x,
|
||||
area.y,
|
||||
area.width,
|
||||
area.height,
|
||||
0,
|
||||
0,
|
||||
step.width,
|
||||
step.height,
|
||||
);
|
||||
image = step;
|
||||
area = { x: 0, y: 0, width: step.width, height: step.height };
|
||||
}
|
||||
const out = createCanvas();
|
||||
out.width = STORY_THUMB_WIDTH;
|
||||
out.height = STORY_THUMB_HEIGHT;
|
||||
const context = out.getContext('2d');
|
||||
context.imageSmoothingQuality = 'high';
|
||||
context.drawImage(
|
||||
image,
|
||||
area.x,
|
||||
area.y,
|
||||
area.width,
|
||||
area.height,
|
||||
0,
|
||||
0,
|
||||
STORY_THUMB_WIDTH,
|
||||
STORY_THUMB_HEIGHT,
|
||||
);
|
||||
// A very busy view can exceed the limit; lower the quality until it fits.
|
||||
for (const quality of [STORY_THUMB_QUALITY, 0.7, 0.55, 0.4]) {
|
||||
const url = out.toDataURL('image/jpeg', quality);
|
||||
if (isStoryThumb(url)) return url;
|
||||
}
|
||||
throw new Error('Thumbnail too large');
|
||||
}
|
||||
|
||||
/**
|
||||
* Capture the globe as it is drawn now. The WebGL canvas has no
|
||||
* preserveDrawingBuffer, so it is read inside the next postRender, while the
|
||||
* frame is still in the drawing buffer; a render is requested for it.
|
||||
* @param {object} viewer Cesium viewer (its `scene`).
|
||||
* @param {object} options
|
||||
* @param {() => HTMLCanvasElement} options.createCanvas Makes an empty canvas.
|
||||
* @param {number} [options.timeoutMs] Give up when no frame is drawn.
|
||||
* @returns {Promise<string>} JPEG data URL.
|
||||
*/
|
||||
export function captureStoryThumb(viewer, { createCanvas, timeoutMs = 3000 }) {
|
||||
const scene = viewer?.scene;
|
||||
if (!scene?.postRender || !scene.canvas)
|
||||
return Promise.reject(new Error('Globe not ready'));
|
||||
return new Promise((resolve, reject) => {
|
||||
let timer = null;
|
||||
const remove = scene.postRender.addEventListener(() => {
|
||||
remove();
|
||||
clearTimeout(timer);
|
||||
try {
|
||||
resolve(encodeStoryThumb(scene.canvas, createCanvas));
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
timer = setTimeout(() => {
|
||||
remove();
|
||||
reject(new Error('No frame was drawn'));
|
||||
}, timeoutMs);
|
||||
scene.requestRender?.();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
STORY_THUMB_HEIGHT,
|
||||
STORY_THUMB_MAX_LENGTH,
|
||||
STORY_THUMB_WIDTH,
|
||||
captureStoryThumb,
|
||||
centreCrop,
|
||||
encodeStoryThumb,
|
||||
isStoryThumb,
|
||||
} from './storyThumb.js';
|
||||
import { STORY_TAGS, isStoryTagList } from './storyTags.js';
|
||||
|
||||
/** Canvas double recording each draw; toDataURL answers `url(quality)`. */
|
||||
function fakeCanvases(url = () => 'data:image/jpeg;base64,AAAA') {
|
||||
const made = [];
|
||||
const create = () => {
|
||||
const canvas = {
|
||||
width: 0,
|
||||
height: 0,
|
||||
draws: [],
|
||||
qualities: [],
|
||||
getContext: () => ({
|
||||
drawImage: (...args) => canvas.draws.push(args),
|
||||
}),
|
||||
toDataURL: (type, quality) => {
|
||||
canvas.qualities.push([type, quality]);
|
||||
return url(quality);
|
||||
},
|
||||
};
|
||||
made.push(canvas);
|
||||
return canvas;
|
||||
};
|
||||
return { made, create };
|
||||
}
|
||||
|
||||
test('centreCrop keeps the centred 16:9 part of a wider or taller source', () => {
|
||||
assert.deepEqual(centreCrop(1920, 1080), {
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
});
|
||||
assert.deepEqual(centreCrop(2000, 1000), {
|
||||
x: 111,
|
||||
y: 0,
|
||||
width: 1778,
|
||||
height: 1000,
|
||||
});
|
||||
assert.deepEqual(centreCrop(800, 1000), {
|
||||
x: 0,
|
||||
y: 275,
|
||||
width: 800,
|
||||
height: 450,
|
||||
});
|
||||
});
|
||||
|
||||
test('encodeStoryThumb halves a large view down to 320x180 JPEG at 0.82', () => {
|
||||
const { made, create } = fakeCanvases();
|
||||
const source = { width: 2000, height: 1000 };
|
||||
const url = encodeStoryThumb(source, create);
|
||||
assert.equal(url, 'data:image/jpeg;base64,AAAA');
|
||||
// 1778 wide halves to 889, then 445, then the final 320x180.
|
||||
assert.deepEqual(
|
||||
made.map(({ width, height }) => [width, height]),
|
||||
[
|
||||
[889, 500],
|
||||
[445, 250],
|
||||
[STORY_THUMB_WIDTH, STORY_THUMB_HEIGHT],
|
||||
],
|
||||
);
|
||||
assert.deepEqual(
|
||||
made[0].draws[0].slice(1),
|
||||
[111, 0, 1778, 1000, 0, 0, 889, 500],
|
||||
);
|
||||
assert.deepEqual(made.at(-1).qualities, [['image/jpeg', 0.82]]);
|
||||
});
|
||||
|
||||
test('encodeStoryThumb lowers the quality until the image fits, then gives up', () => {
|
||||
const big = 'data:image/jpeg;base64,' + 'A'.repeat(STORY_THUMB_MAX_LENGTH);
|
||||
const fits = fakeCanvases((quality) =>
|
||||
quality > 0.6 ? big : 'data:image/jpeg;base64,AAAA',
|
||||
);
|
||||
assert.equal(
|
||||
encodeStoryThumb({ width: 320, height: 180 }, fits.create),
|
||||
'data:image/jpeg;base64,AAAA',
|
||||
);
|
||||
assert.deepEqual(
|
||||
fits.made.at(-1).qualities.map(([, quality]) => quality),
|
||||
[0.82, 0.7, 0.55],
|
||||
);
|
||||
const never = fakeCanvases(() => big);
|
||||
assert.throws(
|
||||
() => encodeStoryThumb({ width: 320, height: 180 }, never.create),
|
||||
/too large/,
|
||||
);
|
||||
assert.throws(
|
||||
() => encodeStoryThumb({ width: 0, height: 0 }, never.create),
|
||||
/Nothing to capture/,
|
||||
);
|
||||
});
|
||||
|
||||
/** A Cesium scene double: postRender listeners run on requestRender. */
|
||||
function fakeViewer({ draws = true } = {}) {
|
||||
const listeners = new Set();
|
||||
const scene = {
|
||||
canvas: { width: 640, height: 360 },
|
||||
renders: 0,
|
||||
postRender: {
|
||||
addEventListener(listener) {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
},
|
||||
},
|
||||
requestRender() {
|
||||
scene.renders++;
|
||||
if (draws) for (const listener of [...listeners]) listener();
|
||||
},
|
||||
listeners,
|
||||
};
|
||||
return { scene };
|
||||
}
|
||||
|
||||
test('captureStoryThumb reads the canvas inside the postRender it requested', async () => {
|
||||
const viewer = fakeViewer();
|
||||
const { create } = fakeCanvases();
|
||||
const url = await captureStoryThumb(viewer, { createCanvas: create });
|
||||
assert.equal(url, 'data:image/jpeg;base64,AAAA');
|
||||
assert.equal(viewer.scene.renders, 1);
|
||||
assert.equal(viewer.scene.listeners.size, 0, 'the listener is removed');
|
||||
});
|
||||
|
||||
test('captureStoryThumb gives up when no frame is drawn or there is no globe', async () => {
|
||||
const viewer = fakeViewer({ draws: false });
|
||||
await assert.rejects(
|
||||
captureStoryThumb(viewer, {
|
||||
createCanvas: fakeCanvases().create,
|
||||
timeoutMs: 1,
|
||||
}),
|
||||
/No frame was drawn/,
|
||||
);
|
||||
assert.equal(viewer.scene.listeners.size, 0);
|
||||
await assert.rejects(
|
||||
captureStoryThumb({}, { createCanvas: fakeCanvases().create }),
|
||||
/Globe not ready/,
|
||||
);
|
||||
});
|
||||
|
||||
test('isStoryThumb accepts only bounded base64 JPEG or PNG data URLs', () => {
|
||||
assert.equal(isStoryThumb('data:image/jpeg;base64,AAAA'), true);
|
||||
assert.equal(isStoryThumb('data:image/png;base64,AAA='), true);
|
||||
for (const value of [
|
||||
'',
|
||||
null,
|
||||
42,
|
||||
'data:image/gif;base64,AAAA',
|
||||
'data:image/jpeg,AAAA',
|
||||
'https://example.com/a.jpg',
|
||||
'data:image/jpeg;base64,AA"A',
|
||||
'data:image/jpeg;base64,' + 'A'.repeat(STORY_THUMB_MAX_LENGTH),
|
||||
])
|
||||
assert.equal(isStoryThumb(value), false, String(value).slice(0, 40));
|
||||
});
|
||||
|
||||
test('isStoryTagList accepts up to five different known tags', () => {
|
||||
assert.equal(STORY_TAGS.length, 10);
|
||||
assert.equal(isStoryTagList([]), true);
|
||||
assert.equal(isStoryTagList(STORY_TAGS.slice(0, 5)), true);
|
||||
assert.equal(isStoryTagList(STORY_TAGS.slice(0, 6)), false);
|
||||
assert.equal(isStoryTagList(['Floods', 'Floods']), false);
|
||||
assert.equal(isStoryTagList(['floods']), false);
|
||||
assert.equal(isStoryTagList('Floods'), false);
|
||||
});
|
||||
Reference in new issue
Block a user