Merge main and switch Cesium and Navara in place through Vue

Preserve the camera, map source and layer selection across engine sessions. Restore the previous engine if startup fails and retain local history navigation.
This commit is contained in:
German Khokhlov committed 2026-11-02 13:10:36 +04:00
commit b8f4d097c4
1691 files changed
+225876 -41594

No files matched your search

@@ -0,0 +1,20 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { SCENE_RECIPES, displayShotTitle } from './recipes.js';
import { setLocale } from '../i18n/index.js';
test('an operator-typed title in the built-in Nepal scene stays as typed', () => {
const scene = SCENE_RECIPES.find((r) => r.id === 'bhote-koshi-nepal-scene');
assert.ok(scene, 'built-in bootstrap scene exists');
for (const locale of ['ru', 'es', 'it', 'zh-CN', 'zh-Hant']) {
setLocale(locale);
const title = 'Global Incident Context';
// A shot captured by the operator: no sourcePackId, renamed to this title.
const shown = displayShotTitle(
title,
{ id: 'shot-user', title },
{ id: scene.id },
);
assert.equal(shown, title, `${locale}: got ${shown}`);
}
});
+59 -64
View File
@@ -1,54 +1,56 @@
import * as Cesium from 'cesium';
import { renderPackGeometry } from './geometry.js';
import { useDataPacksStore } from '../../ui/stores/dataPacks.js';
import { applicationPinia } from '../../ui/vueRuntime.js';
function caption(viewer, pack) {
const card = document.createElement('section');
card.dataset.directorPack = pack.id;
Object.assign(card.style, {
color: '#e3faff',
background: '#08141eed',
border: '1px solid #2491a8',
padding: '8px',
margin: '4px',
maxWidth: '260px',
font: '12px sans-serif',
});
const title = document.createElement('div');
title.textContent = `${pack.id} · ${pack.attribution.text} · ${pack.attribution.license}`;
card.append(title);
if (pack.attribution.url) {
const link = document.createElement('a');
link.textContent = 'Source';
link.href = pack.attribution.url;
link.target = '_blank';
link.rel = 'noopener noreferrer';
link.style.color = '#6eeaff';
card.append(link);
}
return card;
}
const xyz = (p) => Cesium.Cartesian3.fromDegrees(...p);
/** Create rendering adapters; data acquisition and authored placement stay independent. */
export function createPackPresentations(viewer, targets = new Map()) {
let panel;
// Key every panel and card on the page, so a new one never reuses an old
// one's DOM.
let panelKeys = 0,
cardKeys = 0;
/**
* Create rendering adapters; data acquisition and authored placement stay
* independent. Each pack's attribution card is presented to the data packs
* store, which its view renders inside the viewer's container.
*/
export function createPackPresentations(
viewer,
targets = new Map(),
{ store = useDataPacksStore(applicationPinia()) } = {},
) {
const owner = {};
let key,
cards = [];
function present() {
store.publish(
owner,
cards.length ? { key, container: viewer.container, cards } : null,
);
}
function addCard(pack) {
if (!panel) {
panel = document.createElement('div');
panel.dataset.directorPacks = '';
Object.assign(panel.style, {
position: 'absolute',
right: '10px',
bottom: '70px',
maxHeight: '40vh',
overflowY: 'auto',
zIndex: '30',
});
viewer.container.append(panel);
}
const card = caption(viewer, pack);
panel.append(card);
return card;
if (!cards.length) key = ++panelKeys;
const card = {
key: ++cardKeys,
id: pack.id,
title: `${pack.id} · ${pack.attribution.text} · ${pack.attribution.license}`,
url: pack.attribution.url || null,
media: null,
};
cards = [...cards, card];
present();
return card.key;
}
function updateCard(key, patch) {
cards = cards.map((card) =>
card.key === key ? { ...card, ...patch } : card,
);
present();
}
function removeCard(key) {
cards = cards.filter((card) => card.key !== key);
present();
}
function resource(pack) {
const entities = [],
@@ -77,7 +79,12 @@ export function createPackPresentations(viewer, targets = new Map()) {
viewer.scene.requestRender();
},
card() {
return (card ||= addCard(pack));
card ||= addCard(pack);
},
/** @param {{kind: 'video'|'audio', src: string}} media */
media(media) {
card ||= addCard(pack);
updateCard(card, { media });
},
url(blob) {
const url = URL.createObjectURL(blob);
@@ -88,16 +95,8 @@ export function createPackPresentations(viewer, targets = new Map()) {
if (destroyed) return;
destroyed = true;
for (const key of featureKeys.splice(0)) targets.delete(key);
for (const media of card?.querySelectorAll('video,audio') || []) {
media.pause();
media.removeAttribute('src');
media.load();
}
card?.remove();
if (panel && !panel.childElementCount) {
panel.remove();
panel = null;
}
// The view stops a removed card's player as it goes.
if (card) removeCard(card);
for (const entity of entities.splice(0)) viewer.entities.remove(entity);
for (const primitive of primitives.splice(0))
viewer.scene.primitives.remove(primitive);
@@ -211,14 +210,10 @@ export function createPackPresentations(viewer, targets = new Map()) {
pixelOffset: new Cesium.Cartesian2(0, -24),
},
});
const media = document.createElement(
asset.mimeType.startsWith('video/') ? 'video' : 'audio',
);
media.controls = true;
media.preload = 'none';
media.style.width = '240px';
media.src = handle.url(new Blob([asset.bytes], { type: asset.mimeType }));
handle.card().append(media);
handle.media({
kind: asset.mimeType.startsWith('video/') ? 'video' : 'audio',
src: handle.url(new Blob([asset.bytes], { type: asset.mimeType })),
});
}),
};
}
@@ -0,0 +1,137 @@
// src/scenes/dataPacks/presentationView.test.mjs — loaded packs' attribution
// cards render in the viewer's container from what the data-pack
// presentations present, and a removed card's player stops.
import '../../testSupport/registerDom.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import { createApp, nextTick } from 'vue';
import { createPinia } from 'pinia';
import { useDataPacksStore } from '../../ui/stores/dataPacks.js';
import DataPacks from '../../ui/views/panels/DataPacks.vue';
import { createPackPresentations } from './presentation.js';
const ANCHOR = { id: 'here', lat: 30, lon: -97, alt: 10 };
const pack = (id, url) => ({
id,
attribution: { text: 'Synthetic', license: 'CC0-1.0', url },
placement: { anchorId: 'here' },
});
function fixture(t) {
document.body.replaceChildren();
const container = document.body.appendChild(document.createElement('div'));
const pinia = createPinia();
const app = createApp(DataPacks).use(pinia);
app.mount(document.body.appendChild(document.createElement('div')));
const viewer = {
container,
scene: { requestRender() {} },
entities: { add: (spec) => spec, remove() {} },
};
const store = useDataPacksStore(pinia);
const presentations = createPackPresentations(viewer, new Map(), { store });
t.after(() => app.unmount());
const settle = async () => {
for (let flush = 0; flush < 4; flush += 1) await nextTick();
};
const $ = (selector) => container.querySelector(selector);
const $$ = (selector) => [...container.querySelectorAll(selector)];
return { presentations, viewer, store, settle, $, $$ };
}
const media = (presentations, id, mimeType = 'audio/mpeg') =>
presentations.media({
pack: pack(id),
asset: { bytes: new Uint8Array([1, 2, 3]), mimeType },
anchors: [ANCHOR],
signal: new AbortController().signal,
});
test('a loaded pack shows its attribution card in the viewer container', async (t) => {
const { presentations, settle, $, $$ } = fixture(t);
assert.equal($('[data-director-packs]'), null);
const handle = await media(presentations, 'clip', 'video/webm');
await settle();
const panel = $('[data-director-packs]');
assert.equal(panel.tagName, 'DIV');
assert.equal(panel.style.position, 'absolute');
assert.equal(panel.style.right, '10px');
assert.equal(panel.style.bottom, '70px');
assert.equal(panel.style.zIndex, '30');
const [card] = $$('[data-director-pack]');
assert.equal(card.tagName, 'SECTION');
assert.equal(card.dataset.directorPack, 'clip');
assert.equal(card.style.maxWidth, '260px');
assert.equal(
card.querySelector('div').textContent,
'clip · Synthetic · CC0-1.0',
);
assert.equal(card.querySelector('a'), null, 'no link without a source URL');
const video = card.querySelector('video');
assert.equal(video.controls, true);
assert.equal(video.preload, 'none');
assert.equal(video.style.width, '240px');
assert.match(video.getAttribute('src'), /^blob:/);
handle.dispose();
await settle();
assert.equal($('[data-director-packs]'), null);
});
test('a card links its source, and a removed card stops its player', async (t) => {
const { presentations, settle, $, $$ } = fixture(t);
const first = await media(presentations, 'one');
const second = await presentations.media({
pack: pack('two', 'https://example.org/two'),
asset: { bytes: new Uint8Array([1]), mimeType: 'audio/ogg' },
anchors: [ANCHOR],
signal: new AbortController().signal,
});
await settle();
assert.deepEqual(
$$('[data-director-pack]').map((card) => card.dataset.directorPack),
['one', 'two'],
);
const link = $('[data-director-pack="two"] a');
assert.equal(link.textContent, 'Source');
assert.equal(link.getAttribute('href'), 'https://example.org/two');
assert.equal(link.target, '_blank');
assert.equal(link.rel, 'noopener noreferrer');
const audio = $('[data-director-pack="one"] audio');
const calls = [];
audio.pause = () => calls.push('pause');
audio.load = () => calls.push('load');
first.dispose();
await settle();
assert.deepEqual(calls, ['pause', 'load']);
assert.equal(audio.getAttribute('src'), null);
assert.equal(audio.isConnected, false);
assert.deepEqual(
$$('[data-director-pack]').map((card) => card.dataset.directorPack),
['two'],
);
second.dispose();
await settle();
assert.equal($('[data-director-packs]'), null);
});
test('each set of presentations keeps its own panel', async (t) => {
const { presentations, viewer, store, settle, $$ } = fixture(t);
const one = await media(presentations, 'one');
await media(presentations, 'two');
const later = createPackPresentations(viewer, new Map(), { store });
const three = await media(later, 'three');
await settle();
const cards = () =>
$$('[data-director-packs]').map((panel) =>
[...panel.querySelectorAll('[data-director-pack]')].map(
(card) => card.dataset.directorPack,
),
);
assert.deepEqual(cards(), [['one', 'two'], ['three']]);
one.dispose();
await settle();
assert.deepEqual(cards(), [['two'], ['three']]);
three.dispose();
await settle();
assert.deepEqual(cards(), [['two']]);
});
+318 -112
View File
@@ -18,15 +18,19 @@ import { resolveCameraPose, resolveCameraMove } from '../director/camera.js';
import { createCameraMotion } from './cameraMotion.js';
import { createStateChannel } from '../app/stateChannel.js';
import { SceneControls } from '../ui/scenes.js';
import { createToast } from '../ui/toast.js';
import { buildPlaybackQueue, playSceneQueue } from '../director/playback.js';
import { createScenePlaybackAdapter } from './playbackAdapter.js';
import * as geo from '../geo/index.js';
import {
SCENE_APPEND_RECIPES,
SCENE_RECIPES,
displaySceneTitle,
displayShotTitle,
getSceneAppendRecipeById,
} from './recipes.js';
import { sceneLayerPlan, sceneRequiresContextModeExit } from './scenePolicy.js';
import { t, tn, msg, onLocaleChange } from '../i18n/index.js';
import { createSceneDataPacks } from './dataPacks/controller.js';
import { createSceneInteractions } from './interactions.js';
import { createSceneSharing } from './sharing.js';
@@ -61,6 +65,7 @@ import {
stringifySceneDocument,
SceneDocumentError,
} from '../director/document.js';
import { sceneSaveFailureReason } from './sceneSaveError.js';
/** @constant {string} localStorage key for the serialized project */
const STORAGE_KEY = 'godsEyeView.sceneProject.v2';
@@ -128,7 +133,7 @@ export class SceneDirector {
)
return;
if (this._usesAuthoredCamera && !this._claimingCamera)
this.stopScene('Camera ownership changed');
this.stopScene(msg('Camera ownership changed'));
};
this._cameraHandoffUnsubscribe =
styleManager.subscribeCameraHandoff?.(yieldCamera);
@@ -155,6 +160,8 @@ export class SceneDirector {
this._runAbort = null;
/** @type {AbortController|null} Aborts the in-flight LOAD's layer transitions */
this._loadAbort = null;
/** @type {AbortController|null} Aborts a same-shot seek's layer reconcile */
this._seekAbort = null;
this._clock = createPlaybackClock({
isRunning: () => this._running,
timingForShot: (scene, shot) => this._sceneTimingForShot(scene, shot),
@@ -175,38 +182,52 @@ export class SceneDirector {
/** @type {string|null} Scene whose layer state most recently landed. */
this._loadedSceneId = null;
const readError = this._storageReadError;
this._presentation = {
status: this._storageReadError
? 'Saved project could not be read; storage preserved. Import a valid file to resume saving.'
: 'Ready',
status: '',
progress: 0,
runtime: '',
playbackActive: false,
keyboardEnabled: false,
};
this._setStatus(() =>
readError
? t(
'Saved project could not be read; storage preserved. Import a valid file to resume saving.',
)
: t('Ready'),
);
this._state = createStateChannel(() => ({
...this.getPlaybackStatus(),
...this._presentation,
hasRun: !!this._lastRunJson,
}));
this._bootstrapLegacyShotPacks();
// Upgrade only already-installed packs; unrelated Scenes are untouched.
for (const scene of this._project.scenes) {
for (const marker of [...(scene.appliedShotPacks || [])]) {
const recipe = getSceneAppendRecipeById(marker.id);
if (
recipe?.expansionFromVersion &&
marker.version > 0 &&
marker.version <= recipe.expansionFromVersion
) {
this.appendShotPack(scene.id, marker.id, {
render: false,
announce: false,
});
if (!this._storageReadError) {
this._bootstrapLegacyShotPacks();
// Upgrade only already-installed packs; unrelated Scenes are untouched.
for (const scene of this._project.scenes) {
for (const marker of [...(scene.appliedShotPacks || [])]) {
const recipe = getSceneAppendRecipeById(marker.id);
if (
recipe?.expansionFromVersion &&
marker.version > 0 &&
marker.version <= recipe.expansionFromVersion
) {
this.appendShotPack(scene.id, marker.id, {
render: false,
announce: false,
});
}
}
}
}
this._initUI();
// A status the director wrote itself follows the language; one it was
// handed (an error message) stays as it is.
this._offLocale = onLocaleChange(() => {
if (typeof this._statusText === 'function')
this._updateStatus(this._statusText);
});
this._visibilityUnsubscribe =
this.dataManager.subscribeVisibilityRequests?.((change) => {
if (
@@ -216,7 +237,7 @@ export class SceneDirector {
return;
const scene = this._getSelectedScene();
if (!scene?.releaseLayerIds?.includes(change.layerId)) return;
this.stopScene('Scene layer turned off');
this.stopScene(msg('Scene layer turned off'));
});
}
@@ -232,7 +253,7 @@ export class SceneDirector {
destroy() {
if (this._destroyPromise) return this._destroyPromise;
this._destroyed = true;
this._sceneSeekGeneration++;
this._bumpSceneSeekGeneration();
this._visibilityUnsubscribe?.();
this._cameraHandoffUnsubscribe?.();
this._removeCameraInput?.();
@@ -242,13 +263,14 @@ export class SceneDirector {
this._interactions?.destroy();
this._dataPacks?.destroy();
this._controls?.destroy();
this._offLocale?.();
this._state.destroy();
this._destroyPromise = Promise.resolve().then(async () => {
this.stopScene('Stopped');
this.stopScene(msg('Stopped'));
this._loadAbort?.abort();
this._loadGeneration++;
this.engine?.camera.cancelFlight();
clearTimeout(this._storageToastTimer);
this._storageToast?.cancel();
await Promise.allSettled(this._pendingWork || []);
this._clock.destroy();
this._cancelActiveSceneTravel();
@@ -319,50 +341,54 @@ export class SceneDirector {
/** Persist the current project state to localStorage with an updated timestamp. */
_saveProject() {
if (this._storageReadError) {
this._toastStorageError(
'Scene not saved — existing saved project could not be read. Export edits or import a valid file.',
this._toastStorageError(() =>
t(
'Scene not saved — existing saved project could not be read. Export edits or import a valid file.',
),
);
return;
return false;
}
this._project.updatedAt = new Date().toISOString();
try {
const payload = JSON.stringify(this._project);
parseSceneDocument(payload);
localStorage.setItem(STORAGE_KEY, payload);
return true;
} catch (e) {
// Private browsing / block-all-cookies / quota-exceeded throws here. The
// in-memory project stays usable this session, but persistence failed —
// tell the user instead of crashing the caller (M11).
// A validation failure is logged with its technical path and check;
// the toast says it in words (sceneSaveError.js).
const invalid = e instanceof SceneDocumentError;
console.warn(
'[Scenes] Could not persist project (storage unavailable):',
invalid
? '[Scenes] Could not persist project (invalid project data):'
: '[Scenes] Could not persist project (storage unavailable):',
e,
);
this._toastStorageError(
e instanceof SceneDocumentError
? `Scene not saved — ${e.message}`
invalid
? () =>
t('Scene not saved — {reason}', {
reason: sceneSaveFailureReason(e),
})
: undefined,
);
return false;
}
}
/** Surface a "scene not saved" notice via the global toast + scene status line. */
/**
* Surface a "scene not saved" notice via the global toast + scene status
* line. `message` words it, so the status line follows the locale.
*/
_toastStorageError(
message = 'Scene not saved — browser storage unavailable',
message = () => t('Scene not saved — browser storage unavailable'),
) {
this._updateStatus(message);
try {
const toast = document.getElementById('toast');
if (toast) {
toast.textContent = message;
toast.classList.add('visible');
clearTimeout(this._storageToastTimer);
this._storageToastTimer = setTimeout(() => {
toast.classList.remove('visible');
}, 2600);
}
} catch {
/* toast is best-effort */
}
this._storageToast ??= createToast({ durationMs: 2600 });
this._storageToast.show(message());
}
/** Immutable playback snapshots and completed editing actions. */
@@ -376,7 +402,12 @@ export class SceneDirector {
_shotOutcome(type, scene, shot, index = scene.shots.indexOf(shot)) {
if (type === 'shot-loaded')
this._presentation.status = `Loaded: ${scene.title} / ${shot.title}`;
this._setStatus(() =>
t('Loaded: {scene} / {shot}', {
scene: displaySceneTitle(scene),
shot: displayShotTitle(shot.title, shot, scene),
}),
);
this._publish({
type,
sceneId: scene.id,
@@ -387,15 +418,24 @@ export class SceneDirector {
}
/**
* Wire up all scene-panel DOM event listeners and render the initial UI state.
* Exits silently if the scene-select element is missing (headless/test mode).
* Present the Scene panel through SceneControls, which publishes it to the
* store the panel views render; a page without them simply draws nothing.
*/
_initUI() {
this._sharing?.mount();
this._controls = new SceneControls({
subscribe: (listener) => this.subscribe(listener),
read: () => ({
scenes: this._project.scenes,
// The panel shows display titles; shots keep the stored title for
// editing and matching.
scenes: this._project.scenes.map((scene) => ({
...scene,
title: displaySceneTitle(scene),
shots: scene.shots.map((shot) => ({
...shot,
displayTitle: displayShotTitle(shot.title, shot, scene),
})),
})),
selectedSceneId: this._selectedSceneId,
selectedShotId: this._selectedShotId,
running: this._running,
@@ -491,6 +531,7 @@ export class SceneDirector {
const scene = {
id: uid('scene'),
// i18n-ignore: stored English, like normalizeProject; displaySceneTitle translates it.
title: sceneName.trim() || `Scene ${this._project.scenes.length + 1}`,
shots: [],
};
@@ -768,8 +809,10 @@ export class SceneDirector {
(shot, index) => shot.title === requiredShotTitles[index],
));
if (!inventoryMatches) {
this._updateStatus(
`Cannot update ${recipe.title}: shot inventory changed`,
this._updateStatus(() =>
t('Cannot update {scene}: shot inventory changed', {
scene: t(recipe.title),
}),
);
return {
appended: false,
@@ -799,8 +842,10 @@ export class SceneDirector {
(beatId, index) => beatId === requiredSourcePackBeatIds[index],
);
if (!sourcePackMatches) {
this._updateStatus(
`Cannot update ${recipe.title}: evidence beats changed`,
this._updateStatus(() =>
t('Cannot update {scene}: evidence beats changed', {
scene: t(recipe.title),
}),
);
return {
appended: false,
@@ -822,8 +867,10 @@ export class SceneDirector {
shot: resolvePatchedShot(patch),
}));
if (resolvedPatches.some(({ shot }) => !shot)) {
this._updateStatus(
`Cannot update ${recipe.title}: shot bindings are incomplete`,
this._updateStatus(() =>
t('Cannot update {scene}: shot bindings are incomplete', {
scene: t(recipe.title),
}),
);
return {
appended: false,
@@ -895,16 +942,26 @@ export class SceneDirector {
}
this._selectedSceneId = scene.id;
this._selectedShotId = appendedShots[0]?.id || this._selectedShotId;
this._saveProject();
const saved = this._saveProject();
if (render) {
this._renderSceneSelect();
this._renderShotList();
}
if (announce) {
this._updateStatus(
if (announce && saved) {
this._updateStatus(() =>
marker
? `Updated ${patchedShotCount} ${patchedShotCount === 1 ? 'shot' : 'shots'}: ${recipe.title}`
: `Appended ${appendedShots.length} shots: ${recipe.title}`,
? tn(
patchedShotCount,
'Updated {count} shot: {scene}',
'Updated {count} shots: {scene}',
{ scene: t(recipe.title) },
)
: tn(
appendedShots.length,
'Appended {count} shot: {scene}',
'Appended {count} shots: {scene}',
{ scene: t(recipe.title) },
),
);
}
return {
@@ -926,13 +983,14 @@ export class SceneDirector {
const camera = this.styleManager.getCameraState();
if (!camera) {
this._updateStatus('Cannot capture shot: camera not ready');
this._updateStatus(() => t('Cannot capture shot: camera not ready'));
return;
}
const shot = normalizeShot(
{
id: uid('shot'),
// i18n-ignore: stored English; displayShotTitle translates it when shown.
title: `Shot ${scene.shots.length + 1}`,
durationSec: DEFAULT_SHOT_DURATION_SEC,
holdSec: DEFAULT_HOLD_SEC,
@@ -945,9 +1003,16 @@ export class SceneDirector {
scene.shots.push(shot);
this._selectedShotId = shot.id;
this._saveProject();
const saved = this._saveProject();
this._shotOutcome('shot-captured', scene, shot);
this._updateStatus(`Captured: ${scene.title} / ${shot.title}`);
if (saved) {
this._updateStatus(() =>
t('Captured: {scene} / {shot}', {
scene: displaySceneTitle(scene),
shot: displayShotTitle(shot.title, shot, scene),
}),
);
}
}
/**
@@ -960,7 +1025,7 @@ export class SceneDirector {
const shot = scene.shots.find((item) => item.id === this._selectedShotId);
if (!shot) {
this._updateStatus('Select a shot first');
this._updateStatus(() => t('Select a shot first'));
return;
}
@@ -973,9 +1038,16 @@ export class SceneDirector {
shot.visual = this.styleManager.getVisualState();
shot.layers = this._captureLayerStates();
this._saveProject();
const saved = this._saveProject();
this._shotOutcome('shot-updated', scene, shot);
this._updateStatus(`Updated: ${scene.title} / ${shot.title}`);
if (saved) {
this._updateStatus(() =>
t('Updated: {scene} / {shot}', {
scene: displaySceneTitle(scene),
shot: displayShotTitle(shot.title, shot, scene),
}),
);
}
}
/**
@@ -1014,7 +1086,7 @@ export class SceneDirector {
loadShot(sceneId, shotId, options) {
if (this._destroyed)
return Promise.resolve({ started: false, reason: 'destroyed' });
this._sceneSeekGeneration++;
this._bumpSceneSeekGeneration();
this._interactionTransitions = 0;
const previousGeneration = this._loadGeneration;
const work = this._loadShot(sceneId, shotId, options);
@@ -1081,7 +1153,11 @@ export class SceneDirector {
const released = await this._releaseSceneLayers(previousScene, token);
if (!released || token.cancelled) {
if (!token.cancelled)
this._updateStatus(`Could not leave scene: ${previousScene.title}`);
this._updateStatus(() =>
t('Could not leave scene: {scene}', {
scene: displaySceneTitle(previousScene),
}),
);
return;
}
this._loadedSceneId = null;
@@ -1131,7 +1207,12 @@ export class SceneDirector {
seeking: true,
});
if (this._loadAbort === controller) this._loadAbort = null;
this._updateStatus(`Seeked: ${scene.title} / ${shot.title}`);
this._updateStatus(() =>
t('Seeked: {scene} / {shot}', {
scene: displaySceneTitle(scene),
shot: displayShotTitle(shot.title, shot, scene),
}),
);
this._activateInteractions(scene, shot);
return { started: true, shotId };
}
@@ -1450,9 +1531,30 @@ export class SceneDirector {
return new Promise((resolve) => this._runIdleResolvers.add(resolve));
}
/** Apply a new time inside the already-loaded shot without rebuilding its stack. */
_seekLoadedShot(scene, seekState) {
if (this._destroyed) return false;
/**
* Supersede any pending seek. Only a seek's own layer reconcile is aborted:
* a request that is later rejected must not cancel an in-flight LOAD.
*/
_bumpSceneSeekGeneration() {
if (this._seekAbort) {
this._seekAbort.abort();
if (this._loadAbort === this._seekAbort) this._loadAbort = null;
this._seekAbort = null;
}
return ++this._sceneSeekGeneration;
}
/**
* Apply a new time inside the already-loaded shot without rebuilding its stack.
* @returns {Promise<boolean|null>} Null when the shortcut does not apply and
* LOAD must rebuild the shot; otherwise whether the seek settled.
*/
async _seekLoadedShot(
scene,
seekState,
seekGeneration = this._sceneSeekGeneration,
) {
if (this._destroyed) return null;
const shot = seekState?.shot;
if (
!scene ||
@@ -1462,17 +1564,77 @@ export class SceneDirector {
this._loadedSceneId !== scene.id ||
this._selectedShotId !== shot.id
)
return null;
if (this._destroyed || seekGeneration !== this._sceneSeekGeneration)
return false;
if (!this._claimCameraOwnership()) return false;
this._cancelActiveSceneTravel();
this._loadAbort?.abort();
this._loadAbort = null;
this._loadGeneration += 1;
const generation = ++this._loadGeneration;
this._clock.stopShot();
const states = this._layerStatesForShot(scene, shot, {
cameraSettled: seekState.cameraProgress >= 1,
sceneSeek: seekState,
});
// A manual toggle, or a superseded LOAD transition whose rollback is still
// settling, leaves declared layers off the shot's stack. Reconcile only
// those through the cancellable admission path.
const staleStates = Object.fromEntries(
Object.entries(states)
.filter(([id, state]) => {
const wantEnabled = !!state?.enabled;
const lifecycle = this.dataManager.getLayerLifecycleState(id);
return (
lifecycle &&
(lifecycle.enabled !== wantEnabled ||
lifecycle.lifecycleState === 'enabling' ||
lifecycle.lifecycleState === 'disabling' ||
lifecycle.uncertain ||
this.dataManager.isEffectivelyEnabled(id) !== wantEnabled)
);
})
.map(([id, state]) => [id, { enabled: !!state?.enabled }]),
);
if (Object.keys(staleStates).length) {
const previousEnabled = new Map(
Object.keys(staleStates).map((id) => [
id,
this.dataManager.isEffectivelyEnabled(id),
]),
);
const controller = new AbortController();
this._loadAbort = controller;
this._seekAbort = controller;
const layerResult = await this._applyLayerStates(
staleStates,
this._loadToken(generation, controller.signal, seekGeneration),
{ stopOnRefusal: true, exitContextMode: false },
);
if (this._loadAbort === controller) this._loadAbort = null;
if (this._seekAbort === controller) this._seekAbort = null;
const superseded = () =>
this._destroyed ||
this._loadAbort ||
this._running ||
seekGeneration !== this._sceneSeekGeneration;
if (layerResult.cancelled || superseded()) return false;
if (layerResult.refused.length) {
// Only a refusal rolls back. A cancelled reconcile leaves layer state
// to whatever superseded it, as a cancelled LOAD does.
for (const id of [...layerResult.applied].reverse()) {
if (superseded()) break;
await this.dataManager.setEnabled(
id,
previousEnabled.get(id) ?? false,
{ origin: 'scene' },
);
}
return false;
}
}
if (this._destroyed || seekGeneration !== this._sceneSeekGeneration)
return false;
let applied = true;
for (const [layerId, state] of Object.entries(states)) {
if (!state?.enabled || !state.params) continue;
@@ -1484,7 +1646,9 @@ export class SceneDirector {
applied = false;
}
}
if (!applied) return false;
if (!applied) return null;
if (this._destroyed || seekGeneration !== this._sceneSeekGeneration)
return false;
this._setCameraView(
seekState.camera || resolveCameraPose(scene, shot.camera),
);
@@ -1493,15 +1657,20 @@ export class SceneDirector {
running: false,
seeking: true,
});
this._updateStatus(`Seeked: ${scene.title} / ${shot.title}`);
this._updateStatus(() =>
t('Seeked: {scene} / {shot}', {
scene: displaySceneTitle(scene),
shot: displayShotTitle(shot.title, shot, scene),
}),
);
return true;
}
/** Seek the complete authored scene state to an exact clock position. */
seekScene(sceneId, progress) {
if (this._destroyed) return Promise.resolve(false);
this.stopScene('Seeking scene clock');
const generation = ++this._sceneSeekGeneration;
this.stopScene(msg('Seeking scene clock'));
const generation = this._bumpSceneSeekGeneration();
return this._trackWork(this._seekScene(sceneId, progress, generation));
}
@@ -1515,7 +1684,10 @@ export class SceneDirector {
return false;
const seekState = this._sceneSeekState(scene, progress);
if (!seekState) return false;
if (this._seekLoadedShot(scene, seekState)) return true;
const seeked = await this._seekLoadedShot(scene, seekState, generation);
if (this._destroyed || generation !== this._sceneSeekGeneration)
return false;
if (seeked !== null) return seeked;
const result = await this._loadShot(scene.id, seekState.shot.id, {
sceneSeek: seekState,
});
@@ -1535,15 +1707,17 @@ export class SceneDirector {
* @param {AbortSignal} [signal] - Abort signal for this LOAD's manager calls
* @returns {{ cancelled: boolean, signal: AbortSignal|undefined }}
*/
_loadToken(generation, signal = undefined) {
_loadToken(generation, signal = undefined, seekGeneration = null) {
const director = this;
return {
signal,
get cancelled() {
return (
director._destroyed ||
signal?.aborted ||
director._loadGeneration !== generation
Boolean(signal?.aborted) ||
director._loadGeneration !== generation ||
(seekGeneration !== null &&
director._sceneSeekGeneration !== seekGeneration)
);
},
};
@@ -1570,7 +1744,7 @@ export class SceneDirector {
this._claimingCamera = false;
}
if (claimed === false) {
this._updateStatus('Camera unavailable — exit cockpit first');
this._updateStatus(() => t('Camera unavailable — exit cockpit first'));
return false;
}
return true;
@@ -1682,7 +1856,7 @@ export class SceneDirector {
startScene(sceneId, options) {
if (this._destroyed)
return Promise.resolve({ started: false, reason: 'destroyed' });
this._sceneSeekGeneration++;
this._bumpSceneSeekGeneration();
return this._trackWork(this._startScene(sceneId, options));
}
@@ -1692,20 +1866,20 @@ export class SceneDirector {
) {
if (this._running) return { started: false, reason: 'already-running' };
let queue = this._buildPlaybackQueue(
sceneId || this._selectedSceneId || this._project.scenes[0]?.id,
{ single },
);
const startSceneId =
sceneId || this._selectedSceneId || this._project.scenes[0]?.id;
let queue = this._buildPlaybackQueue(startSceneId, { single });
if (afterShotId !== null) {
const index = queue.findIndex(
({ scene, shot }) => scene.id === sceneId && shot.id === afterShotId,
({ scene, shot }) =>
scene.id === startSceneId && shot.id === afterShotId,
);
if (index < 0) return { started: false, reason: 'shot-not-found' };
queue = queue.slice(index + 1);
if (!queue.length) return { started: false, reason: 'scene-complete' };
}
if (!queue.length) {
this._updateStatus('No shots to run');
this._updateStatus(() => t('No shots to run'));
return { started: false, reason: 'no-shots' };
}
@@ -1767,10 +1941,11 @@ export class SceneDirector {
// Initialize telemetry accumulator for this run
this._activeRun = {
recipeId: `project-${PROJECT_VERSION}`,
// i18n-ignore: run telemetry record, downloaded as JSON
title: 'Editable Scene Run',
startedAt: new Date().toISOString(),
estimatedDurationSec,
scenesRun: queue.length,
scenesRun: new Set(queue.map(({ scene }) => scene.id)).size,
events: [],
};
@@ -1778,6 +1953,7 @@ export class SceneDirector {
this._logEvent('scene_run_start', { count: queue.length });
this._setPlaybackKeyboardEnabled(true);
let runResult = { started: true, shots: queue.length };
try {
await playSceneQueue(queue, {
token,
@@ -1788,13 +1964,19 @@ export class SceneDirector {
releaseOnFinish: preview,
});
} catch (error) {
this._updateStatus(`Error: ${error.message || 'run failed'}`);
this._updateStatus(() =>
t('Error: {message}', {
message: error.message || 'run failed',
}),
);
this._logEvent('scene_run_error', {
message: error.message || 'unknown error',
});
runResult = { started: false, reason: 'run-failed' };
} finally {
this._finishRun();
}
return runResult;
}
/**
@@ -1832,13 +2014,15 @@ export class SceneDirector {
* enabled while the post-await check skips its params. The manager rolls an
* aborted enable back through the module's own disable().
*
* @param {string} [reason='Stopped'] - Human-readable cancellation reason
* @param {string} [reason='Stopped'] - Cancellation reason, in English: it
* is logged as data and translated only for the status line (callers mark
* theirs with msg()).
*/
stopScene(reason = 'Stopped') {
stopScene(reason = msg('Stopped')) {
this._setSceneMediaPlayback();
this._interactions?.clear();
this._dataPacks?.clear();
this._sceneSeekGeneration++;
this._bumpSceneSeekGeneration();
this._loadAbort?.abort();
this._loadAbort = null;
this._loadGeneration++;
@@ -1849,7 +2033,7 @@ export class SceneDirector {
if (!this._running || !this._runToken) return;
this._runToken.cancelled = true;
this._runAbort?.abort();
this._updateStatus(reason);
this._updateStatus(() => t(reason));
this._logEvent('scene_stopped', { reason });
}
@@ -1905,8 +2089,8 @@ export class SceneDirector {
}
if (action.type === 'shot') {
if (this._interactionTransitions >= 64) {
this._updateStatus(
'Scene transition limit reached — load a shot to reset',
this._updateStatus(() =>
t('Scene transition limit reached — load a shot to reset'),
);
return false;
}
@@ -1949,7 +2133,9 @@ export class SceneDirector {
try {
payload = stringifySceneDocument(this._project);
} catch (error) {
this._updateStatus(`Export failed: ${error.message}`);
this._updateStatus(() =>
t('Export failed: {error}', { error: error.message }),
);
return;
}
// Trigger a browser download via a temporary anchor element
@@ -1962,7 +2148,7 @@ export class SceneDirector {
link.click();
link.remove();
URL.revokeObjectURL(url);
this._presentation.status = 'Project exported';
this._setStatus(() => t('Project exported'));
this._publish({ type: 'project-exported', project: this._project });
}
@@ -1992,7 +2178,7 @@ export class SceneDirector {
)
return false;
// Validate before touching playback, selection or the saved project.
this.stopScene('Importing project');
this.stopScene(msg('Importing project'));
await Promise.allSettled([...(this._pendingWork || [])]);
if (this._destroyed || generation !== this._importGeneration) return;
if (
@@ -2020,9 +2206,10 @@ export class SceneDirector {
this._selectedShotId =
selection?.shotId || project.scenes[0]?.shots[0]?.id || null;
this._loadedSceneId = null;
this._saveProject();
const saved = this._saveProject();
this._publish({ type: 'project-imported', project });
this._updateStatus(`Imported ${file.name}`);
if (saved)
this._updateStatus(() => t('Imported {file}', { file: file.name }));
return true;
} catch (error) {
if (
@@ -2031,10 +2218,10 @@ export class SceneDirector {
generation !== this._importGeneration
)
return false;
this._updateStatus(
this._updateStatus(() =>
error instanceof SceneDocumentError
? `Import failed: ${error.message}`
: 'Import failed (could not read JSON file)',
? t('Import failed: {error}', { error: error.message })
: t('Import failed (could not read JSON file)'),
);
}
}
@@ -2084,7 +2271,11 @@ export class SceneDirector {
* the transition in flight.
* @returns {Promise<{ applied: string[], refused: string[], cancelled: boolean }>}
*/
async _applyLayerStates(targetStates, token = null) {
async _applyLayerStates(
targetStates,
token = null,
{ stopOnRefusal = false, exitContextMode = true } = {},
) {
const applied = [];
const refused = [];
const abort = () => ({ applied, refused, cancelled: true });
@@ -2094,8 +2285,10 @@ export class SceneDirector {
// the operator's pre-mode state, which is exactly where a stopped scene
// should come to rest. Tearing that transaction in half would strand
// Context, so it completes and cancellation is honoured immediately after.
await this._exitIsolatingContextMode();
if (token?.cancelled) return abort();
if (exitContextMode) {
await this._exitIsolatingContextMode();
if (token?.cancelled) return abort();
}
const signal = token?.signal;
const registered = new Set(
@@ -2125,6 +2318,7 @@ export class SceneDirector {
console.warn(
`[Scenes] Layer refused: ${id} → ${enabled ? 'on' : 'off'}`,
);
if (stopOnRefusal) break;
continue;
}
if (params && typeof this.dataManager.restoreLayerState !== 'function') {
@@ -2134,7 +2328,9 @@ export class SceneDirector {
}
if (refused.length) {
this._updateStatus(`Layers refused: ${refused.join(', ')}`);
this._updateStatus(() =>
t('Layers refused: {layers}', { layers: refused.join(', ') }),
);
this._logEvent('shot_layers_refused', { layerIds: [...refused] });
}
return { applied, refused, cancelled: false };
@@ -2224,8 +2420,8 @@ export class SceneDirector {
`[Scenes] Could not exit ${mode}:`,
result.error || 'unknown reason',
);
this._updateStatus(
`Could not exit ${mode} — scene layers may be refused`,
this._updateStatus(() =>
t('Could not exit {mode} — scene layers may be refused', { mode }),
);
this._logEvent('context_mode_exit_failed', {
mode,
@@ -2251,7 +2447,7 @@ export class SceneDirector {
token,
);
if (!completed && !token.cancelled && !this._destroyed)
this.stopScene('Camera move interrupted');
this.stopScene(msg('Camera move interrupted'));
}
/**
@@ -2340,7 +2536,7 @@ export class SceneDirector {
const pending = readers.filter(({ read }) => read()?.pending === true);
if (!pending.length) return;
if (pending.some(({ maxWaitMs }) => Date.now() - began >= maxWaitMs)) {
this.stopScene('Scene media timed out');
this.stopScene(msg('Scene media timed out'));
throw new Error(
'Scene media did not finish within its bounded playback window',
);
@@ -2457,10 +2653,20 @@ export class SceneDirector {
* @param {string} text
*/
_updateStatus(text) {
this._presentation.status = text;
this._setStatus(text);
this._publish({ type: 'status-changed' });
}
/**
* Set the status line without publishing. A function is called again when
* the locale changes, so its text follows the language.
* @param {string|(() => string)} text
*/
_setStatus(text) {
this._statusText = text;
this._presentation.status = typeof text === 'function' ? text() : text;
}
/**
* Set the runtime label (scene/shot name) and toggle its active class.
* @param {string} text - Empty string hides the label
+453 -9
View File
@@ -1,4 +1,6 @@
import { readShellSource } from '../testSupport/readShellSource.mjs';
import { useStatusStore } from '../ui/stores/status.js';
import { applicationPinia } from '../ui/vueRuntime.js';
// Director-level pins for scene playback.
//
// scenePolicy.test.mjs pins the pure decisions; these pin the wiring, which is
@@ -12,9 +14,9 @@ import { readShellSource } from '../testSupport/readShellSource.mjs';
// cancellable — an AbortSignal for the data manager, a liveness predicate for
// the visual commit. Several of these assert exactly that plumbing.
import assert from 'node:assert/strict';
import fs from 'node:fs';
import test from 'node:test';
import { LayerLifecycle } from '../data/lifecycle.js';
import { SceneDirector } from './director.js';
import { SCENE_TRACKING_PARAM_KEYS } from './scenePolicy.js';
import { SCENE_RECIPES, getSceneAppendRecipeById } from './recipes.js';
@@ -176,6 +178,348 @@ test('scene clock seek resolves the exact shot phase and camera in both directio
}
});
test('same-shot seeking restores declared layer visibility after manual changes', async () => {
const { director, dataManager, styleManager, restore } = makeDirector();
try {
const shot = director._project.scenes[0].shots[0];
shot.layers = { flights: { enabled: true }, traffic: { enabled: false } };
await director.loadShot('scene-1', 'shot-a', { flyDuration: 0 });
await dataManager.setEnabled('flights', false);
await dataManager.setEnabled('traffic', true);
await dataManager.setEnabled('satellites', true);
dataManager.setEnabledCalls.length = 0;
const visualCalls = styleManager.visualCalls.length;
assert.equal(await director.seekScene('scene-1', 0.25), true);
assert.equal(styleManager.visualCalls.length, visualCalls, 'do not rebuild the shot');
assert.equal(director.getPlaybackTimingState().snapshot.sceneProgress, 0.25);
const enabled = new Map(dataManager.getAll().map(({ id, enabled }) => [id, enabled]));
assert.equal(enabled.get('flights'), true, 'restore the shot\'s enabled layer');
assert.equal(enabled.get('traffic'), false, 'restore the shot\'s disabled layer');
assert.equal(enabled.get('satellites'), true, 'preserve undeclared operator layers');
assert.ok(dataManager.setEnabledCalls.every(({ id }) => id !== 'satellites'));
} finally {
await director.destroy();
restore();
}
});
test('same-shot seeking reports refusal when a manually disabled layer cannot be restored', async () => {
let refuse = false;
const { director, dataManager, styleManager, restore } = makeDirector({
data: { refuse: () => refuse },
});
try {
await director.loadShot('scene-1', 'shot-a', { flyDuration: 0 });
assert.equal(await director.seekScene('scene-1', 0.1), true);
await dataManager.setEnabled('flights', false);
refuse = true;
const visualCalls = styleManager.visualCalls.length;
assert.equal(await director.seekScene('scene-1', 0.25), false);
assert.equal(dataManager.getAll().find(({ id }) => id === 'flights').enabled, false);
const timing = director.getPlaybackTimingState();
assert.equal(timing.activeTimers, 0);
assert.ok(Math.abs(timing.snapshot.sceneProgress - 0.1) < 1e-9, 'keep the last settled seek position');
assert.equal(styleManager.visualCalls.length, visualCalls, 'do not rebuild the shot');
} finally {
await director.destroy();
restore();
}
});
test('same-shot seeking restores visibility a manual toggle is still changing', async () => {
const { director, dataManager, restore } = makeDirector();
try {
await director.loadShot('scene-1', 'shot-a', { flyDuration: 0 });
const disabling = dataManager.setEnabled('flights', false);
assert.equal(await director.seekScene('scene-1', 0.25), true);
await disabling;
await settle();
assert.equal(dataManager.getAll().find(({ id }) => id === 'flights').enabled, true);
} finally {
await director.destroy();
restore();
}
});
test('same-shot seeking restores a layer whose superseded LOAD transition rolls back', async () => {
const { director, dataManager, styleManager, viewer, restore } = makeDirector();
const lifecycle = new LayerLifecycle(viewer);
for (const id of ['flights', 'traffic', 'satellites']) {
lifecycle.register({
id,
name: id,
init() {},
enable() {},
disable() {},
update() {},
});
}
const realDirector = new SceneDirector(viewer, styleManager, lifecycle, { engine: engineFor(viewer) });
try {
await director.loadShot('scene-1', 'shot-a', { flyDuration: 0 });
await dataManager.setEnabled('flights', false);
dataManager.setEnabledCalls.length = 0;
const reload = director.loadShot('scene-1', 'shot-a', { flyDuration: 0 });
for (let i = 0; i < 20 && !dataManager.setEnabledCalls.length; i++) await Promise.resolve();
assert.equal(dataManager.getLayerLifecycleState('flights').lifecycleState, 'enabling');
assert.equal(await director.seekScene('scene-1', 0.25), true);
await reload;
await settle();
assert.equal(dataManager.getAll().find(({ id }) => id === 'flights').enabled, true);
await realDirector.loadShot('scene-1', 'shot-a', { flyDuration: 0 });
await lifecycle.setEnabled('flights', false);
const queuedReload = realDirector.loadShot('scene-1', 'shot-a', { flyDuration: 0 });
for (let i = 0; i < 20 && !lifecycle.isEffectivelyEnabled('flights'); i++) {
await Promise.resolve();
}
assert.deepEqual(lifecycle.getLayerLifecycleState('flights'), {
enabled: false,
lifecycleState: 'disabled',
uncertain: false,
});
assert.equal(await realDirector.seekScene('scene-1', 0.25), true);
await queuedReload;
await settle();
assert.equal(lifecycle.isEnabled('flights'), true);
lifecycle.layers.get('flights').lifecycleUncertain = true;
assert.equal(await realDirector.seekScene('scene-1', 0.3), true);
assert.equal(lifecycle.getLayerLifecycleState('flights').uncertain, false);
let navClaims = 0;
styleManager.runImmediateNavigation = () => {
navClaims += 1;
return false;
};
assert.equal(await realDirector.seekScene('scene-1', 0.4), false);
assert.equal(navClaims, 1, 'camera refusal fails the seek without falling back to LOAD');
} finally {
await realDirector.destroy();
await director.destroy();
restore();
}
});
test('same-shot seeking rolls back earlier layers and preserves Context, clock and camera when a later layer is refused', async () => {
let refuse = () => false;
const { director, dataManager, styleManager, viewer, restore } = makeDirector({
data: { refuse: (id, on) => refuse(id, on) },
});
try {
const shot = director._project.scenes[0].shots[0];
shot.layers = {
flights: { enabled: true },
traffic: { enabled: true },
satellites: { enabled: true },
};
await director.loadShot('scene-1', 'shot-a', { flyDuration: 0 });
assert.equal(await director.seekScene('scene-1', 0.1), true);
await dataManager.setEnabled('flights', false);
await dataManager.setEnabled('traffic', false);
await dataManager.setEnabled('satellites', false);
styleManager.contextMode = 'space-missions';
styleManager.contextExits.length = 0;
refuse = (id) => id === 'traffic';
dataManager.setEnabledCalls.length = 0;
const viewsBefore = viewer.views.length;
const visualCalls = styleManager.visualCalls.length;
assert.equal(await director.seekScene('scene-1', 0.25), false);
assert.equal(
dataManager.setEnabledCalls.some(({ id }) => id === 'satellites'),
false,
'stop the plan before later ids are written',
);
const enabled = new Map(dataManager.getAll().map(({ id, enabled }) => [id, enabled]));
assert.equal(enabled.get('flights'), false, 'first stale layer stays disabled');
assert.equal(enabled.get('traffic'), false, 'refused second layer stays disabled');
assert.equal(enabled.get('satellites'), false, 'later stale layer is never written');
assert.equal(styleManager.contextMode, 'space-missions');
assert.deepEqual(styleManager.contextExits, []);
assert.equal(viewer.views.length, viewsBefore, 'camera stays at the pre-seek pose');
assert.equal(styleManager.visualCalls.length, visualCalls, 'do not rebuild the shot');
assert.ok(
Math.abs(director.getPlaybackTimingState().snapshot.sceneProgress - 0.1) < 1e-9,
'clock stays at the last settled seek position',
);
} finally {
await director.destroy();
restore();
}
});
test('same-shot seeking aborts in-flight admission when superseded by an early-return load or start', async () => {
const { styleManager, viewer, restore } = makeDirector();
let holdEnable = false;
let releaseEnable;
const enableGate = new Promise((resolve) => {
releaseEnable = resolve;
});
const lifecycle = new LayerLifecycle(viewer);
lifecycle.register({
id: 'flights',
name: 'flights',
init() {},
async enable() {
if (holdEnable) await enableGate;
},
disable() {},
update() {},
});
const director = new SceneDirector(viewer, styleManager, lifecycle, { engine: engineFor(viewer) });
try {
await director.loadShot('scene-1', 'shot-a', { flyDuration: 0 });
assert.equal(await director.seekScene('scene-1', 0.1), true);
await lifecycle.setEnabled('flights', false);
holdEnable = true;
const viewsBefore = viewer.views.length;
const seek = director.seekScene('scene-1', 0.25);
for (
let i = 0;
i < 20 && lifecycle.getLayerLifecycleState('flights').lifecycleState !== 'enabling';
i++
) {
await Promise.resolve();
}
assert.equal(lifecycle.getLayerLifecycleState('flights').lifecycleState, 'enabling');
const admissionSignal = director._loadAbort?.signal;
assert.ok(admissionSignal, 'same-shot seek installs an admission controller');
const missingLoad = director.loadShot('missing', 'nope');
assert.equal(
admissionSignal.aborted,
true,
'missing load aborts the admission controller before returning',
);
assert.equal((await missingLoad).reason, 'shot-not-found');
assert.equal(viewer.views.length, viewsBefore, 'shortcut has not committed before abort');
releaseEnable();
assert.equal(await seek, false);
await settle();
assert.equal(lifecycle.isEnabled('flights'), false, 'layer is not restored');
assert.equal(viewer.views.length, viewsBefore, 'setView is not called');
assert.ok(
Math.abs(director.getPlaybackTimingState().snapshot.sceneProgress - 0.1) < 1e-9,
'sceneProgress stays at the last settled value',
);
let loadFallbackCalls = 0;
const origLoadShot = director._loadShot.bind(director);
director._loadShot = (...args) => {
loadFallbackCalls += 1;
return origLoadShot(...args);
};
const origSeekLoadedShot = director._seekLoadedShot.bind(director);
director._seekLoadedShot = async () => {
await director.startScene('missing');
return null;
};
assert.equal(await director.seekScene('scene-1', 0.25), false);
assert.equal(loadFallbackCalls, 0, 'stale seek returning null must not start _loadShot');
director._seekLoadedShot = origSeekLoadedShot;
} finally {
releaseEnable?.();
await director.destroy();
restore();
}
});
test('a rejected loadShot does not cancel an in-flight LOAD', async () => {
const { styleManager, viewer, restore } = makeDirector();
let holdEnable = true;
let releaseEnable;
const enableGate = new Promise((resolve) => {
releaseEnable = resolve;
});
const lifecycle = new LayerLifecycle(viewer);
lifecycle.register({
id: 'flights',
name: 'flights',
init() {},
async enable() {
if (holdEnable) await enableGate;
},
disable() {},
update() {},
});
const director = new SceneDirector(viewer, styleManager, lifecycle, { engine: engineFor(viewer) });
try {
const load = director.loadShot('scene-1', 'shot-a', { flyDuration: 0 });
for (
let i = 0;
i < 20 && lifecycle.getLayerLifecycleState('flights').lifecycleState !== 'enabling';
i++
) {
await Promise.resolve();
}
assert.equal(lifecycle.getLayerLifecycleState('flights').lifecycleState, 'enabling');
assert.equal((await director.loadShot('missing', 'nope')).reason, 'shot-not-found');
holdEnable = false;
releaseEnable();
assert.equal((await load)?.started, true, 'the valid LOAD still lands');
assert.equal(lifecycle.isEnabled('flights'), true);
} finally {
releaseEnable?.();
await director.destroy();
restore();
}
});
test('refused same-shot seek rollback keeps a manual toggle still in flight', async () => {
let refuse = () => false;
const { director, dataManager, restore } = makeDirector({
data: { refuse: (id, on) => refuse(id, on) },
});
try {
const shot = director._project.scenes[0].shots[0];
shot.layers = { flights: { enabled: true }, traffic: { enabled: true } };
await director.loadShot('scene-1', 'shot-a', { flyDuration: 0 });
assert.equal(await director.seekScene('scene-1', 0.1), true);
await dataManager.setEnabled('flights', false);
await dataManager.setEnabled('traffic', false);
refuse = (id) => id === 'traffic';
const manualEnable = dataManager.setEnabled('flights', true);
assert.equal(await director.seekScene('scene-1', 0.25), false);
await manualEnable;
await settle();
assert.equal(
dataManager.getAll().find(({ id }) => id === 'flights').enabled,
true,
'rollback restores the operator\'s intended state, not the stale committed one',
);
} finally {
await director.destroy();
restore();
}
});
test('same-shot seeking keeps the shortcut when declared visibility is unchanged', async () => {
const { director, dataManager, styleManager, restore } = makeDirector();
try {
await director.loadShot('scene-1', 'shot-a', { flyDuration: 0 });
await dataManager.setEnabled('satellites', true);
dataManager.setEnabledCalls.length = 0;
const visualCalls = styleManager.visualCalls.length;
assert.equal(await director.seekScene('scene-1', 0.25), true);
assert.deepEqual(dataManager.setEnabledCalls, []);
assert.equal(styleManager.visualCalls.length, visualCalls);
assert.equal(director.getPlaybackTimingState().snapshot.sceneProgress, 0.25);
} finally {
await director.destroy();
restore();
}
});
test('scene clock subscribers receive authoritative forward playback snapshots', () => {
const { director, restore } = makeDirector();
const snapshots = [];
@@ -371,6 +715,10 @@ test('a legacy three-shot Nepal browser project bootstraps to the current 25-sho
assert.deepEqual(scene.shots.slice(0, 3).map(({ camera }) => camera), originalCameras);
assert.equal(scene.appliedShotPacks[0].id, 'bhote-koshi-nepal-evidence-pack');
assert.equal(scene.appliedShotPacks[0].version, 18);
// displayShotTitle trusts these bindings to localize the bootstrap shots.
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);
} finally {
@@ -602,8 +950,12 @@ const PROJECT_FIXTURE = {
}],
};
/** Stub the browser globals the director touches, headlessly. */
function installSceneRuntime(project = PROJECT_FIXTURE) {
/**
* Stub the browser globals the director touches, headlessly. `storage` replaces
* the seeded entries (key -> raw string); setting `localStorage.full` makes
* every write throw a quota error.
*/
function installSceneRuntime(project = PROJECT_FIXTURE, { storage } = {}) {
const originalDocument = globalThis.document;
const originalLocalStorage = globalThis.localStorage;
const noopClassList = { add() {}, remove() {}, toggle() {}, contains: () => false };
@@ -615,10 +967,17 @@ function installSceneRuntime(project = PROJECT_FIXTURE) {
removeEventListener() {},
body: { classList: noopClassList, appendChild() {} },
};
const stored = new Map([['godsEyeView.sceneProject.v2', JSON.stringify(project)]]);
const stored = new Map(storage
? Object.entries(storage)
: [['godsEyeView.sceneProject.v2', JSON.stringify(project)]]);
globalThis.localStorage = {
stored,
full: false,
getItem: (key) => stored.get(key) ?? null,
setItem: (key, value) => stored.set(key, value),
setItem(key, value) {
if (this.full) throw new DOMException('quota exceeded', 'QuotaExceededError');
stored.set(key, value);
},
removeItem: (key) => stored.delete(key),
};
@@ -638,6 +997,7 @@ function installSceneRuntime(project = PROJECT_FIXTURE) {
*/
function fakeDataManager({ registered = REGISTERED, refuse = () => false } = {}) {
const enabled = new Map();
const pending = new Map();
const setEnabledCalls = [];
const setParamsCalls = [];
const committed = [];
@@ -650,12 +1010,25 @@ function fakeDataManager({ registered = REGISTERED, refuse = () => false } = {})
setParamsCalls,
committed,
getAll: () => registered.map((id) => ({ id, enabled: !!enabled.get(id) })),
getLayerLifecycleState: (id) => {
if (!registered.includes(id)) return null;
const on = !!enabled.get(id);
const target = pending.get(id);
return {
enabled: on,
lifecycleState:
target === undefined ? (on ? 'enabled' : 'disabled') : target ? 'enabling' : 'disabling',
};
},
isEffectivelyEnabled: (id) => pending.get(id) ?? !!enabled.get(id),
getLayerParams: () => null,
async setEnabled(id, shouldEnable, { signal } = {}) {
setEnabledCalls.push({ id, enabled: shouldEnable, signal });
if (refuse(id, shouldEnable)) return false;
// Yield once so a stop landing during the transition is observable.
pending.set(id, shouldEnable);
await Promise.resolve();
if (pending.get(id) === shouldEnable) pending.delete(id);
if (signal?.aborted) return false;
enabled.set(id, shouldEnable);
committed.push({ id, enabled: shouldEnable });
@@ -709,15 +1082,20 @@ function engineFor(viewer) {
/** Cesium viewer double whose flights complete on the next microtask turn. */
function fakeViewer() {
const flights = [];
const views = [];
let cancelled = 0;
return {
flights,
views,
get cancelledFlights() { return cancelled; },
camera: {
flyTo(options) {
flights.push(options);
Promise.resolve().then(() => options.complete?.());
},
setView(options) {
views.push(options);
},
cancelFlight() { cancelled++; },
},
};
@@ -730,7 +1108,8 @@ async function settle(turns = 8) {
/** Build a director over doubles, with the fixture project loaded. */
function makeDirector(options = {}) {
const restore = installSceneRuntime(options.project);
const restore = installSceneRuntime(options.project, { storage: options.storage });
const storage = globalThis.localStorage;
const viewer = fakeViewer();
const styleManager = fakeStyleManager(options.style);
const dataManager = fakeDataManager(options.data);
@@ -741,7 +1120,7 @@ function makeDirector(options = {}) {
// Telemetry is only accumulated during a run; observable-failure assertions
// need the accumulator without driving a whole run.
director._activeRun = { events: [] };
return { director, viewer, styleManager, dataManager, restore };
return { director, viewer, styleManager, dataManager, storage, restore };
}
test('only Play Shot or a scene run grants transient media authority; LOAD, Stop and replacement revoke it', async () => {
@@ -1266,7 +1645,7 @@ test('applyVisualState gates the map-stack switch on both sides of its await', (
// switch would otherwise stand on the globe.
const source = readShellSource();
const method = source.match(/\n {2}async applyVisualState\([\s\S]*?\n {2}\}\n/);
assert.ok(method, 'applyVisualState is missing from ui.js');
assert.ok(method, 'applyVisualState is missing from the UI shell source');
assert.match(method[0], /async applyVisualState\(state = \{\}, \{ isCurrent = null \} = \{\}\)/);
const mapStackBlock = method[0].match(/if \(state\.mapStack\) \{[\s\S]*?\n {4}\}/);
@@ -1564,7 +1943,7 @@ test('invalid authored edits cannot persist an unreadable project over a good sa
try {
const before = localStorage.getItem('godsEyeView.sceneProject.v2');
let notice;
director._toastStorageError = (message) => { notice = message; };
director._toastStorageError = (message) => { notice = message(); };
director._project.scenes[0].shots[0].camera.lat = 91;
director._saveProject();
assert.equal(localStorage.getItem('godsEyeView.sceneProject.v2'), before);
@@ -1621,3 +2000,68 @@ test('scene placement, flights and stop run on a globe engine without a viewer',
restore();
}
});
test('an unreadable saved project does not overwrite its recovery checkpoint (#971)', async () => {
const unreadable = '{"version":99,"scenes":[]}';
const warn = console.warn;
console.warn = () => {};
const { director, storage, restore } = makeDirector({ storage: {
'godsEyeView.sceneProject.v2': unreadable,
'godsEyeView.sceneProject.checkpoint.v1': 'EARLIER-CHECKPOINT',
} });
try {
assert.equal(storage.stored.get('godsEyeView.sceneProject.v2'), unreadable);
assert.equal(storage.stored.get('godsEyeView.sceneProject.checkpoint.v1'), 'EARLIER-CHECKPOINT');
} finally { console.warn = warn; await director.destroy(); restore(); }
});
test('a capture, update or import that cannot be saved keeps the "Scene not saved" status (#971)', async () => {
const warn = console.warn;
console.warn = () => {};
const { director, storage, restore } = makeDirector();
let status = '';
director.subscribe(({ state }) => { status = state.status; });
try {
storage.full = true;
director._selectedSceneId = 'scene-1';
director._selectedShotId = 'shot-a';
director.captureShot();
assert.match(status, /^Scene not saved/, 'failed capture keeps the save failure');
director.updateSelectedShot();
assert.match(status, /^Scene not saved/, 'failed update keeps the save failure');
assert.equal(await director.importProjectFile(
{ name: 'fixture.json' },
{ prepared: { project: structuredClone(PROJECT_FIXTURE), assets: [] } },
), true);
assert.match(status, /^Scene not saved/, 'failed import keeps the save failure');
const toast = useStatusStore(applicationPinia()).toast;
assert.equal(toast.visible, true);
assert.match(toast.text, /^Scene not saved/, 'the page toast says so too');
} finally { console.warn = warn; await director.destroy(); restore(); }
});
test('startScene resolves its result, resumes after a shot without a scene id, and counts distinct scenes (#971)', async () => {
const { director, restore } = makeDirector();
try {
const options = { single: true, preview: false };
assert.deepEqual(await director.startScene('scene-1', options), { started: true, shots: 2 });
assert.equal(director._lastRun.scenesRun, 1, 'one scene with two shots is one scene run');
assert.deepEqual(
await director.startScene(undefined, { ...options, afterShotId: 'shot-a' }),
{ started: true, shots: 1 },
);
} finally { await director.destroy(); restore(); }
});
test('a caught run failure resolves as run-failed, not success (#971)', async () => {
const { director, styleManager, restore } = makeDirector();
const warn = console.warn;
console.warn = () => {};
styleManager.applyVisualState = async () => { throw new Error('visual failed'); };
try {
assert.deepEqual(
await director.startScene('scene-1', { single: true, preview: false }),
{ started: false, reason: 'run-failed' },
);
} finally { console.warn = warn; await director.destroy(); restore(); }
});
@@ -0,0 +1,43 @@
// Director storage-failure notices and stop reasons must be marked for
// translation and present in every shipped catalog, so es/ru users do not
// get English toasts or Scene status lines. The stop reason itself stays
// English data (it is logged); only the status line translates it.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
extractMessages,
readCatalog,
shippedLocales,
} from '../../scripts/i18n.mjs';
const NOTICES = [
'Scene not saved — browser storage unavailable',
'Scene not saved — existing saved project could not be read. Export edits or import a valid file.',
'Saved project could not be read; storage preserved. Import a valid file to resume saving.',
'Scene not saved — {reason}',
'Stopped',
'Stopped (Esc)',
'Stopped by voice',
'Camera ownership changed',
'Scene layer turned off',
'Seeking scene clock',
'Importing project',
'Camera move interrupted',
'Scene media timed out',
];
const messages = extractMessages();
for (const text of NOTICES) {
test(`Director notice is marked with t()/msg(): ${text}`, () => {
assert.ok(messages.has(text), `not marked for translation: ${text}`);
});
for (const locale of shippedLocales()) {
test(`${locale} catalog translates: ${text}`, () => {
const value = readCatalog(locale)[text];
assert.ok(value, `missing in ${locale}.json`);
assert.notEqual(value, text);
});
}
}
+85 -94
View File
@@ -1,67 +1,79 @@
import * as Cesium from 'cesium';
import { nextTick } from 'vue';
import { isPointerFree } from '../data/inputOwnership.js';
import { createInteractionSession } from '../director/interactions/session.js';
import { t } from '../i18n/index.js';
import { useSceneInteractionsStore } from '../ui/stores/sceneInteractions.js';
import { applicationPinia } from '../ui/vueRuntime.js';
/**
* Own the active shot's pick handler, accessible actions and plain-text
* feedback. The Scene actions panel is presented to the scene interactions
* store, which its view renders inside the viewer's container.
*/
// Keys each activation's panel, so a new one never reuses an old one's DOM.
let activations = 0;
/** Own the active shot's pick handler, accessible actions and plain-text feedback. */
export function createSceneInteractions(
viewer,
{ execute, available = () => true },
{
execute,
available = () => true,
store = useSceneInteractionsStore(applicationPinia()),
},
) {
let panel,
status,
card,
let panel = null,
handler,
items = [],
targets = new Map();
const buttons = new Map();
// Only the owner whose panel the store shows may change or remove it.
const shown = () => panel && store.panel?.owner === panel.owner;
const update = (patch) => {
if (!shown()) return;
panel = { ...panel, ...patch };
store.publish(panel);
};
const session = createInteractionSession({
execute: (item, signal) => {
if (!isPointerFree() || !available()) return false;
card.replaceChildren();
if (item.action.type === 'card') {
const text = document.createElement('p');
text.textContent = item.action.text;
card.append(text);
if (item.action.url) {
const link = document.createElement('a');
link.textContent = 'Source';
link.style.color = '#6eeaff';
link.href = item.action.url;
link.target = '_blank';
link.rel = 'noopener noreferrer';
card.append(link);
}
update({
card: { text: item.action.text, url: item.action.url || null },
});
return true;
}
update({ card: null });
return execute(item.action, signal);
},
changed(state) {
for (const [id, button] of buttons) {
button.disabled = state.busy;
button.setAttribute('aria-pressed', String(state.selected === id));
button.style.outline = state.selected === id ? '2px solid #6eeaff' : '';
}
update({
busy: state.busy,
selected: state.selected,
outlined: state.selected ? [state.selected] : [],
});
},
});
function clear() {
session.clear();
handler?.destroy();
handler = null;
panel?.remove();
if (shown()) {
store.connect(null);
store.publish(null);
}
panel = null;
status = null;
card = null;
buttons.clear();
items = [];
targets.clear();
}
async function dispatch(id) {
const current = panel;
const ok = await session.dispatch(id);
if (current && current === panel && status)
status.textContent = ok
? 'Action complete'
: 'Action unavailable or cancelled';
if (current && panel?.owner === current.owner)
update({
status: ok
? t('Action complete')
: t('Action unavailable or cancelled'),
});
return ok;
}
return {
@@ -85,64 +97,35 @@ export function createSceneInteractions(
targets.clear();
throw new Error('Interaction feature is missing from the loaded pack');
}
panel = document.createElement('section');
panel.dataset.directorInteractions = '';
panel.setAttribute('aria-label', 'Scene actions');
Object.assign(panel.style, {
position: 'absolute',
left: '12px',
bottom: '80px',
zIndex: '31',
maxWidth: '300px',
maxHeight: '40vh',
overflowY: 'auto',
background: '#08141eed',
color: '#e3faff',
border: '1px solid #2491a8',
padding: '10px',
font: '13px sans-serif',
// Each activation owns its panel; a click on an older one is ignored.
const owner = {};
panel = {
id: ++activations,
owner,
container: viewer.container,
items: items.map(({ id, label }) => ({ id, label })),
status: t('Select a feature or use Tab and Enter to choose an action.'),
busy: false,
selected: null,
outlined: [],
card: null,
};
store.publish(panel);
store.connect({
dispatch(id, from) {
if (from === owner && panel?.owner === owner) void dispatch(id);
},
});
const owner = panel;
const title = document.createElement('strong');
title.textContent = 'Scene actions';
panel.append(title);
status = document.createElement('p');
status.setAttribute('role', 'status');
status.textContent =
'Select a feature or use Tab and Enter to choose an action.';
panel.append(status);
for (const item of items) {
const button = document.createElement('button');
button.type = 'button';
button.textContent = item.label;
button.dataset.directorAction = item.id;
Object.assign(button.style, {
display: 'block',
background: '#10242e',
color: '#e3faff',
border: '1px solid #397080',
borderRadius: '3px',
padding: '6px 10px',
cursor: 'pointer',
font: 'inherit',
margin: '6px 0',
maxWidth: '100%',
whiteSpace: 'normal',
});
button.addEventListener('click', () => {
if (panel === owner) void dispatch(item.id);
});
buttons.set(item.id, button);
panel.append(button);
}
card = document.createElement('div');
card.dataset.directorActionCard = '';
panel.append(card);
viewer.container.append(panel);
session.activate(items);
handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
handler.setInputAction((event) => {
if (panel !== owner || !isPointerFree() || !available()) return;
if (
panel?.owner !== owner ||
!shown() ||
!isPointerFree() ||
!available()
)
return;
const picked = viewer.scene.pick(event.position)?.id;
const matches = items.filter(
(item) =>
@@ -151,14 +134,22 @@ export function createSceneInteractions(
) === picked,
);
if (!matches.length) return;
for (const item of items) {
const button = buttons.get(item.id);
button.style.outline = matches.includes(item)
? '2px solid #6eeaff'
: '';
}
status.textContent = `Selected feature: ${matches[0].target.featureId}. Choose an action.`;
buttons.get(matches[0].id)?.focus({ preventScroll: true });
update({
outlined: matches.map((item) => item.id),
status: t('Selected feature: {feature}. Choose an action.', {
feature: matches[0].target.featureId,
}),
});
// Focus the first match once the panel shows the selection.
void nextTick(() => {
if (panel?.owner !== owner || !shown()) return;
const id = globalThis.CSS?.escape?.(matches[0].id) ?? matches[0].id;
viewer.container
?.querySelector?.(
`[data-director-interactions] [data-director-action="${id}"]`,
)
?.focus({ preventScroll: true });
});
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
},
};
+192
View File
@@ -0,0 +1,192 @@
// src/scenes/interactionsView.test.mjs — the Scene actions panel renders in
// the viewer's container from what the scene interactions owner presents.
import '../testSupport/registerDom.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import { createApp, nextTick } from 'vue';
import { createPinia } from 'pinia';
import { useSceneInteractionsStore } from '../ui/stores/sceneInteractions.js';
import SceneInteractions from '../ui/views/panels/SceneInteractions.vue';
import { createSceneInteractions } from './interactions.js';
const target = (featureId) => ({ packId: 'qa', featureId });
const key = (featureId) => JSON.stringify(['qa', featureId]);
const SHOT = {
interactions: [
{
id: 'card',
label: 'Read about it',
target: target('point'),
action: { type: 'card', text: 'A note.', url: 'https://example.com/a' },
},
{
id: 'fly',
label: 'Fly there',
target: target('point'),
action: { type: 'fly' },
},
],
};
function fixture(t, { execute = async () => true } = {}) {
document.body.replaceChildren();
const container = document.body.appendChild(document.createElement('div'));
const canvas = container.appendChild(document.createElement('canvas'));
const pinia = createPinia();
const app = createApp(SceneInteractions).use(pinia);
app.mount(document.body.appendChild(document.createElement('div')));
const executed = [];
const interactions = createSceneInteractions(
{ container, scene: { canvas, pick: () => null } },
{
execute: (action, signal) => {
executed.push(action.type);
return execute(action, signal);
},
store: useSceneInteractionsStore(pinia),
},
);
t.after(() => {
interactions.destroy();
app.unmount();
});
const $ = (selector) => container.querySelector(selector);
const settle = async () => {
for (let flush = 0; flush < 4; flush += 1) await nextTick();
};
return { interactions, container, executed, $, settle, pinia };
}
test('a shot with actions shows its panel in the viewer container', async (t) => {
const { interactions, $, settle } = fixture(t);
assert.equal($('[data-director-interactions]'), null);
interactions.activate(SHOT, new Map([[key('point'), {}]]));
await settle();
const panel = $('[data-director-interactions]');
assert.equal(panel.tagName, 'SECTION');
assert.equal(panel.getAttribute('aria-label'), 'Scene actions');
assert.equal(panel.style.position, 'absolute');
assert.equal(panel.style.zIndex, '31');
assert.equal(panel.querySelector('strong').textContent, 'Scene actions');
assert.equal(
panel.querySelector('[role=status]').textContent,
'Select a feature or use Tab and Enter to choose an action.',
);
const buttons = [...panel.querySelectorAll('button')];
assert.deepEqual(
buttons.map((button) => [
button.dataset.directorAction,
button.textContent,
]),
[
['card', 'Read about it'],
['fly', 'Fly there'],
],
);
assert.ok(buttons.every((button) => button.type === 'button'));
assert.deepEqual(
buttons.map((button) => button.getAttribute('aria-pressed')),
['false', 'false'],
);
assert.equal($('[data-director-action-card]').children.length, 0);
});
test('an action reports its outcome and a card action shows its text and source', async (t) => {
const { interactions, executed, $, settle } = fixture(t);
interactions.activate(SHOT, new Map([[key('point'), {}]]));
await settle();
$('[data-director-action="card"]').click();
await settle();
const card = $('[data-director-action-card]');
assert.equal(card.querySelector('p').textContent, 'A note.');
const link = card.querySelector('a');
assert.equal(link.textContent, 'Source');
assert.equal(link.getAttribute('href'), 'https://example.com/a');
assert.equal(link.target, '_blank');
assert.equal(link.rel, 'noopener noreferrer');
assert.equal($('[role=status]').textContent, 'Action complete');
const card1 = $('[data-director-action="card"]');
assert.equal(card1.getAttribute('aria-pressed'), 'true');
// happy-dom orders the shorthand its own way.
assert.deepEqual(card1.style.outline.split(' ').sort(), [
'#6eeaff',
'2px',
'solid',
]);
$('[data-director-action="fly"]').click();
await settle();
assert.deepEqual(executed, ['fly']);
assert.equal(card.children.length, 0, 'another action clears the card');
assert.equal($('[data-director-action="card"]').style.outline, '');
});
test('buttons are disabled while an action runs, and clearing removes the panel', async (t) => {
let finish;
const { interactions, $, settle } = fixture(t, {
execute: () => new Promise((resolve) => (finish = resolve)),
});
interactions.activate(SHOT, new Map([[key('point'), {}]]));
await settle();
$('[data-director-action="fly"]').click();
await settle();
assert.ok(
[...$('[data-director-interactions]').querySelectorAll('button')].every(
(button) => button.disabled,
),
);
finish(false);
await settle();
assert.equal(
$('[role=status]').textContent,
'Action unavailable or cancelled',
);
interactions.clear();
await settle();
assert.equal($('[data-director-interactions]'), null);
});
test('a button from an earlier panel cannot run the replacement actions', async (t) => {
const { interactions, executed, $, settle } = fixture(t);
interactions.activate(SHOT, new Map([[key('point'), {}]]));
await settle();
const old = $('[data-director-action="fly"]');
interactions.clear();
await settle();
interactions.activate(SHOT, new Map([[key('point'), {}]]));
await settle();
assert.ok(old !== $('[data-director-action="fly"]'));
old.click();
await settle();
assert.deepEqual(executed, []);
assert.equal(interactions.getState().selected, null);
});
test('a button reused before the next render still belongs to its own panel', async (t) => {
const { interactions, executed, $, settle } = fixture(t);
interactions.activate(SHOT, new Map([[key('point'), {}]]));
await settle();
const old = $('[data-director-action="fly"]');
interactions.activate(SHOT, new Map([[key('point'), {}]]));
old.click();
await settle();
assert.deepEqual(executed, []);
assert.ok(old !== $('[data-director-action="fly"]'));
assert.equal(old.isConnected, false);
});
test("an earlier owner leaves a later owner's panel alone", async (t) => {
const { interactions, container, $, settle, pinia } = fixture(t);
const later = createSceneInteractions(
{ container, scene: { canvas: $('canvas'), pick: () => null } },
{ execute: async () => true, store: useSceneInteractionsStore(pinia) },
);
t.after(() => later.destroy());
interactions.activate(SHOT, new Map([[key('point'), {}]]));
later.activate(SHOT, new Map([[key('point'), {}]]));
interactions.destroy();
await settle();
assert.ok($('[data-director-interactions]'));
$('[data-director-action="fly"]').click();
await settle();
assert.equal(later.getState().selected, 'fly');
});
+12
View File
@@ -7,6 +7,7 @@ import { SOURCE_PATH_BEAT_IDS } from '../data/bhoteKoshiShotPaths.js';
const ADDITIONAL_SHOTS = [
{
id: 'second-landslide',
// i18n-ignore: stored shot title, matched verbatim
title: 'Second landslide',
lat: 28.399234,
lon: 85.535806,
@@ -17,6 +18,7 @@ const ADDITIONAL_SHOTS = [
},
{
id: 'dhunche',
// i18n-ignore: stored shot title, matched verbatim
title: 'Dhunche',
lat: 28.161431,
lon: 85.324278,
@@ -27,6 +29,7 @@ const ADDITIONAL_SHOTS = [
},
{
id: 'mailung-upper-trishuli',
// i18n-ignore: stored shot title, matched verbatim
title: 'Mailung / Upper Trishuli bridge',
lat: 28.140642,
lon: 85.265996,
@@ -37,6 +40,7 @@ const ADDITIONAL_SHOTS = [
},
{
id: 'mailung-bazzar',
// i18n-ignore: stored shot title, matched verbatim
title: 'Mailung Bazzar, Dandaguan',
lat: 28.126526,
lon: 85.248027,
@@ -47,6 +51,7 @@ const ADDITIONAL_SHOTS = [
},
{
id: 'dandagaun',
// i18n-ignore: stored shot title, matched verbatim
title: 'Dandagaun, Rasuwa',
lat: 28.124424,
lon: 85.245154,
@@ -57,6 +62,7 @@ const ADDITIONAL_SHOTS = [
},
{
id: 'dandagaun-viewpoint',
// i18n-ignore: stored shot title, matched verbatim
title: 'Dandagaun viewpoint restaurant',
lat: 28.086663,
lon: 85.229914,
@@ -67,6 +73,7 @@ const ADDITIONAL_SHOTS = [
},
{
id: 'betrawati-bazaar',
// i18n-ignore: stored shot title, matched verbatim
title: 'Betrawati Bazaar',
lat: 28.029827,
lon: 85.227694,
@@ -77,6 +84,7 @@ const ADDITIONAL_SHOTS = [
},
{
id: 'bhainse',
// i18n-ignore: stored shot title, matched verbatim
title: 'Bhainse',
lat: 28.023087,
lon: 85.229449,
@@ -87,6 +95,7 @@ const ADDITIONAL_SHOTS = [
},
{
id: 'devighat-taadi-khola-bridge',
// i18n-ignore: stored shot title, matched verbatim
title: 'Devighat / Taadi Khola Bridge',
lat: 27.921132,
lon: 85.177113,
@@ -97,6 +106,7 @@ const ADDITIONAL_SHOTS = [
},
{
id: 'charaudi',
// i18n-ignore: stored shot title, matched verbatim
title: 'Charaudi',
lat: 27.865095,
lon: 84.838424,
@@ -107,6 +117,7 @@ const ADDITIONAL_SHOTS = [
},
{
id: 'final-view',
// i18n-ignore: stored shot title, matched verbatim
title: 'Final view',
lat: 28.0834,
lon: 85.206,
@@ -340,6 +351,7 @@ export function expandNepalEvidencePack(base) {
shotPatches: [
...(base.shotPatches || []),
{
// i18n-ignore: stored shot title, matched verbatim
title: 'Final view',
layers: finalView.layers,
},
+11 -3
View File
@@ -1,4 +1,7 @@
/** Connect the portable Director runner to the existing scene presentation. */
import { t } from '../i18n/index.js';
import { displaySceneTitle, displayShotTitle } from './recipes.js';
export function createScenePlaybackAdapter(director, defaultShotDurationSec) {
let timing;
let travel;
@@ -13,8 +16,13 @@ export function createScenePlaybackAdapter(director, defaultShotDurationSec) {
director._selectedShotId = shot.id;
director._renderSceneSelect();
director._renderShotList();
director._updateStatus(
`Running ${index + 1}/${total}: ${scene.title} / ${shot.title}`,
director._updateStatus(() =>
t('Running {index}/{total}: {scene} / {shot}', {
index: index + 1,
total,
scene: displaySceneTitle(scene),
shot: displayShotTitle(shot.title, shot, scene),
}),
);
director._logEvent('shot_start', {
sceneId: scene.id,
@@ -71,7 +79,7 @@ export function createScenePlaybackAdapter(director, defaultShotDurationSec) {
},
complete() {
director._setProgress(1);
director._updateStatus('Scene run complete');
director._updateStatus(() => t('Scene run complete'));
director._logEvent('scene_run_complete', {});
},
};
+8 -1
View File
@@ -7,6 +7,7 @@ import {
BLOOM_SCALE_VERSION,
decodeBloomIntensity,
} from '../bloom.js';
import { RETIRED_STYLES } from '../visualStylePolicy.js';
/** @constant {number} Current schema version for project migration */
export const PROJECT_VERSION = SCENE_DOCUMENT_VERSION;
@@ -122,6 +123,7 @@ export function recipeToScene(recipe) {
const mapStack = keyframe.mapStack || post.mapStack;
return {
id: uid('shot'),
// i18n-ignore: persisted fallback; legacy bootstrap matches 'Shot N'
title: keyframe.title || `Shot ${idx + 1}`,
durationSec: Math.max(
0.2,
@@ -171,6 +173,7 @@ export function recipeToScene(recipe) {
return {
id: recipe.id || uid('scene'),
// i18n-ignore: persisted fallback; built-in titles display through director
title: recipe.title || 'Untitled Scene',
releaseLayerIds: [
...new Set(
@@ -225,6 +228,7 @@ export function normalizeShot(
return {
id: rawShot?.id || uid('shot'),
// i18n-ignore: persisted fallback; legacy bootstrap matches 'Shot N'
title: rawShot?.title || `Shot ${index + 1}`,
durationSec: Math.max(
0.2,
@@ -259,7 +263,9 @@ export function normalizeShot(
...(rawShot?.dataPackIds ? { dataPackIds: [...rawShot.dataPackIds] } : {}),
...(rawShot?.move ? { move: deepClone(rawShot.move) } : {}),
visual: {
style: visual.style || 'normal',
style: RETIRED_STYLES.includes(visual.style)
? 'normal'
: visual.style || 'normal',
bloom: normalizeBloomState(bloom, {
projectVersion,
fallbackIntensity: 50,
@@ -349,6 +355,7 @@ export function normalizeProject(rawProject) {
);
return {
id: scene?.id || uid('scene'),
// i18n-ignore: persisted fallback for a saved scene without a title
title: scene?.title || `Scene ${sceneIdx + 1}`,
...(scene?.dataPacks ? { dataPacks: deepClone(scene.dataPacks) } : {}),
...(scene?.anchors ? { anchors: deepClone(scene.anchors) } : {}),
+129 -9
View File
@@ -4,11 +4,12 @@
*/
import { expandNepalEvidencePack } from './nepalEvidencePack.js';
import { msg, t } from '../i18n/index.js';
const BHOTE_KOSHI_NEPAL_BASE_RECIPE = Object.freeze({
id: 'bhote-koshi-nepal-evidence-pack',
version: 12,
title: 'Bhote Koshi Evidence Sequence',
title: msg('Bhote Koshi Evidence Sequence'),
style: 'normal',
ui: { hidePanels: false, hudMode: 'full', safeFrame: '16:9' },
layers: {
@@ -26,6 +27,7 @@ const BHOTE_KOSHI_NEPAL_BASE_RECIPE = Object.freeze({
fromShotTitles: ['Shot 1', 'Shot 2', 'Shot 3'],
cameraPath: [
{
// i18n-ignore: stored shot title, matched verbatim
title: 'Global Incident Context',
lat: 27.5962,
lon: 78.5718,
@@ -43,6 +45,7 @@ const BHOTE_KOSHI_NEPAL_BASE_RECIPE = Object.freeze({
},
},
{
// i18n-ignore: stored shot title, matched verbatim
title: 'Nepal-Focused Globe Rotation',
lat: 28.7248,
lon: 81.3226,
@@ -60,6 +63,7 @@ const BHOTE_KOSHI_NEPAL_BASE_RECIPE = Object.freeze({
},
},
{
// i18n-ignore: stored shot title, matched verbatim
title: 'Bhote Koshi Regional Approach',
lat: 27.0354,
lon: 84.6287,
@@ -77,6 +81,7 @@ const BHOTE_KOSHI_NEPAL_BASE_RECIPE = Object.freeze({
},
},
{
// i18n-ignore: stored shot title, matched verbatim
title: 'Bhote Koshi Nearby Cities',
lat: 27.891,
lon: 85.428,
@@ -94,6 +99,7 @@ const BHOTE_KOSHI_NEPAL_BASE_RECIPE = Object.freeze({
},
},
{
// i18n-ignore: stored shot title, matched verbatim
title: 'Bhote Koshi Incident Corridor',
lat: 28.0529,
lon: 85.2189,
@@ -111,6 +117,7 @@ const BHOTE_KOSHI_NEPAL_BASE_RECIPE = Object.freeze({
},
},
{
// i18n-ignore: stored shot title, matched verbatim
title: 'Bhote Koshi Flood Path',
lat: 28.1691,
lon: 85.352,
@@ -128,6 +135,7 @@ const BHOTE_KOSHI_NEPAL_BASE_RECIPE = Object.freeze({
},
},
{
// i18n-ignore: stored shot title, matched verbatim
title: 'Bhote Koshi Corridor Overview',
lat: 27.8986,
lon: 84.8723,
@@ -145,6 +153,7 @@ const BHOTE_KOSHI_NEPAL_BASE_RECIPE = Object.freeze({
},
},
{
// i18n-ignore: stored shot title, matched verbatim
title: 'Bhote Koshi Upper Valley',
lat: 28.4187,
lon: 85.4341,
@@ -221,6 +230,7 @@ const BHOTE_KOSHI_NEPAL_BASE_RECIPE = Object.freeze({
},
shotPatches: [
{
// i18n-ignore: stored shot title, matched verbatim
title: 'Global Incident Context',
visual: { mapStack: 'photoreal' },
layers: {
@@ -236,6 +246,7 @@ const BHOTE_KOSHI_NEPAL_BASE_RECIPE = Object.freeze({
},
},
{
// i18n-ignore: stored shot title, matched verbatim
title: 'Nepal-Focused Globe Rotation',
visual: { mapStack: 'photoreal' },
layers: {
@@ -251,6 +262,7 @@ const BHOTE_KOSHI_NEPAL_BASE_RECIPE = Object.freeze({
},
},
{
// i18n-ignore: stored shot title, matched verbatim
title: 'Bhote Koshi Regional Approach',
visual: { mapStack: 'photoreal' },
layers: {
@@ -266,6 +278,7 @@ const BHOTE_KOSHI_NEPAL_BASE_RECIPE = Object.freeze({
},
},
{
// i18n-ignore: stored shot title, matched verbatim
title: 'Bhote Koshi Nearby Cities',
visual: { mapStack: 'photoreal' },
layers: {
@@ -281,6 +294,7 @@ const BHOTE_KOSHI_NEPAL_BASE_RECIPE = Object.freeze({
},
},
{
// i18n-ignore: stored shot title, matched verbatim
title: 'Bhote Koshi Incident Corridor',
camera: {
lat: 28.0529,
@@ -305,6 +319,7 @@ const BHOTE_KOSHI_NEPAL_BASE_RECIPE = Object.freeze({
},
},
{
// i18n-ignore: stored shot title, matched verbatim
title: 'Bhote Koshi Flood Path',
visual: { mapStack: 'photoreal' },
layers: {
@@ -320,6 +335,7 @@ const BHOTE_KOSHI_NEPAL_BASE_RECIPE = Object.freeze({
},
},
{
// i18n-ignore: stored shot title, matched verbatim
title: 'Bhote Koshi Corridor Overview',
visual: { mapStack: 'photoreal' },
layers: {
@@ -335,6 +351,7 @@ const BHOTE_KOSHI_NEPAL_BASE_RECIPE = Object.freeze({
},
},
{
// i18n-ignore: stored shot title, matched verbatim
title: 'Bhote Koshi Upper Valley',
holdSec: 8,
visual: { mapStack: 'photoreal' },
@@ -357,6 +374,7 @@ const BHOTE_KOSHI_NEPAL_BASE_RECIPE = Object.freeze({
},
},
{
// i18n-ignore: stored shot title, matched verbatim
title: 'Upper Valley Collapse',
camera: {
lat: 28.417,
@@ -380,24 +398,29 @@ const BHOTE_KOSHI_NEPAL_BASE_RECIPE = Object.freeze({
},
},
{
// i18n-ignore: stored shot title, matched verbatim
title: 'Nepal-China Border Gate',
visual: { mapStack: 'photoreal' },
},
{
// i18n-ignore: stored shot title, matched verbatim
title: 'Timure Evidence Cluster',
visual: { mapStack: 'photoreal' },
},
{
// i18n-ignore: stored shot title, matched verbatim
title: 'Syabru Besi Passage',
visual: { mapStack: 'photoreal' },
},
{
// i18n-ignore: stored shot title, matched verbatim
title: 'Bidur / Trishuli Consequence',
visual: { mapStack: 'photoreal' },
},
],
cameraPath: [
{
// i18n-ignore: stored shot title, matched verbatim
title: 'Upper Valley Collapse',
lat: 28.417,
lon: 85.3937,
@@ -421,6 +444,7 @@ const BHOTE_KOSHI_NEPAL_BASE_RECIPE = Object.freeze({
},
},
{
// i18n-ignore: stored shot title, matched verbatim
title: 'Debris-Dammed Lake',
lat: 28.392914,
lon: 85.570921,
@@ -444,6 +468,7 @@ const BHOTE_KOSHI_NEPAL_BASE_RECIPE = Object.freeze({
},
},
{
// i18n-ignore: stored shot title, matched verbatim
title: 'Nepal-China Border Gate',
mapStack: 'photoreal',
lat: 28.316789,
@@ -474,6 +499,7 @@ const BHOTE_KOSHI_NEPAL_BASE_RECIPE = Object.freeze({
},
},
{
// i18n-ignore: stored shot title, matched verbatim
title: 'Timure Evidence Cluster',
mapStack: 'photoreal',
lat: 28.285968,
@@ -502,6 +528,7 @@ const BHOTE_KOSHI_NEPAL_BASE_RECIPE = Object.freeze({
},
},
{
// i18n-ignore: stored shot title, matched verbatim
title: 'Syabru Besi Passage',
mapStack: 'photoreal',
lat: 28.210306,
@@ -530,6 +557,7 @@ const BHOTE_KOSHI_NEPAL_BASE_RECIPE = Object.freeze({
},
},
{
// i18n-ignore: stored shot title, matched verbatim
title: 'Bidur / Trishuli Consequence',
mapStack: 'photoreal',
lat: 27.981737,
@@ -569,7 +597,7 @@ const BHOTE_KOSHI_NEPAL_APPEND_RECIPE = BHOTE_KOSHI_NEPAL_BASE_RECIPE
const BHOTE_KOSHI_NEPAL_BOOTSTRAP_RECIPE = BHOTE_KOSHI_NEPAL_APPEND_RECIPE
? Object.freeze({
id: 'bhote-koshi-nepal-scene',
title: 'Nepal Flood Incident',
title: msg('Nepal Flood Incident'),
durationSec: 15,
style: BHOTE_KOSHI_NEPAL_APPEND_RECIPE.style,
ui: BHOTE_KOSHI_NEPAL_APPEND_RECIPE.ui,
@@ -583,6 +611,7 @@ const BHOTE_KOSHI_NEPAL_BOOTSTRAP_RECIPE = BHOTE_KOSHI_NEPAL_APPEND_RECIPE
.slice(0, 3)
.map((keyframe, index) => ({
...keyframe,
// i18n-ignore: legacy shot titles the bootstrap matches verbatim
title: `Shot ${index + 1}`,
})),
})
@@ -593,7 +622,7 @@ const EVENT_RECIPES = [BHOTE_KOSHI_NEPAL_BOOTSTRAP_RECIPE].filter(Boolean);
const PUBLIC_SCENE_RECIPES = [
{
id: 'flights-radar',
title: 'Global Flights Radar',
title: msg('Global Flights Radar'),
durationSec: 30,
style: 'retro',
ui: { hidePanels: true, hudMode: 'minimal', safeFrame: '16:9' },
@@ -663,7 +692,7 @@ const PUBLIC_SCENE_RECIPES = [
},
{
id: 'orbital-watch',
title: 'Orbital Watch',
title: msg('Orbital Watch'),
durationSec: 32,
style: 'surveillance',
ui: { hidePanels: true, hudMode: 'full', safeFrame: '16:9' },
@@ -741,7 +770,7 @@ const PUBLIC_SCENE_RECIPES = [
},
{
id: 'thermal-threats',
title: 'Thermal Threat Board',
title: msg('Thermal Threat Board'),
durationSec: 26,
style: 'thermal',
ui: { hidePanels: true, hudMode: 'full', safeFrame: '16:9' },
@@ -809,7 +838,7 @@ const PUBLIC_SCENE_RECIPES = [
},
{
id: 'city-overload',
title: 'City Overload',
title: msg('City Overload'),
durationSec: 30,
style: 'surveillance',
ui: { hidePanels: true, hudMode: 'minimal', safeFrame: '9:16' },
@@ -887,7 +916,7 @@ const PUBLIC_SCENE_RECIPES = [
},
{
id: 'omniscience-pullback',
title: 'Omniscience Pullback',
title: msg('Omniscience Pullback'),
durationSec: 36,
style: 'retro',
ui: { hidePanels: true, hudMode: 'full', safeFrame: '16:9' },
@@ -965,7 +994,7 @@ const PUBLIC_SCENE_RECIPES = [
];
/** Build the recipe list without mutating stored user-authored projects. */
export function createSceneRecipes({ localDemoRecipes = EVENT_RECIPES } = {}) {
function createSceneRecipes({ localDemoRecipes = EVENT_RECIPES } = {}) {
return [...localDemoRecipes, ...PUBLIC_SCENE_RECIPES];
}
@@ -975,10 +1004,101 @@ export const SCENE_APPEND_RECIPES = BHOTE_KOSHI_NEPAL_APPEND_RECIPE
? [BHOTE_KOSHI_NEPAL_APPEND_RECIPE]
: [];
export function getSceneRecipeById(id) {
function getSceneRecipeById(id) {
return SCENE_RECIPES.find((recipe) => recipe.id === id) || null;
}
export function getSceneAppendRecipeById(id) {
return SCENE_APPEND_RECIPES.find((recipe) => recipe.id === id) || null;
}
// Built-in shot titles stay English in recipes and saved projects (upgrades
// and bindings match them verbatim). These are their display names; a title
// the user typed shows as typed. Place names inside them stay Latin.
const BUILTIN_SHOT_TITLES = new Set([
msg('Global Incident Context'),
msg('Nepal-Focused Globe Rotation'),
msg('Bhote Koshi Regional Approach'),
msg('Bhote Koshi Nearby Cities'),
msg('Bhote Koshi Incident Corridor'),
msg('Bhote Koshi Flood Path'),
msg('Bhote Koshi Corridor Overview'),
msg('Bhote Koshi Upper Valley'),
msg('Upper Valley Collapse'),
msg('Debris-Dammed Lake'),
msg('Nepal-China Border Gate'),
msg('Timure Evidence Cluster'),
msg('Syabru Besi Passage'),
msg('Bidur / Trishuli Consequence'),
msg('Second landslide'),
msg('Mailung / Upper Trishuli bridge'),
msg('Dandagaun viewpoint restaurant'),
msg('Devighat / Taadi Khola Bridge'),
msg('Final view'),
]);
/**
* Display title for a scene: the localized recipe name while the stored title
* still matches the built-in verbatim, the stored title otherwise.
* @param {{id?: string, title?: string}} scene
* @returns {string}
*/
export function displaySceneTitle(scene) {
const builtin = SCENE_RECIPES.find((recipe) => recipe.id === scene?.id);
if (builtin?.title && scene.title === builtin.title) return t(builtin.title);
const title = scene?.title || '';
// Only the generated "Scene N" localizes; an operator-typed "Scene 007"
// keeps its digits, so the number stays a string (no Number() round trip).
const numbered = /^Scene ([1-9]\d*)$/.exec(title);
return numbered ? t('Scene {n}', { n: numbered[1] }) : title;
}
/**
* Display title for a shot: built-in titles and the numbered "Shot N"
* fallback localize; any other title shows as stored.
*
* With `shot`, a built-in title localizes only for a recipe shot
* (`sourcePackId`), so a typed title that matches a built-in one stays as
* typed. Without `shot`, the title alone decides.
* @param {string} title
* @param {{id?: string, sourcePackId?: string}} [shot]
* @param {{id?: string, appliedShotPacks?: Array<{id?: string, shotBindings?: Object<string, string>}>}} [scene]
* The shot's scene, for projects saved before shots recorded their source
* pack.
* @returns {string}
*/
export function displayShotTitle(title, shot = undefined, scene = undefined) {
const text = typeof title === 'string' ? title : '';
const fromRecipe = shot
? Boolean(shot.sourcePackId) || recipeDeclaresShotTitle(scene, shot, text)
: true;
if (fromRecipe && BUILTIN_SHOT_TITLES.has(text)) return t(text);
const numbered = /^Shot ([1-9]\d*)$/.exec(text);
return numbered ? t('Shot {n}', { n: numbered[1] }) : text;
}
/** Whether the built-in recipe behind a scene declares this shot's title. */
function recipeDeclaresShotTitle(scene, shot, title) {
const recipe = scene?.id ? getSceneRecipeById(scene.id) : null;
if (!recipe) return false;
const declares = (path) =>
Array.isArray(path) && path.some((keyframe) => keyframe?.title === title);
if (declares(recipe.cameraPath)) return true;
// A bootstrap recipe seeds legacy "Shot N" keyframes; the upgrade replaces
// them with the append recipe's bootstrap shots, which carry no source pack.
// The pack marker binds each of those titles to its shot id, so a shot the
// operator later gave the same title stays as typed.
return SCENE_APPEND_RECIPES.some(
(append) =>
append.legacySceneBootstrap?.targetSceneTitle === recipe.title &&
declares(append.legacySceneBootstrap.cameraPath) &&
Boolean(shot?.id) &&
(Array.isArray(scene.appliedShotPacks)
? scene.appliedShotPacks
: []
).some(
(marker) =>
marker?.id === append.id && marker.shotBindings?.[title] === shot.id,
),
);
}
+50
View File
@@ -0,0 +1,50 @@
/**
* The reason for «Scene not saved — {reason}» when the project fails
* validation. The validator's text («$.scenes[6].title: expected …») is for
* the console: known failures get a sentence with 1-based numbers, others a
* general one (English keeps the raw text). director.js logs the full error.
*/
import { formatNumber, getLocale, t } from '../i18n/index.js';
const TEXT_LIMIT = /^expected nonempty text, at most (\d+) characters$/;
const SCENE_TITLE = /^\$\.scenes\[(\d+)\]\.title$/;
const SHOT_TITLE = /^\$\.scenes\[(\d+)\]\.shots\[(\d+)\]\.title$/;
const ordinal = (index) => formatNumber(Number(index) + 1);
/**
* @param {unknown} error Usually a SceneDocumentError ({path, reason}).
* @returns {string} Reason in the UI language.
*/
export function sceneSaveFailureReason(error) {
const path = typeof error?.path === 'string' ? error.path : '';
const reason =
typeof error?.reason === 'string'
? error.reason
: String(error?.message || '').slice(path ? path.length + 2 : 0);
const limit = TEXT_LIMIT.exec(reason);
if (limit) {
const max = formatNumber(Number(limit[1]));
const scene = SCENE_TITLE.exec(path);
if (scene)
return t(
'the title of scene {scene} is empty or longer than {max} characters',
{ scene: ordinal(scene[1]), max },
);
const shot = SHOT_TITLE.exec(path);
if (shot)
return t(
'the title of shot {shot} in scene {scene} is empty or longer than {max} characters',
{ scene: ordinal(shot[1]), shot: ordinal(shot[2]), max },
);
}
if (path === '$' && reason === 'file exceeds 5 MiB')
return t('the project is larger than 5 MiB');
if (reason === 'too many shots in project')
return t('the project has too many shots');
// English keeps the validator's own text, which names the field; another
// language gets a general sentence (the field is in the console warning).
if (getLocale() === 'en' && error?.message) return String(error.message);
return t('the scene data failed validation');
}
+101
View File
@@ -0,0 +1,101 @@
// «Scene not saved — {reason}» never shows the validator's JSON path: known
// failures read as a sentence, the rest get a general reason.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { setLocale } from '../i18n/index.js';
import {
SceneDocumentError,
validateSceneDocument,
} from '../director/document.js';
import { sceneSaveFailureReason } from './sceneSaveError.js';
const caught = (project) => {
try {
validateSceneDocument(project);
} catch (error) {
return error;
}
return assert.fail('expected a validation error');
};
test('an empty scene title is named with its 1-based scene number', () => {
setLocale('en');
const scenes = Array.from({ length: 7 }, (_, i) => ({
id: `s${i}`,
title: i === 6 ? ' ' : `Scene ${i + 1}`,
shots: [],
}));
const error = caught({ version: 6, scenes });
assert.ok(error instanceof SceneDocumentError);
assert.equal(error.path, '$.scenes[6].title');
assert.equal(
sceneSaveFailureReason(error),
'the title of scene 7 is empty or longer than 4,096 characters',
);
});
test('a shot title names the shot and its scene', () => {
setLocale('en');
const error = caught({
version: 6,
scenes: [
{
id: 'a',
title: 'A',
shots: [{ id: 'x' }, { id: 'y', title: 'z'.repeat(4097) }],
},
],
});
assert.equal(
sceneSaveFailureReason(error),
'the title of shot 2 in scene 1 is empty or longer than 4,096 characters',
);
});
test('size and shot-count limits read as sentences', () => {
setLocale('en');
assert.equal(
sceneSaveFailureReason(new SceneDocumentError('$', 'file exceeds 5 MiB')),
'the project is larger than 5 MiB',
);
assert.equal(
sceneSaveFailureReason(
new SceneDocumentError('$.scenes[3].shots', 'too many shots in project'),
),
'the project has too many shots',
);
});
test('any other validation failure: English keeps the field, a translation never shows the path', () => {
const errors = [
new SceneDocumentError(
'$.scenes[0].shots[2].layers.x.enabled',
'expected a boolean',
),
new SceneDocumentError('$.scenes[1].anchors[0].id', 'duplicate ID'),
new Error('$.scenes[0]: odd'),
];
setLocale('en');
for (const error of errors)
assert.equal(sceneSaveFailureReason(error), error.message);
assert.equal(
sceneSaveFailureReason(null),
'the scene data failed validation',
);
for (const locale of ['ru', 'es']) {
setLocale(locale);
try {
for (const error of [...errors, null]) {
const text = sceneSaveFailureReason(error);
assert.doesNotMatch(
text,
/\$\.|expected|duplicate|odd/,
`${locale}: ${text}`,
);
}
} finally {
setLocale('en');
}
}
});
+183
View File
@@ -0,0 +1,183 @@
// Display helpers must not rewrite operator-typed scene/shot titles: only the
// generated "Scene N" / "Shot N" and the titles of recipe-sourced shots
// localize; everything else shows exactly as stored.
import test from 'node:test';
import assert from 'node:assert/strict';
import {
SCENE_APPEND_RECIPES,
SCENE_RECIPES,
displaySceneTitle,
displayShotTitle,
} from './recipes.js';
import { setLocale } from '../i18n/index.js';
test.afterEach(() => setLocale('en'));
test('user-typed numbered titles keep their digits in en', () => {
setLocale('en');
assert.equal(
displaySceneTitle({ id: 'scene-user', title: 'Scene 007' }),
'Scene 007',
);
assert.equal(displayShotTitle('Shot 01'), 'Shot 01');
// default generated names still work
assert.equal(
displaySceneTitle({ id: 'scene-user', title: 'Scene 3' }),
'Scene 3',
);
assert.equal(displayShotTitle('Shot 2'), 'Shot 2');
});
test('generated numbered titles localize, typed ones with leading zeros do not', () => {
setLocale('ru');
assert.equal(
displaySceneTitle({ id: 'scene-user', title: 'Scene 3' }),
'Сцена 3',
);
assert.equal(displayShotTitle('Shot 2'), 'Кадр 2');
assert.equal(
displaySceneTitle({ id: 'scene-user', title: 'Scene 007' }),
'Scene 007',
);
assert.equal(displayShotTitle('Shot 01'), 'Shot 01');
});
test('a built-in shot title localizes only for a recipe-sourced shot', () => {
setLocale('ru');
// A built-in shot title (BUILTIN_SHOT_TITLES in recipes.js).
const title = 'Final view';
const userScene = { id: 'scene-user' };
// Operator-typed title that happens to match a built-in one: shown as typed.
assert.equal(
displayShotTitle(title, { id: 'shot-user', title }, userScene),
title,
);
// A recipe-sourced shot: localized.
const fromRecipe = displayShotTitle(
title,
{ id: 'shot-recipe', title, sourcePackId: 'bhote-koshi-nepal-scene' },
userScene,
);
assert.notEqual(fromRecipe, title);
// Without provenance the title alone decides.
assert.equal(displayShotTitle(title), fromRecipe);
// A project saved before shots recorded their source pack: the scene's
// recipe still vouches for a title its keyframes declare (only when such a
// recipe ships in this build).
const named = (keyframe) =>
keyframe?.title && !/^Shot \d+$/.test(keyframe.title);
const recipe = SCENE_RECIPES.find((item) => item.cameraPath?.some(named));
if (recipe) {
const declared = recipe.cameraPath.find(named).title;
assert.equal(
displayShotTitle(
declared,
{ id: 'shot-old', title: declared },
{ id: recipe.id },
),
displayShotTitle(declared),
);
assert.equal(
displayShotTitle(
declared,
{ id: 'shot-old', title: declared },
userScene,
),
declared,
);
}
});
test('the Scene status line shows an operator-typed shot title as typed', async () => {
const { createScenePlaybackAdapter } = await import('./playbackAdapter.js');
const statuses = [];
const director = {
_renderSceneSelect() {},
_renderShotList() {},
// The director words its status through a function (it follows the locale).
_updateStatus: (text) =>
statuses.push(typeof text === 'function' ? text() : text),
_logEvent() {},
};
const adapter = createScenePlaybackAdapter(director, 4);
const title = 'Final view';
const scene = { id: 'scene-user', title: 'Scene 1', shots: [] };
setLocale('ru');
adapter.selectShot({
scene,
shot: { id: 'shot-user', title },
index: 0,
total: 1,
});
adapter.selectShot({
scene,
shot: { id: 'shot-recipe', title, sourcePackId: 'bhote-koshi-nepal-scene' },
index: 0,
total: 1,
});
assert.ok(statuses[0].endsWith(` / ${title}`), statuses[0]);
assert.ok(
statuses[1].endsWith(` / ${displayShotTitle(title)}`) &&
!statuses[1].endsWith(` / ${title}`),
statuses[1],
);
});
test('the scene context of a shot carries its display title by provenance', async () => {
const { layerStatesForShot } = await import('./shotPresentation.js');
const title = 'Final view';
const packs = { recipeForShot: () => null, minimumHoldSec: () => 0 };
const contextFor = (shot) => {
const scene = { id: 'scene-user', title: 'Scene 1', shots: [shot] };
const states = layerStatesForShot(
scene,
{ ...shot, layers: { a: { params: { presentation: 'scene-beat' } } } },
packs,
);
return states.a.params.sceneContext;
};
setLocale('ru');
assert.equal(contextFor({ id: 'u', title }).shotDisplayTitle, title);
assert.notEqual(
contextFor({ id: 'r', title, sourcePackId: 'bhote-koshi-nepal-scene' })
.shotDisplayTitle,
title,
);
});
test('bootstrap shots of a built-in scene localize without a source pack', () => {
setLocale('ru');
const append = SCENE_APPEND_RECIPES.find(
(recipe) => recipe.legacySceneBootstrap?.cameraPath?.length,
);
if (!append) return;
const bootstrap = append.legacySceneBootstrap;
const scene = SCENE_RECIPES.find(
(recipe) => recipe.title === bootstrap.targetSceneTitle,
);
if (!scene) return;
for (const { title } of bootstrap.cameraPath) {
// The upgrade copies these keyframes into the scene without sourcePackId
// and binds each title to its shot in the pack marker.
const upgraded = {
id: scene.id,
appliedShotPacks: [
{ id: append.id, version: 1, shotBindings: { [title]: 'shot-old' } },
],
};
assert.equal(
displayShotTitle(title, { id: 'shot-old', title }, upgraded),
displayShotTitle(title),
);
// Another shot the operator gave the same title stays as typed.
assert.equal(
displayShotTitle(title, { id: 'shot-user', title }, upgraded),
title,
);
// The same title in an operator's own scene stays as typed.
assert.equal(
displayShotTitle(title, { id: 'shot-user', title }, { id: 'scene-user' }),
title,
);
}
});
+125 -81
View File
@@ -12,6 +12,7 @@ import {
} from '../director/authoring.js';
import { createSceneDialog, mountSceneSharing } from '../ui/sceneSharing.js';
import { PACK_LIMITS } from '../director/packs/manifest.js';
import { t, tn } from '../i18n/index.js';
function download(text, name) {
const url = URL.createObjectURL(
@@ -88,10 +89,13 @@ export function createSceneSharing(director) {
await job();
} catch (error) {
if (alive(owner))
dialog.status.textContent =
dialog.setStatus(
error?.name === 'SceneDocumentError'
? error.message
: 'Could not complete this action. Check the file, references and selected assets.';
: t(
'Could not complete this action. Check the file, references and selected assets.',
),
);
} finally {
if (alive(owner)) busy = false;
}
@@ -103,87 +107,120 @@ export function createSceneSharing(director) {
layerIds: director.dataManager.getAll().map((l) => l.id),
});
dialog.text(
`${report.scenes} scenes · ${report.shots} shots · ${report.packs.length} data packs`,
[
tn(report.scenes, '{count} scene', '{count} scenes'),
tn(report.shots, '{count} shot', '{count} shots'),
tn(report.packs.length, '{count} data pack', '{count} data packs'),
].join(' · '),
);
for (const pack of report.packs)
dialog.text(
`${pack.scene} / ${pack.id}: ${pack.status}. File: ${pack.path}. ${pack.attribution.text} · ${pack.attribution.license}`,
t(
'{scene} / {pack}: {status}. File: {path}. {attribution} · {license}',
{
scene: pack.scene,
pack: pack.id,
status: t(pack.status),
path: pack.path,
attribution: pack.attribution.text,
license: pack.attribution.license,
},
),
);
if (report.missingLayers.length)
dialog.text(`Unavailable layers: ${report.missingLayers.join(', ')}`);
dialog.text(
t('Unavailable layers: {layers}', {
layers: report.missingLayers.join(', '),
}),
);
if (report.externalContent)
dialog.text(
'This scene uses registered content or linked media. Those external files are not included in a scene bundle. Their original notices still apply.',
t(
'Uses registered content or linked media. Those external files are not included in a scene bundle. Their original notices still apply.',
),
);
if (report.bundledBytes)
dialog.text(
`${report.bundledBytes} bundled bytes verified. Files stay in memory for this session. Reimport the bundle after reloading the app.`,
t(
'{bytes} bundled bytes verified. Files stay in memory for this session. Reimport the bundle after reloading the app.',
{ bytes: report.bundledBytes },
),
);
return report;
}
async function preview(file) {
const owner = open('Review scene import');
const owner = open(t('Review scene import'));
if (!owner) return;
const expected = currentProject();
dialog.text('Nothing is loaded or changed until you apply this file.');
dialog.text(t('Nothing is loaded or changed until you apply this file.'));
await run(owner, async () => {
const input = await readSceneShare(file, { signal: owner.signal });
if (!alive(owner)) return;
staged = input;
inventory(input);
dialog.status.textContent = 'Ready to import';
dialog.setStatus(t('Ready to import'));
dialog.text(
'Apply replaces the current project. Export your current project first if you want to keep both.',
t(
'Apply replaces the current project. Export your current project first if you want to keep both.',
),
);
const apply = dialog.button('Apply import', () =>
run(owner, async () => {
if (expected !== currentProject()) throw new Error('Project changed');
apply.disabled = true;
const ok = await director.importProjectFile(file, {
prepared: input,
expectedProject: expected,
signal: owner.signal,
});
if (alive(owner)) {
if (ok) close();
else {
apply.disabled = false;
dialog.status.textContent =
'Import was not applied. The current project may have changed.';
const apply = dialog.button(
t('Apply import'),
() =>
run(owner, async () => {
if (expected !== currentProject())
throw new Error('Project changed');
apply.disabled = true;
const ok = await director.importProjectFile(file, {
prepared: input,
expectedProject: expected,
signal: owner.signal,
});
if (alive(owner)) {
if (ok) close();
else {
apply.disabled = false;
dialog.setStatus(
t(
'Import was not applied. The current project may have changed.',
),
);
}
}
}
}),
}),
{ hook: 'data-director-apply-import' },
);
apply.dataset.directorApplyImport = '';
});
}
function edit() {
const scene = director._getSelectedScene(),
shot = scene?.shots.find((s) => s.id === director._selectedShotId);
if (!scene || !shot) {
director._updateStatus('Select a scene and shot first');
director._updateStatus(() => t('Select a scene and shot first'));
return;
}
const owner = open('Edit scene details');
const owner = open(t('Edit scene details'));
if (!owner) return;
const original = structuredClone(director._project),
expected = currentProject();
dialog.text(
'Camera positions use degrees and meters above the ellipsoid. Drafts are validated before they replace your saved scene.',
t(
'Camera positions use degrees and meters above the ellipsoid. Drafts are validated before they replace your saved scene.',
),
);
const sceneText = dialog.input(
'Anchors and data packs',
t('Anchors and data packs'),
json(subset(scene, sceneKeys)),
{ multiline: true },
);
const shotText = dialog.input(
'Shot camera, timing, packs and actions',
t('Shot camera, timing, packs and actions'),
json(subset(shot, shotKeys)),
{ multiline: true },
);
const anchorName = dialog.input('New anchor ID', 'anchor-1');
const anchorName = dialog.input(t('New anchor ID'), 'anchor-1');
dialog.button(
'Capture camera as anchor',
t('Capture camera as anchor'),
() =>
run(owner, async () => {
const details = JSON.parse(sceneText.value),
@@ -210,12 +247,12 @@ export function createSceneSharing(director) {
JSON.parse(shotText.value),
);
sceneText.value = json(details);
dialog.status.textContent = 'Anchor added to draft';
dialog.setStatus(t('Anchor added to draft'));
}),
dialog.body,
{ place: 'body' },
);
dialog.button(
'Set move start to current camera',
t('Set move start to current camera'),
() =>
run(owner, async () => {
const details = JSON.parse(shotText.value),
@@ -246,13 +283,14 @@ export function createSceneSharing(director) {
details,
);
shotText.value = json(details);
dialog.status.textContent =
'Move added to draft; destination remains the shot camera';
dialog.setStatus(
t('Move added to draft; destination remains the shot camera'),
);
}),
dialog.body,
{ place: 'body' },
);
dialog.button(
'Use ordinary flight',
t('Use ordinary flight'),
() => {
if (!alive(owner)) return;
try {
@@ -260,37 +298,39 @@ export function createSceneSharing(director) {
delete details.move;
shotText.value = json(details);
} catch {
dialog.status.textContent = 'Invalid shot JSON';
dialog.setStatus(t('Invalid shot JSON'));
}
},
dialog.body,
{ place: 'body' },
);
const apply = dialog.button('Apply details', () =>
run(owner, async () => {
if (expected !== currentProject()) throw new Error('Project changed');
const project = editSceneDetails(
original,
scene.id,
shot.id,
JSON.parse(sceneText.value),
JSON.parse(shotText.value),
);
const ok = await director.importProjectFile(
{
name: 'scene details',
text: async () => stringifySceneDocument(project),
},
{
prepared: { project, assets: director._bundleAssets.snapshot() },
expectedProject: expected,
signal: owner.signal,
selection: { sceneId: scene.id, shotId: shot.id },
},
);
if (alive(owner) && ok) close();
}),
dialog.button(
t('Apply details'),
() =>
run(owner, async () => {
if (expected !== currentProject()) throw new Error('Project changed');
const project = editSceneDetails(
original,
scene.id,
shot.id,
JSON.parse(sceneText.value),
JSON.parse(shotText.value),
);
const ok = await director.importProjectFile(
{
name: 'scene details',
text: async () => stringifySceneDocument(project),
},
{
prepared: { project, assets: director._bundleAssets.snapshot() },
expectedProject: expected,
signal: owner.signal,
selection: { sceneId: scene.id, shotId: shot.id },
},
);
if (alive(owner) && ok) close();
}),
{ hook: 'data-director-apply-details' },
);
apply.dataset.directorApplyDetails = '';
}
function share() {
let project;
@@ -300,10 +340,10 @@ export function createSceneSharing(director) {
director._selectedSceneId,
);
} catch {
director._updateStatus('Select a scene first');
director._updateStatus(() => t('Select a scene first'));
return;
}
const owner = open('Share selected scene');
const owner = open(t('Share selected scene'));
if (!owner) return;
const paths = new Set(
project.scenes.flatMap((s) =>
@@ -320,19 +360,23 @@ export function createSceneSharing(director) {
staged = { project, assets: existing };
inventory(staged);
dialog.text(
'Scene JSON preserves authored settings and attribution. It does not include asset files. Bundles include only pack files you choose here or previously imported bundle files.',
t(
'Scene JSON preserves authored settings and attribution. It does not include asset files. Bundles include only pack files you choose here or previously imported bundle files.',
),
);
dialog.button('Download scene JSON', () => {
dialog.button(t('Download scene JSON'), () => {
if (alive(owner)) download(stringifySceneDocument(project), 'scene.json');
});
const files = dialog.input('Choose data-pack files', '', { type: 'file' });
files.multiple = true;
const folder = dialog.input('Or choose a data-pack folder', '', {
const files = dialog.input(t('Choose data-pack files'), '', {
type: 'file',
multiple: true,
});
folder.multiple = true;
folder.setAttribute('webkitdirectory', '');
dialog.button('Download asset bundle', () =>
const folder = dialog.input(t('Or choose a data-pack folder'), '', {
type: 'file',
multiple: true,
directory: true,
});
dialog.button(t('Download asset bundle'), () =>
run(owner, async () => {
const selected = [...files.files, ...folder.files];
const packs = project.scenes.flatMap((s) => s.dataPacks || []);
@@ -374,7 +418,7 @@ export function createSceneSharing(director) {
);
if (alive(owner)) {
download(text, 'scene.gevbundle.json');
dialog.status.textContent = 'Asset bundle downloaded';
dialog.setStatus(t('Asset bundle downloaded'));
}
}),
);
+197
View File
@@ -0,0 +1,197 @@
// src/scenes/sharingDialogs.test.mjs — scene sharing drives its authoring bar
// and dialogs through the store, drawn by the scene panels view (happy-dom).
import '../testSupport/registerDom.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import { createApp, nextTick } from 'vue';
import { createSceneSharing } from './sharing.js';
import { stringifySceneDocument } from '../director/document.js';
import { useSceneSharingStore } from '../ui/stores/sceneSharing.js';
import LayerPanelsView from '../ui/views/LayerPanelsView.vue';
import { applicationPinia } from '../ui/vueRuntime.js';
HTMLDialogElement.prototype.showModal ??= function () {
this.open = true;
};
const project = () => ({
version: 6,
scenes: [
{
id: 'one',
title: 'Example',
shots: [
{
id: 'shot',
title: 'Original',
durationSec: 3,
holdSec: 2,
camera: { lat: 1, lon: 2, alt: 300, pitch: -60 },
},
],
},
],
});
function fixture(t, { imported = true } = {}) {
document.body.replaceChildren();
const host = document.body.appendChild(document.createElement('div'));
// The owner presents through the application's store.
const pinia = applicationPinia();
const app = createApp(LayerPanelsView).use(pinia);
app.mount(host);
const imports = [];
let finishImport = null;
const director = {
_project: project(),
_selectedSceneId: 'one',
_selectedShotId: 'shot',
_getSelectedScene() {
return this._project.scenes[0];
},
_updateStatus() {},
styleManager: {
getCameraState: () => ({
lat: 5,
lon: 6,
alt: 700,
heading: 0,
pitch: -30,
roll: 0,
}),
},
_bundleAssets: { snapshot: () => new Map() },
_dataPacks: { sourceIds: () => [] },
dataManager: { getAll: () => [] },
importProjectFile(file, options) {
imports.push(options);
return new Promise((resolve) => {
finishImport = () => resolve(imported);
});
},
};
const sharing = createSceneSharing(director);
t.after(() => {
sharing.destroy();
app.unmount();
});
return {
sharing,
imports,
finish: () => finishImport?.(),
store: useSceneSharingStore(pinia),
};
}
const $ = (selector) => document.querySelector(selector);
const button = (label) =>
[...document.querySelectorAll('[data-director-dialog] button')].find(
(node) => node.textContent === label,
);
const status = () => $('[data-director-dialog] [role=status]').textContent;
const settle = async () => {
for (let i = 0; i < 6; i++) await new Promise((r) => setTimeout(r, 0));
await nextTick();
};
test('mounting offers the authoring bar and destroying withdraws it', async (t) => {
const { sharing, store } = fixture(t);
sharing.mount();
await nextTick();
assert.ok($('[data-director-authoring]'));
sharing.destroy();
await nextTick();
assert.equal($('[data-director-authoring]'), null);
assert.equal(store.toolbar, null);
});
test('EDIT DETAILS drafts in its fields, says what changed and applies the draft', async (t) => {
const { sharing, imports, finish } = fixture(t);
sharing.edit();
await nextTick();
assert.equal(
$('[data-director-dialog]').getAttribute('aria-label'),
'Edit scene details',
);
const [scene, shot] = document.querySelectorAll(
'[data-director-dialog] textarea',
);
assert.deepEqual(JSON.parse(scene.value), {});
assert.equal(JSON.parse(shot.value).durationSec, 3);
// Camera helpers sit in the body, Apply in the footer by its hook.
const capture = button('Capture camera as anchor');
assert.equal(capture.parentElement.nextElementSibling.role, 'status');
capture.click();
await settle();
assert.equal(status(), 'Anchor added to draft');
assert.equal(JSON.parse(scene.value).anchors[0].lat, 5);
shot.value = '{';
shot.dispatchEvent(new Event('input', { bubbles: true }));
button('Use ordinary flight').click();
await nextTick();
assert.equal(status(), 'Invalid shot JSON');
shot.value = JSON.stringify({
camera: { lat: 1, lon: 2, alt: 300, pitch: -60 },
durationSec: 3,
holdSec: 4,
});
shot.dispatchEvent(new Event('input', { bubbles: true }));
$('[data-director-apply-details]').click();
await settle();
assert.equal(imports.length, 1);
assert.equal(imports[0].prepared.project.scenes[0].shots[0].holdSec, 4);
assert.equal(imports[0].prepared.project.scenes[0].anchors[0].id, 'anchor-1');
finish();
await settle();
assert.equal($('[data-director-dialog]'), null);
assert.equal(sharing.getState().open, false);
});
test('SHARE SCENE offers the JSON download and file and folder choosers', async (t) => {
const { sharing } = fixture(t);
sharing.share();
await nextTick();
assert.equal(
$('[data-director-dialog]').getAttribute('aria-label'),
'Share selected scene',
);
assert.ok(button('Download scene JSON'));
assert.ok(button('Download asset bundle'));
const [files, folder] = document.querySelectorAll(
'[data-director-dialog] input[type=file]',
);
assert.equal(files.multiple, true);
assert.equal(files.hasAttribute('webkitdirectory'), false);
assert.equal(folder.multiple, true);
assert.equal(folder.hasAttribute('webkitdirectory'), true);
});
test('an import review holds Apply disabled while the import runs and reopens it on refusal', async (t) => {
const { sharing, imports, finish } = fixture(t, { imported: false });
const text = stringifySceneDocument(project());
await sharing.preview({
name: 'scene.json',
size: text.length,
text: async () => text,
});
await settle();
assert.equal(status(), 'Ready to import');
const apply = $('[data-director-apply-import]');
assert.equal(apply.textContent, 'Apply import');
apply.click();
await settle();
assert.equal(imports.length, 1);
assert.equal($('[data-director-apply-import]').disabled, true);
finish();
await settle();
assert.equal($('[data-director-apply-import]').disabled, false);
assert.equal(
status(),
'Import was not applied. The current project may have changed.',
);
button('Cancel').click();
await nextTick();
assert.equal($('[data-director-dialog]'), null);
});
+4
View File
@@ -1,3 +1,5 @@
import { displaySceneTitle, displayShotTitle } from './recipes.js';
const DEFAULT_SHOT_DURATION_SEC = 4;
const clamp01 = (value) => Math.max(0, Math.min(1, value));
const deepClone = (value) => JSON.parse(JSON.stringify(value));
@@ -63,8 +65,10 @@ export function layerStatesForShot(
state.params.sceneContext = {
sceneId: scene.id,
sceneTitle: scene.title,
sceneDisplayTitle: displaySceneTitle(scene),
shotId: shot.id,
shotTitle: shot.title,
shotDisplayTitle: displayShotTitle(shot.title, shot, scene),
shotIndex,
shotCount: scene.shots.length,
durationSec: shot.durationSec || DEFAULT_SHOT_DURATION_SEC,