Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
feat: improve 3D tiles API token lifecycle (#3759)
Igor Dykhta83e63b8a4bb1
diff --git a/src/actions/src/action-types.ts b/src/actions/src/action-types.tsindex be8e421ff..09e45ab50 100644--- a/src/actions/src/action-types.ts+++ b/src/actions/src/action-types.ts@@ -220,6 +220,7 @@ export const ActionTypes = {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_FILE_NAME: `${ACTION_PREFIX}SET_EXPORT_MAP_FILE_NAME`,+ SET_EXPORT_INCLUDE_LAYER_API_KEYS: `${ACTION_PREFIX}SET_EXPORT_INCLUDE_LAYER_API_KEYS`,// uiState > editorSET_EDITOR_MODE: `${ACTION_PREFIX}SET_EDITOR_MODE`,diff --git a/src/actions/src/ui-state-actions.ts b/src/actions/src/ui-state-actions.tsindex ff0f00861..034b1f13d 100644--- a/src/actions/src/ui-state-actions.ts+++ b/src/actions/src/ui-state-actions.ts@@ -472,6 +472,26 @@ export const setExportMapFileName: ((payload: SetExportMapFileNameUpdaterAction['payload']) => ({payload}));+/** SET_EXPORT_INCLUDE_LAYER_API_KEYS */+export type SetExportIncludeLayerApiKeysUpdaterAction = {+ payload: boolean;+};+/**+ * Whether exported HTML and JSON maps keep access tokens stored on layers.+ * @memberof uiStateActions+ * @param includeLayerApiKeys - include layer API keys in the export+ * @public+ */+export const setExportIncludeLayerApiKeys: (+ includeLayerApiKeys: SetExportIncludeLayerApiKeysUpdaterAction['payload']+) => Merge<+ SetExportIncludeLayerApiKeysUpdaterAction,+ {type: typeof ActionTypes.SET_EXPORT_INCLUDE_LAYER_API_KEYS}+> = createAction(+ ActionTypes.SET_EXPORT_INCLUDE_LAYER_API_KEYS,+ (payload: SetExportIncludeLayerApiKeysUpdaterAction['payload']) => ({payload})+);+/** SET_LOCALE */export type SetLocaleUpdaterAction = {payload: {locale: string};diff --git a/src/components/src/map-container.tsx b/src/components/src/map-container.tsxindex 2ba4b8d87..0c59bfd8d 100644--- a/src/components/src/map-container.tsx+++ b/src/components/src/map-container.tsx@@ -38,7 +38,8 @@ import {LayerBaseConfig,VisualChannelDomain,EditorLayerUtils,- AggregatedBin+ AggregatedBin,+ TILE3D_LOAD_ERROR_MESSAGE} from '@kepler.gl/layers';import {AttributionWithStyle,@@ -813,6 +814,21 @@ export default function MapContainerFactory(}};+ _onTilesetLoadError = (idx: number, kind: 'token' | 'generic' | null) => {+ const layer = this.props.visState.layers[idx];+ const id = `tile3d-load-${layer?.id ?? idx}`;+ if (!kind) {+ this.props.uiStateActions.removeNotification?.(id);+ return;+ }+ this.props.uiStateActions.addNotification(+ errorNotification({+ id,+ message: TILE3D_LOAD_ERROR_MESSAGE[kind]+ })+ );+ };+/* component render functions *//* eslint-disable complexity */@@ -1057,7 +1073,8 @@ export default function MapContainerFactory(onFilteredItemsChange: this._onLayerFilteredItemsChange,onWMSFeatureInfo: this._onWMSFeatureInfo,onRedrawNeeded: this._onRedrawNeeded,- onFitBounds: this._onFitBounds+ onFitBounds: this._onFitBounds,+ onTilesetLoadError: this._onTilesetLoadError},deckGlProps);diff --git a/src/components/src/modal-container.tsx b/src/components/src/modal-container.tsxindex bcb9e9946..3bdd3f6fc 100644--- a/src/components/src/modal-container.tsx+++ b/src/components/src/modal-container.tsx@@ -232,10 +232,11 @@ export default function ModalContainerFactory(_onExportMap = () => {const {uiState} = this.props;- const {format} = uiState.exportMap;+ const {format, includeLayerApiKeys, fileName} = uiState.exportMap;(format === EXPORT_MAP_FORMATS.HTML ? exportHtml : exportJson)(this.props, {- ...(this.props.uiState.exportMap[format] || {}),- fileName: uiState.exportMap.fileName+ ...(uiState.exportMap[format] || {}),+ includeLayerApiKeys,+ fileName});this._closeModal();};@@ -450,6 +451,7 @@ export default function ModalContainerFactory(onChangeExportMapFormat={uiStateActions.setExportMapFormat}onEditUserMapboxAccessToken={uiStateActions.setUserMapboxAccessToken}onChangeExportMapHTMLMode={uiStateActions.setExportHTMLMapMode}+ onChangeExportIncludeLayerApiKeys={uiStateActions.setExportIncludeLayerApiKeys}onChangeExportMapFileName={uiStateActions.setExportMapFileName}/>);diff --git a/src/components/src/modals/export-map-modal/components.tsx b/src/components/src/modals/export-map-modal/components.tsxindex ca49c26fd..7d2ac9f9a 100644--- a/src/components/src/modals/export-map-modal/components.tsx+++ b/src/components/src/modals/export-map-modal/components.tsx@@ -4,7 +4,9 @@import React 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 Checkbox from '../../common/checkbox';export const StyledExportMapModalContent = styled(StyledModalContent)`padding-top: 12px;@@ -52,3 +54,35 @@ export const ExportMapLink = ({children, ...props}) => ({children}</StyledExportLink>);++type IncludeLayerApiKeysToggleProps = {+ id: string;+ checked: boolean;+ onChange: (includeLayerApiKeys: boolean) => void;+};++export const IncludeLayerApiKeysToggle = ({+ id,+ checked,+ onChange+}: IncludeLayerApiKeysToggleProps) => (+ <StyledExportMapSection>+ <div className="description">+ <div className="title">+ <FormattedMessage id="modal.exportMap.includeApiKeys" />+ </div>+ <div className="subtitle">+ <FormattedMessage id="modal.exportMap.includeApiKeysSubtitle" />+ </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>+);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.tsxindex b78574da4..9b66e008c 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@@ -3,7 +3,12 @@import React from 'react';import {StyledExportSection, StyledType, CheckMark} from '../../common/styled-components';-import {StyledExportMapNote, StyledWarning, ExportMapLink} from './components';+import {+ StyledExportMapNote,+ StyledWarning,+ ExportMapLink,+ IncludeLayerApiKeysToggle+} from './components';import {EXPORT_HTML_MAP_MODE_OPTIONS,EXPORT_HTML_MAP_DOC,@@ -14,7 +19,12 @@ import {injectIntl} from 'react-intl';import {FormattedMessage} from '@kepler.gl/localization';import {IntlShape} from 'react-intl';-import {setUserMapboxAccessToken, setExportHTMLMapMode, ActionHandler} from '@kepler.gl/actions';+import {+ setUserMapboxAccessToken,+ setExportHTMLMapMode,+ setExportIncludeLayerApiKeys,+ ActionHandler+} from '@kepler.gl/actions';const ExportMapStyledExportSection = styled(StyledExportSection)`margin: 8px 0 12px;@@ -68,7 +78,9 @@ const BigStyledTile = styled(StyledType)`type ExportHtmlMapProps = {onChangeExportMapHTMLMode: ActionHandler<typeof setExportHTMLMapMode>;+ onChangeExportIncludeLayerApiKeys: ActionHandler<typeof setExportIncludeLayerApiKeys>;onEditUserMapboxAccessToken: ActionHandler<typeof setUserMapboxAccessToken>;+ includeLayerApiKeys?: boolean;options: {userMapboxToken?: string;mode?: string;@@ -85,9 +97,13 @@ function ExportHtmlMapFactory(): React.ComponentType<ExportHtmlMapProps> {onChangeExportMapHTMLMode = () => {return;},+ onChangeExportIncludeLayerApiKeys = () => {+ return;+ },onEditUserMapboxAccessToken = () => {return;},+ includeLayerApiKeys = false,options = {},intl}) => (@@ -95,6 +111,11 @@ function ExportHtmlMapFactory(): React.ComponentType<ExportHtmlMapProps> {<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">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.tsxindex 81fe51c95..28c35f7d0 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,7 +6,13 @@ 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} from './components';+import {+ StyledExportMapNote,+ StyledWarning,+ ExportMapLink,+ IncludeLayerApiKeysToggle+} from './components';+import {ActionHandler, setExportIncludeLayerApiKeys} from '@kepler.gl/actions';import {FormattedMessage} from '@kepler.gl/localization';import {CopyToClipboard} from 'react-copy-to-clipboard';@@ -48,15 +54,28 @@ const StyledJsonExportSection = styled(StyledExportSection)`type ExportJsonPropTypes = {config: any;+ includeLayerApiKeys?: boolean;+ onChangeExportIncludeLayerApiKeys?: ActionHandler<typeof setExportIncludeLayerApiKeys>;};-const ExportJsonMapUnmemoized = ({config = {}}: ExportJsonPropTypes) => {+const ExportJsonMapUnmemoized = ({+ config = {},+ includeLayerApiKeys = false,+ onChangeExportIncludeLayerApiKeys = () => {+ return;+ }+}: ExportJsonPropTypes) => {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}+ onChange={onChangeExportIncludeLayerApiKeys}+ /><StyledJsonExportSection className="export-map-modal__json-options"><div className="description"><div className="title">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 e86bda4b9..00c1ce670 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@@ -19,16 +19,25 @@ import {FormattedMessage} from '@kepler.gl/localization';import {ActionHandler,setExportHTMLMapMode,+ setExportIncludeLayerApiKeys,setExportMapFileName,setUserMapboxAccessToken} from '@kepler.gl/actions';import ExportFileNameSection from '../export-file-name';+interface ExportMapModalOptions {+ format: string;+ includeLayerApiKeys?: boolean;+ fileName?: string;+ [key: string]: any;+}+interface ExportMapModalFactoryProps {- options?: {format: string; fileName?: string};+ options?: ExportMapModalOptions;config: any;onEditUserMapboxAccessToken: ActionHandler<typeof setUserMapboxAccessToken>;onChangeExportMapHTMLMode?: ActionHandler<typeof setExportHTMLMapMode>;+ onChangeExportIncludeLayerApiKeys?: ActionHandler<typeof setExportIncludeLayerApiKeys>;onChangeExportMapFormat?: (format: string) => any;onChangeExportMapFileName?: ActionHandler<typeof setExportMapFileName>;mapFormat?: string;@@ -54,6 +63,7 @@ function ExportMapModalFactory(config = {},onChangeExportMapFormat = NO_OP,onChangeExportMapHTMLMode = NO_OP,+ onChangeExportIncludeLayerApiKeys = NO_OP,onChangeExportMapFileName = NO_OP,onEditUserMapboxAccessToken = NO_OP,options = {format: ''}@@ -97,13 +107,19 @@ function ExportMapModalFactory(><ExportHtmlMaponChangeExportMapHTMLMode={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} />+ <ExportJsonMap+ config={config}+ includeLayerApiKeys={Boolean(options.includeLayerApiKeys)}+ onChangeExportIncludeLayerApiKeys={onChangeExportIncludeLayerApiKeys}+ /></StyledExportMapFormatPanel>) : null}</StyledExportMapFormatPanels>diff --git a/src/components/src/side-panel/layer-panel/layer-api-key-input.tsx b/src/components/src/side-panel/layer-panel/layer-api-key-input.tsxnew file mode 100644index 000000000..70506c7bf--- /dev/null+++ b/src/components/src/side-panel/layer-panel/layer-api-key-input.tsx@@ -0,0 +1,105 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import React, {useCallback, useState} from 'react';+import styled from 'styled-components';+import {useIntl} from 'react-intl';+import {FormattedMessage} from '@kepler.gl/localization';++import {Input} from '../../common/styled-components';++/** Shown in place of a stored key so the value cannot be copied from the input. */+export const API_KEY_MASK = '*****';++const ApiKeyHint = styled.div`+ color: ${props => props.theme.subtextColor};+ font-size: 11px;+ line-height: 1.4;+ margin-top: 6px;+`;++const ApiKeyError = styled.div`+ background-color: ${props => props.theme.notificationColors.error || '#000'};+ color: #fff;+ font-size: 11px;+ line-height: 1.4;+ margin-top: 8px;+ padding: 8px;+ border-radius: 4px;+`;++type LayerApiKeyInputProps = {+ accessToken?: string;+ loadError?: 'token' | 'generic' | null;+ onCommit: (nextToken: string) => void;+};++/**+ * Replaces a layer access token without ever putting the current token in the DOM.+ * An existing token is shown as {@link API_KEY_MASK}. Typing a new value and leaving+ * the field commits it.+ */+const LayerApiKeyInput: React.FC<LayerApiKeyInputProps> = ({accessToken, loadError, onCommit}) => {+ const intl = useIntl();+ const [draft, setDraft] = useState<string | null>(null);+ const isEditing = draft !== null;+ const hasKey = Boolean(accessToken);+ const value = isEditing ? draft : hasKey ? API_KEY_MASK : '';++ const commit = useCallback(() => {+ const next = (draft ?? '').trim();+ setDraft(null);+ if (!next || next === API_KEY_MASK || next === accessToken) {+ return;+ }+ onCommit(next);+ }, [accessToken, draft, onCommit]);++ const blockClipboard = useCallback(+ (event: React.ClipboardEvent<HTMLInputElement>) => {+ if (!isEditing) {+ event.preventDefault();+ }+ },+ [isEditing]+ );++ return (+ <div>+ <Input+ type="text"+ value={value}+ placeholder={intl.formatMessage({id: 'layer.apiKeyPlaceholder'})}+ autoComplete="off"+ autoCorrect="off"+ spellCheck={false}+ data-1p-ignore="true"+ data-lpignore="true"+ aria-label={intl.formatMessage({id: 'layer.apiKey'})}+ onFocus={() => setDraft('')}+ onChange={event => setDraft(event.target.value)}+ onBlur={commit}+ onCopy={blockClipboard}+ onCut={blockClipboard}+ onMouseDown={event => event.stopPropagation()}+ onKeyDown={event => {+ if (event.key === 'Enter') {+ event.currentTarget.blur();+ }+ }}+ />+ <ApiKeyHint>+ <FormattedMessage id="layer.apiKeyHint" />+ </ApiKeyHint>+ {loadError ? (+ <ApiKeyError>+ <FormattedMessage+ id={loadError === 'token' ? 'layer.tile3dTokenErrorField' : 'layer.tile3dLoadError'}+ />+ </ApiKeyError>+ ) : null}+ </div>+ );+};++export default LayerApiKeyInput;diff --git a/src/components/src/side-panel/layer-panel/layer-configurator.tsx b/src/components/src/side-panel/layer-panel/layer-configurator.tsxindex 3d414167a..ec7a2c3d9 100644--- a/src/components/src/side-panel/layer-panel/layer-configurator.tsx+++ b/src/components/src/side-panel/layer-panel/layer-configurator.tsx@@ -37,13 +37,15 @@ import ScenegraphModelSelectorFactory, {import RasterTileLayerConfiguratorFactory from './raster-tile-layer-configurator';import VectorTileLayerConfiguratorFactory from './vector-tile-layer-configurator';+import LayerApiKeyInput from './layer-api-key-input';-import {ActionHandler, toggleModal} from '@kepler.gl/actions';+import {ActionHandler, toggleModal, updateDatasetProps} from '@kepler.gl/actions';import {AGGREGATION_TYPE_OPTIONS,LAYER_TYPES,CUSTOM_SCENEGRAPH_MODEL_ID,- BitmapDatasetMetadata+ BitmapDatasetMetadata,+ Tile3DDatasetMetadata} from '@kepler.gl/constants';import {AggregationLayer,@@ -83,6 +85,7 @@ type LayerConfiguratorProps = {) => void;updateLayerColorUI: (prop: string, newConfig: NestedPartial<ColorUI>) => void;updateLayerTextLabel: (idx: number | 'all', prop: string, value: any) => void;+ updateDatasetProps?: ActionHandler<typeof updateDatasetProps>;disableTypeSelect?: boolean;};@@ -1652,9 +1655,26 @@ export default function LayerConfiguratorFactory();}- _renderTile3dLayerConfig({layer, visConfiguratorProps, layerConfiguratorProps}) {+ _renderTile3dLayerConfig({layer, dataset, visConfiguratorProps, layerConfiguratorProps}) {+ const metadata = (dataset?.metadata || {}) as Tile3DDatasetMetadata;+ const {updateDatasetProps: onUpdateDatasetProps} = this.props;return (<StyledLayerVisualConfigurator>+ <LayerConfigGroup label={'layer.apiKey'}>+ <LayerApiKeyInput+ accessToken={metadata.tile3dAccessToken}+ loadError={+ (layer as {tilesetLoadError?: 'token' | 'generic' | null}).tilesetLoadError+ }+ onCommit={token => {+ const dataId = layer.config.dataId;+ if (!dataId || !onUpdateDatasetProps) {+ return;+ }+ onUpdateDatasetProps(dataId, {metadata: {tile3dAccessToken: token}});+ }}+ />+ </LayerConfigGroup><LayerConfigGroup label={'layer.appearance'}><LayerColorSelector {...layerConfiguratorProps} /><VisConfigSlider {...layer.visConfigSettings.opacity} {...visConfiguratorProps} />diff --git a/src/components/src/side-panel/layer-panel/layer-list.tsx b/src/components/src/side-panel/layer-panel/layer-list.tsxindex 79ab7c542..c118ba97c 100644--- a/src/components/src/side-panel/layer-panel/layer-list.tsx+++ b/src/components/src/side-panel/layer-panel/layer-list.tsx@@ -364,7 +364,8 @@ function LayerListFactory(removeLayer: visStateActions.removeLayer,zoomToLayer: mapStateActions.fitBounds,duplicateLayer: visStateActions.duplicateLayer,- layerSetIsValid: visStateActions.layerSetIsValid+ layerSetIsValid: visStateActions.layerSetIsValid,+ updateDatasetProps: visStateActions.updateDatasetProps}),[visStateActions, mapStateActions]);diff --git a/src/components/src/side-panel/layer-panel/layer-panel.tsx b/src/components/src/side-panel/layer-panel/layer-panel.tsxindex d27e59413..ac2857bd2 100644--- a/src/components/src/side-panel/layer-panel/layer-panel.tsx+++ b/src/components/src/side-panel/layer-panel/layer-panel.tsx@@ -52,6 +52,7 @@ type LayerPanelProps = {duplicateLayer: ActionHandler<typeof VisStateActions.duplicateLayer>;listeners?: React.ElementType;layerToggleVisibility: ActionHandler<typeof VisStateActions.layerToggleVisibility>;+ updateDatasetProps?: ActionHandler<typeof VisStateActions.updateDatasetProps>;splitMap?: SplitMap;};@@ -177,6 +178,13 @@ function LayerPanelFactory(GLOBE_SUPPORTED_LAYERS[layer.type ?? ''] === false ? (<FormattedMessage id={'layerManager.globeUnsupported'} values={{layerType: layer.type}} />) : undefined;+ const tilesetLoadError = (layer as {tilesetLoadError?: 'token' | 'generic' | null})+ .tilesetLoadError;+ const tilesetWarning = tilesetLoadError ? (+ <FormattedMessage+ id={tilesetLoadError === 'token' ? 'layer.tile3dTokenError' : 'layer.tile3dLoadError'}+ />+ ) : undefined;return (<PanelWrapper@@ -195,7 +203,7 @@ function LayerPanelFactory(labelRCGColorValues={config.dataId ? datasets[config.dataId].color : null}layerType={layer.type}allowDuplicate={allowDuplicate}- warning={globeWarning}+ warning={tilesetWarning || globeWarning}onToggleEnableConfig={this._toggleEnableConfig}onToggleVisibility={this._toggleVisibility}onResetIsValid={this._resetIsValid}@@ -224,6 +232,7 @@ function LayerPanelFactory(updateLayerType={this.updateLayerType}updateLayerTextLabel={this.updateLayerTextLabel}updateLayerVisConfig={this.updateLayerVisConfig}+ updateDatasetProps={this.props.updateDatasetProps}/>))}</PanelWrapper>diff --git a/src/layers/src/index.ts b/src/layers/src/index.tsindex 3883367cb..2c4063f7a 100644--- a/src/layers/src/index.ts+++ b/src/layers/src/index.ts@@ -68,7 +68,7 @@ export {} from './raster-tile/raster-tile-layer';import {default as Tile3DLayer} from './tile3d-layer/tile3d-layer';-export {default as Tile3DLayer} from './tile3d-layer/tile3d-layer';+export {default as Tile3DLayer, TILE3D_LOAD_ERROR_MESSAGE} from './tile3d-layer/tile3d-layer';export {default as Tile3DLayerIcon} from './tile3d-layer/tile3d-layer-icon';import {default as BitmapOverlayLayer} from './bitmap-layer/bitmap-layer';diff --git a/src/layers/src/tile3d-layer/tile3d-layer.ts b/src/layers/src/tile3d-layer/tile3d-layer.tsindex 344771c13..6e6b49ab0 100644--- a/src/layers/src/tile3d-layer/tile3d-layer.ts+++ b/src/layers/src/tile3d-layer/tile3d-layer.ts@@ -70,6 +70,10 @@ function _checkLightingActive(context: any): boolean {*/// @ts-expect-error Types have separate declarations of a private property '_loadTileset'.class KeplerTile3DLayer extends DeckTile3DLayer {+ private _tilesetLoadId = 0;+ private _acceptedLoadId = 0;+ private _acceptedTileset: {destroy?: () => void} | null = null;+shouldUpdateState(params: any): boolean {if (super.shouldUpdateState(params)) return true;const lightingActive = _checkLightingActive(this.context);@@ -90,8 +94,21 @@ class KeplerTile3DLayer extends DeckTile3DLayer {// and force sublayer re-creation so models revert to their default (unlit)// materials.updateState(params: any): void {+ const {props, oldProps} = params;+ // deck.gl reloads a tileset only when the data URL changes. Cesium keeps+ // the same URL and puts the API key in loadOptions, so a new key has to+ // be requested explicitly.+ const credentialsChanged =+ Boolean(props?.data) &&+ props.data === oldProps?.data &&+ props.loadOptions !== oldProps?.loadOptions;+super.updateState(params);+ if (credentialsChanged) {+ void this._loadTileset(props.data);+ }+const lightingActive = _checkLightingActive(this.context);const prevLightingActive = (this.state as any)?._lightingWasActive ?? false;@@ -112,15 +129,51 @@ class KeplerTile3DLayer extends DeckTile3DLayer {// @ts-ignore override of private method called by deck.gl internalsprivate async _loadTileset(tilesetUrl: string) {+ const loadId = ++this._tilesetLoadId;+ this.setState({_tilesetLoadFailed: false});+ const notify = (this.props as {onTilesetError?: (kind: Tile3DLoadErrorKind | null) => void})+ .onTilesetError;+ // Defer so a retry does not dispatch while deck is still updating this layer.+ queueMicrotask(() => {+ if (loadId === this._tilesetLoadId) notify?.(null);+ });try {+ const previousTileset = (this.state as any)?.tileset3d;+ if (previousTileset) {+ previousTileset.destroy?.();+ if (this._acceptedTileset === previousTileset) {+ this._acceptedTileset = null;+ this._acceptedLoadId = 0;+ }+ this.setState({tileset3d: null, layerMap: {}});+ }// @ts-expect-error _loadTileset is private in DeckTile3DLayerawait super._loadTileset(tilesetUrl);+ const installed = (this.state as any)?.tileset3d;+ if (loadId !== this._tilesetLoadId) {+ // A newer token retry started. Drop this tileset so the old key+ // cannot overwrite the in-flight or already-accepted request.+ if (installed && installed !== this._acceptedTileset) {+ installed.destroy?.();+ }+ this.setState({+ tileset3d: this._acceptedLoadId === this._tilesetLoadId ? this._acceptedTileset : null,+ layerMap: {}+ });+ return;+ }+ this._acceptedLoadId = loadId;+ this._acceptedTileset = installed ?? null;} catch (error: any) {- if (error?.message?.includes("reading 'refine'")) {- this.raiseError(new Error('Bad tileset format or invalid API key'), '_loadTileset');- } else {- console.error('Tile3DLayer: tileset load error', error);+ if (loadId !== this._tilesetLoadId) {+ return;}+ const kind = tile3dLoadErrorKind(error);+ this.setState({_tilesetLoadFailed: true, tileset3d: null, layerMap: {}});+ queueMicrotask(() => {+ if (loadId === this._tilesetLoadId) notify?.(kind);+ });+ console.error('Tile3DLayer: tileset load error', error);}}@@ -327,6 +380,12 @@ class KeplerTile3DLayer extends DeckTile3DLayer {* complete — no frame is captured with missing tiles.*/get isLoaded(): boolean {+ // A failed tileset request never creates tileset3d, so the base getter+ // stays false and the map spinner never stops.+ if ((this.state as any)?._tilesetLoadFailed) {+ return true;+ }+const baseLoaded = super.isLoaded;if (!baseLoaded) {return false;@@ -359,6 +418,34 @@ class KeplerTile3DLayer extends DeckTile3DLayer {export const TILE3D_LAYER_TYPE = LAYER_TYPES.tile3d;+export type Tile3DLoadErrorKind = 'token' | 'generic';++/** Classify a tileset fetch failure so the UI can tell a bad key from other errors. */+export function tile3dLoadErrorKind(error: unknown): Tile3DLoadErrorKind {+ const message = error instanceof Error ? error.message : String(error ?? '');+ const status =+ typeof (error as {status?: unknown})?.status === 'number'+ ? (error as {status: number}).status+ : undefined;+ if (+ status === 400 ||+ status === 401 ||+ status === 403 ||+ /\b(400|401|403)\b/.test(message) ||+ /api key|access token|unauthorized|forbidden/i.test(message) ||+ message.includes("reading 'refine'")+ ) {+ return 'token';+ }+ return 'generic';+}++export const TILE3D_LOAD_ERROR_MESSAGE: Record<Tile3DLoadErrorKind, string> = {+ token:+ '3D tiles failed to load. The access token may be missing, invalid, or expired. Update it in the layer settings.',+ generic: '3D tiles failed to load. Check the tileset URL and try again.'+};+export type Tile3DLayerVisConfigSettings = {opacity: VisConfigNumber;pointSize: VisConfigNumber;@@ -412,6 +499,8 @@ export default class Tile3DLayer extends Layer {private _layerCallbacks: BindedLayerCallbacks | null = null;private _hasFittedBounds = false;+ /** Set when the tileset request fails, so the layer panel can explain why nothing drew. */+ tilesetLoadError: Tile3DLoadErrorKind | null = null;constructor(props: {dataId: string} & Record<string, any>) {super(props);@@ -548,6 +637,10 @@ export default class Tile3DLayer extends Layer {}_onTilesetLoad = (tileset3d: Tileset3D): void => {+ if (this.tilesetLoadError) {+ this.tilesetLoadError = null;+ this._layerCallbacks?.onTilesetLoadError?.(null);+ }this._extractBoundsFromTileset(tileset3d);const tileUrl = tileset3d.url || '';@@ -663,6 +756,15 @@ export default class Tile3DLayer extends Layer {loader,loadOptions,onTilesetLoad: this._onTilesetLoad,+ // Deck forwards this prop; _loadTileset reads it when the tileset request fails.+ // @ts-expect-error onTilesetError is not part of deck.gl Tile3DLayer props+ onTilesetError: (kind: Tile3DLoadErrorKind | null) => {+ const previous = this.tilesetLoadError;+ this.tilesetLoadError = kind;+ if (kind || previous) {+ this._layerCallbacks?.onTilesetLoadError?.(kind);+ }+ },onTileLoad: this._onTileLoad,onTileUnload: this._onTileUnload,getPointColor: pointColor,diff --git a/src/localization/src/translations/en.ts b/src/localization/src/translations/en.tsindex af8e69139..e837555ce 100644--- a/src/localization/src/translations/en.ts+++ b/src/localization/src/translations/en.ts@@ -116,6 +116,15 @@ export default {service: 'Service',layer: 'Layer',appearance: 'Appearance',+ apiKey: 'Access Token',+ apiKeyPlaceholder: 'Enter a new access token',+ apiKeyHint:+ 'The current token is hidden. Enter a new token and press Enter to reload this layer.',+ tile3dTokenError:+ '3D tiles failed to load. The access token may be missing, invalid, or expired. Update it in the layer settings.',+ tile3dTokenErrorField:+ '3D tiles failed to load. The access token may be missing, invalid, or expired. Enter a new access token below.',+ tile3dLoadError: '3D tiles failed to load. Check the tileset URL and try again.',bounds: 'Bounds',imageSource: 'Image Source',alignment: 'Alignment',@@ -755,6 +764,9 @@ export default {exportMap: {formatTitle: 'Map format',formatSubtitle: 'Choose the format to export your map to',+ includeApiKeys: 'Include layer API keys',+ includeApiKeysSubtitle:+ 'When unchecked, access tokens stored on layers are removed from the exported file.',html: {selection: 'Export your map into an interactive html file.',tokenTitle: 'Mapbox access token',diff --git a/src/reducers/src/ui-state-updaters.ts b/src/reducers/src/ui-state-updaters.tsindex da5d89823..57bf9d1fd 100644--- a/src/reducers/src/ui-state-updaters.ts+++ b/src/reducers/src/ui-state-updaters.ts@@ -227,13 +227,16 @@ export const DEFAULT_EXPORT_JSON: ExportJson = {* @property JSON - Default: 'DEFAULT_EXPORT_JSON',* @property format - Default: 'HTML',* @property fileName Default: `''`,+ * @property includeLayerApiKeys Default: `false`,* @public*/export const DEFAULT_EXPORT_MAP: ExportMap = {[EXPORT_MAP_FORMATS.HTML]: DEFAULT_EXPORT_HTML,[EXPORT_MAP_FORMATS.JSON]: DEFAULT_EXPORT_JSON,format: EXPORT_MAP_FORMATS.HTML,- fileName: ''+ fileName: '',+ // Private layer tokens stay out of the file unless the user opts in.+ includeLayerApiKeys: false};/**@@ -830,6 +833,24 @@ export const setExportMapHTMLModeUpdater = (}});+/**+ * Whether to keep layer access tokens in exported HTML and JSON maps.+ * @param state - `uiState`+ * @param action+ * @param action.payload - include layer API keys+ * @return nextState+ */+export const setExportIncludeLayerApiKeysUpdater = (+ state: UiState,+ {payload: includeLayerApiKeys}: UIStateActions.SetExportIncludeLayerApiKeysUpdaterAction+): UiState => ({+ ...state,+ exportMap: {+ ...state.exportMap,+ includeLayerApiKeys+ }+});+/*** Adds a new notification.* Updates a notification in case of matching ids.diff --git a/src/reducers/src/ui-state.ts b/src/reducers/src/ui-state.tsindex fd45bfee1..7cab9b109 100644--- a/src/reducers/src/ui-state.ts+++ b/src/reducers/src/ui-state.ts@@ -41,6 +41,8 @@ const actionHandler = {[ActionTypes.SET_EXPORT_MAP_HTML_MODE]: uiStateUpdaters.setExportMapHTMLModeUpdater,[ActionTypes.SET_EXPORT_MAP_FILE_NAME]: uiStateUpdaters.setExportMapFileNameUpdater,+ [ActionTypes.SET_EXPORT_INCLUDE_LAYER_API_KEYS]:+ uiStateUpdaters.setExportIncludeLayerApiKeysUpdater,[ActionTypes.LOAD_FILES]: uiStateUpdaters.loadFilesUpdater,[ActionTypes.LOAD_FILES_ERR]: uiStateUpdaters.loadFilesErrUpdater,diff --git a/src/reducers/src/vis-state-updaters.ts b/src/reducers/src/vis-state-updaters.tsindex 5ea8ff57a..0cdaa80ba 100644--- a/src/reducers/src/vis-state-updaters.ts+++ b/src/reducers/src/vis-state-updaters.ts@@ -4130,13 +4130,20 @@ export function updateDatasetPropsUpdater(// validate props: just color for now// we only allow label, color and meta to be updated// const newTable = copyTableAndUpdate(existing, validatedProps);- return {+ const nextState = {...state,datasets: {...datasets,[dataId]: copyTableAndUpdate(existing, validatedProps)}};+ // A tileset access token is read while formatting layer data. Refresh+ // only when that field changes so other metadata edits (e.g. refresh+ // interval) do not rebuild every layer on the dataset.+ if (props.metadata && 'tile3dAccessToken' in props.metadata) {+ return updateAllLayerDomainData(nextState, dataId);+ }+ return nextState;}return state;diff --git a/src/types/layers.d.ts b/src/types/layers.d.tsindex f829ba8ed..b2d5f30c6 100644--- a/src/types/layers.d.ts+++ b/src/types/layers.d.ts@@ -467,6 +467,7 @@ export type LayerCallbacks = {) => void;onRedrawNeeded?: (idx: number) => void;onFitBounds?: (idx: number, bounds: [number, number, number, number]) => void;+ onTilesetLoadError?: (idx: number, kind: 'token' | 'generic' | null) => void;};export type BindedLayerCallbacks = {@@ -479,6 +480,7 @@ export type BindedLayerCallbacks = {) => void;onRedrawNeeded?: () => void;onFitBounds?: (bounds: [number, number, number, number]) => void;+ onTilesetLoadError?: (kind: 'token' | 'generic' | null) => void;};export type VisualChannelAggregation = 'colorAggregation' | 'sizeAggregation';diff --git a/src/types/reducers.d.ts b/src/types/reducers.d.tsindex c2055fc9f..77b9b56e1 100644--- a/src/types/reducers.d.ts+++ b/src/types/reducers.d.ts@@ -499,6 +499,8 @@ export type ExportMap = {JSON: ExportJson;format: 'HTML' | 'JSON';fileName: string;+ /** When false, dataset access tokens are omitted from exported HTML and JSON. */+ includeLayerApiKeys: boolean;};export type ExportVideo = {diff --git a/src/utils/src/export-utils.ts b/src/utils/src/export-utils.tsindex ba2313266..787269ed7 100644--- a/src/utils/src/export-utils.ts+++ b/src/utils/src/export-utils.ts@@ -178,8 +178,63 @@ export function exportToJsonString(data) {}}-export function getMapJSON(state, options = getApplicationConfig().defaultExportJsonSettings) {- const {hasData} = options;+/** Dataset metadata fields that hold a private layer API key. */+const LAYER_API_KEY_METADATA_FIELDS = ['tile3dAccessToken'];++/**+ * Remove access tokens stored on layer datasets. The tileset URL and the rest+ * of the metadata stay so the map can be reopened and a new key entered.+ */+export function omitLayerApiKeys<T>(mapToSave: T): T {+ const saved = mapToSave as {datasets?: Array<{data?: {metadata?: Record<string, unknown>}}>};+ if (!saved || !Array.isArray(saved.datasets)) {+ return mapToSave;+ }++ let changed = false;+ const datasets = saved.datasets.map(dataset => {+ const metadata = dataset?.data?.metadata;+ if (!metadata || typeof metadata !== 'object') {+ return dataset;+ }+ const nextMetadata = {...metadata};+ let metadataChanged = false;+ for (const field of LAYER_API_KEY_METADATA_FIELDS) {+ if (field in nextMetadata) {+ delete nextMetadata[field];+ metadataChanged = true;+ }+ }+ if (!metadataChanged) {+ return dataset;+ }+ changed = true;+ return {+ ...dataset,+ data: {+ ...dataset.data,+ metadata: nextMetadata+ }+ };+ });++ if (!changed) {+ return mapToSave;+ }+ return {...saved, datasets} as T;+}++type MapJsonOptions = {+ hasData?: boolean;+ /** When false, access tokens stored on layer datasets are removed. */+ includeLayerApiKeys?: boolean;+};++export function getMapJSON(+ state,+ options: MapJsonOptions = getApplicationConfig().defaultExportJsonSettings+) {+ const {hasData, includeLayerApiKeys} = options;const schema = state.visState.schema;if (!hasData) {@@ -192,6 +247,9 @@ export function getMapJSON(state, options = getApplicationConfig().defaultExportif (!title || !title.length) {mapToSave = set(['info', 'title'], `keplergl_${generateHashId(6)}`, mapToSave);}+ if (includeLayerApiKeys === false) {+ mapToSave = omitLayerApiKeys(mapToSave);+ }return mapToSave;}@@ -208,10 +266,10 @@ export function exportJson(state, options: any = {}) {}export function exportHtml(state, options) {- const {userMapboxToken, exportMapboxAccessToken, mode} = options;+ const {userMapboxToken, exportMapboxAccessToken, mode, includeLayerApiKeys} = options;const data = {- ...getMapJSON(state),+ ...getMapJSON(state, {hasData: true, includeLayerApiKeys}),mapboxApiAccessToken:(userMapboxToken || '') !== '' ? userMapboxToken : exportMapboxAccessToken,modediff --git a/src/utils/src/index.ts b/src/utils/src/index.tsindex bc461c6fd..5084fc0e7 100644--- a/src/utils/src/index.ts+++ b/src/utils/src/index.ts@@ -98,7 +98,8 @@ export {getExportFileNameBase,getMapJSON,getScaleFromImageSize,- isMSEdge+ isMSEdge,+ omitLayerApiKeys} from './export-utils';export {getFormatValue, getDefaultTimeFormat} from './format';export {getLayerBlendingParameters, patchDeckRendererForPostProcessing} from './gl-utils';diff --git a/test/node/utils/export-utils-test.js b/test/node/utils/export-utils-test.jsindex efb00208b..29c8fd962 100644--- a/test/node/utils/export-utils-test.js+++ b/test/node/utils/export-utils-test.js@@ -11,6 +11,7 @@ import {getScaleFromImageSize,isMSEdge,calculateExportImageSize,+ omitLayerApiKeys,getExportFileName,getExportFileNameBase} from '@kepler.gl/utils';@@ -173,6 +174,65 @@ test('exportUtils -> exportToJsonString', t => {t.end();});+test('exportUtils -> omitLayerApiKeys', t => {+ const saved = {+ datasets: [+ {+ data: {+ id: 'tiles',+ metadata: {+ tile3dUrl: 'https://tile.googleapis.com/v1/3dtiles/root.json',+ tile3dAccessToken: 'secret-key',+ tile3dProvider: 'google'+ }+ }+ },+ {+ data: {+ id: 'points',+ metadata: {source: 'https://example.com/data.geojson'}+ }+ }+ ],+ config: {version: 'v1'}+ };++ const stripped = omitLayerApiKeys(saved);++ t.equal(+ stripped.datasets[0].data.metadata.tile3dAccessToken,+ undefined,+ 'Should drop the tileset access token'+ );+ t.equal(+ stripped.datasets[0].data.metadata.tile3dUrl,+ saved.datasets[0].data.metadata.tile3dUrl,+ 'Should keep the tileset URL'+ );+ t.equal(+ stripped.datasets[0].data.metadata.tile3dProvider,+ 'google',+ 'Should keep the tileset provider'+ );+ t.deepEqual(+ stripped.datasets[1].data.metadata,+ saved.datasets[1].data.metadata,+ 'Should leave datasets without an API key unchanged'+ );+ t.equal(+ saved.datasets[0].data.metadata.tile3dAccessToken,+ 'secret-key',+ 'Should not mutate the original saved map'+ );+ t.deepEqual(+ omitLayerApiKeys({config: {}}),+ {config: {}},+ 'Should return maps without datasets as-is'+ );++ t.end();+});+test('exportUtils -> getExportFileName', t => {t.equal(getExportFileName('', 'kepler.gl.json', 'json'),