Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
feat: swipe view mode support in video export (#3503)
Igor Dykhta372e53a24e73
diff --git a/src/components/src/modals/export-video-modal.tsx b/src/components/src/modals/export-video-modal.tsxindex d1b16cd43..a61fc5d68 100644--- a/src/components/src/modals/export-video-modal.tsx+++ b/src/components/src/modals/export-video-modal.tsx@@ -4,7 +4,7 @@import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';import styled, {ThemeProvider, useTheme} from 'styled-components';-import {DEFAULT_MAPBOX_API_URL, NO_MAP_ID, EMPTY_MAPBOX_STYLE} from '@kepler.gl/constants';+import {DEFAULT_MAPBOX_API_URL, NO_MAP_ID, EMPTY_MAPBOX_STYLE, MapSplitMode} from '@kepler.gl/constants';import {FormattedMessage} from '@kepler.gl/localization';import {Viewport, ExportVideo, Effect} from '@kepler.gl/types';import {@@ -31,6 +31,8 @@ import {} from './hubble-utils';import {useFogHeightAnimation} from './fog-height-animation';+type SwipeContainerType = React.ComponentType<any>;+type HubbleModule = {ExportVideoPanelContainer: React.ComponentType<any>;KeplerUIContext: React.Context<any>;@@ -38,17 +40,23 @@ type HubbleModule = {let _hubbleModule: HubbleModule | null = null;let _hubblePromise: Promise<HubbleModule> | null = null;+let _swipeContainer: SwipeContainerType | null = null;function loadHubble(): Promise<HubbleModule> {if (_hubbleModule) return Promise.resolve(_hubbleModule);if (_hubblePromise) return _hubblePromise;_hubblePromise = import('@hubble.gl/react').then(- mod => {+ async mod => {_hubbleModule = mod as unknown as HubbleModule;+ try {+ const swipeMod = await import('./swipe-export-video-container');+ _swipeContainer = swipeMod.SwipeExportVideoPanelContainer;+ } catch (_err) {+ // swipe export unavailable; regular export still works+ }return _hubbleModule;},err => {- // Allow retry on next call_hubblePromise = null;throw err;}@@ -184,6 +192,9 @@ export type VideoConfiguration = {fileName?: string;resolution?: string;durationMs?: number;+ swipeStartPct?: number;+ swipeEndPct?: number;+ swipeEasing?: 'linear' | 'ease-in-out';};export interface ExportVideoModalProps {@@ -311,8 +322,13 @@ const ExportVideoModalFactory = () => {...exportVideo});const onUpdateVideoConfiguration = useCallback(- (values: VideoConfiguration) => setVideoConfiguration(prev => ({...prev, ...values})),- []+ (values: VideoConfiguration) => {+ setVideoConfiguration(prev => ({...prev, ...values}));+ if (values.swipeStartPct !== undefined || values.swipeEndPct !== undefined || values.swipeEasing !== undefined) {+ uiStateActions.setExportVideoSetting(values as any);+ }+ },+ [uiStateActions]);const hubbleContainerRef = useRef<any>(null);@@ -364,14 +380,22 @@ const ExportVideoModalFactory = () => {typeof window !== 'undefined' ? window.devicePixelRatio : 1);+ const isSwipeMode = mapState.mapSplitMode === MapSplitMode.SWIPE_COMPARE && mapState.isSplit;+useEffect(() => {+ // Block DPR changes during preview to keep basemap and deck.gl layers in sync.+ // hubble.gl sets window.devicePixelRatio to scale render buffers, but this causes+ // visual misalignment between MapLibre and DeckGL during animated preview.+ // Skip in swipe mode — the swipe preview manages its own DPR for canvas compositing.+ if (isSwipeMode) return;+const trueDpr = trueDevicePixelRatio.current;const descriptor = Object.getOwnPropertyDescriptor(window, 'devicePixelRatio');Object.defineProperty(window, 'devicePixelRatio', {get: () => trueDpr,set: () => {- // no-op: prevent hubble.gl from changing DPR+ // no-op: prevent hubble.gl from changing DPR during preview},configurable: true});@@ -383,7 +407,7 @@ const ExportVideoModalFactory = () => {delete (window as any).devicePixelRatio;}};- }, []);+ }, [isSwipeMode]);const onFilterFrameUpdate = useCallback((filterIdx: number, name: string, value: any) => {@@ -429,27 +453,52 @@ const ExportVideoModalFactory = () => {const {ExportVideoPanelContainer, KeplerUIContext} = hubble;+ const SwipeContainer = _swipeContainer;+return (<KeplerUIContext.Provider value={KEPLER_UI}><StyledExportVideoModalContent className="export-video-modal">- <ExportVideoPanelContainer- ref={hubbleContainerRef}- initialState={videoConfiguration}- mapData={keplerState}- onSettingsChange={onUpdateVideoConfiguration}- header={false}- handleClose={onClose}- exportVideoWidth={exportVideoWidth}- onFilterFrameUpdate={onFilterFrameUpdate}- onTripFrameUpdate={onTripFrameUpdate}- deckProps={deckPropsWithEffects}- mapProps={staticMapProps}- disableBaseMap={false}- mapboxLayerBeforeId={topLayer?.id}- defaultFileName={DEFAULT_FILENAME}- animatableFilters={animatableFilters}- getTimeRangeFilterKeyframes={getTimeRangeFilterKeyframes}- />+ {isSwipeMode && SwipeContainer ? (+ <SwipeContainer+ initialState={videoConfiguration}+ mapData={keplerState}+ onSettingsChange={onUpdateVideoConfiguration}+ header={false}+ handleClose={onClose}+ exportVideoWidth={exportVideoWidth}+ onFilterFrameUpdate={onFilterFrameUpdate}+ onTripFrameUpdate={onTripFrameUpdate}+ deckProps={deckPropsWithEffects}+ mapProps={staticMapProps}+ disableBaseMap={false}+ mapboxLayerBeforeId={topLayer?.id}+ defaultFileName={DEFAULT_FILENAME}+ animatableFilters={animatableFilters}+ getTimeRangeFilterKeyframes={getTimeRangeFilterKeyframes}+ swipeStartPct={exportVideo.swipeStartPct}+ swipeEndPct={exportVideo.swipeEndPct}+ swipeEasing={exportVideo.swipeEasing}+ />+ ) : (+ <ExportVideoPanelContainer+ ref={hubbleContainerRef}+ initialState={videoConfiguration}+ mapData={keplerState}+ onSettingsChange={onUpdateVideoConfiguration}+ header={false}+ handleClose={onClose}+ exportVideoWidth={exportVideoWidth}+ onFilterFrameUpdate={onFilterFrameUpdate}+ onTripFrameUpdate={onTripFrameUpdate}+ deckProps={deckPropsWithEffects}+ mapProps={staticMapProps}+ disableBaseMap={false}+ mapboxLayerBeforeId={topLayer?.id}+ defaultFileName={DEFAULT_FILENAME}+ animatableFilters={animatableFilters}+ getTimeRangeFilterKeyframes={getTimeRangeFilterKeyframes}+ />+ )}</StyledExportVideoModalContent></KeplerUIContext.Provider>);diff --git a/src/components/src/modals/hubble-utils.ts b/src/components/src/modals/hubble-utils.tsindex 21f1957d9..801df8216 100644--- a/src/components/src/modals/hubble-utils.ts+++ b/src/components/src/modals/hubble-utils.ts@@ -1,10 +1,12 @@// SPDX-License-Identifier: MIT// Copyright contributors to the kepler.gl project-import {MapView} from '@deck.gl/core';+import {MapView, WebMercatorViewport, type MapViewState} from '@deck.gl/core';import {DEFAULT_MAPBOX_API_URL, FILTER_VIEW_TYPES, FILTER_TYPES} from '@kepler.gl/constants';import {getLayerBlendingParameters, getBaseMapLibrary} from '@kepler.gl/utils';import {isMapboxURL, transformMapboxUrl} from 'maplibregl-mapbox-request-transformer';+import {point} from '@turf/helpers';+import transformTranslate from '@turf/transform-translate';import {TimeRangeFilter} from '@kepler.gl/types';type KeplerState = {@@ -196,3 +198,74 @@ export function getAnimatableFilters(keplerState: KeplerState): TimeRangeFilter[(f.view === FILTER_VIEW_TYPES.enlarged || f.syncedWithLayerTimeline));}++// --- Video export utilities (inlined from @hubble.gl internals) ---++export function scaleToVideoExport(+ viewState: MapViewState,+ container: {width: number; height: number}+): MapViewState & {width: number; height: number} {+ 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;+}++export function parseSetCameraType(strCameraType: string, viewState: MapViewState): MapViewState {+ const modifiedViewState: any = {...viewState};+ const match = strCameraType.match(/\b(?!to)\b\S+\w/g);+ if (!match) return modifiedViewState;++ const turfPoint = point([modifiedViewState.longitude, modifiedViewState.latitude]);++ if (match[0] === 'Orbit') {+ modifiedViewState.bearing = modifiedViewState.bearing + parseInt(match[1], 10);+ }++ const directions = new Set(['East', 'South', 'West', 'North']);+ if (directions.has(match[0])) {+ const directionMap: Record<string, number> = {East: 270, South: 0, West: 90, North: 180};+ const translatedPoly = transformTranslate(turfPoint, 10, directionMap[match[0]]);+ if (match[0] === 'East' || match[0] === 'West') {+ modifiedViewState.longitude = translatedPoly.geometry.coordinates[0];+ } else {+ modifiedViewState.latitude = translatedPoly.geometry.coordinates[1];+ }+ }++ if (match[0] === 'Zoom') {+ modifiedViewState.zoom += match[1] === 'In' ? 3 : -3;+ }++ return modifiedViewState;+}++type Resolution = {value: string; label: string; width: number; height: number};++const RESOLUTIONS: Resolution[] = [+ {value: '960x540', label: 'Good (540p)', width: 960, height: 540},+ {value: '1280x720', label: 'High (720p)', width: 1280, height: 720},+ {value: '1920x1080', label: 'Highest (1080p)', width: 1920, height: 1080},+ {value: '640x480', label: 'Good (480p)', width: 640, height: 480},+ {value: '1280x960', label: 'High (960p)', width: 1280, height: 960},+ {value: '1920x1440', label: 'Highest (1440p)', width: 1920, height: 1440}+];++export function getResolutionSetting(value: string): Resolution {+ return RESOLUTIONS.find(r => r.value === value) || RESOLUTIONS[0];+}diff --git a/src/components/src/modals/swipe-composite-utils.ts b/src/components/src/modals/swipe-composite-utils.tsnew file mode 100644index 000000000..d28513566--- /dev/null+++ b/src/components/src/modals/swipe-composite-utils.ts@@ -0,0 +1,119 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import {easeInOut} from 'popmotion';++export type SwipeEasing = 'linear' | 'ease-in-out';++const linear = (p: number): number => p;+const EASING_MAP: Record<SwipeEasing, (p: number) => number> = {+ linear,+ 'ease-in-out': easeInOut+};++/**+ * Compute the swipe percentage at a given time.+ */+export function getSwipePercentageAtTime(+ timeMs: number,+ durationMs: number,+ startPct: number,+ endPct: number,+ easing: SwipeEasing = 'ease-in-out'+): number {+ const progress = Math.max(0, Math.min(1, timeMs / durationMs));+ const easedProgress = EASING_MAP[easing](progress);+ return startPct + (endPct - startPct) * easedProgress;+}++const HANDLE_RADIUS = 14;+const ARROW_SIZE = 6;++/**+ * Draw a swipe divider (line + circular handle with arrows) onto a 2D canvas context.+ */+function drawSwipeDivider(+ ctx: CanvasRenderingContext2D,+ splitX: number,+ height: number+): void {+ ctx.save();++ // Divider line+ ctx.strokeStyle = '#FFFFFF';+ ctx.lineWidth = 2;+ ctx.shadowColor = 'rgba(0, 0, 0, 0.5)';+ ctx.shadowBlur = 4;+ ctx.beginPath();+ ctx.moveTo(splitX, 0);+ ctx.lineTo(splitX, height);+ ctx.stroke();++ // Handle circle+ const cy = height / 2;+ ctx.shadowBlur = 6;+ ctx.beginPath();+ ctx.arc(splitX, cy, HANDLE_RADIUS, 0, Math.PI * 2);+ ctx.fillStyle = '#29323C';+ ctx.fill();+ ctx.strokeStyle = '#FFFFFF';+ ctx.lineWidth = 2;+ ctx.stroke();+ ctx.shadowBlur = 0;++ // Left arrow+ ctx.fillStyle = '#FFFFFF';+ ctx.beginPath();+ ctx.moveTo(splitX - ARROW_SIZE - 3, cy);+ ctx.lineTo(splitX - 3, cy - ARROW_SIZE);+ ctx.lineTo(splitX - 3, cy + ARROW_SIZE);+ ctx.closePath();+ ctx.fill();++ // Right arrow+ ctx.beginPath();+ ctx.moveTo(splitX + ARROW_SIZE + 3, cy);+ ctx.lineTo(splitX + 3, cy - ARROW_SIZE);+ ctx.lineTo(splitX + 3, cy + ARROW_SIZE);+ ctx.closePath();+ ctx.fill();++ ctx.restore();+}++/**+ * Composite two canvases (left/right map views) with a swipe divider+ * into a single output canvas.+ */+export function compositeSwipeFrame(+ leftCanvas: HTMLCanvasElement,+ rightCanvas: HTMLCanvasElement,+ outputCanvas: HTMLCanvasElement,+ percentage: number,+ showDivider: boolean = true+): void {+ const ctx = outputCanvas.getContext('2d');+ if (!ctx) return;++ const w = outputCanvas.width;+ const h = outputCanvas.height;+ const splitX = Math.round((w * percentage) / 100);++ ctx.clearRect(0, 0, w, h);++ // Draw right (background) canvas fully+ ctx.drawImage(rightCanvas, 0, 0, w, h);++ // Draw left (foreground) canvas clipped to 0..splitX+ ctx.save();+ ctx.beginPath();+ ctx.rect(0, 0, splitX, h);+ ctx.clip();+ ctx.drawImage(leftCanvas, 0, 0, w, h);+ ctx.restore();++ // Draw the divider+ if (showDivider) {+ drawSwipeDivider(ctx, splitX, h);+ }+}diff --git a/src/components/src/modals/swipe-export-settings.tsx b/src/components/src/modals/swipe-export-settings.tsxnew file mode 100644index 000000000..5efce8863--- /dev/null+++ b/src/components/src/modals/swipe-export-settings.tsx@@ -0,0 +1,462 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import React, {ChangeEvent, useMemo, useState} from 'react';+import styled, {ThemeProvider, useTheme} from 'styled-components';+import {SwipeEasing} from './swipe-composite-utils';++import Slider from '../common/slider/slider';+import ItemSelector from '../common/item-selector/item-selector';+import {InputLight} from '../common/styled-components';++// --- Styled components matching the regular export video modal ---++const StyledModalTab = styled.div`+ display: flex;+ border-bottom: 1px solid ${props => props.theme.borderColorLT};+ margin-bottom: 16px;+`;++const StyledTabItem = styled.div`+ padding: 8px 16px;+ cursor: pointer;+ font-size: 14px;+ color: ${props => props.theme.subtextColorLT};+ border-bottom: 2px solid transparent;++ &.active {+ color: ${props => props.theme.textColorLT};+ border-bottom: 2px solid ${props => props.theme.textColorLT};+ font-weight: 500;+ }++ &:hover {+ color: ${props => props.theme.textColorLT};+ }+`;++const InputGrid = styled.div<{$rows?: number}>`+ display: grid;+ grid-template-columns: 100px 1fr;+ grid-row-gap: 12px;+ align-items: center;+`;++const StyledLabelCell = styled.div`+ font-size: 11px;+ font-weight: 500;+ color: ${props => props.theme.subtextColorLT};+`;++const StyledValueCell = styled.div`+ font-size: 11px;+ color: ${props => props.theme.textColorLT};+`;++const SliderWrapper = styled.div`+ display: flex;+ align-items: center;+ width: 100%;+`;++const VideoLengthDisplay = styled.span`+ font-size: 11px;+ color: ${props => props.theme.textColorLT};+ white-space: nowrap;+ margin-left: 8px;+ min-width: 42px;+`;++const SectionDivider = styled.div`+ margin: 14px 0 10px;+ padding-top: 10px;+ border-top: 1px solid ${props => props.theme.borderColorLT};+ font-size: 11px;+ font-weight: 600;+ color: ${props => props.theme.textColorLT};+ margin-bottom: 10px;+`;++const SLIDER_LIGHT_OVERRIDES = {+ sliderBarColor: '#A0A7B4',+ sliderBarBgd: '#D3D8E0',+ sliderBarHoverColor: '#939BA8',+ sliderHandleColor: '#F7F7F7',+ sliderHandleHoverColor: '#F7F7F7',+ sliderInactiveBorderColor: '#F7F7F7',+ sliderHandleTextColor: '#F7F7F7',+ sliderHandleShadow: '0 2px 4px 0 rgba(0,0,0,0.20)'+};++// --- Options ---++const EASING_OPTIONS = [+ {id: 'ease-in-out', label: 'Ease In-Out'},+ {id: 'linear', label: 'Linear'}+];++const FORMAT_OPTIONS = [+ {value: 'gif', label: 'GIF'},+ {value: 'webm', label: 'WebM Video'},+ {value: 'png', label: 'PNG Sequence'},+ {value: 'jpeg', label: 'JPEG Sequence'}+];++const DEFAULT_PREVIEW_RESOLUTIONS: Record<string, string> = {'16:9': '1280x720', '4:3': '1280x960'};++const RESOLUTION_OPTIONS = [+ {value: '960x540', label: 'Good (540p)', aspectRatio: '16:9'},+ {value: '1280x720', label: 'High (720p)', aspectRatio: '16:9'},+ {value: '1920x1080', label: 'Highest (1080p)', aspectRatio: '16:9'},+ {value: '640x480', label: 'Good (480p)', aspectRatio: '4:3'},+ {value: '1280x960', label: 'High (960p)', aspectRatio: '4:3'},+ {value: '1920x1440', label: 'Highest (1440p)', aspectRatio: '4:3'}+];++const CAMERA_PRESETS = [+ 'None',+ 'Orbit (90º)',+ 'Orbit (180º)',+ 'Orbit (360º)',+ 'Zoom Out',+ 'Zoom In'+];++// --- Types ---++export type SwipeExportSettingsProps = {+ durationMs: number;+ mediaType: string;+ resolution: string;+ fileName: string;+ cameraPreset: string;+ frameRate: number;+ onChangeDuration: (value: number) => void;+ onChangeMediaType: (value: string) => void;+ onChangeResolution: (value: string) => void;+ onChangeFileName: (value: string) => void;+ onChangeCameraPreset: (value: string) => void;+ swipeStartPct: number;+ swipeEndPct: number;+ swipeEasing: SwipeEasing;+ disabled: boolean;+ onChangeStartPct: (value: number) => void;+ onChangeEndPct: (value: number) => void;+ onChangeEasing: (value: SwipeEasing) => void;+};++// --- Utilities ---++function printDuration(durationMs: number): string {+ const seconds = Math.floor(durationMs / 1000) % 60;+ const minutes = Math.floor(durationMs / 60000);+ const ms = Math.floor((durationMs % 1000) / 100);+ const hh = minutes > 0 ? `${minutes}:` : '';+ return `${hh}${seconds < 10 ? '0' : ''}${seconds}.${ms}`;+}++function estimateFileSize(+ frameRate: number,+ resolution: [number, number],+ durationMs: number,+ mediaType: string+): string {+ const MB = 8 * 1024 * 1024;+ const seconds = Math.floor(durationMs / 1000);+ const COMPRESSION_RATIO = 0.8;+ const BIT_DEPTH = 6;++ if (mediaType === 'gif' || mediaType === 'png') {+ return `${Math.floor(+ ((resolution[0] * resolution[1] * BIT_DEPTH) / MB) * (frameRate * seconds) * COMPRESSION_RATIO+ )} MB`;+ }+ if (mediaType === 'webm') {+ return `${Math.ceil((resolution[0] / 1280) * frameRate * seconds * 0.125)} MB`;+ }+ if (mediaType === 'jpeg') {+ return `${Math.floor(+ ((resolution[0] * resolution[1] * BIT_DEPTH) / MB) * (frameRate * seconds) * 0.4+ )} MB`;+ }+ return '—';+}++// --- Sub-components ---++const LightSlider: React.FC<any> = props => {+ const theme = useTheme();+ const lightTheme = useMemo(() => ({...theme, ...SLIDER_LIGHT_OVERRIDES}), [theme]);+ return (+ <ThemeProvider theme={lightTheme}>+ <Slider {...props} />+ </ThemeProvider>+ );+};++const LightItemSelector: React.FC<any> = props => (+ <ItemSelector {...props} inputTheme="light" />+);++const getOptionValue = (o: any) => o.value;+const displayOption = (o: any) => o.label;++// --- Animation Tab ---++const AnimationTab: React.FC<{+ durationMs: number;+ cameraPreset: string;+ swipeStartPct: number;+ swipeEndPct: number;+ swipeEasing: SwipeEasing;+ disabled: boolean;+ onChangeDuration: (value: number) => void;+ onChangeCameraPreset: (value: string) => void;+ onChangeStartPct: (value: number) => void;+ onChangeEndPct: (value: number) => void;+ onChangeEasing: (value: SwipeEasing) => void;+}> = ({+ durationMs,+ cameraPreset,+ swipeStartPct,+ swipeEndPct,+ swipeEasing,+ disabled,+ onChangeDuration,+ onChangeCameraPreset,+ onChangeStartPct,+ onChangeEndPct,+ onChangeEasing+}) => (+ <>+ <InputGrid>+ <StyledLabelCell>Duration</StyledLabelCell>+ <StyledValueCell>+ <SliderWrapper>+ <LightSlider+ showValues={false}+ enableBarDrag={!disabled}+ isRanged={false}+ value0={100}+ value1={durationMs}+ step={100}+ minValue={100}+ maxValue={10000}+ onSlider1Change={(v: number) => { if (!disabled) onChangeDuration(v); }}+ />+ <VideoLengthDisplay>{printDuration(durationMs)}</VideoLengthDisplay>+ </SliderWrapper>+ </StyledValueCell>++ <StyledLabelCell>Camera</StyledLabelCell>+ <LightItemSelector+ selectedItems={cameraPreset}+ options={CAMERA_PRESETS}+ multiSelect={false}+ searchable={false}+ onChange={onChangeCameraPreset}+ disabled={disabled}+ />+ </InputGrid>++ <SectionDivider>Swipe</SectionDivider>+ <InputGrid>+ <StyledLabelCell>Start ({Math.round(swipeStartPct)}%)</StyledLabelCell>+ <LightSlider+ showValues={false}+ isRanged={false}+ value1={swipeStartPct}+ minValue={0}+ maxValue={100}+ step={1}+ onSlider1Change={(v: number) => { if (!disabled) onChangeStartPct(v); }}+ disabled={disabled}+ />++ <StyledLabelCell>End ({Math.round(swipeEndPct)}%)</StyledLabelCell>+ <LightSlider+ showValues={false}+ isRanged={false}+ value1={swipeEndPct}+ minValue={0}+ maxValue={100}+ step={1}+ onSlider1Change={(v: number) => { if (!disabled) onChangeEndPct(v); }}+ disabled={disabled}+ />++ <StyledLabelCell>Easing</StyledLabelCell>+ <LightItemSelector+ selectedItems={EASING_OPTIONS.find(o => o.id === swipeEasing) || EASING_OPTIONS[0]}+ options={EASING_OPTIONS}+ multiSelect={false}+ searchable={false}+ onChange={(val: any) => onChangeEasing(val?.id || val)}+ disabled={disabled}+ getOptionValue={(o: any) => o.id}+ displayOption={(o: any) => o.label}+ />+ </InputGrid>+ </>+);++// --- Settings Tab (identical to regular export) ---++const SettingsTab: React.FC<{+ fileName: string;+ mediaType: string;+ resolution: string;+ frameRate: number;+ durationMs: number;+ disabled: boolean;+ onChangeFileName: (value: string) => void;+ onChangeMediaType: (value: string) => void;+ onChangeResolution: (value: string) => void;+}> = ({+ fileName,+ mediaType,+ resolution,+ frameRate,+ durationMs,+ disabled,+ onChangeFileName,+ onChangeMediaType,+ onChangeResolution+}) => {+ const [aspRatio, setAspRatio] = useState<string>('16:9');++ const resolutionParts = resolution.split('x').map(Number);+ const currentResolution: [number, number] = [resolutionParts[0] || 1280, resolutionParts[1] || 720];++ return (+ <InputGrid>+ <StyledLabelCell>File Name</StyledLabelCell>+ <InputLight+ value={fileName}+ placeholder="kepler.gl"+ onChange={(e: ChangeEvent<HTMLInputElement>) => onChangeFileName(e.target.value)}+ disabled={disabled}+ />++ <StyledLabelCell>Media Type</StyledLabelCell>+ <LightItemSelector+ selectedItems={FORMAT_OPTIONS.find(o => o.value === mediaType) || FORMAT_OPTIONS[0]}+ options={FORMAT_OPTIONS}+ multiSelect={false}+ searchable={false}+ onChange={(val: any) => onChangeMediaType(val?.value || val)}+ disabled={disabled}+ getOptionValue={getOptionValue}+ displayOption={displayOption}+ />++ <StyledLabelCell>Ratio</StyledLabelCell>+ <LightItemSelector+ selectedItems={aspRatio}+ options={['4:3', '16:9']}+ multiSelect={false}+ searchable={false}+ onChange={(ratio: string) => {+ setAspRatio(ratio);+ onChangeResolution(DEFAULT_PREVIEW_RESOLUTIONS[ratio]);+ }}+ disabled={disabled}+ />++ <StyledLabelCell>Quality</StyledLabelCell>+ <LightItemSelector+ selectedItems={RESOLUTION_OPTIONS.find(o => o.value === resolution) || RESOLUTION_OPTIONS[1]}+ options={RESOLUTION_OPTIONS.filter(o => o.aspectRatio === aspRatio)}+ multiSelect={false}+ searchable={false}+ onChange={(val: any) => onChangeResolution(val?.value || val)}+ disabled={disabled}+ getOptionValue={getOptionValue}+ displayOption={displayOption}+ />++ <StyledLabelCell>File Size</StyledLabelCell>+ <StyledValueCell>+ Approx. {estimateFileSize(frameRate, currentResolution, durationMs, mediaType)}+ </StyledValueCell>+ </InputGrid>+ );+};++// --- Main Component ---++type TabId = 'animation' | 'settings';++const SwipeExportSettings: React.FC<SwipeExportSettingsProps> = ({+ durationMs,+ mediaType,+ resolution,+ fileName,+ cameraPreset,+ frameRate,+ onChangeDuration,+ onChangeMediaType,+ onChangeResolution,+ onChangeFileName,+ onChangeCameraPreset,+ swipeStartPct,+ swipeEndPct,+ swipeEasing,+ disabled,+ onChangeStartPct,+ onChangeEndPct,+ onChangeEasing+}) => {+ const [activeTab, setActiveTab] = useState<TabId>('animation');++ return (+ <div>+ <StyledModalTab>+ <StyledTabItem+ className={activeTab === 'animation' ? 'active' : ''}+ onClick={() => setActiveTab('animation')}+ >+ Animation+ </StyledTabItem>+ <StyledTabItem+ className={activeTab === 'settings' ? 'active' : ''}+ onClick={() => setActiveTab('settings')}+ >+ Settings+ </StyledTabItem>+ </StyledModalTab>++ {activeTab === 'animation' && (+ <AnimationTab+ durationMs={durationMs}+ cameraPreset={cameraPreset}+ swipeStartPct={swipeStartPct}+ swipeEndPct={swipeEndPct}+ swipeEasing={swipeEasing}+ disabled={disabled}+ onChangeDuration={onChangeDuration}+ onChangeCameraPreset={onChangeCameraPreset}+ onChangeStartPct={onChangeStartPct}+ onChangeEndPct={onChangeEndPct}+ onChangeEasing={onChangeEasing}+ />+ )}++ {activeTab === 'settings' && (+ <SettingsTab+ fileName={fileName}+ mediaType={mediaType}+ resolution={resolution}+ frameRate={frameRate}+ durationMs={durationMs}+ disabled={disabled}+ onChangeFileName={onChangeFileName}+ onChangeMediaType={onChangeMediaType}+ onChangeResolution={onChangeResolution}+ />+ )}+ </div>+ );+};++export default SwipeExportSettings;diff --git a/src/components/src/modals/swipe-export-video-container.tsx b/src/components/src/modals/swipe-export-video-container.tsxnew file mode 100644index 000000000..ae97ab6a6--- /dev/null+++ b/src/components/src/modals/swipe-export-video-container.tsx@@ -0,0 +1,603 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import React, {Component, createRef} from 'react';+import {easeInOut} from 'popmotion';+import download from 'downloadjs';+import styled from 'styled-components';+import {Button} from '../common';+import {+ DeckAdapter,+ KeplerAnimation,+ WebMEncoder,+ JPEGSequenceEncoder,+ PNGSequenceEncoder,+ GifEncoder,+ FormatConfigs,+ Timecode+} from '@hubble.gl/core';+import type {DeckProps, MapViewState} from '@deck.gl/core';+import {FILTER_VIEW_TYPES} from '@kepler.gl/constants';++import {parseSetCameraType, scaleToVideoExport, getResolutionSetting} from './hubble-utils';+import {SwipeExportVideoPreview} from './swipe-export-video-preview';+import SwipeExportSettings from './swipe-export-settings';+import {SwipeEasing} from './swipe-composite-utils';++const ENCODERS = {+ gif: GifEncoder,+ webm: WebMEncoder,+ jpeg: JPEGSequenceEncoder,+ png: PNGSequenceEncoder+};++export type SwipeExportVideoSettings = {+ mediaType?: string;+ cameraPreset?: string;+ fileName?: string;+ resolution?: string;+ durationMs?: number;+ swipeStartPct?: number;+ swipeEndPct?: number;+ swipeEasing?: SwipeEasing;+};++type SwipeExportVideoPanelContainerProps = {+ initialState?: Partial<SwipeExportVideoPanelContainerState>;+ glContext?: WebGL2RenderingContext;+ exportVideoWidth: number;+ handleClose: () => void;+ mapData: any;+ header: boolean;+ deckProps?: DeckProps;+ mapProps: Record<string, any>;+ disableBaseMap: boolean;+ mapboxLayerBeforeId?: string;+ defaultFileName: string;+ animatableFilters: any;+ onTripFrameUpdate: (value: any) => void;+ onFilterFrameUpdate: (filterIdx: number, name: string, value: any) => void;+ getTimeRangeFilterKeyframes: (args: any) => any;+ onSettingsChange: (settings: SwipeExportVideoSettings) => void;+ swipeStartPct: number;+ swipeEndPct: number;+ swipeEasing: SwipeEasing;+};++type SwipeExportVideoPanelContainerState = {+ adapter?: DeckAdapter;+ durationMs: number;+ mediaType: string;+ cameraPreset: string;+ fileName: string;+ resolution: string;+ viewState?: MapViewState;+ rendering: boolean;+ previewing: boolean;+ saving: boolean;+ currentTimeMs: number;+ memo?: {viewState: MapViewState};+};++const PanelBody = styled.div<{$exportVideoWidth: number}>`+ display: grid;+ grid-template-columns: ${props => props.$exportVideoWidth}px 280px;+ grid-template-rows: auto;+ grid-column-gap: 24px;+`;++const TimelineControls = styled.div`+ position: relative;+ display: flex;+ justify-content: center;+ padding-top: 16px;+`;++const timelinePlayButtonStyle = {+ cursor: 'pointer',+ height: '32px',+ width: '32px',+ fill: '#FFF'+};++const ButtonGroup = styled.div`+ display: flex;+`;++const StatusText = styled.div`+ font-size: 11px;+ color: ${props => props.theme.subtextColorLT || '#6A7485'};+ text-align: center;+ margin-top: 4px;+`;++const PlayIcon: React.FC<{style?: React.CSSProperties; onClick?: () => void}> = ({style, onClick}) => (+ <svg+ className="data-ex-icons-play"+ viewBox="0 0 24 24"+ style={style}+ onClick={onClick}+ >+ <path fill="none" d="M0 0h24v24H0z" />+ <path d="M19.376 12.416L8.777 19.482A.5.5 0 0 1 8 19.066V4.934a.5.5 0 0 1 .777-.416l10.599 7.066a.5.5 0 0 1 0 .832z" />+ </svg>+);++const StopIcon: React.FC<{style?: React.CSSProperties; onClick?: () => void}> = ({style, onClick}) => (+ <svg+ className="data-ex-icons-stop"+ viewBox="0 0 24 24"+ style={style}+ onClick={onClick}+ >+ <path fill="none" d="M0 0h24v24H0z" />+ <path d="M6 5h12a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1z" />+ </svg>+);++/**+ * Orchestrates swipe video export recording.+ * Manages a DeckAdapter but overrides the capture pipeline to+ * composite left/right canvases with an animated swipe divider.+ */+export class SwipeExportVideoPanelContainer extends Component<+ SwipeExportVideoPanelContainerProps,+ SwipeExportVideoPanelContainerState+> {+ previewRef = createRef<SwipeExportVideoPreview>();+ animationFrameId: number | null = null;+ activeEncoder: any | null = null;++ constructor(props: SwipeExportVideoPanelContainerProps) {+ super(props);++ const {+ initialState,+ mapData: {mapState},+ glContext+ } = props;++ this.state = {+ mediaType: 'webm',+ cameraPreset: 'None',+ fileName: '',+ resolution: '1280x720',+ durationMs: 1000,+ rendering: false,+ previewing: false,+ saving: false,+ currentTimeMs: 0,+ ...(initialState || {})+ };++ const viewState = scaleToVideoExport(mapState, this._getContainer());+ this.state = {+ ...this.state,+ viewState,+ memo: {viewState},+ adapter: new DeckAdapter({glContext})+ };+ }++ componentDidMount() {+ const {onTripFrameUpdate, onFilterFrameUpdate, getTimeRangeFilterKeyframes} = this.props;+ const animation = new KeplerAnimation({+ ...this.getFilterKeyframes(),+ ...this.getTripKeyframes(),+ cameraKeyframe: this.getCameraKeyframes(),+ onCameraFrameUpdate: this.setViewState as any,+ onTripFrameUpdate,+ onFilterFrameUpdate,+ getTimeRangeFilterKeyframes+ });+ this.state.adapter!.animationManager.attachAnimation(animation);+ }++ componentWillUnmount() {+ this.onStop({abort: true});+ if (this.animationFrameId) {+ cancelAnimationFrame(this.animationFrameId);+ }+ }++ getFileName() {+ const {defaultFileName} = this.props;+ const {fileName} = this.state;+ return fileName || defaultFileName;+ }++ getCanvasSize() {+ const {resolution} = this.state;+ const {width, height} = getResolutionSetting(resolution);+ return {width, height};+ }++ _getContainer() {+ const {width, height} = this.getCanvasSize();+ const {exportVideoWidth} = this.props;+ const aspectRatio = width / height;+ return {height: exportVideoWidth / aspectRatio, width: exportVideoWidth};+ }++ getFormatConfigs(): Partial<FormatConfigs> {+ const {width, height} = this.getCanvasSize();+ return {+ webm: {quality: 0.8},+ jpeg: {quality: 0.8},+ png: {},+ gif: {sampleInterval: 1000, width, height}+ };+ }++ getTimecode(): Timecode {+ const {durationMs} = this.state;+ return {start: 0, end: durationMs, framerate: 30};+ }++ getEncoder() {+ const {mediaType} = this.state;+ return ENCODERS[mediaType];+ }++ getCameraKeyframes() {+ const {viewState, cameraPreset, durationMs} = this.state;+ const {longitude, latitude, zoom, pitch, bearing} = viewState!;+ const {width, height} = this.getCanvasSize();+ return {+ timings: [0, durationMs],+ keyframes: [+ {longitude, latitude, zoom, pitch, bearing},+ parseSetCameraType(cameraPreset, viewState!)+ ],+ easings: [easeInOut],+ width,+ height+ };+ }++ getFilterKeyframes() {+ const {+ mapData: {visState: {filters}},+ animatableFilters+ } = this.props;++ const filterKeyframes = (+ Array.isArray(animatableFilters) && animatableFilters.length+ ? animatableFilters+ : filters.filter((f: any) => f.type === 'timeRange' && f.view === FILTER_VIEW_TYPES.enlarged)+ ).map((f: any) => ({+ id: f.id,+ timings: [0, this.state.durationMs]+ }));++ if (filterKeyframes.length) {+ return {filters, filterKeyframes};+ }+ return {};+ }++ getTripKeyframes() {+ const {+ mapData: {visState: {layers, animationConfig}}+ } = this.props;++ const animatableLayer = layers.filter(+ (l: any) => l.config.animation && l.config.animation.enabled && l.config.isVisible+ );+ const readyToAnimation =+ Array.isArray(animationConfig.domain) && Number.isFinite(animationConfig.currentTime);+ if (animatableLayer.length && readyToAnimation) {+ return {+ animationConfig,+ tripKeyframe: {timings: [0, this.state.durationMs]}+ };+ }+ return {};+ }++ setViewState = (viewState: MapViewState) => {+ this.setState({viewState});+ };++ setStateAndNotify(update: SwipeExportVideoSettings) {+ const {onSettingsChange} = this.props;+ const {mediaType, cameraPreset, fileName, resolution, durationMs} = this.state;+ this.setState({...this.state, ...update} as any);+ if (onSettingsChange) {+ onSettingsChange({mediaType, cameraPreset, fileName, resolution, durationMs, ...update});+ }+ }++ setMediaType = (mediaType: string) => this.setStateAndNotify({mediaType});+ setCameraPreset = (cameraPreset: string) => this.setStateAndNotify({cameraPreset});+ setFileName = (fileName: string) => this.setStateAndNotify({fileName});+ setResolution = (resolution: string) => this.setStateAndNotify({resolution});+ setDuration = (durationMs: number) => this.setStateAndNotify({durationMs});++ /**+ * Start a preview playback — animates the swipe without encoding.+ */+ onPreviewVideo = () => {+ const {adapter, durationMs} = this.state;+ this.setState({+ previewing: true,+ currentTimeMs: 0,+ memo: {viewState: {...this.state.viewState!}}+ });++ adapter!.animationManager.setKeyframes('kepler', {+ ...this.getFilterKeyframes(),+ ...this.getTripKeyframes(),+ cameraKeyframe: this.getCameraKeyframes()+ });++ const startTime = performance.now();+ const animate = () => {+ const elapsed = performance.now() - startTime;+ const currentTimeMs = Math.min(elapsed, durationMs);++ adapter!.animationManager.timeline.setTime(currentTimeMs);+ adapter!.animationManager.draw();++ this.setState({currentTimeMs});++ if (currentTimeMs >= durationMs) {+ this.setState({+ previewing: false,+ currentTimeMs: 0,+ viewState: {...this.state.memo!.viewState}+ });+ return;+ }+ this.animationFrameId = requestAnimationFrame(animate);+ };+ this.animationFrameId = requestAnimationFrame(animate);+ };++ /**+ * Start actual recording — captures composited frames into the encoder.+ * Uses a timer-based approach: updates currentTimeMs, waits for the preview+ * to composite, then captures the composite canvas.+ */+ onRenderVideo = () => {+ const {adapter} = this.state;+ const filename = this.getFileName();+ const Encoder = this.getEncoder();+ const formatConfigs = this.getFormatConfigs();+ const timecode = this.getTimecode();+ const {width, height} = this.getCanvasSize();++ this.setState({+ rendering: true,+ saving: false,+ currentTimeMs: 0,+ memo: {viewState: {...this.state.viewState!}}+ });++ adapter!.animationManager.setKeyframes('kepler', {+ ...this.getFilterKeyframes(),+ ...this.getTripKeyframes(),+ cameraKeyframe: this.getCameraKeyframes()+ });++ const encoder = new Encoder({...formatConfigs, framerate: timecode.framerate});+ this.activeEncoder = encoder;+ encoder.start();++ const frameLengthMs = Math.floor(1000 / timecode.framerate);+ let timeMs = timecode.start;+ let retryCount = 0;+ const MAX_RETRIES = 10;++ const captureNextFrame = () => {+ if (!this.state.rendering || this.activeEncoder !== encoder) return;++ adapter!.animationManager.timeline.setTime(timeMs);+ adapter!.animationManager.draw();+ this.setState({currentTimeMs: timeMs});++ // Allow 3 frames for state update → preview re-render → composite+ const waitAndCapture = () => {+ requestAnimationFrame(() => {+ if (this.activeEncoder !== encoder) return;+ requestAnimationFrame(() => {+ if (this.activeEncoder !== encoder) return;+ requestAnimationFrame(() => {+ if (this.activeEncoder !== encoder) return;+ const preview = this.previewRef.current;+ if (!preview) return;++ // Use the composite canvas that the preview already updates+ const compositeCanvas = preview.getCompositeCanvas();+ if (!compositeCanvas) return;++ // Check if the canvas has any content (not blank)+ const ctx = compositeCanvas.getContext('2d');+ if (!ctx) return;++ let hasContent = true;+ try {+ const pixel = ctx.getImageData(0, 0, 1, 1).data;+ hasContent = pixel[0] !== 0 || pixel[1] !== 0 || pixel[2] !== 0 || pixel[3] !== 0;+ } catch {+ // Canvas may be tainted by cross-origin resources; assume content exists+ }++ if (!hasContent && retryCount < MAX_RETRIES) {+ retryCount++;+ // Trigger composite manually and retry+ preview._compositeFrame();+ requestAnimationFrame(waitAndCapture);+ return;+ }+ retryCount = 0;++ // Capture the composite canvas at target resolution+ const offscreen = document.createElement('canvas');+ offscreen.width = width;+ offscreen.height = height;+ const offCtx = offscreen.getContext('2d');+ if (offCtx) {+ offCtx.drawImage(compositeCanvas, 0, 0, width, height);+ }++ encoder.add(offscreen).then(() => {+ if (this.activeEncoder !== encoder) return;+ timeMs += frameLengthMs;+ if (timeMs > timecode.end) {+ this.setState({saving: true});+ encoder.save().then((blob: Blob | null) => {+ if (this.activeEncoder !== encoder) return;+ if (blob) {+ download(blob, filename + encoder.extension, encoder.mimeType);+ }+ this.setState({+ rendering: false,+ saving: false,+ currentTimeMs: 0,+ viewState: {...this.state.memo!.viewState}+ });+ });+ } else {+ captureNextFrame();+ }+ });+ });+ });+ });+ };++ waitAndCapture();+ };++ // Wait for maps to be ready before starting capture+ setTimeout(() => captureNextFrame(), 500);+ };++ onStop = ({abort = false}: {abort?: boolean} = {}) => {+ if (this.animationFrameId) {+ cancelAnimationFrame(this.animationFrameId);+ this.animationFrameId = null;+ }+ this.activeEncoder = null;+ if (!abort) {+ this.setState({+ rendering: false,+ previewing: false,+ currentTimeMs: 0,+ viewState: this.state.memo?.viewState || this.state.viewState+ });+ }+ };++ render() {+ const {+ exportVideoWidth,+ mapData,+ deckProps,+ mapProps,+ disableBaseMap,+ mapboxLayerBeforeId,+ swipeStartPct,+ swipeEndPct,+ swipeEasing,+ onSettingsChange+ } = this.props;++ const {+ adapter,+ durationMs,+ mediaType,+ cameraPreset,+ fileName,+ resolution,+ viewState,+ rendering,+ previewing,+ saving,+ currentTimeMs+ } = this.state;++ const timecode = this.getTimecode();+ let canvasSize = this.getCanvasSize();+ if (previewing) {+ canvasSize = this._getContainer();+ }++ const isActive = rendering || previewing;++ return (+ <div className="export-video-panel">+ <PanelBody $exportVideoWidth={exportVideoWidth}>+ <SwipeExportVideoPreview+ ref={this.previewRef}+ mapData={mapData}+ adapter={adapter!}+ setViewState={this.setViewState}+ exportVideoWidth={exportVideoWidth}+ resolution={[canvasSize.width, canvasSize.height]}+ viewState={viewState!}+ rendering={rendering}+ saving={saving}+ durationMs={durationMs}+ deckProps={deckProps}+ mapProps={mapProps}+ disableBaseMap={disableBaseMap}+ mapboxLayerBeforeId={mapboxLayerBeforeId}+ swipeStartPct={swipeStartPct}+ swipeEndPct={swipeEndPct}+ swipeEasing={swipeEasing}+ currentTimeMs={currentTimeMs}+ />+ <SwipeExportSettings+ durationMs={durationMs}+ mediaType={mediaType}+ resolution={resolution}+ fileName={fileName}+ cameraPreset={cameraPreset}+ frameRate={timecode.framerate}+ onChangeDuration={this.setDuration}+ onChangeMediaType={this.setMediaType}+ onChangeResolution={this.setResolution}+ onChangeFileName={this.setFileName}+ onChangeCameraPreset={this.setCameraPreset}+ swipeStartPct={swipeStartPct}+ swipeEndPct={swipeEndPct}+ swipeEasing={swipeEasing}+ disabled={isActive}+ onChangeStartPct={(value: number) =>+ onSettingsChange({swipeStartPct: value})+ }+ onChangeEndPct={(value: number) =>+ onSettingsChange({swipeEndPct: value})+ }+ onChangeEasing={(value: SwipeEasing) =>+ onSettingsChange({swipeEasing: value})+ }+ />+ <TimelineControls className="timeline-controls">+ {isActive ? (+ <StopIcon style={timelinePlayButtonStyle} onClick={() => this.onStop({})} />+ ) : (+ <PlayIcon style={timelinePlayButtonStyle} onClick={this.onPreviewVideo} />+ )}+ </TimelineControls>+ {saving && <StatusText>Saving...</StatusText>}+ {rendering && !saving && (+ <StatusText>Rendering... {Math.round((currentTimeMs / durationMs) * 100)}%</StatusText>+ )}+ <ButtonGroup>+ <Button+ style={{marginTop: '16px', width: '100%', height: '32px'}}+ className="export-video-button"+ onClick={this.onRenderVideo}+ disabled={isActive}+ >+ Render+ </Button>+ </ButtonGroup>+ </PanelBody>+ </div>+ );+ }+}diff --git a/src/components/src/modals/swipe-export-video-preview.tsx b/src/components/src/modals/swipe-export-video-preview.tsxnew file mode 100644index 000000000..673455f69--- /dev/null+++ b/src/components/src/modals/swipe-export-video-preview.tsx@@ -0,0 +1,322 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import React, {Component, RefObject, forwardRef, ForwardedRef} from 'react';+import DeckGL from '@deck.gl/react';+import ReactMapGL, {type MapRef, useControl} from 'react-map-gl/maplibre';+// @ts-ignore module resolution mismatch with moduleResolution:"node"+import {MapboxOverlay} from '@deck.gl/mapbox';+import type {Deck, DeckProps, MapViewState} from '@deck.gl/core';+import isEqual from 'lodash.isequal';+import styled from 'styled-components';++import {DeckAdapter} from '@hubble.gl/core';+import {createKeplerLayers} from '@hubble.gl/react';+import {compositeSwipeFrame, getSwipePercentageAtTime, SwipeEasing} from './swipe-composite-utils';++function setRef<T>(ref: React.Ref<T> | React.MutableRefObject<T>, value: T) {+ if (typeof ref === 'function') {+ ref(value);+ } else if (ref) {+ (ref as React.MutableRefObject<T>).current = value;+ }+}++const DeckGLOverlay = forwardRef<Deck, any>(+ (props: any, ref: ForwardedRef<Deck>) => {+ const overlay = useControl<MapboxOverlay>(() => new MapboxOverlay({...props, interleaved: true}));+ overlay.setProps(props);+ setRef(ref, (overlay as any)._deck);+ return null;+ }+);+DeckGLOverlay.displayName = 'DeckGLOverlay';++const PreviewContainer = styled.div<{$width: number; $height: number}>`+ width: ${props => props.$width}px;+ height: ${props => props.$height}px;+ position: relative;+`;++const VisibleCanvas = styled.canvas<{$width: number; $height: number}>`+ width: ${props => props.$width}px;+ height: ${props => props.$height}px;+ display: block;+ position: relative;+ z-index: 1;+`;++const MapLayer = styled.div<{$width: number; $height: number}>`+ width: ${props => props.$width}px;+ height: ${props => props.$height}px;+ position: absolute;+ top: 0;+ left: 0;+ opacity: 0;+ pointer-events: none;+ z-index: 0;+`;++export type SwipeExportVideoPreviewProps = {+ mapData: any;+ resolution: [number, number];+ exportVideoWidth: number;+ disableBaseMap: boolean;+ deckProps?: DeckProps;+ viewState: MapViewState;+ adapter: DeckAdapter;+ mapboxLayerBeforeId?: string;+ rendering: boolean;+ saving: boolean;+ setViewState: (viewState: MapViewState) => void;+ durationMs: number;+ mapProps?: Record<string, any>;+ swipeStartPct: number;+ swipeEndPct: number;+ swipeEasing: SwipeEasing;+ currentTimeMs: number;+};++type SwipeExportVideoPreviewState = {+ leftReady: boolean;+ rightReady: boolean;+};++/**+ * A dual-canvas video export preview that renders left/right split map layers+ * and composites them with an animated swipe divider.+ */+export class SwipeExportVideoPreview extends Component<+ SwipeExportVideoPreviewProps,+ SwipeExportVideoPreviewState+> {+ leftMapRef: RefObject<MapRef> = React.createRef<MapRef>();+ rightMapRef: RefObject<MapRef> = React.createRef<MapRef>();+ leftDeckRef: RefObject<Deck> = React.createRef<Deck>();+ rightDeckRef: RefObject<Deck> = React.createRef<Deck>();+ compositeCanvasRef: RefObject<HTMLCanvasElement> = React.createRef<HTMLCanvasElement>();++ constructor(props: SwipeExportVideoPreviewProps) {+ super(props);++ this.state = {+ leftReady: false,+ rightReady: false+ };++ this._resizeVideo();+ }++ componentDidUpdate(prevProps: SwipeExportVideoPreviewProps) {+ if (!isEqual(prevProps.resolution, this.props.resolution)) {+ this._resizeVideo();+ }++ if (+ prevProps.currentTimeMs !== this.props.currentTimeMs ||+ prevProps.swipeStartPct !== this.props.swipeStartPct ||+ prevProps.swipeEndPct !== this.props.swipeEndPct ||+ prevProps.swipeEasing !== this.props.swipeEasing+ ) {+ this._compositeFrame();+ }+ }++ _resizeVideo() {+ const {exportVideoWidth, resolution} = this.props;+ this._setDevicePixelRatio(resolution[0] / exportVideoWidth);+ }++ _setDevicePixelRatio(devicePixelRatio: number) {+ // @ts-ignore+ window.devicePixelRatio = devicePixelRatio;+ }++ _getContainer() {+ const {exportVideoWidth, resolution} = this.props;+ const aspectRatio = resolution[0] / resolution[1];+ return {height: exportVideoWidth / aspectRatio, width: exportVideoWidth};+ }++ _getCurrentSwipePercentage(): number {+ const {currentTimeMs, durationMs, swipeStartPct, swipeEndPct, swipeEasing} = this.props;+ return getSwipePercentageAtTime(currentTimeMs, durationMs, swipeStartPct, swipeEndPct, swipeEasing);+ }++ _getLeftCanvas(): HTMLCanvasElement | null {+ if (this.leftMapRef.current) {+ return this.leftMapRef.current.getMap().getCanvas();+ }+ // Fallback: DeckGL canvas (no basemap mode)+ if (this.leftDeckRef.current) {+ return (this.leftDeckRef.current as any).getCanvas?.() || null;+ }+ return null;+ }++ _getRightCanvas(): HTMLCanvasElement | null {+ if (this.rightMapRef.current) {+ return this.rightMapRef.current.getMap().getCanvas();+ }+ if (this.rightDeckRef.current) {+ return (this.rightDeckRef.current as any).getCanvas?.() || null;+ }+ return null;+ }++ _compositeFrame() {+ const leftCanvas = this._getLeftCanvas();+ const rightCanvas = this._getRightCanvas();+ const outputCanvas = this.compositeCanvasRef.current;++ if (!leftCanvas || !rightCanvas || !outputCanvas) return;++ const percentage = this._getCurrentSwipePercentage();+ compositeSwipeFrame(leftCanvas, rightCanvas, outputCanvas, percentage, true);+ }++ /**+ * Called by the parent container's adapter after each render.+ * We need both maps to be loaded before compositing and capturing.+ */+ onAfterRender = (proceedToNextFrame: () => void) => {+ const leftLoaded = this._areLayersLoaded('left');+ const rightLoaded = this._areLayersLoaded('right');+ const leftTilesReady =+ this.props.disableBaseMap || !this.leftMapRef.current || this.leftMapRef.current.getMap().areTilesLoaded();+ const rightTilesReady =+ this.props.disableBaseMap || !this.rightMapRef.current || this.rightMapRef.current.getMap().areTilesLoaded();++ if (leftLoaded && rightLoaded && leftTilesReady && rightTilesReady) {+ this._compositeFrame();+ proceedToNextFrame();+ }+ };++ _areLayersLoaded(side: 'left' | 'right'): boolean {+ const deckRef = side === 'left' ? this.leftDeckRef : this.rightDeckRef;+ if (!deckRef.current) return false;+ const layers = deckRef.current.props.layers || [];+ return layers.every((layer: any) => layer.isLoaded);+ }++ /**+ * Get the composited canvas element for video capture.+ */+ getCompositeCanvas(): HTMLCanvasElement | null {+ return this.compositeCanvasRef.current;+ }++ _createLayers(mapIndex: number, beforeId?: string) {+ const {deckProps, mapData, viewState} = this.props;+ if (deckProps && deckProps.layers) {+ return deckProps.layers;+ }+ return createKeplerLayers(mapData, viewState, mapIndex, beforeId);+ }++ _onLeftMapLoad = () => {+ const map = this.leftMapRef.current?.getMap();+ if (map) {+ map.on('render', () => {+ if (!this.state.leftReady) {+ this.setState({leftReady: true});+ }+ this._tryComposite();+ });+ }+ };++ _onRightMapLoad = () => {+ const map = this.rightMapRef.current?.getMap();+ if (map) {+ map.on('render', () => {+ if (!this.state.rightReady) {+ this.setState({rightReady: true});+ }+ this._tryComposite();+ });+ }+ };++ _tryComposite() {+ if (this.state.leftReady && this.state.rightReady) {+ this._compositeFrame();+ }+ }++ _renderMapCanvas(+ side: 'left' | 'right',+ mapIndex: number+ ) {+ const {viewState, adapter, deckProps, mapProps, disableBaseMap, mapboxLayerBeforeId} = this.props;+ const {width, height} = this._getContainer();+ const keplerLayers = this._createLayers(mapIndex, mapboxLayerBeforeId);+ const mapRef = side === 'left' ? this.leftMapRef : this.rightMapRef;+ const deckRef = side === 'left' ? this.leftDeckRef : this.rightDeckRef;+ const onMapLoad = side === 'left' ? this._onLeftMapLoad : this._onRightMapLoad;+ const deck = deckRef.current;++ if (disableBaseMap) {+ return (+ <MapLayer $width={width} $height={height}>+ <DeckGL+ ref={ref => setRef(deckRef, ref?.deck as any)}+ {...(adapter.getProps({deck: deck as any, extraProps: {...deckProps, layers: keplerLayers}}) as any)}+ {...this._getContainer()}+ />+ </MapLayer>+ );+ }++ const {+ mapStyle: mapStyleFromProps,+ mapLib,+ transformRequest+ } = (mapProps || {}) as any;++ return (+ <MapLayer $width={width} $height={height}>+ <ReactMapGL+ ref={mapRef}+ style={{width, height}}+ antialias+ mapLib={mapLib}+ transformRequest={transformRequest}+ preserveDrawingBuffer+ {...viewState}+ mapStyle={mapStyleFromProps}+ onLoad={onMapLoad}+ >+ <DeckGLOverlay+ ref={deckRef}+ deviceProps={{type: 'webgl', webgl: {stencil: true}}}+ {...adapter.getProps({deck: deck as any, extraProps: {...deckProps, layers: keplerLayers}})}+ />+ </ReactMapGL>+ </MapLayer>+ );+ }++ render() {+ const {resolution} = this.props;+ const {width, height} = this._getContainer();++ return (+ <PreviewContainer $width={width} $height={height}>+ {/* Hidden map canvases for left (mapIndex=0) and right (mapIndex=1) */}+ {this._renderMapCanvas('left', 0)}+ {this._renderMapCanvas('right', 1)}++ {/* Visible composited output */}+ <VisibleCanvas+ ref={this.compositeCanvasRef}+ width={resolution[0]}+ height={resolution[1]}+ $width={width}+ $height={height}+ />+ </PreviewContainer>+ );+ }+}diff --git a/src/reducers/src/ui-state-updaters.ts b/src/reducers/src/ui-state-updaters.tsindex 471ff2e61..99558f2a5 100644--- a/src/reducers/src/ui-state-updaters.ts+++ b/src/reducers/src/ui-state-updaters.ts@@ -240,7 +240,10 @@ export const DEFAULT_EXPORT_VIDEO: ExportVideo = {cameraPreset: 'None',fileName: 'kepler.gl',resolution: '',- durationMs: 1000+ durationMs: 1000,+ swipeStartPct: 0,+ swipeEndPct: 100,+ swipeEasing: 'ease-in-out'};/**diff --git a/src/types/reducers.d.ts b/src/types/reducers.d.tsindex 289c2ea78..06e643459 100644--- a/src/types/reducers.d.ts+++ b/src/types/reducers.d.ts@@ -448,6 +448,9 @@ export type ExportVideo = {fileName: string;resolution: string;durationMs: number;+ swipeStartPct: number;+ swipeEndPct: number;+ swipeEasing: 'linear' | 'ease-in-out';};export type MapControlItem = {