Skip to content

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

feat(export-map): preserve custom branding and streamline the export UI (#3830)

Igor Dykhta6a83a393e317
diff --git a/docker/config.full-example.json b/docker/config.full-example.json
index d7a00c823..95e7621c2 100644
--- a/docker/config.full-example.json
+++ b/docker/config.full-example.json
@@ -53,6 +53,7 @@
"defaultExportJsonSettings": {
"hasData": true
},
+ "enableCustomExportBranding": true,
"cdnUrl": "https://studio-public-data.foursquare.com/statics/keplergl",
diff --git a/examples/demo-app/src/utils/runtime-config.js b/examples/demo-app/src/utils/runtime-config.js
index a2ec90bb7..bb3f1e8df 100644
--- a/examples/demo-app/src/utils/runtime-config.js
+++ b/examples/demo-app/src/utils/runtime-config.js
@@ -66,8 +66,6 @@ const CREDENTIAL_TO_CLOUD_KEY = {
*/
export function applyDemoApplicationDefaults() {
initApplicationConfig({
- enableA5Layer: true,
- enableGeohashLayer: true,
customIcons: [
{
id: 'custom-star',
diff --git a/src/actions/src/action-types.ts b/src/actions/src/action-types.ts
index 4c98a55df..8d9e3d416 100644
--- a/src/actions/src/action-types.ts
+++ b/src/actions/src/action-types.ts
@@ -232,6 +232,7 @@ export const ActionTypes = {
SET_EXPORT_MAP_FORMAT: `${ACTION_PREFIX}SET_EXPORT_MAP_FORMAT`,
SET_USER_MAPBOX_ACCESS_TOKEN: `${ACTION_PREFIX}SET_USER_MAPBOX_ACCESS_TOKEN`,
SET_EXPORT_MAP_HTML_MODE: `${ACTION_PREFIX}SET_EXPORT_MAP_HTML_MODE`,
+ SET_EXPORT_MAP_BRANDING: `${ACTION_PREFIX}SET_EXPORT_MAP_BRANDING`,
SET_EXPORT_MAP_FILE_NAME: `${ACTION_PREFIX}SET_EXPORT_MAP_FILE_NAME`,
SET_EXPORT_INCLUDE_LAYER_API_KEYS: `${ACTION_PREFIX}SET_EXPORT_INCLUDE_LAYER_API_KEYS`,
diff --git a/src/actions/src/ui-state-actions.ts b/src/actions/src/ui-state-actions.ts
index ce4070d9d..32cd4ea9e 100644
--- a/src/actions/src/ui-state-actions.ts
+++ b/src/actions/src/ui-state-actions.ts
@@ -476,6 +476,26 @@ export const setExportHTMLMapMode: (
(payload: SetExportHTMLMapModeUpdaterAction['payload']) => ({payload})
);
+/** SET_EXPORT_MAP_BRANDING */
+export type SetExportMapBrandingUpdaterAction = {
+ payload: {
+ appName?: string;
+ appWebsite?: string;
+ };
+};
+/**
+ * Set application branding overrides for exported maps
+ * @memberOf uiStateActions
+ * @param payload - application name and/or website overrides
+ */
+export const setExportMapBranding: (
+ payload: SetExportMapBrandingUpdaterAction['payload']
+) => Merge<SetExportMapBrandingUpdaterAction, {type: typeof ActionTypes.SET_EXPORT_MAP_BRANDING}> =
+ createAction(
+ ActionTypes.SET_EXPORT_MAP_BRANDING,
+ (payload: SetExportMapBrandingUpdaterAction['payload']) => ({payload})
+ );
+
/** SET_EXPORT_MAP_FILE_NAME */
export type SetExportMapFileNameUpdaterAction = {
payload: string;
diff --git a/src/components/src/kepler-gl.tsx b/src/components/src/kepler-gl.tsx
index 264eb344c..5e7e52ff2 100644
--- a/src/components/src/kepler-gl.tsx
+++ b/src/components/src/kepler-gl.tsx
@@ -283,6 +283,7 @@ export const bottomWidgetSelector = (props: KeplerGLProps, theme) => ({
export const modalContainerSelector = (props: KeplerGLProps, rootNode) => ({
appName: props.appName ? props.appName : DEFAULT_KEPLER_GL_PROPS.appName,
+ appWebsite: props.appWebsite,
mapStyle: props.mapStyle,
visState: props.visState,
mapState: props.mapState,
diff --git a/src/components/src/modal-container.spec.ts b/src/components/src/modal-container.spec.ts
index bd131c9cb..5d68ba3df 100644
--- a/src/components/src/modal-container.spec.ts
+++ b/src/components/src/modal-container.spec.ts
@@ -1,9 +1,13 @@
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
+import React from 'react';
+
import {EXPORT_DATA_ID, EXPORT_MAP_ID} from '@kepler.gl/constants';
+import {renderWithTheme} from 'test/helpers/component-jest-utils';
-import {exportDataFromModal} from './modal-container';
+import {exportDataFromModal, ExportMapModalStyle} from './modal-container';
+import ModalDialogFactory from './modals/modal-dialog';
function deferred() {
let resolve!: () => void;
@@ -68,3 +72,30 @@ describe('exportDataFromModal', () => {
});
});
});
+
+describe('ExportMapModalStyle', () => {
+ test('fits the dialog to its label and input columns', () => {
+ const ModalDialog = ModalDialogFactory();
+ const {unmount} = renderWithTheme(
+ React.createElement(
+ ModalDialog,
+ {
+ isOpen: true,
+ footer: false,
+ close: false,
+ onConfirm: jest.fn(),
+ onCancel: jest.fn(),
+ cssStyle: ExportMapModalStyle,
+ theme: {}
+ },
+ React.createElement('div', null, 'Export map')
+ )
+ );
+ const wrapper = document.querySelector('.modal--wrapper') as HTMLElement;
+
+ expect(wrapper).not.toBeNull();
+ expect(getComputedStyle(wrapper).maxWidth).toBe('728px');
+
+ unmount();
+ });
+});
diff --git a/src/components/src/modal-container.tsx b/src/components/src/modal-container.tsx
index 6ae4ebe8d..eabbe7537 100644
--- a/src/components/src/modal-container.tsx
+++ b/src/components/src/modal-container.tsx
@@ -97,12 +97,17 @@ const ExportVideoModalStyle = css`
max-width: 960px;
`;
+export const ExportMapModalStyle = css`
+ max-width: 728px;
+`;
+
const DefaultStyle = css`
max-width: 960px;
`;
export type ModalContainerProps = {
appName: string;
+ appWebsite?: string;
rootNode: React.ReactInstance | null | undefined;
containerW: number;
containerH: number;
@@ -343,13 +348,15 @@ export default function ModalContainerFactory(
_onExportMap = () => {
const {uiState} = this._propsWithMapInfoDraft();
- const {format, includeLayerApiKeys, fileName} = uiState.exportMap;
+ const {format, includeLayerApiKeys, fileName, appName, appWebsite} = uiState.exportMap;
(format === EXPORT_MAP_FORMATS.HTML ? exportHtml : exportJson)(
this._propsWithMapInfoDraft(),
{
...(uiState.exportMap[format] || {}),
includeLayerApiKeys,
- fileName
+ fileName,
+ appName,
+ appWebsite
}
);
this._commitMapInfoDraft();
@@ -580,12 +587,15 @@ export default function ModalContainerFactory(
});
template = (
<ExportMapModal
+ appName={this.props.appName}
+ appWebsite={this.props.appWebsite}
config={keplerGlConfig}
options={uiState.exportMap}
mapInfo={visState.mapInfo}
onChangeExportMapFormat={uiStateActions.setExportMapFormat}
onEditUserMapboxAccessToken={uiStateActions.setUserMapboxAccessToken}
onChangeExportMapHTMLMode={uiStateActions.setExportHTMLMapMode}
+ onChangeExportMapBranding={uiStateActions.setExportMapBranding}
onChangeExportIncludeLayerApiKeys={uiStateActions.setExportIncludeLayerApiKeys}
onChangeExportMapFileName={uiStateActions.setExportMapFileName}
onMapInfoDraft={this._onMapInfoDraft}
@@ -593,7 +603,7 @@ export default function ModalContainerFactory(
);
modalProps = {
title: 'modal.title.exportMap',
- cssStyle: '',
+ cssStyle: ExportMapModalStyle,
footer: true,
onCancel: this._closeModal,
onConfirm: this._onExportMap,
diff --git a/src/components/src/modals/export-file-name.tsx b/src/components/src/modals/export-file-name.tsx
index 71a40f48b..011bfb062 100644
--- a/src/components/src/modals/export-file-name.tsx
+++ b/src/components/src/modals/export-file-name.tsx
@@ -7,7 +7,8 @@ import {useIntl} from 'react-intl';
import {FormattedMessage} from '@kepler.gl/localization';
-import {InputLight, StyledExportSection} from '../common/styled-components';
+import {Help} from '../common/icons';
+import {InputLight, StyledExportSection, Tooltip} from '../common/styled-components';
const FileNameSection = styled(StyledExportSection)<{$compact?: boolean}>`
${props => (props.$compact ? 'margin: 8px 0 12px;' : '')}
@@ -15,7 +16,34 @@ const FileNameSection = styled(StyledExportSection)<{$compact?: boolean}>`
const StyledFileNameInput = styled(InputLight)`
width: 100%;
- max-width: 320px;
+ max-width: 380px;
+`;
+
+const FileNameTitle = styled.div`
+ align-items: center;
+ display: flex;
+`;
+
+const FileNameHelp = styled.button.attrs({type: 'button'})`
+ align-items: center;
+ background: transparent;
+ border: 0;
+ color: ${props => props.theme.labelColor};
+ cursor: help;
+ display: inline-flex;
+ margin-left: 6px;
+ padding: 0;
+
+ &:hover,
+ &:focus {
+ color: ${props => props.theme.textColorHl};
+ }
+`;
+
+const FileNameHelpContent = styled.div`
+ max-width: 220px;
+ text-align: left;
+ white-space: normal;
`;
export type ExportFileNameSectionProps = {
@@ -32,15 +60,26 @@ const ExportFileNameSection: React.FC<ExportFileNameSectionProps> = ({
compact
}) => {
const intl = useIntl();
+ const helpId = `${inputId}-extension-help`;
return (
<FileNameSection $compact={compact}>
- <div className="description">
- <div className="title">
+ <div className={compact ? 'description description--centered' : 'description'}>
+ <FileNameTitle className="title">
<FormattedMessage id="modal.exportFileName.title" />
- </div>
- <div className="subtitle">
- <FormattedMessage id="modal.exportFileName.subtitle" />
- </div>
+ <FileNameHelp
+ aria-describedby={helpId}
+ aria-label={intl.formatMessage({id: 'modal.exportFileName.subtitle'})}
+ data-for={helpId}
+ data-tip
+ >
+ <Help aria-hidden height="12px" />
+ <Tooltip id={helpId} effect="solid" place="top">
+ <FileNameHelpContent>
+ <FormattedMessage id="modal.exportFileName.subtitle" />
+ </FileNameHelpContent>
+ </Tooltip>
+ </FileNameHelp>
+ </FileNameTitle>
</div>
<div className="selection">
<StyledFileNameInput
diff --git a/src/components/src/modals/export-map-modal/components.tsx b/src/components/src/modals/export-map-modal/components.tsx
index 7d2ac9f9a..eefced46c 100644
--- a/src/components/src/modals/export-map-modal/components.tsx
+++ b/src/components/src/modals/export-map-modal/components.tsx
@@ -1,50 +1,266 @@
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
-import React from 'react';
+import React, {useState} from 'react';
import styled from 'styled-components';
import {media} from '@kepler.gl/styles';
import {FormattedMessage} from '@kepler.gl/localization';
-import {StyledExportSection, StyledModalContent} from '../../common/styled-components';
+import {useIntl} from 'react-intl';
+import {StyledExportSection, StyledModalContent, Tooltip} from '../../common/styled-components';
import Checkbox from '../../common/checkbox';
+import {ArrowRight, Help, WarningSign} from '../../common/icons';
export const StyledExportMapModalContent = styled(StyledModalContent)`
- padding-top: 12px;
- padding-bottom: 12px;
+ padding-top: 8px;
+ padding-bottom: 8px;
+
+ ${StyledExportSection} {
+ align-items: start;
+ column-gap: 24px;
+ display: grid;
+ grid-template-columns: 180px minmax(0, 1fr);
+ margin: 16px 0;
+
+ .description {
+ padding-top: 2px;
+ width: auto;
+ }
+
+ .description.description--centered {
+ align-self: center;
+ padding-top: 0;
+ }
+
+ .selection {
+ min-width: 0;
+ padding-left: 0;
+
+ select {
+ border-color: ${props => props.theme.selectBorderColorLT};
+ max-width: 380px;
+ width: 100%;
+ }
+ }
+ }
${media.portable`
padding-top: 8px;
padding-bottom: 8px;
+
+ ${StyledExportSection} {
+ grid-template-columns: minmax(0, 1fr);
+ row-gap: 8px;
+
+ .description {
+ padding-top: 0;
+ }
+ }
+
+ input[type='text'],
+ select,
+ [role='status'],
+ .export-map-modal__json-options .viewer,
+ .export-map-modal__collapsible-section {
+ max-width: none;
+ }
`};
`;
-export const StyledExportMapSection = styled(StyledExportSection)`
- margin: 8px 0 12px;
+export const StyledExportMapSection = styled(StyledExportSection)``;
+
+const StyledLayerApiKeysSection = styled(StyledExportMapSection)`
+ && {
+ margin: 0 0 16px;
+ }
+
+ .kg-checkbox__label {
+ margin-bottom: 0;
+ }
`;
-export const StyledExportMapNote = styled.p`
- color: ${props => props.theme.textColorLT};
- font-size: 12px;
- line-height: 1.4;
- margin: 0 0 8px;
+export const ExportMapSectionTitle = styled.div.attrs({className: 'title'})`
+ align-items: center;
+ display: flex;
+`;
+
+const StyledExportMapHelp = styled.button.attrs({type: 'button'})`
+ align-items: center;
+ background: transparent;
+ border: 0;
+ color: ${props => props.theme.labelColor};
+ cursor: help;
+ display: inline-flex;
+ margin-left: 6px;
+ padding: 0;
+
+ &:hover,
+ &:focus {
+ color: ${props => props.theme.textColorHl};
+ }
`;
+const StyledExportMapHelpContent = styled.div`
+ max-width: 300px;
+ text-align: left;
+ white-space: normal;
+
+ > * + * {
+ margin-top: 6px;
+ }
+`;
+
+type ExportMapHelpProps = {
+ id: string;
+ label: string;
+ children: React.ReactNode;
+};
+
+export const ExportMapHelp = ({id, label, children}: ExportMapHelpProps) => (
+ <StyledExportMapHelp aria-describedby={id} aria-label={label} data-for={id} data-tip>
+ <Help aria-hidden height="12px" />
+ <Tooltip id={id} effect="solid" place="top">
+ <StyledExportMapHelpContent>{children}</StyledExportMapHelpContent>
+ </Tooltip>
+ </StyledExportMapHelp>
+);
+
export const StyledExportMapFormatPanels = styled.div`
display: grid;
+ margin-top: 0;
+ padding-top: 0;
`;
export const StyledExportMapFormatPanel = styled.div<{$active: boolean}>`
grid-area: 1 / 1;
+ display: ${props => (props.$active ? 'block' : 'none')};
overflow: hidden;
- visibility: ${props => (props.$active ? 'visible' : 'hidden')};
- pointer-events: ${props => (props.$active ? 'auto' : 'none')};
+
+ > div > ${StyledExportSection}:last-child {
+ margin-bottom: 0;
+ }
+`;
+
+const StyledCollapsibleSection = styled.div`
+ margin: 4px 0 0;
+ max-width: 584px;
+ width: 100%;
+
+ ${media.portable`
+ max-width: 380px;
+ `};
`;
+const StyledCollapsibleHeader = styled.button.attrs({type: 'button'})<{$expanded: boolean}>`
+ align-items: center;
+ background: transparent;
+ border: 0;
+ color: ${props => props.theme.titleColorLT};
+ cursor: pointer;
+ display: flex;
+ font-family: ${props => props.theme.fontFamilyMedium ?? props.theme.fontFamily};
+ font-size: 12px;
+ font-weight: 500;
+ min-height: 42px;
+ padding: 10px 0 10px 4px;
+ text-align: left;
+ width: 100%;
+
+ &:hover {
+ background-color: ${props => props.theme.panelBackgroundLT};
+ }
+
+ &:focus-visible {
+ box-shadow: inset 0 0 0 2px ${props => props.theme.activeColorLT};
+ outline: 0;
+ }
+
+ svg {
+ margin-right: 6px;
+ transform: rotate(${props => (props.$expanded ? 90 : 0)}deg);
+ transition: transform 0.2s ease;
+ }
+`;
+
+const StyledCollapsibleContent = styled.div`
+ padding: 2px 0 4px;
+`;
+
+type CollapsibleExportMapSectionProps = {
+ id: string;
+ title: React.ReactNode;
+ children: React.ReactNode;
+};
+
+export const CollapsibleExportMapSection = ({
+ id,
+ title,
+ children
+}: CollapsibleExportMapSectionProps) => {
+ const [expanded, setExpanded] = useState(false);
+ const contentId = `${id}-content`;
+ const headerId = `${id}-header`;
+
+ return (
+ <StyledCollapsibleSection className="export-map-modal__collapsible-section">
+ <StyledCollapsibleHeader
+ id={headerId}
+ $expanded={expanded}
+ aria-controls={contentId}
+ aria-expanded={expanded}
+ onClick={() => setExpanded(value => !value)}
+ >
+ <ArrowRight aria-hidden height="12px" />
+ {title}
+ </StyledCollapsibleHeader>
+ {expanded ? (
+ <StyledCollapsibleContent id={contentId} role="region" aria-labelledby={headerId}>
+ {children}
+ </StyledCollapsibleContent>
+ ) : null}
+ </StyledCollapsibleSection>
+ );
+};
+
export const StyledWarning = styled.span`
color: ${props => props.theme.errorColor};
font-weight: ${props => props.theme.selectFontWeightBold};
`;
+const StyledExportMapNotice = styled.div`
+ align-items: flex-start;
+ background-color: ${props => props.theme.selectBackgroundLT};
+ border-left: 2px solid ${props => props.theme.errorColor};
+ box-sizing: border-box;
+ color: ${props => props.theme.textColorLT};
+ display: flex;
+ font-size: 11px;
+ line-height: 1.45;
+ margin-top: 8px;
+ max-width: 380px;
+ padding: 8px 10px;
+ width: 100%;
+
+ svg {
+ flex: 0 0 auto;
+ margin: 1px 8px 0 0;
+ }
+`;
+
+const StyledExportMapNoticeCopy = styled.div`
+ min-width: 0;
+`;
+
+type ExportMapNoticeProps = React.HTMLAttributes<HTMLDivElement> & {
+ children: React.ReactNode;
+};
+
+export const ExportMapNotice = ({children, ...props}: ExportMapNoticeProps) => (
+ <StyledExportMapNotice {...props} role="status">
+ <WarningSign aria-hidden height="14px" />
+ <StyledExportMapNoticeCopy>{children}</StyledExportMapNoticeCopy>
+ </StyledExportMapNotice>
+);
+
export const StyledExportLink = styled.a`
text-decoration-line: underline !important;
`;
@@ -65,24 +281,32 @@ export const IncludeLayerApiKeysToggle = ({
id,
checked,
onChange
-}: IncludeLayerApiKeysToggleProps) => (
- <StyledExportMapSection>
- <div className="description">
- <div className="title">
- <FormattedMessage id="modal.exportMap.includeApiKeys" />
+}: IncludeLayerApiKeysToggleProps) => {
+ const intl = useIntl();
+ const helpId = `${id}-help`;
+
+ return (
+ <StyledLayerApiKeysSection>
+ <div className="description description--centered">
+ <ExportMapSectionTitle>
+ <FormattedMessage id="modal.exportMap.includeApiKeysTitle" />
+ <ExportMapHelp
+ id={helpId}
+ label={intl.formatMessage({id: 'modal.exportMap.includeApiKeysHelpLabel'})}
+ >
+ <FormattedMessage id="modal.exportMap.includeApiKeysSubtitle" />
+ </ExportMapHelp>
+ </ExportMapSectionTitle>
</div>
- <div className="subtitle">
- <FormattedMessage id="modal.exportMap.includeApiKeysSubtitle" />
+ <div className="selection">
+ <Checkbox
+ id={id}
+ type="checkbox"
+ checked={checked}
+ label={<FormattedMessage id="modal.exportMap.includeApiKeys" />}
+ onChange={event => onChange(event.target.checked)}
+ />
</div>
- </div>
- <div className="selection">
- <Checkbox
- id={id}
- type="checkbox"
- checked={checked}
- label={<FormattedMessage id="modal.exportMap.includeApiKeys" />}
- onChange={event => onChange(event.target.checked)}
- />
- </div>
- </StyledExportMapSection>
-);
+ </StyledLayerApiKeysSection>
+ );
+};
diff --git a/src/components/src/modals/export-map-modal/export-html-map.tsx b/src/components/src/modals/export-map-modal/export-html-map.tsx
index 9b66e008c..c774f9a7b 100644
--- a/src/components/src/modals/export-map-modal/export-html-map.tsx
+++ b/src/components/src/modals/export-map-modal/export-html-map.tsx
@@ -2,18 +2,15 @@
// Copyright contributors to the kepler.gl project
import React from 'react';
-import {StyledExportSection, StyledType, CheckMark} from '../../common/styled-components';
+import {InputLight, StyledExportSection} from '../../common/styled-components';
import {
- StyledExportMapNote,
- StyledWarning,
+ ExportMapHelp,
ExportMapLink,
+ ExportMapNotice,
+ ExportMapSectionTitle,
IncludeLayerApiKeysToggle
} from './components';
-import {
- EXPORT_HTML_MAP_MODE_OPTIONS,
- EXPORT_HTML_MAP_DOC,
- EXPORT_HTML_MAP_MODES_DOC
-} from '@kepler.gl/constants';
+import {EXPORT_HTML_MAP_MODE_OPTIONS, EXPORT_HTML_MAP_DOC} from '@kepler.gl/constants';
import styled from 'styled-components';
import {injectIntl} from 'react-intl';
import {FormattedMessage} from '@kepler.gl/localization';
@@ -27,53 +24,15 @@ import {
} from '@kepler.gl/actions';
const ExportMapStyledExportSection = styled(StyledExportSection)`
- margin: 8px 0 12px;
-
- &.export-map-modal__html-options {
- margin-top: 20px;
- }
-
- .disclaimer {
- font-size: ${props => props.theme.inputFontSize};
- color: ${props => props.theme.inputColor};
- line-height: 1.35;
- margin-top: 8px;
+ .selection {
+ align-items: flex-start;
+ flex-direction: column;
}
`;
-interface StyledInputProps {
- error?: boolean;
-}
-
-const StyledInput = styled.input<StyledInputProps>`
+const StyledInput = styled(InputLight)`
+ max-width: 380px;
width: 100%;
- padding: ${props => props.theme.inputPadding};
- color: ${props => (props.error ? 'red' : props.theme.titleColorLT)};
- height: ${props => props.theme.inputBoxHeight};
- outline: 0;
- font-size: ${props => props.theme.inputFontSize};
-
- &:active,
- &:focus,
- &.focus,
- &.active {
- outline: 0;
- }
-`;
-
-const BigStyledTile = styled(StyledType)`
- height: unset;
- width: unset;
- padding: 6px;
- img {
- width: 120px;
- height: 80px;
- }
- p {
- font-size: 11px;
- line-height: 1.3;
- margin: 6px 0 0;
- }
`;
type ExportHtmlMapProps = {
@@ -106,79 +65,95 @@ function ExportHtmlMapFactory(): React.ComponentType<ExportHtmlMapProps> {
includeLayerApiKeys = false,
options = {},
intl
- }) => (
- <div>
- <StyledExportMapNote>
- <FormattedMessage id={'modal.exportMap.html.selection'} />
- </StyledExportMapNote>
- <IncludeLayerApiKeysToggle
- id="export-include-layer-api-keys-html"
- checked={includeLayerApiKeys}
- onChange={onChangeExportIncludeLayerApiKeys}
- />
- <ExportMapStyledExportSection className="export-map-modal__html-options">
- <div className="description">
- <div className="title">
- <FormattedMessage id={'modal.exportMap.html.tokenTitle'} />
- </div>
- <div className="subtitle">
- <FormattedMessage id={'modal.exportMap.html.tokenSubtitle'} />
- </div>
- </div>
- <div className="selection">
- <StyledInput
- onChange={e => onEditUserMapboxAccessToken(e.target.value)}
- type="text"
- placeholder={intl.formatMessage({id: 'modal.exportMap.html.tokenPlaceholder'})}
- value={options ? options.userMapboxToken : ''}
- />
- <div className="disclaimer">
- <StyledWarning>
- <FormattedMessage id={'modal.exportMap.html.tokenMisuseWarning'} />
- </StyledWarning>
- <StyledWarning>
- <FormattedMessage id={'modal.exportMap.html.tokenSecurityWarning'} />
- </StyledWarning>
- <FormattedMessage id={'modal.exportMap.html.tokenDisclaimer'} />
- <ExportMapLink href={EXPORT_HTML_MAP_DOC}>
- <FormattedMessage id={'modal.exportMap.html.tokenUpdate'} />
- </ExportMapLink>
+ }) => {
+ const hasCustomToken = Boolean(options.userMapboxToken?.trim());
+
+ return (
+ <div>
+ <IncludeLayerApiKeysToggle
+ id="export-include-layer-api-keys-html"
+ checked={includeLayerApiKeys}
+ onChange={onChangeExportIncludeLayerApiKeys}
+ />
+ <ExportMapStyledExportSection className="export-map-modal__html-options">
+ <div className="description">
+ <label className="title" htmlFor="export-map-mapbox-token">
+ <FormattedMessage id={'modal.exportMap.html.tokenTitle'} />
+ </label>
+ <div className="subtitle">
+ <FormattedMessage id={'modal.exportMap.html.tokenSubtitle'} />
+ </div>
</div>
- </div>
- </ExportMapStyledExportSection>
- <ExportMapStyledExportSection>
- <div className="description">
- <div className="title">
- <FormattedMessage id={'modal.exportMap.html.modeTitle'} />
+ <div className="selection">
+ <StyledInput
+ id="export-map-mapbox-token"
+ aria-describedby="export-map-token-guidance"
+ aria-label={intl.formatMessage({id: 'modal.exportMap.html.tokenTitle'})}
+ onChange={e => onEditUserMapboxAccessToken(e.target.value)}
+ type="text"
+ placeholder={intl.formatMessage({id: 'modal.exportMap.html.tokenPlaceholder'})}
+ value={options.userMapboxToken ?? ''}
+ />
+ <ExportMapNotice id="export-map-token-guidance">
+ <FormattedMessage
+ id={
+ hasCustomToken
+ ? 'modal.exportMap.html.tokenEmbeddedNotice'
+ : 'modal.exportMap.html.tokenSharedNotice'
+ }
+ />{' '}
+ <ExportMapLink href={EXPORT_HTML_MAP_DOC}>
+ <FormattedMessage id={'modal.exportMap.html.tokenUpdate'} />
+ </ExportMapLink>
+ </ExportMapNotice>
</div>
- <div className="subtitle">
- <FormattedMessage id={'modal.exportMap.html.modeSubtitle1'} />
- <a href={EXPORT_HTML_MAP_MODES_DOC}>
- <FormattedMessage id={'modal.exportMap.html.modeSubtitle2'} />
- </a>
+ </ExportMapStyledExportSection>
+ <ExportMapStyledExportSection>
+ <div className="description">
+ <ExportMapSectionTitle>
+ <label htmlFor="export-map-html-mode">
+ <FormattedMessage id={'modal.exportMap.html.modeTitle'} />
+ </label>
+ <ExportMapHelp
+ id="export-map-html-mode-help"
+ label={intl.formatMessage({id: 'modal.exportMap.html.modeHelpLabel'})}
+ >
+ <div>
+ <strong>
+ <FormattedMessage id="modal.exportMap.html.read" />:
+ </strong>{' '}
+ <FormattedMessage id="modal.exportMap.html.modeReadHelp" />
+ </div>
+ <div>
+ <strong>
+ <FormattedMessage id="modal.exportMap.html.edit" />:
+ </strong>{' '}
+ <FormattedMessage id="modal.exportMap.html.modeEditHelp" />
+ </div>
+ </ExportMapHelp>
+ </ExportMapSectionTitle>
+ <div className="subtitle">
+ <FormattedMessage id={'modal.exportMap.html.modeSubtitle1'} />
+ </div>
</div>
- </div>
- <div className="selection">
- {EXPORT_HTML_MAP_MODE_OPTIONS.map(mode => (
- <BigStyledTile
- key={mode.id}
- selected={options.mode === mode.id}
- onClick={() => mode.available && onChangeExportMapHTMLMode(mode.id)}
+ <div className="selection">
+ <select
+ id="export-map-html-mode"
+ aria-label={intl.formatMessage({id: 'modal.exportMap.html.modeTitle'})}
+ value={options.mode ?? EXPORT_HTML_MAP_MODE_OPTIONS[0].id}
+ onChange={event => onChangeExportMapHTMLMode(event.target.value)}
>
- <img src={mode.url} alt="" />
- <p>
- <FormattedMessage
- id={'modal.exportMap.html.modeDescription'}
- values={{mode: intl.formatMessage({id: mode.label})}}
- />
- </p>
- {options.mode === mode.id && <CheckMark />}
- </BigStyledTile>
- ))}
- </div>
- </ExportMapStyledExportSection>
- </div>
- );
+ {EXPORT_HTML_MAP_MODE_OPTIONS.map(mode => (
+ <option key={mode.id} value={mode.id} disabled={!mode.available}>
+ {intl.formatMessage({id: mode.label})}
+ </option>
+ ))}
+ </select>
+ </div>
+ </ExportMapStyledExportSection>
+ </div>
+ );
+ };
ExportHtmlMap.displayName = 'ExportHtmlMap';
diff --git a/src/components/src/modals/export-map-modal/export-json-map.tsx b/src/components/src/modals/export-map-modal/export-json-map.tsx
index 28c35f7d0..4f2923741 100644
--- a/src/components/src/modals/export-map-modal/export-json-map.tsx
+++ b/src/components/src/modals/export-map-modal/export-json-map.tsx
@@ -6,12 +6,7 @@ import JSONPretty from 'react-json-pretty';
import {ADD_DATA_TO_MAP_DOC} from '@kepler.gl/constants';
import styled from 'styled-components';
import {StyledExportSection, Button} from '../../common/styled-components';
-import {
- StyledExportMapNote,
- StyledWarning,
- ExportMapLink,
- IncludeLayerApiKeysToggle
-} from './components';
+import {ExportMapLink, ExportMapNotice, IncludeLayerApiKeysToggle} from './components';
import {ActionHandler, setExportIncludeLayerApiKeys} from '@kepler.gl/actions';
import {FormattedMessage} from '@kepler.gl/localization';
import {CopyToClipboard} from 'react-copy-to-clipboard';
@@ -41,7 +36,7 @@ const StyledJsonExportSection = styled(StyledExportSection)`
overflow-x: auto;
white-space: pre-wrap;
word-wrap: break-word;
- max-width: 600px;
+ max-width: 380px;
}
.copy-button {
@@ -68,9 +63,6 @@ const ExportJsonMapUnmemoized = ({
const [copied, setCopy] = useState(false);
return (
<div>
- <StyledExportMapNote>
- <FormattedMessage id={'modal.exportMap.json.selection'} />
- </StyledExportMapNote>
<IncludeLayerApiKeysToggle
id="export-include-layer-api-keys-json"
checked={includeLayerApiKeys}
@@ -95,11 +87,9 @@ const ExportJsonMapUnmemoized = ({
</Button>
</CopyToClipboard>
</div>
- <div className="disclaimer">
- <StyledWarning>
- <FormattedMessage id={'modal.exportMap.json.disclaimer'} />
- </StyledWarning>
- </div>
+ <ExportMapNotice id="export-map-json-config-warning">
+ <FormattedMessage id={'modal.exportMap.json.disclaimer'} />
+ </ExportMapNotice>
</div>
</StyledJsonExportSection>
</div>
diff --git a/src/components/src/modals/export-map-modal/export-map-modal.spec.tsx b/src/components/src/modals/export-map-modal/export-map-modal.spec.tsx
new file mode 100644
index 000000000..e7d22f2b5
--- /dev/null
+++ b/src/components/src/modals/export-map-modal/export-map-modal.spec.tsx
@@ -0,0 +1,339 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React from 'react';
+import {fireEvent, within} from '@testing-library/react';
+
+import {EXPORT_HTML_MAP_DOC, EXPORT_HTML_MAP_MODES, EXPORT_MAP_FORMATS} from '@kepler.gl/constants';
+import {messages} from '@kepler.gl/localization';
+import {INITIAL_UI_STATE} from '@kepler.gl/reducers';
+import {initApplicationConfig} from '@kepler.gl/utils';
+import {IntlProvider} from 'react-intl';
+import {renderWithTheme} from 'test/helpers/component-jest-utils';
+
+import ExportHtmlMapFactory from './export-html-map';
+import ExportJsonMapFactory from './export-json-map';
+import ExportMapModalFactory from './export-map-modal';
+
+const ExportMapModal = ExportMapModalFactory(ExportHtmlMapFactory(), ExportJsonMapFactory());
+
+const defaultProps = {
+ appName: 'Acme Maps',
+ appWebsite: 'https://maps.acme.test',
+ config: {},
+ mapInfo: {
+ title: 'City map',
+ description: 'A city map'
+ },
+ options: INITIAL_UI_STATE.exportMap,
+ onEditUserMapboxAccessToken: jest.fn(),
+ onChangeExportMapHTMLMode: jest.fn(),
+ onChangeExportMapBranding: jest.fn(),
+ onChangeExportIncludeLayerApiKeys: jest.fn(),
+ onChangeExportMapFormat: jest.fn(),
+ onChangeExportMapFileName: jest.fn(),
+ onMapInfoDraft: jest.fn()
+};
+
+function renderModal(props = {}) {
+ return renderWithTheme(
+ <IntlProvider locale="en" messages={messages.en}>
+ <ExportMapModal {...defaultProps} {...props} />
+ </IntlProvider>
+ );
+}
+
+function expectCenteredRowLabel(control: HTMLElement) {
+ const section = control.closest('.selection')?.parentElement;
+ const description = section?.querySelector('.description') as HTMLElement;
+
+ expect(getComputedStyle(description).alignSelf).toBe('center');
+ expect(getComputedStyle(description).paddingTop).toBe('0px');
+}
+
+function getPortableExportMapRule() {
+ return Array.from(document.styleSheets)
+ .flatMap(styleSheet => Array.from(styleSheet.cssRules))
+ .find(
+ rule =>
+ rule.cssText.includes('@media (max-width: 768px)') &&
+ rule.cssText.includes('.export-map-modal__json-options .viewer')
+ )?.cssText;
+}
+
+describe('ExportMapModal', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ initApplicationConfig({enableCustomExportBranding: false});
+ });
+
+ afterEach(() => {
+ initApplicationConfig({enableCustomExportBranding: false});
+ });
+
+ test('keeps map details collapsed and puts the file extension note in a tooltip', () => {
+ const {container, getByLabelText, getByRole, queryByLabelText, queryByRole} = renderModal();
+
+ const detailsButton = getByRole('button', {name: 'Map details'});
+ expect(detailsButton).toHaveAttribute('aria-expanded', 'false');
+ expect(detailsButton).toHaveAttribute('aria-controls', 'export-map-details-content');
+ expect(queryByLabelText('Name')).toBeNull();
+ expect(queryByLabelText('Description')).toBeNull();
+ expect(queryByRole('button', {name: 'Branding'})).toBeNull();
+
+ const fileNameInput = getByLabelText('File name');
+ expect(fileNameInput).toBeInTheDocument();
+ expectCenteredRowLabel(fileNameInput);
+ const fileNameHelp = getByRole('button', {
+ name: 'The file type is added automatically.'
+ });
+ expect(fileNameHelp).toHaveAttribute('aria-describedby', 'export-map-file-name-extension-help');
+ expect(document.getElementById('export-map-file-name-extension-help')).toHaveTextContent(
+ 'The file type is added automatically.'
+ );
+ expect(fileNameHelp.closest('.description')?.querySelector('.subtitle')).toBeNull();
+
+ const formatHelp = getByRole('button', {name: 'About HTML and JSON formats'});
+ expect(formatHelp).toHaveAttribute('aria-describedby', 'export-map-format-help');
+ expect(formatHelp.parentElement).toHaveTextContent('Map format');
+ expect(document.getElementById('export-map-format-help')).toHaveTextContent(
+ 'HTML: A standalone interactive map you can open in a browser.'
+ );
+ expect(document.getElementById('export-map-format-help')).toHaveTextContent(
+ 'JSON: Map data and configuration you can reopen in kepler.gl.'
+ );
+ const portableRule = getPortableExportMapRule();
+ expect(portableRule).toContain("input[type='text']");
+ expect(portableRule).toContain('select');
+ expect(portableRule).toContain("[role='status']");
+ expect(portableRule).toContain('.export-map-modal__json-options .viewer');
+ expect(portableRule).toContain('.export-map-modal__collapsible-section');
+ expect(portableRule).toContain('max-width: none');
+
+ fireEvent.click(detailsButton);
+ expect(detailsButton).toHaveAttribute('aria-expanded', 'true');
+ expect(getByLabelText('Name')).toHaveValue('City map');
+ expect(getByLabelText('Description')).toHaveValue('A city map');
+ expect(getByRole('region', {name: 'Map details'})).toBeInTheDocument();
+ expect(queryByLabelText('Application name')).toBeNull();
+ expect(queryByLabelText('Website')).toBeNull();
+
+ fireEvent.change(getByLabelText('Name'), {target: {value: 'Updated map'}});
+ expect(defaultProps.onMapInfoDraft).toHaveBeenCalledWith({
+ title: 'Updated map',
+ description: 'A city map'
+ });
+ expect(container.querySelector('#export-map-details-content')).toBeInTheDocument();
+ });
+
+ test('uses a compact mode dropdown and exposes inherited branding when enabled', () => {
+ initApplicationConfig({enableCustomExportBranding: true});
+ const {container, getByLabelText, getByRole, queryByLabelText, queryByRole, queryByText} =
+ renderModal();
+
+ const formatGroup = getByRole('group', {name: 'Map format'});
+ const htmlFormat = within(formatGroup).getByRole('button', {name: 'html'});
+ const jsonFormat = within(formatGroup).getByRole('button', {name: 'json'});
+ expect(htmlFormat).toHaveAttribute('aria-pressed', 'true');
+ expect(jsonFormat).toHaveAttribute('aria-pressed', 'false');
+ fireEvent.click(jsonFormat);
+ expect(defaultProps.onChangeExportMapFormat).toHaveBeenCalledWith(EXPORT_MAP_FORMATS.JSON);
+
+ const includeApiKeys = getByRole('checkbox', {name: 'Include layer API keys'});
+ expect(includeApiKeys).not.toBeChecked();
+ expectCenteredRowLabel(includeApiKeys);
+ fireEvent.click(includeApiKeys);
+ expect(defaultProps.onChangeExportIncludeLayerApiKeys).toHaveBeenCalledWith(true);
+ const apiKeysHelp = getByRole('button', {name: 'About layer API keys'});
+ expect(apiKeysHelp).toHaveAttribute(
+ 'aria-describedby',
+ 'export-include-layer-api-keys-html-help'
+ );
+ expect(document.getElementById('export-include-layer-api-keys-html-help')).toHaveTextContent(
+ 'When unchecked, access tokens stored on layers are removed from the exported file.'
+ );
+ expect(apiKeysHelp.closest('.description')?.querySelector('.subtitle')).toBeNull();
+ const includeApiKeysLabel = includeApiKeys
+ .closest('.kg-checkbox')
+ ?.querySelector('label') as HTMLElement;
+ expect(getComputedStyle(includeApiKeysLabel).marginBottom).toBe('0px');
+ const apiKeysSection = apiKeysHelp.closest('.description')?.parentElement as HTMLElement;
+ const formatPanels = apiKeysSection
+ .closest('.export-map-modal')
+ ?.querySelector('[aria-hidden="false"]')?.parentElement as HTMLElement;
+ expect(getComputedStyle(formatPanels).marginTop).toBe('0px');
+ expect(getComputedStyle(formatPanels).paddingTop).toBe('0px');
+ expect(getComputedStyle(apiKeysSection).marginTop).toBe('0px');
+ expect(getComputedStyle(apiKeysSection).marginBottom).toBe('16px');
+ expect(getComputedStyle(apiKeysSection.nextElementSibling as Element).marginTop).toBe('16px');
+
+ const tokenInput = getByLabelText('Mapbox access token');
+ const tokenNotice = getByRole('status');
+ expect(tokenInput).toHaveAttribute('aria-describedby', 'export-map-token-guidance');
+ expect(getComputedStyle(tokenNotice).maxWidth).toBe(getComputedStyle(tokenInput).maxWidth);
+ expect(getComputedStyle(tokenNotice).width).toBe(getComputedStyle(tokenInput).width);
+ expect(tokenNotice).toHaveTextContent(
+ 'If this map uses Mapbox and you do not provide your own token, it may stop displaying when the shared token changes.'
+ );
+ expect(getByRole('link', {name: 'Learn how to update the token.'})).toHaveAttribute(
+ 'href',
+ EXPORT_HTML_MAP_DOC
+ );
+ fireEvent.change(tokenInput, {target: {value: 'pk.test'}});
+ expect(defaultProps.onEditUserMapboxAccessToken).toHaveBeenCalledWith('pk.test');
+
+ const modeSelect = getByLabelText('Map mode') as HTMLSelectElement;
+ expect(modeSelect.tagName).toBe('SELECT');
+ expect(modeSelect.value).toBe(EXPORT_HTML_MAP_MODES.READ);
+ expect(Array.from(modeSelect.options).map(option => option.text)).toEqual([
+ 'View only',
+ 'View and edit'
+ ]);
+ const modeHelp = getByRole('button', {name: 'About map modes'});
+ expect(modeHelp).toHaveAttribute('aria-describedby', 'export-map-html-mode-help');
+ expect(document.getElementById('export-map-html-mode-help')).toHaveTextContent(
+ 'View only: Hides editing controls; viewers can still explore the map.'
+ );
+ expect(document.getElementById('export-map-html-mode-help')).toHaveTextContent(
+ 'View and edit: Shows editing controls so viewers can change the map.'
+ );
+ expect(queryByRole('link', {name: 'Learn more'})).toBeNull();
+ expect(container.querySelector('img')).toBeNull();
+
+ fireEvent.change(modeSelect, {target: {value: EXPORT_HTML_MAP_MODES.EDIT}});
+ expect(defaultProps.onChangeExportMapHTMLMode).toHaveBeenCalledWith(EXPORT_HTML_MAP_MODES.EDIT);
+
+ const detailsButton = getByRole('button', {name: 'Map details'});
+ const mapModeSection = modeSelect.closest('.selection')?.parentElement as HTMLElement;
+ const detailsSection = detailsButton.parentElement as HTMLElement;
+ expect(
+ modeSelect.compareDocumentPosition(detailsButton) & Node.DOCUMENT_POSITION_FOLLOWING
+ ).toBeTruthy();
+ expect(getComputedStyle(mapModeSection).marginBottom).toBe('0px');
+ expect(getComputedStyle(detailsSection).marginTop).toBe('4px');
+ expect(getComputedStyle(detailsSection).maxWidth).toBe('584px');
+ expect(queryByText('Name, description and branding')).toBeNull();
+ expect(queryByRole('button', {name: 'Branding'})).toBeNull();
+ expect(detailsButton).toHaveAttribute('aria-expanded', 'false');
+ expect(queryByLabelText('Application name')).toBeNull();
+ expect(queryByLabelText('Website')).toBeNull();
+
+ fireEvent.click(detailsButton);
+ expect(detailsButton).toHaveAttribute('aria-expanded', 'true');
+ expect(getByLabelText('Application name')).toHaveValue('Acme Maps');
+ expect(getByLabelText('Website')).toHaveValue('https://maps.acme.test');
+ ['Name', 'Description', 'Application name', 'Website'].forEach(label =>
+ expectCenteredRowLabel(getByLabelText(label))
+ );
+
+ fireEvent.change(getByLabelText('Application name'), {target: {value: 'Atlas'}});
+ expect(defaultProps.onChangeExportMapBranding).toHaveBeenCalledWith({appName: 'Atlas'});
+
+ fireEvent.change(getByLabelText('Website'), {target: {value: 'https://atlas.test'}});
+ expect(defaultProps.onChangeExportMapBranding).toHaveBeenCalledWith({
+ appWebsite: 'https://atlas.test'
+ });
+ });
+
+ test('keeps an empty application name while clearing and retyping', () => {
+ initApplicationConfig({enableCustomExportBranding: true});
+
+ function ControlledExportMapModal() {
+ const [options, setOptions] = React.useState(INITIAL_UI_STATE.exportMap);
+
+ return (
+ <ExportMapModal
+ {...defaultProps}
+ options={options}
+ onChangeExportMapBranding={branding =>
+ setOptions(currentOptions => ({...currentOptions, ...branding}))
+ }
+ />
+ );
+ }
+
+ const {getByLabelText, getByRole} = renderWithTheme(
+ <IntlProvider locale="en" messages={messages.en}>
+ <ControlledExportMapModal />
+ </IntlProvider>
+ );
+
+ fireEvent.click(getByRole('button', {name: 'Map details'}));
+ const appNameInput = getByLabelText('Application name');
+ expect(appNameInput).toHaveValue('Acme Maps');
+
+ fireEvent.change(appNameInput, {target: {value: ''}});
+ expect(appNameInput).toHaveValue('');
+
+ fireEvent.change(appNameInput, {target: {value: 'Atlas'}});
+ expect(appNameInput).toHaveValue('Atlas');
+ });
+
+ test('shows the security notice when a custom Mapbox token is embedded', () => {
+ const options = {
+ ...INITIAL_UI_STATE.exportMap,
+ HTML: {...INITIAL_UI_STATE.exportMap.HTML, userMapboxToken: 'pk.test'}
+ };
+ const {getByRole, queryByText} = renderModal({options});
+
+ expect(getByRole('status')).toHaveTextContent(
+ 'Your Mapbox token will be visible to anyone with the exported HTML.'
+ );
+ expect(
+ queryByText(
+ 'If this map uses Mapbox and you do not provide your own token, it may stop displaying when the shared token changes.'
+ )
+ ).toBeNull();
+ });
+
+ test('keeps the JSON panel compact and exposes shared export branding', () => {
+ initApplicationConfig({enableCustomExportBranding: true});
+ const options = {
+ ...INITIAL_UI_STATE.exportMap,
+ format: EXPORT_MAP_FORMATS.JSON,
+ appName: 'Atlas JSON',
+ appWebsite: 'https://json.atlas.test'
+ };
+ const {container, getByLabelText, getByRole, getByText, queryByText} = renderModal({options});
+ const inactivePanel = container.querySelector('[inert]') as HTMLElement;
+
+ expect(inactivePanel).not.toBeNull();
+ expect(getComputedStyle(inactivePanel).display).toBe('none');
+ expect(
+ queryByText(
+ 'Export current map data and config into a single Json file. You can later open the same map by uploading this file to kepler.gl.'
+ )
+ ).toBeNull();
+ expect(getByText('Map Config')).toBeInTheDocument();
+ expect(getByRole('button', {name: 'About layer API keys'})).toHaveAttribute(
+ 'aria-describedby',
+ 'export-include-layer-api-keys-json-help'
+ );
+ const configWarning = container.querySelector('#export-map-json-config-warning') as HTMLElement;
+ const configViewer = container.querySelector(
+ '.export-map-modal__json-options .viewer'
+ ) as HTMLElement;
+ expect(configWarning).toHaveAttribute('role', 'status');
+ expect(configWarning).toHaveTextContent('Map config is coupled with loaded datasets.');
+ expect(configWarning.querySelector('svg')).not.toBeNull();
+ expect(getComputedStyle(configWarning).borderLeftWidth).toBe('2px');
+ expect(getComputedStyle(configWarning).fontSize).toBe('11px');
+ expect(getComputedStyle(configViewer).maxWidth).toBe('380px');
+ expect(getComputedStyle(configWarning).maxWidth).toBe(getComputedStyle(configViewer).maxWidth);
+ expect(getComputedStyle(configWarning).width).toBe(getComputedStyle(configViewer).width);
+
+ fireEvent.click(getByRole('button', {name: 'Map details'}));
+ expect(getByLabelText('Application name')).toHaveValue('Atlas JSON');
+ expect(getByLabelText('Website')).toHaveValue('https://json.atlas.test');
+
+ fireEvent.change(getByLabelText('Application name'), {target: {value: 'Updated Atlas'}});
+ expect(defaultProps.onChangeExportMapBranding).toHaveBeenCalledWith({
+ appName: 'Updated Atlas'
+ });
+
+ fireEvent.change(getByLabelText('Website'), {target: {value: 'https://updated.atlas.test'}});
+ expect(defaultProps.onChangeExportMapBranding).toHaveBeenCalledWith({
+ appWebsite: 'https://updated.atlas.test'
+ });
+ });
+});
diff --git a/src/components/src/modals/export-map-modal/export-map-modal.tsx b/src/components/src/modals/export-map-modal/export-map-modal.tsx
index babe96a82..11c892829 100644
--- a/src/components/src/modals/export-map-modal/export-map-modal.tsx
+++ b/src/components/src/modals/export-map-modal/export-map-modal.tsx
@@ -5,19 +5,24 @@ import React, {useState} from 'react';
import styled from 'styled-components';
import {useIntl} from 'react-intl';
-import {FileType} from '../../common/icons';
-import {StyledType, CheckMark, InputLight} from '../../common/styled-components';
+import {InputLight} from '../../common/styled-components';
import {
EXPORT_MAP_FORMATS,
EXPORT_MAP_FORMAT_OPTIONS,
+ KEPLER_GL_NAME,
+ KEPLER_GL_WEBSITE,
MAP_INFO_CHARACTER
} from '@kepler.gl/constants';
import {MapInfo} from '@kepler.gl/types';
+import {getApplicationConfig} from '@kepler.gl/utils';
import {
StyledExportMapModalContent,
StyledExportMapSection,
StyledExportMapFormatPanels,
- StyledExportMapFormatPanel
+ StyledExportMapFormatPanel,
+ CollapsibleExportMapSection,
+ ExportMapHelp,
+ ExportMapSectionTitle
} from './components';
import ExportHtmlMapFactory from './export-html-map';
import ExportJsonMapFactory from './export-json-map';
@@ -26,6 +31,7 @@ import {
ActionHandler,
setExportHTMLMapMode,
setExportIncludeLayerApiKeys,
+ setExportMapBranding,
setExportMapFileName,
setUserMapboxAccessToken
} from '@kepler.gl/actions';
@@ -35,15 +41,20 @@ interface ExportMapModalOptions {
format: string;
includeLayerApiKeys?: boolean;
fileName?: string;
+ appName?: string;
+ appWebsite?: string;
[key: string]: any;
}
interface ExportMapModalFactoryProps {
options?: ExportMapModalOptions;
config: any;
+ appName?: string;
+ appWebsite?: string;
mapInfo?: Partial<MapInfo>;
onEditUserMapboxAccessToken: ActionHandler<typeof setUserMapboxAccessToken>;
onChangeExportMapHTMLMode?: ActionHandler<typeof setExportHTMLMapMode>;
+ onChangeExportMapBranding?: ActionHandler<typeof setExportMapBranding>;
onChangeExportIncludeLayerApiKeys?: ActionHandler<typeof setExportIncludeLayerApiKeys>;
onChangeExportMapFormat?: (format: string) => any;
onChangeExportMapFileName?: ActionHandler<typeof setExportMapFileName>;
@@ -54,15 +65,53 @@ interface ExportMapModalFactoryProps {
const MapInfoInput = styled(InputLight)`
width: 100%;
- max-width: 320px;
+ max-width: 380px;
`;
const style = {width: '100%'};
-const CompactType = styled(StyledType)`
- height: 64px;
- width: 64px;
- padding: 4px;
+const FormatSelector = styled.div`
+ display: flex;
+ gap: 8px;
+`;
+
+const FormatButton = styled.button.attrs({type: 'button'})<{$selected: boolean}>`
+ align-items: center;
+ background-color: ${props =>
+ props.$selected ? props.theme.selectionBtnActBgd : props.theme.selectionBtnBgd};
+ border: 1px solid
+ ${props =>
+ props.$selected
+ ? props.theme.selectionBtnBorderActColor
+ : props.theme.selectionBtnBorderColor};
+ border-radius: 2px;
+ color: ${props => (props.$selected ? props.theme.selectionBtnActColor : props.theme.textColorLT)};
+ cursor: pointer;
+ display: inline-flex;
+ font-family: ${props => props.theme.fontFamilyMedium ?? props.theme.fontFamily};
+ font-size: 12px;
+ font-weight: 500;
+ height: 38px;
+ justify-content: center;
+ letter-spacing: 0.3px;
+ min-width: 92px;
+ padding: 0 18px;
+ text-transform: uppercase;
+
+ &:hover:not(:disabled) {
+ border-color: ${props => props.theme.selectionBtnBorderActColor};
+ color: ${props => props.theme.selectionBtnActColor};
+ }
+
+ &:focus-visible {
+ box-shadow: 0 0 0 2px ${props => props.theme.activeColorLT};
+ outline: 0;
+ }
+
+ &:disabled {
+ cursor: not-allowed;
+ opacity: 0.45;
+ }
`;
const NO_OP = () => ({} as any);
@@ -75,8 +124,11 @@ function ExportMapModalFactory(
) {
const ExportMapModalUnmemoized = ({
config = {},
+ appName,
+ appWebsite,
onChangeExportMapFormat = NO_OP,
onChangeExportMapHTMLMode = NO_OP,
+ onChangeExportMapBranding = NO_OP,
onChangeExportIncludeLayerApiKeys = NO_OP,
onChangeExportMapFileName = NO_OP,
onEditUserMapboxAccessToken = NO_OP,
@@ -87,6 +139,8 @@ function ExportMapModalFactory(
const intl = useIntl();
const [draftTitle, setDraftTitle] = useState(mapInfo?.title ?? '');
const [draftDescription, setDraftDescription] = useState(mapInfo?.description ?? '');
+ const htmlOptions = options[EXPORT_MAP_FORMATS.HTML] || {};
+ const showCustomExportBranding = getApplicationConfig().enableCustomExportBranding;
return (
<StyledExportMapModalContent className="export-map-modal">
<div style={style}>
@@ -98,67 +152,41 @@ function ExportMapModalFactory(
/>
<StyledExportMapSection>
<div className="description">
- <div className="title">
- <FormattedMessage id="modal.exportMap.nameTitle" />
- </div>
- </div>
- <div className="selection">
- <MapInfoInput
- id="export-map-name"
- type="text"
- value={draftTitle}
- maxLength={MAP_INFO_CHARACTER.title}
- aria-label={intl.formatMessage({id: 'modal.exportMap.nameTitle'})}
- onChange={event => {
- const title = event.target.value;
- setDraftTitle(title);
- onMapInfoDraft({title, description: draftDescription});
- }}
- />
- </div>
- </StyledExportMapSection>
- <StyledExportMapSection>
- <div className="description">
- <div className="title">
- <FormattedMessage id="modal.exportMap.descriptionTitle" />
- </div>
- </div>
- <div className="selection">
- <MapInfoInput
- id="export-map-description"
- type="text"
- value={draftDescription}
- maxLength={MAP_INFO_CHARACTER.description}
- aria-label={intl.formatMessage({id: 'modal.exportMap.descriptionTitle'})}
- onChange={event => {
- const description = event.target.value;
- setDraftDescription(description);
- onMapInfoDraft({title: draftTitle, description});
- }}
- />
- </div>
- </StyledExportMapSection>
- <StyledExportMapSection>
- <div className="description">
- <div className="title">
+ <ExportMapSectionTitle>
<FormattedMessage id={'modal.exportMap.formatTitle'} />
- </div>
+ <ExportMapHelp
+ id="export-map-format-help"
+ label={intl.formatMessage({id: 'modal.exportMap.formatHelpLabel'})}
+ >
+ <div>
+ <strong>HTML:</strong> <FormattedMessage id="modal.exportMap.formatHtmlHelp" />
+ </div>
+ <div>
+ <strong>JSON:</strong> <FormattedMessage id="modal.exportMap.formatJsonHelp" />
+ </div>
+ </ExportMapHelp>
+ </ExportMapSectionTitle>
<div className="subtitle">
<FormattedMessage id={'modal.exportMap.formatSubtitle'} />
</div>
</div>
<div className="selection">
- {EXPORT_MAP_FORMAT_OPTIONS.map(op => (
- <CompactType
- key={op.id}
- selected={options.format === op.id}
- onClick={() => op.available && onChangeExportMapFormat(op.id)}
- >
- <FileType ext={op.label} height="48px" fontSize="10px" />
-
- {options.format === op.id && <CheckMark />}
- </CompactType>
- ))}
+ <FormatSelector
+ role="group"
+ aria-label={intl.formatMessage({id: 'modal.exportMap.formatTitle'})}
+ >
+ {EXPORT_MAP_FORMAT_OPTIONS.map(op => (
+ <FormatButton
+ key={op.id}
+ $selected={options.format === op.id}
+ aria-pressed={options.format === op.id}
+ disabled={!op.available}
+ onClick={() => onChangeExportMapFormat(op.id)}
+ >
+ {op.label}
+ </FormatButton>
+ ))}
+ </FormatSelector>
</div>
</StyledExportMapSection>
<StyledExportMapFormatPanels>
@@ -172,7 +200,7 @@ function ExportMapModalFactory(
onChangeExportIncludeLayerApiKeys={onChangeExportIncludeLayerApiKeys}
onEditUserMapboxAccessToken={onEditUserMapboxAccessToken}
includeLayerApiKeys={Boolean(options.includeLayerApiKeys)}
- options={options[EXPORT_MAP_FORMATS.HTML]}
+ options={htmlOptions}
/>
</StyledExportMapFormatPanel>
{options.format === EXPORT_MAP_FORMATS.JSON ? (
@@ -185,6 +213,91 @@ function ExportMapModalFactory(
</StyledExportMapFormatPanel>
) : null}
</StyledExportMapFormatPanels>
+ <CollapsibleExportMapSection
+ id="export-map-details"
+ title={<FormattedMessage id="modal.exportMap.mapDetailsTitle" />}
+ >
+ <StyledExportMapSection>
+ <div className="description description--centered">
+ <div className="title">
+ <FormattedMessage id="modal.exportMap.nameTitle" />
+ </div>
+ </div>
+ <div className="selection">
+ <MapInfoInput
+ id="export-map-name"
+ type="text"
+ value={draftTitle}
+ maxLength={MAP_INFO_CHARACTER.title}
+ aria-label={intl.formatMessage({id: 'modal.exportMap.nameTitle'})}
+ onChange={event => {
+ const title = event.target.value;
+ setDraftTitle(title);
+ onMapInfoDraft({title, description: draftDescription});
+ }}
+ />
+ </div>
+ </StyledExportMapSection>
+ <StyledExportMapSection>
+ <div className="description description--centered">
+ <div className="title">
+ <FormattedMessage id="modal.exportMap.descriptionTitle" />
+ </div>
+ </div>
+ <div className="selection">
+ <MapInfoInput
+ id="export-map-description"
+ type="text"
+ value={draftDescription}
+ maxLength={MAP_INFO_CHARACTER.description}
+ aria-label={intl.formatMessage({id: 'modal.exportMap.descriptionTitle'})}
+ onChange={event => {
+ const description = event.target.value;
+ setDraftDescription(description);
+ onMapInfoDraft({title: draftTitle, description});
+ }}
+ />
+ </div>
+ </StyledExportMapSection>
+ {showCustomExportBranding ? (
+ <>
+ <StyledExportMapSection>
+ <div className="description description--centered">
+ <div className="title">
+ <FormattedMessage id="modal.exportMap.appNameTitle" />
+ </div>
+ </div>
+ <div className="selection">
+ <MapInfoInput
+ id="export-map-app-name"
+ type="text"
+ value={options.appName ?? appName ?? KEPLER_GL_NAME}
+ aria-label={intl.formatMessage({id: 'modal.exportMap.appNameTitle'})}
+ onChange={event => onChangeExportMapBranding({appName: event.target.value})}
+ />
+ </div>
+ </StyledExportMapSection>
+ <StyledExportMapSection>
+ <div className="description description--centered">
+ <div className="title">
+ <FormattedMessage id="modal.exportMap.appWebsiteTitle" />
+ </div>
+ </div>
+ <div className="selection">
+ <MapInfoInput
+ id="export-map-app-website"
+ type="text"
+ value={options.appWebsite ?? appWebsite ?? KEPLER_GL_WEBSITE}
+ aria-label={intl.formatMessage({id: 'modal.exportMap.appWebsiteTitle'})}
+ onChange={event =>
+ onChangeExportMapBranding({appWebsite: event.target.value})
+ }
+ />
+ </div>
+ </StyledExportMapSection>
+ </>
+ ) : null}
+ </CollapsibleExportMapSection>
</div>
</StyledExportMapModalContent>
);
diff --git a/src/localization/src/translations/en.ts b/src/localization/src/translations/en.ts
index 10dabcd6d..d8b854997 100644
--- a/src/localization/src/translations/en.ts
+++ b/src/localization/src/translations/en.ts
@@ -824,10 +824,18 @@ export default {
},
exportMap: {
formatTitle: 'Map format',
- formatSubtitle: 'Choose the format to export your map to',
+ formatSubtitle: 'Choose an export format',
+ formatHelpLabel: 'About HTML and JSON formats',
+ formatHtmlHelp: 'A standalone interactive map you can open in a browser.',
+ formatJsonHelp: 'Map data and configuration you can reopen in kepler.gl.',
+ mapDetailsTitle: 'Map details',
nameTitle: 'Name',
descriptionTitle: 'Description',
+ appNameTitle: 'Application name',
+ appWebsiteTitle: 'Website',
+ includeApiKeysTitle: 'Layer API keys',
includeApiKeys: 'Include layer API keys',
+ includeApiKeysHelpLabel: 'About layer API keys',
includeApiKeysSubtitle:
'When unchecked, access tokens stored on layers are removed from the exported file.',
html: {
@@ -839,14 +847,21 @@ export default {
'* If you do not provide your own token, the map may fail to display at any time when we replace ours to avoid misuse. ',
tokenSecurityWarning:
'* Warning: your Mapbox token will be embedded in the exported HTML file. Anyone with access to this file can see and use your token. Use a scoped token with URL restrictions when possible. ',
+ tokenSharedNotice:
+ 'If this map uses Mapbox and you do not provide your own token, it may stop displaying when the shared token changes.',
+ tokenEmbeddedNotice:
+ 'Your Mapbox token will be visible to anyone with the exported HTML. Use a scoped token with URL restrictions.',
tokenDisclaimer: 'You can change the Mapbox token later using the following instructions: ',
- tokenUpdate: 'How to update an existing map token.',
- modeTitle: 'Map Mode',
- modeSubtitle1: 'Select the app mode. More ',
- modeSubtitle2: 'info',
+ tokenUpdate: 'Learn how to update the token.',
+ modeTitle: 'Map mode',
+ modeSubtitle1: 'Choose what viewers can do.',
+ modeSubtitle2: 'Learn more',
+ modeHelpLabel: 'About map modes',
+ modeReadHelp: 'Hides editing controls; viewers can still explore the map.',
+ modeEditHelp: 'Shows editing controls so viewers can change the map.',
modeDescription: 'Allow users to {mode} the map',
- read: 'read',
- edit: 'edit'
+ read: 'View only',
+ edit: 'View and edit'
},
json: {
configTitle: 'Map Config',
diff --git a/src/reducers/src/ui-state-updaters.ts b/src/reducers/src/ui-state-updaters.ts
index 9ff91836b..138d99d1c 100644
--- a/src/reducers/src/ui-state-updaters.ts
+++ b/src/reducers/src/ui-state-updaters.ts
@@ -864,6 +864,24 @@ export const setExportMapHTMLModeUpdater = (
}
});
+/**
+ * Set application branding overrides for exported maps.
+ * @param state - `uiState`
+ * @param action
+ * @param action.payload application name and/or website overrides
+ * @return nextState
+ */
+export const setExportMapBrandingUpdater = (
+ state: UiState,
+ {payload}: UIStateActions.SetExportMapBrandingUpdaterAction
+): UiState => ({
+ ...state,
+ exportMap: {
+ ...state.exportMap,
+ ...payload
+ }
+});
+
/**
* Whether to keep layer access tokens in exported HTML and JSON maps.
* @param state - `uiState`
diff --git a/src/reducers/src/ui-state.ts b/src/reducers/src/ui-state.ts
index 781654304..3cc440076 100644
--- a/src/reducers/src/ui-state.ts
+++ b/src/reducers/src/ui-state.ts
@@ -41,6 +41,7 @@ const actionHandler = {
[ActionTypes.SET_EXPORT_MAP_FORMAT]: uiStateUpdaters.setExportMapFormatUpdater,
[ActionTypes.SET_EXPORT_MAP_HTML_MODE]: uiStateUpdaters.setExportMapHTMLModeUpdater,
+ [ActionTypes.SET_EXPORT_MAP_BRANDING]: uiStateUpdaters.setExportMapBrandingUpdater,
[ActionTypes.SET_EXPORT_MAP_FILE_NAME]: uiStateUpdaters.setExportMapFileNameUpdater,
[ActionTypes.SET_EXPORT_INCLUDE_LAYER_API_KEYS]:
uiStateUpdaters.setExportIncludeLayerApiKeysUpdater,
diff --git a/src/schemas/src/schema-manager.ts b/src/schemas/src/schema-manager.ts
index a229be430..abeb027a0 100644
--- a/src/schemas/src/schema-manager.ts
+++ b/src/schemas/src/schema-manager.ts
@@ -87,6 +87,9 @@ export type SavedMap = {
created_at: string;
title?: string;
description?: string;
+ source?: string;
+ appName?: string;
+ appWebsite?: string;
};
};
diff --git a/src/types/reducers.d.ts b/src/types/reducers.d.ts
index 1fa76d7a1..fc9b8b25d 100644
--- a/src/types/reducers.d.ts
+++ b/src/types/reducers.d.ts
@@ -585,6 +585,10 @@ export type ExportMap = {
fileName: string;
/** When false, dataset access tokens are omitted from exported HTML and JSON. */
includeLayerApiKeys: boolean;
+ /** Optional application name override for exported HTML and JSON. */
+ appName?: string;
+ /** Optional application website override for exported HTML and JSON. */
+ appWebsite?: string;
};
export type ExportVideo = {
diff --git a/src/types/schemas.d.ts b/src/types/schemas.d.ts
index bca249111..38548cc63 100644
--- a/src/types/schemas.d.ts
+++ b/src/types/schemas.d.ts
@@ -297,6 +297,9 @@ export type SavedMap = {
created_at: string;
title?: string;
description?: string;
+ source?: string;
+ appName?: string;
+ appWebsite?: string;
};
};
diff --git a/src/utils/src/application-config.ts b/src/utils/src/application-config.ts
index 40a2d3d38..1a3d52211 100644
--- a/src/utils/src/application-config.ts
+++ b/src/utils/src/application-config.ts
@@ -119,6 +119,11 @@ export type KeplerApplicationConfig = {
defaultExportJsonSettings?: {
hasData?: boolean;
};
+ /**
+ * Whether to show editable application name and website controls for exported maps.
+ * Enabled by default.
+ */
+ enableCustomExportBranding?: boolean;
baseMapLibraryConfig?: Record<BaseMapLibraryType, BaseMapLibraryConfig>;
plugins?: any[];
// KeplerTable alternative
@@ -398,6 +403,7 @@ const DEFAULT_APPLICATION_CONFIG: Required<KeplerApplicationConfig> = {
defaultExportJsonSettings: {
hasData: true
},
+ enableCustomExportBranding: true,
baseMapLibraryConfig: {
maplibre: {
diff --git a/src/utils/src/export-map-html.ts b/src/utils/src/export-map-html.ts
index 47e737764..2e8d24818 100644
--- a/src/utils/src/export-map-html.ts
+++ b/src/utils/src/export-map-html.ts
@@ -1,7 +1,12 @@
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
-import {EXPORT_HTML_MAP_MODES, KEPLER_GL_VERSION} from '@kepler.gl/constants';
+import {
+ EXPORT_HTML_MAP_MODES,
+ KEPLER_GL_NAME,
+ KEPLER_GL_VERSION,
+ KEPLER_GL_WEBSITE
+} from '@kepler.gl/constants';
import {optionalMapInfo} from './map-info-utils';
// React (and react-dom) no longer publish UMD builds starting with v19, so the
@@ -31,6 +36,42 @@ function toScriptJSON(value: unknown): string {
.replace(/\u2029/g, '\\u2029');
}
+/** Escape text interpolated directly into HTML markup. */
+function escapeHTML(value: string): string {
+ return value
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;')
+ .replace(/'/g, '&#39;');
+}
+
+/** Resolve user-entered branding links to an absolute HTTP(S) URL. */
+function normalizeAppWebsite(value: unknown): string {
+ if (typeof value !== 'string' || !value.trim()) {
+ return KEPLER_GL_WEBSITE;
+ }
+
+ const trimmedValue = value.trim();
+ const hasScheme = /^[a-z][a-z\d+.-]*:/i.test(trimmedValue);
+ if (hasScheme && !/^https?:/i.test(trimmedValue)) {
+ return KEPLER_GL_WEBSITE;
+ }
+
+ const absoluteValue = /^https?:/i.test(trimmedValue)
+ ? trimmedValue
+ : trimmedValue.startsWith('//')
+ ? `https:${trimmedValue}`
+ : `https://${trimmedValue}`;
+
+ try {
+ const url = new URL(absoluteValue);
+ return url.protocol === 'http:' || url.protocol === 'https:' ? url.href : KEPLER_GL_WEBSITE;
+ } catch {
+ return KEPLER_GL_WEBSITE;
+ }
+}
+
/**
* This method is used to create an html file which will inlcude kepler and map data
* @param {Object} options Object that collects all necessary data to create the html file
@@ -38,15 +79,22 @@ function toScriptJSON(value: unknown): string {
* @param {Array<Object>} options.datasets Data to include in the map
* @param {Object} options.config this object will contain the full kepler.gl instance configuration {mapState, mapStyle, visState}
* @param {Object} [options.info] map title and description
+ * @param {string} [options.appName] application name used by the exported map
+ * @param {string} [options.appWebsite] application website linked by the exported map
* @param {string} version which version of Kepler.gl to load.
*/
export const exportMapToHTML = (options, version = KEPLER_GL_VERSION) => {
+ const appName =
+ typeof options.appName === 'string' && options.appName ? options.appName : KEPLER_GL_NAME;
+ const appWebsite = normalizeAppWebsite(options.appWebsite);
+ const branding = {appName, appWebsite};
+
return `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
- <title>Kepler.gl embedded map</title>
+ <title>${escapeHTML(appName)} embedded map</title>
<!--Uber Font-->
<link rel="stylesheet" href="https://d1a3f4spazzrp4.cloudfront.net/kepler.gl/uber-fonts/4.0.0/superfine.css">
@@ -267,6 +315,8 @@ export const exportMapToHTML = (options, version = KEPLER_GL_VERSION) => {
console.warn('[kepler.gl]', WARNING_MESSAGE);
}
+ const branding = ${toScriptJSON(branding)};
+
/** STORE **/
// Pre-seed styleType so the correct basemap fetch starts on the very
// first render, avoiding a flash of the default dark basemap.
@@ -368,38 +418,41 @@ export const exportMapToHTML = (options, version = KEPLER_GL_VERSION) => {
? KeplerGl.injectComponents([CustomMapControlFactory])
: KeplerGl.KeplerGl;
- var KeplerElement = (function makeKeplerElement(react, keplerGl, mapboxToken) {
- var LogoSvg = function LogoSvg() {
+ var KeplerElement = (function makeKeplerElement(react, keplerGl, mapboxToken, branding) {
+ var BrandLogo = function BrandLogo() {
return react.createElement(
"div",
{ className: "logo-container", style: {position: 'fixed', zIndex: 10000, padding: '4px'} },
react.createElement(
- "svg",
+ "a",
{
className: "kepler_gl__logo",
- width: "107px",
- height: "21px",
- viewBox: "0 0 124 24"
+ href: branding.appWebsite,
+ target: "_blank",
+ rel: "noopener noreferrer",
+ style: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ color: '#1FBAD6',
+ fontFamily: "ff-clan-web-pro, 'Helvetica Neue', Helvetica, sans-serif",
+ fontSize: '14px',
+ fontWeight: 600,
+ letterSpacing: '1.17px',
+ textDecoration: 'none'
+ }
},
react.createElement(
- "g",
- { transform: "translate(13.500000, 13.500000) rotate(45.000000) translate(-13.500000, -13.500000) translate(4.000000, 4.000000)" },
- react.createElement("rect", { x: "0", y: "6", transform: "matrix(2.535181e-06 1 -1 2.535181e-06 18.1107 6.0369)", fill: "#535C6C", width: "12.1", height: "12.1" }),
- react.createElement("rect", { x: "6", y: "0", transform: "matrix(2.535182e-06 1 -1 2.535182e-06 18.1107 -6.0369)", fill:"#1FBAD6", width: "12.1", height: "12.1" })
+ "svg",
+ {width: "22px", height: "15px", viewBox: "0 0 22 15", "aria-hidden": true},
+ react.createElement(
+ "g",
+ {transform: "translate(11, -3) rotate(45.000000)"},
+ react.createElement("rect", {fill: "#535C6C", x: "0", y: "5", width: "10", height: "10"}),
+ react.createElement("rect", {fill: "#1FBAD6", x: "5", y: "0", width: "10", height: "10"})
+ )
),
- react.createElement(
- "g",
- {},
- react.createElement("path", { fill:"#1FBAD6", d: "M39,8.7h2.2l-2.8,4.2l2.9,5.1H39l-2.4-4.2h-1.3V18h-2V5l2-0.1v7.3h1.3L39,8.7z" }),
- react.createElement("path", { fill:"#1FBAD6", d: "M42.4,13.3c0-1.5,0.4-2.7,1.1-3.5s1.8-1.2,3.1-1.2c1.3,0,2.2,0.4,2.8,1.1c0.6,0.7,0.9,1.8,0.9,3.3 c0,0.4,0,0.8,0,1.1h-5.8c0,1.6,0.8,2.4,2.4,2.4c1,0,2-0.2,2.9-0.6l0.2,1.7c-0.4,0.2-0.9,0.4-1.4,0.5s-1.1,0.2-1.7,0.2 c-1.5,0-2.6-0.4-3.3-1.2C42.8,16.1,42.4,14.9,42.4,13.3z M46.6,10.1c-0.7,0-1.2,0.2-1.5,0.5c-0.4,0.4-0.6,0.9-0.6,1.7h4 c0-0.8-0.2-1.4-0.5-1.7S47.2,10.1,46.6,10.1z" }),
- react.createElement("path", { fill:"#1FBAD6", d: "M57.1,18.2c-1,0-1.8-0.3-2.3-0.9l0,0l0,1.3v2.5h-2V8.7h1.5l0.3,0.9h0c0.3-0.3,0.7-0.6,1.2-0.7 c0.4-0.2,0.9-0.3,1.4-0.3c1.2,0,2.1,0.4,2.7,1.1c0.6,0.7,0.9,2,0.9,3.7c0,1.6-0.3,2.8-1,3.7C59.2,17.8,58.3,18.2,57.1,18.2z M56.7,10.3c-0.4,0-0.8,0.1-1.1,0.2c-0.3,0.2-0.6,0.4-0.8,0.7v4.3c0.2,0.3,0.4,0.5,0.7,0.7c0.3,0.2,0.7,0.3,1.1,0.3 c0.7,0,1.2-0.2,1.6-0.7c0.4-0.5,0.5-1.3,0.5-2.5c0-0.8-0.1-1.4-0.2-1.8s-0.4-0.7-0.7-0.9C57.6,10.4,57.2,10.3,56.7,10.3z" }),
- react.createElement("path", { fill:"#1FBAD6", d: "M63.2,16V5l2-0.1v10.8c0,0.3,0.1,0.5,0.2,0.6c0.1,0.1,0.3,0.2,0.6,0.2c0.3,0,0.6,0,0.9-0.1V18 c-0.4,0.1-1,0.2-1.6,0.2c-0.8,0-1.3-0.2-1.7-0.5S63.2,16.8,63.2,16z" }),
- react.createElement("path", { fill:"#1FBAD6", d: "M68.2,13.3c0-1.5,0.4-2.7,1.1-3.5c0.7-0.8,1.8-1.2,3.1-1.2c1.3,0,2.2,0.4,2.8,1.1c0.6,0.7,0.9,1.8,0.9,3.3 c0,0.4,0,0.8,0,1.1h-5.8c0,1.6,0.8,2.4,2.4,2.4c1,0,2-0.2,2.9-0.6l0.2,1.7c-0.4,0.2-0.9,0.4-1.4,0.5s-1.1,0.2-1.7,0.2 c-1.5,0-2.6-0.4-3.3-1.2C68.6,16.1,68.2,14.9,68.2,13.3z M72.4,10.1c-0.7,0-1.2,0.2-1.5,0.5c-0.4,0.4-0.6,0.9-0.6,1.7h4 c0-0.8-0.2-1.4-0.5-1.7S73,10.1,72.4,10.1z" }),
- react.createElement("path", { fill:"#1FBAD6", d: "M80.2,8.7l0.1,1.7h0c0.3-0.6,0.7-1.1,1.1-1.4c0.4-0.3,1-0.5,1.6-0.5c0.4,0,0.7,0,1,0.1l-0.1,2 c-0.3-0.1-0.7-0.2-1-0.2c-0.7,0-1.3,0.3-1.7,0.8c-0.4,0.5-0.7,1.2-0.7,2.1V18h-2V8.7H80.2z" }),
- react.createElement("path", { fill:"#1FBAD6", d: "M83.8,17c0-0.8,0.4-1.2,1.2-1.2c0.8,0,1.2,0.4,1.2,1.2c0,0.8-0.4,1.1-1.2,1.1C84.2,18.2,83.8,17.8,83.8,17z" }),
- react.createElement("path", { fill:"#1FBAD6", d: "M88.5,18.7c0-0.8,0.4-1.4,1.2-1.8c-0.6-0.3-0.9-0.8-0.9-1.5c0-0.7,0.4-1.2,1.1-1.6c-0.3-0.3-0.6-0.6-0.7-0.9 c-0.2-0.4-0.2-0.8-0.2-1.3c0-1,0.3-1.8,0.9-2.3c0.6-0.5,1.6-0.8,2.8-0.8c0.5,0,1,0,1.4,0.1c0.4,0.1,0.8,0.2,1.1,0.4l2.4-0.2v1.5 h-1.5c0.2,0.4,0.2,0.8,0.2,1.3c0,1-0.3,1.7-0.9,2.2s-1.5,0.8-2.7,0.8c-0.7,0-1.2-0.1-1.6-0.2c-0.1,0.1-0.2,0.2-0.3,0.3 c-0.1,0.1-0.1,0.2-0.1,0.4c0,0.2,0.1,0.3,0.2,0.4c0.1,0.1,0.3,0.2,0.6,0.2l2.7,0.2c1,0.1,1.7,0.3,2.2,0.6c0.5,0.3,0.8,0.9,0.8,1.7 c0,0.6-0.2,1.1-0.5,1.5c-0.4,0.4-0.9,0.8-1.5,1c-0.7,0.2-1.5,0.4-2.4,0.4c-1.3,0-2.3-0.2-3-0.6C88.8,20.1,88.5,19.5,88.5,18.7z M95.1,18.4c0-0.3-0.1-0.5-0.3-0.7s-0.6-0.2-1.1-0.3l-2.7-0.3c-0.2,0.1-0.4,0.3-0.5,0.5c-0.1,0.2-0.2,0.4-0.2,0.6 c0,0.4,0.2,0.8,0.5,1c0.4,0.2,1,0.3,1.8,0.3C94.2,19.5,95.1,19.2,95.1,18.4z M94.3,11.5c0-0.6-0.1-1-0.4-1.2 c-0.3-0.2-0.7-0.3-1.3-0.3c-0.7,0-1.1,0.1-1.4,0.3c-0.3,0.2-0.4,0.6-0.4,1.2s0.1,1,0.4,1.2c0.3,0.2,0.7,0.3,1.4,0.3 c0.6,0,1.1-0.1,1.3-0.4S94.3,12,94.3,11.5z" }),
- react.createElement("path", { fill:"#1FBAD6", d: "M99.4,16V5l2-0.1v10.8c0,0.3,0.1,0.5,0.2,0.6c0.1,0.1,0.3,0.2,0.6,0.2c0.3,0,0.6,0,0.9-0.1V18 c-0.4,0.1-1,0.2-1.6,0.2c-0.8,0-1.3-0.2-1.7-0.5S99.4,16.8,99.4,16z" })
- )
+ react.createElement("span", null, branding.appName)
)
);
};
@@ -429,16 +482,18 @@ export const exportMapToHTML = (options, version = KEPLER_GL_VERSION) => {
return react.createElement(
'div',
{style: {position: 'absolute', left: 0, width: '100vw', height: '100vh'}},
- ${options.mode === EXPORT_HTML_MAP_MODES.READ ? 'LogoSvg(),' : ''}
+ ${options.mode === EXPORT_HTML_MAP_MODES.READ ? 'BrandLogo(),' : ''}
react.createElement(KeplerGlComponent, {
mapboxApiAccessToken: mapboxToken,
id: "map",
width: windowDimension.width,
- height: windowDimension.height
+ height: windowDimension.height,
+ appName: branding.appName,
+ appWebsite: branding.appWebsite
})
)
}
- }(React, KeplerGl, MAPBOX_TOKEN));
+ }(React, KeplerGl, MAPBOX_TOKEN, branding));
const app = (function createReactReduxProvider(react, reactRedux, KeplerElement) {
return react.createElement(
diff --git a/src/utils/src/export-utils.ts b/src/utils/src/export-utils.ts
index 71038c942..697dc5815 100644
--- a/src/utils/src/export-utils.ts
+++ b/src/utils/src/export-utils.ts
@@ -7,6 +7,8 @@ import {
EXPORT_IMG_RATIO_OPTIONS,
EXPORT_IMG_RATIOS,
FourByThreeRatioOption,
+ KEPLER_GL_NAME,
+ KEPLER_GL_WEBSITE,
OneXResolutionOption,
type ExportResolutionOption
} from '@kepler.gl/constants';
@@ -224,6 +226,10 @@ type MapJsonOptions = {
hasData?: boolean;
/** When false, access tokens stored on layer datasets are removed. */
includeLayerApiKeys?: boolean;
+ /** Optional application name to preserve in exported JSON metadata. */
+ appName?: string;
+ /** Optional application website to preserve in exported JSON metadata. */
+ appWebsite?: string;
};
export function getMapJSON(
@@ -241,11 +247,23 @@ export function getMapJSON(
if (includeLayerApiKeys === false) {
mapToSave = omitLayerApiKeys(mapToSave);
}
+ if (options.appName !== undefined || options.appWebsite !== undefined) {
+ mapToSave = {
+ ...mapToSave,
+ info: {
+ ...mapToSave.info,
+ ...(options.appName !== undefined ? {appName: options.appName} : {}),
+ ...(options.appWebsite !== undefined ? {appWebsite: options.appWebsite} : {})
+ }
+ };
+ }
return mapToSave;
}
export function exportJson(state, options: any = {}) {
- const map = getMapJSON(state, options);
+ const appName = options.appName || state.appName || KEPLER_GL_NAME;
+ const appWebsite = options.appWebsite ?? state.appWebsite ?? KEPLER_GL_WEBSITE;
+ const map = getMapJSON(state, {...options, appName, appWebsite});
map.info.source = 'kepler.gl';
const fileBlob = new Blob([exportToJsonString(map)], {type: 'application/json'});
const fileName = getExportFileName(
@@ -256,14 +274,26 @@ export function exportJson(state, options: any = {}) {
downloadFile(fileBlob, fileName);
}
+/** Prefer a non-empty user token, otherwise use the configured export token. */
+export function resolveMapboxTokenForExport(
+ userMapboxToken: string | null | undefined,
+ exportMapboxAccessToken: string | null | undefined
+): string | undefined {
+ return userMapboxToken?.trim() || exportMapboxAccessToken?.trim() || undefined;
+}
+
export function exportHtml(state, options) {
- const {userMapboxToken, exportMapboxAccessToken, mode, includeLayerApiKeys} = options;
+ const {userMapboxToken, exportMapboxAccessToken, mode, includeLayerApiKeys, appName, appWebsite} =
+ options;
+ const exportAppName = appName || state.appName || KEPLER_GL_NAME;
+ const exportAppWebsite = appWebsite ?? state.appWebsite ?? KEPLER_GL_WEBSITE;
const data = {
...getMapJSON(state, {hasData: true, includeLayerApiKeys}),
- mapboxApiAccessToken:
- (userMapboxToken || '') !== '' ? userMapboxToken : exportMapboxAccessToken,
- mode
+ mapboxApiAccessToken: resolveMapboxTokenForExport(userMapboxToken, exportMapboxAccessToken),
+ mode,
+ appName: exportAppName,
+ appWebsite: exportAppWebsite
};
const fileBlob = new Blob([exportMapToHTML(data)], {type: 'text/html'});
diff --git a/test/node/reducers/ui-state-test.js b/test/node/reducers/ui-state-test.js
index 64930c0d8..ce49c802e 100644
--- a/test/node/reducers/ui-state-test.js
+++ b/test/node/reducers/ui-state-test.js
@@ -17,6 +17,7 @@ import {
setExportSelectedDataset,
setExportDataType,
setExportFiltered,
+ setExportMapBranding,
setExportMapFileName,
startExportingImage,
addNotification,
@@ -314,6 +315,36 @@ test('#uiStateReducer -> SET_EXPORT_MAP_FILE_NAME', t => {
t.end();
});
+test('#uiStateReducer -> SET_EXPORT_MAP_BRANDING', t => {
+ const withAppName = reducer(INITIAL_UI_STATE, setExportMapBranding({appName: 'Atlas Lab'}));
+
+ t.deepEqual(
+ withAppName.exportMap,
+ {
+ ...INITIAL_UI_STATE.exportMap,
+ appName: 'Atlas Lab'
+ },
+ 'should set the application name and preserve existing export fields'
+ );
+
+ const withWebsite = reducer(
+ withAppName,
+ setExportMapBranding({appWebsite: 'https://atlas.example.com'})
+ );
+
+ t.deepEqual(
+ withWebsite.exportMap,
+ {
+ ...INITIAL_UI_STATE.exportMap,
+ appName: 'Atlas Lab',
+ appWebsite: 'https://atlas.example.com'
+ },
+ 'should merge a partial website update without replacing the application name'
+ );
+
+ t.end();
+});
+
test('#uiStateReducer -> SET_EXPORT_FILTERED', t => {
const newReducer = reducer(INITIAL_UI_STATE, setExportFiltered(false));
diff --git a/test/node/utils/export-utils-test.js b/test/node/utils/export-utils-test.js
index 72de10361..0b2f4d46d 100644
--- a/test/node/utils/export-utils-test.js
+++ b/test/node/utils/export-utils-test.js
@@ -16,17 +16,31 @@ import {
getExportFileNameBase,
exportMapToHTML
} from '@kepler.gl/utils';
+import {resolveMapboxTokenForExport} from '../../../src/utils/src/export-utils';
import {EXPORT_IMG_RATIOS, RESOLUTIONS} from '@kepler.gl/constants';
test('exportUtils -> ExportJson', t => {
const state = keplerGlReducer(undefined, registerEntry({id: 'test'})).test;
- const body = exportToJsonString(getMapJSON(state));
+ const map = getMapJSON(state, {
+ hasData: true,
+ appName: '</script> Atlas',
+ appWebsite: 'https://atlas.example.com/?next="map"'
+ });
+ const body = exportToJsonString(map);
getScaleFromImageSize;
t.equal(typeof body, 'string', 'Should validate the type of body to be a string');
t.doesNotThrow(() => {
JSON.parse(body);
}, 'Should not throw when trying to parse body');
+ t.equal(map.info.app, 'kepler.gl', 'should preserve the JSON format discriminator');
+ t.equal(map.info.appName, '</script> Atlas', 'should preserve the application name');
+ t.equal(
+ map.info.appWebsite,
+ 'https://atlas.example.com/?next="map"',
+ 'should preserve the application website'
+ );
+ t.deepEqual(JSON.parse(body).info, map.info, 'should safely serialize branding as JSON metadata');
t.end();
});
@@ -71,6 +85,175 @@ test('exportUtils -> ExportHtml escapes script terminators in map info', t => {
t.end();
});
+test('exportUtils -> ExportHtml preserves custom branding', t => {
+ const branding = {
+ appName: 'Atlas Lab',
+ appWebsite: 'https://atlas.example.com/maps'
+ };
+ const html = exportMapToHTML({
+ datasets: [],
+ config: {version: 'v1', config: {}},
+ mode: 'READ',
+ ...branding
+ });
+ const brandingMatch = html.match(/const branding = (.+);/);
+
+ t.ok(brandingMatch, 'exported html should define branding settings');
+ t.deepEqual(
+ JSON.parse(brandingMatch[1]),
+ branding,
+ 'exported html should serialize the custom branding'
+ );
+ t.ok(
+ html.includes('<title>Atlas Lab embedded map</title>'),
+ 'exported html should use the app name in the document title'
+ );
+ t.ok(
+ html.includes('href: branding.appWebsite'),
+ 'the read-only logo should link to the app website'
+ );
+ t.ok(
+ html.includes('react.createElement("span", null, branding.appName)'),
+ 'the read-only logo should render the app name'
+ );
+ t.ok(html.includes('BrandLogo(),'), 'a read-only export should render the branding badge');
+ t.ok(
+ html.includes('appName: branding.appName') && html.includes('appWebsite: branding.appWebsite'),
+ 'the embedded component should receive the branding props'
+ );
+
+ t.end();
+});
+
+test('exportUtils -> ExportHtml normalizes branding websites', t => {
+ const getBranding = appWebsite => {
+ const html = exportMapToHTML({
+ datasets: [],
+ config: {version: 'v1', config: {}},
+ mode: 'READ',
+ appWebsite
+ });
+ const brandingMatch = html.match(/const branding = (.+);/);
+ return JSON.parse(brandingMatch[1]);
+ };
+
+ t.equal(
+ getBranding(' example.com/maps ').appWebsite,
+ 'https://example.com/maps',
+ 'scheme-less websites should become absolute HTTPS URLs'
+ );
+ t.equal(
+ getBranding('javascript:alert(1)').appWebsite,
+ 'http://kepler.gl/',
+ 'unsupported URL schemes should use the Kepler website'
+ );
+ t.equal(
+ getBranding(' ').appWebsite,
+ 'http://kepler.gl/',
+ 'empty websites should use the Kepler website'
+ );
+ t.equal(
+ getBranding('not a website').appWebsite,
+ 'http://kepler.gl/',
+ 'invalid websites should use the Kepler website'
+ );
+
+ t.end();
+});
+
+test('exportUtils -> ExportHtml uses default branding', t => {
+ const html = exportMapToHTML({
+ datasets: [],
+ config: {version: 'v1', config: {}},
+ mode: 'READ'
+ });
+ const brandingMatch = html.match(/const branding = (.+);/);
+
+ t.ok(brandingMatch, 'exported html should define default branding settings');
+ t.deepEqual(
+ JSON.parse(brandingMatch[1]),
+ {appName: 'kepler.gl', appWebsite: 'http://kepler.gl/'},
+ 'exported html should retain the Kepler defaults'
+ );
+ t.ok(
+ html.includes('<title>kepler.gl embedded map</title>'),
+ 'the default document title should use the canonical app name'
+ );
+
+ t.end();
+});
+
+test('exportUtils -> ExportHtml safely serializes branding', t => {
+ const appName = '</title><script>window.brandPwned=1;</script> & Map\u2028\u2029';
+ const appWebsite =
+ 'https://example.com/?next=</script><script>window.websitePwned=1;</script>\u2028\u2029';
+ const html = exportMapToHTML({
+ datasets: [],
+ config: {version: 'v1', config: {}},
+ mode: 'READ',
+ appName,
+ appWebsite
+ });
+ const brandingMatch = html.match(/const branding = (.+);/);
+
+ t.notOk(
+ html.includes('<script>window.brandPwned'),
+ 'the app name should not be able to close the title element'
+ );
+ t.notOk(
+ html.includes('<script>window.websitePwned'),
+ 'the app website should not be able to close the inline script'
+ );
+ t.ok(
+ html.includes(
+ '<title>&lt;/title&gt;&lt;script&gt;window.brandPwned=1;&lt;/script&gt; &amp; Map\u2028\u2029 embedded map</title>'
+ ),
+ 'the app name should be escaped for the document title'
+ );
+ t.ok(html.includes('\\u003c/script>'), 'branding should escape `<` in inline scripts');
+ t.ok(html.includes('\\u2028\\u2029'), 'branding should escape JavaScript line terminators');
+ t.notOk(
+ brandingMatch[1].includes('<'),
+ 'serialized branding should not contain literal opening angle brackets'
+ );
+ t.deepEqual(
+ JSON.parse(brandingMatch[1]),
+ {
+ appName,
+ appWebsite:
+ 'https://example.com/?next=%3C/script%3E%3Cscript%3Ewindow.websitePwned=1;%3C/script%3E'
+ },
+ 'escaped branding should retain its normalized values at runtime'
+ );
+
+ t.end();
+});
+
+test('exportUtils -> resolveMapboxTokenForExport', t => {
+ t.equal(
+ resolveMapboxTokenForExport(' ', 'shared-token'),
+ 'shared-token',
+ 'whitespace-only user tokens should use the configured export token'
+ );
+ t.equal(
+ resolveMapboxTokenForExport(' user-token ', 'shared-token'),
+ 'user-token',
+ 'user tokens should be trimmed before export'
+ );
+ t.equal(
+ resolveMapboxTokenForExport('', undefined),
+ undefined,
+ 'missing user and export tokens should remain missing'
+ );
+ t.equal(
+ resolveMapboxTokenForExport('', ' '),
+ undefined,
+ 'whitespace-only configured export tokens should remain missing'
+ );
+
+ t.end();
+});
+
test('exportUtils -> getScaleFromImageSize', t => {
t.equal(
getScaleFromImageSize(800, 600, 1400, 990),