Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
feat: optional map name and description (#3797)
Igor Dykhtaa2fdfba4e0d6
diff --git a/examples/demo-app-sqlrooms/src/cloud-providers/carto/carto-provider.js b/examples/demo-app-sqlrooms/src/cloud-providers/carto/carto-provider.jsindex 523f91a44..167841825 100644--- a/examples/demo-app-sqlrooms/src/cloud-providers/carto/carto-provider.js+++ b/examples/demo-app-sqlrooms/src/cloud-providers/carto/carto-provider.js@@ -84,8 +84,8 @@ export default class CartoProvider extends Provider {const cs = await this._carto.getCustomStorage();- const {title, description} = info;- const name = title;+ const {title, description} = info || {};+ const name = (options.fileName && String(options.fileName).trim()) || title || 'Untitled Map';const thumbnailBase64 =mapData && thumbnail ? await this._blobToBase64(mapData.thumbnail) : null;diff --git a/examples/demo-app-sqlrooms/src/cloud-providers/dropbox/dropbox-provider.js b/examples/demo-app-sqlrooms/src/cloud-providers/dropbox/dropbox-provider.jsindex 9d7e3cdf7..ad5e50445 100644--- a/examples/demo-app-sqlrooms/src/cloud-providers/dropbox/dropbox-provider.js+++ b/examples/demo-app-sqlrooms/src/cloud-providers/dropbox/dropbox-provider.js@@ -191,9 +191,12 @@ export default class DropboxProvider extends Provider {const {isPublic} = options;const {map, thumbnail} = mapData;- // generate file name if is not provided- const name = map.info && map.info.title;- const fileName = `${name}.json`;+ // File name is the download name. The map title stays in info.title.+ const name =+ (options.fileName && String(options.fileName).trim()) ||+ (map.info && map.info.title) ||+ 'Untitled Map';+ const fileName = `${name.replace(/\.json$/i, '')}.json`;const fileContent = map;// FileWriteMode: Selects what to do if the file already exists.// Always overwrite if sharingdiff --git a/examples/demo-app-sqlrooms/src/cloud-providers/google-drive/google-drive-provider.js b/examples/demo-app-sqlrooms/src/cloud-providers/google-drive/google-drive-provider.jsindex f738dbd3b..8a40476ed 100644--- a/examples/demo-app-sqlrooms/src/cloud-providers/google-drive/google-drive-provider.js+++ b/examples/demo-app-sqlrooms/src/cloud-providers/google-drive/google-drive-provider.js@@ -252,7 +252,8 @@ export default class GoogleDriveProvider extends Provider {const {map, thumbnail} = mapData;const title = (map.info && map.info.title) || 'Untitled Map';const description = (map.info && map.info.description) || '';- const fileName = `${title}.json`;+ const fileBase = (options.fileName && String(options.fileName).trim()) || title;+ const fileName = `${fileBase.replace(/\.json$/i, '')}.json`;const folderId = await this._ensureAppFolder(token);const existing = await this._findFileByName(token, folderId, fileName);@@ -275,7 +276,7 @@ export default class GoogleDriveProvider extends Provider {}if (thumbnail) {- const pngName = `${title}.png`;+ const pngName = `${fileBase.replace(/\.json$/i, '')}.png`;const existingPng = await this._findFileByName(token, folderId, pngName);if (existingPng) {await this._updateBinaryFile(token, existingPng.id, thumbnail, MIME_PNG);diff --git a/examples/demo-app/src/cloud-providers/carto/carto-provider.js b/examples/demo-app/src/cloud-providers/carto/carto-provider.jsindex 4b4ba772f..da5d0b670 100644--- a/examples/demo-app/src/cloud-providers/carto/carto-provider.js+++ b/examples/demo-app/src/cloud-providers/carto/carto-provider.js@@ -83,8 +83,8 @@ export default class CartoProvider extends Provider {const cs = await this._carto.getCustomStorage();- const {title, description} = info;- const name = title;+ const {title, description} = info || {};+ const name = (options.fileName && String(options.fileName).trim()) || title || 'Untitled Map';const thumbnailBase64 =mapData && thumbnail ? await this._blobToBase64(mapData.thumbnail) : null;diff --git a/examples/demo-app/src/cloud-providers/dropbox/dropbox-provider.js b/examples/demo-app/src/cloud-providers/dropbox/dropbox-provider.jsindex eabbc5f01..d543bb736 100644--- a/examples/demo-app/src/cloud-providers/dropbox/dropbox-provider.js+++ b/examples/demo-app/src/cloud-providers/dropbox/dropbox-provider.js@@ -191,9 +191,12 @@ export default class DropboxProvider extends Provider {const {isPublic} = options;const {map, thumbnail} = mapData;- // generate file name if is not provided- const name = map.info && map.info.title;- const fileName = `${name}.json`;+ // File name is the download name. The map title stays in info.title.+ const name =+ (options.fileName && String(options.fileName).trim()) ||+ (map.info && map.info.title) ||+ 'Untitled Map';+ const fileName = `${name.replace(/\.json$/i, '')}.json`;const fileContent = map;// FileWriteMode: Selects what to do if the file already exists.// Always overwrite if sharingdiff --git a/examples/demo-app/src/cloud-providers/google-drive/google-drive-provider.js b/examples/demo-app/src/cloud-providers/google-drive/google-drive-provider.jsindex 2c1b4bd03..107661981 100644--- a/examples/demo-app/src/cloud-providers/google-drive/google-drive-provider.js+++ b/examples/demo-app/src/cloud-providers/google-drive/google-drive-provider.js@@ -251,7 +251,8 @@ export default class GoogleDriveProvider extends Provider {const {map, thumbnail} = mapData;const title = (map.info && map.info.title) || 'Untitled Map';const description = (map.info && map.info.description) || '';- const fileName = `${title}.json`;+ const fileBase = (options.fileName && String(options.fileName).trim()) || title;+ const fileName = `${fileBase.replace(/\.json$/i, '')}.json`;const folderId = await this._ensureAppFolder(token);const existing = await this._findFileByName(token, folderId, fileName);@@ -274,7 +275,7 @@ export default class GoogleDriveProvider extends Provider {}if (thumbnail) {- const pngName = `${title}.png`;+ const pngName = `${fileBase.replace(/\.json$/i, '')}.png`;const existingPng = await this._findFileByName(token, folderId, pngName);if (existingPng) {await this._updateBinaryFile(token, existingPng.id, thumbnail, MIME_PNG);diff --git a/src/components/src/common/styled-components.tsx b/src/components/src/common/styled-components.tsxindex 2e9d6e697..7e9cfebe9 100644--- a/src/components/src/common/styled-components.tsx+++ b/src/components/src/common/styled-components.tsx@@ -498,6 +498,7 @@ export const StyledModalSection = styled.div.attrs(({className}) => ({margin-bottom: 32px;.modal-section-title {+ display: block;font-weight: 500;}.modal-section-subtitle {diff --git a/src/components/src/index.ts b/src/components/src/index.tsindex 26352c56a..c26e92ee9 100644--- a/src/components/src/index.ts+++ b/src/components/src/index.ts@@ -152,6 +152,7 @@ export {default as BrushConfigFactory} from './side-panel/interaction-panel/brusexport {default as TooltipConfigFactory} from './side-panel/interaction-panel/tooltip-config';export {default as GeocoderConfigFactory} from './side-panel/interaction-panel/geocoder-config';export {default as LegendConfigFactory} from './side-panel/interaction-panel/legend-config';+export {default as MapInfoConfigFactory} from './side-panel/interaction-panel/map-info-config';export {default as ZoomOpacityConfigFactory} from './side-panel/interaction-panel/zoom-opacity-config';export {default as DndContextFactory} from './dnd-context';@@ -190,6 +191,8 @@ export {export type {MapLegendProps, MapLegendIcons} from './map/map-legend';export {default as MapLegendPanelFactory} from './map/map-legend-panel';+export {default as MapInfoPanelFactory} from './map/map-info-panel';+export type {MapInfoPanelProps} from './map/map-info-panel';export {default as MapPopoverFactory, getSelectedFeature} from './map/map-popover';export {default as MapPopoverContentFactory} from './map/map-popover-content';export {default as SplitMapButtonFactory} from './map/split-map-button';diff --git a/src/components/src/map-container.tsx b/src/components/src/map-container.tsxindex f80a0aaf9..67dd27533 100644--- a/src/components/src/map-container.tsx+++ b/src/components/src/map-container.tsx@@ -1693,6 +1693,7 @@ export default function MapContainerFactory(onToggleLayerForMap={visStateActions.toggleLayerForMap}charts={this.props.visState.charts}visStateActions={visStateActions}+ mapInfo={visState.mapInfo}/>)}{isSplitSelector(this.props) && <Droppable containerId={containerId} />}diff --git a/src/components/src/map/map-control.tsx b/src/components/src/map/map-control.tsxindex 83a6995e1..460352973 100644--- a/src/components/src/map/map-control.tsx+++ b/src/components/src/map/map-control.tsx@@ -19,6 +19,7 @@ import {LayerVisConfig,LayerOrder,MapControls,+ MapInfo,MapState,ChartConfig} from '@kepler.gl/types';@@ -28,6 +29,7 @@ import {getApplicationConfig} from '@kepler.gl/utils';import {MapViewMode} from '@kepler.gl/constants';import AnnotationControlFactory from './annotations/annotation-control';+import MapInfoPanelFactory from './map-info-panel';import ViewportJsonEditorControlFactory from './viewport-json-editor';interface StyledMapControlProps {@@ -107,6 +109,7 @@ export type MapControlProps = {onToggleLayerForMap?: (mapIndex: number, layerId: string) => void;charts?: ChartConfig[];visStateActions?: typeof VisStateActions;+ mapInfo?: Partial<MapInfo>;};MapControlFactory.deps = [@@ -118,7 +121,8 @@ MapControlFactory.deps = [ThemeToggleButtonFactory,AnnotationControlFactory,MapNavigationControlFactory,- ViewportJsonEditorControlFactory+ ViewportJsonEditorControlFactory,+ MapInfoPanelFactory];function MapControlFactory(@@ -130,9 +134,11 @@ function MapControlFactory(ThemeToggleButton: ReturnType<typeof ThemeToggleButtonFactory>,AnnotationControl: ReturnType<typeof AnnotationControlFactory>,MapNavigationControl: ReturnType<typeof MapNavigationControlFactory>,- ViewportJsonEditorControl: ReturnType<typeof ViewportJsonEditorControlFactory>+ ViewportJsonEditorControl: ReturnType<typeof ViewportJsonEditorControlFactory>,+ MapInfoPanel: ReturnType<typeof MapInfoPanelFactory>) {const DEFAULT_ACTIONS = [+ MapInfoPanel,SplitMapButton,Toggle3dButton,MapDrawPanel,diff --git a/src/components/src/map/map-info-panel.tsx b/src/components/src/map/map-info-panel.tsxnew file mode 100644index 000000000..f558f0503--- /dev/null+++ b/src/components/src/map/map-info-panel.tsx@@ -0,0 +1,231 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import classnames from 'classnames';+import React, {useCallback, useContext} from 'react';+import Markdown from 'markdown-to-jsx';+import styled from 'styled-components';+import {IntlContext} from 'react-intl';++import {MapControls, MapInfo} from '@kepler.gl/types';+import {getApplicationConfig} from '@kepler.gl/utils';++import LinkRenderer from '../common/link-renderer';+import {ArrowDown, Docs} from '../common/icons';+import {MapControlButton} from '../common/styled-components';+import MapControlTooltipFactory, {MapControlTooltipProps} from './map-control-tooltip';++const InfoFloatingPanel = styled.div`+ width: 280px;+ max-width: calc(100vw - 48px);+`;++const InfoPanel = styled.div`+ position: relative;+ background: ${props => props.theme.panelBackground};+ padding: 16px 28px 16px 20px;+ width: 100%;+ box-sizing: border-box;+ box-shadow: ${props => props.theme.panelBoxShadow};++ .map-info-title {+ color: ${props => props.theme.titleTextColor};+ font-size: 13px;+ font-weight: 500;+ display: flex;+ justify-content: space-between;+ gap: 8px;+ word-break: break-word;+ }++ .map-info-description {+ color: ${props => props.theme.textColor};+ font-size: 11px;+ margin-top: 12px;+ word-break: break-word;++ &.map-info-description--only {+ margin-top: 0;+ }++ a {+ font-weight: 500;+ color: ${props => props.theme.titleTextColor};+ }++ p {+ margin: 0;+ }++ p + p {+ margin-top: 8px;+ }+ }+`;++const MinimizeButton = styled.button`+ position: absolute;+ top: 8px;+ right: 8px;+ display: flex;+ align-items: center;+ justify-content: center;+ width: 16px;+ height: 16px;+ padding: 0;+ border: 0;+ background: transparent;+ color: ${props => props.theme.textColor};+ cursor: pointer;+ opacity: 0;++ ${InfoPanel}:hover & {+ opacity: 1;+ }++ &:focus-visible {+ opacity: 1;+ }++ &:hover {+ color: ${props => props.theme.textColorHl};+ }+`;++type MapInfoLinkProps = {+ href?: string;+ children?: React.ReactNode;+};++/** Only http(s) links from a saved description are clickable. */+const MapInfoLink: React.FC<MapInfoLinkProps> = ({href = '', children}) => {+ if (!/^https?:\/\//i.test(href)) {+ return <span>{children}</span>;+ }+ return <LinkRenderer href={href}>{children}</LinkRenderer>;+};++/**+ * Images are not rendered: a description loaded from an untrusted map file would+ * otherwise fetch an arbitrary url as soon as the card opens.+ */+const MapInfoImage: React.FC<{alt?: string}> = ({alt}) => (alt ? <span>{alt}</span> : null);++export type MapInfoPanelProps = {+ mapControls: MapControls;+ onToggleMapControl: (control: string) => void;+ mapInfo?: Partial<MapInfo>;+ className?: string;+};++MapInfoPanelFactory.deps = [MapControlTooltipFactory];++function MapInfoPanelFactory(MapControlTooltip: React.FC<MapControlTooltipProps>) {+ const MapInfoPanel: React.FC<MapInfoPanelProps> = ({+ mapControls,+ onToggleMapControl,+ mapInfo,+ className+ }) => {+ const intl = useContext(IntlContext);+ const title = mapInfo?.title ?? '';+ const description = mapInfo?.description ?? '';+ const hasTitle = Boolean(title.trim());+ const hasDescription = Boolean(description.trim());+ const hasContent = hasTitle || hasDescription;+ const active = Boolean(mapControls?.mapInfo?.active);+ // Match the other map controls: a missing entry stays hidden. The default+ // control list sets show: true.+ const show = Boolean(mapControls?.mapInfo?.show);+ const showCard = show && active && hasContent;++ const openPanel = useCallback(+ (event: React.MouseEvent) => {+ event.preventDefault();+ if (!active) {+ onToggleMapControl('mapInfo');+ }+ },+ [active, onToggleMapControl]+ );++ const closePanel = useCallback(+ (event: React.MouseEvent) => {+ event.preventDefault();+ if (active) {+ onToggleMapControl('mapInfo');+ }+ },+ [active, onToggleMapControl]+ );++ if (!getApplicationConfig().enableMapInfo || !show || !hasContent) {+ return null;+ }++ if (!showCard) {+ return (+ <MapControlTooltip id="show-map-info" message="tooltip.showMapInfo">+ <MapControlButton+ className={classnames('map-control-button', 'map-info', className)}+ onClick={openPanel}+ data-testid="map-info-button"+ >+ <Docs height="18px" />+ </MapControlButton>+ </MapControlTooltip>+ );+ }++ const closeLabel = intl+ ? intl.formatMessage({id: 'tooltip.hideMapInfo'})+ : 'tooltip.hideMapInfo';++ return (+ <InfoFloatingPanel+ className={classnames('map-info-panel', className)}+ data-testid="map-info-panel"+ >+ <InfoPanel>+ <MinimizeButton type="button" aria-label={closeLabel} onClick={closePanel}>+ <ArrowDown height="14px" />+ </MinimizeButton>+ {hasTitle ? (+ <div className="map-info-title">+ <div>{title}</div>+ </div>+ ) : null}+ {hasDescription ? (+ <div+ className={classnames('map-info-description', {+ 'map-info-description--only': !hasTitle+ })}+ >+ <Markdown+ options={{+ disableParsingRawHTML: true,+ overrides: {+ a: {+ component: MapInfoLink+ },+ img: {+ component: MapInfoImage+ }+ }+ }}+ >+ {description}+ </Markdown>+ </div>+ ) : null}+ </InfoPanel>+ </InfoFloatingPanel>+ );+ };++ MapInfoPanel.displayName = 'MapInfoPanel';++ return MapInfoPanel;+}++export default MapInfoPanelFactory;diff --git a/src/components/src/modal-container.tsx b/src/components/src/modal-container.tsxindex 8e793d260..932e2c259 100644--- a/src/components/src/modal-container.tsx+++ b/src/components/src/modal-container.tsx@@ -171,7 +171,42 @@ export default function ModalContainerFactory(}};+ _mapInfoDraft: {title: string; description: string} | null = null;++ _onMapInfoDraft = (info: {title: string; description: string}) => {+ this._mapInfoDraft = info;+ };++ _propsWithMapInfoDraft = () => {+ const draft = this._mapInfoDraft;+ if (!draft) {+ return this.props;+ }+ return {+ ...this.props,+ visState: {+ ...this.props.visState,+ mapInfo: {+ ...this.props.visState.mapInfo,+ title: draft.title,+ description: draft.description+ }+ }+ };+ };++ _commitMapInfoDraft = () => {+ if (!this._mapInfoDraft) {+ return;+ }+ this.props.visStateActions.setMapInfo({+ title: this._mapInfoDraft.title,+ description: this._mapInfoDraft.description+ });+ };+_closeModal = () => {+ this._mapInfoDraft = null;if (this.props.uiState.currentModal === ADD_DATA_ID) {this.props.visStateActions.clearStagedLoadedFiles();}@@ -274,18 +309,23 @@ export default function ModalContainerFactory(};_onExportMap = () => {- const {uiState} = this.props;+ const {uiState} = this._propsWithMapInfoDraft();const {format, includeLayerApiKeys, fileName} = uiState.exportMap;- (format === EXPORT_MAP_FORMATS.HTML ? exportHtml : exportJson)(this.props, {- ...(uiState.exportMap[format] || {}),- includeLayerApiKeys,- fileName- });+ (format === EXPORT_MAP_FORMATS.HTML ? exportHtml : exportJson)(+ this._propsWithMapInfoDraft(),+ {+ ...(uiState.exportMap[format] || {}),+ includeLayerApiKeys,+ fileName+ }+ );+ this._commitMapInfoDraft();this._closeModal();};_exportFileToCloud = ({provider, isPublic, overwrite, closeModal}) => {- const toSave = exportMap(this.props);+ const toSave = exportMap(this._propsWithMapInfoDraft());+ this._commitMapInfoDraft();this.props.providerActions.exportFileToCloud({mapData: toSave,@@ -293,7 +333,8 @@ export default function ModalContainerFactory(options: {isPublic,overwrite,- mapIdToOverwrite: this.props.providerState.savedMapId+ mapIdToOverwrite: this.props.providerState.savedMapId,+ fileName: this.props.uiState.exportMap.fileName},closeModal,onSuccess: this.props.onExportToCloudSuccess,@@ -500,11 +541,13 @@ export default function ModalContainerFactory(<ExportMapModalconfig={keplerGlConfig}options={uiState.exportMap}+ mapInfo={visState.mapInfo}onChangeExportMapFormat={uiStateActions.setExportMapFormat}onEditUserMapboxAccessToken={uiStateActions.setUserMapboxAccessToken}onChangeExportMapHTMLMode={uiStateActions.setExportHTMLMapMode}onChangeExportIncludeLayerApiKeys={uiStateActions.setExportIncludeLayerApiKeys}onChangeExportMapFileName={uiStateActions.setExportMapFileName}+ onMapInfoDraft={this._onMapInfoDraft}/>);modalProps = {@@ -575,6 +618,9 @@ export default function ModalContainerFactory({...providerState}exportImage={uiState.exportImage}mapInfo={visState.mapInfo}+ fileName={uiState.exportMap.fileName}+ onChangeFileName={uiStateActions.setExportMapFileName}+ onMapInfoDraft={this._onMapInfoDraft}onSetMapInfo={visStateActions.setMapInfo}cleanupExportImage={uiStateActions.cleanupExportImage}onUpdateImageSetting={uiStateActions.setExportImageSetting}@@ -592,7 +638,7 @@ export default function ModalContainerFactory(template = (<OverWriteMapModal{...providerState}- title={get(visState, ['mapInfo', 'title'])}+ title={get(visState, ['mapInfo', 'title']) ?? ''}onUpdateImageSetting={uiStateActions.setExportImageSetting}cleanupExportImage={uiStateActions.cleanupExportImage}onConfirm={this._onOverwriteMap}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.tsxindex 00c1ce670..babe96a82 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@@ -1,12 +1,18 @@// 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 {useIntl} from 'react-intl';import {FileType} from '../../common/icons';-import {StyledType, CheckMark} from '../../common/styled-components';-import {EXPORT_MAP_FORMATS, EXPORT_MAP_FORMAT_OPTIONS} from '@kepler.gl/constants';+import {StyledType, CheckMark, InputLight} from '../../common/styled-components';+import {+ EXPORT_MAP_FORMATS,+ EXPORT_MAP_FORMAT_OPTIONS,+ MAP_INFO_CHARACTER+} from '@kepler.gl/constants';+import {MapInfo} from '@kepler.gl/types';import {StyledExportMapModalContent,StyledExportMapSection,@@ -35,14 +41,22 @@ interface ExportMapModalOptions {interface ExportMapModalFactoryProps {options?: ExportMapModalOptions;config: any;+ mapInfo?: Partial<MapInfo>;onEditUserMapboxAccessToken: ActionHandler<typeof setUserMapboxAccessToken>;onChangeExportMapHTMLMode?: ActionHandler<typeof setExportHTMLMapMode>;onChangeExportIncludeLayerApiKeys?: ActionHandler<typeof setExportIncludeLayerApiKeys>;onChangeExportMapFormat?: (format: string) => any;onChangeExportMapFileName?: ActionHandler<typeof setExportMapFileName>;+ /** Latest name and description. Applied when the map is exported, not while typing. */+ onMapInfoDraft?: (info: {title: string; description: string}) => void;mapFormat?: string;}+const MapInfoInput = styled(InputLight)`+ width: 100%;+ max-width: 320px;+`;+const style = {width: '100%'};const CompactType = styled(StyledType)`@@ -66,66 +80,115 @@ function ExportMapModalFactory(onChangeExportIncludeLayerApiKeys = NO_OP,onChangeExportMapFileName = NO_OP,onEditUserMapboxAccessToken = NO_OP,+ onMapInfoDraft = NO_OP,+ mapInfo,options = {format: ''}- }: ExportMapModalFactoryProps) => (- <StyledExportMapModalContent className="export-map-modal">- <div style={style}>- <ExportFileNameSection- fileName={options.fileName}- inputId="export-map-file-name"- compact- onChange={onChangeExportMapFileName}- />- <StyledExportMapSection>- <div className="description">- <div className="title">- <FormattedMessage id={'modal.exportMap.formatTitle'} />+ }: ExportMapModalFactoryProps) => {+ const intl = useIntl();+ const [draftTitle, setDraftTitle] = useState(mapInfo?.title ?? '');+ const [draftDescription, setDraftDescription] = useState(mapInfo?.description ?? '');+ return (+ <StyledExportMapModalContent className="export-map-modal">+ <div style={style}>+ <ExportFileNameSection+ fileName={options.fileName}+ inputId="export-map-file-name"+ compact+ onChange={onChangeExportMapFileName}+ />+ <StyledExportMapSection>+ <div className="description">+ <div className="title">+ <FormattedMessage id="modal.exportMap.nameTitle" />+ </div></div>- <div className="subtitle">- <FormattedMessage id={'modal.exportMap.formatSubtitle'} />+ <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>- <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" />+ <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">+ <FormattedMessage id={'modal.exportMap.formatTitle'} />+ </div>+ <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>- ))}- </div>- </StyledExportMapSection>- <StyledExportMapFormatPanels>- <StyledExportMapFormatPanel- $active={options.format === EXPORT_MAP_FORMATS.HTML}- aria-hidden={options.format !== EXPORT_MAP_FORMATS.HTML}- inert={options.format !== EXPORT_MAP_FORMATS.HTML ? true : undefined}- >- <ExportHtmlMap- onChangeExportMapHTMLMode={onChangeExportMapHTMLMode}- onChangeExportIncludeLayerApiKeys={onChangeExportIncludeLayerApiKeys}- onEditUserMapboxAccessToken={onEditUserMapboxAccessToken}- includeLayerApiKeys={Boolean(options.includeLayerApiKeys)}- options={options[EXPORT_MAP_FORMATS.HTML]}- />- </StyledExportMapFormatPanel>- {options.format === EXPORT_MAP_FORMATS.JSON ? (- <StyledExportMapFormatPanel $active>- <ExportJsonMap- config={config}- includeLayerApiKeys={Boolean(options.includeLayerApiKeys)}+ {options.format === op.id && <CheckMark />}+ </CompactType>+ ))}+ </div>+ </StyledExportMapSection>+ <StyledExportMapFormatPanels>+ <StyledExportMapFormatPanel+ $active={options.format === EXPORT_MAP_FORMATS.HTML}+ aria-hidden={options.format !== EXPORT_MAP_FORMATS.HTML}+ inert={options.format !== EXPORT_MAP_FORMATS.HTML ? true : undefined}+ >+ <ExportHtmlMap+ onChangeExportMapHTMLMode={onChangeExportMapHTMLMode}onChangeExportIncludeLayerApiKeys={onChangeExportIncludeLayerApiKeys}+ onEditUserMapboxAccessToken={onEditUserMapboxAccessToken}+ includeLayerApiKeys={Boolean(options.includeLayerApiKeys)}+ options={options[EXPORT_MAP_FORMATS.HTML]}/></StyledExportMapFormatPanel>- ) : null}- </StyledExportMapFormatPanels>- </div>- </StyledExportMapModalContent>- );+ {options.format === EXPORT_MAP_FORMATS.JSON ? (+ <StyledExportMapFormatPanel $active>+ <ExportJsonMap+ config={config}+ includeLayerApiKeys={Boolean(options.includeLayerApiKeys)}+ onChangeExportIncludeLayerApiKeys={onChangeExportIncludeLayerApiKeys}+ />+ </StyledExportMapFormatPanel>+ ) : null}+ </StyledExportMapFormatPanels>+ </div>+ </StyledExportMapModalContent>+ );+ };ExportMapModalUnmemoized.displayName = 'ExportMapModal';diff --git a/src/components/src/modals/save-map-modal.spec.tsx b/src/components/src/modals/save-map-modal.spec.tsxindex 9f571331e..620e94ea0 100644--- a/src/components/src/modals/save-map-modal.spec.tsx+++ b/src/components/src/modals/save-map-modal.spec.tsx@@ -86,7 +86,7 @@ describe('SaveMapModal', () => {const {getByText} = renderWithTheme(<SaveMapModal {...UNDEFINED_MAP_TITLE_PROPS} />);const confirmButton = getByText('modal.button.save');expect(confirmButton).toBeInTheDocument();- expect(confirmButton).toBeDisabled();+ expect(confirmButton).toBeEnabled();});test('renders SaveMapModal component with provider correctly set and map title set', () => {@@ -149,18 +149,29 @@ describe('SaveMapModal', () => {setProvider: jest.fn(),cloudProviders: []}));- const {getByTestId, getByPlaceholderText} = renderWithTheme(+ const {getByTestId, getByLabelText, getByText} = renderWithTheme(<SaveMapModal {...UNDEFINED_MAP_TITLE_PROPS} />);const mapInfoPanel = getByTestId(dataTestIds.providerMapInfoPanel);expect(mapInfoPanel).toBeInTheDocument();- const titleInput = getByPlaceholderText('Type map title');+ const titleInput = getByLabelText('Name');expect(titleInput).toBeInTheDocument();+ // rendered without an IntlProvider, so the label shows the message id+ expect(getByLabelText('modal.exportFileName.title')).toHaveAttribute(+ 'id',+ 'save-map-file-name'+ );fireEvent.change(titleInput, {target: {value: 'first kepler map'}});- expect(DEFAULT_PROS.onSetMapInfo).toHaveBeenCalledWith({title: 'first kepler map'});+ expect(DEFAULT_PROS.onSetMapInfo).not.toHaveBeenCalled();++ fireEvent.click(getByText('modal.button.save'));+ expect(DEFAULT_PROS.onSetMapInfo).toHaveBeenCalledWith({+ title: 'first kepler map',+ description: ''+ });});test('call onUpdateImageSetting', () => {diff --git a/src/components/src/modals/save-map-modal.tsx b/src/components/src/modals/save-map-modal.tsxindex b745b5cba..59166b2e6 100644--- a/src/components/src/modals/save-map-modal.tsx+++ b/src/components/src/modals/save-map-modal.tsx@@ -1,10 +1,9 @@// SPDX-License-Identifier: MIT// Copyright contributors to the kepler.gl project-import React, {useCallback, useMemo} from 'react';+import React, {useCallback, useMemo, useState} from 'react';import styled from 'styled-components';import ImageModalContainer, {ImageModalContainerProps} from './image-modal-container';-import {FlexContainer} from '../common/flex-container';import StatusPanel, {UploadAnimation} from './status-panel';import {ProviderSelect} from './cloud-components/provider-select';import {CloudStorageDisclaimer} from './cloud-components/cloud-storage-disclaimer';@@ -13,10 +12,8 @@ import {MAP_THUMBNAIL_DIMENSION, MAP_INFO_CHARACTER, dataTestIds} from '@kepler.import {StyledModalContent,InputLight,- TextAreaLight,StyledExportSection,- StyledModalSection,- StyledModalInputFootnote+ StyledModalSection} from '../common/styled-components';import ImagePreview from '../common/image-preview';import {FormattedMessage} from '@kepler.gl/localization';@@ -65,7 +62,6 @@ const StyledCompactExportSection = styled(StyledExportSection)`const nop = () => {return;};-const TEXT_AREA_LIGHT_STYLE = {resize: 'none'};type CharacterLimits = {title?: number;@@ -78,6 +74,10 @@ type SaveMapModalProps = {isProviderLoading: boolean;providerError?: Error;characterLimits?: CharacterLimits;+ fileName?: string;+ onChangeFileName?: (fileName: string) => void;+ /** Latest name and description. Applied when the map is saved, not while typing. */+ onMapInfoDraft?: (info: {title: string; description: string}) => void;// callbacksonUpdateImageSetting: ImageModalContainerProps['onUpdateImageSetting'];@@ -87,7 +87,10 @@ type SaveMapModalProps = {onCancel: () => void;};-type MapInfoPanelProps = Pick<SaveMapModalProps, 'mapInfo' | 'characterLimits'> & {+type MapInfoPanelProps = Pick<+ SaveMapModalProps,+ 'mapInfo' | 'characterLimits' | 'fileName' | 'onChangeFileName'+> & {onChangeInput: (type: string,event: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>@@ -97,47 +100,54 @@ type MapInfoPanelProps = Pick<SaveMapModalProps, 'mapInfo' | 'characterLimits'>export const MapInfoPanel: React.FC<MapInfoPanelProps> = ({mapInfo,characterLimits,+ fileName = '',+ onChangeFileName,onChangeInput}) => {const {description = '', title = ''} = mapInfo;return (<div className="selection map-info-panel" data-testid={dataTestIds.providerMapInfoPanel}>+ <StyledModalSection className="save-map-modal-file-name">+ <label className="modal-section-title" htmlFor="save-map-file-name">+ <FormattedMessage id="modal.exportFileName.title" />+ </label>+ <div>+ <InputLight+ id="save-map-file-name"+ type="text"+ value={fileName}+ onChange={event => onChangeFileName?.(event.target.value)}+ placeholder="kepler.gl"+ />+ </div>+ </StyledModalSection><StyledModalSection className="save-map-modal-name">- <div className="modal-section-title">Name*</div>+ <label className="modal-section-title" htmlFor="map-title">+ Name+ </label><div><InputLightid="map-title"type="text"value={title}+ maxLength={characterLimits?.title || MAP_INFO_CHARACTER.title}onChange={e => onChangeInput('title', e)}- placeholder="Type map title"/></div></StyledModalSection>- <StyledModalSection>- <FlexContainer className="save-map-modal-description">- <div className="modal-section-title">Description</div>- <div className="modal-section-subtitle">(optional)</div>- </FlexContainer>+ <StyledModalSection className="save-map-modal-description">+ <label className="modal-section-title" htmlFor="map-description">+ Description+ </label><div>- <TextAreaLight- rows={3}+ <InputLightid="map-description"- style={TEXT_AREA_LIGHT_STYLE as React.CSSProperties}+ type="text"value={description}+ maxLength={characterLimits?.description || MAP_INFO_CHARACTER.description}onChange={e => onChangeInput('description', e)}- placeholder="Type map description"/></div>- <StyledModalInputFootnote- error={- Boolean(characterLimits?.description) &&- description.length > Number(characterLimits?.description)- }- >- {description.length}/{characterLimits?.description || MAP_INFO_CHARACTER.description}{' '}- characters- </StyledModalInputFootnote></StyledModalSection></div>);@@ -173,31 +183,43 @@ function SaveMapModalFactory() {cleanupExportImage,onSetMapInfo,onCancel,- onConfirm+ onConfirm,+ fileName,+ onChangeFileName,+ onMapInfoDraft}) => {const {provider, cloudProviders} = useCloudListProvider();+ const [draftTitle, setDraftTitle] = useState(mapInfo.title || '');+ const [draftDescription, setDraftDescription] = useState(mapInfo.description || '');const onChangeInput = (key: string,{target: {value}}: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => {- onSetMapInfo({[key]: value});+ if (key === 'title') {+ setDraftTitle(value);+ } else if (key === 'description') {+ setDraftDescription(value);+ }};const confirmButton = useMemo(() => ({large: true,- disabled: Boolean(!(provider && mapInfo.title)),+ disabled: !provider,children: 'modal.button.save'}),- [provider, mapInfo]+ [provider]);const confirm = useCallback(() => {if (provider) {+ const info = {title: draftTitle, description: draftDescription};+ onMapInfoDraft?.(info);+ onSetMapInfo(info);onConfirm(provider);}- }, [onConfirm, provider]);+ }, [draftDescription, draftTitle, onConfirm, onMapInfoDraft, onSetMapInfo, provider]);return (<ImageModalContainer@@ -242,8 +264,10 @@ function SaveMapModalFactory() {</div>) : (<MapInfoPanel- mapInfo={mapInfo}+ mapInfo={{...mapInfo, title: draftTitle, description: draftDescription}}characterLimits={characterLimits}+ fileName={fileName}+ onChangeFileName={onChangeFileName}onChangeInput={onChangeInput}/>)}diff --git a/src/components/src/side-panel.tsx b/src/components/src/side-panel.tsxindex 79d033407..40414a413 100644--- a/src/components/src/side-panel.tsx+++ b/src/components/src/side-panel.tsx@@ -256,6 +256,9 @@ export default function SidePanelFactory(uiStateActions={uiStateActions}visStateActions={visStateActions}mapLegendActive={Boolean(uiState.mapControls?.mapLegend?.active)}+ mapInfo={mapInfo}+ mapInfoShow={uiState.mapControls?.mapInfo?.show !== false}+ mapInfoActive={uiState.mapControls?.mapInfo?.active !== false}panelMetadata={currentPanel}panelListView={currentPanel?.id === 'layer'diff --git a/src/components/src/side-panel/interaction-manager.tsx b/src/components/src/side-panel/interaction-manager.tsxindex 422c7dc9f..9ed771164 100644--- a/src/components/src/side-panel/interaction-manager.tsx+++ b/src/components/src/side-panel/interaction-manager.tsx@@ -4,13 +4,14 @@import React from 'react';import {useIntl} from 'react-intl';-import {InteractionConfig, LayerOrder, MapState} from '@kepler.gl/types';+import {InteractionConfig, LayerOrder, MapInfo, MapState} from '@kepler.gl/types';import {UIStateActions, VisStateActions} from '@kepler.gl/actions';import {Datasets} from '@kepler.gl/table';import {Layer} from '@kepler.gl/layers';import InteractionPanelFactory from './interaction-panel/interaction-panel';import LegendConfigFactory from './interaction-panel/legend-config';+import MapInfoConfigFactory from './interaction-panel/map-info-config';import ZoomOpacityConfigFactory from './interaction-panel/zoom-opacity-config';import PanelTitleFactory from './panel-title';import {PanelHeaderActionIcon} from './panel-header-action';@@ -40,6 +41,9 @@ type InteractionManagerProps = {layers?: readonly Layer[];layerOrder?: LayerOrder;mapLegendActive?: boolean;+ mapInfo?: Partial<MapInfo>;+ mapInfoShow?: boolean;+ mapInfoActive?: boolean;mapState?: MapState;actionIcons?: {settings?: PanelHeaderActionIcon;@@ -53,14 +57,16 @@ InteractionManagerFactory.deps = [InteractionPanelFactory,PanelTitleFactory,LegendConfigFactory,- ZoomOpacityConfigFactory+ ZoomOpacityConfigFactory,+ MapInfoConfigFactory];function InteractionManagerFactory(InteractionPanel: ReturnType<typeof InteractionPanelFactory>,PanelTitle: ReturnType<typeof PanelTitleFactory>,LegendConfig: ReturnType<typeof LegendConfigFactory>,- ZoomOpacityConfig: ReturnType<typeof ZoomOpacityConfigFactory>+ ZoomOpacityConfig: ReturnType<typeof ZoomOpacityConfigFactory>,+ MapInfoConfig: ReturnType<typeof MapInfoConfigFactory>) {const InteractionManager: React.FC<InteractionManagerProps> = ({interactionConfig,@@ -71,12 +77,26 @@ function InteractionManagerFactory(layers,layerOrder,mapLegendActive,+ mapInfo,+ mapInfoShow,+ mapInfoActive,mapState,actionIcons,interactionConfigIcons}) => {const {interactionConfigChange: onConfigChange, setColumnDisplayFormat} = visStateActions;const intl = useIntl();+ const mapInfoPanel = (+ <MapInfoConfig+ key="mapInfo"+ mapInfo={mapInfo}+ mapInfoShow={mapInfoShow}+ mapInfoActive={mapInfoActive}+ visStateActions={visStateActions}+ uiStateActions={uiStateActions}+ actionIcons={actionIcons}+ />+ );return (<div className="interaction-manager">@@ -114,7 +134,7 @@ function InteractionManagerFactory(/>) : null;}- return (+ const panel = (<InteractionPanelkey={key}datasets={datasets}@@ -125,7 +145,17 @@ function InteractionManagerFactory(interactionConfigIcons={interactionConfigIcons}/>);+ if (key !== 'geocoder') {+ return panel;+ }+ return (+ <React.Fragment key="geocoder-and-map-info">+ {panel}+ {mapInfoPanel}+ </React.Fragment>+ );})}+ {interactionConfig.geocoder ? null : mapInfoPanel}</div>);};diff --git a/src/components/src/side-panel/interaction-panel/map-info-config.tsx b/src/components/src/side-panel/interaction-panel/map-info-config.tsxnew file mode 100644index 000000000..f42f0d3d9--- /dev/null+++ b/src/components/src/side-panel/interaction-panel/map-info-config.tsx@@ -0,0 +1,237 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import React, {ComponentType, useCallback, useState} from 'react';+import styled from 'styled-components';+import classnames from 'classnames';++import {MAP_INFO_CHARACTER} from '@kepler.gl/constants';+import {UIStateActions, VisStateActions} from '@kepler.gl/actions';+import {FormattedMessage} from '@kepler.gl/localization';+import {MapInfo} from '@kepler.gl/types';+import {getApplicationConfig} from '@kepler.gl/utils';++import {Info, Settings} from '../../common/icons';+import InfoHelperFactory from '../../common/info-helper';+import Switch from '../../common/switch';+import PanelHeaderActionFactory, {PanelHeaderActionIcon} from '../panel-header-action';+import {+ Input,+ PanelContent,+ PanelHeaderContent,+ PanelHeaderTitle,+ PanelLabel,+ PanelLabelWrapper,+ StyledPanelHeader,+ TextArea+} from '../../common/styled-components';++const StyledMapInfoPanel = styled.div`+ padding-bottom: 6px;+`;++const HeaderActions = styled.div`+ display: flex;+ align-items: center;+ gap: 24px;+ /* Undo StyledPanelHeader's 10px right padding, then match vertical inset around the switch. */+ margin-right: -10px;+ padding-right: ${props => (props.theme.panelHeaderHeight - props.theme.switchHeight) / 2}px;++ /* Unlabeled switch reserves empty label padding on the right; pull the track flush. */+ .kg-checkbox {+ margin-left: 0;+ margin-right: -${props => props.theme.switchLabelMargin}px;+ }+`;++const MapInfoHint = styled.div`+ color: ${props => props.theme.subtextColor};+ font-size: 11px;+ line-height: 1.4;+ margin-bottom: 10px;+`;++const Field = styled.div`+ margin-bottom: 12px;+`;++const DescriptionLabel = styled(PanelLabelWrapper)`+ align-items: center;+ margin-bottom: 4px;++ .side-panel-panel__label {+ margin-bottom: 0;+ }++ .info-helper {+ margin-left: 4px;+ }+`;++const MapInfoInput = styled(Input)`+ && {+ height: 28px;+ }+`;++const MapInfoTextArea = styled(TextArea)`+ && {+ height: 41px;+ min-height: 41px;+ resize: none;+ display: block;+ white-space: pre-wrap;+ overflow: auto;+ text-overflow: unset;+ line-height: 1.4;+ cursor: text;+ }+`;++const defaultActionIcons = {+ settings: Settings+};++export type MapInfoConfigProps = {+ mapInfo?: Partial<MapInfo>;+ /** When false, the on-map name and description stay hidden. Defaults to shown. */+ mapInfoShow?: boolean;+ /** Whether the on-map card is expanded. Used so turning the switch on opens the card. */+ mapInfoActive?: boolean;+ visStateActions: typeof VisStateActions;+ uiStateActions?: typeof UIStateActions;+ actionIcons?: {+ settings?: PanelHeaderActionIcon;+ };+};++MapInfoConfigFactory.deps = [PanelHeaderActionFactory, InfoHelperFactory];++function MapInfoConfigFactory(+ PanelHeaderAction: ReturnType<typeof PanelHeaderActionFactory>,+ InfoHelper: ReturnType<typeof InfoHelperFactory>+): ComponentType<MapInfoConfigProps> {+ const MapInfoConfig: React.FC<MapInfoConfigProps> = ({+ mapInfo,+ mapInfoShow = true,+ mapInfoActive = true,+ visStateActions,+ uiStateActions,+ actionIcons: customActionIcons+ }) => {+ const actionIcons = {...defaultActionIcons, ...customActionIcons};+ const [isConfigActive, setIsConfigActive] = useState(false);+ const title = mapInfo?.title ?? '';+ const description = mapInfo?.description ?? '';++ const togglePanelActive = useCallback(() => {+ setIsConfigActive(prev => !prev);+ }, []);++ const onToggleShow = useCallback(() => {+ const next = !mapInfoShow;+ uiStateActions?.setMapControlVisibility('mapInfo', next);+ if (next && !mapInfoActive) {+ uiStateActions?.toggleMapControl('mapInfo', 0);+ }+ }, [mapInfoActive, mapInfoShow, uiStateActions]);++ const onTitleChange = useCallback(+ (event: React.ChangeEvent<HTMLInputElement>) => {+ visStateActions.setMapInfo({title: event.target.value});+ },+ [visStateActions]+ );++ const onDescriptionChange = useCallback(+ (event: React.ChangeEvent<HTMLTextAreaElement>) => {+ visStateActions.setMapInfo({description: event.target.value});+ },+ [visStateActions]+ );++ if (!getApplicationConfig().enableMapInfo) {+ return null;+ }++ return (+ <StyledMapInfoPanel className="interaction-panel interaction-map-info">+ <StyledPanelHeader+ className={classnames('interaction-map-info__header', {'is-open': isConfigActive})}+ onClick={togglePanelActive}+ >+ <PanelHeaderContent className="interaction-map-info__header__content">+ <div className="interaction-map-info__header__icon icon">+ <Info height="16px" />+ </div>+ <div className="interaction-map-info__header__title">+ <PanelHeaderTitle>+ <FormattedMessage id="interactions.mapInfo" />+ </PanelHeaderTitle>+ </div>+ </PanelHeaderContent>+ <HeaderActions+ className="interaction-map-info__header__actions"+ onClick={event => event.stopPropagation()}+ >+ <PanelHeaderAction+ className={classnames('interaction-map-info__enable-config', {+ 'is-open': isConfigActive+ })}+ id="map-info-config"+ tooltip="tooltip.interactionSettings"+ active={isConfigActive}+ flush+ onClick={togglePanelActive}+ IconComponent={actionIcons.settings}+ />+ <Switch checked={mapInfoShow} id="map-info-toggle" onChange={onToggleShow} secondary />+ </HeaderActions>+ </StyledPanelHeader>+ {isConfigActive ? (+ <PanelContent className="interaction-map-info__content">+ <MapInfoHint>+ <FormattedMessage id="interactions.mapInfoHint" />+ </MapInfoHint>+ <Field>+ <PanelLabel htmlFor="interaction-map-name">+ <FormattedMessage id="interactions.mapInfoName" />+ </PanelLabel>+ <MapInfoInput+ id="interaction-map-name"+ type="text"+ value={title}+ maxLength={MAP_INFO_CHARACTER.title}+ onChange={onTitleChange}+ />+ </Field>+ <Field>+ <DescriptionLabel>+ <PanelLabel htmlFor="interaction-map-description">+ <FormattedMessage id="interactions.mapInfoDescription" />+ </PanelLabel>+ <InfoHelper+ id="map-info-description-help"+ description="interactions.mapInfoDescriptionHelp"+ width={220}+ />+ </DescriptionLabel>+ <MapInfoTextArea+ id="interaction-map-description"+ rows={2}+ value={description}+ maxLength={MAP_INFO_CHARACTER.description}+ onChange={onDescriptionChange}+ />+ </Field>+ </PanelContent>+ ) : null}+ </StyledMapInfoPanel>+ );+ };++ return MapInfoConfig;+}++export default MapInfoConfigFactory;diff --git a/src/constants/src/default-settings.ts b/src/constants/src/default-settings.tsindex 19fcbcfd3..155bb221c 100644--- a/src/constants/src/default-settings.ts+++ b/src/constants/src/default-settings.ts@@ -1336,7 +1336,7 @@ export const MAP_THUMBNAIL_DIMENSION = {export const MAP_INFO_CHARACTER = {title: 100,- description: 100+ description: 1024};// Load data@@ -1368,7 +1368,8 @@ export const MAP_CONTROLS = keyMirror({effect: null,annotation: null,chart: null,- viewportJson: null+ viewportJson: null,+ mapInfo: null});export enum MapViewMode {diff --git a/src/localization/src/translations/en.ts b/src/localization/src/translations/en.tsindex c9d19e0c3..523f2a947 100644--- a/src/localization/src/translations/en.ts+++ b/src/localization/src/translations/en.ts@@ -543,6 +543,8 @@ export default {dualView: 'Dual',swipeView: 'Swipe',showLegend: 'Show legend',+ showMapInfo: 'Show map info',+ hideMapInfo: 'Minimize map info',disable3DMap: 'Disable 3D Map',globeMap: 'Globe Map',disableGlobeMap: 'Disable Globe Map',@@ -781,6 +783,8 @@ export default {exportMap: {formatTitle: 'Map format',formatSubtitle: 'Choose the format to export your map to',+ nameTitle: 'Name',+ descriptionTitle: 'Description',includeApiKeys: 'Include layer API keys',includeApiKeysSubtitle:'When unchecked, access tokens stored on layers are removed from the exported file.',@@ -962,6 +966,11 @@ ${'```'}copyCoordinate: 'Copy coordinates',coordinateCopied: 'Copied',geocoder: 'Geocoder',+ mapInfo: 'Map info',+ mapInfoHint: 'Name and description are shown in a card on the right side of the map.',+ mapInfoName: 'Name',+ mapInfoDescription: 'Description',+ mapInfoDescriptionHelp: 'Add a link with [label](https://example.com).',legend: 'Legend',legendHint: 'Choose which layers appear in the map legend. Layers stay on the map.',legendEmpty: 'Add a layer to choose what appears in the legend.',diff --git a/src/processors/src/data-processor.ts b/src/processors/src/data-processor.tsindex 3b1cc108f..eb4040d0d 100644--- a/src/processors/src/data-processor.ts+++ b/src/processors/src/data-processor.ts@@ -22,7 +22,8 @@ import {arrowDataTypeToFieldType,compactArrowTable,hasOwnProperty,- isPlainObject+ isPlainObject,+ optionalMapInfo} from '@kepler.gl/utils';import {analyzerTypeToFieldType,@@ -406,8 +407,24 @@ export function processGeojson(rawData: unknown): ProcessorResult {** dispatch(addDataToMap(processKeplerglJSON(keplerGlJson)));*/+function savedMapDisplayInfo(info: unknown): {title?: string; description?: string} {+ const saved =+ info && typeof info === 'object'+ ? optionalMapInfo(info as {title?: unknown; description?: unknown})+ : undefined;+ // Both keys are always present: setMapInfo merges, so omitting one would keep+ // the previously loaded map's value instead of clearing it.+ return {title: saved?.title, description: saved?.description};+}+export function processKeplerglJSON(rawData: SavedMap, schema = KeplerGlSchema): LoadedMap | null {- return rawData ? schema.load(rawData.datasets, rawData.config) : null;+ if (!rawData) {+ return null;+ }+ return {+ ...schema.load(rawData.datasets, rawData.config),+ info: savedMapDisplayInfo(rawData.info)+ };}/**diff --git a/src/reducers/src/ui-state-updaters.ts b/src/reducers/src/ui-state-updaters.tsindex fbfb5bcd6..f018d2ec0 100644--- a/src/reducers/src/ui-state-updaters.ts+++ b/src/reducers/src/ui-state-updaters.ts@@ -113,20 +113,26 @@ const DEFAULT_MAP_LEGEND_CONTROL = {* @property mapLocale Default: `{show: true, active: false}`* @property mapTheme Default: `{show: true, active: false}`* @property viewportJson Default: `{show: true, active: false}`+ * @property mapInfo Default: `{show: true, active: true}`. `show` hides the on-map name and description.* @public*/-export const DEFAULT_MAP_CONTROLS: MapControls = (- Object.keys(MAP_CONTROLS) as Array<keyof typeof MAP_CONTROLS>-).reduce(- (final, current) => ({- ...final,- [current]:- current === MAP_CONTROLS.mapLegend- ? DEFAULT_MAP_LEGEND_CONTROL- : DEFAULT_MAP_CONTROLS_FEATURES- }),- {} as MapControls-);+export const DEFAULT_MAP_CONTROLS: MapControls = {+ ...(Object.keys(MAP_CONTROLS) as Array<keyof typeof MAP_CONTROLS>).reduce(+ (final, current) => ({+ ...final,+ [current]:+ current === MAP_CONTROLS.mapLegend+ ? DEFAULT_MAP_LEGEND_CONTROL+ : DEFAULT_MAP_CONTROLS_FEATURES+ }),+ {} as MapControls+ ),+ // Open by default so a saved title shows on load. An empty map still hides the card.+ mapInfo: {+ ...DEFAULT_MAP_CONTROLS_FEATURES,+ active: true+ }+};/*** Default image export config@@ -1129,6 +1135,28 @@ export const receiveMapConfigUpdater = (};}+ // Honor an explicit collapsed or hidden state. A missing key keeps the default (shown, open).+ const savedMapInfo = uiState.mapControls?.mapInfo;+ const savedMapInfoActive = savedMapInfo?.active;+ const savedMapInfoShow = savedMapInfo?.show;+ if (typeof savedMapInfoActive === 'boolean' || typeof savedMapInfoShow === 'boolean') {+ const currentMapInfo = newState.mapControls.mapInfo;+ newState = {+ ...newState,+ mapControls: {+ ...newState.mapControls,+ mapInfo: {+ show: true,+ active: true,+ ...currentMapInfo,+ ...(typeof savedMapInfoShow === 'boolean' ? {show: savedMapInfoShow} : {}),+ ...(typeof savedMapInfoActive === 'boolean' ? {active: savedMapInfoActive} : {}),+ activeMapIndex: 0+ }+ }+ };+ }+if (uiState.mapControls?.mapLegend?.settings) {newState = setMapControlSettingsUpdater(newState, {payload: {panelId: 'mapLegend', settings: uiState.mapControls.mapLegend.settings}diff --git a/src/reducers/src/vis-state-updaters.ts b/src/reducers/src/vis-state-updaters.tsindex 663752f78..53056d553 100644--- a/src/reducers/src/vis-state-updaters.ts+++ b/src/reducers/src/vis-state-updaters.ts@@ -241,7 +241,8 @@ import {mergeFilterDomain,initCustomPaletteByCustomScale,collectColumnValues,- getColumnStatistics+ getColumnStatistics,+ optionalMapText} from '@kepler.gl/utils';import {createEffect} from '@kepler.gl/effects';import {PayloadAction} from '@reduxjs/toolkit';@@ -379,8 +380,8 @@ export const DEFAULT_EDITOR: Editor = {export const INITIAL_VIS_STATE: VisState = {// map infomapInfo: {- title: '',- description: ''+ title: undefined,+ description: undefined},// layerslayers: [],@@ -5000,13 +5001,16 @@ export const applyCPUFilterUpdater = (export const setMapInfoUpdater = (state: VisState,action: VisStateActions.SetMapInfoUpdaterAction-): VisState => ({- ...state,- mapInfo: {- ...state.mapInfo,- ...action.info- }-});+): VisState => {+ const next = {...state.mapInfo, ...action.info};+ return {+ ...state,+ mapInfo: {+ title: optionalMapText(next.title),+ description: optionalMapText(next.description)+ }+ };+};/*** Helper function to update All layer domain and layer data of state*/diff --git a/src/schemas/src/schema-manager.ts b/src/schemas/src/schema-manager.tsindex ebbfff4f5..a229be430 100644--- a/src/schemas/src/schema-manager.ts+++ b/src/schemas/src/schema-manager.ts@@ -12,7 +12,7 @@ import {visStateSchema} from './vis-state-schema';import uiStateSchema from './ui-state-schema';import {CURRENT_VERSION, VERSIONS} from './versions';-import {isPlainObject} from '@kepler.gl/utils';+import {isPlainObject, optionalMapInfo} from '@kepler.gl/utils';import {MapInfo, SavedVisState, SavedMapStyle, ParsedConfig, BaseMapStyle} from '@kepler.gl/types';@@ -85,12 +85,16 @@ export type SavedMap = {info: {app: string;created_at: string;- title: string;- description: string;+ title?: string;+ description?: string;};};-export type LoadedMap = {datasets?: ParsedDataset[] | null; config?: ParsedConfig | null};+export type LoadedMap = {+ datasets?: ParsedDataset[] | null;+ config?: ParsedConfig | null;+ info?: {title?: string; description?: string};+};export const reducerSchema: {[key: string]:@@ -183,7 +187,7 @@ export class KeplerGLSchema {}getMapInfo(state: any): MapInfo {- return state.visState.mapInfo;+ return optionalMapInfo(state.visState?.mapInfo) || {};}/*** Load saved map, argument can be (datasets, config) or ({datasets, config})diff --git a/src/schemas/src/ui-state-schema.ts b/src/schemas/src/ui-state-schema.tsindex e63db1978..b6ba49513 100644--- a/src/schemas/src/ui-state-schema.ts+++ b/src/schemas/src/ui-state-schema.ts@@ -29,6 +29,14 @@ export const propertiesV1 = {active: null},key: 'chart'+ }),+ mapInfo: new Schema({+ version: VERSIONS.v1,+ properties: {+ active: null,+ show: null+ },+ key: 'mapInfo'})},key: 'mapControls'diff --git a/src/types/actions.d.ts b/src/types/actions.d.tsindex 35b5b368f..f9137cbf3 100644--- a/src/types/actions.d.ts+++ b/src/types/actions.d.ts@@ -14,6 +14,8 @@ export type ExportFileOptions = {isPublic?: boolean;overwrite?: boolean;mapIdToOverwrite?: string | null;+ /** Download name, without extension. Separate from the map title. */+ fileName?: string;};export type OnErrorCallBack = (error: Error) => any;export type OnSuccessCallBack = (p: {diff --git a/src/types/reducers.d.ts b/src/types/reducers.d.tsindex 09f682639..096b66e59 100644--- a/src/types/reducers.d.ts+++ b/src/types/reducers.d.ts@@ -478,8 +478,8 @@ export type InteractionConfig = {zoomOpacity: ZoomOpacityInteraction;};export type MapInfo = {- title: string;- description: string;+ title?: string;+ description?: string;};/** Options captured when a file load starts and forwarded to `addDataToMap`. */export type FileLoadingOptions = {@@ -623,6 +623,7 @@ export type MapControls = {annotation?: MapControlItem;chart?: MapControlItem;viewportJson?: MapControlItem;+ mapInfo?: MapControlItem;sqlPanel?: MapControlItem;aiAssistant?: MapControlItem;[key: string]: MapControlItem | MapControlMapLegend | undefined;diff --git a/src/types/schemas.d.ts b/src/types/schemas.d.tsindex a636d1b0f..b6863c540 100644--- a/src/types/schemas.d.ts+++ b/src/types/schemas.d.ts@@ -174,6 +174,10 @@ export type ParsedUiState = {chart?: {active?: boolean;};+ mapInfo?: {+ active?: boolean;+ show?: boolean;+ };};locale?: string;theme?: string;@@ -289,9 +293,16 @@ export type SavedMap = {info: {app: string;created_at: string;- title: string;- description: string;+ title?: string;+ description?: string;};};-export type LoadedMap = {datasets?: ParsedDataset[] | null; config?: ParsedConfig | null};+export type LoadedMap = {+ datasets?: ParsedDataset[] | null;+ config?: ParsedConfig | null;+ info?: {+ title?: string;+ description?: string;+ };+};diff --git a/src/utils/src/application-config.ts b/src/utils/src/application-config.tsindex 3520e1062..40a2d3d38 100644--- a/src/utils/src/application-config.ts+++ b/src/utils/src/application-config.ts@@ -250,6 +250,12 @@ export type KeplerApplicationConfig = {*/enableChartsPanel?: boolean;+ /**+ * Whether to show the Map info section in Interactions and the on-map+ * name and description card. Enabled by default.+ */+ enableMapInfo?: boolean;+/*** Master switch for power-user JSON editors. When false, every section editor is hidden.* Defaults to true; each section also has its own flag.@@ -483,6 +489,8 @@ const DEFAULT_APPLICATION_CONFIG: Required<KeplerApplicationConfig> = {enableChartsPanel: true,+ enableMapInfo: true,+enableJsonEditors: true,enableLayerJsonEditor: true,enableFilterJsonEditor: true,diff --git a/src/utils/src/export-map-html.ts b/src/utils/src/export-map-html.tsindex 947e2c9fb..3f1768109 100644--- a/src/utils/src/export-map-html.ts+++ b/src/utils/src/export-map-html.ts@@ -2,6 +2,7 @@// Copyright contributors to the kepler.gl projectimport {EXPORT_HTML_MAP_MODES, KEPLER_GL_VERSION} from '@kepler.gl/constants';+import {optionalMapInfo} from './map-info-utils';// React (and react-dom) no longer publish UMD builds starting with v19, so the// exported map loads React and the other UMD peer dependencies as ES modules@@ -18,12 +19,25 @@ const STYLED_COMPONENTS_VERSION = '6.1.19';// document (native ES modules/import maps are blocked under the file:// origin).const ES_MODULE_SHIMS_VERSION = '2.8.1';+/**+ * Serialize a value for interpolation into an inline `<script>`. A literal `</script>`+ * anywhere in the data would close the script element early, and U+2028/U+2029 are+ * line terminators in JavaScript but legal inside a JSON string.+ */+function toScriptJSON(value: unknown): string {+ return JSON.stringify(value ?? null)+ .replace(/</g, '\\u003c')+ .replace(/\u2028/g, '\\u2028')+ .replace(/\u2029/g, '\\u2029');+}+/*** 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* @param {string} options.mapboxApiAccessToken Mapbox token used to fetch mapbox tiles* @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} version which version of Kepler.gl to load.*/export const exportMapToHTML = (options, version = KEPLER_GL_VERSION) => {@@ -470,6 +484,7 @@ export const exportMapToHTML = (options, version = KEPLER_GL_VERSION) => {(function customize(keplerGl, store) {const datasets = ${JSON.stringify(options.datasets)};const config = ${JSON.stringify(options.config)};+ const info = ${toScriptJSON(optionalMapInfo(options.info) ?? null)};const loadedData = keplerGl.KeplerGlSchema.load(datasets,@@ -486,6 +501,7 @@ export const exportMapToHTML = (options, version = KEPLER_GL_VERSION) => {keplerGl.addDataToMap({datasets: loadedData.datasets,config: loadedData.config,+ info,options: {centerMap: false,},diff --git a/src/utils/src/export-utils.ts b/src/utils/src/export-utils.tsindex 787269ed7..71038c942 100644--- a/src/utils/src/export-utils.ts+++ b/src/utils/src/export-utils.ts@@ -2,8 +2,6 @@// Copyright contributors to the kepler.gl projectimport {Blob, URL, atob, Uint8Array, ArrayBuffer, document} from 'global/window';-import get from 'es-toolkit/compat/get';-import {EXPORT_IMG_RESOLUTION_OPTIONS,EXPORT_IMG_RATIO_OPTIONS,@@ -13,9 +11,7 @@ import {type ExportResolutionOption} from '@kepler.gl/constants';import {ExportImage} from '@kepler.gl/types';-import {generateHashId} from '@kepler.gl/common-utils';import domtoimage from './dom-to-image';-import {set} from './utils';import {exportMapToHTML} from './export-map-html';import {getApplicationConfig} from './application-config';@@ -242,11 +238,6 @@ export function getMapJSON(}let mapToSave = schema.save(state);- // add file name if title is not provided- const title = get(mapToSave, ['info', 'title']);- if (!title || !title.length) {- mapToSave = set(['info', 'title'], `keplergl_${generateHashId(6)}`, mapToSave);- }if (includeLayerApiKeys === false) {mapToSave = omitLayerApiKeys(mapToSave);}diff --git a/src/utils/src/index.ts b/src/utils/src/index.tsindex 247cac525..be976faf6 100644--- a/src/utils/src/index.ts+++ b/src/utils/src/index.ts@@ -114,7 +114,7 @@ export {export {getFormatValue, getDefaultTimeFormat} from './format';export {getLayerBlendingParameters, patchDeckRendererForPostProcessing} from './gl-utils';export {flattenMessages, mergeMessages} from './locale-utils';-export {isValidMapInfo} from './map-info-utils';+export {isValidMapInfo, optionalMapInfo, optionalMapText} from './map-info-utils';export {editBottomMapStyle,editTopMapStyle,diff --git a/src/utils/src/map-info-utils.ts b/src/utils/src/map-info-utils.tsindex fdf427606..fea2cb080 100644--- a/src/utils/src/map-info-utils.ts+++ b/src/utils/src/map-info-utils.ts@@ -3,10 +3,33 @@import {MAP_INFO_CHARACTER} from '@kepler.gl/constants';+/** Keep a name or description only when it has visible text. Blank stays unset. */+export function optionalMapText(value: unknown): string | undefined {+ if (typeof value !== 'string' || !value.trim()) {+ return undefined;+ }+ return value;+}++/** Title and description to persist. Omitted when both are unset. */+export function optionalMapInfo(+ info?: {title?: unknown; description?: unknown} | null+): {title?: string; description?: string} | undefined {+ const title = optionalMapText(info?.title);+ const description = optionalMapText(info?.description);+ if (title === undefined && description === undefined) {+ return undefined;+ }+ return {+ ...(title !== undefined ? {title} : {}),+ ...(description !== undefined ? {description} : {})+ };+}+export function isValidMapInfo(mapInfo) {+ const title = mapInfo?.title || '';+ const description = mapInfo?.description || '';return (- mapInfo.title.length &&- mapInfo.title.length <= MAP_INFO_CHARACTER.title &&- (!mapInfo.description.length || mapInfo.description.length <= MAP_INFO_CHARACTER.description)+ title.length <= MAP_INFO_CHARACTER.title && description.length <= MAP_INFO_CHARACTER.description);}diff --git a/test/browser/components/map/map-control-test.js b/test/browser/components/map/map-control-test.jsindex b53c20b65..0b8d9505e 100644--- a/test/browser/components/map/map-control-test.js+++ b/test/browser/components/map/map-control-test.js@@ -80,7 +80,7 @@ test('MapControlFactory - display all options', t => {</MapViewStateContextProvider></IntlWrapper>);- t.equal($.find('.map-control-action').length, 9, 'Should show 9 action panels');+ t.equal($.find('.map-control-action').length, 10, 'Should show 10 action panels');t.equal($.find('.toggle-chart-panel').length,0,@@ -432,3 +432,97 @@ test('MapControlFactory - show panels', t => {t.end();});++test('MapControlFactory - map info panel', t => {+ const onToggleMapControl = sinon.spy();+ const base = {+ datasets: {},+ layers: [],+ locale: 'en',+ layersToRender: {},+ dragRotate: true,+ mapIndex: 0,+ onToggleSplitMap: () => {},+ onTogglePerspective: () => {},+ onToggleMapControl,+ onSetEditorMode: () => {},+ onToggleEditorVisibility: () => {},+ onSetLocale: () => {}+ };++ const mountControl = extra =>+ mountWithTheme(+ <IntlWrapper>+ <MapViewStateContextProvider mapState={{latitude: 0, longitude: 0, zoom: 1}}>+ <MapControl {...base} {...extra} />+ </MapViewStateContextProvider>+ </IntlWrapper>+ );++ const empty = mountControl({+ mapControls: {mapInfo: {show: true, active: true}},+ mapInfo: {title: '', description: ''}+ });+ t.equal(+ empty.find('.map-info-panel').length,+ 0,+ 'hides the panel when title and description are empty'+ );+ t.equal(empty.find('.map-info').length, 0, 'hides the map info button when empty');+ t.equal(empty.find('textarea').length, 0, 'does not edit map info on the map');++ const shown = mountControl({+ mapControls: {mapInfo: {show: true, active: true}},+ mapInfo: {title: 'Harbor', description: 'See [routes](https://example.com)'}+ });+ t.ok(+ shown.find('[data-testid="map-info-panel"]').hostNodes().length > 0,+ 'shows the panel when a title is set'+ );+ t.ok(shown.text().includes('Harbor'), 'renders the map title');+ t.ok(shown.text().includes('routes'), 'renders the description');+ t.equal(+ shown.find('a[href="https://example.com"]').hostNodes().length,+ 1,+ 'renders description links'+ );+ t.equal(shown.find('textarea').length, 0, 'imported map info is display only');++ const withImage = mountControl({+ mapControls: {mapInfo: {show: true, active: true}},+ mapInfo: {description: ''}+ });+ t.equal(withImage.find('img').length, 0, 'an imported description does not fetch images');+ t.ok(withImage.text().includes('pixel'), 'keeps the image alt text as plain text');++ shown.find('button[aria-label="Minimize map info"]').hostNodes().simulate('click');+ t.equal(onToggleMapControl.callCount, 1, 'closing the panel toggles map info');+ t.equal(onToggleMapControl.firstCall.args[0], 'mapInfo');++ const collapsed = mountControl({+ mapControls: {mapInfo: {show: true, active: false}},+ mapInfo: {title: 'Harbor', description: 'Ferry routes'}+ });+ const descriptionOnly = mountControl({+ mapControls: {mapInfo: {show: true, active: true}},+ mapInfo: {description: 'Ferry routes'}+ });+ t.equal(+ descriptionOnly.find('.map-info-title').length,+ 0,+ 'a description without a name does not reserve a title row'+ );+ t.ok(+ descriptionOnly.find('.map-info-description--only').hostNodes().length > 0,+ 'a description without a name starts at the top of the card'+ );+ t.ok(descriptionOnly.text().includes('Ferry routes'), 'renders a description without a name');++ t.equal(collapsed.find('.map-info-panel').length, 0, 'a collapsed panel hides the card');+ t.ok(+ collapsed.find('.map-info').hostNodes().length > 0,+ 'a collapsed panel shows the docs button'+ );++ t.end();+});diff --git a/test/browser/components/side-panel/interaction-manager-test.js b/test/browser/components/side-panel/interaction-manager-test.jsindex e5ccbada3..184335366 100644--- a/test/browser/components/side-panel/interaction-manager-test.js+++ b/test/browser/components/side-panel/interaction-manager-test.js@@ -7,6 +7,7 @@ import sinon from 'sinon';import {InteractionManagerFactory, appInjector} from '@kepler.gl/components';import {defaultInteractionConfig} from '@kepler.gl/reducers';+import {initApplicationConfig} from '@kepler.gl/utils';import {IntlWrapper, mountWithTheme} from 'test/helpers/component-utils';const InteractionManager = appInjector.get(InteractionManagerFactory);@@ -260,3 +261,108 @@ test('Components -> InteractionManager legend settings expand independently', tt.end();});++test('Components -> InteractionManager map info section', t => {+ const setMapInfo = sinon.spy();+ const setMapControlVisibility = sinon.spy();+ const toggleMapControl = sinon.spy();++ const wrapper = mountWithTheme(+ <IntlWrapper>+ <InteractionManager+ interactionConfig={defaultInteractionConfig}+ datasets={{}}+ panelMetadata={panelMetadata}+ mapInfo={{title: undefined, description: undefined}}+ mapInfoShow={true}+ mapInfoActive={true}+ uiStateActions={{setMapControlVisibility, toggleMapControl}}+ visStateActions={{+ interactionConfigChange: () => {},+ setColumnDisplayFormat: () => {},+ setMapInfo,+ layerConfigChange: () => {},+ updateLayerGroup: () => {}+ }}+ />+ </IntlWrapper>+ );++ t.ok(wrapper.find('.interaction-map-info').hostNodes().length >= 1, 'renders map info section');+ t.equal(+ wrapper.find('input#map-info-toggle').at(0).prop('checked'),+ true,+ 'map info switch starts on'+ );+ t.equal(+ wrapper.find('.interaction-map-info__content').hostNodes().length,+ 0,+ 'name and description stay collapsed until opened'+ );++ wrapper.find('.interaction-map-info__header').hostNodes().at(0).simulate('click');+ wrapper.update();++ t.ok(+ wrapper.find('.interaction-map-info__content').hostNodes().length >= 1,+ 'opening settings shows name and description'+ );+ t.equal(wrapper.find('input#interaction-map-name').at(0).prop('value'), '', 'name starts unset');+ t.equal(+ wrapper.find('textarea#interaction-map-description').at(0).prop('value'),+ '',+ 'description starts unset'+ );+ t.equal(+ wrapper.find('textarea#interaction-map-description').at(0).prop('rows'),+ 2,+ 'description is a two-line text area'+ );++ wrapper+ .find('input#interaction-map-name')+ .at(0)+ .simulate('change', {target: {value: 'Harbor'}});+ t.deepEqual(setMapInfo.args[0][0], {title: 'Harbor'}, 'editing the name updates map info');++ wrapper.find('input#map-info-toggle').at(0).simulate('change');+ t.deepEqual(+ setMapControlVisibility.args[0],+ ['mapInfo', false],+ 'turning the switch off hides the on-map card'+ );+ t.equal(toggleMapControl.callCount, 0, 'hiding the card does not collapse it');++ t.end();+});++test('Components -> InteractionManager map info section can be disabled', t => {+ initApplicationConfig({enableMapInfo: false});+ const wrapper = mountWithTheme(+ <IntlWrapper>+ <InteractionManager+ interactionConfig={defaultInteractionConfig}+ datasets={{}}+ panelMetadata={panelMetadata}+ mapInfo={{title: 'Harbor', description: 'Ferry routes'}}+ mapInfoShow={true}+ visStateActions={{+ interactionConfigChange: () => {},+ setColumnDisplayFormat: () => {},+ setMapInfo: () => {},+ layerConfigChange: () => {},+ updateLayerGroup: () => {}+ }}+ />+ </IntlWrapper>+ );++ t.equal(+ wrapper.find('.interaction-map-info').hostNodes().length,+ 0,+ 'hides the map info section when enableMapInfo is false'+ );++ initApplicationConfig({enableMapInfo: true});+ t.end();+});diff --git a/test/browser/file-handler-test.js b/test/browser/file-handler-test.jsindex 11e9c1307..6d7a4ad4b 100644--- a/test/browser/file-handler-test.js+++ b/test/browser/file-handler-test.js@@ -668,8 +668,8 @@ test('#file-handler -> readFileInBatches.keplerMap -> processFileData', async tt.deepEqual(Object.keys(processed[0].data),- ['datasets', 'config'],- 'processFileData of keplergl json should have datasets and config'+ ['datasets', 'config', 'info'],+ 'processFileData of keplergl json should have datasets, config and map info');t.deepEqual(Object.keys(processed[0].data.datasets[0].data),diff --git a/test/node/reducers/composer-state-test.js b/test/node/reducers/composer-state-test.jsindex a92d919c0..7f9e03bf4 100644--- a/test/node/reducers/composer-state-test.js+++ b/test/node/reducers/composer-state-test.js@@ -269,6 +269,89 @@ test('#composerStateReducer - addDataToMapUpdater: mapLegend', t => {t.end();});+test('#composerStateReducer - addDataToMapUpdater: mapInfo', t => {+ const state = keplerGlReducer(undefined, registerEntry({id: 'test'})).test;++ t.equal(state.uiState.mapControls.mapInfo.active, true, 'map info panel starts open');+ t.equal(state.visState.mapInfo.title, undefined, 'map title starts unset');+ t.equal(state.visState.mapInfo.description, undefined, 'map description starts unset');++ const withInfo = addDataToMapUpdater(state, {+ payload: {+ datasets: {+ data: mockRawData,+ info: {id: 'foo'}+ },+ info: {title: 'Harbor', description: 'Ferry routes'}+ }+ });++ drainTasksForTesting();++ t.equal(withInfo.visState.mapInfo.title, 'Harbor', 'loaded map title is restored');+ t.equal(+ withInfo.visState.mapInfo.description,+ 'Ferry routes',+ 'loaded map description is restored'+ );+ t.equal(withInfo.uiState.mapControls.mapInfo.active, true, 'panel stays open when title loads');++ const collapsed = addDataToMapUpdater(state, {+ payload: {+ datasets: {+ data: mockRawData,+ info: {id: 'foo'}+ },+ info: {title: 'Harbor', description: ''},+ config: {+ uiState: {+ mapControls: {+ mapInfo: {active: false}+ }+ }+ }+ }+ });++ drainTasksForTesting();++ t.equal(collapsed.visState.mapInfo.title, 'Harbor', 'collapsed map still restores its title');+ t.equal(collapsed.visState.mapInfo.description, undefined, 'a blank description stays unset');+ t.equal(+ collapsed.uiState.mapControls.mapInfo.active,+ false,+ 'saved collapsed map info panel stays closed'+ );++ const hidden = addDataToMapUpdater(state, {+ payload: {+ datasets: {+ data: mockRawData,+ info: {id: 'foo'}+ },+ info: {title: 'Harbor', description: 'Ferry routes'},+ config: {+ uiState: {+ mapControls: {+ mapInfo: {show: false, active: true}+ }+ }+ }+ }+ });++ drainTasksForTesting();++ t.equal(hidden.visState.mapInfo.title, 'Harbor', 'a hidden map still restores its title');+ t.equal(+ hidden.uiState.mapControls.mapInfo.show,+ false,+ 'saved hidden map info stays off the map'+ );++ t.end();+});+test('#composerStateReducer - addDataToMapUpdater: locale', t => {const state = keplerGlReducer(undefined, registerEntry({id: 'test'})).test;diff --git a/test/node/schemas/ui-state-schema-test.js b/test/node/schemas/ui-state-schema-test.jsindex 5dec4a1d1..01d9e163c 100644--- a/test/node/schemas/ui-state-schema-test.js+++ b/test/node/schemas/ui-state-schema-test.js@@ -23,8 +23,8 @@ test('#uiStateSchema -> v1 -> save load uiState', t => {t.equal(uiToSave.theme, 'dark', 'default theme should be dark');t.deepEqual(uiToSave.mapControls,- {mapLegend: {active: false}, chart: {active: false}},- 'default mapLegend and chart should be inactive with no settings'+ {mapLegend: {active: false}, chart: {active: false}, mapInfo: {active: true, show: true}},+ 'default mapLegend and chart should be inactive and map info open');t.deepEqual(uiLoaded, uiToSave, 'loaded uiState should match saved uiState');diff --git a/test/node/utils/data-processor-test.js b/test/node/utils/data-processor-test.jsindex d31859bf8..443bdd02f 100644--- a/test/node/utils/data-processor-test.js+++ b/test/node/utils/data-processor-test.js@@ -30,6 +30,7 @@ import {parseCsvRowsByFieldType,processCsvData,processGeojson,+ processKeplerglJSON,processRowObject,detectDelimiter} from '@kepler.gl/processors';@@ -1055,3 +1056,52 @@ test('Processor -> analyzerTypeToFieldType', t => {t.end();});++test('Processor -> processKeplerglJSON keeps display info', t => {+ const parsed = processKeplerglJSON({+ datasets: [],+ config: {+ version: 'v1',+ config: {}+ },+ info: {+ app: 'kepler.gl',+ created_at: 'today',+ title: 'Harbor',+ description: 'Ferry routes',+ source: 'kepler.gl'+ }+ });++ t.equal(parsed.info.title, 'Harbor', 'should keep the map title');+ t.equal(parsed.info.description, 'Ferry routes', 'should keep the map description');+ t.equal(parsed.info.app, undefined, 'should not copy export metadata onto map info');+ t.equal(parsed.info.source, undefined, 'should not copy the export source onto map info');+ t.end();+});++test('Processor -> processKeplerglJSON replaces display info', t => {+ const titleOnly = processKeplerglJSON({+ datasets: [],+ config: {version: 'v1', config: {}},+ info: {app: 'kepler.gl', created_at: 'today', title: 'Harbor'}+ });++ t.ok(+ 'description' in titleOnly.info,+ 'should always return description so it clears the previous map'+ );+ t.equal(titleOnly.info.description, undefined, 'should not keep a missing description');++ const noInfo = processKeplerglJSON({+ datasets: [],+ config: {version: 'v1', config: {}}+ });++ t.deepEqual(+ noInfo.info,+ {title: undefined, description: undefined},+ 'a saved map without display info should clear both values'+ );+ t.end();+});diff --git a/test/node/utils/export-utils-test.js b/test/node/utils/export-utils-test.jsindex 29c8fd962..b9b9f5ca0 100644--- a/test/node/utils/export-utils-test.js+++ b/test/node/utils/export-utils-test.js@@ -13,7 +13,8 @@ import {calculateExportImageSize,omitLayerApiKeys,getExportFileName,- getExportFileNameBase+ getExportFileNameBase,+ exportMapToHTML} from '@kepler.gl/utils';import {EXPORT_IMG_RATIOS, RESOLUTIONS} from '@kepler.gl/constants';@@ -30,6 +31,41 @@ test('exportUtils -> ExportJson', t => {t.end();});+test('exportUtils -> ExportHtml includes map info', t => {+ const html = exportMapToHTML({+ datasets: [],+ config: {version: 'v1', config: {}},+ info: {title: 'Harbor', description: 'Ferry routes'},+ mode: 'READ'+ });++ t.ok(html.includes('"title":"Harbor"'), 'exported html should restore the map title');+ t.ok(+ html.includes('"description":"Ferry routes"'),+ 'exported html should restore the map description'+ );+ t.ok(html.includes('info,'), 'exported html should pass info to addDataToMap');++ t.end();+});++test('exportUtils -> ExportHtml escapes script terminators in map info', t => {+ const html = exportMapToHTML({+ datasets: [],+ config: {version: 'v1', config: {}},+ info: {title: '</script><script>window.pwned=1;</script>'},+ mode: 'READ'+ });++ t.notOk(+ html.includes('<script>window.pwned'),+ 'a map title should not be able to close the inline script'+ );+ t.ok(html.includes('\\u003c/script>'), 'should escape `<` in the serialized map info');++ t.end();+});+test('exportUtils -> getScaleFromImageSize', t => {t.equal(getScaleFromImageSize(800, 600, 1400, 990),diff --git a/test/node/utils/map-info-utils-test.js b/test/node/utils/map-info-utils-test.jsindex ca13a5a7e..e8fdf43af 100644--- a/test/node/utils/map-info-utils-test.js+++ b/test/node/utils/map-info-utils-test.js@@ -2,9 +2,14 @@// Copyright contributors to the kepler.gl projectimport test from 'tape';-import {isValidMapInfo} from '@kepler.gl/utils';+import {isValidMapInfo, optionalMapInfo} from '@kepler.gl/utils';test('mapInfoUtils -> isValidMapInfo', t => {+ t.equal(+ isValidMapInfo({title: '', description: ''}),+ true,+ 'Should validate map info with no name or description'+ );t.equal(isValidMapInfo({title: 'example', description: ''}),true,@@ -26,8 +31,15 @@ test('mapInfoUtils -> isValidMapInfo', t => {);t.equal(isValidMapInfo({- description:- 'this is a really long description for a map that is not going to work because i really do not like this kind of long title',+ description: 'a'.repeat(1024),+ title: 'this is a map'+ }),+ true,+ 'Should validate a description at the 1024 character limit'+ );+ t.equal(+ isValidMapInfo({+ description: 'a'.repeat(1025),title: 'this is a map'}),false,@@ -35,3 +47,15 @@ test('mapInfoUtils -> isValidMapInfo', t => {);t.end();});++test('mapInfoUtils -> optionalMapInfo', t => {+ t.equal(optionalMapInfo(undefined), undefined, 'missing info stays unset');+ t.equal(optionalMapInfo({title: '', description: ' '}), undefined, 'blank text stays unset');+ t.deepEqual(optionalMapInfo({title: 'Harbor'}), {title: 'Harbor'}, 'keeps a name');+ t.deepEqual(+ optionalMapInfo({title: 'Harbor', description: 'Ferry routes'}),+ {title: 'Harbor', description: 'Ferry routes'},+ 'keeps a name and description'+ );+ t.end();+});