Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
fix: keep the video export camera on the same center as the main map (#3758)
Igor Dykhtae13d11eecc6e
diff --git a/src/components/src/modals/export-video-modal.spec.tsx b/src/components/src/modals/export-video-modal.spec.tsxindex caebd76f9..841372f7b 100644--- a/src/components/src/modals/export-video-modal.spec.tsx+++ b/src/components/src/modals/export-video-modal.spec.tsx@@ -65,6 +65,17 @@ jest.mock('./hubble-utils', () => ({})),getTimeRangeFilterKeyframes: jest.fn(),getAnimatableFilters: jest.fn(() => []),+ scaleToVideoExport: jest.fn((viewState, container) => ({+ ...viewState,+ width: container.width,+ height: container.height+ })),+ getVideoExportContainer: jest.fn((exportVideoWidth, resolution) => {+ const [width, height] = String(resolution || '1280x720')+ .split('x')+ .map(Number);+ return {width: exportVideoWidth, height: exportVideoWidth / (width / height)};+ }),getResolutionSetting: jest.fn(value => {const [width, height] = String(value || '1280x720').split('x')@@ -159,11 +170,17 @@ describe('ExportVideoModal', () => {expect(panelProps.exportVideoWidth).toBeGreaterThanOrEqual(320);expect(panelProps.handleClose).toBe(DEFAULT_PROPS.onClose);expect(panelProps.initialState).toEqual(DEFAULT_PROPS.exportVideo);- expect(panelProps.mapData).toEqual({- visState: DEFAULT_PROPS.visState,- mapState: DEFAULT_PROPS.mapState,- mapStyle: DEFAULT_PROPS.mapStyle- });+ expect(panelProps.mapData.visState).toEqual(DEFAULT_PROPS.visState);+ expect(panelProps.mapData.mapStyle).toEqual(DEFAULT_PROPS.mapStyle);+ expect(panelProps.mapData.mapState).toEqual(+ expect.objectContaining({+ latitude: DEFAULT_PROPS.mapState.latitude,+ longitude: DEFAULT_PROPS.mapState.longitude,+ zoom: DEFAULT_PROPS.mapState.zoom,+ width: panelProps.exportVideoWidth,+ height: expect.any(Number)+ })+ );});test('passes deckProps from getHubbleDeckGlProps', async () => {diff --git a/src/components/src/modals/export-video-modal.tsx b/src/components/src/modals/export-video-modal.tsxindex b184d5d92..c942ccf40 100644--- a/src/components/src/modals/export-video-modal.tsx+++ b/src/components/src/modals/export-video-modal.tsx@@ -1,7 +1,7 @@// SPDX-License-Identifier: MIT// Copyright contributors to the kepler.gl project-import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';+import React, {useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState} from 'react';import styled, {ThemeProvider, useTheme} from 'styled-components';import {@@ -33,7 +33,9 @@ import {getHubbleDeckGlProps,getTimeRangeFilterKeyframes,getAnimatableFilters,- getResolutionSetting+ getResolutionSetting,+ getVideoExportContainer,+ scaleToVideoExport} from './hubble-utils';import {useFogHeightAnimation} from './fog-height-animation';@@ -277,7 +279,25 @@ const ExportVideoModalFactory = () => {return Math.max(320, Math.min(540, modalInnerW - HUBBLE_PANEL_OVERHEAD));}, [containerW]);+ const [videoConfiguration, setVideoConfiguration] = useState<VideoConfiguration>({+ ...exportVideo+ });+const keplerState = useMemo(() => {+ // Hubble (and our globe/swipe containers) run scaleToVideoExport on+ // mapData.mapState. Apply it here first so the preview camera already+ // matches the main map; a second pass with matching width/height is a no-op+ // for our scaler. Hubble's built-in scaler still uses fitBounds, so 3D+ // mercator is corrected after mount below.+ const container = getVideoExportContainer(+ exportVideoWidth,+ videoConfiguration.resolution || ''+ );+ const exportMapState = {+ ...mapState,+ ...scaleToVideoExport(mapState, container)+ };+if (mapStyle?.styleType === NO_MAP_ID) {const noMapEntry = mapStyle.mapStyles?.[NO_MAP_ID];if (noMapEntry && !noMapEntry.url) {@@ -301,7 +321,7 @@ const ExportVideoModalFactory = () => {)}`;return {visState,- mapState,+ mapState: exportMapState,mapStyle: {...mapStyle,mapStyles: {@@ -312,8 +332,8 @@ const ExportVideoModalFactory = () => {};}}- return {visState, mapState, mapStyle};- }, [visState, mapState, mapStyle]);+ return {visState, mapState: exportMapState, mapStyle};+ }, [visState, mapState, mapStyle, exportVideoWidth, videoConfiguration.resolution]);const onUpdateMap = useCallback((viewPort: Viewport) => {@@ -331,9 +351,6 @@ const ExportVideoModalFactory = () => {(visState.effects || []).map((effect: Effect) => effect.clone()));- const [videoConfiguration, setVideoConfiguration] = useState<VideoConfiguration>({- ...exportVideo- });const onUpdateVideoConfiguration = useCallback((values: VideoConfiguration) => {setVideoConfiguration(prev => ({...prev, ...values}));@@ -399,6 +416,37 @@ const ExportVideoModalFactory = () => {// itself; the flat maplibre base map must be disabled so it doesn't render a// 2D Mercator map behind/around the globe.const isGlobeEnabled = Boolean(mapState?.globe?.enabled);+ const didSyncExportCameraRef = useRef(false);++ // Hubble's ExportVideoPanelContainer constructor always runs its own+ // scaleToVideoExport (fitBounds of screen corners), which recenters a pitched+ // camera. Push the already-corrected camera after mount so the preview matches+ // the main map. Globe/swipe containers use our scaler and don't need this.+ useLayoutEffect(() => {+ if (isSwipeMode || isGlobeEnabled || didSyncExportCameraRef.current) return;+ const panel = hubbleContainerRef.current as {+ setViewState?: (viewState: Record<string, any>) => void;+ setState?: (state: Record<string, any>) => void;+ } | null;+ if (!panel) return;+ const {longitude, latitude, zoom, pitch, bearing, altitude, minZoom, maxZoom, width, height} =+ keplerState.mapState;+ const viewState = {+ longitude,+ latitude,+ zoom,+ pitch,+ bearing,+ altitude,+ minZoom,+ maxZoom,+ width,+ height+ };+ panel.setViewState?.(viewState);+ panel.setState?.({viewState, memo: {viewState}});+ didSyncExportCameraRef.current = true;+ }, [hubble, isSwipeMode, isGlobeEnabled, keplerState.mapState]);useEffect(() => {// Same freeze as before: hubble.gl writes window.devicePixelRatio to scalediff --git a/src/components/src/modals/hubble-utils.spec.ts b/src/components/src/modals/hubble-utils.spec.tsindex 4e2b51d10..ef683ae52 100644--- a/src/components/src/modals/hubble-utils.spec.ts+++ b/src/components/src/modals/hubble-utils.spec.ts@@ -7,7 +7,9 @@ import {getTimeRangeFilterKeyframes,getBeforeLayerId,getStaticMapProps,- getAnimatableFilters+ getAnimatableFilters,+ scaleToVideoExport,+ getVideoExportContainer} from './hubble-utils';jest.mock('@kepler.gl/utils', () => ({@@ -308,4 +310,69 @@ describe('hubble-utils', () => {expect(result[0].id).toBe('synced');});});++ describe('getVideoExportContainer', () => {+ test('returns preview size matching the resolution aspect ratio', () => {+ expect(getVideoExportContainer(540, '1280x720')).toEqual({width: 540, height: 303.75});+ });+ });++ describe('scaleToVideoExport', () => {+ const container = {width: 540, height: 304};++ test('keeps the original camera target in 2D', () => {+ const viewState = {+ latitude: 37.75,+ longitude: -122.35,+ zoom: 11,+ pitch: 0,+ bearing: 0,+ width: 1400,+ height: 900+ };+ const result = scaleToVideoExport(viewState, container);++ expect(result.latitude).toBe(37.75);+ expect(result.longitude).toBe(-122.35);+ expect(result.width).toBe(container.width);+ expect(result.height).toBe(container.height);+ expect(result.zoom).toBeLessThan(viewState.zoom);+ });++ test('keeps the original camera target when the map is pitched', () => {+ const viewState = {+ latitude: 37.75,+ longitude: -122.35,+ zoom: 12,+ pitch: 50,+ bearing: 30,+ width: 1400,+ height: 900+ };+ const result = scaleToVideoExport(viewState, container);++ expect(result.latitude).toBe(37.75);+ expect(result.longitude).toBe(-122.35);+ expect(result.pitch).toBe(50);+ expect(result.bearing).toBe(30);+ });++ test('does not recenter globe cameras toward the equator', () => {+ const viewState = {+ latitude: 37.75,+ longitude: -122.35,+ zoom: 1,+ pitch: 0,+ bearing: 0,+ width: 1400,+ height: 900,+ globe: {enabled: true}+ };+ const result = scaleToVideoExport(viewState as any, container);++ expect(result.latitude).toBe(37.75);+ expect(result.longitude).toBe(-122.35);+ expect(result.zoom).toBe(1);+ });+ });});diff --git a/src/components/src/modals/hubble-utils.ts b/src/components/src/modals/hubble-utils.tsindex ce5e36dac..8ae111bc7 100644--- a/src/components/src/modals/hubble-utils.ts+++ b/src/components/src/modals/hubble-utils.ts@@ -1,7 +1,7 @@// SPDX-License-Identifier: MIT// Copyright contributors to the kepler.gl project-import {MapView, WebMercatorViewport, type MapViewState} from '@deck.gl/core';+import {MapView, type MapViewState} from '@deck.gl/core';import {DEFAULT_MAPBOX_API_URL,EMPTY_MAPBOX_STYLE,@@ -354,41 +354,48 @@ export function getAnimatableFilters(keplerState: KeplerState): TimeRangeFilter[// --- Video export utilities (inlined from @hubble.gl internals) ---+type VideoExportViewState = MapViewState & {+ width?: number;+ height?: number;+ altitude?: number;+ globe?: {enabled?: boolean};+};++type ScaledVideoViewState = MapViewState & {+ width: number;+ height: number;+ altitude?: number;+};+export function scaleToVideoExport(- viewState: MapViewState,+ viewState: VideoExportViewState,container: {width: number; height: number}-): MapViewState & {width: number; height: number} {- // In globe mode (and at extreme zooms) the WebMercatorViewport used below can- // produce a non-invertible projection matrix, making `unproject` throw. The- // Mercator fit-bounds rescaling only makes sense for the flat MapView anyway,- // so fall back to simply resizing the viewport to the export container.- try {- const viewport = new WebMercatorViewport(viewState);- const nw = viewport.unproject([0, 0]) as [number, number];- const se = viewport.unproject([viewport.width, viewport.height]) as [number, number];- const videoViewport = new WebMercatorViewport({- ...viewState,- width: container.width,- height: container.height- }).fitBounds([nw, se]);- const {height, width, latitude, longitude, zoom, altitude} = videoViewport;- return {- height,- width,- latitude,- longitude,- pitch: viewState.pitch,- zoom,- bearing: viewState.bearing,- altitude- } as any;- } catch (e) {- return {- ...viewState,- width: container.width,- height: container.height- } as any;- }+): ScaledVideoViewState {+ // Keep the camera pointed at the same lat/lng as the main map. The previous+ // WebMercatorViewport.fitBounds(screen-corners) path recentered the view:+ // with pitch/bearing it uses the AABB of a trapezoid, and at globe zooms a+ // mercator unproject silently pulls the target toward the equator.+ const isGlobe = Boolean(viewState.globe?.enabled);+ const srcWidth = Number(viewState.width) || 0;+ const srcHeight = Number(viewState.height) || 0;+ const canScaleZoom = !isGlobe && srcWidth > 0 && srcHeight > 0;+ const zoom = canScaleZoom+ ? viewState.zoom ++ (Math.log2(Math.min(container.width / srcWidth, container.height / srcHeight)) || 0)+ : viewState.zoom;++ return {+ longitude: viewState.longitude,+ latitude: viewState.latitude,+ zoom,+ pitch: viewState.pitch,+ bearing: viewState.bearing,+ altitude: viewState.altitude,+ minZoom: viewState.minZoom,+ maxZoom: viewState.maxZoom,+ width: container.width,+ height: container.height+ };}export function parseSetCameraType(strCameraType: string, viewState: MapViewState): MapViewState {@@ -434,3 +441,13 @@ const RESOLUTIONS: Resolution[] = [export function getResolutionSetting(value: string): Resolution {return RESOLUTIONS.find(r => r.value === value) || RESOLUTIONS[0];}++/** CSS size of the video-export preview, matching hubble's `_getContainer`. */+export function getVideoExportContainer(+ exportVideoWidth: number,+ resolution: string+): {width: number; height: number} {+ const {width, height} = getResolutionSetting(resolution);+ const aspectRatio = width / height;+ return {width: exportVideoWidth, height: exportVideoWidth / aspectRatio};+}