Skip to content

Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.

feat(image-export): add transparent background exports (#3827)

Igor Dykhtaa4d2b0ff111d
diff --git a/src/actions/src/ui-state-actions.ts b/src/actions/src/ui-state-actions.ts
index 7962e3bf0..ce4070d9d 100644
--- a/src/actions/src/ui-state-actions.ts
+++ b/src/actions/src/ui-state-actions.ts
@@ -261,7 +261,7 @@ export type SetExportImageSettingUpdaterAction = {
payload: Partial<ExportImage>;
};
/**
- * Set `exportImage` settings: ratio, resolution, legend, charts
+ * Set `exportImage` settings: ratio, resolution, legend, charts, transparent background
* @memberof uiStateActions
* @param newSetting - {ratio: '1x'}
* @public
@@ -285,6 +285,7 @@ export const startExportingImage: (options?: {
ratio?: string;
resolution?: string;
legend?: string;
+ transparentBackground?: boolean;
center?: boolean;
}) => Merge<SetExportImageSettingUpdaterAction, {type: typeof ActionTypes.START_EXPORTING_IMAGE}> =
createAction(ActionTypes.START_EXPORTING_IMAGE, (payload: any) => ({payload}));
diff --git a/src/components/src/common/image-preview.tsx b/src/components/src/common/image-preview.tsx
index 0b30935a0..2a2cfe244 100644
--- a/src/components/src/common/image-preview.tsx
+++ b/src/components/src/common/image-preview.tsx
@@ -32,6 +32,16 @@ const StyledImagePreview = styled.div.attrs({
overflow: hidden;
}
+ .preview-image--transparent {
+ background-color: #fff;
+ background-image: linear-gradient(45deg, #d2d2d2 25%, transparent 25%),
+ linear-gradient(-45deg, #d2d2d2 25%, transparent 25%),
+ linear-gradient(45deg, transparent 75%, #d2d2d2 75%),
+ linear-gradient(-45deg, transparent 75%, #d2d2d2 75%);
+ background-position: 0 0, 0 8px, 8px -8px, -8px 0;
+ background-size: 16px 16px;
+ }
+
.preview-image-container {
position: relative;
width: 100%;
@@ -88,6 +98,7 @@ const ImagePreview = ({exportImage, showDimension = false}: ImagePreviewProps) =
error,
imageDataUri,
processing,
+ transparentBackground,
imageSize: {imageW = 0, imageH = 0} = {}
} = exportImage || {};
@@ -101,7 +112,7 @@ const ImagePreview = ({exportImage, showDimension = false}: ImagePreviewProps) =
{imageW} pixel x {imageH} pixel
</div>
) : null}
- <div className="preview-image">
+ <div className={`preview-image${transparentBackground ? ' preview-image--transparent' : ''}`}>
<div className="preview-image-container">
{processing ? (
<div className="preview-image-spinner">
diff --git a/src/components/src/kepler-gl.tsx b/src/components/src/kepler-gl.tsx
index a5429bd2c..264eb344c 100644
--- a/src/components/src/kepler-gl.tsx
+++ b/src/components/src/kepler-gl.tsx
@@ -254,6 +254,7 @@ export const plotContainerSelector = (props: KeplerGLProps) => ({
resolution: props.uiState.exportImage.resolution,
legend: props.uiState.exportImage.legend,
charts: props.uiState.exportImage.charts,
+ transparentBackground: props.uiState.exportImage.transparentBackground,
center: props.uiState.exportImage.center,
imageSize: props.uiState.exportImage.imageSize,
escapeXhtmlForWebpack: props.uiState.exportImage.escapeXhtmlForWebpack,
diff --git a/src/components/src/map-container.tsx b/src/components/src/map-container.tsx
index 67dd27533..2b1b576d7 100644
--- a/src/components/src/map-container.tsx
+++ b/src/components/src/map-container.tsx
@@ -99,6 +99,7 @@ import {
import {
getGlobeBaseLayers,
getGlobeTopLayers,
+ getGlobeDepthDiskLayer,
getGlobeClearColor,
getGlobeBasemapAttributions,
resolveGlobeBasemapProvider,
@@ -238,6 +239,8 @@ export interface MapContainerProps {
primary?: boolean; // primary one will be reporting its size to appState
readOnly?: boolean;
isExport?: boolean;
+ /** Omit basemap/CSS fills while preserving transparent export pixels. */
+ transparentBackground?: boolean;
// onMapStyleLoaded?: (map: maplibregl.Map | ReturnType<MapRef['getMap']> | null) => void;
onMapStyleLoaded?: (map: GetMapRef | null) => void;
onMapRender?: (map: GetMapRef | null) => void;
@@ -458,19 +461,30 @@ export default function MapContainerFactory(
globeModeSelector = props => Boolean(props.mapState?.globe?.enabled);
globeBackgroundColorSelector = props => props.mapState?.globe?.config?.backgroundColor;
globeStarsSelector = props => Boolean(props.mapState?.globe?.config?.stars);
+ transparentBackgroundSelector = props => Boolean(props.transparentBackground);
styleSelector = createSelector(
this.mapStyleTypeSelector,
this.mapStyleBackgroundColorSelector,
this.globeModeSelector,
this.globeBackgroundColorSelector,
this.globeStarsSelector,
- (styleType, backgroundColor, isGlobeMode, globeBackgroundColor, globeStars) => ({
+ this.transparentBackgroundSelector,
+ (
+ styleType,
+ backgroundColor,
+ isGlobeMode,
+ globeBackgroundColor,
+ globeStars,
+ transparentBackground
+ ) => ({
...MAP_STYLE.container,
- ...(styleType === NO_MAP_ID ? {backgroundColor: rgbToHex(backgroundColor)} : {}),
+ ...(!transparentBackground && styleType === NO_MAP_ID
+ ? {backgroundColor: rgbToHex(backgroundColor)}
+ : {}),
// In globe mode the deck.gl canvas is transparent (the globe View uses
// `clearColor: false` to avoid corrupting the picking buffer), so the
// background around the globe is painted here on the container instead.
- ...(isGlobeMode
+ ...(!transparentBackground && isGlobeMode
? {
// Fall back to the default globe background when none is configured.
backgroundColor: rgbToHex(
@@ -1257,21 +1271,25 @@ export default function MapContainerFactory(
// In globe mode, prepend globe base layers and append top layers
const globeBaseLayers =
isGlobeMode && mapState.globe
- ? getGlobeBaseLayers({
- mapboxApiAccessToken: mapboxApiAccessToken || '',
- globe: mapState.globe,
- mapStyleType: mapStyle?.styleType,
- basemapProvider: globeBasemapProvider,
- // Use the live (internal) latitude so the tile LOD compensation
- // stays in sync with the deck viewport during a drag; mapState
- // latitude lags behind while rotating.
- latitude: internalMapState.latitude,
- zoom: internalMapState.zoom
- })
+ ? this.props.transparentBackground
+ ? [getGlobeDepthDiskLayer({fillColor: [0, 0, 0, 0] as any})]
+ : getGlobeBaseLayers({
+ mapboxApiAccessToken: mapboxApiAccessToken || '',
+ globe: mapState.globe,
+ mapStyleType: mapStyle?.styleType,
+ basemapProvider: globeBasemapProvider,
+ // Use the live (internal) latitude so the tile LOD compensation
+ // stays in sync with the deck viewport during a drag; mapState
+ // latitude lags behind while rotating.
+ latitude: internalMapState.latitude,
+ zoom: internalMapState.zoom
+ })
: [];
const globeTopLayers =
isGlobeMode && mapState.globe
- ? getGlobeTopLayers({globe: mapState.globe, zoom: internalMapState.zoom})
+ ? this.props.transparentBackground
+ ? []
+ : getGlobeTopLayers({globe: mapState.globe, zoom: internalMapState.zoom})
: [];
const finalDeckGlLayers = isGlobeMode
? [...globeBaseLayers, ...deckGlLayers, ...globeTopLayers]
diff --git a/src/components/src/modals/export-image-modal.tsx b/src/components/src/modals/export-image-modal.tsx
index 5875e06b5..f480a2498 100644
--- a/src/components/src/modals/export-image-modal.tsx
+++ b/src/components/src/modals/export-image-modal.tsx
@@ -24,6 +24,7 @@ import type {ExportResolutionOption} from '@kepler.gl/constants';
import type {ExportImage} from '@kepler.gl/types';
import {StyledModalContent, SelectionButton, CheckMark} from '../common/styled-components';
import Switch from '../common/switch';
+import TippyTooltip from '../common/tippy-tooltip';
import {injectIntl, IntlShape} from 'react-intl';
import {FormattedMessage} from '@kepler.gl/localization';
import {getApplicationConfig} from '@kepler.gl/utils';
@@ -60,6 +61,21 @@ const ImageOptionList = styled.div`
}
}
+ .transparent-background-option {
+ display: flex;
+ align-items: center;
+ }
+
+ .transparent-background-help {
+ margin-left: 4px;
+ color: ${props => props.theme.subtextColorLT};
+ cursor: help;
+
+ &:hover {
+ color: ${props => props.theme.textColorLT};
+ }
+ }
+
.file-name-input {
margin-top: 8px;
@@ -161,8 +177,11 @@ const ExportImageModalFactory = () => {
cleanupExportImage,
intl
}) => {
- const {legend, charts, ratio, resolution, fileName} = exportImage;
+ const {legend, charts, transparentBackground, ratio, resolution, fileName} = exportImage;
const chartsEnabled = Boolean(getApplicationConfig().enableChartsPanel);
+ const transparentBackgroundHelp = intl.formatMessage({
+ id: 'modal.exportImage.transparentBackgroundHelp'
+ });
// Filter resolutions based on selected ratio
const filteredResolutions = useMemo(() => {
@@ -301,6 +320,30 @@ const ExportImageModalFactory = () => {
<FormattedMessage id={'modal.exportImage.optionsTitle'} />
</div>
<div className="option-list">
+ <div className="transparent-background-option">
+ <Switch
+ type="checkbox"
+ id="export-transparent-background"
+ checked={Boolean(transparentBackground)}
+ label={intl.formatMessage({id: 'modal.exportImage.transparentBackground'})}
+ onChange={() =>
+ onUpdateImageSetting({transparentBackground: !transparentBackground})
+ }
+ />
+ <TippyTooltip
+ placement="top"
+ isLightTheme
+ render={() => <div>{transparentBackgroundHelp}</div>}
+ >
+ <span
+ className="transparent-background-help"
+ tabIndex={0}
+ aria-label={transparentBackgroundHelp}
+ >
+ (?)
+ </span>
+ </TippyTooltip>
+ </div>
<Switch
type="checkbox"
id="add-map-legend"
diff --git a/src/components/src/modals/image-modal-container.tsx b/src/components/src/modals/image-modal-container.tsx
index 292890718..fb9735c22 100644
--- a/src/components/src/modals/image-modal-container.tsx
+++ b/src/components/src/modals/image-modal-container.tsx
@@ -42,7 +42,8 @@ const ImageModalContainer: React.FC<ImageModalContainerProps> = ({
mapH: get(provider, ['thumbnail', 'height']) || MAP_THUMBNAIL_DIMENSION.height,
ratio: EXPORT_IMG_RATIOS.CUSTOM,
legend: false,
- charts: false
+ charts: false,
+ transparentBackground: false
});
}
} else {
@@ -51,7 +52,8 @@ const ImageModalContainer: React.FC<ImageModalContainerProps> = ({
mapH: MAP_THUMBNAIL_DIMENSION.height,
ratio: EXPORT_IMG_RATIOS.CUSTOM,
legend: false,
- charts: false
+ charts: false,
+ transparentBackground: false
});
}
}, [provider, onUpdateImageSetting]);
diff --git a/src/components/src/plot-container.tsx b/src/components/src/plot-container.tsx
index 66fb551d2..b3d5803f0 100644
--- a/src/components/src/plot-container.tsx
+++ b/src/components/src/plot-container.tsx
@@ -17,7 +17,7 @@ import MapContainerFactory from './map-container';
import MapsLayoutFactory from './maps-layout';
import {MapViewStateContextProvider} from './map-view-state-context';
-import {GEOCODER_LAYER_ID} from '@kepler.gl/constants';
+import {EMPTY_MAPBOX_STYLE, GEOCODER_LAYER_ID} from '@kepler.gl/constants';
import {Effect, SplitMap, ExportImage} from '@kepler.gl/types';
import {
ActionHandler,
@@ -116,6 +116,7 @@ interface PlotContainerProps {
resolution?: string;
legend?: boolean;
charts?: boolean;
+ transparentBackground?: boolean;
center?: boolean;
imageSize: ExportImage['imageSize'];
escapeXhtmlForWebpack?: boolean;
@@ -147,6 +148,7 @@ export default function PlotContainerFactory(
resolution,
legend = false,
charts = false,
+ transparentBackground = false,
center,
imageSize,
escapeXhtmlForWebpack,
@@ -175,6 +177,11 @@ export default function PlotContainerFactory(
const deckLayersLoadingRef = useRef(true);
const mapStyleLoadedRef = useRef(false);
const screenshotTakenRef = useRef(false);
+ const captureGenerationRef = useRef(0);
+ const renderedMapStylesRef = useRef<{
+ bottomMapStyle: unknown;
+ topMapStyle: unknown;
+ } | null>(null);
// Memoize the scale calculation
const scale = useMemo(() => {
@@ -207,29 +214,73 @@ export default function PlotContainerFactory(
// Memoize the map style
const scaledMapStyle = useMemo(() => {
const mapStyle = mapFields.mapStyle;
+
+ if (transparentBackground) {
+ return {
+ ...mapStyle,
+ bottomMapStyle: EMPTY_MAPBOX_STYLE,
+ topMapStyle: undefined
+ };
+ }
+
return {
...mapStyle,
bottomMapStyle: scaleMapStyleByResolution(mapStyle.bottomMapStyle, scale),
topMapStyle: scaleMapStyleByResolution(mapStyle.topMapStyle, scale)
};
- }, [mapFields.mapStyle, scale]);
+ }, [mapFields.mapStyle, scale, transparentBackground]);
+
+ const isGlobeMode = Boolean(mapState.globe?.enabled);
+ const effectiveBottomMapStyle = isGlobeMode
+ ? EMPTY_MAPBOX_STYLE
+ : scaledMapStyle.bottomMapStyle ?? EMPTY_MAPBOX_STYLE;
+ const effectiveTopMapStyle = isGlobeMode ? undefined : scaledMapStyle.topMapStyle;
+
+ useEffect(() => {
+ const previousMapStyles = renderedMapStylesRef.current;
+ const mapStyleChanged =
+ !previousMapStyles ||
+ previousMapStyles.bottomMapStyle !== effectiveBottomMapStyle ||
+ previousMapStyles.topMapStyle !== effectiveTopMapStyle;
+
+ captureGenerationRef.current += 1;
+ screenshotTakenRef.current = false;
+ deckLayersLoadingRef.current = true;
+ if (mapStyleChanged) {
+ mapStyleLoadedRef.current = false;
+ }
+ renderedMapStylesRef.current = {
+ bottomMapStyle: effectiveBottomMapStyle,
+ topMapStyle: effectiveTopMapStyle
+ };
+ }, [effectiveBottomMapStyle, effectiveTopMapStyle, transparentBackground]);
// Memoize the retrieveNewScreenshot callback
const debouncedScreenshot = useMemo(
() =>
- debounce(() => {
+ debounce((captureGeneration: number) => {
+ if (captureGeneration !== captureGenerationRef.current) {
+ return;
+ }
if (plottingAreaRef.current) {
convertToPng(plottingAreaRef.current, {
filter: DOM_FILTER_FUNC,
width: imageSize.imageW,
height: imageSize.imageH,
- escapeXhtmlForWebpack
+ escapeXhtmlForWebpack,
+ ...(transparentBackground ? {style: {backgroundColor: 'transparent'}} : {})
})
- .then(setExportImageDataUri)
+ .then(dataUri => {
+ if (captureGeneration === captureGenerationRef.current) {
+ setExportImageDataUri(dataUri);
+ }
+ })
.catch(err => {
- setExportImageError(err);
- if (enableErrorNotification) {
- addNotification(exportImageError({err}));
+ if (captureGeneration === captureGenerationRef.current) {
+ setExportImageError(err);
+ if (enableErrorNotification) {
+ addNotification(exportImageError({err}));
+ }
}
});
}
@@ -238,6 +289,7 @@ export default function PlotContainerFactory(
imageSize.imageW,
imageSize.imageH,
escapeXhtmlForWebpack,
+ transparentBackground,
setExportImageDataUri,
setExportImageError,
enableErrorNotification,
@@ -245,7 +297,12 @@ export default function PlotContainerFactory(
]
);
- const retrieveNewScreenshot = useCallback(debouncedScreenshot, [debouncedScreenshot]);
+ useEffect(() => () => debouncedScreenshot.cancel(), [debouncedScreenshot]);
+
+ const retrieveNewScreenshot = useCallback(
+ () => debouncedScreenshot(captureGenerationRef.current),
+ [debouncedScreenshot]
+ );
const tryScreenshot = useCallback(() => {
if (mapStyleLoadedRef.current && !deckLayersLoadingRef.current) {
@@ -268,7 +325,10 @@ export default function PlotContainerFactory(
// Memoize the onMapRender callback
const debouncedMapRender = useMemo(
() =>
- debounce(map => {
+ debounce((map, captureGeneration: number) => {
+ if (captureGeneration !== captureGenerationRef.current) {
+ return;
+ }
if (map.isStyleLoaded()) {
mapStyleLoadedRef.current = true;
tryScreenshot();
@@ -277,7 +337,12 @@ export default function PlotContainerFactory(
[tryScreenshot]
);
- const onMapRender = useCallback(debouncedMapRender, [debouncedMapRender]);
+ useEffect(() => () => debouncedMapRender.cancel(), [debouncedMapRender]);
+
+ const onMapRender = useCallback(
+ map => debouncedMapRender(map, captureGenerationRef.current),
+ [debouncedMapRender]
+ );
const deckRenderCallbacks = useMemo(
() => ({
@@ -306,12 +371,21 @@ export default function PlotContainerFactory(
ratio !== undefined ||
resolution !== undefined ||
legend !== undefined ||
- charts !== undefined
+ charts !== undefined ||
+ transparentBackground !== undefined
) {
setExportImageSetting({processing: true});
tryScreenshot();
}
- }, [ratio, resolution, legend, charts, setExportImageSetting, tryScreenshot]);
+ }, [
+ ratio,
+ resolution,
+ legend,
+ charts,
+ transparentBackground,
+ setExportImageSetting,
+ tryScreenshot
+ ]);
// Memoize size calculations
const {size, width, height} = useMemo(() => {
@@ -366,6 +440,7 @@ export default function PlotContainerFactory(
...mapFields,
mapStyle: scaledMapStyle,
mapState: newMapState,
+ transparentBackground,
mapControls: {
mapLegend: {
show: Boolean(legend),
@@ -403,6 +478,7 @@ export default function PlotContainerFactory(
newMapState,
legend,
charts,
+ transparentBackground,
onMapRender,
deckRenderCallbacks,
plotEffects,
diff --git a/src/localization/src/translations/en.ts b/src/localization/src/translations/en.ts
index 3f67f633f..10dabcd6d 100644
--- a/src/localization/src/translations/en.ts
+++ b/src/localization/src/translations/en.ts
@@ -745,6 +745,8 @@ export default {
resolutionDescription: 'High resolution is better for prints.',
resolutionPlaceholder: 'Select resolution...',
optionsTitle: 'Options',
+ transparentBackground: 'Transparent background',
+ transparentBackgroundHelp: 'Hide basemap',
mapLegendTitle: 'Map Legend',
mapLegendAdd: 'Add legend on map',
chartsTitle: 'Charts',
diff --git a/src/reducers/src/ui-state-updaters.ts b/src/reducers/src/ui-state-updaters.ts
index f018d2ec0..9ff91836b 100644
--- a/src/reducers/src/ui-state-updaters.ts
+++ b/src/reducers/src/ui-state-updaters.ts
@@ -142,6 +142,7 @@ export const DEFAULT_MAP_CONTROLS: MapControls = {
* @property resolution Default: `'ONE_X'`,
* @property legend Default: `false`,
* @property charts Default: `false`,
+ * @property transparentBackground Default: `false`,
* @property mapH Default: 0,
* @property mapW Default: 0,
* @property imageSize Default: {zoomOffset: 0, scale: 1, imageW: 0, imageH: 0},
@@ -158,6 +159,7 @@ export const DEFAULT_EXPORT_IMAGE: ExportImage = {
resolution: RESOLUTIONS.ONE_X,
legend: false,
charts: false,
+ transparentBackground: false,
mapH: 0,
mapW: 0,
imageSize: {
diff --git a/src/types/reducers.d.ts b/src/types/reducers.d.ts
index b89faad03..5b3f1668f 100644
--- a/src/types/reducers.d.ts
+++ b/src/types/reducers.d.ts
@@ -544,6 +544,8 @@ export declare type ExportImage = {
legend: boolean;
/** When true, include the charts panel in the exported image. */
charts: boolean;
+ /** When true, omit the basemap and preserve transparent pixels in the exported image. */
+ transparentBackground?: boolean;
mapH: number;
mapW: number;
imageSize: {
diff --git a/test/browser-headless/component/transparent-export-test.js b/test/browser-headless/component/transparent-export-test.js
new file mode 100644
index 000000000..8d4b150ee
--- /dev/null
+++ b/test/browser-headless/component/transparent-export-test.js
@@ -0,0 +1,70 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import test from 'tape';
+import {convertToPng} from '@kepler.gl/utils';
+
+function loadImage(src) {
+ return new Promise((resolve, reject) => {
+ const image = new Image();
+ image.onload = () => resolve(image);
+ image.onerror = reject;
+ image.src = src;
+ });
+}
+
+test('convertToPng preserves transparent canvas pixels', t => {
+ const size = 4;
+ const source = document.createElement('div');
+ source.style.position = 'relative';
+ source.style.width = `${size}px`;
+ source.style.height = `${size}px`;
+ source.style.backgroundColor = 'rgba(0, 0, 0, 0)';
+
+ const layer = document.createElement('canvas');
+ layer.width = size;
+ layer.height = size;
+ layer.style.position = 'absolute';
+ layer.style.inset = '0';
+ layer.style.width = `${size}px`;
+ layer.style.height = `${size}px`;
+
+ const layerContext = layer.getContext('2d');
+ layerContext.fillStyle = 'rgb(255, 0, 0)';
+ layerContext.fillRect(0, 0, 2, 2);
+
+ source.appendChild(layer);
+ document.body.appendChild(source);
+
+ convertToPng(source, {width: size, height: size})
+ .then(loadImage)
+ .then(image => {
+ const decoded = document.createElement('canvas');
+ decoded.width = size;
+ decoded.height = size;
+
+ const decodedContext = decoded.getContext('2d');
+ decodedContext.drawImage(image, 0, 0);
+ const pixels = decodedContext.getImageData(0, 0, size, size).data;
+
+ t.deepEqual(
+ Array.from(pixels.slice(0, 4)),
+ [255, 0, 0, 255],
+ 'opaque canvas content should remain opaque in the exported PNG'
+ );
+
+ const transparentPixelOffset = (size * size - 1) * 4;
+ t.equal(
+ pixels[transparentPixelOffset + 3],
+ 0,
+ 'untouched export background should remain fully transparent'
+ );
+ })
+ .catch(error => {
+ t.fail(`transparent PNG export should succeed: ${error?.message || error}`);
+ })
+ .then(() => {
+ source.remove();
+ t.end();
+ });
+});
diff --git a/test/browser-headless/index.js b/test/browser-headless/index.js
index afcc772dd..c2ccb2533 100644
--- a/test/browser-headless/index.js
+++ b/test/browser-headless/index.js
@@ -3,3 +3,4 @@
// test components
import './component/map-container-test';
+import './component/transparent-export-test';
diff --git a/test/browser/components/modals/export-image-modal-test.js b/test/browser/components/modals/export-image-modal-test.js
index 30d7dc4cd..82651fdaf 100644
--- a/test/browser/components/modals/export-image-modal-test.js
+++ b/test/browser/components/modals/export-image-modal-test.js
@@ -10,7 +10,8 @@ import {
ExportImageModalFactory,
ImagePreview,
appInjector,
- SelectionButton
+ SelectionButton,
+ TippyTooltip
} from '@kepler.gl/components';
import {INITIAL_UI_STATE} from '@kepler.gl/reducers';
@@ -93,6 +94,31 @@ test('Components -> ExportImageModal.mount', t => {
t.ok(onUpdateImageSetting.calledWith({resolution: 'TWO_X'}), 'should call update resolution');
+ const transparentBackgroundInput = wrapper.find('input#export-transparent-background').at(0);
+ t.equal(
+ transparentBackgroundInput.prop('checked'),
+ false,
+ 'transparent background should be disabled by default'
+ );
+ transparentBackgroundInput.simulate('change');
+ t.ok(
+ onUpdateImageSetting.calledWith({transparentBackground: true}),
+ 'should call update transparent background'
+ );
+
+ const transparentBackgroundHelp = wrapper.find('.transparent-background-help').at(0);
+ t.equal(transparentBackgroundHelp.text(), '(?)', 'should render a helper trigger');
+ t.equal(
+ transparentBackgroundHelp.prop('aria-label'),
+ 'Hide basemap',
+ 'should describe the helper trigger'
+ );
+ t.equal(
+ wrapper.find(TippyTooltip).at(0).prop('render')().props.children,
+ 'Hide basemap',
+ 'should show the basemap explanation in the helper tooltip'
+ );
+
t.end();
});
@@ -140,6 +166,43 @@ test('Components -> ExportImageModal.preview image', t => {
t.end();
});
+test('Components -> ExportImageModal.preview transparent image', t => {
+ const imageDataUri = 'data:image/png;base64,2i3u';
+ const exportImage = {
+ ...INITIAL_UI_STATE.exportImage,
+ imageDataUri,
+ transparentBackground: true,
+ imageSize: {
+ scale: 1,
+ imageW: 500,
+ imageH: 500
+ }
+ };
+ let wrapper;
+
+ t.doesNotThrow(() => {
+ wrapper = mountWithTheme(
+ <IntlWrapper>
+ <ExportImageModal
+ mapW={500}
+ mapH={500}
+ exportImage={exportImage}
+ onUpdateImageSetting={() => {}}
+ cleanupExportImage={() => {}}
+ />
+ </IntlWrapper>
+ );
+ }, 'Should not fail with a transparent preview image');
+
+ t.equal(
+ wrapper.find('.preview-image--transparent').length,
+ 1,
+ 'should show a checkerboard behind a transparent image'
+ );
+
+ t.end();
+});
+
test('Components -> ExportImageModal.unmount', t => {
const onUpdateImageSetting = () => {};
const cleanupExportImage = sinon.spy();
diff --git a/test/browser/components/plot-container-test.js b/test/browser/components/plot-container-test.js
index 6423c3b3d..6624b015a 100644
--- a/test/browser/components/plot-container-test.js
+++ b/test/browser/components/plot-container-test.js
@@ -5,10 +5,13 @@ import React from 'react';
import {IntlWrapper, mountWithTheme} from 'test/helpers/component-utils';
import test from 'tape';
+import sinon from 'sinon';
import {appInjector, PlotContainerFactory, plotContainerSelector} from '@kepler.gl/components';
+import {EMPTY_MAPBOX_STYLE, NO_MAP_ID} from '@kepler.gl/constants';
import {mockKeplerProps} from '../../helpers/mock-state';
import {Provider} from 'react-redux';
import configureStore from 'redux-mock-store';
+import domtoimage from '../../../src/utils/src/dom-to-image';
const PlotContainer = appInjector.get(PlotContainerFactory);
const initialProps = plotContainerSelector(mockKeplerProps);
@@ -93,3 +96,232 @@ test('PlotContainer -> mount -> imageSize', t => {
t.equal(map.props.mapState.zoom, 1.8721094288367688, 'should set zoom when center: true');
t.end();
});
+
+test('PlotContainer -> transparent background', t => {
+ const imageSize = {
+ scale: 1,
+ imageW: 800,
+ imageH: 600
+ };
+ const bottomMapStyle = {
+ version: 8,
+ sources: {},
+ layers: [{id: 'background', type: 'background', paint: {'background-color': '#ffffff'}}]
+ };
+ const topMapStyle = {version: 8, sources: {}, layers: []};
+ const mapFields = {
+ ...initialProps.mapFields,
+ mapStyle: {
+ ...initialProps.mapFields.mapStyle,
+ styleType: NO_MAP_ID,
+ backgroundColor: [12, 34, 56],
+ bottomMapStyle,
+ topMapStyle
+ }
+ };
+ const store = mockStore(initialState);
+
+ const selectorProps = plotContainerSelector({
+ ...mockKeplerProps,
+ uiState: {
+ ...mockKeplerProps.uiState,
+ exportImage: {
+ ...mockKeplerProps.uiState.exportImage,
+ transparentBackground: true
+ }
+ }
+ });
+ t.equal(
+ selectorProps.transparentBackground,
+ true,
+ 'selector should forward transparentBackground'
+ );
+
+ const normalWrapper = mountWithTheme(
+ <Provider store={store}>
+ <IntlWrapper>
+ <PlotContainer
+ {...initialProps}
+ imageSize={imageSize}
+ mapFields={mapFields}
+ transparentBackground={false}
+ setExportImageSetting={() => {}}
+ setExportImageDataUri={() => {}}
+ setExportImageError={() => {}}
+ addNotification={() => {}}
+ />
+ </IntlWrapper>
+ </Provider>
+ );
+ const normalMap = normalWrapper.find('MapContainer').instance();
+
+ t.deepEqual(normalMap.props.mapStyle, mapFields.mapStyle, 'should keep the map style');
+ t.equal(
+ normalMap.styleSelector(normalMap.props).backgroundColor,
+ '#0C2238',
+ 'should keep the no-basemap background color'
+ );
+
+ const transparentWrapper = mountWithTheme(
+ <Provider store={store}>
+ <IntlWrapper>
+ <PlotContainer
+ {...initialProps}
+ imageSize={imageSize}
+ mapFields={mapFields}
+ transparentBackground={true}
+ setExportImageSetting={() => {}}
+ setExportImageDataUri={() => {}}
+ setExportImageError={() => {}}
+ addNotification={() => {}}
+ />
+ </IntlWrapper>
+ </Provider>
+ );
+ const transparentMap = transparentWrapper.find('MapContainer').instance();
+ const transparentStyle = transparentMap.styleSelector(transparentMap.props);
+
+ t.equal(
+ transparentMap.props.transparentBackground,
+ true,
+ 'should pass transparentBackground to MapContainer'
+ );
+ t.deepEqual(
+ transparentMap.props.mapStyle.bottomMapStyle,
+ EMPTY_MAPBOX_STYLE,
+ 'should replace the bottom basemap with an empty style'
+ );
+ t.equal(
+ transparentMap.props.mapStyle.topMapStyle,
+ undefined,
+ 'should omit the top basemap style'
+ );
+ t.notOk(
+ Object.prototype.hasOwnProperty.call(transparentStyle, 'backgroundColor'),
+ 'should omit the map container background color'
+ );
+ t.notOk(
+ Object.prototype.hasOwnProperty.call(transparentStyle, 'backgroundImage'),
+ 'should omit the map container background image'
+ );
+
+ normalWrapper.unmount();
+ transparentWrapper.unmount();
+ t.end();
+});
+
+test('PlotContainer -> waits for the replacement style before capturing', t => {
+ const clock = sinon.useFakeTimers();
+ const toPng = sinon.stub(domtoimage, 'toPng').returns(new Promise(() => undefined));
+ let mapProps;
+ const TestMapContainer = props => {
+ mapProps = props;
+ return <div />;
+ };
+ const TestMapsLayout = ({children}) => <>{children}</>;
+ const TestPlotContainer = PlotContainerFactory(TestMapContainer, TestMapsLayout);
+ const imageSize = {
+ scale: 1,
+ imageW: 800,
+ imageH: 600
+ };
+ const mapFields = {
+ ...initialProps.mapFields,
+ mapStyle: {
+ ...initialProps.mapFields.mapStyle,
+ bottomMapStyle: {
+ version: 8,
+ sources: {},
+ layers: [{id: 'background', type: 'background', paint: {'background-color': '#ffffff'}}]
+ }
+ }
+ };
+ const renderPlot = transparentBackground => (
+ <TestPlotContainer
+ {...initialProps}
+ imageSize={imageSize}
+ mapFields={mapFields}
+ transparentBackground={transparentBackground}
+ setExportImageSetting={() => {}}
+ setExportImageDataUri={() => {}}
+ setExportImageError={() => {}}
+ addNotification={() => {}}
+ />
+ );
+ let wrapper;
+
+ try {
+ wrapper = mountWithTheme(renderPlot(false));
+ mapProps.deckRenderCallbacks.onDeckAfterRender({layers: []});
+ mapProps.onMapRender({isStyleLoaded: () => true});
+ clock.tick(1000);
+ t.equal(toPng.callCount, 1, 'should capture after the initial map is ready');
+
+ toPng.resetHistory();
+ wrapper.setProps({children: renderPlot(true)});
+ wrapper.update();
+ clock.tick(1000);
+ t.equal(toPng.callCount, 0, 'should not capture using readiness from the previous style');
+
+ mapProps.deckRenderCallbacks.onDeckAfterRender({layers: []});
+ mapProps.onMapRender({isStyleLoaded: () => true});
+ clock.tick(1000);
+ t.equal(toPng.callCount, 1, 'should capture after the replacement style is ready');
+ } finally {
+ wrapper?.unmount();
+ toPng.restore();
+ clock.restore();
+ }
+
+ t.end();
+});
+
+test('PlotContainer -> transparent globe keeps only the depth occluder', t => {
+ const imageSize = {
+ scale: 1,
+ imageW: 800,
+ imageH: 600
+ };
+ const mapFields = {
+ ...initialProps.mapFields,
+ mapState: {
+ ...initialProps.mapFields.mapState,
+ globe: {
+ ...initialProps.mapFields.mapState.globe,
+ enabled: true
+ }
+ }
+ };
+ const store = mockStore(initialState);
+ const wrapper = mountWithTheme(
+ <Provider store={store}>
+ <IntlWrapper>
+ <PlotContainer
+ {...initialProps}
+ imageSize={imageSize}
+ mapFields={mapFields}
+ transparentBackground={true}
+ setExportImageSetting={() => {}}
+ setExportImageDataUri={() => {}}
+ setExportImageError={() => {}}
+ addNotification={() => {}}
+ />
+ </IntlWrapper>
+ </Provider>
+ );
+ const map = wrapper.find('MapContainer').instance();
+ const layersForDeck = map.layersForDeckSelector(map.props);
+ const deckWrapper = map._renderDeckOverlay(layersForDeck, {primaryMap: true});
+ const globeSystemLayerIds = deckWrapper.props.children.props.layers
+ .map(layer => layer.id)
+ .filter(id => id.startsWith('globe-'));
+
+ t.deepEqual(
+ globeSystemLayerIds,
+ ['globe-depth-disk-layer'],
+ 'should omit visible globe basemap layers but retain the depth occluder'
+ );
+
+ wrapper.unmount();
+ t.end();
+});
diff --git a/test/node/reducers/ui-state-test.js b/test/node/reducers/ui-state-test.js
index fcced6624..64930c0d8 100644
--- a/test/node/reducers/ui-state-test.js
+++ b/test/node/reducers/ui-state-test.js
@@ -10,6 +10,7 @@ import {
openDeleteModal,
openReplaceDatasetModal,
setExportImageSetting,
+ cleanupExportImage,
setExportVideoSetting,
toggleMapControl,
setMapControlVisibility,
@@ -175,6 +176,28 @@ test('#uiStateReducer -> SET_EXPORT_IMAGE_SETTING', t => {
t.end();
});
+test('#uiStateReducer -> transparent export image background', t => {
+ const newReducer = reducer(
+ INITIAL_UI_STATE,
+ setExportImageSetting({transparentBackground: true})
+ );
+
+ t.equal(
+ newReducer.exportImage.transparentBackground,
+ true,
+ 'should enable the transparent background option'
+ );
+
+ const cleanedReducer = reducer(newReducer, cleanupExportImage());
+ t.equal(
+ cleanedReducer.exportImage.transparentBackground,
+ true,
+ 'should preserve the transparent background option during cleanup'
+ );
+
+ t.end();
+});
+
test('#uiStateReducer -> START_EXPORTING_IMAGE', t => {
const newReducer = reducer(INITIAL_UI_STATE, startExportingImage());