feat(map): publish shared Cesium adapter
This commit is contained in:
@@ -0,0 +1,403 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import type * as CesiumModule from "cesium";
|
||||
|
||||
import type {
|
||||
CesiumMapRendererProps,
|
||||
MapCamera,
|
||||
MapProviderId,
|
||||
MapRuntimeState,
|
||||
} from "./contracts.js";
|
||||
import {
|
||||
MapRuntimeError,
|
||||
applyCacheIntent,
|
||||
assetEndpointPath,
|
||||
fetchMapRuntimeConfiguration,
|
||||
fetchSameOriginJson,
|
||||
initialMapRuntimeState,
|
||||
withProviderState,
|
||||
} from "./runtime.js";
|
||||
|
||||
type CesiumNamespace = typeof CesiumModule;
|
||||
type ProviderEndpoint = {
|
||||
assetId: number;
|
||||
type: "IMAGERY" | "TERRAIN" | "3DTILES";
|
||||
externalType?: "BING";
|
||||
credentialMode: "gateway";
|
||||
url?: string;
|
||||
options?: {
|
||||
url?: string;
|
||||
mapStyle?: string;
|
||||
};
|
||||
attributions?: readonly unknown[];
|
||||
};
|
||||
|
||||
export function CesiumMapRenderer({
|
||||
runtimeConfigUrl,
|
||||
camera,
|
||||
layers,
|
||||
settings,
|
||||
cacheIntent,
|
||||
rendererGeneration = 0,
|
||||
className,
|
||||
onRuntimeStateChange,
|
||||
onCameraChange,
|
||||
}: CesiumMapRendererProps) {
|
||||
const containerRef = useRef<HTMLDivElement | null>(null);
|
||||
const stateCallbackRef = useRef(onRuntimeStateChange);
|
||||
const cameraCallbackRef = useRef(onCameraChange);
|
||||
|
||||
stateCallbackRef.current = onRuntimeStateChange;
|
||||
cameraCallbackRef.current = onCameraChange;
|
||||
|
||||
useEffect(() => {
|
||||
const container = containerRef.current;
|
||||
if (!container) {
|
||||
return;
|
||||
}
|
||||
const abortController = new AbortController();
|
||||
let disposed = false;
|
||||
let viewer: CesiumModule.Viewer | null = null;
|
||||
let runtimeState = initialMapRuntimeState();
|
||||
|
||||
const publish = (next: MapRuntimeState) => {
|
||||
runtimeState = next;
|
||||
if (!disposed) {
|
||||
stateCallbackRef.current?.(next);
|
||||
}
|
||||
};
|
||||
publish(runtimeState);
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
const configuration = await fetchMapRuntimeConfiguration(
|
||||
runtimeConfigUrl,
|
||||
abortController.signal,
|
||||
);
|
||||
const Cesium = await import("cesium");
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
viewer = createViewer(Cesium, container, settings);
|
||||
applyCamera(Cesium, viewer, camera);
|
||||
const removeCameraListener = bindCamera(Cesium, viewer, cameraCallbackRef);
|
||||
const removeRenderListener = bindRenderRecovery(viewer, publish);
|
||||
|
||||
const providerJobs = (["imagery", "terrain", "buildings"] as const).map(
|
||||
async (providerId) => {
|
||||
const visible = layers[providerId];
|
||||
publish(
|
||||
withProviderState(runtimeState, providerId, {
|
||||
phase: visible ? "loading" : "disabled",
|
||||
}),
|
||||
);
|
||||
if (!visible) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const endpoint = await fetchProviderEndpoint(
|
||||
configuration,
|
||||
providerId,
|
||||
abortController.signal,
|
||||
);
|
||||
if (disposed || !viewer) {
|
||||
return;
|
||||
}
|
||||
await attachProvider(
|
||||
Cesium,
|
||||
viewer,
|
||||
configuration.gateway.cache_proxy_prefix,
|
||||
endpoint,
|
||||
providerId,
|
||||
cacheIntent,
|
||||
false,
|
||||
settings,
|
||||
);
|
||||
publish(
|
||||
withProviderState(runtimeState, providerId, {
|
||||
phase: "ready",
|
||||
attributions: endpoint.attributions,
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
if (abortController.signal.aborted) {
|
||||
return;
|
||||
}
|
||||
publish(
|
||||
withProviderState(runtimeState, providerId, {
|
||||
phase: "error",
|
||||
code: safeErrorCode(error),
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
await Promise.allSettled(providerJobs);
|
||||
if (!disposed && viewer && layers.grid) {
|
||||
viewer.imageryLayers.addImageryProvider(
|
||||
new Cesium.GridImageryProvider({
|
||||
cells: 16,
|
||||
color: tokenColor(
|
||||
Cesium,
|
||||
container,
|
||||
"--nodedc-text-secondary",
|
||||
"rgba(247, 248, 244, 0.72)",
|
||||
),
|
||||
glowColor: tokenColor(
|
||||
Cesium,
|
||||
container,
|
||||
"--nodedc-text-muted",
|
||||
"rgba(247, 248, 244, 0.48)",
|
||||
),
|
||||
backgroundColor: Cesium.Color.TRANSPARENT,
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (disposed) {
|
||||
removeCameraListener();
|
||||
removeRenderListener();
|
||||
}
|
||||
} catch (error) {
|
||||
if (!abortController.signal.aborted) {
|
||||
const code = safeErrorCode(error);
|
||||
publish({
|
||||
phase: "gateway-unavailable",
|
||||
providers: {
|
||||
imagery: { phase: "error", code },
|
||||
terrain: { phase: "error", code },
|
||||
buildings: { phase: "error", code },
|
||||
},
|
||||
code,
|
||||
});
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
return () => {
|
||||
disposed = true;
|
||||
abortController.abort();
|
||||
viewer?.destroy();
|
||||
viewer = null;
|
||||
container.replaceChildren();
|
||||
};
|
||||
}, [
|
||||
runtimeConfigUrl,
|
||||
rendererGeneration,
|
||||
layers.imagery,
|
||||
layers.terrain,
|
||||
layers.buildings,
|
||||
layers.grid,
|
||||
cacheIntent.enabled,
|
||||
cacheIntent.no_overwrite,
|
||||
settings.atmosphere_enabled,
|
||||
settings.lighting_enabled,
|
||||
settings.monochrome_enabled,
|
||||
settings.terrain_exaggeration,
|
||||
settings.buildings_maximum_screen_space_error,
|
||||
settings.camera_animation_enabled,
|
||||
]);
|
||||
|
||||
return <div ref={containerRef} className={className} data-nodedc-map-renderer="cesium" />;
|
||||
}
|
||||
|
||||
function createViewer(
|
||||
Cesium: CesiumNamespace,
|
||||
container: HTMLElement,
|
||||
settings: CesiumMapRendererProps["settings"],
|
||||
): CesiumModule.Viewer {
|
||||
const viewer = new Cesium.Viewer(container, {
|
||||
animation: false,
|
||||
baseLayer: false,
|
||||
baseLayerPicker: false,
|
||||
fullscreenButton: false,
|
||||
geocoder: false,
|
||||
homeButton: false,
|
||||
infoBox: false,
|
||||
navigationHelpButton: false,
|
||||
sceneModePicker: false,
|
||||
selectionIndicator: false,
|
||||
timeline: false,
|
||||
terrainProvider: new Cesium.EllipsoidTerrainProvider(),
|
||||
requestRenderMode: true,
|
||||
maximumRenderTimeChange: Number.POSITIVE_INFINITY,
|
||||
});
|
||||
viewer.scene.globe.enableLighting = settings.lighting_enabled;
|
||||
if (viewer.scene.skyAtmosphere) {
|
||||
viewer.scene.skyAtmosphere.show = settings.atmosphere_enabled;
|
||||
}
|
||||
viewer.scene.verticalExaggeration = settings.terrain_exaggeration;
|
||||
viewer.scene.rethrowRenderErrors = false;
|
||||
return viewer;
|
||||
}
|
||||
|
||||
async function fetchProviderEndpoint(
|
||||
configuration: Awaited<ReturnType<typeof fetchMapRuntimeConfiguration>>,
|
||||
providerId: MapProviderId,
|
||||
signal: AbortSignal,
|
||||
): Promise<ProviderEndpoint> {
|
||||
const document = await fetchSameOriginJson(
|
||||
assetEndpointPath(configuration, providerId),
|
||||
signal,
|
||||
);
|
||||
const expectedAssetId = configuration.assets[providerId];
|
||||
const expectedType =
|
||||
providerId === "imagery"
|
||||
? "IMAGERY"
|
||||
: providerId === "terrain"
|
||||
? "TERRAIN"
|
||||
: "3DTILES";
|
||||
if (
|
||||
document.assetId !== expectedAssetId ||
|
||||
document.type !== expectedType ||
|
||||
document.credentialMode !== "gateway"
|
||||
) {
|
||||
throw new MapRuntimeError("map_provider_contract_mismatch");
|
||||
}
|
||||
if (
|
||||
(providerId === "imagery" &&
|
||||
(document.externalType !== "BING" ||
|
||||
!isEndpointOptions(document.options) ||
|
||||
typeof document.options.url !== "string")) ||
|
||||
(providerId !== "imagery" && typeof document.url !== "string")
|
||||
) {
|
||||
throw new MapRuntimeError("map_provider_contract_mismatch");
|
||||
}
|
||||
return document as ProviderEndpoint;
|
||||
}
|
||||
|
||||
async function attachProvider(
|
||||
Cesium: CesiumNamespace,
|
||||
viewer: CesiumModule.Viewer,
|
||||
cacheProxyPrefix: string,
|
||||
endpoint: ProviderEndpoint,
|
||||
providerId: MapProviderId,
|
||||
cacheIntent: CesiumMapRendererProps["cacheIntent"],
|
||||
refresh: boolean,
|
||||
settings: CesiumMapRendererProps["settings"],
|
||||
): Promise<void> {
|
||||
const publicUrl =
|
||||
providerId === "imagery" ? endpoint.options?.url : endpoint.url;
|
||||
if (!publicUrl) {
|
||||
throw new MapRuntimeError("map_provider_contract_mismatch");
|
||||
}
|
||||
const resource = new Cesium.Resource({
|
||||
url: applyCacheIntent(publicUrl, cacheIntent, refresh),
|
||||
proxy: new Cesium.DefaultProxy(cacheProxyPrefix),
|
||||
});
|
||||
if (providerId === "imagery") {
|
||||
const provider = await Cesium.BingMapsImageryProvider.fromUrl(resource, {
|
||||
key: "gateway-proxy",
|
||||
mapStyle: bingMapStyle(Cesium, endpoint.options?.mapStyle),
|
||||
});
|
||||
const layer = viewer.imageryLayers.addImageryProvider(provider);
|
||||
if (settings.monochrome_enabled) {
|
||||
layer.saturation = 0;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (providerId === "terrain") {
|
||||
viewer.terrainProvider = await Cesium.CesiumTerrainProvider.fromUrl(resource);
|
||||
return;
|
||||
}
|
||||
const tileset = await Cesium.Cesium3DTileset.fromUrl(resource, {
|
||||
maximumScreenSpaceError: settings.buildings_maximum_screen_space_error,
|
||||
});
|
||||
viewer.scene.primitives.add(tileset);
|
||||
}
|
||||
|
||||
function bindCamera(
|
||||
Cesium: CesiumNamespace,
|
||||
viewer: CesiumModule.Viewer,
|
||||
callbackRef: { current: ((camera: MapCamera) => void) | undefined },
|
||||
): () => void {
|
||||
const listener = () => {
|
||||
const position = viewer.camera.positionCartographic;
|
||||
callbackRef.current?.({
|
||||
longitude: Cesium.Math.toDegrees(position.longitude),
|
||||
latitude: Cesium.Math.toDegrees(position.latitude),
|
||||
height: position.height,
|
||||
heading: Cesium.Math.toDegrees(viewer.camera.heading),
|
||||
pitch: Cesium.Math.toDegrees(viewer.camera.pitch),
|
||||
roll: Cesium.Math.toDegrees(viewer.camera.roll),
|
||||
});
|
||||
};
|
||||
return viewer.camera.moveEnd.addEventListener(listener);
|
||||
}
|
||||
|
||||
function bindRenderRecovery(
|
||||
viewer: CesiumModule.Viewer,
|
||||
publish: (state: MapRuntimeState) => void,
|
||||
): () => void {
|
||||
let recoveryAttempted = false;
|
||||
return viewer.scene.renderError.addEventListener(() => {
|
||||
if (!recoveryAttempted) {
|
||||
recoveryAttempted = true;
|
||||
viewer.scene.requestRender();
|
||||
return;
|
||||
}
|
||||
publish({
|
||||
phase: "render-error",
|
||||
providers: {
|
||||
imagery: { phase: "error", code: "cesium_render_error" },
|
||||
terrain: { phase: "error", code: "cesium_render_error" },
|
||||
buildings: { phase: "error", code: "cesium_render_error" },
|
||||
},
|
||||
code: "cesium_render_error",
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function applyCamera(
|
||||
Cesium: CesiumNamespace,
|
||||
viewer: CesiumModule.Viewer,
|
||||
camera: MapCamera | null,
|
||||
): void {
|
||||
if (!camera) {
|
||||
viewer.camera.flyHome(0);
|
||||
return;
|
||||
}
|
||||
viewer.camera.setView({
|
||||
destination: Cesium.Cartesian3.fromDegrees(
|
||||
camera.longitude,
|
||||
camera.latitude,
|
||||
camera.height,
|
||||
),
|
||||
orientation: {
|
||||
heading: Cesium.Math.toRadians(camera.heading),
|
||||
pitch: Cesium.Math.toRadians(camera.pitch),
|
||||
roll: Cesium.Math.toRadians(camera.roll),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function bingMapStyle(
|
||||
Cesium: CesiumNamespace,
|
||||
value: string | undefined,
|
||||
): CesiumModule.BingMapsStyle {
|
||||
if (value === "Road") {
|
||||
return Cesium.BingMapsStyle.ROAD;
|
||||
}
|
||||
if (value === "AerialWithLabels") {
|
||||
return Cesium.BingMapsStyle.AERIAL_WITH_LABELS;
|
||||
}
|
||||
return Cesium.BingMapsStyle.AERIAL;
|
||||
}
|
||||
|
||||
function safeErrorCode(error: unknown): string {
|
||||
return error instanceof MapRuntimeError ? error.code : "map_provider_unavailable";
|
||||
}
|
||||
|
||||
function isEndpointOptions(
|
||||
value: unknown,
|
||||
): value is NonNullable<ProviderEndpoint["options"]> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function tokenColor(
|
||||
Cesium: CesiumNamespace,
|
||||
container: HTMLElement,
|
||||
token: string,
|
||||
fallback: string,
|
||||
): CesiumModule.Color {
|
||||
const value = getComputedStyle(container).getPropertyValue(token).trim();
|
||||
return Cesium.Color.fromCssColorString(value || fallback) ?? Cesium.Color.WHITE;
|
||||
}
|
||||
Reference in New Issue
Block a user