Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
[Feat] Load cloud map with provider (#947)
Shan Hec75812d52f56
diff --git a/UPGRADE-GUIDE.md b/UPGRADE-GUIDE.mdindex 1b19d76a8..e8e54a65b 100644--- a/UPGRADE-GUIDE.md+++ b/UPGRADE-GUIDE.md@@ -1,5 +1,9 @@# Upgrade Guide++## Upgrade from v1.1 to v2.0++## Upgrade from v1.1.11 to v1.1.12### Breaking Changesdiff --git a/src/utils/file-utils.js b/cloud-providers.jssimilarity index 78%rename from src/utils/file-utils.jsrename to cloud-providers.jsindex bd047719d..6881c599c 100644--- a/src/utils/file-utils.js+++ b/cloud-providers.js@@ -18,17 +18,4 @@// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN// THE SOFTWARE.-import {generateHashId} from 'utils/utils';-import {getFileHandler} from 'processors/file-handler';--export const processFileToLoad = file => {- return {- fileBlob: file,- info: {- id: generateHashId(4),- label: file.name,- size: file.size- },- handler: getFileHandler(file)- };-};+module.exports = require('./dist/cloud-providers');diff --git a/docs/api-reference/actions/actions.md b/docs/api-reference/actions/actions.mdindex 7e9ff4d5d..5e3326cd1 100644--- a/docs/api-reference/actions/actions.md+++ b/docs/api-reference/actions/actions.md@@ -26,65 +26,65 @@- [visStateActions][42]- [addFilter][43]- [addLayer][45]- - [enlargeFilter][47]- - [interactionConfigChange][49]- - [layerConfigChange][51]- - [layerTextLabelChange][53]- - [layerTypeChange][55]- - [layerVisConfigChange][57]- - [layerVisualChannelConfigChange][59]- - [loadFiles][61]- - [loadFilesErr][63]- - [onLayerClick][65]- - [onLayerHover][67]- - [onMapClick][69]- - [onMouseMove][70]- - [removeDataset][72]- - [removeFilter][74]- - [removeLayer][76]- - [reorderLayer][78]- - [setEditorMode][81]- - [setFilter][84]- - [setFilterPlot][86]- - [showDatasetTable][88]- - [toggleFilterAnimation][90]- - [toggleLayerForMap][92]- - [updateAnimationTime][94]- - [updateFilterAnimationSpeed][96]- - [updateLayerAnimationSpeed][98]- - [updateLayerBlending][100]- - [updateVisData][102]-- [uiStateActions][104]- - [addNotification][105]- - [cleanupExportImage][107]- - [hideExportDropdown][108]- - [openDeleteModal][109]- - [removeNotification][111]- - [setExportData][113]- - [setExportDataType][114]- - [setExportFiltered][116]- - [setExportImageDataUri][118]- - [setExportSelectedDataset][120]- - [setRatio][122]- - [setResolution][124]- - [setUserMapboxAccessToken][126]- - [showExportDropdown][128]- - [startExportingImage][130]- - [toggleLegend][131]- - [toggleMapControl][132]- - [toggleModal][134]- - [toggleSidePanel][136]-- [rootActions][138]- - [deleteEntry][139]- - [registerEntry][141]- - [renameEntry][143]-- [mapStateActions][145]- - [fitBounds][146]- - [togglePerspective][149]- - [toggleSplitMap][151]- - [updateMap][154]-- [layerColorUIChange][157]-- [setExportMapFormat][159]+ - [applyCPUFilter][47]+ - [enlargeFilter][49]+ - [interactionConfigChange][51]+ - [layerConfigChange][53]+ - [layerTextLabelChange][55]+ - [layerTypeChange][57]+ - [layerVisConfigChange][59]+ - [layerVisualChannelConfigChange][61]+ - [loadFiles][63]+ - [loadFilesErr][65]+ - [onLayerClick][67]+ - [onLayerHover][69]+ - [onMapClick][71]+ - [onMouseMove][72]+ - [removeDataset][74]+ - [removeFilter][76]+ - [removeLayer][78]+ - [reorderLayer][80]+ - [setEditorMode][83]+ - [setFilter][86]+ - [setFilterPlot][88]+ - [setMapInfo][90]+ - [showDatasetTable][92]+ - [toggleFilterAnimation][94]+ - [toggleLayerForMap][96]+ - [updateAnimationTime][98]+ - [updateFilterAnimationSpeed][100]+ - [updateLayerAnimationSpeed][102]+ - [updateLayerBlending][104]+ - [updateVisData][106]+- [uiStateActions][108]+ - [addNotification][109]+ - [cleanupExportImage][111]+ - [hideExportDropdown][112]+ - [openDeleteModal][113]+ - [removeNotification][115]+ - [setExportData][117]+ - [setExportDataType][118]+ - [setExportFiltered][120]+ - [setExportImageDataUri][122]+ - [setExportImageSetting][124]+ - [setExportSelectedDataset][126]+ - [setUserMapboxAccessToken][128]+ - [showExportDropdown][130]+ - [startExportingImage][132]+ - [toggleMapControl][133]+ - [toggleModal][135]+ - [toggleSidePanel][137]+- [rootActions][139]+ - [deleteEntry][140]+ - [registerEntry][142]+ - [renameEntry][144]+- [mapStateActions][146]+ - [fitBounds][147]+ - [togglePerspective][150]+ - [toggleSplitMap][152]+ - [updateMap][155]+- [layerColorUIChange][158]+- [setExportMapFormat][160]## forwardActions@@ -96,8 +96,8 @@ Returns an action dispatcher that wraps and forwards the actions to a specific i**Parameters**-- `id` **[string][161]** instance id-- `dispatch` **[Function][162]** action dispatcher+- `id` **[string][162]** instance id+- `dispatch` **[Function][163]** action dispatcher**Examples**@@ -129,9 +129,9 @@ Whether an action is a forward action**Parameters**-- `action` **[Object][163]** the action object+- `action` **[Object][164]** the action object-Returns **[boolean][164]** boolean - whether the action is a forward action+Returns **[boolean][165]** boolean - whether the action is a forward action### unwrap@@ -139,9 +139,9 @@ Unwrap an action**Parameters**-- `action` **[Object][163]** the action object+- `action` **[Object][164]** the action object-Returns **[Object][163]** unwrapped action+Returns **[Object][164]** unwrapped action### wrapTo@@ -174,8 +174,8 @@ A forward action looks like this**Parameters**-- `id` **[string][161]** The id to forward to-- `action` **[Object][163]** the action object {type: string, payload: \*}+- `id` **[string][162]** The id to forward to+- `action` **[Object][164]** the action object {type: string, payload: \*}**Examples**@@ -194,7 +194,7 @@ this.props.dispatch(wrapToMap1(togglePerspective()));Kepler.gl action types, can be listened by reducers to perform additional tasks whenever an action is called in kepler.gl-Type: [Object][163]+Type: [Object][164]**Examples**@@ -237,38 +237,38 @@ It should not be called from outside kepler.gl without a valid `inputStyle` in tparam {void}- **ActionTypes**: [`ActionTypes.ADD_CUSTOM_MAP_STYLE`][12]-- **Updaters**: [`mapStyleUpdaters.addCustomMapStyleUpdater`][165]+- **Updaters**: [`mapStyleUpdaters.addCustomMapStyleUpdater`][166]### inputMapStyleInput a custom map style object- **ActionTypes**: [`ActionTypes.INPUT_MAP_STYLE`][12]-- **Updaters**: [`mapStyleUpdaters.inputMapStyleUpdater`][166]+- **Updaters**: [`mapStyleUpdaters.inputMapStyleUpdater`][167]**Parameters**-- `inputStyle` **[Object][163]**- - `inputStyle.url` **[string][161]** style url e.g. `'mapbox://styles/heshan/xxxxxyyyyzzz'`- - `inputStyle.id` **[string][161]** style url e.g. `'custom_style_1'`- - `inputStyle.style` **[Object][163]** actual mapbox style json- - `inputStyle.name` **[string][161]** style name- - `inputStyle.layerGroups` **[Object][163]** layer groups that can be used to set map layer visibility- - `inputStyle.icon` **[Object][163]** icon image data url-- `mapState` **[Object][163]** mapState is optional+- `inputStyle` **[Object][164]**+ - `inputStyle.url` **[string][162]** style url e.g. `'mapbox://styles/heshan/xxxxxyyyyzzz'`+ - `inputStyle.id` **[string][162]** style url e.g. `'custom_style_1'`+ - `inputStyle.style` **[Object][164]** actual mapbox style json+ - `inputStyle.name` **[string][162]** style name+ - `inputStyle.layerGroups` **[Object][164]** layer groups that can be used to set map layer visibility+ - `inputStyle.icon` **[Object][164]** icon image data url+- `mapState` **[Object][164]** mapState is optional### loadCustomMapStyleCallback when a custom map style object is received- **ActionTypes**: [`ActionTypes.LOAD_CUSTOM_MAP_STYLE`][12]-- **Updaters**: [`mapStyleUpdaters.loadCustomMapStyleUpdater`][167]+- **Updaters**: [`mapStyleUpdaters.loadCustomMapStyleUpdater`][168]**Parameters**-- `customMapStyle` **[Object][163]**- - `customMapStyle.icon` **[string][161]**- - `customMapStyle.style` **[Object][163]**+- `customMapStyle` **[Object][164]**+ - `customMapStyle.icon` **[string][162]**+ - `customMapStyle.style` **[Object][164]**- `customMapStyle.error` **any**### loadMapStyleErr@@ -276,7 +276,7 @@ Callback when a custom map style object is receivedCallback when load map style error- **ActionTypes**: [`ActionTypes.LOAD_MAP_STYLE_ERR`][12]-- **Updaters**: [`mapStyleUpdaters.loadMapStyleErrUpdater`][168]+- **Updaters**: [`mapStyleUpdaters.loadMapStyleErrUpdater`][169]**Parameters**@@ -287,55 +287,55 @@ Callback when load map style errorCallback when load map style success- **ActionTypes**: [`ActionTypes.LOAD_MAP_STYLES`][12]-- **Updaters**: [`mapStyleUpdaters.loadMapStylesUpdater`][169]+- **Updaters**: [`mapStyleUpdaters.loadMapStylesUpdater`][170]**Parameters**-- `newStyles` **[Object][163]** a `{[id]: style}` mapping+- `newStyles` **[Object][164]** a `{[id]: style}` mapping### mapConfigChangeUpdate `visibleLayerGroups`to change layer group visibility- **ActionTypes**: [`ActionTypes.MAP_CONFIG_CHANGE`][12]-- **Updaters**: [`mapStyleUpdaters.mapConfigChangeUpdater`][170]+- **Updaters**: [`mapStyleUpdaters.mapConfigChangeUpdater`][171]**Parameters**-- `mapStyle` **[Object][163]** new config `{visibleLayerGroups: {label: false, road: true, background: true}}`+- `mapStyle` **[Object][164]** new config `{visibleLayerGroups: {label: false, road: true, background: true}}`### mapStyleChangeChange to another map style. The selected style should already been loaded into `mapStyle.mapStyles`- **ActionTypes**: [`ActionTypes.MAP_STYLE_CHANGE`][12]-- **Updaters**: [`mapStyleUpdaters.mapStyleChangeUpdater`][171]+- **Updaters**: [`mapStyleUpdaters.mapStyleChangeUpdater`][172]**Parameters**-- `styleType` **[string][161]** the style to change to+- `styleType` **[string][162]** the style to change to### requestMapStylesRequest map style style object based on style.url.- **ActionTypes**: [`ActionTypes.REQUEST_MAP_STYLES`][12]-- **Updaters**: [`mapStyleUpdaters.requestMapStylesUpdater`][172]+- **Updaters**: [`mapStyleUpdaters.requestMapStylesUpdater`][173]**Parameters**-- `mapStyles` **[Array][173]<[Object][163]>**+- `mapStyles` **[Array][174]<[Object][164]>**### set3dBuildingColorSet 3d building layer group color- **ActionTypes**: [`ActionTypes.SET_3D_BUILDING_COLOR`][12]-- **Updaters**: [`mapStyleUpdaters.set3dBuildingColorUpdater`][174]+- **Updaters**: [`mapStyleUpdaters.set3dBuildingColorUpdater`][175]**Parameters**-- `color` **[Array][173]** [r, g, b]+- `color` **[Array][174]** [r, g, b]## main@@ -345,7 +345,7 @@ is listened by all subreducers,### addDataToMapAdd data to kepler.gl reducer, prepare map with preset configuration if config is passed.-Kepler.gl provides a handy set of utils to parse data from different format to the `data` object required in dataset. You rarely need to manually format the data obejct.+Kepler.gl provides a handy set of utils to parse data from different formats to the `data` object required in dataset. You rarely need to manually format the data obejct.Use `KeplerGlSchema.getConfigToSave` to generate a json blob of the currents instance config.The config object value will always have higher precedence than the options properties.@@ -354,27 +354,27 @@ Kepler.gl uses `dataId` in the config to match with loaded dataset. If you passto match the `info.id` of your dataset to the `dataId` in each `layer`, `filter` and `interactionConfig.tooltips.fieldsToShow`- **ActionTypes**: [`ActionTypes.ADD_DATA_TO_MAP`][12]-- **Updaters**: [`combinedUpdaters.addDataToMapUpdater`][175]+- **Updaters**: [`combinedUpdaters.addDataToMapUpdater`][176]**Parameters**-- `data` **[Object][163]**- - `data.datasets` **([Array][173]<[Object][163]> | [Object][163])** **\*required** datasets can be a dataset or an array of datasets+- `data` **[Object][164]**+ - `data.datasets` **([Array][174]<[Object][164]> | [Object][164])** **\*required** datasets can be a dataset or an array of datasetsEach dataset object needs to have `info` and `data` property.- - `data.datasets.info` **[Object][163]** \-info of a dataset- - `data.datasets.info.id` **[string][161]** id of this dataset. If config is defined, `id` should matches the `dataId` in config.- - `data.datasets.info.label` **[string][161]** A display name of this dataset- - `data.datasets.data` **[Object][163]** **\*required** The data object, in a tabular format with 2 properties `fields` and `rows`- - `data.datasets.data.fields` **[Array][173]<[Object][163]>** **\*required** Array of fields,- - `data.datasets.data.fields.name` **[string][161]** **\*required** Name of the field,- - `data.datasets.data.rows` **[Array][173]<[Array][173]>** **\*required** Array of rows, in a tabular format with `fields` and `rows`- - `data.options` **[Object][163]**- - `data.options.centerMap` **[boolean][164]** `default: true` if `centerMap` is set to `true` kepler.gl will+ - `data.datasets.info` **[Object][164]** \-info of a dataset+ - `data.datasets.info.id` **[string][162]** id of this dataset. If config is defined, `id` should matches the `dataId` in config.+ - `data.datasets.info.label` **[string][162]** A display name of this dataset+ - `data.datasets.data` **[Object][164]** **\*required** The data object, in a tabular format with 2 properties `fields` and `rows`+ - `data.datasets.data.fields` **[Array][174]<[Object][164]>** **\*required** Array of fields,+ - `data.datasets.data.fields.name` **[string][162]** **\*required** Name of the field,+ - `data.datasets.data.rows` **[Array][174]<[Array][174]>** **\*required** Array of rows, in a tabular format with `fields` and `rows`+ - `data.options` **[Object][164]**+ - `data.options.centerMap` **[boolean][165]** `default: true` if `centerMap` is set to `true` kepler.gl willplace the map view within the data points boundaries. `options.centerMap` will override `config.mapState` if passed in.- - `data.options.readOnly` **[boolean][164]** `default: false` if `readOnly` is set to `true`+ - `data.options.readOnly` **[boolean][165]** `default: false` if `readOnly` is set to `true`the left setting panel will be hidden- - `data.options.keepExistingConfig` **[boolean][164]** whether to keep exiting map data and associated layer filter interaction config `default: false`.- - `data.config` **[Object][163]** this object will contain the full kepler.gl instance configuration {mapState, mapStyle, visState}+ - `data.options.keepExistingConfig` **[boolean][165]** whether to keep exiting map data and associated layer filter interaction config `default: false`.+ - `data.config` **[Object][164]** this object will contain the full kepler.gl instance configuration {mapState, mapStyle, visState}**Examples**@@ -423,6 +423,10 @@ this.props.dispatch(readOnly: false,keepExistingConfig: false},+ info: {+ title: 'Taro and Blue',+ description: 'This is my map'+ }config: sampleConfig}));@@ -433,14 +437,14 @@ this.props.dispatch(Initialize kepler.gl reducer. It is used to pass in `mapboxApiAccessToken` to `mapStyle` reducer.- **ActionTypes**: [`ActionTypes.INIT`][12]-- **Updaters**: [`mapStyleUpdaters.initMapStyleUpdater`][176]+- **Updaters**: [`mapStyleUpdaters.initMapStyleUpdater`][177]**Parameters**-- `payload` **[Object][163]**- - `payload.mapboxApiAccessToken` **[string][161]** mapboxApiAccessToken to be saved to mapStyle reducer- - `payload.mapboxApiUrl` **[string][161]** mapboxApiUrl to be saved to mapStyle reducer.- - `payload.mapStylesReplaceDefault` **[Boolean][164]** mapStylesReplaceDefault to be saved to mapStyle reducer+- `payload` **[Object][164]**+ - `payload.mapboxApiAccessToken` **[string][162]** mapboxApiAccessToken to be saved to mapStyle reducer+ - `payload.mapboxApiUrl` **[string][162]** mapboxApiUrl to be saved to mapStyle reducer.+ - `payload.mapStylesReplaceDefault` **[Boolean][165]** mapStylesReplaceDefault to be saved to mapStyle reducer### receiveMapConfig@@ -456,17 +460,17 @@ It is also useful when you want to prepare the kepler.gl instance with some presIt will reset current configuration first then apply config to it.- **ActionTypes**: [`ActionTypes.RECEIVE_MAP_CONFIG`][12]-- **Updaters**: [`mapStateUpdaters.receiveMapConfigUpdater`][177], [`mapStyleUpdaters.receiveMapConfigUpdater`][178], [`visStateUpdaters.receiveMapConfigUpdater`][179]+- **Updaters**: [`mapStateUpdaters.receiveMapConfigUpdater`][178], [`mapStyleUpdaters.receiveMapConfigUpdater`][179], [`visStateUpdaters.receiveMapConfigUpdater`][180]**Parameters**-- `config` **[Object][163]** **\*required** The Config Object-- `options` **[Object][163]** **\*optional** The Option object- - `options.centerMap` **[boolean][164]** `default: true` if `centerMap` is set to `true` kepler.gl will+- `config` **[Object][164]** **\*required** The Config Object+- `options` **[Object][164]** **\*optional** The Option object+ - `options.centerMap` **[boolean][165]** `default: true` if `centerMap` is set to `true` kepler.gl willplace the map view within the data points boundaries- - `options.readOnly` **[boolean][164]** `default: false` if `readOnly` is set to `true`+ - `options.readOnly` **[boolean][165]** `default: false` if `readOnly` is set to `true`the left setting panel will be hidden- - `options.keepExistingConfig` **[boolean][164]** whether to keep exiting layer filter and interaction config `default: false`.+ - `options.keepExistingConfig` **[boolean][165]** whether to keep exiting layer filter and interaction config `default: false`.**Examples**@@ -483,7 +487,7 @@ this.props.dispatch(receiveMapConfig(parsedConfig));Reset all sub-reducers to its initial state. This can be used to clear out all configuration in the reducer.- **ActionTypes**: [`ActionTypes.RESET_MAP_CONFIG`][12]-- **Updaters**: [`mapStateUpdaters.resetMapConfigUpdater`][180], [`mapStyleUpdaters.resetMapConfigMapStyleUpdater`][181], [`mapStyleUpdaters.resetMapConfigMapStyleUpdater`][181], [`visStateUpdaters.resetMapConfigUpdater`][182]+- **Updaters**: [`mapStateUpdaters.resetMapConfigUpdater`][181], [`mapStyleUpdaters.resetMapConfigMapStyleUpdater`][182], [`mapStyleUpdaters.resetMapConfigMapStyleUpdater`][182], [`visStateUpdaters.resetMapConfigUpdater`][183]## visStateActions@@ -496,11 +500,11 @@ filters and interaction settings.Add a new filter- **ActionTypes**: [`ActionTypes.ADD_FILTER`][12]-- **Updaters**: [`visStateUpdaters.addFilterUpdater`][183]+- **Updaters**: [`visStateUpdaters.addFilterUpdater`][184]**Parameters**-- `dataId` **[string][161]** dataset `id` this new filter is associated with+- `dataId` **[string][162]** dataset `id` this new filter is associated withReturns **{type: ActionTypes.ADD_FILTER, dataId: dataId}**@@ -509,24 +513,37 @@ Returns **{type: ActionTypes.ADD_FILTER, dataId: dataId}**Add a new layer- **ActionTypes**: [`ActionTypes.ADD_LAYER`][12]-- **Updaters**: [`visStateUpdaters.addLayerUpdater`][184]+- **Updaters**: [`visStateUpdaters.addLayerUpdater`][185]**Parameters**-- `props` **[Object][163]** new layer props+- `props` **[Object][164]** new layer propsReturns **{type: ActionTypes.ADD_LAYER, props: props}**+### applyCPUFilter++Trigger CPU filter of selected dataset++- **ActionTypes**: [`ActionTypes.APPLY_CPU_FILTER`][12]+- **Updaters**: [`visStateUpdaters.applyCPUFilterUpdater`][186]++**Parameters**++- `dataId` **([string][162] | Arrary<[string][162]>)** single dataId or an array of dataIds++Returns **{type: ActionTypes.APPLY_CPU_FILTER, dataId: [string][162]}**+### enlargeFilterShow larger time filter at bottom for time playback (apply to time filter only)- **ActionTypes**: [`ActionTypes.ENLARGE_FILTER`][12]-- **Updaters**: [`visStateUpdaters.enlargeFilterUpdater`][185]+- **Updaters**: [`visStateUpdaters.enlargeFilterUpdater`][187]**Parameters**-- `idx` **[Number][186]** index of filter to enlarge+- `idx` **[Number][188]** index of filter to enlargeReturns **{type: ActionTypes.ENLARGE_FILTER, idx: idx}**@@ -535,11 +552,11 @@ Returns **{type: ActionTypes.ENLARGE_FILTER, idx: idx}**Update `interactionConfig`- **ActionTypes**: [`ActionTypes.INTERACTION_CONFIG_CHANGE`][12]-- **Updaters**: [`visStateUpdaters.interactionConfigChangeUpdater`][187]+- **Updaters**: [`visStateUpdaters.interactionConfigChangeUpdater`][189]**Parameters**-- `config` **[Object][163]** new config as key value map: `{tooltip: {enabled: true}}`+- `config` **[Object][164]** new config as key value map: `{tooltip: {enabled: true}}`Returns **{type: ActionTypes.INTERACTION_CONFIG_CHANGE, config: config}**@@ -548,12 +565,12 @@ Returns **{type: ActionTypes.INTERACTION_CONFIG_CHANGE, config: config}**Update layer base config: dataId, label, column, isVisible- **ActionTypes**: [`ActionTypes.LAYER_CONFIG_CHANGE`][12]-- **Updaters**: [`visStateUpdaters.layerConfigChangeUpdater`][188]+- **Updaters**: [`visStateUpdaters.layerConfigChangeUpdater`][190]**Parameters**-- `oldLayer` **[Object][163]** layer to be updated-- `newConfig` **[Object][163]** new config+- `oldLayer` **[Object][164]** layer to be updated+- `newConfig` **[Object][164]** new configReturns **{type: ActionTypes.LAYER_CONFIG_CHANGE, oldLayer: oldLayer, newConfig: newConfig}**@@ -562,13 +579,13 @@ Returns **{type: ActionTypes.LAYER_CONFIG_CHANGE, oldLayer: oldLayer, newConfig:Update layer text label- **ActionTypes**: [`ActionTypes.LAYER_TEXT_LABEL_CHANGE`][12]-- **Updaters**: [`visStateUpdaters.layerTextLabelChangeUpdater`][189]+- **Updaters**: [`visStateUpdaters.layerTextLabelChangeUpdater`][191]**Parameters**-- `oldLayer` **[Object][163]** layer to be updated-- `idx` **[Number][186]** \-`idx` of text label to be updated-- `prop` **[string][161]** `prop` of text label, e,g, `anchor`, `alignment`, `color`, `size`, `field`+- `oldLayer` **[Object][164]** layer to be updated+- `idx` **[Number][188]** \-`idx` of text label to be updated+- `prop` **[string][162]** `prop` of text label, e,g, `anchor`, `alignment`, `color`, `size`, `field`- `value` **any** new value### layerTypeChange@@ -576,12 +593,12 @@ Update layer text labelUpdate layer type. Previews layer config will be copied if applicable.- **ActionTypes**: [`ActionTypes.LAYER_TYPE_CHANGE`][12]-- **Updaters**: [`visStateUpdaters.layerTypeChangeUpdater`][190]+- **Updaters**: [`visStateUpdaters.layerTypeChangeUpdater`][192]**Parameters**-- `oldLayer` **[Object][163]** layer to be updated-- `newType` **[string][161]** new type+- `oldLayer` **[Object][164]** layer to be updated+- `newType` **[string][162]** new typeReturns **{type: ActionTypes.LAYER_TYPE_CHANGE, oldLayer: oldLayer, newType: newType}**@@ -590,12 +607,12 @@ Returns **{type: ActionTypes.LAYER_TYPE_CHANGE, oldLayer: oldLayer, newType: newUpdate layer `visConfig`- **ActionTypes**: [`ActionTypes.LAYER_VIS_CONFIG_CHANGE`][12]-- **Updaters**: [`visStateUpdaters.layerVisConfigChangeUpdater`][191]+- **Updaters**: [`visStateUpdaters.layerVisConfigChangeUpdater`][193]**Parameters**-- `oldLayer` **[Object][163]** layer to be updated-- `newVisConfig` **[Object][163]** new visConfig as a key value map: e.g. `{opacity: 0.8}`+- `oldLayer` **[Object][164]** layer to be updated+- `newVisConfig` **[Object][164]** new visConfig as a key value map: e.g. `{opacity: 0.8}`Returns **{type: ActionTypes.LAYER_VIS_CONFIG_CHANGE, oldLayer: oldLayer, newVisConfig: newVisConfig}**@@ -604,13 +621,13 @@ Returns **{type: ActionTypes.LAYER_VIS_CONFIG_CHANGE, oldLayer: oldLayer, newVisUpdate layer visual channel- **ActionTypes**: [`ActionTypes.LAYER_VISUAL_CHANNEL_CHANGE`][12]-- **Updaters**: [`visStateUpdaters.layerVisualChannelChangeUpdater`][192]+- **Updaters**: [`visStateUpdaters.layerVisualChannelChangeUpdater`][194]**Parameters**-- `oldLayer` **[Object][163]** layer to be updated-- `newConfig` **[Object][163]** new visual channel config-- `channel` **[string][161]** channel to be updated+- `oldLayer` **[Object][164]** layer to be updated+- `newConfig` **[Object][164]** new visual channel config+- `channel` **[string][162]** channel to be updatedReturns **{type: ActionTypes.LAYER_VISUAL_CHANNEL_CHANGE, oldLayer: oldLayer, newConfig: newConfig, channel: channel}**@@ -619,11 +636,11 @@ Returns **{type: ActionTypes.LAYER_VISUAL_CHANNEL_CHANGE, oldLayer: oldLayer, neTrigger file loading dispatch `addDataToMap` if succeed, or `loadFilesErr` if failed- **ActionTypes**: [`ActionTypes.LOAD_FILES`][12]-- **Updaters**: [`uiStateUpdaters.loadFilesUpdater`][193], [`visStateUpdaters.loadFilesUpdater`][194]+- **Updaters**: [`uiStateUpdaters.loadFilesUpdater`][195], [`visStateUpdaters.loadFilesUpdater`][196]**Parameters**-- `files` **[Array][173]<[Object][163]>** array of fileblob+- `files` **[Array][174]<[Object][164]>** array of fileblobReturns **{type: ActionTypes.LOAD_FILES, files: any}**@@ -632,24 +649,24 @@ Returns **{type: ActionTypes.LOAD_FILES, files: any}**Trigger loading file error- **ActionTypes**: [`ActionTypes.LOAD_FILES_ERR`][12]-- **Updaters**: [`uiStateUpdaters.loadFilesErrUpdater`][195], [`visStateUpdaters.loadFilesErrUpdater`][196]+- **Updaters**: [`uiStateUpdaters.loadFilesErrUpdater`][197], [`visStateUpdaters.loadFilesErrUpdater`][198]**Parameters**- `error` **any**-Returns **{type: ActionTypes.LOAD_FILES_ERR, error: [Object][163]}**+Returns **{type: ActionTypes.LOAD_FILES_ERR, error: [Object][164]}**### onLayerClickTrigger layer click event with clicked object- **ActionTypes**: [`ActionTypes.LAYER_CLICK`][12]-- **Updaters**: [`visStateUpdaters.layerClickUpdater`][197]+- **Updaters**: [`visStateUpdaters.layerClickUpdater`][199]**Parameters**-- `info` **[Object][163]** Object clicked, returned by deck.gl+- `info` **[Object][164]** Object clicked, returned by deck.glReturns **{type: ActionTypes.LAYER_CLICK, info: info}**@@ -658,11 +675,11 @@ Returns **{type: ActionTypes.LAYER_CLICK, info: info}**Trigger layer hover event with hovered object- **ActionTypes**: [`ActionTypes.LAYER_HOVER`][12]-- **Updaters**: [`visStateUpdaters.layerHoverUpdater`][198]+- **Updaters**: [`visStateUpdaters.layerHoverUpdater`][200]**Parameters**-- `info` **[Object][163]** Object hovered, returned by deck.gl+- `info` **[Object][164]** Object hovered, returned by deck.glReturns **{type: ActionTypes.LAYER_HOVER, info: info}**@@ -671,7 +688,7 @@ Returns **{type: ActionTypes.LAYER_HOVER, info: info}**Trigger map click event, unselect clicked object- **ActionTypes**: [`ActionTypes.MAP_CLICK`][12]-- **Updaters**: [`visStateUpdaters.mapClickUpdater`][199]+- **Updaters**: [`visStateUpdaters.mapClickUpdater`][201]Returns **{type: ActionTypes.MAP_CLICK}**@@ -679,14 +696,14 @@ Returns **{type: ActionTypes.MAP_CLICK}**Trigger map mouse moveevent, payload would beReact-map-gl PointerEvent-[https://uber.github.io/react-map-gl/#/documentation/api-reference/pointer-event][200]+[https://uber.github.io/react-map-gl/#/documentation/api-reference/pointer-event][202]- **ActionTypes**: [`ActionTypes.MOUSE_MOVE`][12]-- **Updaters**: [`visStateUpdaters.mouseMoveUpdater`][201]+- **Updaters**: [`visStateUpdaters.mouseMoveUpdater`][203]**Parameters**-- `evt` **[Object][163]** PointerEvent+- `evt` **[Object][164]** PointerEventReturns **{type: ActionTypes.MAP_CLICK}**@@ -695,11 +712,11 @@ Returns **{type: ActionTypes.MAP_CLICK}**Remove a dataset and all layers, filters, tooltip configs that based on it- **ActionTypes**: [`ActionTypes.REMOVE_DATASET`][12]-- **Updaters**: [`visStateUpdaters.removeDatasetUpdater`][202]+- **Updaters**: [`visStateUpdaters.removeDatasetUpdater`][204]**Parameters**-- `key` **[string][161]** dataset id+- `key` **[string][162]** dataset idReturns **{type: ActionTypes.REMOVE_DATASET, key: key}**@@ -708,11 +725,11 @@ Returns **{type: ActionTypes.REMOVE_DATASET, key: key}**Remove a filter from `visState.filters`, once a filter is removed, data will be re-filtered and layer will be updated- **ActionTypes**: [`ActionTypes.REMOVE_FILTER`][12]-- **Updaters**: [`visStateUpdaters.removeFilterUpdater`][203]+- **Updaters**: [`visStateUpdaters.removeFilterUpdater`][205]**Parameters**-- `idx` **[Number][186]** idx of filter to be removed+- `idx` **[Number][188]** idx of filter to be removedReturns **{type: ActionTypes.REMOVE_FILTER, idx: idx}**@@ -721,11 +738,11 @@ Returns **{type: ActionTypes.REMOVE_FILTER, idx: idx}**Remove a layer- **ActionTypes**: [`ActionTypes.REMOVE_LAYER`][12]-- **Updaters**: [`visStateUpdaters.removeLayerUpdater`][204]+- **Updaters**: [`visStateUpdaters.removeLayerUpdater`][206]**Parameters**-- `idx` **[Number][186]** idx of layer to be removed+- `idx` **[Number][188]** idx of layer to be removedReturns **{type: ActionTypes.REMOVE_LAYER, idx: idx}**@@ -734,11 +751,11 @@ Returns **{type: ActionTypes.REMOVE_LAYER, idx: idx}**Reorder layer, order is an array of layer indexes, index 0 will be the one at the bottom- **ActionTypes**: [`ActionTypes.REORDER_LAYER`][12]-- **Updaters**: [`visStateUpdaters.reorderLayerUpdater`][205]+- **Updaters**: [`visStateUpdaters.reorderLayerUpdater`][207]**Parameters**-- `order` **[Array][173]<[Number][186]>** an array of layer indexes+- `order` **[Array][174]<[Number][188]>** an array of layer indexes**Examples**@@ -755,11 +772,11 @@ Returns **{type: ActionTypes.REORDER_LAYER, order: order}**Set the map mode- **ActionTypes**: [`ActionTypes.SET_EDITOR_MODE`][12]-- **Updaters**: [`visStateUpdaters.setEditorModeUpdater`][206]+- **Updaters**: [`visStateUpdaters.setEditorModeUpdater`][208]**Parameters**-- `mode` **[string][161]** one of EDITOR_MODES+- `mode` **[string][162]** one of EDITOR_MODES**Examples**@@ -775,14 +792,14 @@ this.props.dispatch(setMapMode(EDITOR_MODES.DRAW_POLYGON));Update filter property- **ActionTypes**: [`ActionTypes.SET_FILTER`][12]-- **Updaters**: [`visStateUpdaters.setFilterUpdater`][207]+- **Updaters**: [`visStateUpdaters.setFilterUpdater`][209]**Parameters**-- `idx` **[Number][186]** \-`idx` of filter to be updated-- `prop` **[string][161]** `prop` of filter, e,g, `dataId`, `name`, `value`+- `idx` **[Number][188]** \-`idx` of filter to be updated+- `prop` **[string][162]** `prop` of filter, e,g, `dataId`, `name`, `value`- `value` **any** new value-- `valueIndex` **[Number][186]** array properties like dataset require index in order to improve performance+- `valueIndex` **[Number][188]** array properties like dataset require index in order to improve performanceReturns **{type: ActionTypes.SET_FILTER, idx: idx, prop: prop, value: value}**@@ -791,12 +808,27 @@ Returns **{type: ActionTypes.SET_FILTER, idx: idx, prop: prop, value: value}**Set the property of a filter plot- **ActionTypes**: [`ActionTypes.SET_FILTER_PLOT`][12]-- **Updaters**: [`visStateUpdaters.setFilterPlotUpdater`][208]+- **Updaters**: [`visStateUpdaters.setFilterPlotUpdater`][210]++**Parameters**++- `idx` **[Number][188]**+- `newProp` **[Object][164]** key value mapping of new prop `{yAxis: 'histogram'}`++Returns **{type: ActionTypes.SET_FILTER_PLOT, idx: any, newProp: any}**++### setMapInfo++Set the property of a filter plot++- **ActionTypes**: [`ActionTypes.SET_MAP_INFO`][12]+- **Updaters**: [`visStateUpdaters.setMapInfoUpdater`][211]**Parameters**-- `idx` **[Number][186]**-- `newProp` **[Object][163]** key value mapping of new prop `{yAxis: 'histogram'}`+- `info`+- `idx` **[Number][188]**+- `newProp` **[Object][164]** key value mapping of new prop `{yAxis: 'histogram'}`Returns **{type: ActionTypes.SET_FILTER_PLOT, idx: any, newProp: any}**@@ -805,11 +837,11 @@ Returns **{type: ActionTypes.SET_FILTER_PLOT, idx: any, newProp: any}**Display dataset table in a modal- **ActionTypes**: [`ActionTypes.SHOW_DATASET_TABLE`][12]-- **Updaters**: [`visStateUpdaters.showDatasetTableUpdater`][209]+- **Updaters**: [`visStateUpdaters.showDatasetTableUpdater`][212]**Parameters**-- `dataId` **[string][161]** dataset id to show in table+- `dataId` **[string][162]** dataset id to show in tableReturns **{type: ActionTypes.SHOW_DATASET_TABLE, dataId: dataId}**@@ -818,11 +850,11 @@ Returns **{type: ActionTypes.SHOW_DATASET_TABLE, dataId: dataId}**Start and end filter animation- **ActionTypes**: [`ActionTypes.TOGGLE_FILTER_ANIMATION`][12]-- **Updaters**: [`visStateUpdaters.toggleFilterAnimationUpdater`][210]+- **Updaters**: [`visStateUpdaters.toggleFilterAnimationUpdater`][213]**Parameters**-- `idx` **[Number][186]** idx of filter+- `idx` **[Number][188]** idx of filterReturns **{type: ActionTypes.TOGGLE_FILTER_ANIMATION, idx: idx}**@@ -831,12 +863,12 @@ Returns **{type: ActionTypes.TOGGLE_FILTER_ANIMATION, idx: idx}**Toggle visibility of a layer in a split map- **ActionTypes**: [`ActionTypes.TOGGLE_LAYER_FOR_MAP`][12]-- **Updaters**: [`visStateUpdaters.toggleLayerForMapUpdater`][211]+- **Updaters**: [`visStateUpdaters.toggleLayerForMapUpdater`][214]**Parameters**-- `mapIndex` **[Number][186]** index of the split map-- `layerId` **[string][161]** id of the layer+- `mapIndex` **[Number][188]** index of the split map+- `layerId` **[string][162]** id of the layerReturns **{type: ActionTypes.TOGGLE_LAYER_FOR_MAP, mapIndex: any, layerId: any}**@@ -845,11 +877,11 @@ Returns **{type: ActionTypes.TOGGLE_LAYER_FOR_MAP, mapIndex: any, layerId: any}*Reset animation- **ActionTypes**: [`ActionTypes.UPDATE_ANIMATION_TIME`][12]-- **Updaters**: [`visStateUpdaters.updateAnimationTimeUpdater`][212]+- **Updaters**: [`visStateUpdaters.updateAnimationTimeUpdater`][215]**Parameters**-- `value` **[Number][186]** Current value of the slider+- `value` **[Number][188]** Current value of the sliderReturns **{type: ActionTypes.UPDATE_ANIMATION_TIME, value: value}**@@ -858,12 +890,12 @@ Returns **{type: ActionTypes.UPDATE_ANIMATION_TIME, value: value}**Change filter animation speed- **ActionTypes**: [`ActionTypes.UPDATE_FILTER_ANIMATION_SPEED`][12]-- **Updaters**: [`visStateUpdaters.updateFilterAnimationSpeedUpdater`][213]+- **Updaters**: [`visStateUpdaters.updateFilterAnimationSpeedUpdater`][216]**Parameters**-- `idx` **[Number][186]** `idx` of filter-- `speed` **[Number][186]** `speed` to change it to. `speed` is a multiplier+- `idx` **[Number][188]** `idx` of filter+- `speed` **[Number][188]** `speed` to change it to. `speed` is a multiplierReturns **{type: ActionTypes.UPDATE_FILTER_ANIMATION_SPEED, idx: idx, speed: speed}**@@ -872,11 +904,11 @@ Returns **{type: ActionTypes.UPDATE_FILTER_ANIMATION_SPEED, idx: idx, speed: speupdate trip layer animation speed- **ActionTypes**: [`ActionTypes.UPDATE_LAYER_ANIMATION_SPEED`][12]-- **Updaters**: [`visStateUpdaters.updateLayerAnimationSpeedUpdater`][214]+- **Updaters**: [`visStateUpdaters.updateLayerAnimationSpeedUpdater`][217]**Parameters**-- `speed` **[Number][186]** `speed` to change it to. `speed` is a multiplier+- `speed` **[Number][188]** `speed` to change it to. `speed` is a multiplierReturns **{type: ActionTypes.UPDATE_LAYER_ANIMATION_SPEED, speed: speed}**@@ -885,11 +917,11 @@ Returns **{type: ActionTypes.UPDATE_LAYER_ANIMATION_SPEED, speed: speed}**Update layer blending mode- **ActionTypes**: [`ActionTypes.UPDATE_LAYER_BLENDING`][12]-- **Updaters**: [`visStateUpdaters.updateLayerBlendingUpdater`][215]+- **Updaters**: [`visStateUpdaters.updateLayerBlendingUpdater`][218]**Parameters**-- `mode` **[string][161]** one of `additive`, `normal` and `subtractive`+- `mode` **[string][162]** one of `additive`, `normal` and `subtractive`Returns **{type: ActionTypes.UPDATE_LAYER_BLENDING, mode: mode}**@@ -898,25 +930,25 @@ Returns **{type: ActionTypes.UPDATE_LAYER_BLENDING, mode: mode}**Add new dataset to `visState`, with option to load a map config along with the datasets- **ActionTypes**: [`ActionTypes.UPDATE_VIS_DATA`][12]-- **Updaters**: [`visStateUpdaters.updateVisDataUpdater`][216]+- **Updaters**: [`visStateUpdaters.updateVisDataUpdater`][219]**Parameters**-- `datasets` **([Array][173]<[Object][163]> | [Object][163])** **\*required** datasets can be a dataset or an array of datasets+- `datasets` **([Array][174]<[Object][164]> | [Object][164])** **\*required** datasets can be a dataset or an array of datasetsEach dataset object needs to have `info` and `data` property.- - `datasets.info` **[Object][163]** \-info of a dataset- - `datasets.info.id` **[string][161]** id of this dataset. If config is defined, `id` should matches the `dataId` in config.- - `datasets.info.label` **[string][161]** A display name of this dataset- - `datasets.data` **[Object][163]** **\*required** The data object, in a tabular format with 2 properties `fields` and `rows`- - `datasets.data.fields` **[Array][173]<[Object][163]>** **\*required** Array of fields,- - `datasets.data.fields.name` **[string][161]** **\*required** Name of the field,- - `datasets.data.rows` **[Array][173]<[Array][173]>** **\*required** Array of rows, in a tabular format with `fields` and `rows`-- `options` **[Object][163]**- - `options.centerMap` **[boolean][164]** `default: true` if `centerMap` is set to `true` kepler.gl will+ - `datasets.info` **[Object][164]** \-info of a dataset+ - `datasets.info.id` **[string][162]** id of this dataset. If config is defined, `id` should matches the `dataId` in config.+ - `datasets.info.label` **[string][162]** A display name of this dataset+ - `datasets.data` **[Object][164]** **\*required** The data object, in a tabular format with 2 properties `fields` and `rows`+ - `datasets.data.fields` **[Array][174]<[Object][164]>** **\*required** Array of fields,+ - `datasets.data.fields.name` **[string][162]** **\*required** Name of the field,+ - `datasets.data.rows` **[Array][174]<[Array][174]>** **\*required** Array of rows, in a tabular format with `fields` and `rows`+- `options` **[Object][164]**+ - `options.centerMap` **[boolean][165]** `default: true` if `centerMap` is set to `true` kepler.gl willplace the map view within the data points boundaries- - `options.readOnly` **[boolean][164]** `default: false` if `readOnly` is set to `true`+ - `options.readOnly` **[boolean][165]** `default: false` if `readOnly` is set to `true`the left setting panel will be hidden-- `config` **[Object][163]** this object will contain the full kepler.gl instance configuration {mapState, mapStyle, visState}+- `config` **[Object][164]** this object will contain the full kepler.gl instance configuration {mapState, mapStyle, visState}Returns **{type: ActionTypes.UPDATE_VIS_DATA, datasets: datasets, options: options, config: config}**@@ -932,194 +964,176 @@ It also manges which settings are selected during image and map exportAdd a notification to be displayed- **ActionTypes**: [`ActionTypes.ADD_NOTIFICATION`][12]-- **Updaters**: [`uiStateUpdaters.addNotificationUpdater`][217]+- **Updaters**: [`uiStateUpdaters.addNotificationUpdater`][220]**Parameters**-- `notification` **[Object][163]** The `notification` object to be added+- `notification` **[Object][164]** The `notification` object to be added### cleanupExportImageDelete cached export image- **ActionTypes**: [`ActionTypes.CLEANUP_EXPORT_IMAGE`][12]-- **Updaters**: [`uiStateUpdaters.cleanupExportImage`][218]+- **Updaters**: [`uiStateUpdaters.cleanupExportImage`][221]### hideExportDropdownHide side panel header dropdown, activated by clicking the share link on top of the side panel- **ActionTypes**: [`ActionTypes.HIDE_EXPORT_DROPDOWN`][12]-- **Updaters**: [`uiStateUpdaters.hideExportDropdownUpdater`][219]+- **Updaters**: [`uiStateUpdaters.hideExportDropdownUpdater`][222]### openDeleteModalToggle active map control panel- **ActionTypes**: [`ActionTypes.OPEN_DELETE_MODAL`][12]-- **Updaters**: [`uiStateUpdaters.openDeleteModalUpdater`][220]+- **Updaters**: [`uiStateUpdaters.openDeleteModalUpdater`][223]**Parameters**-- `datasetId` **[string][161]** `id` of the dataset to be deleted+- `datasetId` **[string][162]** `id` of the dataset to be deleted### removeNotificationRemove a notification- **ActionTypes**: [`ActionTypes.REMOVE_NOTIFICATION`][12]-- **Updaters**: [`uiStateUpdaters.removeNotificationUpdater`][221]+- **Updaters**: [`uiStateUpdaters.removeNotificationUpdater`][224]**Parameters**-- `id` **[string][161]** `id` of the notification to be removed+- `id` **[string][162]** `id` of the notification to be removed### setExportDataWhether to including data in map config, toggle between `true` or `false`- **ActionTypes**: [`ActionTypes.SET_EXPORT_DATA`][12]-- **Updaters**: [`uiStateUpdaters.setExportDataUpdater`][222]+- **Updaters**: [`uiStateUpdaters.setExportDataUpdater`][225]### setExportDataTypeSet data format for exporting data- **ActionTypes**: [`ActionTypes.SET_EXPORT_DATA_TYPE`][12]-- **Updaters**: [`uiStateUpdaters.setExportDataTypeUpdater`][223]+- **Updaters**: [`uiStateUpdaters.setExportDataTypeUpdater`][226]**Parameters**-- `dataType` **[string][161]** one of `'text/csv'`+- `dataType` **[string][162]** one of `'text/csv'`### setExportFilteredWhether to export filtered data, `true` or `false`- **ActionTypes**: [`ActionTypes.SET_EXPORT_FILTERED`][12]-- **Updaters**: [`uiStateUpdaters.setExportFilteredUpdater`][224]+- **Updaters**: [`uiStateUpdaters.setExportFilteredUpdater`][227]**Parameters**-- `payload` **[boolean][164]** set `true` to ony export filtered data+- `payload` **[boolean][165]** set `true` to ony export filtered data### setExportImageDataUriSet `exportImage.setExportImageDataUri` to a dataUri- **ActionTypes**: [`ActionTypes.SET_EXPORT_IMAGE_DATA_URI`][12]-- **Updaters**: [`uiStateUpdaters.setExportImageDataUri`][225]+- **Updaters**: [`uiStateUpdaters.setExportImageDataUri`][228]**Parameters**-- `dataUri` **[string][161]** export image data uri+- `dataUri` **[string][162]** export image data uri-### setExportSelectedDataset--Set selected dataset for export--- **ActionTypes**: [`ActionTypes.SET_EXPORT_SELECTED_DATASET`][12]-- **Updaters**: [`uiStateUpdaters.setExportSelectedDatasetUpdater`][226]--**Parameters**--- `datasetId` **[string][161]** dataset id+### setExportImageSetting-### setRatio+Set `exportImage` settings: ratio, resolution, legend-Set `exportImage.ratio`--- **ActionTypes**: [`ActionTypes.SET_RATIO`][12]-- **Updaters**: [`uiStateUpdaters.setRatioUpdater`][227]+- **ActionTypes**: [`ActionTypes.SET_EXPORT_IMAGE_SETTING`][12]+- **Updaters**: [`uiStateUpdaters.setExportImageSetting`][229]**Parameters**-- `ratio` **[string][161]** one of `'SCREEN'`, `'FOUR_BY_THREE'` and `'SIXTEEN_BY_NINE'`+- `newSetting` **[Object][164]** {ratio: '1x'}-### setResolution+### setExportSelectedDataset-Set `exportImage.resolution`+Set selected dataset for export-- **ActionTypes**: [`ActionTypes.SET_RESOLUTION`][12]-- **Updaters**: [`uiStateUpdaters.setResolutionUpdater`][228]+- **ActionTypes**: [`ActionTypes.SET_EXPORT_SELECTED_DATASET`][12]+- **Updaters**: [`uiStateUpdaters.setExportSelectedDatasetUpdater`][230]**Parameters**-- `resolution` **[string][161]** one of `'ONE_X'`, `'TWO_X'`+- `datasetId` **[string][162]** dataset id### setUserMapboxAccessTokenWhether we export a mapbox access token used to create a single map html file- **ActionTypes**: [`ActionTypes.SET_USER_MAPBOX_ACCESS_TOKEN`][12]-- **Updaters**: [`uiStateUpdaters.setUserMapboxAccessTokenUpdater`][229]+- **Updaters**: [`uiStateUpdaters.setUserMapboxAccessTokenUpdater`][231]**Parameters**-- `payload` **[string][161]** mapbox access token+- `payload` **[string][162]** mapbox access token### showExportDropdownHide and show side panel header dropdown, activated by clicking the share link on top of the side panel- **ActionTypes**: [`ActionTypes.SHOW_EXPORT_DROPDOWN`][12]-- **Updaters**: [`uiStateUpdaters.showExportDropdownUpdater`][230]+- **Updaters**: [`uiStateUpdaters.showExportDropdownUpdater`][232]**Parameters**-- `id` **[string][161]** id of the dropdown+- `id` **[string][162]** id of the dropdown### startExportingImageSet `exportImage.exporting` to true- **ActionTypes**: [`ActionTypes.START_EXPORTING_IMAGE`][12]-- **Updaters**: [`uiStateUpdaters.startExportingImage`][231]--### toggleLegend--Set `exportImage.legend` to true or false--- **ActionTypes**: [`ActionTypes.TOGGLE_LEGEND`][12]-- **Updaters**: [`uiStateUpdaters.toggleLegendUpdater`][232]+- **Updaters**: [`uiStateUpdaters.startExportingImage`][233]### toggleMapControlToggle active map control panel- **ActionTypes**: [`ActionTypes.TOGGLE_MAP_CONTROL`][12]-- **Updaters**: [`uiStateUpdaters.toggleMapControlUpdater`][233]+- **Updaters**: [`uiStateUpdaters.toggleMapControlUpdater`][234]**Parameters**-- `panelId` **[string][161]** map control panel id, one of the keys of: [`DEFAULT_MAP_CONTROLS`][234]+- `panelId` **[string][162]** map control panel id, one of the keys of: [`DEFAULT_MAP_CONTROLS`][235]### toggleModalShow and hide modal dialog- **ActionTypes**: [`ActionTypes.TOGGLE_MODAL`][12]-- **Updaters**: [`uiStateUpdaters.toggleModalUpdater`][235]+- **Updaters**: [`uiStateUpdaters.toggleModalUpdater`][236]**Parameters**-- `id` **([string][161] | null)** id of modal to be shown, null to hide modals. One of:- [`DATA_TABLE_ID`][236]- - [`DELETE_DATA_ID`][237]- - [`ADD_DATA_ID`][238]- - [`EXPORT_IMAGE_ID`][239]- - [`EXPORT_DATA_ID`][240]- - [`ADD_MAP_STYLE_ID`][241]+- `id` **([string][162] | null)** id of modal to be shown, null to hide modals. One of:- [`DATA_TABLE_ID`][237]+ - [`DELETE_DATA_ID`][238]+ - [`ADD_DATA_ID`][239]+ - [`EXPORT_IMAGE_ID`][240]+ - [`EXPORT_DATA_ID`][241]+ - [`ADD_MAP_STYLE_ID`][242]### toggleSidePanelToggle active side panel- **ActionTypes**: [`ActionTypes.TOGGLE_SIDE_PANEL`][12]-- **Updaters**: [`uiStateUpdaters.toggleSidePanelUpdater`][242]+- **Updaters**: [`uiStateUpdaters.toggleSidePanelUpdater`][243]**Parameters**-- `id` **[string][161]** id of side panel to be shown, one of `layer`, `filter`, `interaction`, `map`+- `id` **[string][162]** id of side panel to be shown, one of `layer`, `filter`, `interaction`, `map`## rootActions@@ -1140,7 +1154,7 @@ the instance state and later transfer it to a newly mounted component with the s**Parameters**-- `id` **[string][161]** the id of the instance to be deleted+- `id` **[string][162]** the id of the instance to be deleted### registerEntry@@ -1153,13 +1167,13 @@ performed. Instance reducer can only handle actions when it is instantiated.**Parameters**-- `payload` **[Object][163]**- - `payload.id` **[string][161]** **\*required** The id of the instance- - `payload.mint` **[boolean][164]** Whether to use a fresh empty state, when `mint: true` it will _always_ load a fresh state when the component is re-mounted.+- `payload` **[Object][164]**+ - `payload.id` **[string][162]** **\*required** The id of the instance+ - `payload.mint` **[boolean][165]** Whether to use a fresh empty state, when `mint: true` it will _always_ load a fresh state when the component is re-mounted.When `mint: false` it will register with existing instance state under the same `id`, when the component is unmounted then mounted again. Default: `true`- - `payload.mapboxApiAccessToken` **[string][161]** mapboxApiAccessToken to be saved in `map-style` reducer.- - `payload.mapboxApiUrl` **[string][161]** mapboxApiUrl to be saved in `map-style` reducer.- - `payload.mapStylesReplaceDefault` **[Boolean][164]** mapStylesReplaceDefault to be saved in `map-style` reducer.+ - `payload.mapboxApiAccessToken` **[string][162]** mapboxApiAccessToken to be saved in `map-style` reducer.+ - `payload.mapboxApiUrl` **[string][162]** mapboxApiUrl to be saved in `map-style` reducer.+ - `payload.mapStylesReplaceDefault` **[Boolean][165]** mapStylesReplaceDefault to be saved in `map-style` reducer.### renameEntry@@ -1170,8 +1184,8 @@ Rename an instance in the root reducer, keep its entire state**Parameters**-- `oldId` **[string][161]** **\*required** old id-- `newId` **[string][161]** **\*required** new id+- `oldId` **[string][162]** **\*required** old id+- `newId` **[string][162]** **\*required** new id## mapStateActions@@ -1184,11 +1198,11 @@ toggle between single and split maps.Fit map viewport to bounds- **ActionTypes**: [`ActionTypes.FIT_BOUNDS`][12]-- **Updaters**: [`mapStateUpdaters.fitBoundsUpdater`][243]+- **Updaters**: [`mapStateUpdaters.fitBoundsUpdater`][244]**Parameters**-- `bounds` **[Array][173]<[Number][186]>** as `[lngMin, latMin, lngMax, latMax]`+- `bounds` **[Array][174]<[Number][188]>** as `[lngMin, latMin, lngMax, latMax]`**Examples**@@ -1202,7 +1216,7 @@ this.props.dispatch(fitBounds([-122.23, 37.127, -122.11, 37.456]));Toggle between 3d and 2d map.- **ActionTypes**: [`ActionTypes.TOGGLE_PERSPECTIVE`][12]-- **Updaters**: [`mapStateUpdaters.togglePerspectiveUpdater`][244]+- **Updaters**: [`mapStateUpdaters.togglePerspectiveUpdater`][245]**Examples**@@ -1216,11 +1230,11 @@ this.props.dispatch(togglePerspective());Toggle between single map or split maps- **ActionTypes**: [`ActionTypes.TOGGLE_SPLIT_MAP`][12]-- **Updaters**: [`mapStateUpdaters.toggleSplitMapUpdater`][245], [`uiStateUpdaters.toggleSplitMapUpdater`][246], [`visStateUpdaters.toggleSplitMapUpdater`][247]+- **Updaters**: [`mapStateUpdaters.toggleSplitMapUpdater`][246], [`uiStateUpdaters.toggleSplitMapUpdater`][247], [`visStateUpdaters.toggleSplitMapUpdater`][248]**Parameters**-- `index` **[Number][186]?** index is provided, close split map at index+- `index` **[Number][188]?** index is provided, close split map at index**Examples**@@ -1234,19 +1248,19 @@ this.props.dispatch(toggleSplitMap());Update map viewport- **ActionTypes**: [`ActionTypes.UPDATE_MAP`][12]-- **Updaters**: [`mapStateUpdaters.updateMapUpdater`][248]+- **Updaters**: [`mapStateUpdaters.updateMapUpdater`][249]**Parameters**-- `viewport` **[Object][163]** viewport object container one or any of these properties `width`, `height`, `latitude` `longitude`, `zoom`, `pitch`, `bearing`, `dragRotate`- - `viewport.width` **[Number][186]?** Width of viewport- - `viewport.height` **[Number][186]?** Height of viewport- - `viewport.zoom` **[Number][186]?** Zoom of viewport- - `viewport.pitch` **[Number][186]?** Camera angle in degrees (0 is straight down)- - `viewport.bearing` **[Number][186]?** Map rotation in degrees (0 means north is up)- - `viewport.latitude` **[Number][186]?** Latitude center of viewport on map in mercator projection- - `viewport.longitude` **[Number][186]?** Longitude Center of viewport on map in mercator projection- - `viewport.dragRotate` **[boolean][164]?** Whether to enable drag and rotate map into perspective viewport+- `viewport` **[Object][164]** viewport object container one or any of these properties `width`, `height`, `latitude` `longitude`, `zoom`, `pitch`, `bearing`, `dragRotate`+ - `viewport.width` **[Number][188]?** Width of viewport+ - `viewport.height` **[Number][188]?** Height of viewport+ - `viewport.zoom` **[Number][188]?** Zoom of viewport+ - `viewport.pitch` **[Number][188]?** Camera angle in degrees (0 is straight down)+ - `viewport.bearing` **[Number][188]?** Map rotation in degrees (0 means north is up)+ - `viewport.latitude` **[Number][188]?** Latitude center of viewport on map in mercator projection+ - `viewport.longitude` **[Number][188]?** Longitude Center of viewport on map in mercator projection+ - `viewport.dragRotate` **[boolean][165]?** Whether to enable drag and rotate map into perspective viewport**Examples**@@ -1260,24 +1274,24 @@ this.props.dispatch(updateMap({latitude: 37.75043, longitude: -122.34679, width:Set the color palette ui for layer color- **ActionTypes**: [`ActionTypes.LAYER_COLOR_UI_CHANGE`][12]-- **Updaters**: [`visStateUpdaters.layerColorUIChangeUpdater`][249]+- **Updaters**: [`visStateUpdaters.layerColorUIChangeUpdater`][250]**Parameters**-- `oldLayer` **[Object][163]** layer to be updated-- `prop` **[String][161]** which color prop-- `newConfig` **[object][163]** to be merged+- `oldLayer` **[Object][164]** layer to be updated+- `prop` **[String][162]** which color prop+- `newConfig` **[object][164]** to be merged## setExportMapFormatSet the export map format (html, json)- **ActionTypes**: [`ActionTypes.SET_EXPORT_MAP_FORMAT`][12]-- **Updaters**: [`uiStateUpdaters.setExportMapFormatUpdater`][250]+- **Updaters**: [`uiStateUpdaters.setExportMapFormatUpdater`][251]**Parameters**-- `payload` **[string][161]** map format+- `payload` **[string][162]** map format[1]: #forwardactions@@ -1371,410 +1385,412 @@ Set the export map format (html, json)[46]: #parameters-16-[47]: #enlargefilter+[47]: #applycpufilter[48]: #parameters-17-[49]: #interactionconfigchange+[49]: #enlargefilter[50]: #parameters-18-[51]: #layerconfigchange+[51]: #interactionconfigchange[52]: #parameters-19-[53]: #layertextlabelchange+[53]: #layerconfigchange[54]: #parameters-20-[55]: #layertypechange+[55]: #layertextlabelchange[56]: #parameters-21-[57]: #layervisconfigchange+[57]: #layertypechange[58]: #parameters-22-[59]: #layervisualchannelconfigchange+[59]: #layervisconfigchange[60]: #parameters-23-[61]: #loadfiles+[61]: #layervisualchannelconfigchange[62]: #parameters-24-[63]: #loadfileserr+[63]: #loadfiles[64]: #parameters-25-[65]: #onlayerclick+[65]: #loadfileserr[66]: #parameters-26-[67]: #onlayerhover+[67]: #onlayerclick[68]: #parameters-27-[69]: #onmapclick+[69]: #onlayerhover-[70]: #onmousemove+[70]: #parameters-28-[71]: #parameters-28+[71]: #onmapclick-[72]: #removedataset+[72]: #onmousemove[73]: #parameters-29-[74]: #removefilter+[74]: #removedataset[75]: #parameters-30-[76]: #removelayer+[76]: #removefilter[77]: #parameters-31-[78]: #reorderlayer+[78]: #removelayer[79]: #parameters-32-[80]: #examples-5+[80]: #reorderlayer-[81]: #seteditormode+[81]: #parameters-33-[82]: #parameters-33+[82]: #examples-5-[83]: #examples-6+[83]: #seteditormode-[84]: #setfilter+[84]: #parameters-34-[85]: #parameters-34+[85]: #examples-6-[86]: #setfilterplot+[86]: #setfilter[87]: #parameters-35-[88]: #showdatasettable+[88]: #setfilterplot[89]: #parameters-36-[90]: #togglefilteranimation+[90]: #setmapinfo[91]: #parameters-37-[92]: #togglelayerformap+[92]: #showdatasettable[93]: #parameters-38-[94]: #updateanimationtime+[94]: #togglefilteranimation[95]: #parameters-39-[96]: #updatefilteranimationspeed+[96]: #togglelayerformap[97]: #parameters-40-[98]: #updatelayeranimationspeed+[98]: #updateanimationtime[99]: #parameters-41-[100]: #updatelayerblending+[100]: #updatefilteranimationspeed[101]: #parameters-42-[102]: #updatevisdata+[102]: #updatelayeranimationspeed[103]: #parameters-43-[104]: #uistateactions+[104]: #updatelayerblending-[105]: #addnotification+[105]: #parameters-44-[106]: #parameters-44+[106]: #updatevisdata-[107]: #cleanupexportimage+[107]: #parameters-45-[108]: #hideexportdropdown+[108]: #uistateactions-[109]: #opendeletemodal+[109]: #addnotification-[110]: #parameters-45+[110]: #parameters-46-[111]: #removenotification+[111]: #cleanupexportimage-[112]: #parameters-46+[112]: #hideexportdropdown-[113]: #setexportdata+[113]: #opendeletemodal-[114]: #setexportdatatype+[114]: #parameters-47-[115]: #parameters-47+[115]: #removenotification-[116]: #setexportfiltered+[116]: #parameters-48-[117]: #parameters-48+[117]: #setexportdata-[118]: #setexportimagedatauri+[118]: #setexportdatatype[119]: #parameters-49-[120]: #setexportselecteddataset+[120]: #setexportfiltered[121]: #parameters-50-[122]: #setratio+[122]: #setexportimagedatauri[123]: #parameters-51-[124]: #setresolution+[124]: #setexportimagesetting[125]: #parameters-52-[126]: #setusermapboxaccesstoken+[126]: #setexportselecteddataset[127]: #parameters-53-[128]: #showexportdropdown+[128]: #setusermapboxaccesstoken[129]: #parameters-54-[130]: #startexportingimage+[130]: #showexportdropdown++[131]: #parameters-55-[131]: #togglelegend+[132]: #startexportingimage-[132]: #togglemapcontrol+[133]: #togglemapcontrol-[133]: #parameters-55+[134]: #parameters-56-[134]: #togglemodal+[135]: #togglemodal-[135]: #parameters-56+[136]: #parameters-57-[136]: #togglesidepanel+[137]: #togglesidepanel-[137]: #parameters-57+[138]: #parameters-58-[138]: #rootactions+[139]: #rootactions-[139]: #deleteentry+[140]: #deleteentry-[140]: #parameters-58+[141]: #parameters-59-[141]: #registerentry+[142]: #registerentry-[142]: #parameters-59+[143]: #parameters-60-[143]: #renameentry+[144]: #renameentry-[144]: #parameters-60+[145]: #parameters-61-[145]: #mapstateactions+[146]: #mapstateactions-[146]: #fitbounds+[147]: #fitbounds-[147]: #parameters-61+[148]: #parameters-62-[148]: #examples-7+[149]: #examples-7-[149]: #toggleperspective+[150]: #toggleperspective-[150]: #examples-8+[151]: #examples-8-[151]: #togglesplitmap+[152]: #togglesplitmap-[152]: #parameters-62+[153]: #parameters-63-[153]: #examples-9+[154]: #examples-9-[154]: #updatemap+[155]: #updatemap-[155]: #parameters-63+[156]: #parameters-64-[156]: #examples-10+[157]: #examples-10-[157]: #layercoloruichange+[158]: #layercoloruichange-[158]: #parameters-64+[159]: #parameters-65-[159]: #setexportmapformat+[160]: #setexportmapformat-[160]: #parameters-65+[161]: #parameters-66-[161]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String+[162]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String-[162]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function+[163]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function-[163]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object+[164]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object-[164]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean+[165]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean-[165]: ../reducers/map-style.md#mapstyleupdatersaddcustommapstyleupdater+[166]: ../reducers/map-style.md#mapstyleupdatersaddcustommapstyleupdater-[166]: ../reducers/map-style.md#mapstyleupdatersinputmapstyleupdater+[167]: ../reducers/map-style.md#mapstyleupdatersinputmapstyleupdater-[167]: ../reducers/map-style.md#mapstyleupdatersloadcustommapstyleupdater+[168]: ../reducers/map-style.md#mapstyleupdatersloadcustommapstyleupdater-[168]: ../reducers/map-style.md#mapstyleupdatersloadmapstyleerrupdater+[169]: ../reducers/map-style.md#mapstyleupdatersloadmapstyleerrupdater-[169]: ../reducers/map-style.md#mapstyleupdatersloadmapstylesupdater+[170]: ../reducers/map-style.md#mapstyleupdatersloadmapstylesupdater-[170]: ../reducers/map-style.md#mapstyleupdatersmapconfigchangeupdater+[171]: ../reducers/map-style.md#mapstyleupdatersmapconfigchangeupdater-[171]: ../reducers/map-style.md#mapstyleupdatersmapstylechangeupdater+[172]: ../reducers/map-style.md#mapstyleupdatersmapstylechangeupdater-[172]: ../reducers/map-style.md#mapstyleupdatersrequestmapstylesupdater+[173]: ../reducers/map-style.md#mapstyleupdatersrequestmapstylesupdater-[173]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array+[174]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array-[174]: ../reducers/map-style.md#mapstyleupdatersset3dbuildingcolorupdater+[175]: ../reducers/map-style.md#mapstyleupdatersset3dbuildingcolorupdater-[175]: ../reducers/composers.md#combinedupdatersadddatatomapupdater+[176]: ../reducers/composers.md#combinedupdatersadddatatomapupdater-[176]: ../reducers/map-style.md#mapstyleupdatersinitmapstyleupdater+[177]: ../reducers/map-style.md#mapstyleupdatersinitmapstyleupdater-[177]: ../reducers/map-state.md#mapstateupdatersreceivemapconfigupdater+[178]: ../reducers/map-state.md#mapstateupdatersreceivemapconfigupdater-[178]: ../reducers/map-style.md#mapstyleupdatersreceivemapconfigupdater+[179]: ../reducers/map-style.md#mapstyleupdatersreceivemapconfigupdater-[179]: ../reducers/vis-state.md#visstateupdatersreceivemapconfigupdater+[180]: ../reducers/vis-state.md#visstateupdatersreceivemapconfigupdater-[180]: ../reducers/map-state.md#mapstateupdatersresetmapconfigupdater+[181]: ../reducers/map-state.md#mapstateupdatersresetmapconfigupdater-[181]: ../reducers/map-style.md#mapstyleupdatersresetmapconfigmapstyleupdater+[182]: ../reducers/map-style.md#mapstyleupdatersresetmapconfigmapstyleupdater-[182]: ../reducers/vis-state.md#visstateupdatersresetmapconfigupdater+[183]: ../reducers/vis-state.md#visstateupdatersresetmapconfigupdater-[183]: ../reducers/vis-state.md#visstateupdatersaddfilterupdater+[184]: ../reducers/vis-state.md#visstateupdatersaddfilterupdater-[184]: ../reducers/vis-state.md#visstateupdatersaddlayerupdater+[185]: ../reducers/vis-state.md#visstateupdatersaddlayerupdater-[185]: ../reducers/vis-state.md#visstateupdatersenlargefilterupdater+[186]: ../reducers/vis-state.md#visstateupdatersapplycpufilterupdater-[186]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number+[187]: ../reducers/vis-state.md#visstateupdatersenlargefilterupdater-[187]: ../reducers/vis-state.md#visstateupdatersinteractionconfigchangeupdater+[188]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number-[188]: ../reducers/vis-state.md#visstateupdaterslayerconfigchangeupdater+[189]: ../reducers/vis-state.md#visstateupdatersinteractionconfigchangeupdater-[189]: ../reducers/vis-state.md#visstateupdaterslayertextlabelchangeupdater+[190]: ../reducers/vis-state.md#visstateupdaterslayerconfigchangeupdater-[190]: ../reducers/vis-state.md#visstateupdaterslayertypechangeupdater+[191]: ../reducers/vis-state.md#visstateupdaterslayertextlabelchangeupdater-[191]: ../reducers/vis-state.md#visstateupdaterslayervisconfigchangeupdater+[192]: ../reducers/vis-state.md#visstateupdaterslayertypechangeupdater-[192]: ../reducers/vis-state.md#visstateupdaterslayervisualchannelchangeupdater+[193]: ../reducers/vis-state.md#visstateupdaterslayervisconfigchangeupdater-[193]: ../reducers/ui-state.md#uistateupdatersloadfilesupdater+[194]: ../reducers/vis-state.md#visstateupdaterslayervisualchannelchangeupdater-[194]: ../reducers/vis-state.md#visstateupdatersloadfilesupdater+[195]: ../reducers/ui-state.md#uistateupdatersloadfilesupdater-[195]: ../reducers/ui-state.md#uistateupdatersloadfileserrupdater+[196]: ../reducers/vis-state.md#visstateupdatersloadfilesupdater-[196]: ../reducers/vis-state.md#visstateupdatersloadfileserrupdater+[197]: ../reducers/ui-state.md#uistateupdatersloadfileserrupdater-[197]: ../reducers/vis-state.md#visstateupdaterslayerclickupdater+[198]: ../reducers/vis-state.md#visstateupdatersloadfileserrupdater-[198]: ../reducers/vis-state.md#visstateupdaterslayerhoverupdater+[199]: ../reducers/vis-state.md#visstateupdaterslayerclickupdater-[199]: ../reducers/vis-state.md#visstateupdatersmapclickupdater+[200]: ../reducers/vis-state.md#visstateupdaterslayerhoverupdater-[200]: https://uber.github.io/react-map-gl/#/documentation/api-reference/pointer-event+[201]: ../reducers/vis-state.md#visstateupdatersmapclickupdater-[201]: ../reducers/vis-state.md#visstateupdatersmousemoveupdater+[202]: https://uber.github.io/react-map-gl/#/documentation/api-reference/pointer-event-[202]: ../reducers/vis-state.md#visstateupdatersremovedatasetupdater+[203]: ../reducers/vis-state.md#visstateupdatersmousemoveupdater-[203]: ../reducers/vis-state.md#visstateupdatersremovefilterupdater+[204]: ../reducers/vis-state.md#visstateupdatersremovedatasetupdater-[204]: ../reducers/vis-state.md#visstateupdatersremovelayerupdater+[205]: ../reducers/vis-state.md#visstateupdatersremovefilterupdater-[205]: ../reducers/vis-state.md#visstateupdatersreorderlayerupdater+[206]: ../reducers/vis-state.md#visstateupdatersremovelayerupdater-[206]: ../reducers/vis-state.md#visstateupdatersseteditormodeupdater+[207]: ../reducers/vis-state.md#visstateupdatersreorderlayerupdater-[207]: ../reducers/vis-state.md#visstateupdaterssetfilterupdater+[208]: ../reducers/vis-state.md#visstateupdatersseteditormodeupdater-[208]: ../reducers/vis-state.md#visstateupdaterssetfilterplotupdater+[209]: ../reducers/vis-state.md#visstateupdaterssetfilterupdater-[209]: ../reducers/vis-state.md#visstateupdatersshowdatasettableupdater+[210]: ../reducers/vis-state.md#visstateupdaterssetfilterplotupdater-[210]: ../reducers/vis-state.md#visstateupdaterstogglefilteranimationupdater+[211]: ../reducers/vis-state.md#visstateupdaterssetmapinfoupdater-[211]: ../reducers/vis-state.md#visstateupdaterstogglelayerformapupdater+[212]: ../reducers/vis-state.md#visstateupdatersshowdatasettableupdater-[212]: ../reducers/vis-state.md#visstateupdatersupdateanimationtimeupdater+[213]: ../reducers/vis-state.md#visstateupdaterstogglefilteranimationupdater-[213]: ../reducers/vis-state.md#visstateupdatersupdatefilteranimationspeedupdater+[214]: ../reducers/vis-state.md#visstateupdaterstogglelayerformapupdater-[214]: ../reducers/vis-state.md#visstateupdatersupdatelayeranimationspeedupdater+[215]: ../reducers/vis-state.md#visstateupdatersupdateanimationtimeupdater-[215]: ../reducers/vis-state.md#visstateupdatersupdatelayerblendingupdater+[216]: ../reducers/vis-state.md#visstateupdatersupdatefilteranimationspeedupdater-[216]: ../reducers/vis-state.md#visstateupdatersupdatevisdataupdater+[217]: ../reducers/vis-state.md#visstateupdatersupdatelayeranimationspeedupdater-[217]: ../reducers/ui-state.md#uistateupdatersaddnotificationupdater+[218]: ../reducers/vis-state.md#visstateupdatersupdatelayerblendingupdater-[218]: ../reducers/ui-state.md#uistateupdaterscleanupexportimage+[219]: ../reducers/vis-state.md#visstateupdatersupdatevisdataupdater-[219]: ../reducers/ui-state.md#uistateupdatershideexportdropdownupdater+[220]: ../reducers/ui-state.md#uistateupdatersaddnotificationupdater-[220]: ../reducers/ui-state.md#uistateupdatersopendeletemodalupdater+[221]: ../reducers/ui-state.md#uistateupdaterscleanupexportimage-[221]: ../reducers/ui-state.md#uistateupdatersremovenotificationupdater+[222]: ../reducers/ui-state.md#uistateupdatershideexportdropdownupdater-[222]: ../reducers/ui-state.md#uistateupdaterssetexportdataupdater+[223]: ../reducers/ui-state.md#uistateupdatersopendeletemodalupdater-[223]: ../reducers/ui-state.md#uistateupdaterssetexportdatatypeupdater+[224]: ../reducers/ui-state.md#uistateupdatersremovenotificationupdater-[224]: ../reducers/ui-state.md#uistateupdaterssetexportfilteredupdater+[225]: ../reducers/ui-state.md#uistateupdaterssetexportdataupdater-[225]: ../reducers/ui-state.md#uistateupdaterssetexportimagedatauri+[226]: ../reducers/ui-state.md#uistateupdaterssetexportdatatypeupdater-[226]: ../reducers/ui-state.md#uistateupdaterssetexportselecteddatasetupdater+[227]: ../reducers/ui-state.md#uistateupdaterssetexportfilteredupdater-[227]: ../reducers/ui-state.md#uistateupdaterssetratioupdater+[228]: ../reducers/ui-state.md#uistateupdaterssetexportimagedatauri-[228]: ../reducers/ui-state.md#uistateupdaterssetresolutionupdater+[229]: ../reducers/ui-state.md#uistateupdaterssetexportimagesetting-[229]: ../reducers/ui-state.md#uistateupdaterssetusermapboxaccesstokenupdater+[230]: ../reducers/ui-state.md#uistateupdaterssetexportselecteddatasetupdater-[230]: ../reducers/ui-state.md#uistateupdatersshowexportdropdownupdater+[231]: ../reducers/ui-state.md#uistateupdaterssetusermapboxaccesstokenupdater-[231]: ../reducers/ui-state.md#uistateupdatersstartexportingimage+[232]: ../reducers/ui-state.md#uistateupdatersshowexportdropdownupdater-[232]: ../reducers/ui-state.md#uistateupdaterstogglelegendupdater+[233]: ../reducers/ui-state.md#uistateupdatersstartexportingimage-[233]: ../reducers/ui-state.md#uistateupdaterstogglemapcontrolupdater+[234]: ../reducers/ui-state.md#uistateupdaterstogglemapcontrolupdater-[234]: #default_map_controls+[235]: #default_map_controls-[235]: ../reducers/ui-state.md#uistateupdaterstogglemodalupdater+[236]: ../reducers/ui-state.md#uistateupdaterstogglemodalupdater-[236]: ../constants/default-settings.md#data_table_id+[237]: ../constants/default-settings.md#data_table_id-[237]: ../constants/default-settings.md#delete_data_id+[238]: ../constants/default-settings.md#delete_data_id-[238]: ../constants/default-settings.md#add_data_id+[239]: ../constants/default-settings.md#add_data_id-[239]: ../constants/default-settings.md#export_image_id+[240]: ../constants/default-settings.md#export_image_id-[240]: ../constants/default-settings.md#export_data_id+[241]: ../constants/default-settings.md#export_data_id-[241]: ../constants/default-settings.md#add_map_style_id+[242]: ../constants/default-settings.md#add_map_style_id-[242]: ../reducers/ui-state.md#uistateupdaterstogglesidepanelupdater+[243]: ../reducers/ui-state.md#uistateupdaterstogglesidepanelupdater-[243]: ../reducers/map-state.md#mapstateupdatersfitboundsupdater+[244]: ../reducers/map-state.md#mapstateupdatersfitboundsupdater-[244]: ../reducers/map-state.md#mapstateupdaterstoggleperspectiveupdater+[245]: ../reducers/map-state.md#mapstateupdaterstoggleperspectiveupdater-[245]: ../reducers/map-state.md#mapstateupdaterstogglesplitmapupdater+[246]: ../reducers/map-state.md#mapstateupdaterstogglesplitmapupdater-[246]: ../reducers/ui-state.md#uistateupdaterstogglesplitmapupdater+[247]: ../reducers/ui-state.md#uistateupdaterstogglesplitmapupdater-[247]: ../reducers/vis-state.md#visstateupdaterstogglesplitmapupdater+[248]: ../reducers/vis-state.md#visstateupdaterstogglesplitmapupdater-[248]: ../reducers/map-state.md#mapstateupdatersupdatemapupdater+[249]: ../reducers/map-state.md#mapstateupdatersupdatemapupdater-[249]: ../reducers/vis-state.md#visstateupdaterslayercoloruichangeupdater+[250]: ../reducers/vis-state.md#visstateupdaterslayercoloruichangeupdater-[250]: ../reducers/ui-state.md#uistateupdaterssetexportmapformatupdater+[251]: ../reducers/ui-state.md#uistateupdaterssetexportmapformatupdaterdiff --git a/docs/api-reference/cloud-providers/cloud-provider.md b/docs/api-reference/cloud-providers/cloud-provider.mdnew file mode 100644index 000000000..03b5a6b43--- /dev/null+++ b/docs/api-reference/cloud-providers/cloud-provider.md@@ -0,0 +1,277 @@+<!-- Generated by documentation.js. Update this documentation by updating the source code. -->++### Table of Contents++- [Provider][1]+ - [downloadMap][4]+ - [getAccessToken][7]+ - [getMapUrl][8]+ - [getShareUrl][10]+ - [getUserName][12]+ - [hasPrivateStorage][13]+ - [hasSharingUrl][14]+ - [listMaps][15]+ - [login][17]+ - [logout][19]+ - [uploadMap][21]+- [MapResponse][23]+- [Viz][25]++## Provider++The default provider class++**Parameters**++- `props` **[object][27]**+ - `props.name` **[string][28]**+ - `props.displayName` **[string][28]**+ - `props.icon` **ReactElement** React element+ - `props.thumbnail` **[object][27]** thumbnail size object+ - `props.thumbnail.width` **[number][29]** thumbnail width in pixels+ - `props.thumbnail.height` **[number][29]** thumbnail height in pixels++**Examples**++```javascript+const myProvider = new Provider({+ name: 'foo',+ displayName: 'Foo Storage'+ icon: Icon,+ thumbnail: {width: 300, height: 200}+})+```++### downloadMap++This method will be called when user select a map to load from the storage map viewer++**Parameters**++- `loadParams` **any** the loadParams property of each visualization object++**Examples**++```javascript+async downloadMap(loadParams) {+ const mockResponse = {+ map: {+ datasets: [],+ config: {},+ info: {+ app: 'kepler.gl',+ created_at: ''+ title: 'test map',+ description: 'Hello this is my test dropbox map'+ }+ },+ // pass csv here if your provider currently only support save / load file as csv+ format: 'keplergl'+ };++ return downloadMap;+}+```++Returns **[MapResponse][30]** the map object containing dataset config info and format option++### getAccessToken++This method is called to determine whether user already logged in to this provider++Returns **[boolean][31]** true if a user already logged in++### getMapUrl++This method is called by kepler.gl demo app to pushes a new location to history, becoming the current location.++**Parameters**++- `fullURL` **[boolean][31]** Whether to return the full url with domain, or just the location (optional, default `true`)++Returns **[string][28]** mapUrl++### getShareUrl++This method is called after user share a map, to display the share url.++**Parameters**++- `fullUrl` **[boolean][31]** Whether to return the full url with domain, or just the location (optional, default `false`)++Returns **[string][28]** shareUrl++### getUserName++This method is called to get the user name of the current user. It will be displayed in the cloud provider tile.++Returns **[string][28]** true if a user already logged in++### hasPrivateStorage++Whether this provider support upload map to a private storage. If truthy, user will be displayed with the storage save icon on the top right of the side bar.++Returns **[boolean][31]**++### hasSharingUrl++Whether this provider support share map via a public url, if truthy, user will be displayed with a share map via url under the export map option on the top right of the side bar++Returns **[boolean][31]**++### listMaps++This method is called to get a list of maps saved by the current logged in user.++**Examples**++```javascript+async listMaps() {+ return [+ {+ id: 'a',+ title: 'My map',+ description: 'My first kepler map',+ imageUrl: 'http://',+ lastModification: 1582677787000,+ privateMap: false,+ loadParams: {}+ }+ ];+ }+```++Returns **[Array][32]<[Viz][33]>** an array of Viz objects++### login++This method will be called when user click the login button in the cloud provider tile.+Upon login success, `onCloudLoginSuccess` has to be called to notify kepler.gl UI++**Parameters**++- `onCloudLoginSuccess` **[function][34]** callbacks to be called after login success++### logout++This method will be called when user click the logout button under the cloud provider tile.+Upon login success, `onCloudLoginSuccess` has to be called to notify kepler.gl UI++**Parameters**++- `onCloudLogoutSuccess` **[function][34]** callbacks to be called after logout success++### uploadMap++This method will be called to upload map for saving and sharing. Kepler.gl will package map data, config, title, description and thumbnail for upload to storage.+With the option to overwrite already saved map, and upload as private or public map.++**Parameters**++- `param` **[Object][27]**+ - `param.mapData` **[Object][27]** the map object+ - `param.mapData.map` **[Object][27]** {datasets. config, info: {title, description}}+ - `param.mapData.thumbnail` **[Blob][35]** A thumbnail of current map. thumbnail size can be defined by provider by this.thumbnail+ - `param.options` **[Object][27]** (optional, default `{}`)+ - `param.options.overwrite` **[boolean][31]** whether user choose to overwrite already saved map under the same name+ - `param.options.isPublic` **[boolean][31]** whether user wish to share the map with others. if isPublic is truthy, kepler will call this.getShareUrl() to display an URL they can share with others++## MapResponse++The returned object of `downloadMap`. The response object should contain: datasets: \[], config: {}, and info: {}+each dataset object should be {info: {id, label}, data: {...}}+to inform how kepler should process your data object, pass in `format`++Type: [Object][27]++### Properties++- `map` **[Object][27]**+ - `map.datasets` **[Array][32]<[Object][27]>**+ - `map.config` **[Object][27]**+ - `map.info` **[Object][27]**+- `format` **[string][28]** one of 'csv': csv file string, 'geojson': geojson object, 'row': row object, 'keplergl': datasets array saved using KeplerGlSchema.save++## Viz++Type: [Object][27]++### Properties++- `id` **[string][28]** An unique id+- `title` **[string][28]** The title of the map+- `description` **[string][28]** The description of the map+- `imageUrl` **[string][28]** The imageUrl of the map+- `lastModification` **[number][29]** An epoch timestamp in milliseconds+- `privateMap` **[boolean][31]** Optional, whether if this map is private to the user, or can be accessed by others via URL+- `loadParams` **any** A property to be passed to `downloadMap`++[1]: #provider++[2]: #parameters++[3]: #examples++[4]: #downloadmap++[5]: #parameters-1++[6]: #examples-1++[7]: #getaccesstoken++[8]: #getmapurl++[9]: #parameters-2++[10]: #getshareurl++[11]: #parameters-3++[12]: #getusername++[13]: #hasprivatestorage++[14]: #hassharingurl++[15]: #listmaps++[16]: #examples-2++[17]: #login++[18]: #parameters-4++[19]: #logout++[20]: #parameters-5++[21]: #uploadmap++[22]: #parameters-6++[23]: #mapresponse++[24]: #properties++[25]: #viz++[26]: #properties-1++[27]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object++[28]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String++[29]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number++[30]: #mapresponse++[31]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean++[32]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array++[33]: #viz++[34]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function++[35]: https://developer.mozilla.org/docs/Web/API/Blobdiff --git a/docs/api-reference/cloud-providers/overview.md b/docs/api-reference/cloud-providers/overview.mdindex eb81ae7d7..1b8a8e733 100644--- a/docs/api-reference/cloud-providers/overview.md+++ b/docs/api-reference/cloud-providers/overview.md@@ -14,56 +14,52 @@ A "cloud provider" object provides:- any service specific methods (such as `uploadFile`)- a set of oauth2 methods to plug into the authentication flow and get access tokens-Cloud-providers providers implement the following properties--| Field/method | Description |-| --- | --- |-| `name` | |-| `icon` | |-| `login` | |-| `uploadFile` | |+Cloud-providers providers can implement the following properties++| Field/method | Description | Required? |+| --- | --- | --- |+| `name` | Name of the provider | required |+| `displayName` | Display name |+| `icon` | React Element to render as Icon |+| `thumbnail` | Size of the thumbnail image of the map that required by the provider |+| `hasPrivateStorage` | To participate in kepler's build-in private map saving function | required |+| `hasSharingUrl` | To participate in kepler's build-in share map via URL function | required |+| `getShareUrl` | To show user the shared Url of the map |+| `getMapUrl` | To update browser location once a map has been saved / loaded || `getAccessToken` | To participate in kepler's built-in oauth login routes |-| `getAccessTokenFromLocation` | To participate in kepler's built-in oauth login routes |-| `hasPrivateStorage` | To participate in kepler's build-in map saving function |-| `hasSharingUrl` | To participate in kepler's build-in share map via URL function |+| `getUserName` | To display user name of the logged in user |+| `login` | Method called to perform user login | required |+| `logout` | Method called to logout an user | required |+| `uploadMap` | Method called to upload map to storage | required |+| `listMaps` | Method called to load a catalog of maps saved by the current user | required |+| `downloadMap` | MEthod called to download a specific map | required |-## Adding a new Cloud Provider--An instance of the provider is added to array of cloud providers in the file `src/cloud-providers/providers.js`--## Cloud Provider Instance Fields and Methods--## name : String--The UI name of the provider--## icon : ReactElement--This should be a React SVG icon for the provider-## hasPrivateStorage() : Boolean--Whether the provider has private backend to store maps. If any provider supports private storage, The cloud storage icon in side panel will be shown.--## hasSharingUrl() : Boolean--Whether the provider supports share map with an URL. If any provider supports this feature, The share map url icon option will be shown as an option in the share map dropdown.--## Methods--### login()--### upload({})+## Adding a new Cloud Provider-### getAccessToken+An instance of the provider is added to array of cloud providers in the file `src/cloud-providers/providers.js` then passed to kepler.gl demo app. An example provider: [Dropbox Provider](https://github.com/keplergl/kepler.gl/blob/master/examples/demo-app/src/cloud-providers/dropbox-provider.js)-This lets the provider participate in kepler's built-in oauth flow.+```js+import {Provider} from 'kepler.gl/cloud-providers';-Can be ignored for providers that implement or use libraries that implement custom login flows (e.g signin using Google gapi).+class MyProvider extends Provider {+ constructor() {+ this.name = 'foo';+ this.displayName = 'My Provider';+ }+ // ... other required methods below+}-### getAccessTokenFromLocation+const myProvider = new MyProvider();+const App = () =>+ <KeplerGl+ mapboxApiAccessToken={AUTH_TOKENS.MAPBOX_TOKEN}+ id="map"+ cloudProviders={[myProvider]}+ />+```-This lets the provider participate in kepler's built-in oauth flow.-Can be ignored for providers that implement or use libraries that implement custom login flows (e.g signin using Google gapi).+## Cloud Provider Instance Fields and Methods+See [Cloud Provider API](./cloud-provider.md)diff --git a/docs/api-reference/reducers/reducers.md b/docs/api-reference/reducers/reducers.mdindex fdaa8b4aa..54055fdcc 100644--- a/docs/api-reference/reducers/reducers.md+++ b/docs/api-reference/reducers/reducers.md@@ -7,8 +7,9 @@- [keplerGlReducer.plugin][6]- [mapStateLens][9]- [mapStyleLens][11]-- [uiStateLens][13]-- [visStateLens][15]+- [providerStateLens][13]+- [uiStateLens][15]+- [visStateLens][17]## keplerGlReducer@@ -43,14 +44,14 @@ which will be shallow **merged** with default initial state.Default subreducer state:-- [`visState`][17]-- [`mapState`][18]-- [`mapStyle`][19]-- [`uiState`][20]+- [`visState`][19]+- [`mapState`][20]+- [`mapStyle`][21]+- [`uiState`][22]**Parameters**-- `iniSt` **[Object][21]** custom state to be merged with default initial state+- `iniSt` **[Object][23]** custom state to be merged with default initial state**Examples**@@ -73,7 +74,7 @@ You should only use this to adding additional actions instead of replacing defau**Parameters**-- `customReducer` **([Object][21] \| [Function][22])** A reducer map or a reducer+- `customReducer` **([Object][23] \| [Function][24])** A reducer map or a reducer**Examples**@@ -104,7 +105,7 @@ const myKeplerGlReducer = keplerGlReducer## mapStateLensConnect subreducer `mapState`, used with `injectComponents`. Learn more at-[Replace UI Component][23]+[Replace UI Component][25]**Parameters**@@ -113,7 +114,16 @@ Connect subreducer `mapState`, used with `injectComponents`. Learn more at## mapStyleLensConnect subreducer `mapStyle`, used with `injectComponents`. Learn more at-[Replace UI Component][23]+[Replace UI Component][25]++**Parameters**++- `reduxState` **any**++## providerStateLens++Connect subreducer `providerState`, used with `injectComponents`. Learn more at+[Replace UI Component][25]**Parameters**@@ -122,7 +132,7 @@ Connect subreducer `mapStyle`, used with `injectComponents`. Learn more at## uiStateLensConnect subreducer `uiState`, used with `injectComponents`. Learn more at-[Replace UI Component][23]+[Replace UI Component][25]**Parameters**@@ -131,7 +141,7 @@ Connect subreducer `uiState`, used with `injectComponents`. Learn more at## visStateLensConnect subreducer `visState`, used with `injectComponents`. Learn more at-[Replace UI Component][23]+[Replace UI Component][25]**Parameters**@@ -161,24 +171,28 @@ Connect subreducer `visState`, used with `injectComponents`. Learn more at[12]: #parameters-3-[13]: #uistatelens+[13]: #providerstatelens[14]: #parameters-4-[15]: #visstatelens+[15]: #uistatelens[16]: #parameters-5-[17]: ./vis-state.md#INITIAL_VIS_STATE+[17]: #visstatelens++[18]: #parameters-6++[19]: ./vis-state.md#INITIAL_VIS_STATE-[18]: ./map-state.md#INITIAL_MAP_STATE+[20]: ./map-state.md#INITIAL_MAP_STATE-[19]: ./map-style.md#INITIAL_MAP_STYLE+[21]: ./map-style.md#INITIAL_MAP_STYLE-[20]: ./ui-state.md#INITIAL_UI_STATE+[22]: ./ui-state.md#INITIAL_UI_STATE-[21]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object+[23]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object-[22]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function+[24]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function-[23]: ../advanced-usages/replace-ui-component.md#pass-custom-component-props+[25]: ../advanced-usages/replace-ui-component.md#pass-custom-component-propsdiff --git a/docs/api-reference/reducers/ui-state.md b/docs/api-reference/reducers/ui-state.mdindex 1ec2589af..73f31446b 100644--- a/docs/api-reference/reducers/ui-state.md+++ b/docs/api-reference/reducers/ui-state.md@@ -18,23 +18,21 @@- [setExportDataUpdater][27]- [setExportFilteredUpdater][29]- [setExportImageDataUri][31]- - [setExportSelectedDatasetUpdater][33]- - [setRatioUpdater][35]- - [setResolutionUpdater][37]- - [showExportDropdownUpdater][39]- - [startExportingImage][41]- - [toggleLegendUpdater][43]- - [toggleMapControlUpdater][45]- - [toggleModalUpdater][47]- - [toggleSidePanelUpdater][49]- - [toggleSplitMapUpdater][51]-- [DEFAULT_EXPORT_HTML][53]-- [setUserMapboxAccessTokenUpdater][55]+ - [setExportImageSetting][33]+ - [setExportSelectedDatasetUpdater][35]+ - [showExportDropdownUpdater][37]+ - [startExportingImage][39]+ - [toggleMapControlUpdater][41]+ - [toggleModalUpdater][43]+ - [toggleSidePanelUpdater][45]+ - [toggleSplitMapUpdater][47]+- [DEFAULT_EXPORT_HTML][49]+- [setUserMapboxAccessTokenUpdater][51]## uiStateUpdatersUpdaters for `uiState` reducer. Can be used in your root reducer to directly modify kepler.gl's state.-Read more about [Using updaters][57]+Read more about [Using updaters][53]**Examples**@@ -73,371 +71,345 @@ export default composedReducer;Add a notification to be displayed-- **Action**: [`addNotification`][58]+- **Action**: [`addNotification`][54]**Parameters**-- `state` **[Object][59]** `uiState`-- `action` **[Object][59]**- - `action.payload` **[Object][59]**+- `state` **[Object][55]** `uiState`+- `action` **[Object][55]**+ - `action.payload` **[Object][55]**-Returns **[Object][59]** nextState+Returns **[Object][55]** nextState### cleanupExportImageDelete cached export image-- **Action**: [`cleanupExportImage`][60]+- **Action**: [`cleanupExportImage`][56]**Parameters**-- `state` **[Object][59]** `uiState`+- `state` **[Object][55]** `uiState`-Returns **[Object][59]** nextState+Returns **[Object][55]** nextState### DEFAULT_EXPORT_DATADefault initial `exportData` settings-Type: [Object][59]+Type: [Object][55]#### Properties-- `selectedDataset` **[string][61]** Default: `''`,-- `dataType` **[string][61]** Default: `'csv'`,-- `filtered` **[boolean][62]** Default: `true`,-- `config` **[boolean][62]** deprecated-- `data` **[boolean][62]** used in modal config export. Default: `false`+- `selectedDataset` **[string][57]** Default: `''`,+- `dataType` **[string][57]** Default: `'csv'`,+- `filtered` **[boolean][58]** Default: `true`,+- `config` **[boolean][58]** deprecated+- `data` **[boolean][58]** used in modal config export. Default: `false`### DEFAULT_EXPORT_IMAGEDefault image export config-Type: [Object][59]+Type: [Object][55]#### Properties-- `ratio` **[string][61]** Default: `'SCREEN'`,-- `resolution` **[string][61]** Default: `'ONE_X'`,-- `legend` **[boolean][62]** Default: `false`,-- `imageDataUri` **[string][61]** Default: `''`,-- `exporting` **[boolean][62]** Default: `false`-- `error` **[boolean][62]** Default: `false`+- `ratio` **[string][57]** Default: `'SCREEN'`,+- `resolution` **[string][57]** Default: `'ONE_X'`,+- `legend` **[boolean][58]** Default: `false`,+- `imageDataUri` **[string][57]** Default: `''`,+- `exporting` **[boolean][58]** Default: `false`+- `error` **[boolean][58]** Default: `false`### DEFAULT_MAP_CONTROLS_FEATURESA list of map control visibility and whether is it active.-Type: [Object][59]+Type: [Object][55]#### Properties-- `visibleLayers` **[Object][59]** Default: `{show: true, active: false}`-- `mapLegend` **[Object][59]** Default: `{show: true, active: false}`-- `toggle3d` **[Object][59]** Default: `{show: true}`-- `splitMap` **[Object][59]** Default: `{show: true}`+- `visibleLayers` **[Object][55]** Default: `{show: true, active: false}`+- `mapLegend` **[Object][55]** Default: `{show: true, active: false}`+- `toggle3d` **[Object][55]** Default: `{show: true}`+- `splitMap` **[Object][55]** Default: `{show: true}`### hideExportDropdownUpdaterHide side panel header dropdown, activated by clicking the share link on top of the side panel-- **Action**: [`hideExportDropdown`][63]+- **Action**: [`hideExportDropdown`][59]**Parameters**-- `state` **[Object][59]** `uiState`+- `state` **[Object][55]** `uiState`-Returns **[Object][59]** nextState+Returns **[Object][55]** nextState### INITIAL_UI_STATEDefault initial `uiState`-Type: [Object][59]+Type: [Object][55]#### Properties-- `readOnly` **[boolean][62]** Default: `false`-- `activeSidePanel` **[string][61]** Default: `'layer'`-- `currentModal` **([string][61] | null)** Default: `'addData'`-- `datasetKeyToRemove` **([string][61] | null)** Default: `null`-- `visibleDropdown` **([string][61] | null)** Default: `null`-- `exportImage` **[Object][59]** Default: [`DEFAULT_EXPORT_IMAGE`][9]-- `exportData` **[Object][59]** Default: [`DEFAULT_EXPORT_DATA`][7]-- `mapControls` **[Object][59]** Default: [`DEFAULT_MAP_CONTROLS`][64]-- `activeMapIndex` **[number][65]** defines which map the user clicked on. Default: 0+- `readOnly` **[boolean][58]** Default: `false`+- `activeSidePanel` **[string][57]** Default: `'layer'`+- `currentModal` **([string][57] | null)** Default: `'addData'`+- `datasetKeyToRemove` **([string][57] | null)** Default: `null`+- `visibleDropdown` **([string][57] | null)** Default: `null`+- `exportImage` **[Object][55]** Default: [`DEFAULT_EXPORT_IMAGE`][9]+- `exportData` **[Object][55]** Default: [`DEFAULT_EXPORT_DATA`][7]+- `mapControls` **[Object][55]** Default: [`DEFAULT_MAP_CONTROLS`][60]+- `activeMapIndex` **[number][61]** defines which map the user clicked on. Default: 0### loadFilesErrUpdaterHandles load file error and set fileLoading property to false-- **Action**: [`loadFilesErr`][66]+- **Action**: [`loadFilesErr`][62]**Parameters**- `state`-- `error` **[Object][59]**+- `error` **[Object][55]**- `error.error`-Returns **[Object][59]** nextState+Returns **[Object][55]** nextState### loadFilesUpdaterFired when file loading begin-- **Action**: [`loadFiles`][67]+- **Action**: [`loadFiles`][63]**Parameters**-- `state` **[Object][59]** `uiState`+- `state` **[Object][55]** `uiState`-Returns **[Object][59]** nextState+Returns **[Object][55]** nextState### openDeleteModalUpdaterToggle active map control panel-- **Action**: [`openDeleteModal`][68]+- **Action**: [`openDeleteModal`][64]**Parameters**-- `state` **[Object][59]** `uiState`-- `action` **[Object][59]**- - `action.payload` **[string][61]** dataset id+- `state` **[Object][55]** `uiState`+- `action` **[Object][55]**+ - `action.payload` **[string][57]** dataset id-Returns **[Object][59]** nextState+Returns **[Object][55]** nextState### removeNotificationUpdaterRemove a notification-- **Action**: [`removeNotification`][69]+- **Action**: [`removeNotification`][65]**Parameters**-- `state` **[Object][59]** `uiState`-- `action` **[Object][59]**- - `action.payload` **[String][61]** id of the notification to be removed+- `state` **[Object][55]** `uiState`+- `action` **[Object][55]**+ - `action.payload` **[String][57]** id of the notification to be removed-Returns **[Object][59]** nextState+Returns **[Object][55]** nextState### setExportDataTypeUpdaterSet data format for exporting data-- **Action**: [`setExportDataType`][70]+- **Action**: [`setExportDataType`][66]**Parameters**-- `state` **[Object][59]** `uiState`-- `action` **[Object][59]**- - `action.payload` **[string][61]** one of `'text/csv'`+- `state` **[Object][55]** `uiState`+- `action` **[Object][55]**+ - `action.payload` **[string][57]** one of `'text/csv'`-Returns **[Object][59]** nextState+Returns **[Object][55]** nextState### setExportDataUpdaterWhether to including data in map config, toggle between `true` or `false`-- **Action**: [`setExportData`][71]+- **Action**: [`setExportData`][67]**Parameters**-- `state` **[Object][59]** `uiState`+- `state` **[Object][55]** `uiState`-Returns **[Object][59]** nextState+Returns **[Object][55]** nextState### setExportFilteredUpdaterWhether to export filtered data, `true` or `false`-- **Action**: [`setExportFiltered`][72]+- **Action**: [`setExportFiltered`][68]**Parameters**-- `state` **[Object][59]** `uiState`-- `action` **[Object][59]**- - `action.payload` **[boolean][62]**+- `state` **[Object][55]** `uiState`+- `action` **[Object][55]**+ - `action.payload` **[boolean][58]**-Returns **[Object][59]** nextState+Returns **[Object][55]** nextState### setExportImageDataUriSet `exportImage.setExportImageDataUri` to a image dataUri-- **Action**: [`setExportImageDataUri`][73]+- **Action**: [`setExportImageDataUri`][69]**Parameters**-- `state` **[Object][59]** `uiState`-- `action` **[Object][59]**- - `action.payload` **[string][61]** export image data uri+- `state` **[Object][55]** `uiState`+- `action` **[Object][55]**+ - `action.payload` **[string][57]** export image data uri-Returns **[Object][59]** nextState+Returns **[Object][55]** nextState-### setExportSelectedDatasetUpdater--Set selected dataset for export--- **Action**: [`setExportSelectedDataset`][74]--**Parameters**--- `state` **[Object][59]** `uiState`-- `action` **[Object][59]**- - `action.payload` **[string][61]** dataset id+### setExportImageSetting-Returns **[Object][59]** nextState--### setRatioUpdater--Set `exportImage.ratio`+Set `exportImage.legend` to `true` or `false`-- **Action**: [`setRatio`][75]+- **Action**: [`setExportImageSetting`][70]**Parameters**-- `state` **[Object][59]** `uiState`-- `action` **[Object][59]**- - `action.payload` **[string][61]** one of `'SCREEN'`, `'FOUR_BY_THREE'` and `'SIXTEEN_BY_NINE'`+- `state` **[Object][55]** `uiState`+- `$1` **[Object][55]**+ - `$1.payload`-Returns **[Object][59]** nextState+Returns **[Object][55]** nextState-### setResolutionUpdater+### setExportSelectedDatasetUpdater-Set `exportImage.resolution`+Set selected dataset for export-- **Action**: [`setResolution`][76]+- **Action**: [`setExportSelectedDataset`][71]**Parameters**-- `state` **[Object][59]** `uiState`-- `action` **[Object][59]**- - `action.payload` **[string][61]** one of `'ONE_X'`, `'TWO_X'`+- `state` **[Object][55]** `uiState`+- `action` **[Object][55]**+ - `action.payload` **[string][57]** dataset id-Returns **[Object][59]** nextState+Returns **[Object][55]** nextState### showExportDropdownUpdaterHide and show side panel header dropdown, activated by clicking the share link on top of the side panel-- **Action**: [`showExportDropdown`][77]+- **Action**: [`showExportDropdown`][72]**Parameters**-- `state` **[Object][59]** `uiState`-- `action` **[Object][59]**- - `action.payload` **[string][61]** id of the dropdown+- `state` **[Object][55]** `uiState`+- `action` **[Object][55]**+ - `action.payload` **[string][57]** id of the dropdown-Returns **[Object][59]** nextState+Returns **[Object][55]** nextState### startExportingImageSet `exportImage.exporting` to `true`-- **Action**: [`startExportingImage`][78]--**Parameters**--- `state` **[Object][59]** `uiState`--Returns **[Object][59]** nextState--### toggleLegendUpdater--Set `exportImage.legend` to `true` or `false`--- **Action**: [`toggleLegend`][79]+- **Action**: [`startExportingImage`][73]**Parameters**-- `state` **[Object][59]** `uiState`+- `state` **[Object][55]** `uiState`-Returns **[Object][59]** nextState+Returns **[Object][55]** nextState### toggleMapControlUpdaterToggle active map control panel-- **Action**: [`toggleMapControl`][80]+- **Action**: [`toggleMapControl`][74]**Parameters**-- `state` **[Object][59]** `uiState`-- `action` **[Object][59]** action- - `action.payload` **[string][61]** map control panel id, one of the keys of: [`DEFAULT_MAP_CONTROLS`][64]+- `state` **[Object][55]** `uiState`+- `action` **[Object][55]** action+ - `action.payload` **[string][57]** map control panel id, one of the keys of: [`DEFAULT_MAP_CONTROLS`][60]- `action.payload.panelId`- `action.payload.index` (optional, default `0`)-Returns **[Object][59]** nextState+Returns **[Object][55]** nextState### toggleModalUpdaterShow and hide modal dialog-- **Action**: [`toggleModal`][81]+- **Action**: [`toggleModal`][75]**Parameters**-- `state` **[Object][59]** `uiState`-- `action` **[Object][59]**- - `action.payload` **([string][61] | null)** id of modal to be shown, null to hide modals. One of:- [`DATA_TABLE_ID`][82]- - [`DELETE_DATA_ID`][83]- - [`ADD_DATA_ID`][84]- - [`EXPORT_IMAGE_ID`][85]- - [`EXPORT_DATA_ID`][86]- - [`ADD_MAP_STYLE_ID`][87]+- `state` **[Object][55]** `uiState`+- `action` **[Object][55]**+ - `action.payload` **([string][57] | null)** id of modal to be shown, null to hide modals. One of:- [`DATA_TABLE_ID`][76]+ - [`DELETE_DATA_ID`][77]+ - [`ADD_DATA_ID`][78]+ - [`EXPORT_IMAGE_ID`][79]+ - [`EXPORT_DATA_ID`][80]+ - [`ADD_MAP_STYLE_ID`][81]-Returns **[Object][59]** nextState+Returns **[Object][55]** nextState### toggleSidePanelUpdaterToggle active side panel-- **Action**: [`toggleSidePanel`][88]+- **Action**: [`toggleSidePanel`][82]**Parameters**-- `state` **[Object][59]** `uiState`-- `action` **[Object][59]**- - `action.payload` **([string][61] | null)** id of side panel to be shown, one of `layer`, `filter`, `interaction`, `map`. close side panel if `null`+- `state` **[Object][55]** `uiState`+- `action` **[Object][55]**+ - `action.payload` **([string][57] | null)** id of side panel to be shown, one of `layer`, `filter`, `interaction`, `map`. close side panel if `null`-Returns **[Object][59]** nextState+Returns **[Object][55]** nextState### toggleSplitMapUpdaterHandles toggle map split and reset all map control index to 0-- **Action**: [`toggleSplitMap`][89]+- **Action**: [`toggleSplitMap`][83]**Parameters**- `state`-Returns **[Object][59]** nextState+Returns **[Object][55]** nextState## DEFAULT_EXPORT_HTML-Type: [Object][59]+Type: [Object][55]### Properties-- `exportMapboxAccessToken` **[string][61]** Default: null, this is used when we provide a default mapbox token for users to take advantage of-- `userMapboxToken` **[string][61]** Default: '', mapbox token provided by user through input field+- `exportMapboxAccessToken` **[string][57]** Default: null, this is used when we provide a default mapbox token for users to take advantage of+- `userMapboxToken` **[string][57]** Default: '', mapbox token provided by user through input field## setUserMapboxAccessTokenUpdaterwhether to export a mapbox access to HTML single page-- **Action**: [`setUserMapboxAccessToken`][90]+- **Action**: [`setUserMapboxAccessToken`][84]**Parameters**-- `state` **[Object][59]** `uiState`-- `action` **[Object][59]**- - `action.payload` **[string][61]**+- `state` **[Object][55]** `uiState`+- `action` **[Object][55]**+ - `action.payload` **[string][57]**-Returns **[Object][59]** nextState+Returns **[Object][55]** nextState[1]: #uistateupdaters@@ -503,118 +475,106 @@ Returns **[Object][59]** nextState[32]: #parameters-10-[33]: #setexportselecteddatasetupdater+[33]: #setexportimagesetting[34]: #parameters-11-[35]: #setratioupdater+[35]: #setexportselecteddatasetupdater[36]: #parameters-12-[37]: #setresolutionupdater+[37]: #showexportdropdownupdater[38]: #parameters-13-[39]: #showexportdropdownupdater+[39]: #startexportingimage[40]: #parameters-14-[41]: #startexportingimage+[41]: #togglemapcontrolupdater[42]: #parameters-15-[43]: #togglelegendupdater+[43]: #togglemodalupdater[44]: #parameters-16-[45]: #togglemapcontrolupdater+[45]: #togglesidepanelupdater[46]: #parameters-17-[47]: #togglemodalupdater+[47]: #togglesplitmapupdater[48]: #parameters-18-[49]: #togglesidepanelupdater--[50]: #parameters-19--[51]: #togglesplitmapupdater--[52]: #parameters-20--[53]: #default_export_html--[54]: #properties-4--[55]: #setusermapboxaccesstokenupdater+[49]: #default_export_html-[56]: #parameters-21+[50]: #properties-4-[57]: ../advanced-usage/using-updaters.md+[51]: #setusermapboxaccesstokenupdater-[58]: ../actions/actions.md#addnotification+[52]: #parameters-19-[59]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object+[53]: ../advanced-usage/using-updaters.md-[60]: ../actions/actions.md#cleanupexportimage+[54]: ../actions/actions.md#addnotification-[61]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String+[55]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object-[62]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean+[56]: ../actions/actions.md#cleanupexportimage-[63]: ../actions/actions.md#hideexportdropdown+[57]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String-[64]: #default_map_controls+[58]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean-[65]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number+[59]: ../actions/actions.md#hideexportdropdown-[66]: ../actions/actions.md#loadfileserr+[60]: #default_map_controls-[67]: ../actions/actions.md#loadfiles+[61]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number-[68]: ../actions/actions.md#opendeletemodal+[62]: ../actions/actions.md#loadfileserr-[69]: ../actions/actions.md#removenotification+[63]: ../actions/actions.md#loadfiles-[70]: ../actions/actions.md#setexportdatatype+[64]: ../actions/actions.md#opendeletemodal-[71]: ../actions/actions.md#setexportdata+[65]: ../actions/actions.md#removenotification-[72]: ../actions/actions.md#setexportfiltered+[66]: ../actions/actions.md#setexportdatatype-[73]: ../actions/actions.md#setexportimagedatauri+[67]: ../actions/actions.md#setexportdata-[74]: ../actions/actions.md#setexportselecteddataset+[68]: ../actions/actions.md#setexportfiltered-[75]: ../actions/actions.md#setratio+[69]: ../actions/actions.md#setexportimagedatauri-[76]: ../actions/actions.md#setresolution+[70]: ../actions/actions.md#setexportimagesetting-[77]: ../actions/actions.md#showexportdropdown+[71]: ../actions/actions.md#setexportselecteddataset-[78]: ../actions/actions.md#startexportingimage+[72]: ../actions/actions.md#showexportdropdown-[79]: ../actions/actions.md#togglelegend+[73]: ../actions/actions.md#startexportingimage-[80]: ../actions/actions.md#togglemapcontrol+[74]: ../actions/actions.md#togglemapcontrol-[81]: ../actions/actions.md#togglemodal+[75]: ../actions/actions.md#togglemodal-[82]: ../constants/default-settings.md#data_table_id+[76]: ../constants/default-settings.md#data_table_id-[83]: ../constants/default-settings.md#delete_data_id+[77]: ../constants/default-settings.md#delete_data_id-[84]: ../constants/default-settings.md#add_data_id+[78]: ../constants/default-settings.md#add_data_id-[85]: ../constants/default-settings.md#export_image_id+[79]: ../constants/default-settings.md#export_image_id-[86]: ../constants/default-settings.md#export_data_id+[80]: ../constants/default-settings.md#export_data_id-[87]: ../constants/default-settings.md#add_map_style_id+[81]: ../constants/default-settings.md#add_map_style_id-[88]: ../actions/actions.md#togglesidepanel+[82]: ../actions/actions.md#togglesidepanel-[89]: ../actions/actions.md#togglesplitmap+[83]: ../actions/actions.md#togglesplitmap-[90]: ../actions/actions.md#setusermapboxaccesstoken+[84]: ../actions/actions.md#setusermapboxaccesstokendiff --git a/docs/api-reference/reducers/vis-state.md b/docs/api-reference/reducers/vis-state.mdindex 1d8ca28c1..d51bb329e 100644--- a/docs/api-reference/reducers/vis-state.md+++ b/docs/api-reference/reducers/vis-state.md@@ -5,39 +5,41 @@- [visStateUpdaters][1]- [addFilterUpdater][3]- [addLayerUpdater][5]- - [enlargeFilterUpdater][7]- - [INITIAL_VIS_STATE][9]- - [interactionConfigChangeUpdater][11]- - [layerClickUpdater][13]- - [layerHoverUpdater][15]- - [layerTypeChangeUpdater][17]- - [layerVisConfigChangeUpdater][19]- - [layerVisualChannelChangeUpdater][21]- - [loadFilesErrUpdater][23]- - [loadFilesUpdater][25]- - [mapClickUpdater][27]- - [receiveMapConfigUpdater][29]- - [removeDatasetUpdater][31]- - [removeFilterUpdater][33]- - [removeLayerUpdater][35]- - [reorderLayerUpdater][37]- - [resetMapConfigUpdater][39]- - [setFilterPlotUpdater][41]- - [setFilterUpdater][43]- - [showDatasetTableUpdater][45]- - [toggleFilterAnimationUpdater][47]- - [toggleLayerForMapUpdater][49]- - [toggleSplitMapUpdater][51]- - [updateAnimationTimeUpdater][53]- - [updateFilterAnimationSpeedUpdater][55]- - [updateLayerAnimationSpeedUpdater][57]- - [updateLayerBlendingUpdater][59]- - [updateVisDataUpdater][61]+ - [applyCPUFilterUpdater][7]+ - [enlargeFilterUpdater][9]+ - [INITIAL_VIS_STATE][11]+ - [interactionConfigChangeUpdater][13]+ - [layerClickUpdater][15]+ - [layerHoverUpdater][17]+ - [layerTypeChangeUpdater][19]+ - [layerVisConfigChangeUpdater][21]+ - [layerVisualChannelChangeUpdater][23]+ - [loadFilesErrUpdater][25]+ - [loadFilesUpdater][27]+ - [mapClickUpdater][29]+ - [receiveMapConfigUpdater][31]+ - [removeDatasetUpdater][33]+ - [removeFilterUpdater][35]+ - [removeLayerUpdater][37]+ - [reorderLayerUpdater][39]+ - [resetMapConfigUpdater][41]+ - [setFilterPlotUpdater][43]+ - [setFilterUpdater][45]+ - [setMapInfoUpdater][47]+ - [showDatasetTableUpdater][49]+ - [toggleFilterAnimationUpdater][51]+ - [toggleLayerForMapUpdater][53]+ - [toggleSplitMapUpdater][55]+ - [updateAnimationTimeUpdater][57]+ - [updateFilterAnimationSpeedUpdater][59]+ - [updateLayerAnimationSpeedUpdater][61]+ - [updateLayerBlendingUpdater][63]+ - [updateVisDataUpdater][65]## visStateUpdatersUpdaters for `visState` reducer. Can be used in your root reducer to directly modify kepler.gl's state.-Read more about [Using updaters][63]+Read more about [Using updaters][67]**Examples**@@ -76,454 +78,482 @@ export default composedReducer;Add a new filter-- **Action**: [`addFilter`][64]+- **Action**: [`addFilter`][68]**Parameters**-- `state` **[Object][65]** `visState`-- `action` **[Object][65]** action- - `action.dataId` **[string][66]** dataset `id` this new filter is associated with+- `state` **[Object][69]** `visState`+- `action` **[Object][69]** action+ - `action.dataId` **[string][70]** dataset `id` this new filter is associated with-Returns **[Object][65]** nextState+Returns **[Object][69]** nextState### addLayerUpdaterAdd a new layer-- **Action**: [`addLayer`][67]+- **Action**: [`addLayer`][71]**Parameters**-- `state` **[Object][65]** `visState`-- `action` **[Object][65]** action- - `action.props` **[Object][65]** new layer props+- `state` **[Object][69]** `visState`+- `action` **[Object][69]** action+ - `action.props` **[Object][69]** new layer props-Returns **[Object][65]** nextState+Returns **[Object][69]** nextState++### applyCPUFilterUpdater++When select dataset for export, apply cpu filter to selected dataset++- **Action**: [`applyCPUFilter`][72]++**Parameters**++- `state` **[Object][69]** `visState`+- `action` **[Object][69]**+ - `action.dataId` **[string][70]** dataset id++Returns **[Object][69]** nextState### enlargeFilterUpdaterShow larger time filter at bottom for time playback (apply to time filter only)-- **Action**: [`enlargeFilter`][68]+- **Action**: [`enlargeFilter`][73]**Parameters**-- `state` **[Object][65]** `visState`-- `action` **[Object][65]** action- - `action.idx` **[Number][69]** index of filter to enlarge+- `state` **[Object][69]** `visState`+- `action` **[Object][69]** action+ - `action.idx` **[Number][74]** index of filter to enlarge-Returns **[Object][65]** nextState+Returns **[Object][69]** nextState### INITIAL_VIS_STATEDefault initial `visState`-Type: [Object][65]+Type: [Object][69]#### Properties-- `layers` **[Array][70]**-- `layerData` **[Array][70]**-- `layerToBeMerged` **[Array][70]**-- `layerOrder` **[Array][70]**-- `filters` **[Array][70]**-- `filterToBeMerged` **[Array][70]**-- `datasets` **[Array][70]**-- `editingDataset` **[string][66]**-- `interactionConfig` **[Object][65]**-- `interactionToBeMerged` **[Object][65]**-- `layerBlending` **[string][66]**-- `hoverInfo` **[Object][65]**-- `clicked` **[Object][65]**-- `mousePos` **[Object][65]**-- `splitMaps` **[Array][70]** a list of objects of layer availabilities and visibilities for each map-- `layerClasses` **[Object][65]**-- `animationConfig` **[Object][65]**-- `editor` **[Object][65]**+- `layers` **[Array][75]**+- `layerData` **[Array][75]**+- `layerToBeMerged` **[Array][75]**+- `layerOrder` **[Array][75]**+- `filters` **[Array][75]**+- `filterToBeMerged` **[Array][75]**+- `datasets` **[Array][75]**+- `editingDataset` **[string][70]**+- `interactionConfig` **[Object][69]**+- `interactionToBeMerged` **[Object][69]**+- `layerBlending` **[string][70]**+- `hoverInfo` **[Object][69]**+- `clicked` **[Object][69]**+- `mousePos` **[Object][69]**+- `splitMaps` **[Array][75]** a list of objects of layer availabilities and visibilities for each map+- `layerClasses` **[Object][69]**+- `animationConfig` **[Object][69]**+- `editor` **[Object][69]**### interactionConfigChangeUpdaterUpdate `interactionConfig`-- **Action**: [`interactionConfigChange`][71]+- **Action**: [`interactionConfigChange`][76]**Parameters**-- `state` **[Object][65]** `visState`-- `action` **[Object][65]** action- - `action.config` **[Object][65]** new config as key value map: `{tooltip: {enabled: true}}`+- `state` **[Object][69]** `visState`+- `action` **[Object][69]** action+ - `action.config` **[Object][69]** new config as key value map: `{tooltip: {enabled: true}}`-Returns **[Object][65]** nextState+Returns **[Object][69]** nextState### layerClickUpdaterTrigger layer click event with clicked object-- **Action**: [`onLayerClick`][72]+- **Action**: [`onLayerClick`][77]**Parameters**-- `state` **[Object][65]** `visState`-- `action` **[Object][65]** action- - `action.info` **[Object][65]** Object clicked, returned by deck.gl+- `state` **[Object][69]** `visState`+- `action` **[Object][69]** action+ - `action.info` **[Object][69]** Object clicked, returned by deck.gl-Returns **[Object][65]** nextState+Returns **[Object][69]** nextState### layerHoverUpdaterTrigger layer hover event with hovered object-- **Action**: [`onLayerHover`][73]+- **Action**: [`onLayerHover`][78]**Parameters**-- `state` **[Object][65]** `visState`-- `action` **[Object][65]** action- - `action.info` **[Object][65]** Object hovered, returned by deck.gl+- `state` **[Object][69]** `visState`+- `action` **[Object][69]** action+ - `action.info` **[Object][69]** Object hovered, returned by deck.gl-Returns **[Object][65]** nextState+Returns **[Object][69]** nextState### layerTypeChangeUpdaterUpdate layer type. Previews layer config will be copied if applicable.-- **Action**: [`layerTypeChange`][74]+- **Action**: [`layerTypeChange`][79]**Parameters**-- `state` **[Object][65]** `visState`-- `action` **[Object][65]** action- - `action.oldLayer` **[Object][65]** layer to be updated- - `action.newType` **[string][66]** new type+- `state` **[Object][69]** `visState`+- `action` **[Object][69]** action+ - `action.oldLayer` **[Object][69]** layer to be updated+ - `action.newType` **[string][70]** new type-Returns **[Object][65]** nextState+Returns **[Object][69]** nextState### layerVisConfigChangeUpdaterUpdate layer `visConfig`-- **Action**: [`layerVisConfigChange`][75]+- **Action**: [`layerVisConfigChange`][80]**Parameters**-- `state` **[Object][65]** `visState`-- `action` **[Object][65]** action- - `action.oldLayer` **[Object][65]** layer to be updated- - `action.newVisConfig` **[Object][65]** new visConfig as a key value map: e.g. `{opacity: 0.8}`+- `state` **[Object][69]** `visState`+- `action` **[Object][69]** action+ - `action.oldLayer` **[Object][69]** layer to be updated+ - `action.newVisConfig` **[Object][69]** new visConfig as a key value map: e.g. `{opacity: 0.8}`-Returns **[Object][65]** nextState+Returns **[Object][69]** nextState### layerVisualChannelChangeUpdaterUpdate layer visual channel-- **Action**: [`layerVisualChannelConfigChange`][76]+- **Action**: [`layerVisualChannelConfigChange`][81]**Parameters**-- `state` **[Object][65]** `visState`-- `action` **[Object][65]** action- - `action.oldLayer` **[Object][65]** layer to be updated- - `action.newConfig` **[Object][65]** new visual channel config- - `action.channel` **[string][66]** channel to be updated+- `state` **[Object][69]** `visState`+- `action` **[Object][69]** action+ - `action.oldLayer` **[Object][69]** layer to be updated+ - `action.newConfig` **[Object][69]** new visual channel config+ - `action.channel` **[string][70]** channel to be updated-Returns **[Object][65]** nextState+Returns **[Object][69]** nextState### loadFilesErrUpdaterTrigger loading file error-- **Action**: [`loadFilesErr`][77]+- **Action**: [`loadFilesErr`][82]**Parameters**-- `state` **[Object][65]** `visState`-- `action` **[Object][65]** action+- `state` **[Object][69]** `visState`+- `action` **[Object][69]** action- `action.error` **any**-Returns **[Object][65]** nextState+Returns **[Object][69]** nextState### loadFilesUpdaterTrigger file loading dispatch `addDataToMap` if succeed, or `loadFilesErr` if failed-- **Action**: [`loadFiles`][78]+- **Action**: [`loadFiles`][83]**Parameters**-- `state` **[Object][65]** `visState`-- `action` **[Object][65]** action- - `action.files` **[Array][70]<[Object][65]>** array of fileblob+- `state` **[Object][69]** `visState`+- `action` **[Object][69]** action+ - `action.files` **[Array][75]<[Object][69]>** array of fileblob-Returns **[Object][65]** nextState+Returns **[Object][69]** nextState### mapClickUpdaterTrigger map click event, unselect clicked object-- **Action**: [`onMapClick`][79]+- **Action**: [`onMapClick`][84]**Parameters**-- `state` **[Object][65]** `visState`+- `state` **[Object][69]** `visState`-Returns **[Object][65]** nextState+Returns **[Object][69]** nextState### receiveMapConfigUpdaterPropagate `visState` reducer with a new configuration. Current config will be override.-- **Action**: [`receiveMapConfig`][80]+- **Action**: [`receiveMapConfig`][85]**Parameters**-- `state` **[Object][65]** `visState`-- `action` **[Object][65]** action- - `action.payload` **[Object][65]** map config to be propagated- - `action.payload.config` **[Object][65]** map config to be propagated- - `action.payload.option` **[Object][65]** {keepExistingConfig: true | false}+- `state` **[Object][69]** `visState`+- `action` **[Object][69]** action+ - `action.payload` **[Object][69]** map config to be propagated+ - `action.payload.config` **[Object][69]** map config to be propagated+ - `action.payload.option` **[Object][69]** {keepExistingConfig: true | false}- `action.payload.config` (optional, default `{}`)- `action.payload.options` (optional, default `{}`)-Returns **[Object][65]** nextState+Returns **[Object][69]** nextState### removeDatasetUpdaterRemove a dataset and all layers, filters, tooltip configs that based on it-- **Action**: [`removeDataset`][81]+- **Action**: [`removeDataset`][86]**Parameters**-- `state` **[Object][65]** `visState`-- `action` **[Object][65]** action- - `action.key` **[string][66]** dataset id+- `state` **[Object][69]** `visState`+- `action` **[Object][69]** action+ - `action.key` **[string][70]** dataset id-Returns **[Object][65]** nextState+Returns **[Object][69]** nextState### removeFilterUpdaterRemove a filter-- **Action**: [`removeFilter`][82]+- **Action**: [`removeFilter`][87]**Parameters**-- `state` **[Object][65]** `visState`-- `action` **[Object][65]** action- - `action.idx` **[Number][69]** index of filter to b e removed+- `state` **[Object][69]** `visState`+- `action` **[Object][69]** action+ - `action.idx` **[Number][74]** index of filter to b e removed-Returns **[Object][65]** nextState+Returns **[Object][69]** nextState### removeLayerUpdaterremove layer-- **Action**: [`removeLayer`][83]+- **Action**: [`removeLayer`][88]**Parameters**-- `state` **[Object][65]** `visState`-- `action` **[Object][65]** action- - `action.idx` **[Number][69]** index of layer to b e removed+- `state` **[Object][69]** `visState`+- `action` **[Object][69]** action+ - `action.idx` **[Number][74]** index of layer to b e removed-Returns **[Object][65]** nextState+Returns **[Object][69]** nextState### reorderLayerUpdaterReorder layer-- **Action**: [`reorderLayer`][84]+- **Action**: [`reorderLayer`][89]**Parameters**-- `state` **[Object][65]** `visState`-- `action` **[Object][65]** action- - `action.order` **[Array][70]<[Number][69]>** an array of layer indexes+- `state` **[Object][69]** `visState`+- `action` **[Object][69]** action+ - `action.order` **[Array][75]<[Number][74]>** an array of layer indexes-Returns **[Object][65]** nextState+Returns **[Object][69]** nextState### resetMapConfigUpdaterreset visState to initial State-- **Action**: [`resetMapConfig`][85]+- **Action**: [`resetMapConfig`][90]**Parameters**-- `state` **[Object][65]** `visState`+- `state` **[Object][69]** `visState`-Returns **[Object][65]** nextState+Returns **[Object][69]** nextState### setFilterPlotUpdaterSet the property of a filter plot-- **Action**: [`setFilterPlot`][86]+- **Action**: [`setFilterPlot`][91]**Parameters**-- `state` **[Object][65]** `visState`-- `action` **[Object][65]** action- - `action.idx` **[Number][69]**- - `action.newProp` **[Object][65]** key value mapping of new prop `{yAxis: 'histogram'}`+- `state` **[Object][69]** `visState`+- `action` **[Object][69]** action+ - `action.idx` **[Number][74]**+ - `action.newProp` **[Object][69]** key value mapping of new prop `{yAxis: 'histogram'}`-Returns **[Object][65]** nextState+Returns **[Object][69]** nextState### setFilterUpdaterUpdate filter property-- **Action**: [`setFilter`][87]+- **Action**: [`setFilter`][92]**Parameters**-- `state` **[Object][65]** `visState`-- `action` **[Object][65]** action- - `action.idx` **[Number][69]** `idx` of filter to be updated- - `action.prop` **[string][66]** `prop` of filter, e,g, `dataId`, `name`, `value`+- `state` **[Object][69]** `visState`+- `action` **[Object][69]** action+ - `action.idx` **[Number][74]** `idx` of filter to be updated+ - `action.prop` **[string][70]** `prop` of filter, e,g, `dataId`, `name`, `value`- `action.value` **any** new value-- `datasetId` **[string][66]** used when updating a prop (dataId, name) that can be linked to multiple datasets+- `datasetId` **[string][70]** used when updating a prop (dataId, name) that can be linked to multiple datasets++Returns **[Object][69]** nextState++### setMapInfoUpdater++User input to update the info of the map-Returns **[Object][65]** nextState+- **Action**: [`setMapInfo`][93]++**Parameters**++- `state` **[Object][69]** `visState`+- `action` **[Object][69]** action+ - `action.info` **[Object][69]** {title: 'hello'}++Returns **[Object][69]** nextState### showDatasetTableUpdaterDisplay dataset table in a modal-- **Action**: [`showDatasetTable`][88]+- **Action**: [`showDatasetTable`][94]**Parameters**-- `state` **[Object][65]** `visState`-- `action` **[Object][65]** action- - `action.dataId` **[string][66]** dataset id to show in table+- `state` **[Object][69]** `visState`+- `action` **[Object][69]** action+ - `action.dataId` **[string][70]** dataset id to show in table-Returns **[Object][65]** nextState+Returns **[Object][69]** nextState### toggleFilterAnimationUpdaterStart and end filter animation-- **Action**: [`toggleFilterAnimation`][89]+- **Action**: [`toggleFilterAnimation`][95]**Parameters**-- `state` **[Object][65]** `visState`-- `action` **[Object][65]** action- - `action.idx` **[Number][69]** idx of filter+- `state` **[Object][69]** `visState`+- `action` **[Object][69]** action+ - `action.idx` **[Number][74]** idx of filter-Returns **[Object][65]** nextState+Returns **[Object][69]** nextState### toggleLayerForMapUpdaterToggle visibility of a layer in a split map-- **Action**: [`toggleLayerForMap`][90]+- **Action**: [`toggleLayerForMap`][96]**Parameters**-- `state` **[Object][65]**-- `action` **[Object][65]**- - `action.mapIndex` **[Number][69]** index of the split map- - `action.layerId` **[string][66]** id of the layer+- `state` **[Object][69]**+- `action` **[Object][69]**+ - `action.mapIndex` **[Number][74]** index of the split map+ - `action.layerId` **[string][70]** id of the layer-Returns **[Object][65]** nextState+Returns **[Object][69]** nextState### toggleSplitMapUpdaterToggle visibility of a layer for a split map-- **Action**: [`toggleSplitMap`][91]+- **Action**: [`toggleSplitMap`][97]**Parameters**-- `state` **[Object][65]** `visState`-- `action` **[Object][65]** action- - `action.payload` **([Number][69] \| [undefined][92])** index of the split map+- `state` **[Object][69]** `visState`+- `action` **[Object][69]** action+ - `action.payload` **([Number][74] \| [undefined][98])** index of the split map-Returns **[Object][65]** nextState+Returns **[Object][69]** nextState### updateAnimationTimeUpdaterReset animation config current time to a specified value-- **Action**: [`updateAnimationTime`][93]+- **Action**: [`updateAnimationTime`][99]**Parameters**-- `state` **[Object][65]** `visState`-- `action` **[Object][65]** action- - `action.value` **[Number][69]** the value current time will be set to+- `state` **[Object][69]** `visState`+- `action` **[Object][69]** action+ - `action.value` **[Number][74]** the value current time will be set to-Returns **[Object][65]** nextState+Returns **[Object][69]** nextState### updateFilterAnimationSpeedUpdaterChange filter animation speed-- **Action**: [`updateFilterAnimationSpeed`][94]+- **Action**: [`updateFilterAnimationSpeed`][100]**Parameters**-- `state` **[Object][65]** `visState`-- `action` **[Object][65]** action- - `action.idx` **[Number][69]** `idx` of filter- - `action.speed` **[Number][69]** `speed` to change it to. `speed` is a multiplier+- `state` **[Object][69]** `visState`+- `action` **[Object][69]** action+ - `action.idx` **[Number][74]** `idx` of filter+ - `action.speed` **[Number][74]** `speed` to change it to. `speed` is a multiplier-Returns **[Object][65]** nextState+Returns **[Object][69]** nextState### updateLayerAnimationSpeedUpdaterUpdate animation speed with the vertical speed slider-- **Action**: [`updateLayerAnimationSpeed`][95]+- **Action**: [`updateLayerAnimationSpeed`][101]**Parameters**-- `state` **[Object][65]** `visState`-- `action` **[Object][65]** action- - `action.speed` **[Number][69]** the updated speed of the animation+- `state` **[Object][69]** `visState`+- `action` **[Object][69]** action+ - `action.speed` **[Number][74]** the updated speed of the animation-Returns **[Object][65]** nextState+Returns **[Object][69]** nextState### updateLayerBlendingUpdaterupdate layer blending mode-- **Action**: [`updateLayerBlending`][96]+- **Action**: [`updateLayerBlending`][102]**Parameters**-- `state` **[Object][65]** `visState`-- `action` **[Object][65]** action- - `action.mode` **[string][66]** one of `additive`, `normal` and `subtractive`+- `state` **[Object][69]** `visState`+- `action` **[Object][69]** action+ - `action.mode` **[string][70]** one of `additive`, `normal` and `subtractive`-Returns **[Object][65]** nextState+Returns **[Object][69]** nextState### updateVisDataUpdaterAdd new dataset to `visState`, with option to load a map config along with the datasets-- **Action**: [`updateVisData`][97]+- **Action**: [`updateVisData`][103]**Parameters**-- `state` **[Object][65]** `visState`-- `action` **[Object][65]** action- - `action.datasets` **([Array][70]<[Object][65]> | [Object][65])** **\*required** datasets can be a dataset or an array of datasets+- `state` **[Object][69]** `visState`+- `action` **[Object][69]** action+ - `action.datasets` **([Array][75]<[Object][69]> | [Object][69])** **\*required** datasets can be a dataset or an array of datasetsEach dataset object needs to have `info` and `data` property.- - `action.datasets.info` **[Object][65]** \-info of a dataset- - `action.datasets.info.id` **[string][66]** id of this dataset. If config is defined, `id` should matches the `dataId` in config.- - `action.datasets.info.label` **[string][66]** A display name of this dataset- - `action.datasets.data` **[Object][65]** **\*required** The data object, in a tabular format with 2 properties `fields` and `rows`- - `action.datasets.data.fields` **[Array][70]<[Object][65]>** **\*required** Array of fields,- - `action.datasets.data.fields.name` **[string][66]** **\*required** Name of the field,- - `action.datasets.data.rows` **[Array][70]<[Array][70]>** **\*required** Array of rows, in a tabular format with `fields` and `rows`- - `action.options` **[Object][65]** option object `{centerMap: true, keepExistingConfig: false}`- - `action.config` **[Object][65]** map config--Returns **[Object][65]** nextState+ - `action.datasets.info` **[Object][69]** \-info of a dataset+ - `action.datasets.info.id` **[string][70]** id of this dataset. If config is defined, `id` should matches the `dataId` in config.+ - `action.datasets.info.label` **[string][70]** A display name of this dataset+ - `action.datasets.data` **[Object][69]** **\*required** The data object, in a tabular format with 2 properties `fields` and `rows`+ - `action.datasets.data.fields` **[Array][75]<[Object][69]>** **\*required** Array of fields,+ - `action.datasets.data.fields.name` **[string][70]** **\*required** Name of the field,+ - `action.datasets.data.rows` **[Array][75]<[Array][75]>** **\*required** Array of rows, in a tabular format with `fields` and `rows`+ - `action.options` **[Object][69]** option object `{centerMap: true, keepExistingConfig: false}`+ - `action.config` **[Object][69]** map config++Returns **[Object][69]** nextState[1]: #visstateupdaters@@ -537,184 +567,196 @@ Returns **[Object][65]** nextState[6]: #parameters-1-[7]: #enlargefilterupdater+[7]: #applycpufilterupdater[8]: #parameters-2-[9]: #initial_vis_state+[9]: #enlargefilterupdater-[10]: #properties+[10]: #parameters-3-[11]: #interactionconfigchangeupdater+[11]: #initial_vis_state-[12]: #parameters-3+[12]: #properties-[13]: #layerclickupdater+[13]: #interactionconfigchangeupdater[14]: #parameters-4-[15]: #layerhoverupdater+[15]: #layerclickupdater[16]: #parameters-5-[17]: #layertypechangeupdater+[17]: #layerhoverupdater[18]: #parameters-6-[19]: #layervisconfigchangeupdater+[19]: #layertypechangeupdater[20]: #parameters-7-[21]: #layervisualchannelchangeupdater+[21]: #layervisconfigchangeupdater[22]: #parameters-8-[23]: #loadfileserrupdater+[23]: #layervisualchannelchangeupdater[24]: #parameters-9-[25]: #loadfilesupdater+[25]: #loadfileserrupdater[26]: #parameters-10-[27]: #mapclickupdater+[27]: #loadfilesupdater[28]: #parameters-11-[29]: #receivemapconfigupdater+[29]: #mapclickupdater[30]: #parameters-12-[31]: #removedatasetupdater+[31]: #receivemapconfigupdater[32]: #parameters-13-[33]: #removefilterupdater+[33]: #removedatasetupdater[34]: #parameters-14-[35]: #removelayerupdater+[35]: #removefilterupdater[36]: #parameters-15-[37]: #reorderlayerupdater+[37]: #removelayerupdater[38]: #parameters-16-[39]: #resetmapconfigupdater+[39]: #reorderlayerupdater[40]: #parameters-17-[41]: #setfilterplotupdater+[41]: #resetmapconfigupdater[42]: #parameters-18-[43]: #setfilterupdater+[43]: #setfilterplotupdater[44]: #parameters-19-[45]: #showdatasettableupdater+[45]: #setfilterupdater[46]: #parameters-20-[47]: #togglefilteranimationupdater+[47]: #setmapinfoupdater[48]: #parameters-21-[49]: #togglelayerformapupdater+[49]: #showdatasettableupdater[50]: #parameters-22-[51]: #togglesplitmapupdater+[51]: #togglefilteranimationupdater[52]: #parameters-23-[53]: #updateanimationtimeupdater+[53]: #togglelayerformapupdater[54]: #parameters-24-[55]: #updatefilteranimationspeedupdater+[55]: #togglesplitmapupdater[56]: #parameters-25-[57]: #updatelayeranimationspeedupdater+[57]: #updateanimationtimeupdater[58]: #parameters-26-[59]: #updatelayerblendingupdater+[59]: #updatefilteranimationspeedupdater[60]: #parameters-27-[61]: #updatevisdataupdater+[61]: #updatelayeranimationspeedupdater[62]: #parameters-28-[63]: ../advanced-usage/using-updaters.md+[63]: #updatelayerblendingupdater++[64]: #parameters-29++[65]: #updatevisdataupdater++[66]: #parameters-30++[67]: ../advanced-usage/using-updaters.md++[68]: ../actions/actions.md#addfilter++[69]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object-[64]: ../actions/actions.md#addfilter+[70]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String-[65]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object+[71]: ../actions/actions.md#addlayer-[66]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String+[72]: ../actions/actions.md#applycpufilter-[67]: ../actions/actions.md#addlayer+[73]: ../actions/actions.md#enlargefilter-[68]: ../actions/actions.md#enlargefilter+[74]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number-[69]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number+[75]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array-[70]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array+[76]: ../actions/actions.md#interactionconfigchange-[71]: ../actions/actions.md#interactionconfigchange+[77]: ../actions/actions.md#onlayerclick-[72]: ../actions/actions.md#onlayerclick+[78]: ../actions/actions.md#onlayerhover-[73]: ../actions/actions.md#onlayerhover+[79]: ../actions/actions.md#layertypechange-[74]: ../actions/actions.md#layertypechange+[80]: ../actions/actions.md#layervisconfigchange-[75]: ../actions/actions.md#layervisconfigchange+[81]: ../actions/actions.md#layervisualchannelconfigchange-[76]: ../actions/actions.md#layervisualchannelconfigchange+[82]: ../actions/actions.md#loadfileserr-[77]: ../actions/actions.md#loadfileserr+[83]: ../actions/actions.md#loadfiles-[78]: ../actions/actions.md#loadfiles+[84]: ../actions/actions.md#onmapclick-[79]: ../actions/actions.md#onmapclick+[85]: ../actions/actions.md#receivemapconfig-[80]: ../actions/actions.md#receivemapconfig+[86]: ../actions/actions.md#removedataset-[81]: ../actions/actions.md#removedataset+[87]: ../actions/actions.md#removefilter-[82]: ../actions/actions.md#removefilter+[88]: ../actions/actions.md#removelayer-[83]: ../actions/actions.md#removelayer+[89]: ../actions/actions.md#reorderlayer-[84]: ../actions/actions.md#reorderlayer+[90]: ../actions/actions.md#resetmapconfig-[85]: ../actions/actions.md#resetmapconfig+[91]: ../actions/actions.md#setfilterplot-[86]: ../actions/actions.md#setfilterplot+[92]: ../actions/actions.md#setfilter-[87]: ../actions/actions.md#setfilter+[93]: ../actions/actions.md#setmapinfo-[88]: ../actions/actions.md#showdatasettable+[94]: ../actions/actions.md#showdatasettable-[89]: ../actions/actions.md#togglefilteranimation+[95]: ../actions/actions.md#togglefilteranimation-[90]: ../actions/actions.md#togglelayerformap+[96]: ../actions/actions.md#togglelayerformap-[91]: ../actions/actions.md#togglesplitmap+[97]: ../actions/actions.md#togglesplitmap-[92]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined+[98]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined-[93]: ../actions/actions.md#updateanimationtime+[99]: ../actions/actions.md#updateanimationtime-[94]: ../actions/actions.md#updatefilteranimationspeed+[100]: ../actions/actions.md#updatefilteranimationspeed-[95]: ../actions/actions.md#updatelayeranimationspeed+[101]: ../actions/actions.md#updatelayeranimationspeed-[96]: ../actions/actions.md#updatelayerblending+[102]: ../actions/actions.md#updatelayerblending-[97]: ../actions/actions.md#updatevisdata+[103]: ../actions/actions.md#updatevisdatadiff --git a/examples/custom-reducer/package.json b/examples/custom-reducer/package.jsonindex 6512d8d39..befcd1095 100644--- a/examples/custom-reducer/package.json+++ b/examples/custom-reducer/package.json@@ -5,7 +5,7 @@},"dependencies": {"global": "^4.3.0",- "kepler.gl": "^1.1.13",+ "kepler.gl": "^2.0.0","react": "^16.8.4","react-dom": "^16.8.4","react-palm": "^3.1.2",@@ -46,4 +46,4 @@"webpack-hot-middleware": "^2.24.3","webpack-stats-plugin": "^0.2.1"}-}+}\ No newline at end of filediff --git a/examples/custom-theme/package.json b/examples/custom-theme/package.jsonindex 702b63c3a..83d6a473a 100644--- a/examples/custom-theme/package.json+++ b/examples/custom-theme/package.json@@ -5,7 +5,7 @@},"dependencies": {"global": "^4.3.0",- "kepler.gl": "^1.1.13",+ "kepler.gl": "^2.0.0","react": "^16.8.4","react-dom": "^16.8.4","react-palm": "^3.1.2",@@ -47,4 +47,4 @@"webpack-hot-middleware": "^2.24.3","webpack-stats-plugin": "^0.2.1"}-}+}\ No newline at end of filediff --git a/examples/demo-app/package.json b/examples/demo-app/package.jsonindex b7c0588bf..95a870456 100644--- a/examples/demo-app/package.json+++ b/examples/demo-app/package.json@@ -4,13 +4,15 @@"start-prod": "webpack-dev-server -p --progress --hot --open","start-local": "webpack-dev-server --mode development --env.es6 --progress --hot --open","start-local-deck": "webpack-dev-server --mode development --env.es6 --env.deck --progress --hot --open",- "start-local-deck-src": "webpack-dev-server --mode development --env.es6 --env.deck_src --progress --hot --open"+ "start-local-deck-src": "webpack-dev-server --mode development --env.es6 --env.deck_src --progress --hot --open",+ "start-local-https": "webpack-dev-server --mode development --https --env.es6 --progress --hot --open"},"dependencies": {+ "@carto/toolkit": "0.0.1-rc.13","d3-request": "^1.0.6","dropbox": "^4.0.12","global": "^4.3.0",- "kepler.gl": "^1.1.13",+ "kepler.gl": "^2.0.0","lodash.debounce": "^4.0.8","lodash.get": "^4.4.2","react": "^16.8.4",@@ -58,4 +60,4 @@"webpack-hot-middleware": "^2.24.3","webpack-stats-plugin": "^0.2.1"}-}+}\ No newline at end of filediff --git a/examples/demo-app/src/actions.js b/examples/demo-app/src/actions.jsindex 6a7630dbd..338f3dba4 100644--- a/examples/demo-app/src/actions.js+++ b/examples/demo-app/src/actions.js@@ -27,12 +27,10 @@ import {LOADING_SAMPLE_LIST_ERROR_MESSAGE,MAP_CONFIG_URL} from './constants/default-settings';-import {LOADING_METHODS_NAMES} from './constants/default-settings';-import {parseUri, getMapPermalink} from './utils/url';+import {parseUri} from './utils/url';// CONSTANTSexport const INIT = 'INIT';-export const SET_LOADING_METHOD = 'SET_LOADING_METHOD';export const LOAD_REMOTE_RESOURCE_SUCCESS = 'LOAD_REMOTE_RESOURCE_SUCCESS';export const LOAD_REMOTE_RESOURCE_ERROR = 'LOAD_REMOTE_RESOURCE_ERROR';export const LOAD_MAP_SAMPLE_FILE = 'LOAD_MAP_SAMPLE_FILE';@@ -49,32 +47,6 @@ export function initApp() {};}-/**- * this method set the current loading method- * @param {string} method the string id for the loading method to use- * @returns {{type: string, method: *}}- */-export function setLoadingMethod(method) {- return {- type: SET_LOADING_METHOD,- method- };-}--/**- * this action is triggered when user switches between load modal tabs- * @param {string} method- * @returns {Function}- */-export function switchToLoadingMethod(method) {- return (dispatch, getState) => {- dispatch(setLoadingMethod(method));- if (method === LOADING_METHODS_NAMES.sample && getState().demo.app.sampleMaps.length === 0) {- dispatch(loadSampleConfigurations());- }- };-}-export function loadRemoteResourceSuccess(response, config, options) {return {type: LOAD_REMOTE_RESOURCE_SUCCESS,@@ -106,15 +78,30 @@ export function setLoadingMapStatus(isMapLoading) {};}-export function onExportFileSuccess({response = {}, provider}) {+/**+ * Actions passed to kepler.gl, called+ *+ * Note: exportFile is called on both saving and sharing+ *+ * @param {*} param0+ */+export function onExportFileSuccess({response = {}, provider, options}) {return dispatch => {- // TODO: a more generic way to generate responseUrl- if (response.url) {- const responseUrl = provider.getMapPermalink- ? provider.getMapPermalink(response.url, false)- : getMapPermalink(response.url, false);+ // if isPublic is true, use share Url+ if (options.isPublic && provider.getShareUrl) {+ dispatch(push(provider.getShareUrl(false)));+ } else if (!options.isPublic && provider.getMapUrl) {+ // if save private map to storage, use map url+ dispatch(push(provider.getMapUrl(false)));+ }+ };+}- dispatch(push(responseUrl));+export function onLoadCloudMapSuccess({response, provider, loadParams}) {+ return dispatch => {+ if (provider.getMapUrl) {+ const mapUrl = provider.getMapUrl(false);+ dispatch(push(mapUrl));}};}@@ -179,6 +166,7 @@ function loadRemoteRawData(url) {request(url, (error, result) => {if (error) {reject(error);+ return;}const responseError = detectResponseError(result);if (responseError) {@@ -272,6 +260,7 @@ function loadRemoteConfig(url) {requestJson(url, (error, config) => {if (error) {reject(error);+ return;}const responseError = detectResponseError(config);if (responseError) {@@ -304,6 +293,7 @@ function loadRemoteData(url) {requestMethod(url, (error, result) => {if (error) {reject(error);+ return;}const responseError = detectResponseError(result);if (responseError) {diff --git a/examples/demo-app/src/app.js b/examples/demo-app/src/app.jsindex 40231360e..142fa8e18 100644--- a/examples/demo-app/src/app.js+++ b/examples/demo-app/src/app.js@@ -30,11 +30,16 @@ import {replaceLoadDataModal} from './factories/load-data-modal';import {replaceMapControl} from './factories/map-control';import {replacePanelHeader} from './factories/panel-header';import {AUTH_TOKENS} from './constants/default-settings';-import {loadRemoteMap, loadSampleConfigurations, onExportFileSuccess} from './actions';+import {+ loadRemoteMap,+ loadSampleConfigurations,+ onExportFileSuccess,+ onLoadCloudMapSuccess+} from './actions';-import {getCloudProviders} from './cloud-providers';+import {loadCloudMap} from 'kepler.gl/actions';+import {CLOUD_PROVIDERS} from './cloud-providers';-const CloudProviders = getCloudProviders();const KeplerGl = require('kepler.gl/components').injectComponents([replaceLoadDataModal(),replaceMapControl(),@@ -97,7 +102,19 @@ class App extends Component {componentDidMount() {// if we pass an id as part of the url// we ry to fetch along map configurations- const {params: {id} = {}, location: {query = {}} = {}} = this.props;+ const {params: {id, provider} = {}, location: {query = {}} = {}} = this.props;++ const cloudProvider = CLOUD_PROVIDERS.find(c => c.name === provider);+ if (cloudProvider) {+ this.props.dispatch(+ loadCloudMap({+ loadParams: query,+ provider: cloudProvider,+ onSuccess: onLoadCloudMapSuccess+ })+ );+ return;+ }// Load sample using its idif (id) {@@ -355,8 +372,9 @@ class App extends Component {getState={keplerGlGetState}width={width}height={height - (showBanner ? BannerHeight : 0)}- cloudProviders={CloudProviders}+ cloudProviders={CLOUD_PROVIDERS}onExportToCloudSuccess={onExportFileSuccess}+ onLoadCloudMapSuccess={onLoadCloudMapSuccess}/>)}</AutoSizer>diff --git a/examples/demo-app/src/cloud-providers/dropbox-provider.js b/examples/demo-app/src/cloud-providers/dropbox-provider.jsdeleted file mode 100644index ea1caf8aa..000000000--- a/examples/demo-app/src/cloud-providers/dropbox-provider.js+++ /dev/null@@ -1,201 +0,0 @@-// Copyright (c) 2020 Uber Technologies, Inc.-//-// Permission is hereby granted, free of charge, to any person obtaining a copy-// of this software and associated documentation files (the "Software"), to deal-// in the Software without restriction, including without limitation the rights-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell-// copies of the Software, and to permit persons to whom the Software is-// furnished to do so, subject to the following conditions:-//-// The above copyright notice and this permission notice shall be included in-// all copies or substantial portions of the Software.-//-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN-// THE SOFTWARE.--// DROPBOX-import {Dropbox} from 'dropbox';-import window from 'global/window';-import {parseQueryString} from '../utils/url';-import DropboxIcon from '../components/icons/dropbox-icon';--const NAME = 'dropbox';-const DISPLAY_NAME = 'Dropbox';-const DOMAIN = 'www.dropbox.com';-const KEPLER_DROPBOX_FOLDER_LINK = `//${DOMAIN}/home/Apps`;-const CORS_FREE_DOMAIN = 'dl.dropboxusercontent.com';-const PRIVATE_STORAGE_ENABLED = false;-const SHARING_ENABLED = true;--export default class DropboxProvider {- constructor(clientId, appName, icon = DropboxIcon) {- // All cloud-providers providers must implement the following properties- this.name = NAME;- this.displayName = DISPLAY_NAME;- this.clientId = clientId;- this.appName = appName;- this.icon = icon;-- this._folderLink = `${KEPLER_DROPBOX_FOLDER_LINK}/${appName}`;-- // Initialize Dropbox API- this._dropbox = new Dropbox({fetch: window.fetch});- this._dropbox.setClientId(clientId);- }-- /**- * This method will handle the oauth flow by performing the following steps:- * - Opening a new window- * - Subscribe to message channel- * - Receive the token when ready- * - Close the opened tab- */- login(onCloudLoginSuccess) {- const link = this._authLink();-- const authWindow = window.open(link, '_blank', 'width=1024,height=716');- const handleToken = e => {- // TODO: add security step to validate which domain the message is coming from- authWindow.close();- window.removeEventListener('message', handleToken);- this._dropbox.setAccessToken(e.data.token);- if (window.localStorage) {- window.localStorage.setItem(- 'dropbox',- JSON.stringify({- // dropbox token doesn't expire unless revoked by the user- token: e.data.token,- timestamp: new Date()- })- );- }- };- onCloudLoginSuccess();- window.addEventListener('message', handleToken);- }-- getUserName() {- // TODO: Implement- return null;- }-- logout(onCloudLogoutSuccess) {- // TODO: Implement- }-- isEnabled() {- // TODO: Implement- return this.clientId !== null;- }-- isConnected() {- // TODO: Implement- }-- hasPrivateStorage() {- return PRIVATE_STORAGE_ENABLED;- }-- hasSharingUrl() {- return SHARING_ENABLED;- }-- /**- *- * @param mapData map data and config in one json object {map: {datasets: Array<Object>, config: Object, info: Object}- * @param blob json file blob to upload- * @param fileName if blob doesn't contain a file name, this field is used- * @param isPublic define whether the file will be available publicly once uploaded- * @returns {Promise<DropboxTypes.files.FileMetadata>}- */- async uploadFile({mapData, blob, fileName, isPublic = true}) {- const metadata = await this._dropbox.filesUpload({- path: `/${fileName || blob.name}`,- contents: blob- });-- return isPublic ? await this.shareFile(metadata) : metadata;- }-- /**- * It will set access to file to public- * @param {Object} metadata metadata response from uploading the file- * @returns {Promise<DropboxTypes.sharing.FileLinkMetadataReference | DropboxTypes.sharing.FolderLinkMetadataReference | DropboxTypes.sharing.SharedLinkMetadataReference>}- */- shareFile(metadata) {- return this._dropbox- .sharingCreateSharedLinkWithSettings({- path: metadata.path_display || metadata.path_lower- })- .then(- // Update URL to avoid CORS issue- // Unfortunately this is not the ideal scenario but it will make sure people- // can share dropbox urls with users without the dropbox account (publish on twitter, facebook)- result => ({- ...result,- folder_link: this._folderLink,- url: this._overrideUrl(result.url)- })- );- }-- /**- * Provides the current dropbox auth token. If stored in localStorage is set onto dropbox handler and returned- * @returns {any}- */- getAccessToken() {- let token = this._dropbox.getAccessToken();- if (!token && window.localStorage) {- const jsonString = window.localStorage.getItem('dropbox');- token = jsonString && JSON.parse(jsonString).token;- if (token) {- this._dropbox.setAccessToken(token);- }- }- return (token || '') !== '' ? token : null;- }-- /**- * This method will extract the auth token from the third party service callback url.- * @param {object} location the window location provided by react router- * @returns {?string} the token extracted from the oauth 2 callback URL- */- getAccessTokenFromLocation(location) {- if (!(location && location.hash.length)) {- return null;- }- // dropbox token usually start with # therefore we want to remore the '#'- const query = window.location.hash.substring(1);- return parseQueryString(query).access_token;- }-- // PRIVATE-- /**- * Generate auth link url to open to be used to handle OAuth2- * @param {string} path- */- _authLink(path = 'auth') {- return this._dropbox.getAuthenticationUrl(- `${window.location.origin}/${path}`,- btoa(JSON.stringify({handler: 'dropbox', origin: window.location.origin}))- );- }-- /**- * Override dropbox cloud-providers url- * https://www.dropbox.com/s/bxwwdb81z0jg7pb/keplergl_2018-11-01T23%3A22%3A43.940Z.json?dl=0- * ->- * https://dl.dropboxusercontent.com/s/bxwwdb81z0jg7pb/keplergl_2018-11-01T23%3A22%3A43.940Z.json- * @param metadata- * @returns {DropboxTypes.sharing.FileLinkMetadataReference}- */- _overrideUrl(url) {- return url ? url.slice(0, url.indexOf('?')).replace(DOMAIN, CORS_FREE_DOMAIN) : null;- }-}diff --git a/examples/demo-app/src/cloud-providers/dropbox/dropbox-error-modal.js b/examples/demo-app/src/cloud-providers/dropbox/dropbox-error-modal.jsnew file mode 100644index 000000000..08b520821--- /dev/null+++ b/examples/demo-app/src/cloud-providers/dropbox/dropbox-error-modal.js@@ -0,0 +1,64 @@+// Copyright (c) 2020 Uber Technologies, Inc.+//+// Permission is hereby granted, free of charge, to any person obtaining a copy+// of this software and associated documentation files (the "Software"), to deal+// in the Software without restriction, including without limitation the rights+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+// copies of the Software, and to permit persons to whom the Software is+// furnished to do so, subject to the following conditions:+//+// The above copyright notice and this permission notice shall be included in+// all copies or substantial portions of the Software.+//+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+// THE SOFTWARE.++import React, {Component, createRef} from 'react';+import ReactDOM from 'react-dom';++const WIDTH = 400;+const HEIGHT = 800;+const style = {borther: 0};++export default class Frame extends Component {+ componentDidMount() {+ this.renderFrameContents();+ }+ componentDidUpdate() {+ this.renderFrameContents();+ }++ componentWillUnmount() {+ ReactDOM.unmountComponentAtNode(this.root.current.contentDocument);+ }++ root = createRef();+ innerHtml = createRef();++ renderFrameContents = () => {+ const doc = this.root.current.contentDocument;+ if (doc.readyState === 'complete') {+ ReactDOM.render(+ <html+ ref={this.innerHtml}+ // eslint-disable-next-line react/no-danger+ dangerouslySetInnerHTML={{+ __html: this.props.children+ }}+ />,+ doc+ );+ } else {+ setTimeout(this.renderFrameContents.bind(this), 0);+ }+ };++ render() {+ return <iframe width={`${WIDTH}px`} height={`${HEIGHT}px`} style={style} ref={this.root} />;+ }+}diff --git a/examples/demo-app/src/components/icons/dropbox-icon.js b/examples/demo-app/src/cloud-providers/dropbox/dropbox-icon.jssimilarity index 100%rename from examples/demo-app/src/components/icons/dropbox-icon.jsrename to examples/demo-app/src/cloud-providers/dropbox/dropbox-icon.jsdiff --git a/examples/demo-app/src/cloud-providers/dropbox/dropbox-provider.js b/examples/demo-app/src/cloud-providers/dropbox/dropbox-provider.jsnew file mode 100644index 000000000..9b02fa23c--- /dev/null+++ b/examples/demo-app/src/cloud-providers/dropbox/dropbox-provider.js@@ -0,0 +1,476 @@+// Copyright (c) 2020 Uber Technologies, Inc.+//+// Permission is hereby granted, free of charge, to any person obtaining a copy+// of this software and associated documentation files (the "Software"), to deal+// in the Software without restriction, including without limitation the rights+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+// copies of the Software, and to permit persons to whom the Software is+// furnished to do so, subject to the following conditions:+//+// The above copyright notice and this permission notice shall be included in+// all copies or substantial portions of the Software.+//+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+// THE SOFTWARE.++// DROPBOX+import {Dropbox} from 'dropbox';+import window from 'global/window';+import Console from 'global/console';+import DropboxIcon from './dropbox-icon';+import {MAP_URI} from '../../constants/default-settings';+import {Provider} from 'kepler.gl/cloud-providers';++const NAME = 'dropbox';+const DISPLAY_NAME = 'Dropbox';+const DOMAIN = 'www.dropbox.com';+const KEPLER_DROPBOX_FOLDER_LINK = `//${DOMAIN}/home/Apps`;+const CORS_FREE_DOMAIN = 'dl.dropboxusercontent.com';+const PRIVATE_STORAGE_ENABLED = true;+const SHARING_ENABLED = true;+const MAX_THUMBNAIL_BATCH = 25;+const IMAGE_URL_PREFIX = 'data:image/gif;base64,';++function parseQueryString(query) {+ const searchParams = new URLSearchParams(query);+ const params = {};+ for (const p of searchParams) {+ if (p && p.length === 2 && p[0]) params[p[0]] = p[1];+ }++ return params;+}++export default class DropboxProvider extends Provider {+ constructor(clientId, appName) {+ super({name: NAME, displayName: DISPLAY_NAME, icon: DropboxIcon});+ // All cloud-providers providers must implement the following properties++ this.clientId = clientId;+ this.appName = appName;++ this._folderLink = `${KEPLER_DROPBOX_FOLDER_LINK}/${appName}`;+ this._path = `/Apps/${window.decodeURIComponent(this.appName)}`;++ // Initialize Dropbox API+ this._initializeDropbox();+ }++ /**+ * This method will handle the oauth flow by performing the following steps:+ * - Opening a new window+ * - Subscribe to message channel+ * - Receive the token when ready+ * - Close the opened tab+ */+ async login(onCloudLoginSuccess) {+ const link = this._authLink();++ const authWindow = window.open(link, '_blank', 'width=1024,height=716');++ const handleToken = async e => {+ // TODO: add security step to validate which domain the message is coming from+ if (authWindow) {+ authWindow.close();+ }++ window.removeEventListener('message', handleToken);++ if (!e.data.token) {+ Console.warn('Failed to login to Dropbox');+ return;+ }++ this._dropbox.setAccessToken(e.data.token);+ // save user name+ const user = await this._getUser();++ if (window.localStorage) {+ window.localStorage.setItem(+ 'dropbox',+ JSON.stringify({+ // dropbox token doesn't expire unless revoked by the user+ token: e.data.token,+ user,+ timestamp: new Date()+ })+ );+ }++ if (typeof onCloudLoginSuccess === 'function') {+ onCloudLoginSuccess();+ }+ };++ window.addEventListener('message', handleToken);+ }++ async downloadMap(loadParams) {+ const token = this.getAccessToken();+ if (!token) {+ this.login(() => this.downloadMap(loadParams));+ }+ const result = await this._dropbox.filesDownload(loadParams);+ const json = await this._readFile(result.fileBlob);++ const response = {+ map: json,+ format: 'keplergl'+ };++ this._loadParam = loadParams;+ return response;+ }++ async listMaps() {+ // list files+ try {+ // https://dropbox.github.io/dropbox-sdk-js/Dropbox.html#filesListFolder__anchor+ const response = await this._dropbox.filesListFolder({+ path: this._path+ });+ const {pngs, visualizations} = this._parseEntries(response);+ // https://dropbox.github.io/dropbox-sdk-js/Dropbox.html#filesGetThumbnailBatch__anchor+ // up to 25 per request+ // TODO: implement pagination, so we don't need to get all the thumbs all at once+ const thumbnails = await Promise.all(this._getThumbnailRequests(pngs)).then(results =>+ results.reduce((accu, r) => [...accu, ...(r.entries || [])], [])+ );++ // append to visualizations+ thumbnails &&+ thumbnails.forEach(thb => {+ if (thb['.tag'] === 'success' && thb.thumbnail) {+ const matchViz = visualizations[pngs[thb.metadata.id] && pngs[thb.metadata.id].name];+ if (matchViz) {+ matchViz.thumbnail = `${IMAGE_URL_PREFIX}${thb.thumbnail}`;+ }+ }+ });++ // dropbox returns+ return Object.values(visualizations).reverse();+ } catch (error) {+ // made the error message human readable for provider updater+ throw this._handleDropboxError(error);+ }+ }++ getUserName() {+ // load user from+ if (window.localStorage) {+ const jsonString = window.localStorage.getItem('dropbox');+ const user = jsonString && JSON.parse(jsonString).user;+ return user;+ }+ return null;+ }++ async logout(onCloudLogoutSuccess) {+ const token = this._dropbox.getAccessToken();++ if (token) {+ await this._dropbox.authTokenRevoke();+ if (window.localStorage) {+ window.localStorage.removeItem('dropbox');+ }+ // re instantiate dropbox+ this._initializeDropbox();+ onCloudLogoutSuccess();+ }+ }++ isEnabled() {+ return this.clientId !== null;+ }++ hasPrivateStorage() {+ return PRIVATE_STORAGE_ENABLED;+ }++ hasSharingUrl() {+ return SHARING_ENABLED;+ }++ /**+ *+ * @param mapData map data and config in one json object {map: {datasets: Array<Object>, config: Object, info: Object}+ * @param blob json file blob to upload+ * @param fileName if blob doesn't contain a file name, this field is used+ * @param isPublic define whether the file will be available publicly once uploaded+ * @returns {Promise<DropboxTypes.files.FileMetadata>}+ */+ async uploadMap({mapData, options = {}}) {+ 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`;+ const fileContent = map;+ // FileWriteMode: Selects what to do if the file already exists.+ const mode = options.overwrite ? 'overwrite' : 'add';++ const metadata = await this._dropbox.filesUpload({+ path: `${this._path}/${fileName}`,+ contents: JSON.stringify(fileContent),+ mode+ });++ // save a thumbnail image+ thumbnail &&+ (await this._dropbox.filesUpload({+ path: `${this._path}/${fileName}`.replace(/\.json$/, '.png'),+ contents: thumbnail,+ mode+ }));++ // keep on create shareUrl+ if (isPublic) {+ return await this._shareFile(metadata);+ }++ // save private map save map url+ this._loadParam = {path: metadata.path_lower};++ return this._loadParam;+ }++ /**+ * Get the share url of current map, this url can be accessed by anyone+ * @param {boolean} fullUrl+ */+ getShareUrl(fullUrl = true) {+ return fullUrl+ ? `${window.location.protocol}//${window.location.host}/${MAP_URI}${this._shareUrl}`+ : `/${MAP_URI}${this._shareUrl}`;+ }++ /**+ * Get the map url of current map, this url can only be accessed by current logged in user+ * @param {boolean} fullUrl+ */+ getMapUrl(fullURL = true) {+ const {path} = this._loadParam;+ const mapLink = `demo/map/dropbox?path=${path}`;+ return fullURL+ ? `${window.location.protocol}//${window.location.host}/${mapLink}`+ : `/${mapLink}`;+ }++ /**+ * Provides the current dropbox auth token. If stored in localStorage is set onto dropbox handler and returned+ * @returns {any}+ */+ getAccessToken() {+ let token = this._dropbox.getAccessToken();+ if (!token && window.localStorage) {+ const jsonString = window.localStorage.getItem('dropbox');+ token = jsonString && JSON.parse(jsonString).token;+ if (token) {+ this._dropbox.setAccessToken(token);+ }+ }+ return (token || '') !== '' ? token : null;+ }++ /**+ * This method will extract the auth token from the third party service callback url.+ * @param {object} location the window location provided by react router+ * @returns {?string} the token extracted from the oauth 2 callback URL+ */+ getAccessTokenFromLocation(location) {+ if (!(location && location.hash.length)) {+ return null;+ }+ // dropbox token usually start with # therefore we want to remove the '#'+ const query = window.location.hash.substring(1);+ return parseQueryString(query).access_token;+ }++ // PRIVATE+ _initializeDropbox() {+ this._dropbox = new Dropbox({fetch: window.fetch});+ this._dropbox.setClientId(this.clientId);+ }++ async _getUser() {+ let response;+ try {+ response = await this._dropbox.usersGetCurrentAccount();+ } catch (error) {+ Console.warn(error);+ return null;+ }++ return this._getUserFromAccount(response);+ }++ _handleDropboxError(error) {+ // dropbox list_folder error+ if (error && error.error && error.error.error_summary) {+ return `Dropbox Error: ${error.error.error_summary}`;+ }++ return error;+ }++ _readFile(fileBlob) {+ return new Promise((resolve, reject) => {+ const fileReader = new FileReader(fileBlob);+ fileReader.onload = ({target: {result}}) => {+ try {+ const json = JSON.parse(result);+ resolve(json);+ } catch (err) {+ reject(err);+ }+ };++ fileReader.readAsText(fileBlob, 'utf-8');+ });+ }++ // append url after map sharing+ _getMapPermalink(mapLink, fullUrl = true) {+ return fullUrl+ ? `${window.location.protocol}//${window.location.host}/${MAP_URI}${mapLink}`+ : `/${MAP_URI}${mapLink}`;+ }++ // append map url after load map from storage, this url is not meant+ // to be directly shared with others+ _getMapPermalinkFromParams({path}, fullURL = true) {+ const mapLink = `demo/map/dropbox?path=${path}`;+ return fullURL+ ? `${window.location.protocol}//${window.location.host}/${mapLink}`+ : `/${mapLink}`;+ }+ /**+ * It will set access to file to public+ * @param {Object} metadata metadata response from uploading the file+ * @returns {Promise<DropboxTypes.sharing.FileLinkMetadataReference | DropboxTypes.sharing.FolderLinkMetadataReference | DropboxTypes.sharing.SharedLinkMetadataReference>}+ */+ _shareFile(metadata) {+ return this._dropbox+ .sharingCreateSharedLinkWithSettings({+ path: metadata.path_display || metadata.path_lower+ })+ .then(+ // Update URL to avoid CORS issue+ // Unfortunately this is not the ideal scenario but it will make sure people+ // can share dropbox urls with users without the dropbox account (publish on twitter, facebook)+ result => {+ // save share link+ this._shareUrl = this._overrideUrl(result.url);++ return {+ // the full url to be displayed+ shareUrl: this.getShareUrl(true),+ folderLink: this._folderLink+ };+ }+ );+ }++ /**+ * Generate auth link url to open to be used to handle OAuth2+ * @param {string} path+ */+ _authLink(path = 'auth') {+ return this._dropbox.getAuthenticationUrl(+ `${window.location.origin}/${path}`,+ btoa(JSON.stringify({handler: 'dropbox', origin: window.location.origin}))+ );+ }++ /**+ * Override dropbox cloud-providers url+ * https://www.dropbox.com/s/bxwwdb81z0jg7pb/keplergl_2018-11-01T23%3A22%3A43.940Z.json?dl=0+ * ->+ * https://dl.dropboxusercontent.com/s/bxwwdb81z0jg7pb/keplergl_2018-11-01T23%3A22%3A43.940Z.json+ * @param metadata+ * @returns {DropboxTypes.sharing.FileLinkMetadataReference}+ */+ _overrideUrl(url) {+ return url ? url.slice(0, url.indexOf('?')).replace(DOMAIN, CORS_FREE_DOMAIN) : null;+ }++ _getUserFromAccount(response) {+ return response ? (response.name && response.name.abbreviated_name) || response.email : null;+ }++ _getThumbnailRequests(pngs) {+ const batches = Object.values(pngs).reduce((accu, c) => {+ const lastBatch = accu.length && accu[accu.length - 1];+ if (!lastBatch || lastBatch.length >= MAX_THUMBNAIL_BATCH) {+ // add new batch+ accu.push([c]);+ } else {+ lastBatch.push(c);+ }+ return accu;+ }, []);++ return batches.map(batch =>+ this._dropbox.filesGetThumbnailBatch({+ entries: batch.map(img => ({+ path: img.path_lower,+ format: 'png',+ size: 'w128h128'+ }))+ })+ );+ }++ /**+ * Parse fileListFolder result as visualizations to be shown in load storage map modal+ * @param {*} response+ */+ _parseEntries(response) {+ const {entries, cursor, has_more} = response;++ if (has_more) {+ this._cursor = cursor;+ }+ const pngs = {};+ const visualizations = {};++ entries.forEach(entry => {+ const {name, path_lower, id, client_modified} = entry;+ if (name && name.endsWith('.json')) {+ // find json+ const title = name.replace(/\.json$/, '');+ const viz = {+ name,+ title,+ id,+ lastModification: new Date(client_modified).getTime(),+ loadParams: {+ path: path_lower+ }+ };++ visualizations[title] = viz;+ } else if (name && name.endsWith('.png')) {+ const title = name.replace(/\.png$/, '');++ pngs[id] = {+ name: title,+ path_lower,+ id+ };+ }+ });++ return {+ visualizations,+ pngs+ };+ }+}diff --git a/examples/demo-app/src/cloud-providers/index.js b/examples/demo-app/src/cloud-providers/index.jsindex 5931827cb..c765388af 100644--- a/examples/demo-app/src/cloud-providers/index.js+++ b/examples/demo-app/src/cloud-providers/index.js@@ -18,11 +18,16 @@// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN// THE SOFTWARE.-import {CLOUD_PROVIDERS} from './providers';+import {AUTH_TOKENS} from '../constants/default-settings';-export function getCloudProviders() {- return CLOUD_PROVIDERS;-}+import DropboxProvider from './dropbox/dropbox-provider';++const {DROPBOX_CLIENT_ID} = AUTH_TOKENS;+const DROPBOX_CLIENT_NAME = 'Kepler.gl%20(managed%20by%20Uber%20Technologies%2C%20Inc.)';++export const DEFAULT_CLOUD_PROVIDER = 'dropbox';++export const CLOUD_PROVIDERS = [new DropboxProvider(DROPBOX_CLIENT_ID, DROPBOX_CLIENT_NAME)];export function getCloudProvider(providerName) {const cloudProvider = CLOUD_PROVIDERS.find(provider => provider.name === providerName);diff --git a/examples/demo-app/src/components/load-data-modal/load-data-modal.js b/examples/demo-app/src/components/load-data-modal/load-data-modal.jsdeleted file mode 100644index a1af651a2..000000000--- a/examples/demo-app/src/components/load-data-modal/load-data-modal.js+++ /dev/null@@ -1,242 +0,0 @@-// Copyright (c) 2020 Uber Technologies, Inc.-//-// Permission is hereby granted, free of charge, to any person obtaining a copy-// of this software and associated documentation files (the "Software"), to deal-// in the Software without restriction, including without limitation the rights-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell-// copies of the Software, and to permit persons to whom the Software is-// furnished to do so, subject to the following conditions:-//-// The above copyright notice and this permission notice shall be included in-// all copies or substantial portions of the Software.-//-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN-// THE SOFTWARE.--import React, {Component} from 'react';-import classnames from 'classnames';-import styled, {ThemeProvider} from 'styled-components';-import PropTypes from 'prop-types';-import {FileUpload, LoadingSpinner, Icons} from 'kepler.gl/components';-import {media, themeLT} from 'kepler.gl/styles';--import {LOADING_METHODS, ASSETS_URL, LOADING_METHODS_NAMES} from '../../constants/default-settings';--import SampleMapGallery from './sample-data-viewer';-import LoadRemoteMap from './load-remote-map';--const propTypes = {- // query options- loadingMethod: PropTypes.object.isRequired,- currentOption: PropTypes.object.isRequired,- sampleMaps: PropTypes.arrayOf(PropTypes.object).isRequired,-- // call backs- onFileUpload: PropTypes.func.isRequired,- onLoadRemoteMap: PropTypes.func.isRequired,- onLoadSample: PropTypes.func.isRequired,- onSwitchToLoadingMethod: PropTypes.func.isRequired-};--const ModalTab = styled.div`- align-items: flex-end;- display: flex;- border-bottom: 1px solid #d8d8d8;- margin-bottom: 32px;- justify-content: space-between;-- .load-data-modal__tab__inner {- display: flex;- }-- .load-data-modal__tab__item.active {- color: ${props => props.theme.textColorLT};- border-bottom: 3px solid ${props => props.theme.textColorLT};- font-weight: 500;- }-- ${media.portable`- font-size: 12px;- `};-`;--const StyledLoadDataModalTabItem = styled.div`- border-bottom: 3px solid transparent;- cursor: pointer;- margin-left: 32px;- padding: 16px 0;- font-size: 14px;- font-weight: 400;- color: ${props => props.theme.subtextColorLT};-- ${media.portable`- margin-left: 16px;- font-size: 12px;- `};-- :first-child {- margin-left: 0;- padding-left: 0;- }-- :hover {- color: ${props => props.theme.textColorLT};- }-`;--const StyledMapIcon = styled.div`- background-image: url("${ASSETS_URL}icon-demo-map.jpg");- background-repeat: no-repeat;- background-size: 64px 48px;- width: 64px;- height: 48px;- border-radius: 2px;-- ${media.portable`- width: 48px;- height: 32px;- `};-`;--const StyledTrySampleData = styled.div`- display: flex;- margin-bottom: 12px;-- .demo-map-title {- margin-left: 16px;- display: flex;- flex-direction: column;- justify-content: flex-end;- }-- .demo-map-label {- font-size: 11px;- color: ${props => props.theme.labelColorLT};-- ${media.portable`- font-size: 10px;- `};- }-- .demo-map-action {- display: flex;- font-size: 14px;- align-items: center;- color: ${props => props.theme.titleColorLT};- cursor: pointer;-- ${media.portable`- font-size: 12px;- `};-- :hover {- font-weight: 500;- }-- span {- white-space: nowrap;- }- svg {- margin-left: 10px;- }- }-`;--const StyledSpinner = styled.div`- text-align: center;- span {- margin: 0 auto;- }-`;--class LoadDataModal extends Component {- render() {- const {- loadingMethod,- currentOption,- previousMethod,- sampleMaps,- isMapLoading,- onSwitchToLoadingMethod,- error- } = this.props;-- return (- <ThemeProvider theme={themeLT}>- <div className="load-data-modal">- {isMapLoading ? (- <StyledSpinner>- <LoadingSpinner />- </StyledSpinner>- ) : (- <div>- {loadingMethod.id !== 'sample' ? (- <Tabs method={loadingMethod.id} toggleMethod={this.props.onSwitchToLoadingMethod} />- ) : null}- {loadingMethod.id === 'upload' ? <FileUpload {...this.props} /> : null}- {loadingMethod.id === 'remote' ? (- <LoadRemoteMap- onLoadRemoteMap={this.props.onLoadRemoteMap}- option={this.props.currentOption}- error={this.props.error}- />- ) : null}- {loadingMethod.id === 'sample' ? (- <SampleMapGallery- sampleData={currentOption}- sampleMaps={sampleMaps}- back={() => onSwitchToLoadingMethod(previousMethod.id)}- onLoadSample={this.props.onLoadSample}- error={error}- />- ) : null}- </div>- )}- </div>- </ThemeProvider>- );- }-}--const Tabs = ({method, toggleMethod}) => (- <ModalTab className="load-data-modal__tab">- <div className="load-data-modal__tab__inner">- {LOADING_METHODS.map(({id, label}) =>- id !== 'sample' ? (- <StyledLoadDataModalTabItem- className={classnames('load-data-modal__tab__item', {- active: method && id === method- })}- key={id}- onClick={() => toggleMethod(id)}- >- <div>{label}</div>- </StyledLoadDataModalTabItem>- ) : null- )}- </div>- <TrySampleData onClick={() => toggleMethod(LOADING_METHODS_NAMES.sample)} />- </ModalTab>-);--const TrySampleData = ({onClick}) => (- <StyledTrySampleData className="try-sample-data">- <StyledMapIcon className="demo-map-icon" />- <div className="demo-map-title">- <div className="demo-map-label">No data ?</div>- <div className="demo-map-action" onClick={onClick}>- <span>Try sample data</span>- <Icons.ArrowRight height="16px" />- </div>- </div>- </StyledTrySampleData>-);--LoadDataModal.propTypes = propTypes;--export default LoadDataModal;diff --git a/examples/demo-app/src/components/load-data-modal/sample-data-viewer.js b/examples/demo-app/src/components/load-data-modal/sample-data-viewer.jsindex 9ba1e5ec9..2c188b64f 100644--- a/examples/demo-app/src/components/load-data-modal/sample-data-viewer.js+++ b/examples/demo-app/src/components/load-data-modal/sample-data-viewer.js@@ -18,20 +18,14 @@// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN// THE SOFTWARE.-import React from 'react';+import React, {Component} from 'react';import PropTypes from 'prop-types';import styled from 'styled-components';-import {Icons} from 'kepler.gl/components';import {format} from 'd3-format';+import {LoadingDialog} from 'kepler.gl/components';const numFormat = format(',');-const propTypes = {- sampleData: PropTypes.object.isRequired,- onLoadSample: PropTypes.func.isRequired,- back: PropTypes.func.isRequired-};-const StyledSampleGallery = styled.div`display: flex;justify-content: space-between;@@ -79,26 +73,6 @@ const StyledSampleMap = styled.div`}`;-const BackLink = styled.div`- display: flex;- font-size: 14px;- align-items: center;- color: ${props => props.theme.titleColorLT};- cursor: pointer;- margin-bottom: 40px;-- :hover {- font-weight: 500;- }-- span {- white-space: nowrap;- }- svg {- margin-right: 10px;- }-`;-const StyledImageCaption = styled.div`color: ${props => props.theme.labelColorLT};font-size: 11px;@@ -129,23 +103,37 @@ const SampleMap = ({sample, onClick}) => (</StyledSampleMap>);-const SampleMapGallery = ({sampleData, sampleMaps, onLoadSample, back, error}) => (- <div className="sample-data-modal">- <BackLink onClick={back}>- <Icons.LeftArrow height="12px" />- <span>Back</span>- </BackLink>- {error && <StyledError>{error.message}</StyledError>}- <StyledSampleGallery className="sample-map-gallery">- {sampleMaps- .filter(sp => sp.visible)- .map(sp => (- <SampleMap sample={sp} key={sp.id} onClick={() => onLoadSample(sp)} />- ))}- </StyledSampleGallery>- </div>-);--SampleMapGallery.propTypes = propTypes;+export default class SampleMapGallery extends Component {+ static propTypes = {+ sampleMaps: PropTypes.arrayOf(PropTypes.object),+ onLoadSample: PropTypes.func.isRequired,+ loadSampleConfigurations: PropTypes.func.isRequired,+ error: PropTypes.object+ };+ componentDidMount() {+ if (!this.props.sampleMaps.length) {+ this.props.loadSampleConfigurations();+ }+ }-export default SampleMapGallery;+ render() {+ const {sampleMaps, onLoadSample, error, isMapLoading} = this.props;+ return (+ <div className="sample-data-modal">+ {error ? (+ <StyledError>{error.message}</StyledError>+ ) : isMapLoading ? (+ <LoadingDialog size={64} message="Loading..." />+ ) : (+ <StyledSampleGallery className="sample-map-gallery">+ {sampleMaps+ .filter(sp => sp.visible)+ .map(sp => (+ <SampleMap sample={sp} key={sp.id} onClick={() => onLoadSample(sp)} />+ ))}+ </StyledSampleGallery>+ )}+ </div>+ );+ }+}diff --git a/examples/demo-app/src/components/load-data-modal/sample-maps-tab.js b/examples/demo-app/src/components/load-data-modal/sample-maps-tab.jsnew file mode 100644index 000000000..aac7f635b--- /dev/null+++ b/examples/demo-app/src/components/load-data-modal/sample-maps-tab.js@@ -0,0 +1,102 @@+// Copyright (c) 2020 Uber Technologies, Inc.+//+// Permission is hereby granted, free of charge, to any person obtaining a copy+// of this software and associated documentation files (the "Software"), to deal+// in the Software without restriction, including without limitation the rights+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+// copies of the Software, and to permit persons to whom the Software is+// furnished to do so, subject to the following conditions:+//+// The above copyright notice and this permission notice shall be included in+// all copies or substantial portions of the Software.+//+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+// THE SOFTWARE.++import React from 'react';+import styled from 'styled-components';+import {Icons} from 'kepler.gl/components';+import {media} from 'kepler.gl/styles';++import {ASSETS_URL} from '../../constants/default-settings';++const StyledMapIcon = styled.div`+ background-image: url("${ASSETS_URL}icon-demo-map.jpg");+ background-repeat: no-repeat;+ background-size: 64px 48px;+ width: 64px;+ height: 48px;+ border-radius: 2px;++ ${media.portable`+ width: 48px;+ height: 32px;+ `};+`;++const StyledTrySampleData = styled.div`+ display: flex;+ margin-bottom: 12px;+ flex-grow: 1;+ justify-content: flex-end;+ color: ${props => props.theme.subtextColorLT};++ .demo-map-title {+ margin-left: 16px;+ display: flex;+ flex-direction: column;+ justify-content: flex-end;+ }++ .demo-map-label {+ font-size: 11px;++ ${media.portable`+ font-size: 10px;+ `};+ }++ .demo-map-action {+ display: flex;+ font-size: 14px;+ align-items: center;+ color: ${props => props.theme.subtextColorLT};+ cursor: pointer;++ ${media.portable`+ font-size: 12px;+ `};++ :hover {+ color: ${props => props.theme.textColorLT};+ }++ span {+ white-space: nowrap;+ }++ svg {+ margin-left: 10px;+ }+ }+`;++const SampleMapsTab = ({onClick}) => (+ <StyledTrySampleData className="try-sample-data">+ <StyledMapIcon className="demo-map-icon" />+ <div className="demo-map-title">+ <div className="demo-map-label">No data ?</div>+ <div className="demo-map-action" onClick={onClick}>+ <span>Try sample data</span>+ <Icons.ArrowRight height="16px" />+ </div>+ </div>+ </StyledTrySampleData>+);++export default SampleMapsTab;diff --git a/examples/demo-app/src/constants/default-settings.js b/examples/demo-app/src/constants/default-settings.jsindex ffc757250..904c3108e 100644--- a/examples/demo-app/src/constants/default-settings.js+++ b/examples/demo-app/src/constants/default-settings.js@@ -47,59 +47,17 @@ export const QUERY_OPTIONS = keyMirror({geojson: null});-export const LOADING_METHODS_NAMES = keyMirror({- upload: null,+export const LOADING_METHODS = keyMirror({remote: null,sample: null});-export const LOADING_METHODS = [- {- id: LOADING_METHODS_NAMES.upload,- label: 'Load Your Data',- options: [- {- id: QUERY_OPTIONS.csv,- queryType: QUERY_TYPES.file,- label: 'Csv',- icon: 'note',- description:- 'Upload a csv file where each row contains one feature and its meta data. ' +- 'Columns with name xxx_lat and xxx_lng will be automatically detected as points.'- },- {- id: QUERY_OPTIONS.geojson,- queryType: QUERY_TYPES.file,- label: 'Geojson',- icon: 'note',- description:- 'Upload a gpx, kml, or zipped Shapefile and we will convert each layer to GeoJSON.'- }- ]- },- {- id: LOADING_METHODS_NAMES.remote,- label: 'Load Map using URL'- },- {- id: LOADING_METHODS_NAMES.sample,- label: 'Sample Data',- options: [- // Dynamically populated- ]- }-];-export const LOADING_SAMPLE_LIST_ERROR_MESSAGE = 'Not able to load sample gallery';export const LOADING_SAMPLE_ERROR_MESSAGE = 'Not able to load sample';export const LOADING_URL_MESSAGE ='You can use the following formats: CSV | JSON | Kepler.gl config json. Make sure the url contains the file extension.';export const CORS_LINK = 'https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS';-export const DEFAULT_LOADING_METHOD = LOADING_METHODS[0];--export const DEFAULT_CLOUD_PROVIDER = 'dropbox';-export const DEFAULT_FEATURE_FLAGS = {cloudStorage: true};diff --git a/examples/demo-app/src/factories/load-data-modal.js b/examples/demo-app/src/factories/load-data-modal.jsindex 4eb42542e..9d23eed68 100644--- a/examples/demo-app/src/factories/load-data-modal.js+++ b/examples/demo-app/src/factories/load-data-modal.js@@ -19,17 +19,52 @@// THE SOFTWARE.import {LoadDataModalFactory} from 'kepler.gl/components';-import LoadDataModal from '../components/load-data-modal/load-data-modal';import {withState} from 'kepler.gl/components';+import {LOADING_METHODS} from '../constants/default-settings';-import {loadRemoteMap, loadSample, switchToLoadingMethod} from '../actions';+import SampleMapGallery from '../components/load-data-modal/sample-data-viewer';+import LoadRemoteMap from '../components/load-data-modal/load-remote-map';+import SampleMapsTab from '../components/load-data-modal/sample-maps-tab';-export const CustomLoadDataModalFactory = () =>- withState([], state => ({...state.demo.app}), {- onSwitchToLoadingMethod: switchToLoadingMethod,+import {loadRemoteMap, loadSample, loadSampleConfigurations} from '../actions';++const additionalMethods = {+ remote: {+ id: LOADING_METHODS.remote,+ label: 'Load Map using URL',+ elementType: LoadRemoteMap+ },+ sample: {+ id: LOADING_METHODS.sample,+ label: 'Sample Maps',+ elementType: SampleMapGallery,+ tabElementType: SampleMapsTab+ }+};++const CustomLoadDataModalFactory = (...deps) => {+ const LoadDataModal = LoadDataModalFactory(...deps);+ const defaultLoadingMethods = LoadDataModal.defaultProps.loadingMethods;++ // add more loading methods+ LoadDataModal.defaultProps = {+ ...LoadDataModal.defaultProps,+ loadingMethods: [+ defaultLoadingMethods.find(lm => lm.id === 'upload'),+ additionalMethods.remote,+ defaultLoadingMethods.find(lm => lm.id === 'storage'),+ additionalMethods.sample+ ]+ };++ return withState([], state => ({...state.demo.app}), {onLoadSample: loadSample,- onLoadRemoteMap: loadRemoteMap+ onLoadRemoteMap: loadRemoteMap,+ loadSampleConfigurations})(LoadDataModal);+};++CustomLoadDataModalFactory.deps = LoadDataModalFactory.deps;export function replaceLoadDataModal() {return [LoadDataModalFactory, CustomLoadDataModalFactory];diff --git a/examples/demo-app/src/reducers/index.js b/examples/demo-app/src/reducers/index.jsindex 56ce148a9..27400dc43 100644--- a/examples/demo-app/src/reducers/index.js+++ b/examples/demo-app/src/reducers/index.js@@ -28,27 +28,19 @@ import {EXPORT_MAP_FORMATS} from 'kepler.gl/constants';import {INIT,- SET_LOADING_METHOD,LOAD_MAP_SAMPLE_FILE,LOAD_REMOTE_RESOURCE_SUCCESS,+ LOAD_REMOTE_RESOURCE_ERROR,SET_SAMPLE_LOADING_STATUS} from '../actions';-import {- AUTH_TOKENS,- DEFAULT_FEATURE_FLAGS,- DEFAULT_LOADING_METHOD,- LOADING_METHODS-} from '../constants/default-settings';+import {AUTH_TOKENS, DEFAULT_FEATURE_FLAGS} from '../constants/default-settings';import {generateHashId} from '../utils/strings';// INITIAL_APP_STATEconst initialAppState = {appName: 'example',loaded: false,- loadingMethod: DEFAULT_LOADING_METHOD,- currentOption: DEFAULT_LOADING_METHOD.options[0],- previousMethod: null,sampleMaps: [], // this is used to store sample maps fetch from a remote json fileisMapLoading: false, // determine whether we are loading a sample map,error: null, // contains error when loading/retrieving data/configuration@@ -67,12 +59,6 @@ export const appReducer = handleActions(...state,loaded: true}),- [SET_LOADING_METHOD]: (state, action) => ({- ...state,- previousMethod: state.loadingMethod,- loadingMethod: LOADING_METHODS.find(({id}) => id === action.method),- error: null- }),[LOAD_MAP_SAMPLE_FILE]: (state, action) => ({...state,sampleMaps: action.samples@@ -158,8 +144,35 @@ export const loadRemoteResourceSuccess = (state, action) => {};};+export const loadRemoteResourceError = (state, action) => {+ const {error, url} = action;++ const errorNote = {+ type: 'error',+ message: error.message || `Error loading ${url}`+ };++ return {+ ...state,+ app: {+ ...state.app,+ isMapLoading: false // we turn of the spinner+ },+ keplerGl: {+ ...state.keplerGl, // in case you keep multiple instances+ map: {+ ...state.keplerGl.map,+ uiState: uiStateUpdaters.addNotificationUpdater(state.keplerGl.map.uiState, {+ payload: errorNote+ })+ }+ }+ };+};+const composedUpdaters = {- [LOAD_REMOTE_RESOURCE_SUCCESS]: loadRemoteResourceSuccess+ [LOAD_REMOTE_RESOURCE_SUCCESS]: loadRemoteResourceSuccess,+ [LOAD_REMOTE_RESOURCE_ERROR]: loadRemoteResourceError};const composedReducer = (state, action) => {diff --git a/examples/demo-app/src/utils/routes.js b/examples/demo-app/src/utils/routes.jsindex 84b9cb94a..accae5d00 100644--- a/examples/demo-app/src/utils/routes.js+++ b/examples/demo-app/src/utils/routes.js@@ -18,11 +18,10 @@// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN// THE SOFTWARE.-import {getCloudProvider} from '../cloud-providers';import {IndexRoute, Route} from 'react-router';import React from 'react';import Demo from '../app';-import {DEFAULT_CLOUD_PROVIDER} from '../constants/default-settings';+import {getCloudProvider, DEFAULT_CLOUD_PROVIDER} from '../cloud-providers';export function onAuthEnterCallback(nextState, replace, callback) {// TODO: detect auth provider@@ -45,6 +44,7 @@ export function buildAppRoutes(Component) {<IndexRoute component={Component} /><Route path="map" component={Component} /><Route path="(:id)" component={Component} />+ <Route path="map/:provider" component={Component} /></Route>];}diff --git a/examples/demo-app/src/utils/url.js b/examples/demo-app/src/utils/url.jsindex e0795e0f4..847bedc38 100644--- a/examples/demo-app/src/utils/url.js+++ b/examples/demo-app/src/utils/url.js@@ -18,29 +18,6 @@// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN// THE SOFTWARE.-import {MAP_URI} from '../constants/default-settings';--export function parseQueryString(query) {- const searchParams = new URLSearchParams(query);- const params = {};- for (const p of searchParams) {- if (p && p.length === 2 && p[0]) params[p[0]] = p[1];- }-- return params;-}--/**- * Returns a permalink with the given map url: kepler.gl/[]- * @param mapLink the cloud-providers url used to store the map- * @returns {string}- */-export function getMapPermalink(mapLink, fullUrl = true) {- return fullUrl- ? `${window.location.protocol}//${window.location.host}/${MAP_URI}${mapLink}`- : `/${MAP_URI}${mapLink}`;-}-// from http://blog.stevenlevithan.com/archives/parseuri/*** Allows to break down a url into multiple paramsdiff --git a/examples/node-app/package.json b/examples/node-app/package.jsonindex e8ef9f23f..9aeaa08ed 100644--- a/examples/node-app/package.json+++ b/examples/node-app/package.json@@ -6,7 +6,7 @@"dependencies": {"express": "^4.17.1","global": "^4.3.0",- "kepler.gl": "^1.1.13",+ "kepler.gl": "^2.0.0","react": "^16.8.4","react-dom": "^16.8.4","react-palm": "^3.1.2",@@ -47,4 +47,4 @@"webpack-hot-middleware": "^2.25.0","webpack-stats-plugin": "^0.2.1"}-}+}\ No newline at end of filediff --git a/examples/open-modal/package.json b/examples/open-modal/package.jsonindex b6e5aba02..f507f0f65 100644--- a/examples/open-modal/package.json+++ b/examples/open-modal/package.json@@ -5,7 +5,7 @@},"dependencies": {"global": "^4.3.0",- "kepler.gl": "^1.1.13",+ "kepler.gl": "^2.0.0","react": "^16.8.4","react-dom": "^16.8.4","react-modal": "^3.1.10",@@ -47,4 +47,4 @@"webpack-hot-middleware": "^2.24.3","webpack-stats-plugin": "^0.2.1"}-}+}\ No newline at end of filediff --git a/examples/replace-component/package.json b/examples/replace-component/package.jsonindex 6512d8d39..befcd1095 100644--- a/examples/replace-component/package.json+++ b/examples/replace-component/package.json@@ -5,7 +5,7 @@},"dependencies": {"global": "^4.3.0",- "kepler.gl": "^1.1.13",+ "kepler.gl": "^2.0.0","react": "^16.8.4","react-dom": "^16.8.4","react-palm": "^3.1.2",@@ -46,4 +46,4 @@"webpack-hot-middleware": "^2.24.3","webpack-stats-plugin": "^0.2.1"}-}+}\ No newline at end of filediff --git a/examples/umd-client/index.html b/examples/umd-client/index.htmlindex 50ac15e5b..d6f174447 100644--- a/examples/umd-client/index.html+++ b/examples/umd-client/index.html@@ -18,7 +18,7 @@<script src="https://unpkg.com/[email protected]/dist/styled-components.min.js" crossorigin></script><!-- Load Kepler.gl-->- <script src="https://unpkg.com/[email protected]/umd/keplergl.min.js"></script>+ <script src="https://unpkg.com/[email protected]/umd/keplergl.min.js"></script><!--If you want to load the build from filepath --><!--<script src="../../umd/keplergl.min.js"></script>-->diff --git a/package.json b/package.jsonindex a3041a8ad..4a85752e5 100644--- a/package.json+++ b/package.json@@ -41,6 +41,7 @@"start:custom-theme": "npm run install-and-start -- examples/custom-theme start-local","start:node-app": "npm run install-and-start -- examples/node-app start-local","start:web": "npm run install-and-start -- website start",+ "start:https": "npm run install-and-start -- examples/demo-app start-local-https","build": "rm -fr dist && babel src --out-dir dist --source-maps inline","build:umd": "webpack --config ./webpack/umd.js --progress --env.prod","analyze": "npm run analyze:bundle",diff --git a/scripts/documentation.js b/scripts/documentation.jsindex 17f815899..5cfcd3594 100644--- a/scripts/documentation.js+++ b/scripts/documentation.js@@ -45,7 +45,7 @@ const PATHS = {api: resolve('./docs/api-reference')};-const BT = "`";+const BT = '`';const TREE = {path: '',@@ -63,14 +63,17 @@ const TREE = {'map-state-actions.js','map-style-actions.js','identity-actions.js'- ], output: 'actions.md', config: {shallow: true}}+ ],+ output: 'actions.md',+ config: {shallow: true}+ }]},{path: 'reducers',children: [{input: ['root.js', 'core.js'], output: 'reducers.md', config: {shallow: true}},- {input: 'combined-updaters.js', output: 'combine.md', config: {shallow: true}},+ {input: 'combined-updaters.js', output: 'combine.md', config: {shallow: true}},{input: 'vis-state-updaters.js', output: 'vis-state.md', config: {shallow: true}},{input: 'map-state-updaters.js', output: 'map-state.md', config: {shallow: true}},{input: 'map-style-updaters.js', output: 'map-style.md', config: {shallow: true}},@@ -79,12 +82,14 @@ const TREE = {},{path: 'processors',- children: [- {input: 'data-processor.js', output: 'processors.md', config: {shallow: true}}- ]+ children: [{input: 'data-processor.js', output: 'processors.md', config: {shallow: true}}]+ },+ {+ path: 'cloud-providers',+ children: [{input: 'provider.js', output: 'cloud-provider.md', config: {shallow: true}}]}]-}+};function _overrideHeading(nodes) {const contents = ['Examples', 'Parameters'];@@ -95,13 +100,14 @@ function _overrideHeading(nodes) {});return nodes.map(node => {- if (node.type === 'heading' &&+ if (+ node.type === 'heading' &&Array.isArray(node.children) &&- contents.includes(node.children[0].value)) {-+ contents.includes(node.children[0].value)+ ) {const value = node.children[0].value;const replacement = mdContents[contents.indexOf(value)].children[0];- return replacement+ return replacement;}return node;@@ -112,7 +118,9 @@ function _appendActionTypesAndUpdatersToActions(node, actionMap) {// __Updaters__: [`visStateUpdaters.loadFilesUpdater`](../reducers/ui-state.md#uistateupdaterssetexportfilteredupdater)if (node.members && node.members.static.length) {- node.members.static = node.members.static.map(nd => _appendActionTypesAndUpdatersToActions(nd, actionMap));+ node.members.static = node.members.static.map(nd =>+ _appendActionTypesAndUpdatersToActions(nd, actionMap)+ );}const action = node.name;@@ -122,10 +130,14 @@ function _appendActionTypesAndUpdatersToActions(node, actionMap) {}const {actionType, updaters} = actionMap[action];- const updaterList = updaters.map(({updater, name, path}) => (- `[${BT}${updater}.${name}${BT}](../reducers/${path.split('/')[2].replace('.js', '')}.md#${(updater + name).toLowerCase()})`- )).join(', ');-+ const updaterList = updaters+ .map(+ ({updater, name, path}) =>+ `[${BT}${updater}.${name}${BT}](../reducers/${path.split('/')[2].replace('.js', '')}.md#${(+ updater + name+ ).toLowerCase()})`+ )+ .join(', ');const mdContent = `* __ActionTypes__: [${BT}ActionTypes.${actionType}${BT}](#actiontypes)@@ -147,8 +159,9 @@ function _appendActionToUpdaters(node, actionMap) {const updater = node.name;- const action = Object.values(actionMap)- .find(action => action.updaters.find(up => up.name === updater));+ const action = Object.values(actionMap).find(action =>+ action.updaters.find(up => up.name === updater)+ );if (!action) {return node;@@ -164,8 +177,8 @@ function _appendActionToUpdaters(node, actionMap) {function _appendListToDescription(node, mdContent) {const tree = unified()- .use(markdown)- .parse(mdContent);+ .use(markdown)+ .parse(mdContent);if (typeof node.description === 'object') {node.description.children = (node.description.children || []).concat(tree.children);@@ -193,16 +206,17 @@ function _isExampleOrParam(node) {}function _isExampleOrParameterLink(node) {- return _isParagraph(node) &&+ return (+ _isParagraph(node) &&_isLinkReference(node.children[0]) &&- _isExampleOrParam(node.children[0].children[0]);+ _isExampleOrParam(node.children[0].children[0])+ );}/*** Remove example and parameter link from TOC*/function _cleanUpTOCChildren(node) {-if (!Array.isArray(node.children)) {return node;}@@ -211,10 +225,12 @@ function _cleanUpTOCChildren(node) {return null;}- const filteredChildren = node.children.reduce((accu, nd) => {- accu.push(_cleanUpTOCChildren(nd));- return accu;- }, []).filter(n => n);+ const filteredChildren = node.children+ .reduce((accu, nd) => {+ accu.push(_cleanUpTOCChildren(nd));+ return accu;+ }, [])+ .filter(n => n);if (!filteredChildren.length) {return null;@@ -227,7 +243,8 @@ function _cleanUpTOCChildren(node) {}function buildChildDoc(inputPath, outputPath, actionMap, config) {- return documentation.build(inputPath, {...INPUT_CONFIG, ...config})+ return documentation+ .build(inputPath, {...INPUT_CONFIG, ...config}).then(res => {// res is an array of parsed comments with inferred properties// and more: everything you need to build documentation or@@ -242,7 +259,7 @@ function buildChildDoc(inputPath, outputPath, actionMap, config) {processed = res.map(node => _appendActionToUpdaters(node, actionMap));}- return documentation.formats.remark(processed, OUT_CONFIG)+ return documentation.formats.remark(processed, OUT_CONFIG);}).then(output => {// output is a string of remark json@@ -250,7 +267,7 @@ function buildChildDoc(inputPath, outputPath, actionMap, config) {ast.children = _overrideHeading(ast.children);if (ast.children.length < 3) {- logError(inputPath, 'has less than 3 children')+ logError(inputPath, 'has less than 3 children');}const tableOfContent = _cleanUpTOCChildren(ast.children[2]);ast.children[2] = tableOfContent;@@ -265,34 +282,31 @@ function buildChildDoc(inputPath, outputPath, actionMap, config) {}function buildMdDocs(nodePath, node, actionMap, allTasks) {-const {path, children} = node;const joinPath = nodePath ? `${nodePath}/${path}` : path;children.forEach(child => {-if (!child.children) {+ const {input, output, config} = child;+ const inputPaths = (Array.isArray(input) ? input : [input]).reduce((accu, inp) => {+ const inputPath = join(PATHS.src, joinPath, inp);++ if (fs.existsSync(inputPath)) {+ // Do something+ accu.push(inputPath);+ } else {+ logError(`[Error] ${inputPath} doesn't exist!`);+ }- const {input, output, config} = child;- const inputPaths = (Array.isArray(input) ? input : [input]).reduce((accu, inp) => {- const inputPath = join(PATHS.src, joinPath, inp);-- if (fs.existsSync(inputPath)) {- // Do something- accu.push(inputPath);- } else {- logError(`[Error] ${inputPath} doesn't exist!`);- }-- return accu;- }, []);+ return accu;+ }, []);- if (!inputPaths.length) {- return;- }- const outputPath = join(PATHS.api, joinPath, output);+ if (!inputPaths.length) {+ return;+ }+ const outputPath = join(PATHS.api, joinPath, output);- allTasks.push(buildChildDoc(inputPaths, outputPath, actionMap, config));+ allTasks.push(buildChildDoc(inputPaths, outputPath, actionMap, config));} else {buildMdDocs(joinPath, child, actionMap, allTasks);}@@ -301,7 +315,6 @@ function buildMdDocs(nodePath, node, actionMap, allTasks) {return allTasks;}-function buildDocs() {logProgress('\n================= Start Building API Documentation =================\n');@@ -313,8 +326,7 @@ function buildDocs() {Promise.all(allTasks).then(() => {logSuccess('\n================= Building API Documentation Success! =================\n');- })-+ });}buildDocs();diff --git a/src/actions/actions.js b/src/actions/actions.jsindex cd1a275c2..740f62758 100644--- a/src/actions/actions.js+++ b/src/actions/actions.js@@ -97,6 +97,10 @@ import {createAction} from 'redux-actions';* readOnly: false,* keepExistingConfig: false* },+ * info: {+ * title: 'Taro and Blue',+ * description: 'This is my map'+ * }* config: sampleConfig* })* );diff --git a/src/actions/index.js b/src/actions/index.jsindex 47bf541a1..a583526ac 100644--- a/src/actions/index.js+++ b/src/actions/index.js@@ -27,6 +27,7 @@ export * from './ui-state-actions';export * from './map-state-actions';export * from './map-style-actions';export * from './identity-actions';+export * from './provider-actions';// Dispatchexport {diff --git a/src/actions/provider-actions.js b/src/actions/provider-actions.jsindex 63682e44b..e4c536e70 100644--- a/src/actions/provider-actions.js+++ b/src/actions/provider-actions.js@@ -29,34 +29,43 @@ export const ActionTypes = addPrefix(EXPORT_FILE_ERROR: null,RESET_PROVIDER_STATUS: null,SET_CLOUD_PROVIDER: null,- SAVE_TO_CLOUD_SUCCESS: null+ POST_SAVE_LOAD_SUCCESS: null,+ LOAD_CLOUD_MAP: null,+ LOAD_CLOUD_MAP_SUCCESS: null,+ LOAD_CLOUD_MAP_ERROR: null,+ GET_SAVED_MAPS: null,+ GET_SAVED_MAPS_SUCCESS: null,+ GET_SAVED_MAPS_ERROR: null}));-export const exportFileToCloud = createAction(- ActionTypes.EXPORT_FILE_TO_CLOUD,- ({mapData, provider, isPublic, onSuccess, onError, closeModal}) => ({- mapData,- provider,- isPublic,- onSuccess,- onError,- closeModal- })-);+export const exportFileToCloud = createAction(ActionTypes.EXPORT_FILE_TO_CLOUD, payload => payload);-export const exportFileSuccess = createAction(- ActionTypes.EXPORT_FILE_SUCCESS,- ({response, provider, onSuccess, closeModal}) => ({response, provider, onSuccess, closeModal})-);+export const exportFileSuccess = createAction(ActionTypes.EXPORT_FILE_SUCCESS, payload => payload);-export const exportFileError = createAction(- ActionTypes.EXPORT_FILE_ERROR,- ({error, provider, onError}) => ({error, provider, onError})-);+export const exportFileError = createAction(ActionTypes.EXPORT_FILE_ERROR, payload => payload);-export const saveToCloudSuccess = createAction(ActionTypes.SAVE_TO_CLOUD_SUCCESS);+export const postSaveLoadSuccess = createAction(+ ActionTypes.POST_SAVE_LOAD_SUCCESS,+ message => message+);export const resetProviderStatus = createAction(ActionTypes.RESET_PROVIDER_STATUS);export const setCloudProvider = createAction(ActionTypes.SET_CLOUD_PROVIDER, provider => provider);++export const loadCloudMap = createAction(ActionTypes.LOAD_CLOUD_MAP, payload => payload);++export const loadCloudMapSuccess = createAction(+ ActionTypes.LOAD_CLOUD_MAP_SUCCESS,+ payload => payload+);++export const getSavedMaps = createAction(ActionTypes.GET_SAVED_MAPS, provider => provider);++export const getSavedMapsSuccess = createAction(+ ActionTypes.GET_SAVED_MAPS_SUCCESS,+ payload => payload+);++export const getSavedMapsError = createAction(ActionTypes.GET_SAVED_MAPS_ERROR, payload => payload);diff --git a/src/actions/vis-state-actions.js b/src/actions/vis-state-actions.jsindex 78838652e..4df22000b 100644--- a/src/actions/vis-state-actions.js+++ b/src/actions/vis-state-actions.js@@ -509,6 +509,15 @@ export function loadFiles(files) {};}+export function loadFileSuccess({fileCache, filesToLoad, totalCount}) {+ return {+ type: ActionTypes.LOAD_FILES_SUCCESS,+ fileCache,+ filesToLoad,+ totalCount+ };+}+/*** Trigger loading file error* @memberof visStateActionsdiff --git a/examples/demo-app/src/cloud-providers/providers.js b/src/cloud-providers/index.jssimilarity index 76%rename from examples/demo-app/src/cloud-providers/providers.jsrename to src/cloud-providers/index.jsindex 9fc99c2cc..e7d1d64c3 100644--- a/examples/demo-app/src/cloud-providers/providers.js+++ b/src/cloud-providers/index.js@@ -18,11 +18,4 @@// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN// THE SOFTWARE.-import {AUTH_TOKENS} from '../constants/default-settings';--import DropboxProvider from './dropbox-provider';--const {DROPBOX_CLIENT_ID} = AUTH_TOKENS;-const DROPBOX_CLIENT_NAME = 'Kepler.gl%20(managed%20by%20Uber%20Technologies%2C%20Inc.)';--export const CLOUD_PROVIDERS = [new DropboxProvider(DROPBOX_CLIENT_ID, DROPBOX_CLIENT_NAME)];+export {default as Provider} from './provider';diff --git a/src/cloud-providers/provider.js b/src/cloud-providers/provider.jsnew file mode 100644index 000000000..0fc198088--- /dev/null+++ b/src/cloud-providers/provider.js@@ -0,0 +1,226 @@+// Copyright (c) 2020 Uber Technologies, Inc.+//+// Permission is hereby granted, free of charge, to any person obtaining a copy+// of this software and associated documentation files (the "Software"), to deal+// in the Software without restriction, including without limitation the rights+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+// copies of the Software, and to permit persons to whom the Software is+// furnished to do so, subject to the following conditions:+//+// The above copyright notice and this permission notice shall be included in+// all copies or substantial portions of the Software.+//+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+// THE SOFTWARE.++import {Upload} from 'components/common/icons';++const NAME = 'cloud-provider';+const DISPLAY_NAME = 'Cloud Provider';+const THUMBNAIL = {width: 300, height: 200};+const ICON = Upload;++/**+ * The default provider class+ * @param {object} props+ * @param {string} props.name+ * @param {string} props.displayName+ * @param {ReactElement} props.icon - React element+ * @param {object} props.thumbnail - thumbnail size object+ * @param {number} props.thumbnail.width - thumbnail width in pixels+ * @param {number} props.thumbnail.height - thumbnail height in pixels+ * @public+ * @example+ *+ * const myProvider = new Provider({+ * name: 'foo',+ * displayName: 'Foo Storage'+ * icon: Icon,+ * thumbnail: {width: 300, height: 200}+ * })+ */+export default class Provider {+ constructor(props) {+ this.name = props.name || NAME;+ this.displayName = props.displayName || DISPLAY_NAME;+ this.icon = props.icon || ICON;+ this.thumbnail = props.thumbnail || THUMBNAIL;+ }++ /**+ * Whether this provider support upload map to a private storage. If truthy, user will be displayed with the storage save icon on the top right of the side bar.+ * @returns {boolean}+ * @public+ */+ hasPrivateStorage() {+ return true;+ }++ /**+ * Whether this provider support share map via a public url, if truthy, user will be displayed with a share map via url under the export map option on the top right of the side bar+ * @returns {boolean}+ * @public+ */+ hasSharingUrl() {+ return true;+ }++ /**+ * This method is called after user share a map, to display the share url.+ * @param {boolean} fullUrl - Whether to return the full url with domain, or just the location+ * @returns {string} shareUrl+ * @public+ */+ getShareUrl(fullUrl = false) {+ return '';+ }++ /**+ * This method is called by kepler.gl demo app to pushes a new location to history, becoming the current location.+ * @param {boolean} fullURL - Whether to return the full url with domain, or just the location+ * @returns {string} mapUrl+ * @public+ */+ getMapUrl(fullURL = true) {+ return '';+ }++ /**+ * This method is called to determine whether user already logged in to this provider+ * @public+ * @returns {boolean} true if a user already logged in+ */+ getAccessToken() {+ return true;+ }++ /**+ * This method is called to get the user name of the current user. It will be displayed in the cloud provider tile.+ * @public+ * @returns {string} true if a user already logged in+ */+ getUserName() {+ return '';+ }++ /**+ * This method will be called when user click the login button in the cloud provider tile.+ * Upon login success, `onCloudLoginSuccess` has to be called to notify kepler.gl UI+ * @param {function} onCloudLoginSuccess - callbacks to be called after login success+ * @public+ */+ async login(onCloudLoginSuccess) {+ onCloudLoginSuccess();+ return;+ }++ /**+ * This method will be called when user click the logout button under the cloud provider tile.+ * Upon login success, `onCloudLoginSuccess` has to be called to notify kepler.gl UI+ * @param {function} onCloudLogoutSuccess - callbacks to be called after logout success+ * @public+ */+ async logout(onCloudLogoutSuccess) {+ onCloudLogoutSuccess();+ return;+ }++ /**+ * This method will be called to upload map for saving and sharing. Kepler.gl will package map data, config, title, description and thumbnail for upload to storage.+ * With the option to overwrite already saved map, and upload as private or public map.+ *+ * @param {Object} param+ * @param {Object} param.mapData - the map object+ * @param {Object} param.mapData.map - {datasets. config, info: {title, description}}+ * @param {Blob} param.mapData.thumbnail - A thumbnail of current map. thumbnail size can be defined by provider by this.thumbnail+ * @param {Object} param.options+ * @param {boolean} param.options.overwrite - whether user choose to overwrite already saved map under the same name+ * @param {boolean} param.options.isPublic - whether user wish to share the map with others. if isPublic is truthy, kepler will call this.getShareUrl() to display an URL they can share with others+ * @public+ */+ async uploadMap({mapData, options = {}}) {+ return;+ }++ /**+ * This method is called to get a list of maps saved by the current logged in user.+ * @returns {Array<Viz>} an array of Viz objects+ * @public+ * @example+ * async listMaps() {+ * return [+ * {+ * id: 'a',+ * title: 'My map',+ * description: 'My first kepler map',+ * imageUrl: 'http://',+ * lastModification: 1582677787000,+ * privateMap: false,+ * loadParams: {}+ * }+ * ];+ * }+ */+ async listMaps() {+ return [];+ }++ /**+ * This method will be called when user select a map to load from the storage map viewer+ * @param {*} loadParams - the loadParams property of each visualization object+ * @returns {MapResponse} - the map object containing dataset config info and format option+ * @public+ * @example+ * async downloadMap(loadParams) {+ * const mockResponse = {+ * map: {+ * datasets: [],+ * config: {},+ * info: {+ * app: 'kepler.gl',+ * created_at: ''+ * title: 'test map',+ * description: 'Hello this is my test dropbox map'+ * }+ * },+ * // pass csv here if your provider currently only support save / load file as csv+ * format: 'keplergl'+ * };+ *+ * return downloadMap;+ * }+ */+ async downloadMap(loadParams) {+ return;+ }++ /**+ * @typedef {Object} Viz+ * @property {string} id - An unique id+ * @property {string} title - The title of the map+ * @property {string} description - The description of the map+ * @property {string} imageUrl - The imageUrl of the map+ * @property {number} lastModification - An epoch timestamp in milliseconds+ * @property {boolean} privateMap - Optional, whether if this map is private to the user, or can be accessed by others via URL+ * @property {*} loadParams - A property to be passed to `downloadMap`+ * @public+ */++ /**+ * The returned object of `downloadMap`. The response object should contain: datasets: [], config: {}, and info: {}+ * each dataset object should be {info: {id, label}, data: {...}}+ * to inform how kepler should process your data object, pass in `format`+ * @typedef {Object} MapResponse+ * @property {Object} map+ * @property {Array<Object>} map.datasets+ * @property {Object} map.config+ * @property {Object} map.info+ * @property {string} format - one of 'csv': csv file string, 'geojson': geojson object, 'row': row object, 'keplergl': datasets array saved using KeplerGlSchema.save+ * @public+ */+}diff --git a/src/components/common/file-uploader/file-upload.js b/src/components/common/file-uploader/file-upload.jsindex f981ca2dc..2ca63a4db 100644--- a/src/components/common/file-uploader/file-upload.js+++ b/src/components/common/file-uploader/file-upload.js@@ -169,142 +169,145 @@ const StyledDisclaimer = styled(StyledMessage)`margin: 0 auto;`;-class FileUpload extends Component {- static propTypes = {- onFileUpload: PropTypes.func.isRequired,- validFileExt: PropTypes.arrayOf(PropTypes.string),- fileLoading: PropTypes.bool- };-- static defaultProps = {- validFileExt: defaultValidFileExt- };-- state = {- dragOver: false,- fileLoading: false,- files: [],- errorFiles: []- };-- static getDerivedStateFromProps(props, state) {- if (state.fileLoading && props.fileLoading === false && state.files.length) {+function FileUploadFactory() {+ class FileUpload extends Component {+ static propTypes = {+ onFileUpload: PropTypes.func.isRequired,+ validFileExt: PropTypes.arrayOf(PropTypes.string),+ fileLoading: PropTypes.bool+ };++ static defaultProps = {+ validFileExt: defaultValidFileExt+ };++ state = {+ dragOver: false,+ fileLoading: false,+ files: [],+ errorFiles: []+ };++ static getDerivedStateFromProps(props, state) {+ if (state.fileLoading && props.fileLoading === false && state.files.length) {+ return {+ files: [],+ fileLoading: props.fileLoading+ };+ }return {- files: [],fileLoading: props.fileLoading};}- return {- fileLoading: props.fileLoading++ frame = createRef();++ _isValidFileType = filename => {+ const {validFileExt} = this.props;+ const fileExt = validFileExt.find(ext => filename.endsWith(ext));++ return Boolean(fileExt);};- }- frame = createRef();+ _handleFileInput = (files, e) => {+ if (e) {+ e.stopPropagation();+ }- _isValidFileType = filename => {- const {validFileExt} = this.props;- const fileExt = validFileExt.find(ext => filename.endsWith(ext));+ const nextState = {files: [], errorFiles: [], dragOver: false};+ for (let i = 0; i < files.length; i++) {+ const file = files[i];- return Boolean(fileExt);- };+ if (file && this._isValidFileType(file.name)) {+ nextState.files.push(file);+ } else {+ nextState.errorFiles.push(file.name);+ }+ }- _handleFileInput = (files, e) => {- if (e) {- e.stopPropagation();- }+ this.setState(nextState, () =>+ nextState.files.length ? this.props.onFileUpload(nextState.files) : null+ );+ };- const nextState = {files: [], errorFiles: [], dragOver: false};- for (let i = 0; i < files.length; i++) {- const file = files[i];+ _toggleDragState = newState => {+ this.setState({dragOver: newState});+ };- if (file && this._isValidFileType(file.name)) {- nextState.files.push(file);- } else {- nextState.errorFiles.push(file.name);+ _renderMessage() {+ const {errorFiles, files} = this.state;+ if (errorFiles.length) {+ return <WarningMsg>{`File ${errorFiles.join(', ')} is not supported.`}</WarningMsg>;+ } else if (this.props.fileLoading && files.length) {+ return (+ <StyledMessage className="file-uploader__message">+ <div className="loading-action">Uploading</div>+ <div>+ {files.map((f, i) => (+ <PositiveMsg key={i}>{f.name}</PositiveMsg>+ ))}+ ...+ </div>+ <div className="loading-spinner">+ <LoadingSpinner size={20} />+ </div>+ </StyledMessage>+ );}- }- this.setState(nextState, () =>- nextState.files.length ? this.props.onFileUpload(nextState.files) : null- );- };+ return null;+ }- _toggleDragState = newState => {- this.setState({dragOver: newState});- };+ render() {+ const {dragOver, files} = this.state;+ const {validFileExt} = this.props;- _renderMessage() {- const {errorFiles, files} = this.state;- if (errorFiles.length) {- return <WarningMsg>{`File ${errorFiles.join(', ')} is not supported.`}</WarningMsg>;- } else if (this.props.fileLoading && files.length) {return (- <StyledMessage className="file-uploader__message">- <div className="loading-action">Uploading</div>- <div>- {files.map((f, i) => (- <PositiveMsg key={i}>{f.name}</PositiveMsg>- ))}- ...- </div>- <div className="loading-spinner">- <LoadingSpinner size={20} />- </div>- </StyledMessage>+ <StyledFileUpload className="file-uploader" ref={this.frame}>+ <input className="filter-upload__input" type="file" onChange={this._onChange} />+ {FileDrop ? (+ <FileDrop+ frame={this.frame.current || document}+ onDragOver={() => this._toggleDragState(true)}+ onDragLeave={() => this._toggleDragState(false)}+ onDrop={this._handleFileInput}+ className="file-uploader__file-drop"+ >+ <StyledUploadMessage className="file-upload__message">+ <ReactMarkdown source={CONFIG_UPLOAD_MESSAGE} renderers={{link: LinkRenderer}} />+ </StyledUploadMessage>+ <StyledFileDrop dragOver={dragOver}>+ <div style={{opacity: dragOver ? 0.5 : 1}}>+ <StyledDragNDropIcon>+ <StyledFileTypeFow className="file-type-row">+ {validFileExt.map(ext => (+ <FileType key={ext} ext={ext} height="50px" fontSize="9px" />+ ))}+ </StyledFileTypeFow>+ <DragNDrop height="44px" />+ </StyledDragNDropIcon>+ <div>{this._renderMessage()}</div>+ </div>+ {!files.length ? (+ <StyledDragFileWrapper>+ <MsgWrapper>{MESSAGE}</MsgWrapper>+ <span className="file-upload-or">or</span>+ <UploadButton onUpload={this._handleFileInput}>browse your files</UploadButton>+ </StyledDragFileWrapper>+ ) : null}+ <StyledDisclaimer>{DISCLAIMER}</StyledDisclaimer>+ </StyledFileDrop>+ </FileDrop>+ ) : null}++ <WarningMsg>{isChrome() ? CHROME_MSG : ''}</WarningMsg>+ </StyledFileUpload>);}-- return null;}- render() {- const {dragOver, files} = this.state;- const {validFileExt} = this.props;-- return (- <StyledFileUpload className="file-uploader" ref={this.frame}>- <input className="filter-upload__input" type="file" onChange={this._onChange} />- {FileDrop ? (- <FileDrop- frame={this.frame.current || document}- onDragOver={() => this._toggleDragState(true)}- onDragLeave={() => this._toggleDragState(false)}- onDrop={this._handleFileInput}- className="file-uploader__file-drop"- >- <StyledUploadMessage className="file-upload__message">- <ReactMarkdown source={CONFIG_UPLOAD_MESSAGE} renderers={{link: LinkRenderer}} />- </StyledUploadMessage>- <StyledFileDrop dragOver={dragOver}>- <div style={{opacity: dragOver ? 0.5 : 1}}>- <StyledDragNDropIcon>- <StyledFileTypeFow className="file-type-row">- {validFileExt.map(ext => (- <FileType key={ext} ext={ext} height="50px" fontSize="9px" />- ))}- </StyledFileTypeFow>- <DragNDrop height="44px" />- </StyledDragNDropIcon>- <div>{this._renderMessage()}</div>- </div>- {!files.length ? (- <StyledDragFileWrapper>- <MsgWrapper>{MESSAGE}</MsgWrapper>- <span className="file-upload-or">or</span>- <UploadButton onUpload={this._handleFileInput}>browse your files</UploadButton>- </StyledDragFileWrapper>- ) : null}- <StyledDisclaimer>{DISCLAIMER}</StyledDisclaimer>- </StyledFileDrop>- </FileDrop>- ) : null}-- <WarningMsg>{isChrome() ? CHROME_MSG : ''}</WarningMsg>- </StyledFileUpload>- );- }+ return polyfill(FileUpload);}-polyfill(FileUpload);--export default FileUpload;+export default FileUploadFactory;+export const FileUpload = FileUploadFactory();diff --git a/src/components/common/icons/arrow-left.js b/src/components/common/icons/arrow-left.jsindex 1d68e9000..3d7bf911e 100644--- a/src/components/common/icons/arrow-left.js+++ b/src/components/common/icons/arrow-left.js@@ -36,7 +36,12 @@ export default class ArrowLeft extends Component {render() {return (<Base {...this.props}>- <path d="M15.41 16.09l-4.58-4.59 4.58-4.59L14 5.5l-6 6 6 6z" />+ <g+ id="arrow-left"+ transform="translate(32.000000, 31.500000) scale(-1, 1) translate(-32.000000, -31.500000) translate(17.000000, 9.000000)"+ >+ <path d="M5.7,44.7 L1.2,40.3 C0.8,39.9 0.8,39.3 1.2,38.9 L17.6,23 L1.2,7 C0.8,6.6 0.8,6 1.2,5.5 L5.7,1.1 C6.1,0.7 6.8,0.7 7.2,1.1 L24.3,17.8 L28.8,22.2 C29.2,22.6 29.2,23.2 28.8,23.6 L24.2,28 L7.2,44.7 C6.8,45.1 6.1,45.1 5.7,44.7" />+ </g>{' '}</Base>);}diff --git a/src/components/common/loading-spinner.js b/src/components/common/loading-spinner.jsindex 909beefa3..a6bc4f81f 100644--- a/src/components/common/loading-spinner.js+++ b/src/components/common/loading-spinner.js@@ -31,10 +31,10 @@ const animationName = keyframes``;const Loader = styled.span`- border-left-color: rgb(198, 198, 198);- border-top-color: rgb(198, 198, 198);+ border-left-color: ${props => props.color || props.theme.primaryBtnBgd};animation: _preloader_spin_ 500ms linear infinite;border-radius: 50%;+ border-top-color: transparent;border-bottom-color: transparent;border-right-color: transparent;cursor: wait;@@ -43,8 +43,22 @@ const Loader = styled.span`animation-name: ${animationName};}`;-const LoadingSpinner = ({size = 32}) => (- <Loader style={{width: `${size}px`, height: `${size}px`}} />+const LoadingWrapper = styled.div`+ border-radius: 50%;+ border: 3px solid ${props => props.borderColor || props.theme.borderColorLT};+ padding: 2px;+`;++const LoadingSpinner = ({size = 32, color, borderColor, strokeWidth = 3, gap = 2}) => (+ <LoadingWrapper style={{width: `${size}px`, height: `${size}px`, padding: `${gap}px`}}>+ <Loader+ color={color}+ style={{+ width: `${size - strokeWidth * 2 - gap * 2}px`,+ height: `${size - strokeWidth * 2 - gap * 2}px`+ }}+ />+ </LoadingWrapper>);export default LoadingSpinner;diff --git a/src/components/index.js b/src/components/index.jsindex 8abf38383..db41026f6 100644--- a/src/components/index.js+++ b/src/components/index.js@@ -44,7 +44,6 @@ export {AddDataButtonFactory, default as LayerManagerFactory} from './side-panelexport {default as LayerPanelFactory} from './side-panel/layer-panel/layer-panel';export {default as LayerConfiguratorFactory} from './side-panel/layer-panel/layer-configurator';-export {default as DatasetSquare} from './common/styled-components';export {default as SourceDataCatalogFactory} from './side-panel/common/source-data-catalog';export {default as SourceDataSelectorFactory} from './side-panel/common/source-data-selector';export {default as DatasetTitleFactory} from './side-panel/common/dataset-title';@@ -63,13 +62,13 @@ export {default as LayerGroupSelectorFactory} from './side-panel/map-style-panelexport {default as MapStyleSelectorFactory} from './side-panel/map-style-panel/map-style-selector';export {default as CustomPanelsFactory} from './side-panel/custom-panel';-// // map container factories+// // map factoriesexport {default as MapPopoverFactory} from './map/map-popover';export {default as MapControlFactory} from './map/map-control';export {default as LayerHoverInfoFactory} from './map/layer-hover-info';export {default as CoordinateInfoFactory} from './map/coordinate-info';-// // modal container factories+// // modal factoriesexport {default as ModalDialogFactory} from './modals/modal-dialog';export {default as DeleteDatasetModalFactory} from './modals/delete-data-modal';export {default as DataTableModalFactory} from './modals/data-table-modal';@@ -78,12 +77,15 @@ export {default as ExportImageModalFactory} from './modals/export-image-modal';export {default as ExportDataModalFactory} from './modals/export-data-modal';export {default as AddMapStyleModalFactory} from './modals/add-map-style-modal';export {default as ExportMapModalFactory} from './modals/export-map-modal/export-map-modal';+export {default as ModalTabsFactory} from './modals/modal-tabs';+export {default as LoadStorageMapFactory} from './modals/load-storage-map';// // common factoryexport {default as AnimationControlFactory} from './common/animation-control/animation-control';export {default as SpeedControlFactory} from './common/animation-control/speed-control';export {default as AnimationPlaybacksFactory} from './common/animation-control/playback-controls';export {default as FloatingTimeDisplayFactory} from './common/animation-control/floating-time-display';+export {default as DatasetSquare} from './common/styled-components';// // Filtersexport {default as TimeWidgetFactory} from './filters/time-widget';@@ -97,7 +99,8 @@ export {default as RangeFilterFactory} from './filters/range-filter';export {injector, withState} from './injector';// Common Components-export {default as FileUpload} from './common/file-uploader/file-upload';+export {default as CloudTile} from './modals/cloud-tile';+export {default as FileUploadFactory, FileUpload} from './common/file-uploader/file-upload';export {default as ItemSelector} from './common/item-selector/item-selector';export {default as FieldSelector} from './common/field-selector';export {default as RangeSlider} from './common/range-slider';@@ -105,6 +108,7 @@ export {default as Modal, ModalFooter, ModalTitle} from './common/modal';export {default as AppLogo} from './common/logo';export {default as Switch} from './common/switch';export {default as LoadingSpinner} from './common/loading-spinner';+export {default as LoadingDialog} from './modals/loading-dialog';export * from './common/styled-components';import * as Icons from './common/icons';export {Icons};diff --git a/src/components/kepler-gl.js b/src/components/kepler-gl.jsindex cab6bd5a4..3267bb9e2 100644--- a/src/components/kepler-gl.js+++ b/src/components/kepler-gl.js@@ -38,7 +38,9 @@ import {KEPLER_GL_VERSION,THEME,DEFAULT_MAPBOX_API_URL,- SAVE_MAP_ID+ SAVE_MAP_ID,+ SHARE_MAP_ID,+ OVERWRITE_MAP_ID} from 'constants/default-settings';import {MISSING_MAPBOX_TOKEN} from 'constants/user-feedbacks';@@ -222,6 +224,7 @@ function KeplerGlFactory(mapState,uiState,visState,+ providerState,// actions,visStateActions,@@ -246,7 +249,8 @@ function KeplerGlFactory(hoverInfo,clicked,mousePos,- animationConfig+ animationConfig,+ mapInfo} = visState;const notificationPanelFields = {@@ -265,6 +269,7 @@ function KeplerGlFactory(layerClasses,interactionConfig,mapStyle,+ mapInfo,layerBlending,onSaveMap,uiState,@@ -272,7 +277,8 @@ function KeplerGlFactory(visStateActions,uiStateActions,width: this.props.sidePanelWidth,- availableProviders+ availableProviders,+ mapSaved: providerState.mapSaved};const mapFields = {@@ -317,7 +323,11 @@ function KeplerGlFactory());const isExporting =- uiState.currentModal === EXPORT_IMAGE_ID || uiState.currentModal === SAVE_MAP_ID;+ uiState.currentModal === EXPORT_IMAGE_ID ||+ uiState.currentModal === SAVE_MAP_ID ||+ uiState.currentModal === SHARE_MAP_ID ||+ uiState.currentModal === OVERWRITE_MAP_ID;+const theme = this.availableThemeSelector(this.props);return (@@ -373,8 +383,11 @@ function KeplerGlFactory(containerW={containerW}containerH={mapState.height}providerState={this.props.providerState}+ // User defined cloud provider propscloudProviders={this.props.cloudProviders}onExportToCloudSuccess={this.props.onExportToCloudSuccess}+ onLoadCloudMapSuccess={this.props.onLoadCloudMapSuccess}+ onLoadCloudMapError={this.props.onLoadCloudMapError}onExportToCloudError={this.props.onExportToCloudError}/></GlobalStyle>diff --git a/src/components/modal-container.js b/src/components/modal-container.jsindex e6d93bc8c..ebf3b5bd8 100644--- a/src/components/modal-container.js+++ b/src/components/modal-container.js@@ -22,6 +22,8 @@ import React, {Component} from 'react';import PropTypes from 'prop-types';import {css} from 'styled-components';import {findDOMNode} from 'react-dom';+import {createSelector} from 'reselect';+import get from 'lodash.get';import ModalDialogFactory from './modals/modal-dialog';import KeplerGlSchema from 'schemas';@@ -30,6 +32,7 @@ import {isValidMapInfo} from 'utils/map-info-utils';// modalsimport DeleteDatasetModalFactory from './modals/delete-data-modal';+import OverWriteMapModalFactory from './modals/overwrite-map-modal';import DataTableModalFactory from './modals/data-table-modal';import LoadDataModalFactory from './modals/load-data-modal';import ExportImageModalFactory from './modals/export-image-modal';@@ -52,7 +55,8 @@ import {EXPORT_MAP_ID,ADD_MAP_STYLE_ID,SAVE_MAP_ID,- SHARE_MAP_ID+ SHARE_MAP_ID,+ OVERWRITE_MAP_ID} from 'constants/default-settings';import {EXPORT_MAP_FORMATS} from '../constants/default-settings';@@ -69,8 +73,7 @@ const DataTableModalStyle = css`margin: 0 auto;`}`;--const DeleteDatasetModalStyled = css`+const smallModalCss = css`width: 40%;padding: 40px 40px 32px 40px;`;@@ -85,6 +88,7 @@ const DefaultStyle = css`ModalContainerFactory.deps = [DeleteDatasetModalFactory,+ OverWriteMapModalFactory,DataTableModalFactory,LoadDataModalFactory,ExportImageModalFactory,@@ -98,6 +102,7 @@ ModalContainerFactory.deps = [export default function ModalContainerFactory(DeleteDatasetModal,+ OverWriteMapModal,DataTableModal,LoadDataModal,ExportImageModal,@@ -125,7 +130,13 @@ export default function ModalContainerFactory(onSaveToStorage: PropTypes.func,cloudProviders: PropTypes.arrayOf(PropTypes.object)};-+ cloudProviders = props => props.cloudProviders;+ providerWithStorage = createSelector(this.cloudProviders, cloudProviders =>+ cloudProviders.filter(p => p.hasPrivateStorage())+ );+ providerWithShare = createSelector(this.cloudProviders, cloudProviders =>+ cloudProviders.filter(p => p.hasSharingUrl())+ );_closeModal = () => {this.props.uiStateActions.toggleModal(null);};@@ -167,26 +178,39 @@ export default function ModalContainerFactory(this._closeModal();};- _exportFileToCloud = ({provider, isPublic, closeModal}) => {+ _exportFileToCloud = ({provider, isPublic, overwrite, closeModal}) => {const toSave = exportMap(this.props);+this.props.providerActions.exportFileToCloud({mapData: toSave,provider,- isPublic,+ options: {+ isPublic,+ overwrite+ },closeModal,onSuccess: this.props.onExportToCloudSuccess,onError: this.props.onExportToCloudError});};- _onSaveMap = () => {+ _onSaveMap = (overwrite = false) => {const {currentProvider} = this.props.providerState;const provider = this.props.cloudProviders.find(p => p.name === currentProvider);- this._exportFileToCloud({provider, isPublic: false, closeModal: true});+ this._exportFileToCloud({+ provider,+ isPublic: false,+ overwrite,+ closeModal: true+ });+ };++ _onOverwriteMap = () => {+ this._onSaveMap(true);};_onShareMapUrl = provider => {- this._exportFileToCloud({provider, isPublic: true, closeModal: false});+ this._exportFileToCloud({provider, isPublic: true, overwrite: false, closeModal: false});};_onCloseSaveMap = () => {@@ -194,6 +218,14 @@ export default function ModalContainerFactory(this._closeModal();};+ _onLoadCloudMap = payload => {+ this.props.providerActions.loadCloudMap({+ ...payload,+ onSuccess: this.props.onLoadCloudMapSuccess,+ onError: this.props.onLoadCloudMapError+ });+ };+/* eslint-disable complexity */render() {const {@@ -206,9 +238,9 @@ export default function ModalContainerFactory(rootNode,visStateActions,uiStateActions,- cloudProviders,providerState} = this.props;+const {currentModal, datasetKeyToRemove} = uiState;const {datasets, layers, editingDataset} = visState;@@ -250,7 +282,7 @@ export default function ModalContainerFactory();modalProps = {title: 'Delete Dataset',- cssStyle: DeleteDatasetModalStyled,+ cssStyle: smallModalCss,footer: true,onConfirm: () => this._deleteDataset(datasetKeyToRemove),onCancel: this._closeModal,@@ -265,8 +297,14 @@ export default function ModalContainerFactory(case ADD_DATA_ID:template = (<LoadDataModal+ {...providerState}onClose={this._closeModal}onFileUpload={this._onFileUpload}+ onLoadCloudMap={this._onLoadCloudMap}+ cloudProviders={this.providerWithStorage(this.props)}+ onSetCloudProvider={this.props.providerActions.setCloudProvider}+ getSavedMaps={this.props.providerActions.getSavedMaps}+ loadFiles={uiState.loadFiles}{...uiState.loadFiles}/>);@@ -378,8 +416,8 @@ export default function ModalContainerFactory(exportImage={uiState.exportImage}mapInfo={visState.mapInfo}onSetMapInfo={visStateActions.setMapInfo}- onUpdateSetting={uiStateActions.setExportImageSetting}- cloudProviders={cloudProviders.filter(p => p.hasPrivateStorage())}+ onUpdateImageSetting={uiStateActions.setExportImageSetting}+ cloudProviders={this.providerWithStorage(this.props)}onSetCloudProvider={this.props.providerActions.setCloudProvider}/>);@@ -387,7 +425,7 @@ export default function ModalContainerFactory(title: 'Save Map',footer: true,onCancel: this._closeModal,- onConfirm: this._onSaveMap,+ onConfirm: () => this._onSaveMap(false),confirmButton: {large: true,disabled:@@ -398,14 +436,41 @@ export default function ModalContainerFactory(}};break;-+ case OVERWRITE_MAP_ID:+ template = (+ <OverWriteMapModal+ {...providerState}+ cloudProviders={this.props.cloudProviders}+ title={get(visState, ['mapInfo', 'title'])}+ onSetCloudProvider={this.props.providerActions.setCloudProvider}+ onUpdateImageSetting={uiStateActions.setExportImageSetting}+ />+ );+ modalProps = {+ title: 'Overwrite Existing File?',+ cssStyle: smallModalCss,+ footer: true,+ onConfirm: this._onOverwriteMap,+ onCancel: this._closeModal,+ confirmButton: {+ large: true,+ children: 'Yes',+ disabled:+ uiState.exportImage.exporting ||+ !isValidMapInfo(visState.mapInfo) ||+ !providerState.currentProvider+ }+ };+ break;case SHARE_MAP_ID:template = (<ShareMapModal{...providerState}- cloudProviders={cloudProviders.filter(p => p.hasSharingUrl())}+ isReady={!uiState.exportImage.exporting}+ cloudProviders={this.providerWithShare(this.props)}onExport={this._onShareMapUrl}onSetCloudProvider={this.props.providerActions.setCloudProvider}+ onUpdateImageSetting={uiStateActions.setExportImageSetting}/>);modalProps = {diff --git a/src/components/modals/cloud-tile.js b/src/components/modals/cloud-tile.jsindex a01b95f39..85e489df0 100644--- a/src/components/modals/cloud-tile.js+++ b/src/components/modals/cloud-tile.js@@ -22,6 +22,7 @@ import React from 'react';import styled from 'styled-components';import {Logout, Login} from 'components/common/icons';import {CenterVerticalFlexbox, Button} from 'components/common/styled-components';+import LoadingSpinner from 'components/common/loading-spinner';const StyledTileWrapper = styled.div.attrs({className: 'provider-tile__wrapper'@@ -112,7 +113,13 @@ const LogoutButton = ({onClick}) => (</Button>);-// eslint-disable-next-line complexity+const ActionButton = ({isConnected, actionName, isReady}) =>+ isConnected && actionName ? (+ <Button className="cloud-tile__action" small secondary disabled={!isReady}>+ {isReady ? actionName : <LoadingSpinner size={12} />}+ </Button>+ ) : null;+const CloudTile = ({// action when click on the tileonSelect,@@ -129,10 +136,13 @@ const CloudTile = ({// whether provider is selected as currentProviderisSelected,// whether user has logged in- isConnected+ isConnected,++ isReady = true}) => {const userName =typeof cloudProvider.getUserName === 'function' ? cloudProvider.getUserName() : null;+const onClickConnect =typeof onConnect === 'function'? onConnect@@ -148,11 +158,7 @@ const CloudTile = ({<StyledTileWrapper onClick={isConnected ? onSelect : onClickConnect} selected={isSelected}><StyledCloudName>{cloudProvider.displayName || cloudProvider.name}</StyledCloudName>{cloudProvider.icon ? <cloudProvider.icon height="64px" /> : null}- {isConnected && actionName ? (- <Button className="cloud-tile__action" small secondary>- {actionName}- </Button>- ) : null}+ <ActionButton isConnected={isConnected} actionName={actionName} isReady={isReady} />{userName && <StyledUserName>{userName}</StyledUserName>}{isSelected && <CheckMark />}</StyledTileWrapper>diff --git a/src/components/modals/error-display.js b/src/components/modals/error-display.jsnew file mode 100644index 000000000..ec4ffbeb7--- /dev/null+++ b/src/components/modals/error-display.js@@ -0,0 +1,39 @@+// Copyright (c) 2020 Uber Technologies, Inc.+//+// Permission is hereby granted, free of charge, to any person obtaining a copy+// of this software and associated documentation files (the "Software"), to deal+// in the Software without restriction, including without limitation the rights+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+// copies of the Software, and to permit persons to whom the Software is+// furnished to do so, subject to the following conditions:+//+// The above copyright notice and this permission notice shall be included in+// all copies or substantial portions of the Software.+//+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+// THE SOFTWARE.++import React from 'react';+import ErrorBoundary from 'components/common/error-boundary';+import NotificationItemFactory from 'components/notification-panel/notification-item';+const NotificationItem = NotificationItemFactory();++const ErrorDisplay = ({error}) => (+ <ErrorBoundary>+ <NotificationItem+ notification={{+ type: 'error',+ message: error,+ id: 'cloud-export-error'+ }}+ isExpanded+ />+ </ErrorBoundary>+);++export default ErrorDisplay;diff --git a/src/components/modals/export-image-modal.js b/src/components/modals/export-image-modal.jsindex e5330e558..cbc4f2d17 100644--- a/src/components/modals/export-image-modal.js+++ b/src/components/modals/export-image-modal.js@@ -23,7 +23,11 @@ import PropTypes from 'prop-types';import styled from 'styled-components';import ImagePreview from 'components/common/image-preview';-import {EXPORT_IMG_RATIO_OPTIONS, EXPORT_IMG_RESOLUTION_OPTIONS} from 'constants/default-settings';+import {+ EXPORT_IMG_RATIO_OPTIONS,+ EXPORT_IMG_RESOLUTION_OPTIONS,+ EXPORT_IMG_RATIOS+} from 'constants/default-settings';import {StyledModalContent, SelectionButton} from 'components/common/styled-components';import Switch from 'components/common/switch';@@ -73,7 +77,12 @@ const ExportImageModalFactory = () => {_updateMapDim() {const {exportImage, mapH, mapW} = this.props;if (mapH !== exportImage.mapH || mapW !== exportImage.mapW) {- this.props.onUpdateSetting({mapH, mapW});+ this.props.onUpdateSetting({+ mapH,+ mapW,+ ratio: EXPORT_IMG_RATIOS.CUSTOM,+ legend: false+ });}}diff --git a/src/components/modals/image-modal-container.js b/src/components/modals/image-modal-container.jsnew file mode 100644index 000000000..3c2c52e1d--- /dev/null+++ b/src/components/modals/image-modal-container.js@@ -0,0 +1,82 @@+// Copyright (c) 2020 Uber Technologies, Inc.+//+// Permission is hereby granted, free of charge, to any person obtaining a copy+// of this software and associated documentation files (the "Software"), to deal+// in the Software without restriction, including without limitation the rights+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+// copies of the Software, and to permit persons to whom the Software is+// furnished to do so, subject to the following conditions:+//+// The above copyright notice and this permission notice shall be included in+// all copies or substantial portions of the Software.+//+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+// THE SOFTWARE.++import React, {Component} from 'react';+import PropTypes from 'prop-types';+import get from 'lodash.get';++import {MAP_THUMBNAIL_DIMENSION, EXPORT_IMG_RATIOS} from 'constants/default-settings';++export default class ImageModalContainer extends Component {+ static propTypes = {+ onSetCloudProvider: PropTypes.func.isRequired,+ onUpdateImageSetting: PropTypes.func.isRequired,+ cloudProviders: PropTypes.arrayOf(PropTypes.object),+ currentProvider: PropTypes.string+ };++ static defaultProps = {+ cloudProviders: [],+ currentProvider: null+ };++ componentDidMount() {+ this._updateThumbSize();+ this._setDefaultProvider();+ }++ componentDidUpdate(prevProps) {+ // set thumbnail size if provider changes+ if (this.props.currentProvider !== prevProps.currentProvider) {+ this._updateThumbSize();+ }+ }++ _updateThumbSize() {+ if (this.props.currentProvider && this.props.cloudProviders.length) {+ const provider = this.props.cloudProviders.find(p => p.name === this.props.currentProvider);++ if (provider && provider.thumbnail) {+ this.props.onUpdateImageSetting({+ mapW: get(provider, ['thumbnail', 'width']) || MAP_THUMBNAIL_DIMENSION.width,+ mapH: get(provider, ['thumbnail', 'height']) || MAP_THUMBNAIL_DIMENSION.height,+ ratio: EXPORT_IMG_RATIOS.CUSTOM,+ legend: false+ });+ }+ }+ }++ _setDefaultProvider() {+ if (!this.props.currentProvider && this.props.cloudProviders.length) {+ const connected = this.props.cloudProviders.find(+ p => typeof p.getAccessToken === 'function' && p.getAccessToken()+ );++ if (connected) {+ this.props.onSetCloudProvider(connected.name);+ }+ }+ }++ render() {+ return <>{this.props.children}</>;+ }+}diff --git a/src/components/modals/load-data-modal.js b/src/components/modals/load-data-modal.jsindex de5506c80..0a43a8cbf 100644--- a/src/components/modals/load-data-modal.js+++ b/src/components/modals/load-data-modal.js@@ -18,32 +18,85 @@// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN// THE SOFTWARE.-import React from 'react';+import React, {useState} from 'react';import PropTypes from 'prop-types';import styled from 'styled-components';+import get from 'lodash.get';-import FileUpload from 'components/common/file-uploader/file-upload';+import FileUploadFactory from 'components/common/file-uploader/file-upload';+import LoadStorageMapFactory from './load-storage-map';+import ModalTabsFactory from './modal-tabs';-const StyledLoadDataModal = styled.div`+import LoadingDialog from './loading-dialog';+import {LOADING_METHODS} from 'constants/default-settings';++const StyledLoadDataModal = styled.div.attrs({+ className: 'load-data-modal'+})`padding: ${props => props.theme.modalPadding};+ min-height: 440px;+ display: flex;+ flex-direction: column;`;-const loadDataModalFactory = () => {- const LoadDataModal = props => (- <StyledLoadDataModal>- <div className="load-data-modal">- <FileUpload {...props} />- </div>- </StyledLoadDataModal>- );+const noop = () => {};+const getDefaultMethod = methods => (Array.isArray(methods) ? get(methods, [0]) : null);++LoadDataModalFactory.deps = [ModalTabsFactory, FileUploadFactory, LoadStorageMapFactory];++function LoadDataModalFactory(ModalTabs, FileUpload, LoadStorageMap) {+ const LoadDataModal = props => {+ const {fileLoading, loadingMethods} = props;+ const [currentMethod, toggleMethod] = useState(getDefaultMethod(loadingMethods));++ return (+ <StyledLoadDataModal>+ <ModalTabs+ currentMethod={currentMethod.id}+ loadingMethods={loadingMethods}+ toggleMethod={toggleMethod}+ />+ {fileLoading ? (+ <LoadingDialog size={64} />+ ) : (+ currentMethod && <currentMethod.elementType key={currentMethod.id} {...props} />+ )}+ </StyledLoadDataModal>+ );+ };LoadDataModal.propTypes = {// call backsonFileUpload: PropTypes.func.isRequired,- fileLoading: PropTypes.bool+ onLoadCloudMap: PropTypes.func.isRequired,+ fileLoading: PropTypes.bool,+ loadingMethods: PropTypes.arrayOf(+ PropTypes.shape({+ id: PropTypes.string,+ label: PropTypes.string,+ elementType: PropTypes.elementType,+ tabElementType: PropTypes.elementType+ })+ )};+ LoadDataModal.defaultProps = {+ onFileUpload: noop,+ fileLoading: false,+ loadingMethods: [+ {+ id: LOADING_METHODS.upload,+ label: 'Load Files',+ elementType: FileUpload+ },+ {+ id: LOADING_METHODS.storage,+ label: 'Load from Storage',+ elementType: LoadStorageMap+ }+ ]+ };return LoadDataModal;-};+}-export default loadDataModalFactory;+export default LoadDataModalFactory;diff --git a/src/components/modals/load-storage-map.js b/src/components/modals/load-storage-map.jsnew file mode 100644index 000000000..51482bf97--- /dev/null+++ b/src/components/modals/load-storage-map.js@@ -0,0 +1,321 @@+// Copyright (c) 2020 Uber Technologies, Inc.+//+// Permission is hereby granted, free of charge, to any person obtaining a copy+// of this software and associated documentation files (the "Software"), to deal+// in the Software without restriction, including without limitation the rights+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+// copies of the Software, and to permit persons to whom the Software is+// furnished to do so, subject to the following conditions:+//+// The above copyright notice and this permission notice shall be included in+// all copies or substantial portions of the Software.+//+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+// THE SOFTWARE.++import React, {Component} from 'react';+import styled from 'styled-components';+import moment from 'moment';++import LoadingDialog from './loading-dialog';+import {Button} from 'components/common/styled-components';+import CloudTile from './cloud-tile';+import {Base, ArrowLeft} from 'components/common/icons';++const StyledProviderSection = styled.div`+ display: flex;+`;++const StyledSpinner = styled.div`+ text-align: center;+ span {+ margin: 0 auto;+ }+`;++const StyledVisualizationSection = styled.div`+ display: flex;+ flex-direction: column;+ align-items: stretch;+`;++const StyledBackBtn = styled.a`+ font-size: 12px;+ line-height: 14px;+ margin-bottom: 16px;+ color: #3a414c;+ cursor: pointer;++ &:hover {+ font-weight: 500;+ }+`;++const StyledProviderVisSection = styled.div`+ flex: 1 1 auto;+ background-color: #f8f8f9;+ padding: 20px 24px;+ min-height: 280px;++ .title {+ font-size: 14px;+ line-height: 16px;+ font-weight: 500;+ margin-bottom: 16px;++ span {+ text-transform: capitalize;+ }+ }+`;++const StyledSeparator = styled.hr`+ border: solid #bfbfbf;+ border-width: 0 0 1px 0;+ margin-bottom: 16px;+`;++const StyledVisualizationList = styled.div`+ display: flex;+ flex-flow: row wrap;+ align-items: stretch;+ justify-content: space-between;+`;++const StyledVisualizationItem = styled.div`+ flex: 0 0 auto;+ width: 208px;+ display: flex;+ flex-direction: column;+ padding: 16px 8px;+ color: #3a414c;+ cursor: pointer;+ font-size: 12px;+ line-height: 18px;++ &:hover {+ .vis_item-icon,+ .vis_item-thumb,+ .vis_item-description,+ .vis_item-modification-date {+ opacity: 1;+ }+ }++ .vis_item-icon,+ .vis_item-thumb,+ .vis_item-description,+ .vis_item-modification-date {+ opacity: 0.9;+ transition: opacity 0.4s ease;+ }++ .vis_item-icon {+ position: relative;+ flex: 0 0 108px;+ background-color: #6a7484;+ border-radius: 4px;+ display: flex;+ flex-direction: row;+ align-items: center;+ justify-content: center;+ }++ .vis_item-thumb {+ position: relative;+ flex: 0 0 108px;+ background-size: cover;+ background-position: center;+ border-radius: 4px;+ }++ .vis_item-privacy {+ position: absolute;+ top: 0;+ left: 0;+ padding: 3px 6px;+ border-radius: 4px 0;+ background-color: rgba(58, 65, 76, 0.7);+ color: #fff;+ font-size: 11px;+ line-height: 18px;+ }++ .vis_item-title {+ margin-top: 16px;+ font-weight: 500;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }++ .vis_item-description {+ flex: 1 1 auto;+ margin-top: 8px;+ }++ .vis_item-modification-date {+ margin-top: 16px;+ flex: 1 0 auto;+ color: #6a7484;+ line-height: 15px;+ }+`;++const MapIcon = props => {+ return (+ <div {...props}>+ {props.children}+ <Base height="32px" viewBox={'0 0 16 16'}>+ <path+ fill="#d3d8d6"+ d="m13.6 11.572-3.2 2.1336v-9.2776l3.2-2.1336zm-12-7.144 3.2-2.1336v9.2776l-3.2 2.1336zm13.244 8.2376c0.2224-0.148 0.356-0.3984 0.356-0.6656v-11.2c0-0.2952-0.1624-0.5664-0.4224-0.7048-0.26-0.14-0.576-0.1248-0.8216 0.0392l-4.3128 2.876-3.5432-2.8352c-0.1208-0.0936-0.2952-0.1624-0.472-0.1688-0.1648-0.0064-0.348 0.0464-0.472 0.128l-4.8 3.2c-0.2224 0.1488-0.356 0.3984-0.356 0.6656v11.2c0 0.2952 0.1624 0.5664 0.4224 0.7056 0.1184 0.0632 0.248 0.0944 0.3776 0.0944 0.1552 0 0.3096-0.0448 0.444-0.1344l4.3128-2.876 3.5432 2.8352c0.1448 0.116 0.3216 0.1752 0.5 0.1752 0.1184 0 0.236-0.0248 0.3464-0.0784z"+ />+ </Base>+ </div>+ );+};++const PrivacyBadge = ({privateMap}) => (+ <span className="vis_item-privacy">{privateMap ? 'Private' : 'Public'}</span>+);++const VisualizationItem = ({vis, onClick}) => {+ return (+ <StyledVisualizationItem onClick={onClick}>+ {vis.thumbnail ? (+ <div className="vis_item-thumb" style={{backgroundImage: `url(${vis.thumbnail})`}}>+ {vis.hasOwnProperty('privateMap') ? <PrivacyBadge privateMap={vis.privateMap} /> : null}+ </div>+ ) : (+ <MapIcon className="vis_item-icon">+ {vis.hasOwnProperty('privateMap') ? <PrivacyBadge privateMap={vis.privateMap} /> : null}+ </MapIcon>+ )}+ <span className="vis_item-title">{vis.title}</span>+ {vis.description && vis.description.length && (+ <span className="vis_item-description">{vis.description}</span>+ )}+ <span className="vis_item-modification-date">+ Last modified {moment.utc(vis.lastModification).fromNow()}+ </span>+ </StyledVisualizationItem>+ );+};+const ProviderSelect = ({cloudProviders, onSetCloudProvider, currentProvider}) =>+ cloudProviders.length ? (+ <StyledProviderSection>+ {cloudProviders.map(provider => (+ <CloudTile+ key={provider.name}+ onSelect={() => onSetCloudProvider(provider.name)}+ onSetCloudProvider={onSetCloudProvider}+ cloudProvider={provider}+ isSelected={provider.name === currentProvider}+ isConnected={Boolean(provider.getAccessToken())}+ />+ ))}+ </StyledProviderSection>+ ) : (+ <p>No storage provider available</p>+ );++function LoadStorageMapFactory() {+ class LoadStorageMap extends Component {+ componentDidMount() {+ this._getSavedMaps();+ }+ componentDidUpdate(prevProps) {+ if (prevProps.currentProvider !== this.props.currentProvider) {+ this._getSavedMaps();+ }+ }++ _getProvider = () => {+ const {currentProvider, cloudProviders} = this.props;+ return (cloudProviders || []).find(p => p.name === currentProvider);+ };++ _getSavedMaps() {+ const provider = this._getProvider();+ if (provider) {+ this.props.getSavedMaps(provider);+ }+ }++ _onLoadCloudMap(provider, vis) {+ this.props.onLoadCloudMap({+ loadParams: vis.loadParams,+ provider+ });+ }+ render() {+ const {+ visualizations,+ cloudProviders,+ currentProvider = null,+ isProviderLoading,+ onSetCloudProvider+ } = this.props;++ const provider = this._getProvider();++ return (+ <div>+ {!provider ? (+ <ProviderSelect+ cloudProviders={cloudProviders}+ onSetCloudProvider={onSetCloudProvider}+ currentProvider={currentProvider}+ />+ ) : (+ <>+ {isProviderLoading && (+ <StyledSpinner>+ <LoadingDialog size={64} message="Loading..." />+ </StyledSpinner>+ )}+ {!isProviderLoading && visualizations && (+ <StyledVisualizationSection>+ <StyledBackBtn>+ <Button link onClick={() => onSetCloudProvider(null)}>+ <ArrowLeft height="14px" />+ Back+ </Button>+ </StyledBackBtn>+ <StyledProviderVisSection>+ <span className="title">+ <span>{currentProvider}</span> Storage / Maps+ </span>+ <StyledSeparator />+ <StyledVisualizationList>+ {visualizations.length ? (+ visualizations.map(vis => (+ <VisualizationItem+ key={vis.id}+ onClick={() => this._onLoadCloudMap(provider, vis)}+ vis={vis}+ />+ ))+ ) : (+ <div className="visualization-list__message">No saved maps yet</div>+ )}+ </StyledVisualizationList>+ </StyledProviderVisSection>+ </StyledVisualizationSection>+ )}+ </>+ )}+ </div>+ );+ }+ }+ return LoadStorageMap;+}++export default LoadStorageMapFactory;diff --git a/src/components/modals/loading-dialog.js b/src/components/modals/loading-dialog.jsnew file mode 100644index 000000000..3d8018475--- /dev/null+++ b/src/components/modals/loading-dialog.js@@ -0,0 +1,66 @@+// Copyright (c) 2020 Uber Technologies, Inc.+//+// Permission is hereby granted, free of charge, to any person obtaining a copy+// of this software and associated documentation files (the "Software"), to deal+// in the Software without restriction, including without limitation the rights+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+// copies of the Software, and to permit persons to whom the Software is+// furnished to do so, subject to the following conditions:+//+// The above copyright notice and this permission notice shall be included in+// all copies or substantial portions of the Software.+//+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+// THE SOFTWARE.++import React from 'react';+import styled from 'styled-components';+import LoadingSpinner from 'components/common/loading-spinner';++const StyledSpinner = styled.div`+ text-align: center;++ span {+ margin: 0 auto;+ }+`;++const StyledLoadingDialog = styled.div.attrs({+ className: 'data-loading-dialog'+})`+ display: flex;+ align-items: center;+ justify-content: center;+ flex-grow: 1;++ .loading-content {+ display: flex;+ justify-content: center;+ align-items: center;+ }++ .loading-message {+ margin-left: 32px;+ color: ${props => props.theme.titleColorLT};+ font-weight: 500;+ font-size: 14px;+ }+`;++const LoadingDialog = ({size = 64, message = 'Loading...'}) => (+ <StyledLoadingDialog>+ <div className="loading-content">+ <StyledSpinner>+ <LoadingSpinner size={size} />+ </StyledSpinner>+ <div className="loading-message">{message}</div>+ </div>+ </StyledLoadingDialog>+);++export default LoadingDialog;diff --git a/src/components/modals/modal-tabs.js b/src/components/modals/modal-tabs.jsnew file mode 100644index 000000000..481bdedef--- /dev/null+++ b/src/components/modals/modal-tabs.js@@ -0,0 +1,124 @@+// Copyright (c) 2020 Uber Technologies, Inc.+//+// Permission is hereby granted, free of charge, to any person obtaining a copy+// of this software and associated documentation files (the "Software"), to deal+// in the Software without restriction, including without limitation the rights+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+// copies of the Software, and to permit persons to whom the Software is+// furnished to do so, subject to the following conditions:+//+// The above copyright notice and this permission notice shall be included in+// all copies or substantial portions of the Software.+//+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+// THE SOFTWARE.++import React, {useCallback} from 'react';+import classnames from 'classnames';+import styled from 'styled-components';+import PropTypes from 'prop-types';+import {media} from 'styles';++const ModalTab = styled.div`+ align-items: flex-end;+ display: flex;+ border-bottom: 1px solid #d8d8d8;+ margin-bottom: 32px;+ justify-content: space-between;++ .load-data-modal__tab__inner {+ display: flex;+ width: 100%;+ }++ .load-data-modal__tab__item.active {+ color: ${props => props.theme.textColorLT};+ border-bottom: 3px solid ${props => props.theme.textColorLT};+ font-weight: 500;+ }++ ${media.portable`+ font-size: 12px;+ `};+`;++const StyledLoadDataModalTabItem = styled.div`+ border-bottom: 3px solid transparent;+ cursor: pointer;+ margin-left: 32px;+ padding: 16px 0;+ font-size: 14px;+ font-weight: 400;+ color: ${props => props.theme.subtextColorLT};++ ${media.portable`+ margin-left: 16px;+ font-size: 12px;+ `};++ :first-child {+ margin-left: 0;+ padding-left: 0;+ }++ :hover {+ color: ${props => props.theme.textColorLT};+ }+`;++const noop = () => {};++const ModalTabItem = ({currentMethod, method, toggleMethod}) => {+ const onClick = useCallback(() => toggleMethod(method), [method, toggleMethod]);++ return method.tabElementType ? (+ <method.tabElementType onClick={onClick} />+ ) : (+ <StyledLoadDataModalTabItem+ className={classnames('load-data-modal__tab__item', {+ active: currentMethod && method.id === currentMethod+ })}+ onClick={onClick}+ >+ <div>{method.label || method.id}</div>+ </StyledLoadDataModalTabItem>+ );+};++function ModalTabsFactory() {+ const ModalTabs = ({currentMethod, toggleMethod, loadingMethods}) => (+ <ModalTab className="load-data-modal__tab">+ <div className="load-data-modal__tab__inner">+ {loadingMethods.map(method => (+ <ModalTabItem+ key={method.id}+ method={method}+ currentMethod={currentMethod}+ toggleMethod={toggleMethod}+ />+ ))}+ </div>+ </ModalTab>+ );++ ModalTabs.propTypes = {+ toggleMethod: PropTypes.func.isRequired,+ currentMethod: PropTypes.string,+ loadingMethods: PropTypes.arrayOf(PropTypes.object)+ };++ ModalTabs.defaultProps = {+ toggleMethod: noop,+ currentMethod: null,+ loadingMethods: []+ };++ return ModalTabs;+}++export default ModalTabsFactory;diff --git a/src/components/modals/overwrite-map-modal.js b/src/components/modals/overwrite-map-modal.jsnew file mode 100644index 000000000..e4f278b72--- /dev/null+++ b/src/components/modals/overwrite-map-modal.js@@ -0,0 +1,90 @@+// Copyright (c) 2020 Uber Technologies, Inc.+//+// Permission is hereby granted, free of charge, to any person obtaining a copy+// of this software and associated documentation files (the "Software"), to deal+// in the Software without restriction, including without limitation the rights+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+// copies of the Software, and to permit persons to whom the Software is+// furnished to do so, subject to the following conditions:+//+// The above copyright notice and this permission notice shall be included in+// all copies or substantial portions of the Software.+//+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+// THE SOFTWARE.++import React from 'react';+import styled from 'styled-components';+import {CenterVerticalFlexbox} from 'components/common/styled-components';+import {UploadAnimation} from './status-panel';+import ImageModalContainer from './image-modal-container';++const StyledMsg = styled.div`+ margin-top: 24px;+ font-size: 14px;+`;++const StyledTitle = styled.span`+ font-weight: 600;+ color: black;+`;++const StyledIcon = styled.div`+ margin-top: 24px;+`;++const StyledOverwriteMapModal = styled(CenterVerticalFlexbox)`+ padding: 24px 12px;+ min-height: 220px;+`;++const OverwriteMapModalFactory = () => {+ const OverwriteMapModal = ({+ mapSaved,+ title,+ currentProvider,+ cloudProviders,+ isProviderLoading,+ onUpdateImageSetting,+ onSetCloudProvider+ }) => {+ const provider = cloudProviders.find(cp => cp.name === currentProvider);+ return (+ <ImageModalContainer+ currentProvider={currentProvider}+ cloudProviders={cloudProviders}+ onUpdateImageSetting={onUpdateImageSetting}+ onSetCloudProvider={onSetCloudProvider}+ >+ <StyledOverwriteMapModal className="overwrite-map-modal">+ {isProviderLoading ? (+ <StyledMsg>+ <StyledTitle>Saving map...</StyledTitle>+ <UploadAnimation icon={provider && provider.icon} />+ </StyledMsg>+ ) : (+ <>+ <StyledIcon>+ {provider && provider.icon ? <provider.icon height="64px" /> : null}+ </StyledIcon>+ <StyledMsg className="overwrite-map-msg">+ <StyledTitle>{title}</StyledTitle>+ {` already exists in your ${mapSaved}. Would you like to overwrite it?`}+ </StyledMsg>+ </>+ )}+ </StyledOverwriteMapModal>+ </ImageModalContainer>+ );+ };+ return OverwriteMapModal;+};++export const OverwriteMapModal = OverwriteMapModalFactory();++export default OverwriteMapModalFactory;diff --git a/src/components/modals/save-map-modal.js b/src/components/modals/save-map-modal.jsindex d2d0fd5d8..8a45d1d20 100644--- a/src/components/modals/save-map-modal.js+++ b/src/components/modals/save-map-modal.js@@ -22,12 +22,10 @@ import React, {Component} from 'react';import PropTypes from 'prop-types';import styled from 'styled-components';import CloudTile from './cloud-tile';+import ImageModalContainer from './image-modal-container';+import {UploadAnimation} from './status-panel';-import {- MAP_THUMBNAIL_DIMENSION,- MAP_INFO_CHARACTER,- EXPORT_IMG_RATIOS-} from 'constants/default-settings';+import {MAP_THUMBNAIL_DIMENSION, MAP_INFO_CHARACTER} from 'constants/default-settings';import {StyledModalContent,@@ -70,52 +68,79 @@ const StyledSaveMapModal = styled.div.attrs({}`;+const nop = () => {};++export const MapInfoPanel = ({+ mapInfo = {description: '', title: ''},+ characterLimits,+ onChangeInput+}) => (+ <div className="selection map-info-panel">+ <StyledModalSection className="save-map-modal-name">+ <div className="modal-section-title">Name*</div>+ <div>+ <InputLight+ id="map-title"+ type="text"+ value={mapInfo.title}+ onChange={e => onChangeInput('title', e)}+ placeholder="Type map title"+ />+ </div>+ </StyledModalSection>+ <StyledModalSection>+ <div className="save-map-modal-description" style={{display: 'flex'}}>+ <div className="modal-section-title">Description</div>+ <div className="modal-section-subtitle">(optional)</div>+ </div>+ <div>+ <TextAreaLight+ rows="3"+ id="map-description"+ style={{resize: 'none'}}+ value={mapInfo.description}+ onChange={e => onChangeInput('description', e)}+ placeholder="Type map description"+ />+ </div>+ <StyledModalInputFootnote+ className="save-map-modal-description__footnote"+ error={+ characterLimits.description && mapInfo.description.length > characterLimits.description+ }+ >+ {mapInfo.description.length}/{characterLimits.description || MAP_INFO_CHARACTER.description}{' '}+ characters+ </StyledModalInputFootnote>+ </StyledModalSection>+ </div>+);+function SaveMapModalFactory() {class SaveMapModal extends Component {static propTypes = {exportImage: PropTypes.object.isRequired,mapInfo: PropTypes.object.isRequired,- onSetMapInfo: PropTypes.func.isRequired,- onSetCloudProvider: PropTypes.func.isRequired,- isLoading: PropTypes.bool.isRequired,+ isProviderLoading: PropTypes.bool.isRequired,thumbWidth: PropTypes.number,thumbHeight: PropTypes.number,characterLimits: PropTypes.object,cloudProviders: PropTypes.arrayOf(PropTypes.object),- currentProvider: PropTypes.string+ currentProvider: PropTypes.string,+ onSetMapInfo: PropTypes.func.isRequired,+ onSetCloudProvider: PropTypes.func.isRequired,+ onUpdateImageSetting: PropTypes.func.isRequired};static defaultProps = {- thumbWidth: MAP_THUMBNAIL_DIMENSION.width,- thumbHeight: MAP_THUMBNAIL_DIMENSION.height,characterLimits: MAP_INFO_CHARACTER,cloudProviders: [],currentProvider: null,- isLoading: false,- mapInfo: {title: '', description: ''}+ providerError: null,+ isProviderLoading: false,+ onSetCloudProvider: nop};- componentDidMount() {- this.props.onUpdateSetting({- mapW: this.props.thumbWidth,- mapH: this.props.thumbHeight,- ratio: EXPORT_IMG_RATIOS.CUSTOM- });- this._setDefaultProvider();- }-- _setDefaultProvider() {- if (!this.props.currentProvider && this.props.cloudProviders.length) {- const connected = this.props.cloudProviders.find(- p => typeof p.getAccessToken === 'function' && p.getAccessToken()- );-- if (connected) {- this.props.onSetCloudProvider(connected.name);- }- }- }-_onChangeInput = (key, e) => {const {target: {value}@@ -129,83 +154,67 @@ function SaveMapModalFactory() {exportImage,characterLimits = {},cloudProviders,- isLoading,+ isProviderLoading,currentProvider,- onSetCloudProvider+ onSetCloudProvider,+ onUpdateImageSetting} = this.props;+ const provider = currentProvider+ ? cloudProviders.find(p => p.name === currentProvider)+ : null;return (- <StyledSaveMapModal>- <StyledModalContent className="save-map-modal-content">- <StyledExportSection disabled={isLoading}>- <div className="description">- <div className="title">Cloud storage</div>- <div className="subtitle">Login save map to your personal cloud storage</div>- </div>- <div className="selection">- {cloudProviders.map(cloudProvider => (- <CloudTile- key={cloudProvider.name}- onSelect={() => onSetCloudProvider(cloudProvider.name)}- onSetCloudProvider={onSetCloudProvider}- cloudProvider={cloudProvider}- isSelected={cloudProvider.name === currentProvider}- isConnected={Boolean(cloudProvider.getAccessToken())}- />- ))}- </div>- </StyledExportSection>- <StyledExportSection>- <div className="description image-preview-panel">- <ImagePreview- exportImage={exportImage}- width={this.props.thumbWidth}- showDimension={false}- />- </div>- <div className="selection map-info-panel">- <StyledModalSection className="save-map-modal-name">- <div className="modal-section-title">Name*</div>- <div>- <InputLight- id="map-title"- type="text"- value={mapInfo.title}- onChange={e => this._onChangeInput('title', e)}- placeholder="Type map title"- />- </div>- </StyledModalSection>- <StyledModalSection>- <div className="save-map-modal-description" style={{display: 'flex'}}>- <div className="modal-section-title">Description</div>- <div className="modal-section-subtitle">(optional)</div>- </div>- <div>- <TextAreaLight- rows="3"- id="map-description"- style={{resize: 'none'}}- value={mapInfo.description}- onChange={e => this._onChangeInput('description', e)}- placeholder="Type map description"+ <ImageModalContainer+ currentProvider={currentProvider}+ cloudProviders={cloudProviders}+ onUpdateImageSetting={onUpdateImageSetting}+ onSetCloudProvider={onSetCloudProvider}+ >+ <StyledSaveMapModal>+ <StyledModalContent className="save-map-modal-content">+ <StyledExportSection disabled={isProviderLoading}>+ <div className="description">+ <div className="title">Cloud storage</div>+ <div className="subtitle">Login save map to your personal cloud storage</div>+ </div>+ <div className="selection">+ {cloudProviders.map(cloudProvider => (+ <CloudTile+ key={cloudProvider.name}+ onSelect={() => onSetCloudProvider(cloudProvider.name)}+ onSetCloudProvider={onSetCloudProvider}+ cloudProvider={cloudProvider}+ isSelected={cloudProvider.name === currentProvider}+ isConnected={Boolean(+ cloudProvider.getAccessToken && cloudProvider.getAccessToken()+ )}/>+ ))}+ </div>+ </StyledExportSection>+ <StyledExportSection>+ <div className="description image-preview-panel">+ <ImagePreview+ exportImage={exportImage}+ width={MAP_THUMBNAIL_DIMENSION.width}+ showDimension={false}+ />+ </div>+ {isProviderLoading ? (+ <div className="selection map-saving-animation">+ <UploadAnimation icon={provider && provider.icon} /></div>- <StyledModalInputFootnote- className="save-map-modal-description__footnote"- error={- characterLimits.description &&- mapInfo.description.length > characterLimits.description- }- >- {mapInfo.description.length}/- {characterLimits.description || MAP_INFO_CHARACTER.description} characters- </StyledModalInputFootnote>- </StyledModalSection>- </div>- </StyledExportSection>- </StyledModalContent>- </StyledSaveMapModal>+ ) : (+ <MapInfoPanel+ mapInfo={mapInfo}+ characterLimits={characterLimits}+ onChangeInput={this._onChangeInput}+ />+ )}+ </StyledExportSection>+ </StyledModalContent>+ </StyledSaveMapModal>+ </ImageModalContainer>);}}diff --git a/src/components/modals/share-map-modal.js b/src/components/modals/share-map-modal.jsindex b75ab213d..69abcae9a 100644--- a/src/components/modals/share-map-modal.js+++ b/src/components/modals/share-map-modal.js@@ -21,13 +21,14 @@import React, {useState, Component} from 'react';import styled, {ThemeProvider} from 'styled-components';import {CopyToClipboard} from 'react-copy-to-clipboard';-import {Button} from 'components/common/styled-components';import {themeLT} from 'styles/base';+import ImageModalContainer from './image-modal-container';import {StyledModalContent,StyledExportSection,- InputLight+ InputLight,+ Button} from 'components/common/styled-components';import CloudTile from './cloud-tile';import StatusPanel from './status-panel';@@ -73,19 +74,6 @@ export const SharingUrl = ({url, message}) => {};const nop = () => {};-export const MAP_URI = 'demo/map?mapUrl=';--/**- * Returns a permalink with the given map url: kepler.gl/[]- * @param mapLink the cloud-providers url used to store the map- * @returns {string}- */-export function getMapPermalink(mapLink, fullURL = true) {- return fullURL- ? `${window.location.protocol}//${window.location.host}/${MAP_URI}${mapLink}`- : `/${MAP_URI}${mapLink}`;-}-const StyledShareMapModal = styled(StyledModalContent)`padding: 24px 72px 40px 72px;margin: 0 -72px -40px -72px;@@ -98,117 +86,104 @@ const StyledInnerDiv = styled.div`export default function ShareMapUrlModalFactory() {class ShareMapUrlModal extends Component {static defaultProps = {- isLoading: false,+ isProviderLoading: false,onExport: nop,cloudProviders: [],currentProvider: null,- error: null,+ providerError: null,successInfo: {},onSetCloudProvider: nop};- componentDidMount() {- this._setDefaultProvider();- }-- _setDefaultProvider() {- if (!this.props.currentProvider && this.props.cloudProviders.length) {- const connected = this.props.cloudProviders.find(- p => typeof p.getAccessToken === 'function' && p.getAccessToken()- );-- if (connected) {- this.props.onSetCloudProvider(connected.name);- }- }- }-render() {const {- isLoading,+ isProviderLoading,+ isReady,onExport,cloudProviders,currentProvider,- error,+ providerError,successInfo,- onSetCloudProvider+ onSetCloudProvider,+ onUpdateImageSetting} = this.props;- const {metaUrl, folderLink} = successInfo;+ const {shareUrl, folderLink} = successInfo;const provider = currentProvider? cloudProviders.find(p => p.name === currentProvider): null;- // TODO: A better way to obtain sharingLink- const sharingLink = metaUrl- ? provider && provider.getMapPermalink- ? provider.getMapPermalink(metaUrl, true)- : getMapPermalink(metaUrl, true)- : null;-return (<ThemeProvider theme={themeLT}>- <StyledShareMapModal className="export-cloud-modal">- <StyledInnerDiv>- <StyledExportSection>- <div className="description">- <div className="title">Share Map Url</div>- <div className="subtitle">Generate a map url to share with others</div>- </div>- <div className="selection">- <div className="title warning">{SHARE_DISCLAIMER}</div>- </div>- </StyledExportSection>- <StyledExportSection disabled={isLoading}>- <div className="description">- <div className="title">Cloud storage</div>- <div className="subtitle">- Login and upload map data to your personal cloud storage- </div>- </div>- <div className="selection">- {cloudProviders.map(cloudProvider => (- <CloudTile- key={cloudProvider.name}- onSelect={() => onExport(cloudProvider)}- onSetCloudProvider={onSetCloudProvider}- cloudProvider={cloudProvider}- actionName="Upload"- isSelected={cloudProvider.name === currentProvider}- isConnected={Boolean(cloudProvider.getAccessToken())}- />- ))}- </div>- </StyledExportSection>- {isLoading || error ? (- <StatusPanel- isLoading={isLoading}- error={error}- providerIcon={provider && provider.icon}- />- ) : null}- {sharingLink && (+ <ImageModalContainer+ currentProvider={currentProvider}+ cloudProviders={cloudProviders}+ onUpdateImageSetting={onUpdateImageSetting}+ onSetCloudProvider={onSetCloudProvider}+ >+ <StyledShareMapModal className="export-cloud-modal">+ <StyledInnerDiv><StyledExportSection><div className="description">- <div className="title">Share Url</div>+ <div className="title">Share Map Url</div>+ <div className="subtitle">Generate a map url to share with others</div>+ </div>+ <div className="selection">+ <div className="title warning">{SHARE_DISCLAIMER}</div>+ </div>+ </StyledExportSection>+ <StyledExportSection disabled={isProviderLoading}>+ <div className="description">+ <div className="title">Cloud storage</div>+ <div className="subtitle">+ Login and upload map data to your personal cloud storage+ </div></div><div className="selection">- <SharingUrl key={0} url={sharingLink} />- {folderLink && (- <a- key={1}- href={folderLink}- target="_blank"- rel="noopener noreferrer"- style={{textDecoration: 'underline'}}- >- Go to your Kepler.gl {currentProvider} page- </a>- )}+ {cloudProviders.map(cloudProvider => (+ <CloudTile+ key={cloudProvider.name}+ onSelect={() => onExport(cloudProvider)}+ onSetCloudProvider={onSetCloudProvider}+ cloudProvider={cloudProvider}+ actionName="Upload"+ isSelected={cloudProvider.name === currentProvider}+ isConnected={Boolean(cloudProvider.getAccessToken())}+ isReady={isReady}+ />+ ))}</div></StyledExportSection>- )}- </StyledInnerDiv>- </StyledShareMapModal>+ {isProviderLoading || providerError ? (+ <StatusPanel+ isLoading={isProviderLoading}+ error={providerError}+ providerIcon={provider && provider.icon}+ />+ ) : null}+ {shareUrl && (+ <StyledExportSection>+ <div className="description">+ <div className="title">Share Url</div>+ </div>+ <div className="selection">+ <SharingUrl key={0} url={shareUrl} />+ {folderLink && (+ <a+ key={1}+ href={folderLink}+ target="_blank"+ rel="noopener noreferrer"+ style={{textDecoration: 'underline'}}+ >+ Go to your Kepler.gl {currentProvider} page+ </a>+ )}+ </div>+ </StyledExportSection>+ )}+ </StyledInnerDiv>+ </StyledShareMapModal>+ </ImageModalContainer></ThemeProvider>);}diff --git a/src/components/modals/status-panel.js b/src/components/modals/status-panel.jsindex 0b6bbfe22..d8feaec2c 100644--- a/src/components/modals/status-panel.js+++ b/src/components/modals/status-panel.js@@ -22,10 +22,8 @@ import React from 'react';import styled from 'styled-components';import {MapIcon} from 'components/common/icons';import {StyledExportSection} from 'components/common/styled-components';-import NotificationItemFactory from 'components/notification-panel/notification-item';-import ErrorBoundary from 'components/common/error-boundary';+import ErrorDisplay from './error-display';-const NotificationItem = NotificationItemFactory();const StyledUploader = styled.div`display: flex;align-items: center;@@ -65,20 +63,7 @@ const Line = () => (</StyledSvg>);-const ErrorDisplay = ({error}) => (- <ErrorBoundary>- <NotificationItem- notification={{- type: 'error',- message: error,- id: 'cloud-export-error'- }}- isExpanded- />- </ErrorBoundary>-);--const UploadAnimation = props => (+export const UploadAnimation = props => (<StyledUploader><StyledMapIcon><MapIcon height="48px" />diff --git a/src/components/modals/storage-map-viewer.js b/src/components/modals/storage-map-viewer.jsnew file mode 100644index 000000000..181dc6dd1--- /dev/null+++ b/src/components/modals/storage-map-viewer.js@@ -0,0 +1,169 @@+// Copyright (c) 2020 Uber Technologies, Inc.+//+// Permission is hereby granted, free of charge, to any person obtaining a copy+// of this software and associated documentation files (the "Software"), to deal+// in the Software without restriction, including without limitation the rights+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+// copies of the Software, and to permit persons to whom the Software is+// furnished to do so, subject to the following conditions:+//+// The above copyright notice and this permission notice shall be included in+// all copies or substantial portions of the Software.+//+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+// THE SOFTWARE.++import React from 'react';+import PropTypes from 'prop-types';+import styled from 'styled-components';+import moment from 'moment';+import {LeftArrow} from 'components/common/icons';++const imageH = 108;++const propTypes = {+ onLoadAsset: PropTypes.func.isRequired,+ back: PropTypes.func.isRequired+};++const StyledAssetGallery = styled.div.attrs({+ className: 'storage-asset-gallery'+})`+ display: flex;+ justify-content: flex-start;+ flex-wrap: wrap;+`;++const StyledAssetItem = styled.div.attrs({+ className: 'asset__item'+})`+ width: 23%;+ margin-right: 2%;+ max-width: 500px;+ margin-bottom: 40px;+ height: 245px;+ display: flex;+ flex-direction: column;+ justify-content: space-between;++ :last {+ margin-right: 0;+ }++ .asset__title {+ font-size: 12px;+ font-weight: 500;+ color: ${props => props.theme.textColorLT};+ line-height: 18px;+ height: 32px;+ }++ .asset__image {+ border-radius: 4px;+ overflow: hidden;+ margin-bottom: 12px;+ opacity: 0.9;+ transition: opacity 0.4s ease;+ position: relative;+ line-height: 0;+ height: ${imageH}px;+ flex-shrink: 0;++ img {+ max-width: 100%;+ }+ :hover {+ cursor: pointer;+ opacity: 1;+ }+ }++ .asset__image__caption {+ font-size: 11px;+ font-weight: 400;+ line-height: 16px;+ margin-top: 10px;+ height: 48px;+ overflow: hidden;+ display: -webkit-box;+ text-overflow: ellipsis;+ -webkit-line-clamp: 3;+ -webkit-box-orient: vertical;+ }++ .asset__last-updated {+ font-size: 11px;+ color: ${props => props.theme.textColorLT};+ }+`;++const BackLink = styled.div`+ display: flex;+ font-size: 14px;+ align-items: center;+ color: ${props => props.theme.titleColorLT};+ cursor: pointer;+ margin-bottom: 40px;++ :hover {+ font-weight: 500;+ }++ span {+ white-space: nowrap;+ }+ svg {+ margin-right: 10px;+ }+`;++const StyledError = styled.div`+ color: red;+ font-size: 14px;+ margin-bottom: 16px;+`;++const getDuration = last => moment.duration(new Date().valueOf() - last).humanize();++const AssetItem = ({asset, onClick}) => (+ <StyledAssetItem>+ <div className="asset__image" onClick={onClick}>+ {asset.imageUrl && <img src={asset.imageUrl} />}+ </div>+ <div className="asset__title">{asset.label || asset.title}</div>+ <div className="asset__image__caption">{asset.description}</div>+ {asset.lastUpdated ? (+ <div className="asset__last-updated">Last Modified {getDuration(asset.lastUpdated)} ago</div>+ ) : null}+ </StyledAssetItem>+);++class StorageAssetsViewer extends React.Component {+ static propTypes = propTypes;++ render() {+ const {assets, onLoadAsset, back, error} = this.props;++ return (+ <div className="storage-asset-viewer">+ <BackLink onClick={back}>+ <LeftArrow height="12px" />+ <span>Back</span>+ </BackLink>+ {error && <StyledError>{error.message}</StyledError>}+ <StyledAssetGallery>+ {assets.map(sp => (+ <AssetItem asset={sp} key={sp.id} onClick={() => onLoadAsset(sp)} />+ ))}+ </StyledAssetGallery>+ </div>+ );+ }+}++export default StorageAssetsViewer;diff --git a/src/components/plot-container.js b/src/components/plot-container.jsindex 0ae706317..bc88e4721 100644--- a/src/components/plot-container.js+++ b/src/components/plot-container.js@@ -89,10 +89,11 @@ export default function PlotContainerFactory(MapContainer) {if (imageSize.scale) {return imageSize.scale;}+const scale = getScaleFromImageSize(imageSize.imageW,imageSize.imageH,- mapState.width,+ mapState.width * (mapState.isSplit ? 2 : 1),mapState.height);@@ -130,8 +131,10 @@ export default function PlotContainerFactory(MapContainer) {};render() {- const {exportImageSetting, mapFields} = this.props;+ const {exportImageSetting, mapFields, splitMaps} = this.props;const {imageSize = {}, legend} = exportImageSetting;+ const isSplit = splitMaps && splitMaps.length > 1;+const size = {width: imageSize.imageW || 1,height: imageSize.imageH || 1@@ -144,7 +147,8 @@ export default function PlotContainerFactory(MapContainer) {// override viewport based on export settingsmapState: {...mapFields.mapState,- ...size,+ width: size.width / (isSplit ? 2 : 1),+ height: size.height,zoom: mapFields.mapState.zoom + (Math.log2(scale) || 0)},mapControls: {@@ -154,9 +158,25 @@ export default function PlotContainerFactory(MapContainer) {active: true}},- MapComponent: StaticMap+ MapComponent: StaticMap,+ onMapRender: this._onMapRender,+ isExport: true,+ deckGlProps};+ const mapContainers = !isSplit ? (+ <MapContainer index={0} {...mapProps} />+ ) : (+ splitMaps.map((settings, index) => (+ <MapContainer+ key={index}+ index={index}+ {...mapProps}+ mapLayers={splitMaps[index].layers}+ />+ ))+ );+return (<StyledPlotContainerstyle={{position: 'absolute', top: -9999, left: -9999}}@@ -166,16 +186,11 @@ export default function PlotContainerFactory(MapContainer) {ref={this.plottingAreaRef}style={{width: `${size.width}px`,- height: `${size.height}px`+ height: `${size.height}px`,+ display: 'flex'}}>- <MapContainer- index={0}- onMapRender={this._onMapRender}- isExport- deckGlProps={deckGlProps}- {...mapProps}- />+ {mapContainers}</div></StyledPlotContainer>);diff --git a/src/components/side-panel.js b/src/components/side-panel.jsindex b40c90c20..55bc326dc 100644--- a/src/components/side-panel.js+++ b/src/components/side-panel.js@@ -41,7 +41,8 @@ import {EXPORT_MAP_ID,SAVE_MAP_ID,SHARE_MAP_ID,- SIDEBAR_PANELS+ SIDEBAR_PANELS,+ OVERWRITE_MAP_ID} from 'constants/default-settings';const SidePanelContent = styled.div`@@ -103,6 +104,7 @@ export default function SidePanelFactory(visStateActions: PropTypes.object.isRequired,mapStyleActions: PropTypes.object.isRequired,availableProviders: PropTypes.object,+ mapSaved: PropTypes.string,panels: PropTypes.arrayOf(PropTypes.object)};@@ -115,6 +117,15 @@ export default function SidePanelFactory(availableProviders: {}};+ static defaultProps = {+ panels: SIDEBAR_PANELS,+ uiState: {},+ visStateActions: {},+ mapStyleActions: {},+ uiStateActions: {},+ availableProviders: {}+ };+/* component private functions */_onOpenOrClose = () => {this.props.uiStateActions.toggleSidePanel(@@ -147,10 +158,21 @@ export default function SidePanelFactory(_onClickExportMap = () => this.props.uiStateActions.toggleModal(EXPORT_MAP_ID);- _onClickSaveToStorage = () => this.props.uiStateActions.toggleModal(SAVE_MAP_ID);+ _onClickSaveToStorage = () => {+ this.props.uiStateActions.toggleModal(this.props.mapSaved ? OVERWRITE_MAP_ID : SAVE_MAP_ID);+ };++ _onClickSaveAsToStorage = () => {+ // add (copy) to file name+ this.props.visStateActions.setMapInfo({+ title: `${this.props.mapInfo.title || 'Kepler.gl'} (Copy)`+ });+ this.props.uiStateActions.toggleModal(SAVE_MAP_ID);+ };_onClickShareMap = () => this.props.uiStateActions.toggleModal(SHARE_MAP_ID);+ // eslint-disable-next-line complexityrender() {const {appName,@@ -235,6 +257,11 @@ export default function SidePanelFactory(onExportMap={this._onClickExportMap}onSaveMap={this.props.onSaveMap}onSaveToStorage={availableProviders.hasStorage ? this._onClickSaveToStorage : null}+ onSaveAsToStorage={+ availableProviders.hasStorage && this.props.mapSaved+ ? this._onClickSaveAsToStorage+ : null+ }onShareMap={availableProviders.hasShare ? this._onClickShareMap : null}/><PanelToggle@@ -276,7 +303,7 @@ export default function SidePanelFactory({activeSidePanel === 'map' && (<MapManager {...mapManagerActions} mapStyle={this.props.mapStyle} />)}- {customPanels.length && customPanels.find(p => p.id === activeSidePanel) ? (+ {(customPanels || []).find(p => p.id === activeSidePanel) ? (<CustomPanels{...getCustomPanelProps(this.props)}activeSidePanel={activeSidePanel}diff --git a/src/components/side-panel/panel-header.js b/src/components/side-panel/panel-header.jsindex 36d41fa02..aac82dfd0 100644--- a/src/components/side-panel/panel-header.js+++ b/src/components/side-panel/panel-header.js@@ -24,16 +24,7 @@ import PropTypes from 'prop-types';import {createSelector} from 'reselect';import {Tooltip} from 'components/common/styled-components';import KeplerGlLogo from 'components/common/logo';-import {- Save,- DataTable,- Save2,- Gear,- Picture,- Db,- Map as MapIcon,- Share-} from 'components/common/icons';+import {Save, DataTable, Save2, Picture, Db, Map as MapIcon, Share} from 'components/common/icons';import ClickOutsideCloseDropdown from 'components/side-panel/panel-dropdown';import Toolbar from 'components/common/toolbar';import ToolbarItem from 'components/common/toolbar-item';@@ -91,10 +82,8 @@ const StyledPanelAction = styled.div.attrs({}`;-// By assigning this style we can position the toolbar in the right place on the screenconst StyledToolbar = styled(Toolbar)`position: absolute;- left: 64px;`;export const PanelAction = ({item, onClick}) => (@@ -190,7 +179,7 @@ export const SaveExportDropdownFactory = PanelHeaderDropdown => {{label: 'Share Map URL',icon: Share,- key: 'save',+ key: 'share',onClick: props => props.onShareMap}]@@ -216,15 +205,21 @@ export const CloudStorageDropdownFactory = PanelHeaderDropdown => {{label: 'Save',icon: Save2,- key: 'data',+ key: 'save',onClick: props => props.onSaveToStorage},{- label: 'Settings',- icon: Gear,- key: 'settings',- onClick: props => props.onExportData+ label: 'Save As',+ icon: Save2,+ key: 'saveAs',+ onClick: props => props.onSaveAsToStorage}+ // {+ // label: 'Settings',+ // icon: Gear,+ // key: 'settings',+ // onClick: props => props.onExportData+ // }]};return CloudStorageDropdown;@@ -246,6 +241,7 @@ function PanelHeaderFactory(SaveExportDropdown, CloudStorageDropdown) {onExportConfig: PropTypes.func,onExportMap: PropTypes.func,onSaveToStorage: PropTypes.func,+ onSaveAsToStorage: PropTypes.func,onSaveMap: PropTypes.func,onShareMap: PropTypes.func};@@ -275,21 +271,15 @@ function PanelHeaderFactory(SaveExportDropdown, CloudStorageDropdown) {appName,version,actionItems,- onSaveToStorage,- onSaveMap,- onShareMap,- onExportImage,- onExportData,- onExportConfig,- onExportMap,visibleDropdown,showExportDropdown,- hideExportDropdown+ hideExportDropdown,+ ...dropdownCallbacks} = this.props;let items = actionItems || [];// don't render cloud storage icon if onSaveToStorage is not provided- if (typeof onSaveToStorage !== 'function') {+ if (typeof this.props.onSaveToStorage !== 'function') {items = actionItems.filter(ai => ai.id !== 'storage');}@@ -317,13 +307,7 @@ function PanelHeaderFactory(SaveExportDropdown, CloudStorageDropdown) {<item.dropdownComponentonClose={hideExportDropdown}show={visibleDropdown === item.id}- onSaveToStorage={onSaveToStorage}- onSaveMap={onSaveMap}- onShareMap={onShareMap}- onExportData={onExportData}- onExportImage={onExportImage}- onExportConfig={onExportConfig}- onExportMap={onExportMap}+ {...dropdownCallbacks}/>) : null}</div>diff --git a/src/constants/action-types.js b/src/constants/action-types.jsindex dce056ce6..04c44e445 100644--- a/src/constants/action-types.js+++ b/src/constants/action-types.js@@ -93,6 +93,7 @@ const ActionTypes = keyMirror({SET_FILTER_PLOT: null,LOAD_FILES: null,LOAD_FILES_ERR: null,+ LOAD_FILES_SUCCESS: null,LAYER_COLOR_UI_CHANGE: null,TOGGLE_FEATURE_LAYER: null,APPLY_CPU_FILTER: null,diff --git a/src/constants/default-settings.js b/src/constants/default-settings.jsindex f5ab1479b..84dfba427 100644--- a/src/constants/default-settings.js+++ b/src/constants/default-settings.js@@ -93,6 +93,13 @@ export const EXPORT_MAP_ID = 'exportMap';* @public*/export const SAVE_MAP_ID = 'saveMap';+/**+ * Modal id: confirm to overwrite saved map+ * @constant+ * @type {string}+ * @public+ */+export const OVERWRITE_MAP_ID = 'overwriteMap';/*** Modal id: share map url modal* @constant@@ -756,3 +763,16 @@ export const MAP_INFO_CHARACTER = {title: 100,description: 100};++// Load data+export const LOADING_METHODS = keyMirror({+ upload: null,+ storage: null+});++export const DATASET_FORMATS = keyMirror({+ row: null,+ geojson: null,+ csv: null,+ keplergl: null+});diff --git a/src/processors/data-processor.js b/src/processors/data-processor.jsindex 4cba2d271..5b3bab82c 100644--- a/src/processors/data-processor.js+++ b/src/processors/data-processor.js@@ -24,11 +24,11 @@ import {console as globalConsole} from 'global/window';import assert from 'assert';import {Analyzer, DATA_TYPES as AnalyzerDATA_TYPES} from 'type-analyzer';import normalize from '@mapbox/geojson-normalize';-import {ALL_FIELD_TYPES} from 'constants/default-settings';+import {ALL_FIELD_TYPES, DATASET_FORMATS} from 'constants/default-settings';import {notNullorUndefined, parseFieldValue, getSampleData} from 'utils/data-utils';import KeplerGlSchema from 'schemas';import {GUIDES_FILE_FORMAT} from 'constants/user-guides';-import {isPlainObject} from 'utils/utils';+import {isPlainObject, toArray} from 'utils/utils';export const ACCEPTED_ANALYZER_TYPES = [AnalyzerDATA_TYPES.DATE,@@ -626,11 +626,32 @@ export function processKeplerglJSON(rawData) {return rawData ? KeplerGlSchema.load(rawData.datasets, rawData.config) : null;}+/**+ * Parse a single or an array of datasets saved using kepler.gl schema+ * @param {Array | Array<Object>} rawData+ */+export function processKeplerglDataset(rawData) {+ if (!rawData) {+ return null;+ }++ const results = KeplerGlSchema.parseSavedData(toArray(rawData));+ return Array.isArray(rawData) ? results : results[0];+}++export const DATASET_HANDLERS = {+ [DATASET_FORMATS.row]: processRowObject,+ [DATASET_FORMATS.geojson]: processGeojson,+ [DATASET_FORMATS.csv]: processCsvData,+ [DATASET_FORMATS.keplergl]: processKeplerglDataset+};+export const Processors = {processGeojson,processCsvData,processRowObject,processKeplerglJSON,+ processKeplerglDataset,analyzerTypeToFieldType,getFieldsFromData,parseCsvRowsByFieldType,diff --git a/src/processors/file-handler.js b/src/processors/file-handler.jsindex c48b8742d..7593ded87 100644--- a/src/processors/file-handler.js+++ b/src/processors/file-handler.js@@ -19,16 +19,54 @@// THE SOFTWARE.import {FileReader} from 'global/window';-import {processCsvData, processGeojson, processKeplerglJSON} from './data-processor';+import Console from 'global/console';+import {+ processCsvData,+ processGeojson,+ processKeplerglJSON,+ processRowObject+} from './data-processor';+import {isPlainObject} from 'utils/utils';+import {DATASET_FORMATS} from 'constants/default-settings';const FILE_HANDLERS = {csv: loadCsv,json: loadJSON};+export function readFile({file, fileCache = []}) {+ return new Promise((resolve, reject) => {+ const {handler, format} = getFileHandler(file);+ if (!handler) {+ Console.warn(+ `Canont determine file handler for file ${file.name}. It must have a valid file extension`+ );+ resolve(fileCache);+ }++ handler({file, format}).then(result => {+ if (!result || !result.data) {+ // return fileCache, to keep process other files+ resolve(fileCache);+ }+ resolve([+ ...fileCache,+ {+ data: result.data,+ info: {+ label: file.name,+ format: result.format+ }+ }+ ]);+ });+ });+}+export function getFileHandler(fileBlob) {const type = getFileType(fileBlob.name);- return FILE_HANDLERS[type];++ return {handler: FILE_HANDLERS[type], format: type};}export function getFileType(filename) {@@ -54,11 +92,35 @@ function readCSVFile(fileBlob) {});}-export function loadCsv(fileBlob, processor = processCsvData) {- return readCSVFile(fileBlob).then(rawData => (rawData ? processor(rawData) : null));+export function loadCsv({file, format, processor = processCsvData}) {+ return readCSVFile(file).then(rawData => (rawData ? {data: processor(rawData), format} : null));}-function readJSONFile(fileBlob) {+export function loadJSON({file, processor = processGeojson}) {+ return readJSONFile(file).then(content => {+ if (isKeplerGlMap(content)) {+ return {+ format: DATASET_FORMATS.keplergl,+ data: processKeplerglJSON(content)+ };+ } else if (isRowObject(content)) {+ return {+ format: DATASET_FORMATS.row,+ data: processRowObject(content)+ };+ } else if (isGeoJson(content)) {+ return {+ format: DATASET_FORMATS.geojson,+ data: processGeojson(content)+ };+ }+ // unsupported json format+ Console.warn(`unsupported Json format ${file.name}`);+ return null;+ });+}++export function readJSONFile(fileBlob) {return new Promise((resolve, reject) => {const fileReader = new FileReader();fileReader.onload = ({target: {result}}) => {@@ -66,17 +128,35 @@ function readJSONFile(fileBlob) {const json = JSON.parse(result);resolve(json);} catch (err) {- resolve(null);+ reject(null);}};- fileReader.readAsText(fileBlob);+ fileReader.readAsText(fileBlob, 'UTF-8');});}+export function isGeoJson(json) {+ // json can be feature collection+ // or simgle feature+ return isPlainObject(json) && (isFeature(json) || isFeatureCollection(json));+}++export function isFeature(json) {+ return json.type === 'Feature' && json.geometry;+}++export function isFeatureCollection(json) {+ return json.type === 'FeatureCollection' && json.features;+}++export function isRowObject(json) {+ return Array.isArray(json) && isPlainObject(json[0]);+}+export function isKeplerGlMap(json) {return (- typeof json === 'object' &&+ isPlainObject(json) &&json.datasets &&json.config &&json.info &&@@ -84,16 +164,10 @@ export function isKeplerGlMap(json) {);}-export function determineJsonProcess(jsonData, defaultProcessor) {- if (isKeplerGlMap(jsonData)) {+export function determineJsonProcess({dataset, format}, defaultProcessor) {+ if (isKeplerGlMap(dataset)) {return processKeplerglJSON;}return defaultProcessor;}--export function loadJSON(fileBlob, processor = processGeojson) {- return readJSONFile(fileBlob).then(rawData =>- rawData ? determineJsonProcess(rawData, processor)(rawData) : null- );-}diff --git a/src/reducers/combined-updaters.js b/src/reducers/combined-updaters.jsindex 48593d534..fbfd42b1c 100644--- a/src/reducers/combined-updaters.js+++ b/src/reducers/combined-updaters.js@@ -19,7 +19,10 @@// THE SOFTWARE.import {toggleModalUpdater, loadFilesSuccessUpdater} from './ui-state-updaters';-import {updateVisDataUpdater as visStateUpdateVisDataUpdater} from './vis-state-updaters';+import {+ updateVisDataUpdater as visStateUpdateVisDataUpdater,+ setMapInfoUpdater+} from './vis-state-updaters';import {receiveMapConfigUpdater as stateMapConfigUpdater} from './map-state-updaters';import {receiveMapConfigUpdater as styleMapConfigUpdater} from './map-style-updaters';import {findMapBounds} from 'utils/data-utils';@@ -101,7 +104,7 @@ export const defaultAddDataToMapOptions = {* @public*/export const addDataToMapUpdater = (state, {payload}) => {- const {datasets, config} = payload;+ const {datasets, config, info} = payload;const options = {...defaultAddDataToMapOptions,@@ -126,6 +129,15 @@ export const addDataToMapUpdater = (state, {payload}) => {})};+ // merge map info+ // save title, description provider and queryParams+ if (info) {+ mergedState = {+ ...mergedState,+ visState: setMapInfoUpdater(mergedState.visState, {info})+ };+ }+let bounds;if (options.centerMap) {// find map bounds for new layersdiff --git a/src/reducers/provider-state-updaters.js b/src/reducers/provider-state-updaters.jsindex 8043c5537..60d1e147f 100644--- a/src/reducers/provider-state-updaters.js+++ b/src/reducers/provider-state-updaters.js@@ -20,35 +20,40 @@import {withTask} from 'react-palm/tasks';import {default as Console} from 'global/console';-import window from 'global/window';--import {generateHashId, getError} from 'utils/utils';-import {EXPORT_FILE_TO_CLOUD_TASK, ACTION_TASK, DELAY_TASK} from 'tasks/tasks';-import {exportFileSuccess, exportFileError, saveToCloudSuccess} from 'actions/provider-actions';+import {generateHashId, getError, isPlainObject} from 'utils/utils';+import {+ EXPORT_FILE_TO_CLOUD_TASK,+ ACTION_TASK,+ DELAY_TASK,+ LOAD_CLOUD_MAP_TASK,+ GET_SAVED_MAPS_TASK+} from 'tasks/tasks';+import {+ exportFileSuccess,+ exportFileError,+ postSaveLoadSuccess,+ loadCloudMapSuccess,+ getSavedMapsSuccess,+ getSavedMapsError+} from 'actions/provider-actions';import {removeNotification, toggleModal, addNotification} from 'actions/ui-state-actions';-import {DEFAULT_NOTIFICATION_TYPES, DEFAULT_NOTIFICATION_TOPICS} from 'constants/default-settings';+import {addDataToMap} from 'actions/actions';+import {+ DEFAULT_NOTIFICATION_TYPES,+ DEFAULT_NOTIFICATION_TOPICS,+ DATASET_FORMATS+} from 'constants/default-settings';+import {toArray} from 'utils/utils';+import KeplerGlSchema from 'schemas';export const INITIAL_PROVIDER_STATE = {- isLoading: false,- error: null,+ isProviderLoading: false,+ providerError: null,currentProvider: null,- successInfo: {}+ successInfo: {},+ mapSaved: null};--function createFileJson(mapData = {}) {- if (!window.Blob || !window.File) {- return {file: null, fileName: null};- }- const {map = {}, info = {}} = mapData;- const data = JSON.stringify(map);- const newBlob = new window.Blob([data], {type: 'application/json'});-- // TODO: Allow user import file name- const name = info.title && info.title.length ? info.title : `keplergl_${generateHashId(6)}`;- const fileName = `${name}.json`;-- return {file: new window.File([newBlob], fileName), fileName};-}+import {DATASET_HANDLERS} from 'processors/data-processor';function createActionTask(action, payload) {if (typeof action === 'function') {@@ -58,6 +63,32 @@ function createActionTask(action, payload) {return null;}+function _validateProvider(provider, method) {+ if (!provider) {+ Console.error(`provider is not defined`);+ return false;+ }++ if (typeof provider[method] !== 'function') {+ Console.error(`${method} is not a function of Cloud provider: ${provider.name}`);+ return false;+ }++ return true;+}++function createGlobalNotificationTasks({type, message, delayClose = true}) {+ const id = generateHashId();+ const successNote = {+ id,+ type: DEFAULT_NOTIFICATION_TYPES[type] || DEFAULT_NOTIFICATION_TYPES.success,+ topic: DEFAULT_NOTIFICATION_TOPICS.global,+ message+ };+ const task = ACTION_TASK().map(_ => addNotification(successNote));+ return delayClose ? [task, DELAY_TASK(3000).map(_ => removeNotification(id))] : [task];+}+/*** This method will export the current kepler config file to the chosen cloud proder* add returns a share URL@@ -66,41 +97,28 @@ function createActionTask(action, payload) {* @param {*} action*/export const exportFileToCloudUpdater = (state, action) => {- const {mapData, provider, isPublic, onSuccess, onError, closeModal} = action.payload;-- if (!provider) {- Console.error(`provider is not defined`);- return state;- }+ const {mapData, provider, options = {}, onSuccess, onError, closeModal} = action.payload;- if (typeof provider.uploadFile !== 'function') {- Console.error(`uploadFile is not a function of Cloud provider: ${provider.name}`);+ if (!_validateProvider(provider, 'uploadMap')) {return state;}- // TODO: do we need to always create a fileBlob?- // if this is provider specific, we should just send over the json- // and let provider decide what format to use- const {file, fileName} = createFileJson(mapData);-const newState = {...state,- isLoading: true,+ isProviderLoading: true,currentProvider: provider.name};- // payload called by provider.uploadFile+ // payload called by provider.uploadMapconst payload = {mapData,- blob: file,- fileName,- isPublic+ options};const uploadFileTask = EXPORT_FILE_TO_CLOUD_TASK({provider, payload}).bimap(// success- response => exportFileSuccess({response, provider, onSuccess, closeModal}),+ response => exportFileSuccess({response, provider, options, onSuccess, closeModal}),// error- error => exportFileError({error, provider, onError})+ error => exportFileError({error, provider, options, onError}));return withTask(newState, uploadFileTask);@@ -112,21 +130,24 @@ export const exportFileToCloudUpdater = (state, action) => {* @param {*} action*/export const exportFileSuccessUpdater = (state, action) => {- const {response, provider, onSuccess, closeModal} = action.payload;+ const {response, provider, options, onSuccess, closeModal} = action.payload;const newState = {...state,- isLoading: false,+ isProviderLoading: false,// TODO: do we always have to store this?- successInfo: {- metaUrl: response.url,- folderLink: response.folder_link- }+ successInfo: response,+ ...(!options.isPublic+ ? {+ mapSaved: provider.name+ }+ : {})};const tasks = [- createActionTask(onSuccess, {response, provider}),- closeModal && ACTION_TASK().map(_ => saveToCloudSuccess())+ createActionTask(onSuccess, {response, provider, options}),+ closeModal &&+ ACTION_TASK().map(_ => postSaveLoadSuccess(`Map saved to ${state.currentProvider}!`))].filter(d => d);return tasks.length ? withTask(newState, tasks) : newState;@@ -137,19 +158,12 @@ export const exportFileSuccessUpdater = (state, action) => {* @param {*} state* @param {*} action*/-export const saveToCloudSuccessUpdater = (state, action) => {- const id = generateHashId();- const successNote = {- id,- type: DEFAULT_NOTIFICATION_TYPES.success,- topic: DEFAULT_NOTIFICATION_TOPICS.global,- message: `Saved to ${state.currentProvider} successfully`- };+export const postSaveLoadSuccessUpdater = (state, action) => {+ const message = action.payload || `Saved / Load to ${state.currentProvider} Success`;const tasks = [ACTION_TASK().map(_ => toggleModal(null)),- ACTION_TASK().map(_ => addNotification(successNote)),- DELAY_TASK(3000).map(_ => removeNotification(id))+ ...createGlobalNotificationTasks({message})];return withTask(state, tasks);@@ -162,11 +176,10 @@ export const saveToCloudSuccessUpdater = (state, action) => {*/export const exportFileErrorUpdater = (state, action) => {const {error, provider, onError} = action.payload;-const newState = {...state,- isLoading: false,- error: getError(error)+ isProviderLoading: false,+ providerError: getError(error)};const task = createActionTask(onError, {error, provider});@@ -174,6 +187,118 @@ export const exportFileErrorUpdater = (state, action) => {return task ? withTask(newState, task) : newState;};+export const loadCloudMapUpdater = (state, action) => {+ const {loadParams, provider, onSuccess, onError} = action.payload;+ if (!loadParams) {+ Console.warn('load map error: loadParams is undefined');+ return state;+ }+ if (!_validateProvider(provider, 'downloadMap')) {+ return state;+ }++ const newState = {+ ...state,+ isProviderLoading: true+ };++ // payload called by provider.downloadMap+ const uploadFileTask = LOAD_CLOUD_MAP_TASK({provider, payload: loadParams}).bimap(+ // success+ response => loadCloudMapSuccess({response, loadParams, provider, onSuccess, onError}),+ // error+ error => exportFileError({error, provider, onError})+ );++ return withTask(newState, uploadFileTask);+};++function checkLoadMapResponseError(response) {+ if (!response || !isPlainObject(response)) {+ return new Error('Load map response is empty');+ }+ if (!isPlainObject(response.map)) {+ return new Error(`Load map response should be an object property "map"`);+ }+ if (!response.map.datasets || !response.map.config) {+ return new Error(`Load map response.map should be an object with property datasets or config`);+ }++ return null;+}++function getDatasetHandler(format) {+ const defaultHandler = DATASET_HANDLERS[DATASET_FORMATS.csv];+ if (!format) {+ Console.warn('format is not provided in load map response, will use csv by default');+ return defaultHandler;+ }++ if (!DATASET_HANDLERS[format]) {+ const supportedFormat = Object.keys(DATASET_FORMATS)+ .map(k => `'${k}'`)+ .join(', ');+ Console.warn(+ `unknown format ${format}. Please use one of ${supportedFormat}, will use csv by default`+ );+ return defaultHandler;+ }++ return DATASET_HANDLERS[format];+}++function parseLoadMapResponse(response, loadParams, provider) {+ const {map, format} = response;+ const processorMethod = getDatasetHandler(format);++ const parsedDatasets = toArray(map.datasets).map((ds, i) => {+ if (format === DATASET_FORMATS.keplergl) {+ // no need to obtain id, directly pass them in+ return processorMethod(ds);+ }+ const info = (ds && ds.info) || {id: generateHashId(6)};+ const data = processorMethod(ds.data || ds);+ return {info, data};+ });++ const parsedConfig = map.config ? KeplerGlSchema.parseSavedConfig(map.config) : null;++ const info = {+ ...map.info,+ provider: provider.name,+ loadParams+ };+ return {datasets: parsedDatasets, config: parsedConfig, info};+}++export const loadCloudMapSuccessUpdater = (state, action) => {+ const {response, loadParams, provider, onSuccess, onError} = action.payload;++ const formatError = checkLoadMapResponseError(response);+ if (formatError) {+ // if response format is not correct+ return exportFileErrorUpdater(state, {+ payload: {error: formatError, provider, onError}+ });+ }++ const newState = {+ ...state,+ mapSaved: provider.name,+ currentProvider: provider.name,+ isProviderLoading: false+ };++ const payload = parseLoadMapResponse(response, loadParams, provider);++ const tasks = [+ ACTION_TASK().map(_ => addDataToMap(payload)),+ createActionTask(onSuccess, {response, loadParams, provider}),+ ACTION_TASK().map(_ => postSaveLoadSuccess(`Map from ${provider.name} loaded`))+ ].filter(d => d);++ return tasks.length ? withTask(newState, tasks) : newState;+};/**** @param {*} state@@ -181,8 +306,8 @@ export const exportFileErrorUpdater = (state, action) => {*/export const resetProviderStatusUpdater = (state, action) => ({...state,- isLoading: false,- error: null,+ isProviderLoading: false,+ providerError: null,successInfo: {}});@@ -195,3 +320,49 @@ export const setCloudProviderUpdater = (state, action) => ({...state,currentProvider: action.payload});++export const getSavedMapsUpdater = (state, action) => {+ const provider = action.payload;+ if (!_validateProvider(provider, 'listMaps')) {+ return state;+ }++ const getSavedMapsTask = GET_SAVED_MAPS_TASK(provider).bimap(+ // success+ visualizations => getSavedMapsSuccess({visualizations, provider}),+ // error+ error => getSavedMapsError({error, provider})+ );++ return withTask(+ {+ ...state,+ isProviderLoading: true+ },+ getSavedMapsTask+ );+};++export const getSavedMapsSuccessUpdater = (state, action) => ({+ ...state,+ isProviderLoading: false,+ visualizations: action.payload.visualizations+});++export const getSavedMapsErrorUpdater = (state, action) => {+ const message =+ getError(action.payload.error) || `Error getting saved maps from ${state.currentProvider}`;++ Console.warn(action.payload.error);++ const newState = {+ ...state,+ currentProvider: null,+ isProviderLoading: false+ };++ return withTask(+ newState,+ createGlobalNotificationTasks({type: 'error', message, delayClose: false})+ );+};diff --git a/src/reducers/provider-state.js b/src/reducers/provider-state.jsindex 80a0300ba..2d2629ae5 100644--- a/src/reducers/provider-state.js+++ b/src/reducers/provider-state.js@@ -32,7 +32,12 @@ const actionHandler = {[ActionTypes.EXPORT_FILE_ERROR]: providerStateUpdaters.exportFileErrorUpdater,[ActionTypes.RESET_PROVIDER_STATUS]: providerStateUpdaters.resetProviderStatusUpdater,[ActionTypes.SET_CLOUD_PROVIDER]: providerStateUpdaters.setCloudProviderUpdater,- [ActionTypes.SAVE_TO_CLOUD_SUCCESS]: providerStateUpdaters.saveToCloudSuccessUpdater+ [ActionTypes.POST_SAVE_LOAD_SUCCESS]: providerStateUpdaters.postSaveLoadSuccessUpdater,+ [ActionTypes.LOAD_CLOUD_MAP]: providerStateUpdaters.loadCloudMapUpdater,+ [ActionTypes.LOAD_CLOUD_MAP_SUCCESS]: providerStateUpdaters.loadCloudMapSuccessUpdater,+ [ActionTypes.GET_SAVED_MAPS]: providerStateUpdaters.getSavedMapsUpdater,+ [ActionTypes.GET_SAVED_MAPS_SUCCESS]: providerStateUpdaters.getSavedMapsSuccessUpdater,+ [ActionTypes.GET_SAVED_MAPS_ERROR]: providerStateUpdaters.getSavedMapsErrorUpdater};// construct provider-state reducerdiff --git a/src/reducers/vis-state-updaters.js b/src/reducers/vis-state-updaters.jsindex f3650360e..532cc04d4 100644--- a/src/reducers/vis-state-updaters.js+++ b/src/reducers/vis-state-updaters.js@@ -19,17 +19,17 @@// THE SOFTWARE.import {console as Console} from 'global/window';-import Task, {disableStackCapturing, withTask} from 'react-palm/tasks';+import {disableStackCapturing, withTask} from 'react-palm/tasks';import cloneDeep from 'lodash.clonedeep';import uniq from 'lodash.uniq';import get from 'lodash.get';import xor from 'lodash.xor';// Tasks-import {LOAD_FILE_TASK} from 'tasks/tasks';+import {LOAD_FILE_TASK, ACTION_TASK} from 'tasks/tasks';// Actions-import {loadFilesErr} from 'actions/vis-state-actions';+import {loadFilesErr, loadFileSuccess} from 'actions/vis-state-actions';import {addDataToMap} from 'actions';// Utils@@ -51,7 +51,7 @@ import {} from 'utils/filter-utils';import {setFilterGpuMode, assignGpuChannel} from 'utils/gpu-filter-utils';import {createNewDataEntry} from 'utils/dataset-utils';-import {set, toArray} from 'utils/utils';+import {set, toArray, generateHashId} from 'utils/utils';import {findDefaultLayer, calculateLayerData} from 'utils/layer-utils/layer-utils';@@ -71,10 +71,8 @@ import {} from 'utils/split-map-utils';import {Layer, LayerClasses} from 'layers';-import {processFileToLoad} from 'utils/file-utils';import {DEFAULT_TEXT_LABEL} from 'layers/layer-factory';--import {EDITOR_MODES} from 'constants/default-settings';+import {EDITOR_MODES, DATASET_FORMATS} from 'constants/default-settings';// react-palm// disable capture exception for react-palm call to withTask@@ -799,7 +797,9 @@ export const toggleFilterFeatureUpdater = (state, action) => {const isVisible = get(filter, ['value', 'properties', 'isVisible']);const newFilter = {...filter,- value: featureToFilterValue(filter.value, filter.id, {isVisible: !isVisible})+ value: featureToFilterValue(filter.value, filter.id, {+ isVisible: !isVisible+ })};return {@@ -1320,29 +1320,99 @@ function closeSpecificMapAtIndex(state, action) {*/export const loadFilesUpdater = (state, action) => {const {files} = action;- const filesToLoad = files.map(fileBlob => processFileToLoad(fileBlob));-- // reader -> parser -> augment -> receiveVisData- const loadFileTasks = [- Task.all(filesToLoad.map(LOAD_FILE_TASK)).bimap(results => {- const data = results.reduce(- (f, c) => ({- // using concat here because the current datasets could be an array or a single item- datasets: f.datasets.concat(c.datasets),+ if (!files.length) {+ return state;+ }++ const fileCache = [];+ return withTask(+ {+ ...state,+ fileLoading: true,+ fileLoadingProgress: 0+ },+ makeLoadFileTask(files.length, files, fileCache)+ );+};++function makeLoadFileTask(totalCount, filesToLoad, fileCache) {+ const file = filesToLoad.pop();++ return LOAD_FILE_TASK({file, fileCache}).bimap(+ // success+ result =>+ loadFileSuccess({+ fileCache: result,+ filesToLoad: [...filesToLoad],+ totalCount+ }),+ // error+ loadFilesErr+ );+}++export const loadFileSuccessUpdater = (state, action) => {+ const {fileCache, filesToLoad = [], totalCount} = action;++ // still more to load+ if (filesToLoad.length) {+ const fileLoadingProgress = ((totalCount - filesToLoad.length) / totalCount) * 100;++ return withTask(+ {+ ...state,+ fileLoadingProgress+ },+ makeLoadFileTask(totalCount, filesToLoad, fileCache)+ );+ }++ const result = fileCache.reduce(+ (accu, file) => {+ const {data, info = {}} = file;+ const {format} = info;++ if (format) {+ if (format !== DATASET_FORMATS.keplergl) {+ const newDataset = {+ data,+ info: {+ id: generateHashId(4),+ ...info+ }+ };++ accu.datasets.push(newDataset);+ return accu;+ }++ return {+ datasets: accu.datasets.concat(data.datasets),// we need to deep merge this thing unless we find a better solution// this case will only happen if we allow to load multiple keplergl json filesconfig: {- ...f.config,- ...(c.config || {})+ ...accu.config,+ ...(data.config || {})}- }),- {datasets: [], config: {}, options: {centerMap: true}}- );- return addDataToMap(data);- }, loadFilesErr)- ];+ };+ }+ return accu;+ },+ {datasets: [], config: {}}+ );++ const options = {+ centerMap: !(result.config && result.config.mapState)+ };- return withTask(state, loadFileTasks);+ return withTask(+ {+ ...state,+ fileLoading: false,+ fileLoadingProgress: 100+ },+ ACTION_TASK().map(_ => addDataToMap({...result, options}))+ );};/**@@ -1565,7 +1635,11 @@ export function setFeaturesUpdater(state, {features = []}) {if (filterId) {const featureValue = featureToFilterValue(feature, filterId);const filterIdx = state.filters.findIndex(fil => fil.id === filterId);- return setFilterUpdater(newState, {idx: filterIdx, prop: 'value', value: featureValue});+ return setFilterUpdater(newState, {+ idx: filterIdx,+ prop: 'value',+ value: featureValue+ });}return newState;@@ -1693,7 +1767,11 @@ export function setPolygonFilterLayerUpdater(state, payload) {};}- return setFilterUpdater(newState, {idx: filterIdx, prop: 'layerId', value: newLayerId});+ return setFilterUpdater(newState, {+ idx: filterIdx,+ prop: 'layerId',+ value: newLayerId+ });}/**diff --git a/src/reducers/vis-state.js b/src/reducers/vis-state.jsindex a951a5c44..46041dbd5 100644--- a/src/reducers/vis-state.js+++ b/src/reducers/vis-state.js@@ -55,6 +55,8 @@ const actionHandler = {[ActionTypes.LOAD_FILES_ERR]: visStateUpdaters.loadFilesErrUpdater,+ [ActionTypes.LOAD_FILES_SUCCESS]: visStateUpdaters.loadFileSuccessUpdater,+[ActionTypes.MAP_CLICK]: visStateUpdaters.mapClickUpdater,[ActionTypes.MOUSE_MOVE]: visStateUpdaters.mouseMoveUpdater,diff --git a/src/schemas/schema-manager.js b/src/schemas/schema-manager.jsindex 74d201263..2dbea6277 100644--- a/src/schemas/schema-manager.js+++ b/src/schemas/schema-manager.js@@ -77,11 +77,15 @@ class KeplerGLSchema {config: this.getConfigToSave(state),info: {app: 'kepler.gl',- created_at: new Date().toString()+ created_at: new Date().toString(),+ ...this.getMapInfo(state)}};}+ getMapInfo(state) {+ return state.visState.mapInfo;+ }/*** Load saved map, argument can be (datasets, config) or ({datasets, config})* @param {Object|Array<Object>} savedDatasetsdiff --git a/src/styles/base.js b/src/styles/base.jsindex 695d9d413..e833f9517 100644--- a/src/styles/base.js+++ b/src/styles/base.js@@ -29,7 +29,7 @@ export const boxShadow = '0 1px 2px 0 rgba(0,0,0,0.10)';export const boxSizing = 'border-box';export const borderRadius = '1px';export const borderColor = '#3A414C';-export const borderColorLight = '#F1F1F1';+export const borderColorLT = '#F1F1F1';// TEXTexport const fontFamily = `ff-clan-web-pro, 'Helvetica Neue', Helvetica, sans-serif`;@@ -184,7 +184,7 @@ export const panelBackgroundLT = '#f8f8f9';export const panelBorderColor = '#3A414C';export const panelBorder = `1px solid ${borderColor}`;-export const panelBorderLT = `1px solid ${borderColorLight}`;+export const panelBorderLT = `1px solid ${borderColorLT}`;export const mapPanelBackgroundColor = '#242730';export const mapPanelHeaderBackgroundColor = '#29323C';@@ -798,6 +798,9 @@ export const theme = {chickletedInputContainer,secondaryChickletedInput,+ borderColor,+ borderColorLT,+secondaryInput,dropdownScrollBar,dropdownList,diff --git a/src/tasks/tasks.js b/src/tasks/tasks.jsindex 59d6f593b..50f52c25d 100644--- a/src/tasks/tasks.js+++ b/src/tasks/tasks.js@@ -20,35 +20,10 @@import Task, {taskCreator} from 'react-palm/tasks';import {json as requestJson} from 'd3-request';-import console from 'global/console';--export const LOAD_FILE_TASK = taskCreator(- ({fileBlob, info, handler, processor}, success, error) => {- return handler(fileBlob, processor)- .then(result => {- if (!result) {- // TODO: capture in the UI and show message- error(new Error('File to load data, result is empty'));- } else {- // we are trying to standardize the shape of our return- // since we start using the kepler.json format- // result has both datasets and info- // TODO: I think we should pass info to the handler and return- // the same format back from the file handler-- if (result.datasets) {- // this is coming from parsing keplergl.json file- success(result); // info is already part of datasets- }- success({datasets: {data: result, info}});- }- })- .catch(err => {- console.log(err);- error(err);- });- },+import {readFile} from '../processors/file-handler';+export const LOAD_FILE_TASK = Task.fromPromise(+ ({file, fileCache}) => readFile({file, fileCache}),'LOAD_FILE_TASK');@@ -72,11 +47,22 @@ export const LOAD_MAP_STYLE_TASK = taskCreator(* task to upload file to cloud provider*/export const EXPORT_FILE_TO_CLOUD_TASK = Task.fromPromise(- ({provider, payload}) => provider.uploadFile(payload),+ ({provider, payload}) => provider.uploadMap(payload),'EXPORT_FILE_TO_CLOUD_TASK');+export const LOAD_CLOUD_MAP_TASK = Task.fromPromise(+ ({provider, payload}) => provider.downloadMap(payload),++ 'LOAD_CLOUD_MAP_TASK'+);++export const GET_SAVED_MAPS_TASK = Task.fromPromise(+ provider => provider.listMaps(),++ 'GET_SAVED_MAPS_TASK'+);/*** task to dispatch a function as a task*/diff --git a/src/utils/export-utils.js b/src/utils/export-utils.jsindex efde31a4c..7acbc8eff 100644--- a/src/utils/export-utils.js+++ b/src/utils/export-utils.js@@ -29,6 +29,8 @@ import {} from 'constants/default-settings';import {exportMapToHTML} from 'templates/export-map-html';import {formatCsv} from 'processors/data-processor';+import get from 'lodash.get';+import {set, generateHashId} from 'utils/utils';import KeplerGlSchema from 'schemas';@@ -145,7 +147,17 @@ export function exportToJsonString(data) {export function getMapJSON(state, options = DEFAULT_EXPORT_JSON_SETTINGS) {const {hasData} = options;- return hasData ? KeplerGlSchema.save(state) : KeplerGlSchema.getConfigToSave(state);+ if (!hasData) {+ return KeplerGlSchema.getConfigToSave(state);+ }++ let mapToSave = KeplerGlSchema.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);+ }+ return mapToSave;}export function exportJson(state, options = {}) {@@ -202,15 +214,13 @@ export function exportData(state, option) {});}-export function exportMap(state) {- const mapToState = getMapJSON(state);- const {mapInfo} = state.visState;+export function exportMap(state, option) {const {imageDataUri} = state.uiState.exportImage;const thumbnail = imageDataUri ? dataURItoBlob(imageDataUri) : null;+ const mapToSave = getMapJSON(state, option);return {- map: mapToState,- info: mapInfo,+ map: mapToSave,thumbnail};}diff --git a/test/browser/components/common/file-uploader-test.js b/test/browser/components/common/file-uploader-test.jsindex fb69113c8..40a2e3d63 100644--- a/test/browser/components/common/file-uploader-test.js+++ b/test/browser/components/common/file-uploader-test.js@@ -23,7 +23,7 @@ import test from 'tape';import sinon from 'sinon';import {mountWithTheme} from 'test/helpers/component-utils';-import FileUplad, {WarningMsg} from 'components/common/file-uploader/file-upload';+import {FileUpload, WarningMsg} from 'components/common/file-uploader/file-upload';import FileDrop from 'components/common/file-uploader/file-drop';import UploadButton from 'components/common/file-uploader/upload-button';@@ -31,7 +31,7 @@ test('Components -> FileUploader.render', t => {let wrapper;t.doesNotThrow(() => {- wrapper = mountWithTheme(<FileUplad />);+ wrapper = mountWithTheme(<FileUpload />);}, 'Show not fail without data');t.equal(wrapper.find(FileDrop).length, 1, 'should render FileUploader');@@ -46,7 +46,7 @@ test('Components -> FileUpload.onDrop', t => {t.deepEqual(arg, mockFiles, 'should call onFileUpload with files');});const stopPropagation = sinon.spy();- const wrapper = mountWithTheme(<FileUplad onFileUpload={onFileUpload} />);+ const wrapper = mountWithTheme(<FileUpload onFileUpload={onFileUpload} />);t.equal(wrapper.find(FileDrop).length, 1, 'should render FileUploader');@@ -77,7 +77,7 @@ test('Components -> FileUpload.onDrop -> render loading msg', t => {t.deepEqual(arg, mockFiles, 'should call onFileUpload with files');});- const wrapper = mountWithTheme(<FileUplad onFileUpload={onFileUpload} fileLoading />);+ const wrapper = mountWithTheme(<FileUpload onFileUpload={onFileUpload} fileLoading />);const FileDropDiv = wrapper.find('.file-uploader__file-drop').at(0);// mock file drop event@@ -108,7 +108,7 @@ test('Components -> FileUpload.onDrop -> render error msg', t => {t.deepEqual(arg, mockFiles, 'should call onFileUpload with files');});- const wrapper = mountWithTheme(<FileUplad onFileUpload={onFileUpload} />);+ const wrapper = mountWithTheme(<FileUpload onFileUpload={onFileUpload} />);const FileDropDiv = wrapper.find('.file-uploader__file-drop').at(0);// mock file drop event@@ -136,7 +136,7 @@ test('Components -> FileUpload.dragOver', t => {const onFileUpload = sinon.spy(arg => {t.deepEqual(arg, mockFiles, 'should call onFileUpload with files');});- const wrapper = mountWithTheme(<FileUplad onFileUpload={onFileUpload} />);+ const wrapper = mountWithTheme(<FileUpload onFileUpload={onFileUpload} />);t.equal(wrapper.find(FileDrop).length, 1, 'should render FileUploader');@@ -160,7 +160,7 @@ test('Components -> FileUpload.dragLeave', t => {const onFileUpload = sinon.spy(arg => {t.deepEqual(arg, mockFiles, 'should call onFileUpload with files');});- const wrapper = mountWithTheme(<FileUplad onFileUpload={onFileUpload} />);+ const wrapper = mountWithTheme(<FileUpload onFileUpload={onFileUpload} />);t.equal(wrapper.find(FileDrop).length, 1, 'should render FileUploader');@@ -184,7 +184,7 @@ test('Components -> UploadButton fileInput', t => {const onFileUpload = sinon.spy(arg => {t.deepEqual(arg, mockFiles, 'should call onFileUpload with files');});- const wrapper = mountWithTheme(<FileUplad onFileUpload={onFileUpload} />);+ const wrapper = mountWithTheme(<FileUpload onFileUpload={onFileUpload} />);const uploadButton = wrapper.find(UploadButton);t.equal(uploadButton.length, 1, 'should render UploadButton');const input = uploadButton.find('input');diff --git a/test/browser/components/modals/save-map-modal-test.js b/test/browser/components/modals/save-map-modal-test.jsindex 28ad8fc8d..cc145aea3 100644--- a/test/browser/components/modals/save-map-modal-test.js+++ b/test/browser/components/modals/save-map-modal-test.js@@ -26,19 +26,32 @@ import SaveMapModalFactory from 'components/modals/save-map-modal';import CloudTile from 'components/modals/cloud-tile';import ImagePreview from 'components/common/image-preview';+import MockProvider from 'test/helpers/mock-provider';++const mockProvider = new MockProvider();const SaveMapModal = SaveMapModalFactory();test('Components -> SaveMapModal.mount', t => {- const onUpdateSetting = sinon.spy();+ const onUpdateImageSetting = sinon.spy();const onSetCloudProvider = sinon.spy();// mountt.doesNotThrow(() => {mountWithTheme(- <SaveMapModal onUpdateSetting={onUpdateSetting} onSetCloudProvider={onSetCloudProvider} />+ <SaveMapModal+ onUpdateImageSetting={onUpdateImageSetting}+ onSetCloudProvider={onSetCloudProvider}+ cloudProviders={[mockProvider]}+ currentProvider="taro"+ />);}, 'Show not fail without props');- t.ok(onUpdateSetting.calledOnce, 'should call onUpdateSetting when mount');+ t.ok(onUpdateImageSetting.calledOnce, 'should call onUpdateImageSetting when mount');+ t.deepEqual(+ onUpdateImageSetting.args,+ [[{mapW: 100, mapH: 60, ratio: 'CUSTOM', legend: false}]],+ 'should call onUpdateImageSetting when mount'+ );t.ok(onSetCloudProvider.notCalled, 'should not call onSetCloudProvider when mount');t.end();@@ -47,10 +60,6 @@ test('Components -> SaveMapModal.mount', t => {test('Components -> SaveMapModal.mount with providers', t => {const onSetCloudProvider = sinon.spy();- const mockProvider = {- getAccessToken: () => true,- name: 'taro'- };// mountt.doesNotThrow(() => {mountWithTheme(@@ -106,12 +115,7 @@ test('Components -> SaveMapModal on click provider', t => {const onSetCloudProvider = sinon.spy();const login = sinon.spy();const logout = sinon.spy();-- const mockProvider = {- getAccessToken: () => true,- name: 'taro',- logout- };+ mockProvider.logout = logout;const mockProvider2 = {getAccessToken: () => false,@@ -126,8 +130,9 @@ test('Components -> SaveMapModal on click provider', t => {<SaveMapModalcloudProviders={[mockProvider, mockProvider2]}currentProvider="taro"- onUpdateSetting={() => {}}onSetCloudProvider={onSetCloudProvider}+ onUpdateSetting={() => {}}+ onUpdateImageSetting={() => {}}/>);}, 'Show not fail mount props');diff --git a/test/browser/components/modals/share-map-modal-test.js b/test/browser/components/modals/share-map-modal-test.jsindex b7a0a4d7e..fff92832b 100644--- a/test/browser/components/modals/share-map-modal-test.js+++ b/test/browser/components/modals/share-map-modal-test.js@@ -79,15 +79,22 @@ test('Components -> ShareMapUrlModal.mount with isLoading', t => {let wrapper;t.doesNotThrow(() => {wrapper = mountWithTheme(- <ShareMapUrlModal isLoading onSetCloudProvider={() => {}} cloudProviders={[mockProvider]} />+ <ShareMapUrlModal+ isProviderLoading+ onSetCloudProvider={() => {}}+ cloudProviders={[mockProvider]}+ />);- }, 'Show not fail mount with isLoading');+ }, 'Show not fail mount with isProviderLoading');- t.ok(wrapper.find(StatusPanel).length === 1, 'should render StatusPanel when loading');+ t.ok(+ wrapper.find(StatusPanel).length === 1,+ 'should render StatusPanel when isProviderLoading=true'+ );wrapper = mountWithTheme(<ShareMapUrlModal- error="something is wrong"+ providerError="something is wrong"onSetCloudProvider={() => {}}cloudProviders={[mockProvider]}/>@@ -109,8 +116,7 @@ test('Components -> ShareMapUrlModal.mount with SharingUrl', t => {const shareUrl = 'http://taro-and-blue';const mockProvider = {getAccessToken: () => true,- name: 'taro',- getMapPermalink: () => shareUrl+ name: 'taro'};// mount@@ -118,7 +124,7 @@ test('Components -> ShareMapUrlModal.mount with SharingUrl', t => {t.doesNotThrow(() => {wrapper = mountWithTheme(<ShareMapUrlModal- successInfo={{metaUrl: 'http://somdthing'}}+ successInfo={{shareUrl}}cloudProviders={[mockProvider]}currentProvider="taro"onSetCloudProvider={() => {}}@@ -134,7 +140,7 @@ test('Components -> ShareMapUrlModal.mount with SharingUrl', t => {.find('input').props().value,shareUrl,- 'should render with successInfo.metaUrl'+ 'should render with successInfo.shareUrl');t.end();diff --git a/test/helpers/mock-provider.js b/test/helpers/mock-provider.jsnew file mode 100644index 000000000..435ad3f22--- /dev/null+++ b/test/helpers/mock-provider.js@@ -0,0 +1,56 @@+// Copyright (c) 2020 Uber Technologies, Inc.+//+// Permission is hereby granted, free of charge, to any person obtaining a copy+// of this software and associated documentation files (the "Software"), to deal+// in the Software without restriction, including without limitation the rights+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+// copies of the Software, and to permit persons to whom the Software is+// furnished to do so, subject to the following conditions:+//+// The above copyright notice and this permission notice shall be included in+// all copies or substantial portions of the Software.+//+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+// THE SOFTWARE.++import React from 'react';++const MockIcon = () => <div id="provider-icon" />;++export default class MockProvider {+ constructor() {+ // All cloud-providers providers must implement the following properties+ this.name = 'taro';+ this.displayName = 'Taro';+ this.icon = MockIcon;+ this.thumbnail = {width: 100, height: 60};+ }+ login(onSuccess) {+ onSuccess();+ return;+ }+ logout(onSuccess) {+ onSuccess();+ return;+ }+ hasPrivateStorage() {+ return true;+ }+ hasSharingUrl() {+ return true;+ }+ getAccessToken() {+ return true;+ }+ async uploadMap(args) {+ const promise = new Promise((resolve, reject) => {+ () => resolve('done!')();+ });+ await promise;+ }+}diff --git a/test/node/reducers/provider-state-test.js b/test/node/reducers/provider-state-test.jsindex 33e1b0be8..0befeec88 100644--- a/test/node/reducers/provider-state-test.js+++ b/test/node/reducers/provider-state-test.js@@ -19,7 +19,6 @@// THE SOFTWARE.import test from 'tape';-import React from 'react';import {drainTasksForTesting, succeedTaskInTest, errorTaskInTest} from 'react-palm/tasks';import sinon from 'sinon';import {default as Console} from 'global/console';@@ -28,37 +27,7 @@ import ActionTypes from 'constants/action-types';import {exportFileToCloud, resetProviderStatus, setCloudProvider} from 'actions/provider-actions';import reducer, {providerStateReducerFactory} from 'reducers/provider-state';import {INITIAL_PROVIDER_STATE} from 'reducers/provider-state-updaters';--const MockIcon = () => <div id="provider-icon" />;--class MockProvider {- constructor() {- // All cloud-providers providers must implement the following properties- this.name = 'taro';- this.displayName = 'Taro';- this.icon = MockIcon;- }- login(onSuccess) {- onSuccess();- return;- }- logout(onSuccess) {- onSuccess();- return;- }- hasPrivateStorage() {- return true;- }- hasSharingUrl() {- return true;- }- async uploadFile(args) {- const promise = new Promise((resolve, reject) => {- () => resolve('done!')();- });- await promise;- }-}+import MockProvider from 'test/helpers/mock-provider';test('#providerStateReducer', t => {t.deepEqual(@@ -103,8 +72,8 @@ test('#providerStateReducer -> EXPORT_FILE_TO_CLOUD', t => {t.ok(errSpy.calledTwice, 'should call console.error if provider does not have uploadFile');t.equal(errSpy.getCall(1).args[0],- 'uploadFile is not a function of Cloud provider: taro',- 'should warn when cannot find uploadFile function'+ 'uploadMap is not a function of Cloud provider: taro',+ 'should warn when cannot find uploadMap function');// mapData@@ -114,7 +83,9 @@ test('#providerStateReducer -> EXPORT_FILE_TO_CLOUD', t => {exportFileToCloud({mapData: {data: []},provider: mockProvider,- isPublic: false+ options: {+ isPublic: false+ }}));@@ -124,13 +95,14 @@ test('#providerStateReducer -> EXPORT_FILE_TO_CLOUD', t => {t.deepEqual(nextState,{- isLoading: true,- error: null,+ isProviderLoading: true,+ providerError: null,currentProvider: 'taro',successInfo: {},- initialState: {}+ initialState: {},+ mapSaved: null},- 'Should set isLoading and current provider'+ 'Should set isProviderLoading and current provider');t.equal(task1.type, 'EXPORT_FILE_TO_CLOUD_TASK', 'should create export file tasks');@@ -140,9 +112,9 @@ test('#providerStateReducer -> EXPORT_FILE_TO_CLOUD', t => {provider: mockProvider,payload: {mapData: {data: []},- blob: null,- fileName: null,- isPublic: false+ options: {+ isPublic: false+ }}},'should call upload file with correct payload'@@ -154,13 +126,14 @@ test('#providerStateReducer -> EXPORT_FILE_TO_CLOUD', t => {t.deepEqual(resultState1,{- isLoading: false,- error: null,+ isProviderLoading: false,+ providerError: null,currentProvider: 'taro',initialState: {},- successInfo: {metaUrl: 'taro_and_blue', folderLink: undefined}+ mapSaved: 'taro',+ successInfo: {url: 'taro_and_blue'}},- 'Should set isLoading to false and successInfo'+ 'Should set isProviderLoading to false and successInfo, mapSaved to taro');const task2 = drainTasksForTesting();t.ok(task2.length === 0, 'should create 0 task');@@ -170,10 +143,11 @@ test('#providerStateReducer -> EXPORT_FILE_TO_CLOUD', t => {t.deepEqual(resultState2,{- isLoading: false,- error: 'hello',+ isProviderLoading: false,+ providerError: 'hello',currentProvider: 'taro',initialState: {},+ mapSaved: null,successInfo: {}},'Should set isLoading to false and error'@@ -212,7 +186,11 @@ test('#providerStateReducer -> EXPORT_FILE_TO_CLOUD -> onSuccess : onError', t =const onSuccess = args => {t.deepEqual(args,- {response: mockResponse, provider: mockProvider},+ {+ response: mockResponse,+ provider: mockProvider,+ options: {isPublic: false}+ },'should call onSuccess with arguments');return {};@@ -230,7 +208,10 @@ test('#providerStateReducer -> EXPORT_FILE_TO_CLOUD -> onSuccess : onError', t =provider: mockProvider,onSuccess,onError,- closeModal: true+ closeModal: true,+ options: {+ isPublic: false+ }}));const [task1, ...more] = drainTasksForTesting();@@ -247,13 +228,14 @@ test('#providerStateReducer -> EXPORT_FILE_TO_CLOUD -> onSuccess : onError', t =t.deepEqual(nextState,{- isLoading: false,- error: null,+ isProviderLoading: false,+ providerError: null,currentProvider: 'taro',+ mapSaved: 'taro',initialState: {},- successInfo: {metaUrl: 'taro_and_blue', folderLink: undefined}+ successInfo: {url: 'taro_and_blue'}},- 'Should set isLoading to false and successInfo'+ 'Should set isProviderLoading to false and successInfo');const resultState1 = reducer(nextState, succeedTaskInTest(task2, undefined));@@ -272,11 +254,12 @@ test('#providerStateReducer -> EXPORT_FILE_TO_CLOUD -> onSuccess : onError', t =t.deepEqual(resultState3,{- isLoading: false,- error: null,+ isProviderLoading: false,+ providerError: null,currentProvider: 'taro',+ mapSaved: 'taro',initialState: {},- successInfo: {metaUrl: 'taro_and_blue', folderLink: undefined},+ successInfo: {url: 'taro_and_blue'},modalId: null},'Should call toggleModal(null'@@ -301,7 +284,9 @@ test('#providerStateReducer -> RESET_PROVIDER_STATUS', t => {exportFileToCloud({mapData: {data: []},provider: mockProvider,- isPublic: false+ options: {+ isPublic: false+ }}));const nextState1 = reducer(nextState, resetProviderStatus());@@ -309,11 +294,12 @@ test('#providerStateReducer -> RESET_PROVIDER_STATUS', t => {t.deepEqual(nextState1,{- isLoading: false,- error: null,+ isProviderLoading: false,+ providerError: null,currentProvider: 'taro',successInfo: {},- initialState: {}+ initialState: {},+ mapSaved: null},'Should resetProviderStatus');@@ -326,10 +312,11 @@ test('#providerStateReducer -> SET_CLOUD_PROVIDER', t => {t.deepEqual(nextState,{- isLoading: false,- error: null,+ isProviderLoading: false,+ providerError: null,currentProvider: 'blue',successInfo: {},+ mapSaved: null,initialState: {}},'Should setCloudProvider'