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

+189 -83
View File
@@ -7,17 +7,36 @@ import {
normalizeAllocationStrategy,
} from './data/detectionPolicy.js';
import { clampScopeTerminusPct } from './scopeMask.js';
import { clampScopeFeatherPct } from './scopeMaskPolicy.js';
import {
decodeLayerStateParams,
encodeLayerStateParams,
} from './data/layerState.js';
import { STYLE_URL_NAMES } from './view/index.js';
import {
SHARE_VIEW_PANELS,
SHARE_VIEW_STYLE_PARAMS,
decodeShareView,
encodeShareView,
} from './share/viewCodec.js';
import {
fromLegacyShareState,
toLegacyShareState,
} from './share/legacyShareState.js';
import {
appRootUrl,
parseSharePath,
shareLinkUrl,
} from './share/shareLinkPath.js';
/**
* Share Links — URL Hash State Management
*
* Encodes camera position + style into the URL hash so links can be shared.
* Format: #lat=37.77&lon=-122.42&alt=800&heading=0&pitch=-35&style=nvg&bloom=1&bi=84&bv=2&sharpen=0&si=65&hud=tactical&hv=1&dm=BALANCED&dd=50&da=elastic&kf=16&ko=0&cr=0&map=photoreal
* The address bar follows the live view in the long hash form:
* #lat=37.77&lon=-122.42&alt=800&heading=0&pitch=-35&style=nvg&bloom=1&bi=84&bv=2&sharpen=0&si=65&hud=tactical&hv=1&dm=BALANCED&dd=50&da=elastic&kf=16&ko=0&cr=0&map=photoreal
*
* A shared link is the short form, `<app>/share/<code>`, with the code from
* src/share/viewCodec.js (docs/SHARE-LINK-FORMAT.md). Both forms open here.
*/
const DEBOUNCE_MS = 500;
@@ -30,20 +49,9 @@ const SHARE_UI_STATE_PARAM = 'ui';
const SHARE_STYLE_PARAMS_PARAM = 'sp';
const SHARE_CREATED_AT_PARAM = 'at';
const SHARE_PANEL_STATE_REGISTRY = Object.freeze([
{ id: 'control-panel', token: 'c', pinnable: true },
{ id: 'location-bar', token: 'l', pinnable: true },
{ id: 'data-panel', token: 'd', pinnable: false },
{ id: 'cctv-panel', token: 'v', pinnable: false },
{ id: 'recent-imagery-panel', token: 'i', pinnable: false },
{ id: 'street-level-panel', token: 't', pinnable: false },
{ id: 'radio-panel', token: 'r', pinnable: false },
{ id: 'scene-panel', token: 's', pinnable: false },
{ id: 'global-context-panel', token: 'g', pinnable: false },
{ id: 'pp-toggles', token: 'p', pinnable: false },
{ id: 'param-slider-panel', token: 'm', pinnable: false },
]);
// The panel and visual-preset parameter tables are the share format's own
// (src/share/viewCodec.js); the long form spells their entries by token.
const SHARE_PANEL_STATE_REGISTRY = SHARE_VIEW_PANELS;
const SHARE_PANEL_STATE_BY_TOKEN = Object.freeze(
new Map(SHARE_PANEL_STATE_REGISTRY.map((entry) => [entry.token, entry])),
);
@@ -52,39 +60,7 @@ const URL_TO_STYLE = Object.fromEntries(
Object.entries(STYLE_TO_URL).map(([k, v]) => [v, k]),
);
const SHARE_STYLE_PARAM_REGISTRY = Object.freeze({
retro: Object.freeze([
{ key: 'pixelation', token: 'p', min: 1, max: 10 },
{ key: 'distortion', token: 'd', min: 0, max: 1 },
{ key: 'instability', token: 'i', min: 0, max: 1 },
]),
surveillance: Object.freeze([
{ key: 'gain', token: 'g', min: 0, max: 1 },
{ key: 'bloom', token: 'b', min: 0, max: 1 },
{ key: 'scanlineStr', token: 's', min: 0, max: 1 },
{ key: 'pixelation', token: 'p', min: 1, max: 6 },
]),
thermal: Object.freeze([
{ key: 'sensitivity', token: 's', min: 0, max: 1 },
{ key: 'bloom', token: 'b', min: 0, max: 1 },
{ key: 'mode', token: 'm', min: 0, max: 1 },
{ key: 'pixelation', token: 'p', min: 1, max: 6 },
{ key: 'palette', token: 'a', min: 0, max: 1 },
]),
anime: Object.freeze([
{ key: 'saturation', token: 's', min: 0, max: 2 },
{ key: 'edgeThick', token: 'e', min: 0, max: 1 },
]),
noir: Object.freeze([
{ key: 'contrastAmt', token: 'c', min: 0, max: 2 },
{ key: 'grainAmt', token: 'g', min: 0, max: 1 },
{ key: 'vignetteAmt', token: 'v', min: 0, max: 1 },
]),
snow: Object.freeze([
{ key: 'density', token: 'd', min: 0, max: 1 },
{ key: 'wind', token: 'w', min: 0, max: 1 },
]),
});
const SHARE_STYLE_PARAM_REGISTRY = SHARE_VIEW_STYLE_PARAMS;
export class ShareLinkManager {
/**
@@ -93,9 +69,20 @@ export class ShareLinkManager {
*/
constructor(
engine,
{ onRestore, isNavigationCurrent, cancelOwnedNavigation } = {},
{
onRestore,
isNavigationCurrent,
cancelOwnedNavigation,
initialShareCode = null,
} = {},
) {
this.engine = engineFromViewer(engine);
// A host may hand over the share code to open instead of the address.
this._initialShareCode =
typeof initialShareCode === 'string' ? initialShareCode : null;
// Why the share code this page opened with was refused, if it was.
this.rejectedShareCode = null;
this._followSubjectProvider = null;
this._onRestore = onRestore; // callback: ({ style, bloom, sharpen }) => void
this._debounceTimer = null;
this._currentStyle = 'normal';
@@ -118,10 +105,7 @@ export class ShareLinkManager {
this._detectionOutsideOpacityPct = 1;
this._celestialRingEnabled = false;
this._scopeEnabled = true;
// Feather opens on a soft 11% scope-mask edge (owner final lock 2026-08-24,
// superseding the 08-22 hard-crop and 08-23 8% rulings) — mirrors
// SCOPE_FEATHER_RATIO_DEFAULT in scopeMask.js and the slider's markup value.
this._scopeFeatherPct = 11;
this._scopeFeatherPct = 100;
// null = the altitude-adaptive terminus (the default). A number pins the
// outside-fill opacity as a percent, 94..100. (`sce`, 2026-08-17)
this._scopeTerminusPct = null;
@@ -130,6 +114,13 @@ export class ShareLinkManager {
this._panelStateProvider = null;
this._styleParamStateProvider = null;
this._initialRestorePending = false;
// Each incoming share (start-up or a later hash navigation) gets a token;
// only the newest one may release URL-write suppression.
this._restoreToken = 0;
// The hash this page last read or wrote. A location change back to it is
// the app's own state, never an incoming share.
this._knownHash = null;
this._unwatchNavigation = null;
this._restoreAuthority = {
visual: 0,
map: 0,
@@ -156,10 +147,44 @@ export class ShareLinkManager {
}
/**
* Parse URL hash on page load. Returns parsed state or null.
* Parse the share this page opened with: the host's `initialShareCode`, a
* `/share/<code>` address, or a long-form hash. Returns the parsed state, or
* null for none. A share code that cannot be opened is recorded in
* `rejectedShareCode` and restores nothing.
*/
parseInitialHash() {
const hash = window.location.hash.slice(1);
this._knownHash = hash;
const code =
this._initialShareCode ??
parseSharePath(window.location.pathname)?.code ??
null;
this._initialShareCode = null;
const state =
code === null ? this._parseShareHash(hash) : this._parseShareCode(code);
if (!state) return null;
this._beginIncomingRestore(state);
return state;
}
/**
* The restore state for a share code, in the long form's parsed shape plus
* `shareView` (what the view follows, with its offset and last-known fix),
* or null when the code is refused.
*/
_parseShareCode(code) {
const result = decodeShareView(code);
if (!result.ok) {
this.rejectedShareCode = result.reason;
return null;
}
const state = toLegacyShareState(result.state);
state.shareView = result.state.view;
return state;
}
/** Parse one hash without side effects. Returns null unless it is a share. */
_parseShareHash(hash) {
if (!hash) return null;
const params = new URLSearchParams(hash);
@@ -181,7 +206,9 @@ export class ShareLinkManager {
parseOr(params.get('dd'), 50),
50,
);
const style = URL_TO_STYLE[params.get('style')] || 'normal';
const style = Object.hasOwn(URL_TO_STYLE, params.get('style'))
? URL_TO_STYLE[params.get('style')]
: 'normal';
const decodedLayerState = decodeLayerStateParams(params);
const state = {
lat,
@@ -231,10 +258,7 @@ export class ShareLinkManager {
// (`_scopeFeatherPct` in the constructor tracks the default: that one
// mirrors live state for the link this session generates, so it must match
// the mask, not the archive.)
scopeFeatherPct: Math.max(
0,
Math.min(100, Math.round(parseOr(params.get('scf'), 35))),
),
scopeFeatherPct: clampScopeFeatherPct(parseOr(params.get('scf'), 35)),
// Absent (or non-numeric) `sce` = adaptive (null), the default behavior;
// a value pins the terminus opacity percent, clamped into the SUPPORTED
// 94..100 band. `sce=0` used to survive as a sub-94 terminus — a hole in
@@ -251,15 +275,55 @@ export class ShareLinkManager {
panelState: decodePanelStateParams(params),
sharedAtMs: decodeShareCreatedAtMs(params),
};
return state;
}
/** Reserve restore lanes and hold URL writes for one incoming share. */
_beginIncomingRestore(state) {
state.restoreAuthority = {
visual: this._restoreAuthority.visual,
map: this._restoreAuthority.map,
panels: new Map(this._restoreAuthority.panels),
};
// Hold URL writes until the complete incoming state has been restored.
state.restoreToken = ++this._restoreToken;
// Hold URL writes until the complete incoming state has been restored. A
// debounced write of the previous view must not land over the new link.
this._initialRestorePending = true;
return state;
clearTimeout(this._debounceTimer);
this._debounceTimer = null;
}
/**
* Restore a share link opened in this tab after start-up: a pasted address,
* a followed link, or Back/Forward. The app's own replaceState writes never
* fire these events, and a hash equal to the last one read or written is
* ignored anyway, so only a genuinely different incoming share restores.
*/
watchNavigation(onNavigate) {
this._unwatchNavigation?.();
if (this._destroyed || typeof onNavigate !== 'function') return;
const target = globalThis.window;
if (typeof target?.addEventListener !== 'function') return;
const handler = () => this._handleLocationChange(onNavigate);
target.addEventListener('hashchange', handler);
target.addEventListener('popstate', handler);
this._unwatchNavigation = () => {
target.removeEventListener('hashchange', handler);
target.removeEventListener('popstate', handler);
this._unwatchNavigation = null;
};
}
_handleLocationChange(onNavigate) {
if (this._destroyed) return;
const hash = window.location.hash.slice(1);
// Back/Forward fires both popstate and hashchange for one entry.
if (hash === this._knownHash) return;
this._knownHash = hash;
const state = this._parseShareHash(hash);
if (!state) return;
this._beginIncomingRestore(state);
onNavigate(state);
}
/**
@@ -379,9 +443,13 @@ export class ShareLinkManager {
};
}
/** Release initial hash suppression only after every restore owner settles. */
completeInitialRestore() {
/**
* Release hash suppression only after every restore owner settles. A token
* from a superseded share restore leaves the newer one holding the URL.
*/
completeInitialRestore(restoreToken = this._restoreToken) {
if (!this._initialRestorePending) return;
if (restoreToken !== this._restoreToken) return;
this._initialRestorePending = false;
this._scheduleUpdate();
}
@@ -404,6 +472,16 @@ export class ShareLinkManager {
this._layerStateProvider = typeof provider === 'function' ? provider : null;
}
/**
* Install the source of the entity the camera follows, used for share links:
* `({ nowMs }) => ({ kind, id, offset, lastKnown }) | null`, in the share
* format's terms (src/share/follow.js), with the fix as of `nowMs`.
*/
setFollowSubjectProvider(provider) {
this._followSubjectProvider =
typeof provider === 'function' ? provider : null;
}
/** Install the finalized panel-state source used by URL generation. */
setPanelStateProvider(provider) {
this._panelStateProvider = typeof provider === 'function' ? provider : null;
@@ -494,10 +572,7 @@ export class ShareLinkManager {
if (typeof extras.scopeEnabled === 'boolean')
this._scopeEnabled = extras.scopeEnabled;
if (typeof extras.scopeFeatherPct === 'number') {
this._scopeFeatherPct = Math.max(
0,
Math.min(100, Math.round(extras.scopeFeatherPct)),
);
this._scopeFeatherPct = clampScopeFeatherPct(extras.scopeFeatherPct);
}
if (extras.scopeTerminusPct === null) this._scopeTerminusPct = null;
else if (typeof extras.scopeTerminusPct === 'number') {
@@ -507,15 +582,41 @@ export class ShareLinkManager {
this._scheduleUpdate();
}
/**
* The share link for the current state, `<app>/share/<code>`, stamped with
* its creation time, or null before the camera has a position. While the
* camera follows an entity, the link follows it too.
*/
buildLink({ nowMs = Date.now() } = {}) {
const params = this._buildHashParams();
if (!params) return null;
// The long form is the one description of the live state; the code is
// that state in the share format.
const state = fromLegacyShareState(this._parseShareHash(params.toString()));
state.sharedAtMs = Math.floor(nowMs / 1000) * 1000;
let subject = null;
try {
subject = this._followSubjectProvider?.({ nowMs }) ?? null;
} catch {
subject = null;
}
if (subject) {
state.view = {
kind: 'thing',
entity: { kind: subject.kind, id: subject.id },
offset: subject.offset ?? null,
lastKnown: subject.lastKnown ?? null,
};
}
return shareLinkUrl(encodeShareView(state), window.location.href);
}
/** Copy a current-state snapshot with a copy-time timestamp. Returns true on success. */
async copyLink({ nowMs = Date.now() } = {}) {
const params = this._buildHashParams();
if (!params) return false;
params.set(SHARE_CREATED_AT_PARAM, String(Math.floor(nowMs / 1000)));
const copiedUrl = new URL(window.location.href);
copiedUrl.hash = params.toString();
try {
await navigator.clipboard.writeText(copiedUrl.href);
const href = this.buildLink({ nowMs });
if (!href) return false;
await navigator.clipboard.writeText(href);
return true;
} catch {
return false;
@@ -539,12 +640,15 @@ export class ShareLinkManager {
const params = this._buildHashParams();
if (!params) return;
// The hash belongs to this page's address, not the document base the
// app may load under.
history.replaceState(
null,
'',
new URL(`#${params.toString()}`, window.location.href).href,
);
// app may load under. A `/share/<code>` address gives way to the app's
// own address, so a reload follows the live view; replacing it adds no
// history entry.
const url = parseSharePath(new URL(window.location.href).pathname)
? appRootUrl(window.location.href)
: new URL(window.location.href);
url.hash = params.toString();
this._knownHash = url.hash.slice(1);
history.replaceState(null, '', url.href);
}
/** Build a deterministic snapshot without mutating history. */
@@ -597,8 +701,8 @@ export class ShareLinkManager {
this._styleParamStateProvider?.(this._currentStyle),
);
// Copy-time metadata is intentionally absent here. `copyLink()` adds a
// fresh timestamp to its ephemeral URL without aging the live address.
// Creation-time metadata is intentionally absent here. `buildLink()`
// stamps its own link without aging the live address.
params.delete(SHARE_CREATED_AT_PARAM);
return params;
}
@@ -621,9 +725,11 @@ export class ShareLinkManager {
this._debounceTimer = null;
this._removeCameraChanged?.();
this._removeCameraChanged = null;
this._unwatchNavigation?.();
this._layerStateProvider = null;
this._panelStateProvider = null;
this._styleParamStateProvider = null;
this._followSubjectProvider = null;
this._onRestore = null;
}
}