Skip to content

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

[Docs] Export identity actions individually and add JSDocs (#290)

Shan He3cbdb9802b20
diff --git a/package.json b/package.json
index 51b067fa4..41714ecb1 100644
--- a/package.json
+++ b/package.json
@@ -25,9 +25,9 @@
"scripts": {
"install:example": "cd examples/demo-app && npm i",
"install-and-start": "node ./scripts/install-and-start",
- "fast-test": "NODE_ENV=test babel-tape-runner ./test/node.js && NODE_ENV=test babel-tape-runner -r ./test/setup-browser-env.js ./test/browser.js",
+ "fast-test": "npm run test-node && npm run test-browser",
"test-browser": "NODE_ENV=test babel-tape-runner -r ./test/setup-browser-env.js ./test/browser.js",
- "test-node": "NODE_ENV=test babel-tape-runner ./test/node.js | tap-spec",
+ "test-node": "NODE_ENV=test babel-tape-runner ./test/node.js",
"test": "npm run lint && npm run test-node && npm run test-browser",
"cover": "nyc --reporter html --reporter cobertura --reporter json-summary npm test && nyc report",
"start": "npm run install-and-start -- examples/demo-app start-local",
diff --git a/src/actions/actions.js b/src/actions/actions.js
index 9f909f633..0be81ba17 100644
--- a/src/actions/actions.js
+++ b/src/actions/actions.js
@@ -21,20 +21,127 @@
import ActionTypes from 'constants/action-types';
import {createAction} from 'redux-actions';
-// create actions
-const {ADD_DATA_TO_MAP, INIT, RECEIVE_MAP_CONFIG, RESET_MAP_CONFIG} = ActionTypes;
-
// kepler.gl actions accessible outside component
export * from './vis-state-actions';
export * from './ui-state-actions';
export * from './map-state-actions';
export * from './map-style-actions';
-
export * from './identity-actions';
-export const [receiveMapConfig, resetMapConfig, keplerGlInit, addDataToMap] = [
- RECEIVE_MAP_CONFIG,
- RESET_MAP_CONFIG,
- INIT,
- ADD_DATA_TO_MAP
-].map(a => createAction(a));
+ /**
+ * Add 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.
+ *
+ * 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.
+ *
+ * Kepler.gl uses `dataId` in the config to match with loaded dataset. If you pass a config object, you need
+ * to match the `info.id` of your dataset to the `dataId` in eath `layer`, `filter` and `interactionConfig.tooltips.fieldsToShow`
+ *
+ * @param {Array<Object>|Object} datasets - ***required** datasets can be a dataset or an array of datasets
+ * Each dataset object needs to have `info` and `data` property.
+ * @param {Object} datasets.info -info of a dataset
+ * @param {string} datasets.info.id - id of this dataset. If config is defined, `id` should matches the `dataId` in config.
+ * @param {string} datasets.info.label - A display name of this dataset
+ * @param {Object} datasets.data - ***required** The data object, in a tabular format with 2 properties `fields` and `rows`
+ * @param {Array<Object>} datasets.data.fields - ***required** Array of fields,
+ * @param {string} datasets.data.fields.name - ***required** Name of the field,
+ * @param {Array<Array>} datasets.data.rows - ***required** Array of rows, in a tabular format with `fields` and `rows`
+ *
+ * @param {Object} options
+ * @param {boolean} options.centerMap `default: true` if `centerMap` is set to `true` kepler.gl will
+ * place the map view within the data points boundaries
+ * @param {boolean} options.readOnly `default: false` if `readOnly` is set to `true`
+ * the left setting panel will be hidden
+ * @param {Object} config this object will contain the full kepler.gl instance configuration {mapState, mapStyle, visState}
+ * @public
+ * @example
+ * import {addDataToMap} from 'kepler.gl/actions';
+ *
+ * this.props.dispatch(
+ * addDataToMap(
+ * // datasets
+ * {
+ * info: {
+ * label: 'Sample Taxi Trips in New York City',
+ * id: 'test_trip_data'
+ * },
+ * data: {
+ * fields: [{
+ * name: 'begintrip_lat',
+ * type: 'real',
+ * format: ''
+ * }, {
+ * name: 'begintrip_lng',
+ * type: 'real',
+ * format: ''
+ * }],
+ * rows: [
+ * [37.1234, -121.20292],
+ * [34.1223, -121.98234]
+ * ]
+ * }
+ * },
+ * // option
+ * {
+ * centerMap: true,
+ * readOnly: false
+ * },
+ * // config
+ * {
+ * mapStyle: {
+ * styleType: 'light'
+ * }
+ * }
+ * )
+ * );
+ */
+export const addDataToMap = createAction(
+ ActionTypes.ADD_DATA_TO_MAP,
+ (datasets, options, config) => ({datasets, options, config})
+);
+
+/**
+ * Reset all sub-reducers to its initial state. This can be used to clear out all configuration in the reducer.
+ * @public
+ */
+export const resetMapConfig = createAction(
+ ActionTypes.RESET_MAP_CONFIG
+);
+
+/**
+ * Pass config to kepler.gl instance, prepare the state with preset configs.
+ * Calling `KeplerGlSchema.parseSavedConfig` to convert saved config before passing it in is required.
+ *
+ * You can call `receiveMapConfig` before passing in any data. The reducer will store layer and filter config, waiting for
+ * data to come in. When data arrives, you can call `addDataToMap` without passing any config, and the reducer will try to match
+ * preloaded configs. This behavior is designed to allow asynchronic data loading.
+ *
+ * It is also useful when you want to prepare the kepler.gl instance with some preset layer and filter settings.
+ * **Note** Sequence is important, `receiveMapConfig` needs to be called __before__ data is loaded. Currently kepler.gl doesn't allow callling `receiveMapConfig` after data is loaded.
+ * It will reset current configuration first then apply config to it.
+ *
+ * @param {Object} config - ***required** The Config Object
+ * @public
+ * @example
+ * import {receiveMapConfig} from 'kepler.gl/actions';
+ * import KeplerGlSchema from 'kepler.gl/schemas';
+ *
+ * const parsedConfig = KeplerGlSchema.parseSavedConfig(config);
+ * this.props.dispatch(receiveMapConfig(parsedConfig));
+ */
+export const receiveMapConfig = createAction(
+ ActionTypes.RECEIVE_MAP_CONFIG,
+ config => config
+);
+
+/**
+ * Initialize kepler.gl reducer. It is used to pass in `mapboxApiAccessToken` to `mapStyle` reducer.
+ * @param {Object} payload
+ * @param {string} payload.mapboxApiAccessToken - mapboxApiAccessToken to be saved to mapStyle reducer
+ * @public
+ */
+export const keplerGlInit = createAction(
+ ActionTypes.INIT,
+ ({mapboxApiAccessToken} = {}) => ({mapboxApiAccessToken})
+);
diff --git a/src/actions/identity-actions.js b/src/actions/identity-actions.js
index 01a901f21..b04a0f697 100644
--- a/src/actions/identity-actions.js
+++ b/src/actions/identity-actions.js
@@ -19,15 +19,46 @@
// THE SOFTWARE.
import {createAction} from 'redux-actions';
-import {ACTION_PREFIX} from 'constants/default-settings';
+import ActionTypes from 'constants/action-types';
-// Actions to add and remove entries
-export const REGISTER_ENTRY = `${ACTION_PREFIX}REGISTER_ENTRY`;
-export const DELETE_ENTRY = `${ACTION_PREFIX}DELETE_ENTRY`;
-export const RENAME_ENTRY = `${ACTION_PREFIX}RENAME_ENTRY`;
+/**
+ *
+ * Add a new kepler.gl instance in `keplerGlReducer`. This action is called under-the-hood when a `KeplerGl` component is **mounted** to the dom.
+ * Note that if you dispatch actions such as adding data to a kepler.gl instance before the React component is mounted, the action will not be
+ * performed. Instance reducer can only handle actions when it is instantiated.
+ * @param {Object} payload
+ * @param {string} payload.id - ***required** The id of the instance
+ * @param {boolean} payload.mint - 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`
+ * @param {string} payload.mapboxApiAccessToken - mapboxApiAccessToken to be saved in `map-style` reducer.
+ * @public
+ */
+export const registerEntry = createAction(
+ ActionTypes.REGISTER_ENTRY,
+ ({id, mint, mapboxApiAccessToken}) => ({id, mint, mapboxApiAccessToken})
+);
-export const [registerEntry, deleteEntry, renameEntry] = [
- REGISTER_ENTRY,
- DELETE_ENTRY,
- RENAME_ENTRY
-].map(a => createAction(a));
+/**
+ *
+ * Delete an instance from `keplerGlReducer`. This action is called under-the-hood when a `KeplerGl` component is **un-mounted** to the dom.
+ * If `mint` is set to be `true` in the component prop, the instance state will be deleted from the root reducer. Otherwise, the root reducer will keep
+ * the instance state and later transfer it to a newly mounted component with the same `id`
+ * @param {string} id - the id of the instance to be deleted
+ * @public
+ */
+export const deleteEntry = createAction(
+ ActionTypes.DELETE_ENTRY,
+ id => id
+);
+
+/**
+ *
+ * Rename an instance in the root reducer, keep its entire state
+ * @param {string} oldId - ***required** old id
+ * @param {string} newId - ***required** new id
+ * @public
+ */
+export const renameEntry = createAction(
+ ActionTypes.RENAME_ENTRY,
+ (oldId, newId) => ({oldId, newId})
+);
diff --git a/src/components/container.js b/src/components/container.js
index 0845eaf93..e0ebee2ab 100644
--- a/src/components/container.js
+++ b/src/components/container.js
@@ -79,8 +79,8 @@ export function ContainerFactory(KeplerGl) {
componentWillReceiveProps(nextProps) {
// check if id has changed, if true, copy state over
- if (nextProps.id !== this.props.id) {
- this.props.dispatch(renameEntry(this.props.id, nextProps));
+ if (nextProps.id && nextProps.id !== this.props.id) {
+ this.props.dispatch(renameEntry(this.props.id, nextProps.id));
}
}
diff --git a/src/constants/action-types.js b/src/constants/action-types.js
index 3e5d83e2f..c9c4141a9 100644
--- a/src/constants/action-types.js
+++ b/src/constants/action-types.js
@@ -22,6 +22,11 @@ import keyMirror from 'keymirror';
import {ACTION_PREFIX} from './default-settings';
const ActionTypes = keyMirror({
+ // identity action
+ REGISTER_ENTRY: null,
+ DELETE_ENTRY: null,
+ RENAME_ENTRY: null,
+
// visState
ADD_DATA: null,
ADD_FILTER: null,
diff --git a/src/reducers/root.js b/src/reducers/root.js
index 32b4c2169..15b31aa32 100644
--- a/src/reducers/root.js
+++ b/src/reducers/root.js
@@ -22,12 +22,7 @@ import {handleActions} from 'redux-actions';
import {actionFor, updateProperty} from '../actions/action-wrapper';
import {coreReducerFactory} from './core';
-
-import {
- REGISTER_ENTRY,
- DELETE_ENTRY,
- RENAME_ENTRY
-} from '../actions/identity-actions';
+import ActionTypes from 'constants/action-types';
import {keplerGlInit} from '../actions/actions';
/*
@@ -60,7 +55,7 @@ export function provideInitialState(initialState) {
{}
);
- const handleRenameEntry = (state, {payload: [oldId, newId]}) =>
+ const handleRenameEntry = (state, {payload: {oldId, newId}}) =>
Object.keys(state).reduce(
(accu, curr) => ({
...accu,
@@ -79,9 +74,9 @@ export function provideInitialState(initialState) {
// perform additional state reducing (e.g. switch action.type etc...)
return handleActions(
{
- [REGISTER_ENTRY]: handleRegisterEntry,
- [DELETE_ENTRY]: handleDeleteEntry,
- [RENAME_ENTRY]: handleRenameEntry
+ [ActionTypes.REGISTER_ENTRY]: handleRegisterEntry,
+ [ActionTypes.DELETE_ENTRY]: handleDeleteEntry,
+ [ActionTypes.RENAME_ENTRY]: handleRenameEntry
},
initialCoreState
)(state, action);
diff --git a/test/browser/components/container-test.js b/test/browser/components/container-test.js
index 37be90312..32438772a 100644
--- a/test/browser/components/container-test.js
+++ b/test/browser/components/container-test.js
@@ -229,3 +229,96 @@ test('Components -> Container -> Mount with mint:false', t => {
spy.restore();
t.end();
});
+
+test('Components -> Container -> Mount then rename', t => {
+ const dispatch = sinon.spy();
+
+ // mount with custom state
+ const store = mockStore({smoothie: {}});
+ const appReducer = combineReducers({
+ smoothie: rootReducer
+ });
+
+ let wrapper;
+ const testId = {
+ id: 'milkshake'
+ };
+
+ // mount with mint: false
+ t.doesNotThrow(() => {
+ wrapper = mount(
+ <Container
+ getState={s => s.smoothie}
+ id={testId.id}
+ mapboxApiAccessToken="hello.world"
+ dispatch={dispatch}
+ store={store}
+ />
+ );
+ }, 'Should not throw error when mount');
+
+ const expectedActions0 = {type: '@@kepler.gl/REGISTER_ENTRY', payload: {id: 'milkshake', mint: true, mapboxApiAccessToken: 'hello.world'}};
+
+ t.deepEqual(
+ store.getActions().pop(),
+ expectedActions0,
+ 'should register entry'
+ );
+
+ let nextState = appReducer({}, expectedActions0);
+ let expectedState = {
+ smoothie: {
+ milkshake: {
+ ...initialCoreState,
+ mapStyle: {
+ ...initialCoreState.mapStyle,
+ // should replace access token
+ mapboxApiAccessToken: 'hello.world'
+ }
+ }
+ }
+ };
+ t.deepEqual(
+ nextState,
+ expectedState,
+ 'should register milkshake to root reducer'
+ );
+
+ wrapper.setProps({id: 'milkshake-2'});
+ // actions = store.getActions();
+ const expectedActions1 = {
+ type: '@@kepler.gl/RENAME_ENTRY',
+ payload: {oldId: 'milkshake', newId: 'milkshake-2'}
+ };
+
+ t.deepEqual(
+ store.getActions().pop(),
+ expectedActions1,
+ 'should rename entry'
+ );
+
+ const nextState1 = appReducer(nextState, expectedActions1);
+ const expectedState1 = {
+ smoothie: {
+ 'milkshake-2': nextState.smoothie.milkshake
+ }
+ };
+
+ t.deepEqual(
+ nextState1,
+ expectedState1,
+ 'should rename milkshake to milkshake-2'
+ );
+ // unmount
+ wrapper.unmount();
+
+ const expectedActions2 = {type: '@@kepler.gl/DELETE_ENTRY', payload: 'milkshake-2'};
+
+ t.deepEqual(
+ store.getActions().pop(),
+ expectedActions2,
+ 'should call unmount milkshake-2'
+ );
+
+ t.end();
+});
diff --git a/test/node/reducers/composer-state-test.js b/test/node/reducers/composer-state-test.js
index f1e8d273d..6e5d04e88 100644
--- a/test/node/reducers/composer-state-test.js
+++ b/test/node/reducers/composer-state-test.js
@@ -58,7 +58,7 @@ const mockRawData = {
test('#composerStateReducer - addDataToMapComposed: mapStyle', t => {
// init kepler.gl root and instance
- const state = keplerGlReducer({}, registerEntry({id: 'test'})).test;
+ const state = keplerGlReducer(undefined, registerEntry({id: 'test'})).test;
const newState = addDataToMapComposed(state, {
payload: {