Skip to content

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

[Enhancement] React 17: replace componentWillReceiveProps and componentWillMount (#745)

Shan Heddaef710bef8
diff --git a/examples/custom-reducer/package.json b/examples/custom-reducer/package.json
index c43f96c2b..6d72d42f8 100644
--- a/examples/custom-reducer/package.json
+++ b/examples/custom-reducer/package.json
@@ -9,7 +9,7 @@
"react": "^16.8.4",
"react-dom": "^16.8.4",
"react-palm": "^1.1.2",
- "react-redux": "^4.0.0",
+ "react-redux": "^7.1.3",
"react-virtualized": "^9.21.0",
"redux-actions": "^2.2.1",
"styled-components": "^4.1.3"
diff --git a/examples/custom-theme/package.json b/examples/custom-theme/package.json
index 9a043f0a2..a482737ab 100644
--- a/examples/custom-theme/package.json
+++ b/examples/custom-theme/package.json
@@ -9,7 +9,7 @@
"react": "^16.8.4",
"react-dom": "^16.8.4",
"react-palm": "^1.1.2",
- "react-redux": "^4.0.0",
+ "react-redux": "^7.1.3",
"react-virtualized": "^9.21.0",
"redux-actions": "^2.2.1",
"styled-components": "^4.1.3"
@@ -47,4 +47,4 @@
"webpack-hot-middleware": "^2.24.3",
"webpack-stats-plugin": "^0.2.1"
}
-}
\ No newline at end of file
+}
diff --git a/examples/demo-app/package.json b/examples/demo-app/package.json
index 39cfbf1af..b6b51ee37 100644
--- a/examples/demo-app/package.json
+++ b/examples/demo-app/package.json
@@ -17,8 +17,8 @@
"react-dom": "^16.8.4",
"react-markdown": "^4.2.2",
"react-palm": "^1.1.2",
- "react-redux": "^5.1.1",
- "react-router": "^3.0.5",
+ "react-redux": "^7.1.3",
+ "react-router": "3.2.5",
"react-router-redux": "^4.0.8",
"react-virtualized": "^9.21.0",
"redux-actions": "^2.2.1",
@@ -57,4 +57,4 @@
"webpack-hot-middleware": "^2.24.3",
"webpack-stats-plugin": "^0.2.1"
}
-}
\ No newline at end of file
+}
diff --git a/examples/demo-app/src/app.js b/examples/demo-app/src/app.js
index 899812eeb..c8a7eb94e 100644
--- a/examples/demo-app/src/app.js
+++ b/examples/demo-app/src/app.js
@@ -62,6 +62,7 @@ import {processCsvData, processGeojson} from 'kepler.gl/processors';
const BannerHeight = 30;
const BannerKey = 'kgHideBanner-iiba';
+const keplerGlGetState = state => state.demo.keplerGl;
const GlobalStyle = styled.div`
font-family: ff-clan-web-pro, 'Helvetica Neue', Helvetica, sans-serif;
@@ -99,12 +100,12 @@ class App extends Component {
height: window.innerHeight
};
- UNSAFE_componentWillMount() {
+ componentDidMount() {
// if we pass an id as part of the url
// we ry to fetch along map configurations
const {
params: {id} = {},
- location: {query = {}}
+ location: {query = {}} = {}
} = this.props;
// Load sample using its id
@@ -117,9 +118,7 @@ class App extends Component {
// TODO?: validate map url
this.props.dispatch(loadRemoteMap({dataUrl: query.mapUrl}));
}
- }
- componentDidMount() {
// delay zs to show the banner
// if (!window.localStorage.getItem(BannerKey)) {
// window.setTimeout(this._showBanner, 3000);
@@ -353,7 +352,7 @@ class App extends Component {
/*
* Specify path to keplerGl state, because it is not mount at the root
*/
- getState={state => state.demo.keplerGl}
+ getState={keplerGlGetState}
width={width}
height={height - (showBanner ? BannerHeight : 0)}
onSaveMap={this._isCloudStorageEnabled() && this._toggleCloudModal}
diff --git a/examples/node-app/package.json b/examples/node-app/package.json
index eba364f46..61d254ec1 100644
--- a/examples/node-app/package.json
+++ b/examples/node-app/package.json
@@ -10,7 +10,7 @@
"react": "^16.8.4",
"react-dom": "^16.8.4",
"react-palm": "^1.1.2",
- "react-redux": "^4.4.5",
+ "react-redux": "^7.1.3",
"react-virtualized": "^9.21.0",
"redux-actions": "^2.2.1",
"styled-components": "^4.1.3"
diff --git a/examples/open-modal/package.json b/examples/open-modal/package.json
index 96f15158b..f5a836fec 100644
--- a/examples/open-modal/package.json
+++ b/examples/open-modal/package.json
@@ -10,7 +10,7 @@
"react-dom": "^16.8.4",
"react-modal": "^3.1.10",
"react-palm": "^1.1.2",
- "react-redux": "^4.0.0",
+ "react-redux": "^7.1.3",
"react-virtualized": "^9.21.0",
"redux-actions": "^2.2.1",
"styled-components": "^4.1.3"
diff --git a/examples/open-modal/src/app.js b/examples/open-modal/src/app.js
index 64a9155fa..907ff2567 100644
--- a/examples/open-modal/src/app.js
+++ b/examples/open-modal/src/app.js
@@ -32,8 +32,8 @@ import SavedMap from './components/saved-map';
const MAPBOX_TOKEN = process.env.MapboxAccessToken; // eslint-disable-line
class App extends Component {
- componentWillReceiveProps(nextProps) {
- if (!this.props.keplerGl.bar && nextProps.keplerGl.bar) {
+ componentDidUpdate(prevProps) {
+ if (!prevProps.keplerGl.bar && this.props.keplerGl.bar) {
this.props.dispatch(
wrapTo('bar', addDataToMap(
{
diff --git a/examples/replace-component/package.json b/examples/replace-component/package.json
index b35976b80..6d72d42f8 100644
--- a/examples/replace-component/package.json
+++ b/examples/replace-component/package.json
@@ -9,7 +9,7 @@
"react": "^16.8.4",
"react-dom": "^16.8.4",
"react-palm": "^1.1.2",
- "react-redux": "^4.4.5",
+ "react-redux": "^7.1.3",
"react-virtualized": "^9.21.0",
"redux-actions": "^2.2.1",
"styled-components": "^4.1.3"
diff --git a/examples/webpack.config.local.js b/examples/webpack.config.local.js
index 518790bd8..7ea430df3 100644
--- a/examples/webpack.config.local.js
+++ b/examples/webpack.config.local.js
@@ -55,6 +55,7 @@ function makeLocalDevConfig(env, EXAMPLE_DIR = LIB_DIR) {
// Imports kepler.gl library from the src directory in this repo
'kepler.gl': SRC_DIR,
react: resolve(EXAMPLE_DIR, './node_modules/react'),
+ 'react-redux': resolve(EXAMPLE_DIR, './node_modules/react-redux'),
'styled-components': resolve(
EXAMPLE_DIR,
'./node_modules/styled-components'
diff --git a/package.json b/package.json
index 4d3705809..c04710c4d 100644
--- a/package.json
+++ b/package.json
@@ -105,14 +105,14 @@
"pbf": "^3.1.0",
"prop-types": "^15.6.0",
"react-color": "^2.17.3",
- "react-file-drop": "^0.1.9",
"react-json-pretty": "^1.7.9",
+ "react-lifecycles-compat": "^3.0.4",
"react-map-gl": "^5.0.3",
"react-markdown": "^4.0.6",
"react-modal": "^3.8.1",
"react-onclickoutside": "^6.7.1",
"react-palm": "^3.1.2",
- "react-redux": "^5.1.1",
+ "react-redux": "^7.1.3",
"react-sortable-hoc": "^1.8.3",
"react-tooltip": "^3.10.0",
"react-virtualized": "^9.21.1",
@@ -204,8 +204,8 @@
"webpack-stats-plugin": "^0.2.1"
},
"peerDependencies": {
- "react": "16.x",
- "react-dom": "16.x",
+ "react": "^16.3",
+ "react-dom": "^16.3",
"styled-components": "^4.x"
},
"nyc": {
@@ -213,8 +213,9 @@
"instrument": false,
"exclude": [
"test/**/*.js",
- "src/tasks/*.js",
- "src/templates/*.js"
+ "src/tasks",
+ "src/templates",
+ "src/styles"
]
},
"maintainers": [
diff --git a/src/components/common/file-uploader/file-drop.js b/src/components/common/file-uploader/file-drop.js
new file mode 100644
index 000000000..916e09696
--- /dev/null
+++ b/src/components/common/file-uploader/file-drop.js
@@ -0,0 +1,225 @@
+// Copyright (c) 2019 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.
+
+/**
+ * Copied from https://github.com/sarink/react-file-drop
+ * For React 16.8 compatibility
+ */
+import PropTypes from 'prop-types';
+import React from 'react';
+
+class FileDrop extends React.PureComponent {
+ static isIE = () =>
+ window &&
+ (window.navigator.userAgent.indexOf('MSIE') !== -1 ||
+ window.navigator.appVersion.indexOf('Trident/') > 0);
+
+ static eventHasFiles = event => {
+ // In most browsers this is an array, but in IE11 it's an Object :(
+
+ let hasFiles = false;
+ if (event.dataTransfer) {
+ const types = event.dataTransfer.types;
+ for (const keyOrIndex in types) {
+ if (types[keyOrIndex] === 'Files') {
+ hasFiles = true;
+ break;
+ }
+ }
+ }
+ return hasFiles;
+ };
+
+ static propTypes = {
+ className: PropTypes.string,
+ targetClassName: PropTypes.string,
+ draggingOverFrameClassName: PropTypes.string,
+ draggingOverTargetClassName: PropTypes.string,
+ onDragOver: PropTypes.func,
+ onDragLeave: PropTypes.func,
+ onDrop: PropTypes.func,
+ dropEffect: PropTypes.oneOf(['copy', 'move', 'link', 'none']),
+ frame: (props, propName, componentName) => {
+ const prop = props[propName];
+ if (prop === null) {
+ return new Error(
+ `Warning: Required prop \`${propName}\` was not specified in \`${componentName}\``
+ );
+ }
+ if (
+ prop !== document &&
+ prop !== window &&
+ !(prop instanceof HTMLElement)
+ ) {
+ return new Error(
+ `Warning: Prop \`${propName}\` must be one of the following: document, HTMLElement!`
+ );
+ }
+ },
+ onFrameDragEnter: PropTypes.func,
+ onFrameDragLeave: PropTypes.func,
+ onFrameDrop: PropTypes.func
+ };
+
+ static defaultProps = {
+ dropEffect: 'copy',
+ frame: window ? window.document : undefined,
+ className: 'file-drop',
+ targetClassName: 'file-drop-target',
+ draggingOverFrameClassName: 'file-drop-dragging-over-frame',
+ draggingOverTargetClassName: 'file-drop-dragging-over-target'
+ };
+
+ constructor(props) {
+ super(props);
+ this.frameDragCounter = 0;
+ this.state = {draggingOverFrame: false, draggingOverTarget: false};
+ }
+
+ componentDidMount() {
+ this.startFrameListeners(this.props.frame);
+ this.resetDragging();
+ window.addEventListener('dragover', this.handleWindowDragOverOrDrop);
+ window.addEventListener('drop', this.handleWindowDragOverOrDrop);
+ }
+
+ componentDidUpdate(prevProps) {
+ if (prevProps.frame !== this.props.frame) {
+ this.resetDragging();
+ this.stopFrameListeners(prevProps.frame);
+ this.startFrameListeners(this.props.frame);
+ }
+ }
+
+ componentWillUnmount() {
+ this.stopFrameListeners(this.props.frame);
+ window.removeEventListener('dragover', this.handleWindowDragOverOrDrop);
+ window.removeEventListener('drop', this.handleWindowDragOverOrDrop);
+ }
+
+ resetDragging = () => {
+ this.frameDragCounter = 0;
+ this.setState({draggingOverFrame: false, draggingOverTarget: false});
+ };
+
+ handleWindowDragOverOrDrop = event => {
+ // This prevents the browser from trying to load whatever file the user dropped on the window
+ event.preventDefault();
+ };
+
+ handleFrameDrag = event => {
+ // Only allow dragging of files
+ if (!FileDrop.eventHasFiles(event)) return;
+
+ // We are listening for events on the 'frame', so every time the user drags over any element in the frame's tree,
+ // the event bubbles up to the frame. By keeping count of how many "dragenters" we get, we can tell if they are still
+ // "draggingOverFrame" (b/c you get one "dragenter" initially, and one "dragenter"/one "dragleave" for every bubble)
+ // This is far better than a "dragover" handler, which would be calling `setState` continuously.
+ this.frameDragCounter += event.type === 'dragenter' ? 1 : -1;
+
+ if (this.frameDragCounter === 1) {
+ this.setState({draggingOverFrame: true});
+ if (this.props.onFrameDragEnter) this.props.onFrameDragEnter(event);
+ return;
+ }
+
+ if (this.frameDragCounter === 0) {
+ this.setState({draggingOverFrame: false});
+ if (this.props.onFrameDragLeave) this.props.onFrameDragLeave(event);
+ return;
+ }
+ };
+
+ handleFrameDrop = event => {
+ event.preventDefault();
+ if (!this.state.draggingOverTarget) {
+ this.resetDragging();
+ if (this.props.onFrameDrop) this.props.onFrameDrop(event);
+ }
+ };
+
+ handleDragOver = event => {
+ if (FileDrop.eventHasFiles(event)) {
+ this.setState({draggingOverTarget: true});
+ if (!FileDrop.isIE() && this.props.dropEffect)
+ event.dataTransfer.dropEffect = this.props.dropEffect;
+ if (this.props.onDragOver) this.props.onDragOver(event);
+ }
+ };
+
+ handleDragLeave = event => {
+ this.setState({draggingOverTarget: false});
+ if (this.props.onDragLeave) this.props.onDragLeave(event);
+ };
+
+ handleDrop = event => {
+ if (this.props.onDrop && FileDrop.eventHasFiles(event)) {
+ const files = event.dataTransfer ? event.dataTransfer.files : null;
+ this.props.onDrop(files, event);
+ }
+ this.resetDragging();
+ };
+
+ stopFrameListeners = frame => {
+ if (frame) {
+ frame.removeEventListener('dragenter', this.handleFrameDrag);
+ frame.removeEventListener('dragleave', this.handleFrameDrag);
+ frame.removeEventListener('drop', this.handleFrameDrop);
+ }
+ };
+
+ startFrameListeners = frame => {
+ if (frame) {
+ frame.addEventListener('dragenter', this.handleFrameDrag);
+ frame.addEventListener('dragleave', this.handleFrameDrag);
+ frame.addEventListener('drop', this.handleFrameDrop);
+ }
+ };
+
+ render() {
+ const {
+ children,
+ className,
+ targetClassName,
+ draggingOverFrameClassName,
+ draggingOverTargetClassName
+ } = this.props;
+ const {draggingOverTarget, draggingOverFrame} = this.state;
+
+ let fileDropTargetClassName = targetClassName;
+ if (draggingOverFrame)
+ fileDropTargetClassName += ` ${draggingOverFrameClassName}`;
+ if (draggingOverTarget)
+ fileDropTargetClassName += ` ${draggingOverTargetClassName}`;
+
+ return (
+ <div
+ className={className}
+ onDragOver={this.handleDragOver}
+ onDragLeave={this.handleDragLeave}
+ onDrop={this.handleDrop}
+ >
+ <div className={fileDropTargetClassName}>{children}</div>
+ </div>
+ );
+ }
+}
+
+export default FileDrop;
diff --git a/src/components/common/file-uploader/file-upload.js b/src/components/common/file-uploader/file-upload.js
index 512288c6e..d3807fe62 100644
--- a/src/components/common/file-uploader/file-upload.js
+++ b/src/components/common/file-uploader/file-upload.js
@@ -19,12 +19,15 @@
// THE SOFTWARE.
import React, {Component, createRef} from 'react';
+import {polyfill} from 'react-lifecycles-compat';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import UploadButton from './upload-button';
import {FileType, DragNDrop} from 'components/common/icons';
import LoadingSpinner from 'components/common/loading-spinner';
+import FileDrop from './file-drop';
+
import {isChrome} from 'utils/utils';
import {GUIDES_FILE_FORMAT} from 'constants/user-guides';
import ReactMarkdown from 'react-markdown';
@@ -32,9 +35,6 @@ import ReactMarkdown from 'react-markdown';
// Breakpoints
import {media} from 'styles/media-breakpoints';
-const FileDrop =
- typeof document !== 'undefined' ? require('react-file-drop') : null;
-
// File.type is not reliable if the OS does not have a
// registered mapping for the extension.
// NOTE: Shapefiles must be in a compressed format since
@@ -71,7 +71,7 @@ const StyledUploadMessage = styled.div`
`}
`;
-const WarningMsg = styled.span`
+export const WarningMsg = styled.span`
margin-top: 10px;
color: ${props => props.theme.errorColor};
font-weight: 500;
@@ -172,7 +172,7 @@ const StyledDisclaimer = styled(StyledMessage)`
margin: 0 auto;
`;
-export default class FileUpload extends Component {
+class FileUpload extends Component {
static propTypes = {
onFileUpload: PropTypes.func.isRequired,
@@ -250,6 +250,7 @@ export default class FileUpload extends Component {
</WarningMsg>
);
} else if (this.props.fileLoading && files.length) {
+
return (
<StyledMessage className="file-uploader__message">
<div className="loading-action">Uploading</div>
@@ -283,10 +284,10 @@ export default class FileUpload extends Component {
{FileDrop ? (
<FileDrop
frame={this.frame.current || document}
- targetAlwaysVisible
onDragOver={() => this._toggleDragState(true)}
onDragLeave={() => this._toggleDragState(false)}
onDrop={this._handleFileInput}
+ className="file-uploader__file-drop"
>
<StyledUploadMessage className="file-upload__message">
<ReactMarkdown
@@ -330,3 +331,7 @@ export default class FileUpload extends Component {
);
}
}
+
+polyfill(FileUpload);
+
+export default FileUpload;
diff --git a/src/components/common/file-uploader/upload-button.js b/src/components/common/file-uploader/upload-button.js
index de457e2b6..de86a0e30 100644
--- a/src/components/common/file-uploader/upload-button.js
+++ b/src/components/common/file-uploader/upload-button.js
@@ -65,7 +65,7 @@ export default class UploadButton extends Component {
style={{display: 'none'}}
onChange={this._onChange}
/>
- <span onClick={this._onClick}>{this.props.children}</span>
+ <span className="file-upload__upload-button-span" onClick={this._onClick}>{this.props.children}</span>
</Wrapper>
);
}
diff --git a/src/components/common/item-selector/typeahead.js b/src/components/common/item-selector/typeahead.js
index 0066259a5..93efe5f27 100644
--- a/src/components/common/item-selector/typeahead.js
+++ b/src/components/common/item-selector/typeahead.js
@@ -19,6 +19,7 @@
// THE SOFTWARE.
import React, {Component, createRef} from 'react';
+import {polyfill} from 'react-lifecycles-compat';
import PropTypes from 'prop-types';
import fuzzy from 'fuzzy';
import classNames from 'classnames';
@@ -68,7 +69,56 @@ const InputIcon = styled.div`
color: ${props => props.theme.inputPlaceholderColor};
`;
-export default class Typeahead extends Component {
+function generateSearchFunction(props) {
+ const {searchOptions, filterOption} = props;
+ if (typeof searchOptions === 'function') {
+ if (filterOption !== null) {
+ Console.warn(
+ 'searchOptions prop is being used, filterOption prop will be ignored'
+ );
+ }
+ return searchOptions;
+ } else if (typeof filterOption === 'function') {
+ // use custom filter option
+ return (value, options) => options.filter(o => filterOption(value, o));
+ }
+
+ const mapper =
+ typeof filterOption === 'string'
+ ? Accessor.generateAccessor(filterOption)
+ : Accessor.IDENTITY_FN;
+
+ return (value, options) =>
+ fuzzy
+ .filter(value, options, {extract: mapper})
+ .map(res => options[res.index]);
+}
+
+function getOptionsForValue(value, props, state) {
+ const {options, showOptionsWhenEmpty} = props;
+
+ if (!props.searchable) {
+ // directly pass through options if can not be searched
+ return options;
+ }
+ if (shouldSkipSearch(value, state, showOptionsWhenEmpty)) {
+ return options;
+ }
+
+ const searchOptions = generateSearchFunction(props);
+ return searchOptions(value, options);
+}
+
+function shouldSkipSearch(input, state, showOptionsWhenEmpty) {
+ const emptyValue = !input || input.trim().length === 0;
+
+ // this.state must be checked because it may not be defined yet if this function
+ // is called from within getInitialState
+ const isFocused = state && state.isFocused;
+ return !(showOptionsWhenEmpty && isFocused) && emptyValue;
+}
+
+class Typeahead extends Component {
static propTypes = {
name: PropTypes.string,
customClasses: PropTypes.object,
@@ -96,7 +146,10 @@ export default class Typeahead extends Component {
inputDisplayOption: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
formInputOption: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
defaultClassNames: PropTypes.bool,
- customListComponent: PropTypes.oneOfType([PropTypes.element, PropTypes.func]),
+ customListComponent: PropTypes.oneOfType([
+ PropTypes.element,
+ PropTypes.func
+ ]),
customListItemComponent: PropTypes.oneOfType([
PropTypes.element,
PropTypes.func
@@ -138,14 +191,18 @@ export default class Typeahead extends Component {
resultsTruncatedMessage: null
};
+ static getDerivedStateFromProps(props, state) {
+ // invoked after a component is instantiated as well as before it is re-rendered
+ const searchResults = getOptionsForValue(state.entryValue, props, state);
+
+ return {searchResults};
+ }
+
constructor(props) {
super(props);
this.state = {
- searchResults: this.getOptionsForValue(
- this.props.initialValue,
- this.props.options
- ),
+ searchResults: [],
// This should be called something else, 'entryValue'
entryValue: this.props.value || this.props.initialValue,
@@ -163,10 +220,6 @@ export default class Typeahead extends Component {
}
componentDidMount() {
- this.setState({
- searchResults: this.getOptionsForValue('', this.props.options)
- });
-
// call focus on entry or div to trigger key events listener
if (this.entry.current) {
this.entry.current.focus();
@@ -175,57 +228,26 @@ export default class Typeahead extends Component {
}
}
- componentWillReceiveProps(nextProps) {
- const searchResults = this.getOptionsForValue(
- this.state.entryValue,
- nextProps.options
- );
-
- this.setState({searchResults});
- }
-
root = createRef();
entry = createRef();
- _shouldSkipSearch(input) {
- const emptyValue = !input || input.trim().length === 0;
-
- // this.state must be checked because it may not be defined yet if this function
- // is called from within getInitialState
- const isFocused = this.state && this.state.isFocused;
- return !(this.props.showOptionsWhenEmpty && isFocused) && emptyValue;
- }
-
- getOptionsForValue(value, options) {
- if (!this.props.searchable) {
- // directly pass through options if can not be searched
- return options;
- }
- if (this._shouldSkipSearch(value)) {
- return options;
- }
-
- const searchOptions = this._generateSearchFunction();
- return searchOptions(value, options);
- }
-
- focus() {
+ focus = () => {
if (this.entry.current) {
this.entry.current.focus();
}
- }
+ };
- _hasCustomValue() {
+ _hasCustomValue = () => {
return (
this.props.allowCustomValues > 0 &&
this.state.entryValue.length >= this.props.allowCustomValues &&
this.state.searchResults.indexOf(this.state.entryValue) < 0
);
- }
+ };
- _getCustomValue() {
+ _getCustomValue = () => {
return this._hasCustomValue() ? this.state.entryValue : null;
- }
+ };
_renderIncrementalSearchResults() {
return (
@@ -276,7 +298,7 @@ export default class Typeahead extends Component {
if (this.props.searchable) {
// reset entry input
this.setState({
- searchResults: this.getOptionsForValue('', this.props.options),
+ searchResults: getOptionsForValue('', this.props, this.state),
selection: '',
entryValue: ''
});
@@ -291,7 +313,7 @@ export default class Typeahead extends Component {
const value = this.entry.current.value;
this.setState({
- searchResults: this.getOptionsForValue(value, this.props.options),
+ searchResults: getOptionsForValue(value, this.props, this.state),
selection: '',
entryValue: value
});
@@ -306,19 +328,19 @@ export default class Typeahead extends Component {
return this._onOptionSelected(selection, event);
};
- _onEscape() {
+ _onEscape = () => {
this.setState({
selectionIndex: null
});
- }
+ };
- _onTab(event) {
+ _onTab = event => {
const selection = this.getSelection();
let option = selection
? selection
: this.state.searchResults.length > 0
- ? this.state.searchResults[0]
- : null;
+ ? this.state.searchResults[0]
+ : null;
if (option === null && this._hasCustomValue()) {
option = this._getCustomValue();
@@ -327,9 +349,9 @@ export default class Typeahead extends Component {
if (option !== null) {
return this._onOptionSelected(option, event);
}
- }
+ };
- eventMap(event) {
+ eventMap = event => {
const events = {};
events[KeyEvent.DOM_VK_UP] = this.navUp;
@@ -341,15 +363,17 @@ export default class Typeahead extends Component {
events[KeyEvent.DOM_VK_TAB] = this._onTab;
return events;
- }
+ };
- _nav(delta) {
+ _nav = delta => {
if (!this._hasHint()) {
return;
}
let newIndex =
this.state.selectionIndex === null
- ? delta === 1 ? 0 : delta
+ ? delta === 1
+ ? 0
+ : delta
: this.state.selectionIndex + delta;
let length = this.props.maxVisible
? this.state.searchResults.slice(0, this.props.maxVisible).length
@@ -365,7 +389,7 @@ export default class Typeahead extends Component {
}
this.setState({selectionIndex: newIndex});
- }
+ };
navDown = () => {
this._nav(1);
@@ -430,33 +454,6 @@ export default class Typeahead extends Component {
);
}
- _generateSearchFunction() {
- const searchOptionsProp = this.props.searchOptions;
- const filterOptionProp = this.props.filterOption;
- if (typeof searchOptionsProp === 'function') {
- if (filterOptionProp !== null) {
- Console.warn(
- 'searchOptions prop is being used, filterOption prop will be ignored'
- );
- }
- return searchOptionsProp;
- } else if (typeof filterOptionProp === 'function') {
- // use custom filter option
- return (value, options) =>
- options.filter(o => filterOptionProp(value, o));
- }
-
- const mapper =
- typeof filterOptionProp === 'string'
- ? Accessor.generateAccessor(filterOptionProp)
- : Accessor.IDENTITY_FN;
-
- return (value, options) =>
- fuzzy
- .filter(value, options, {extract: mapper})
- .map(res => options[res.index]);
- }
-
_hasHint() {
return this.state.searchResults.length > 0 || this._hasCustomValue();
}
@@ -492,25 +489,29 @@ export default class Typeahead extends Component {
>
{this._renderHiddenInput()}
{this.props.searchable ? (
- <InputBox>
- <TypeaheadInput
- ref={this.entry}
- type="text"
- disabled={this.props.disabled}
- {...this.props.inputProps}
- placeholder={this.props.placeholder}
- className={inputClassList}
- value={this.state.entryValue}
- onChange={this._onChange}
- onBlur={this._onBlur}
- />
- <InputIcon>
- <Search height="18px"/>
- </InputIcon>
- </InputBox>
+ <InputBox>
+ <TypeaheadInput
+ ref={this.entry}
+ type="text"
+ disabled={this.props.disabled}
+ {...this.props.inputProps}
+ placeholder={this.props.placeholder}
+ className={inputClassList}
+ value={this.state.entryValue}
+ onChange={this._onChange}
+ onBlur={this._onBlur}
+ />
+ <InputIcon>
+ <Search height="18px" />
+ </InputIcon>
+ </InputBox>
) : null}
{this._renderIncrementalSearchResults()}
</TypeaheadWrapper>
);
}
-};
+}
+
+polyfill(Typeahead);
+
+export default Typeahead;
diff --git a/src/components/common/range-slider.js b/src/components/common/range-slider.js
index 1a89b6364..b85f13966 100644
--- a/src/components/common/range-slider.js
+++ b/src/components/common/range-slider.js
@@ -19,9 +19,10 @@
// THE SOFTWARE.
import React, {Component, createRef} from 'react';
+import {polyfill} from 'react-lifecycles-compat';
+
import PropTypes from 'prop-types';
import styled from 'styled-components';
-
import RangePlot from './range-plot';
import Slider from 'components/common/slider/slider';
import {Input} from 'components/common/styled-components';
@@ -45,7 +46,7 @@ const RangeInputWrapper = styled.div`
justify-content: space-between;
`;
-export default class RangeSlider extends Component {
+class RangeSlider extends Component {
static propTypes = {
range: PropTypes.arrayOf(PropTypes.number).isRequired,
value0: PropTypes.number.isRequired,
@@ -72,18 +73,31 @@ export default class RangeSlider extends Component {
onChange: () => {}
};
- state = {value0: 0, value1: 1, width: 288};
+ static getDerivedStateFromProps(props, state) {
+ let update = null
+ const {value0, value1} = props;
+ if (props.value0 !== state.prevValue0 && !isNaN(value0)) {
+ update = {...(update || {}), value0, prevValue0: value0};
+ }
+ if (props.value1 !== state.prevValue1 && !isNaN(value1)) {
+ update = {...(update || {}), value1, prevValue1: value1};
+ }
+ return update;
+ }
+
+ state = {
+ value0: 0,
+ value1: 1,
+ prevValue0: 0,
+ prevValue1: 1,
+ width: 288
+ };
componentDidMount() {
- this._setValueFromProps(this.props);
this._resize();
}
- componentWillReceiveProps(nextProps) {
- this._setValueFromProps(nextProps);
- }
-
- componentDidUpdate() {
+ componentDidUpdate(prevProps, prevState) {
this._resize();
}
@@ -91,14 +105,6 @@ export default class RangeSlider extends Component {
inputValue0 = createRef();
inputValue1 = createRef();
- _setValueFromProps = props => {
- const {value0, value1} = props;
-
- if (!isNaN(value0) && !isNaN(value1)) {
- this.setState({value0, value1});
- }
- };
-
_isVal0InRange = val => {
const {value1, range} = this.props;
@@ -120,7 +126,6 @@ export default class RangeSlider extends Component {
_setRangeVal1 = val => {
const {value0, onChange} = this.props;
val = Number(val);
-
if (this._isVal1InRange(val)) {
onChange([value0, this._roundValToStep(val)]);
return true;
@@ -130,10 +135,10 @@ export default class RangeSlider extends Component {
_setRangeVal0 = val => {
const {value1, onChange} = this.props;
- val = Number(val);
+ const val0 = Number(val);
- if (this._isVal0InRange(val)) {
- onChange([this._roundValToStep(val), value1]);
+ if (this._isVal0InRange(val0)) {
+ onChange([this._roundValToStep(val0), value1]);
return true;
}
return false;
@@ -145,6 +150,9 @@ export default class RangeSlider extends Component {
this.setState({width});
}
}
+ _onChangeInput = (key, e) => {
+ this.setState({[key]: e.target.value});
+ };
_renderInput(key) {
const setRange = key === 'value0' ? this._setRangeVal0 : this._setRangeVal1;
@@ -155,6 +163,8 @@ export default class RangeSlider extends Component {
}
};
+ const onChange = this._onChangeInput.bind(this, key);
+
return (
<SliderInput
className="kg-range-slider__input"
@@ -163,9 +173,7 @@ export default class RangeSlider extends Component {
id={`slider-input-${key}`}
key={key}
value={this.state[key]}
- onChange={e => {
- this.setState({[key]: e.target.value});
- }}
+ onChange={onChange}
onKeyPress={e => {
if (e.key === 'Enter') {
update(e);
@@ -252,3 +260,7 @@ export default class RangeSlider extends Component {
);
}
}
+
+polyfill(RangeSlider);
+
+export default RangeSlider;
diff --git a/src/components/common/time-slider-marker.js b/src/components/common/time-slider-marker.js
index 00f0142cc..bb8f68124 100644
--- a/src/components/common/time-slider-marker.js
+++ b/src/components/common/time-slider-marker.js
@@ -73,9 +73,9 @@ export default class TimeSliderMarker extends Component {
this._updateAxis(this.scaleSelector(this.props));
}
- componentWillReceiveProps(nextProps) {
- if (this.scaleSelector(this.props) !== this.scaleSelector(nextProps)) {
- this._updateAxis(this.scaleSelector(nextProps));
+ componentDidUpdate(prevProps) {
+ if (this.scaleSelector(this.props) !== this.scaleSelector(prevProps)) {
+ this._updateAxis(this.scaleSelector(this.props));
}
}
diff --git a/src/components/container.js b/src/components/container.js
index 6e6e03b77..d9e889b87 100644
--- a/src/components/container.js
+++ b/src/components/container.js
@@ -22,7 +22,7 @@ import React, {Component} from 'react';
import {connect} from 'react-redux';
import memoize from 'lodash.memoize';
import {console as Console} from 'global/window';
-import {injector} from './injector';
+import {injector, typeCheckRecipe} from './injector';
import KeplerGlFactory from './kepler-gl';
import {forwardTo} from 'actions/action-wrapper';
@@ -31,6 +31,7 @@ import {
deleteEntry,
renameEntry
} from 'actions/identity-actions';
+import {notNullorUndefined} from 'utils/data-utils';
export const errorMsg = {
noState:
@@ -38,11 +39,13 @@ export const errorMsg = {
`You might forget to mount keplerGlReducer in your root reducer.` +
`If it is not mounted as state.keplerGl by default, you need to provide getState as a prop`,
- wrongType: type => `injectComponents takes an array of factories replacement pairs as input, ` +
+ wrongType: type =>
+ `injectComponents takes an array of factories replacement pairs as input, ` +
`${type} is provided`,
- wrongPairType: `injectComponents takes an array of factories replacement pairs as input, ` +
- `each pair be a array as [originalFactory, replacement]`
+ wrongPairType:
+ `injectComponents takes an array of factories replacement pairs as input, ` +
+ `each pair be a array as [originalFactory, replacement]`
};
ContainerFactory.deps = [KeplerGlFactory];
@@ -97,16 +100,34 @@ export function ContainerFactory(KeplerGl) {
this.getDispatch = memoize((id, dispatch) => forwardTo(id, dispatch));
}
- componentWillMount() {
- const {id, mint, mapboxApiAccessToken, mapboxApiUrl, mapStylesReplaceDefault} = this.props;
+ componentDidMount() {
+ const {
+ id,
+ mint,
+ mapboxApiAccessToken,
+ mapboxApiUrl,
+ mapStylesReplaceDefault
+ } = this.props;
// add a new entry to reducer
- this.props.dispatch(registerEntry({id, mint, mapboxApiAccessToken, mapboxApiUrl, mapStylesReplaceDefault}));
+ this.props.dispatch(
+ registerEntry({
+ id,
+ mint,
+ mapboxApiAccessToken,
+ mapboxApiUrl,
+ mapStylesReplaceDefault
+ })
+ );
}
- componentWillReceiveProps(nextProps) {
+ componentDidUpdate(prevProps) {
// check if id has changed, if true, copy state over
- if (nextProps.id && nextProps.id !== this.props.id) {
- this.props.dispatch(renameEntry(this.props.id, nextProps.id));
+ if (
+ notNullorUndefined(prevProps.id) &&
+ notNullorUndefined(this.props.id) &&
+ prevProps.id !== this.props.id
+ ) {
+ this.props.dispatch(renameEntry(prevProps.id, this.props.id));
}
}
@@ -139,42 +160,43 @@ export function ContainerFactory(KeplerGl) {
const mapStateToProps = (state, props) => ({state, ...props});
const dispatchToProps = dispatch => ({dispatch});
- return connect(mapStateToProps, dispatchToProps)(Container);
+ return connect(
+ mapStateToProps,
+ dispatchToProps
+ )(Container);
}
// entryPoint
function flattenDeps(allDeps, factory) {
const addToDeps = allDeps.concat([factory]);
- return Array.isArray(factory.deps) && factory.deps.length ?
- factory.deps.reduce((accu, dep) => flattenDeps(accu, dep), addToDeps) :
- addToDeps;
+ return Array.isArray(factory.deps) && factory.deps.length
+ ? factory.deps.reduce((accu, dep) => flattenDeps(accu, dep), addToDeps)
+ : addToDeps;
}
const allDependencies = flattenDeps([], ContainerFactory);
// provide all dependencies to appInjector
-export const appInjector = allDependencies
- .reduce((inj, factory) => inj.provide(factory, factory), injector());
+export const appInjector = allDependencies.reduce(
+ (inj, factory) => inj.provide(factory, factory),
+ injector()
+);
// Helper to inject custom components and return kepler.gl container
-export function injectComponents(recipes) {
- if (!Array.isArray(recipes)) {
- Console.error(errorMsg.wrongType(typeof(recipes)));
- return appInjector.get(ContainerFactory);
- }
-
+export function injectComponents(recipes = []) {
return recipes
.reduce((inj, recipe) => {
- if (!Array.isArray(recipes)) {
- Console.error(errorMsg.wrongPairType);
+ if (!typeCheckRecipe(recipe)) {
return inj;
}
// collect dependencies of custom factories, if there is any.
// Add them to the injector
const customDependencies = flattenDeps([], recipe[1]);
- inj = customDependencies
- .reduce((ij, factory) => ij.provide(factory, factory), inj);
+ inj = customDependencies.reduce(
+ (ij, factory) => ij.provide(factory, factory),
+ inj
+ );
return inj.provide(...recipe);
}, appInjector)
diff --git a/src/components/context.js b/src/components/context.js
new file mode 100644
index 000000000..171ea9f87
--- /dev/null
+++ b/src/components/context.js
@@ -0,0 +1,30 @@
+// Copyright (c) 2019 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 {createContext} from 'react';
+
+const identity = state => state;
+// New Context API only supported after 16.3
+const KeplerGlContext = createContext({
+ selector: identity,
+ id: 'map'
+});
+
+export default KeplerGlContext;
diff --git a/src/components/injector.js b/src/components/injector.js
index e8d8dfcb7..4b5cce311 100644
--- a/src/components/injector.js
+++ b/src/components/injector.js
@@ -21,33 +21,50 @@
import React from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
-import PropTypes from 'prop-types';
import {console as Console} from 'global/window';
+import KeplerGlContext from 'components/context';
const MissingComp = () => <div />;
+
export const errorMsg = {
noDep: (fac, parent) =>
`${fac.name} is required as a dependency of ${parent.name}, ` +
- `but is not provided to injectComponents. It will not be rendered`,
- notFunc: '`factory and its replacement should be a function`'
+ `but is not provided to injectComponents. It will not be rendered.`,
+ notFunc: '`factory and its replacement should be a function`',
+ incompatibleDeps: (
+ fac,
+ given
+ ) => `${fac.name} is expecting ${fac.length} arguments, but ${given} is given,
+ You are likely forget to declare ${fac.name}.deps = []`
};
export function injector(map = new Map()) {
const cache = new Map(); // map<factory, factory -> ?>
const get = (fac, parent) => {
const factory = map.get(fac);
-
// factory is not injected
if (!factory) {
Console.error(errorMsg.noDep(fac, parent));
return MissingComp;
}
- const instances =
- cache.get(factory) ||
- factory(
- ...(factory.deps ? factory.deps.map(dep => get(dep, factory)) : [])
+ // check if custom factory deps is declared
+ const depsLength = factory.deps ? factory.deps.length : 0;
+ let instances;
+ if (factory.length !== depsLength) {
+ Console.error(errorMsg.incompatibleDeps(factory, depsLength));
+
+ const MissingDeps = () => (
+ <div className="factory-missing-deps">{factory.name} is missing dependencies</div>
);
+ instances = MissingDeps;
+ } else {
+ instances =
+ cache.get(factory) ||
+ factory(
+ ...(factory.deps ? factory.deps.map(dep => get(dep, factory)) : [])
+ );
+ }
cache.set(fac, instances);
return instances;
@@ -57,47 +74,69 @@ export function injector(map = new Map()) {
// it will be override: 2018-02-05
return {
provide: (factory, replacement) => {
- if (typeof factory !== 'function') {
- Console.error('Error injecting factory: ', factory);
- Console.error(errorMsg.notFunc);
- return injector(map);
- } else if (typeof replacement !== 'function') {
- Console.error('Error injecting replacement for: ', factory);
- Console.error(errorMsg.notFunc);
+ if (!typeCheckRecipe([factory, replacement])) {
return injector(map);
}
-
- return injector((new Map(map)).set(factory, replacement));
+ return injector(new Map(map).set(factory, replacement));
},
get
};
}
-const identity = state => (state);
+export function typeCheckRecipe(recipe) {
+ if (!Array.isArray(recipe) || recipe.length < 2) {
+ Console.error(errorMsg.wrongPairType);
+ return false;
+ }
+
+ const [factory, replacement] = recipe;
+ if (typeof factory !== 'function') {
+ Console.error('Error injecting factory: ', factory);
+ Console.error(errorMsg.notFunc);
+ return false;
+ } else if (typeof replacement !== 'function') {
+ Console.error('Error injecting replacement for: ', factory);
+ Console.error(errorMsg.notFunc);
+ return false;
+ }
+
+ return true;
+}
+
+const identity = state => state;
// Helper to add reducer state to custom component
-export function withState(lenses, mapStateToProps = identity, actions = {}) {
- return (Component) => {
- const WrappedComponent = ({state, ...props}, {selector, id}) => (
- <Component
- {...lenses.reduce(
- (totalState, lens) => ({
- ...totalState,
- ...lens(selector(state))
- }),
- props
+export function withState(
+ lenses = [],
+ mapStateToProps = identity,
+ actions = {}
+) {
+ return Component => {
+ const WrappedComponent = ({state, ...props}) => (
+ <KeplerGlContext.Consumer>
+ {context => (
+ <Component
+ {...lenses.reduce(
+ (totalState, lens) => ({
+ ...totalState,
+ ...lens(context.selector(state))
+ }),
+ props
+ )}
+ />
)}
- />
+ </KeplerGlContext.Consumer>
);
- WrappedComponent.contextTypes = {
- selector: PropTypes.func,
- id: PropTypes.string
- };
+
return connect(
state => ({...mapStateToProps(state), state}),
- dispatch => Object.keys(actions).reduce((accu, key) => ({
- ...accu,
- [key]: bindActionCreators(actions[key], dispatch)
- }), {})
+ dispatch =>
+ Object.keys(actions).reduce(
+ (accu, key) => ({
+ ...accu,
+ [key]: bindActionCreators(actions[key], dispatch)
+ }),
+ {}
+ )
)(WrappedComponent);
- }
+ };
}
diff --git a/src/components/kepler-gl.js b/src/components/kepler-gl.js
index cbefbd65f..23578f6ef 100644
--- a/src/components/kepler-gl.js
+++ b/src/components/kepler-gl.js
@@ -113,22 +113,22 @@ function KeplerGlFactory(
theme: {}
};
- componentWillMount() {
+ componentDidMount() {
this._validateMapboxToken();
this._loadMapStyle(this.props.mapStyles);
this._handleResize(this.props);
}
- componentWillReceiveProps(nextProps) {
+ componentDidUpdate(prevProps) {
if (
// if dimension props has changed
- this.props.height !== nextProps.height ||
- this.props.width !== nextProps.width ||
+ this.props.height !== prevProps.height ||
+ this.props.width !== prevProps.width ||
// react-map-gl will dispatch updateViewport after this._handleResize is called
// here we check if this.props.mapState.height is sync with props.height
- nextProps.height !== this.props.mapState.height
+ this.props.height !== this.props.mapState.height
) {
- this._handleResize(nextProps);
+ this._handleResize(this.props);
}
}
diff --git a/src/components/modals/add-map-style-modal.js b/src/components/modals/add-map-style-modal.js
index 1c8d3e104..80566163f 100644
--- a/src/components/modals/add-map-style-modal.js
+++ b/src/components/modals/add-map-style-modal.js
@@ -19,6 +19,7 @@
// THE SOFTWARE.
import React, {Component} from 'react';
+import {polyfill} from 'react-lifecycles-compat';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import styled from 'styled-components';
@@ -139,185 +140,194 @@ const InlineLink = styled.a`
}
`;
-class AddMapStyleModal extends Component {
- static propTypes = {
- inputMapStyle: PropTypes.func.isRequired,
- inputStyle: PropTypes.object.isRequired,
- loadCustomMapStyle: PropTypes.func.isRequired,
- mapboxApiAccessToken: PropTypes.string.isRequired,
- mapboxApiUrl: PropTypes.string.isRequired,
- mapState: PropTypes.object.isRequired
- };
-
- state = {
- reRenderKey: 0
- };
-
- componentWillReceiveProps(nextProps) {
- if (
- this.props.inputStyle.accessToken !== nextProps.inputStyle.accessToken
- ) {
- // toke has changed
- // ReactMapGl doesn't re-create map when token has changed
- // here we force the map to update
- this.setState({
- reRenderKey: this.state.reRenderKey + 1
- });
+function AddMapStyleModalFactory() {
+ class AddMapStyleModal extends Component {
+ static propTypes = {
+ inputMapStyle: PropTypes.func.isRequired,
+ inputStyle: PropTypes.object.isRequired,
+ loadCustomMapStyle: PropTypes.func.isRequired,
+ mapboxApiAccessToken: PropTypes.string.isRequired,
+ mapboxApiUrl: PropTypes.string.isRequired,
+ mapState: PropTypes.object.isRequired
+ };
+
+ state = {
+ reRenderKey: 0,
+ previousToken: null
+ };
+
+ static getDerivedStateFromProps(props, state) {
+ if (
+ props.inputStyle &&
+ props.inputStyle.accessToken &&
+ props.inputStyle.accessToken !== state.previousToken
+ ) {
+ // toke has changed
+ // ReactMapGl doesn't re-create map when token has changed
+ // here we force the map to update
+
+ return {
+ reRenderKey: state.reRenderKey + 1,
+ previousToken: props.inputStyle.accessToken
+ };
+ }
+
+ return null;
}
- }
- componentDidUpdate(prevProps) {
- const map = this.mapRef && this.mapRef.getMap();
- if (map && this._map !== map) {
- this._map = map;
+ componentDidUpdate() {
+ const map = this.mapRef && this.mapRef.getMap();
+ if (map && this._map !== map) {
+ this._map = map;
- map.on('style.load', () => {
- const style = map.getStyle();
- this.loadMapStyleJson(style);
- });
+ map.on('style.load', () => {
+ const style = map.getStyle();
+ this.loadMapStyleJson(style);
+ });
- map.on('error', () => {
- this.loadMapStyleError();
- });
+ map.on('error', () => {
+ this.loadMaoStyleError();
+ });
+ }
}
- }
- loadMapStyleJson = style => {
- this.props.loadCustomMapStyle({style, error: false});
- };
-
- loadMapStyleError = () => {
- this.props.loadCustomMapStyle({error: true});
- };
-
- render() {
- const {
- inputStyle,
- mapState,
- mapboxApiUrl
- } = this.props;
-
- const mapboxApiAccessToken = inputStyle.accessToken || this.props.mapboxApiAccessToken;
- const mapProps = {
- ...mapState,
- mapboxApiUrl,
- mapboxApiAccessToken,
- preserveDrawingBuffer: true,
- transformRequest
+ loadMapStyleJson = style => {
+ this.props.loadCustomMapStyle({style, error: false});
};
- return (
- <div className="add-map-style-modal">
- <StyledModalContent>
- <InstructionPanel>
- <StyledModalSection className="modal-section">
- <div className="modal-section-title">
- 1. Publish your style at mapbox or provide access token
- </div>
- <div className="modal-section-subtitle">
- You can create your own map style at
- <InlineLink
- target="_blank"
- href="https://www.mapbox.com/studio/styles/"
- >
- {' '}
- mapbox
- </InlineLink>{' '}
- and
- <InlineLink
- target="_blank"
- href="https://www.mapbox.com/help/studio-manual-publish/"
- >
- {' '}
- publish
- </InlineLink>{' '}
- it.
- </div>
- <div className="modal-section-subtitle">
- To use private style, paste your
- <InlineLink
- target="_blank"
- href="https://www.mapbox.com/help/how-access-tokens-work/"
- >
- {' '}
- access token
- </InlineLink>{' '}
- here. *kepler.gl is a client-side application, data stays in
- your browser..
- </div>
- <InputLight
- type="text"
- value={inputStyle.accessToken || ''}
- onChange={({target: {value}}) =>
- this.props.inputMapStyle({accessToken: value})
- }
- placeholder="e.g. pk.abcdefg.xxxxxx"
- />
- </StyledModalSection>
- <StyledModalSection className="modal-section">
- <div className="modal-section-title">2. Paste style url</div>
- <div className="modal-section-subtitle">
- What is a
- <InlineLink
- target="_blank"
- href="https://www.mapbox.com/help/studio-manual-publish/#style-url"
- >
- {' '}
- style URL
- </InlineLink>
+ loadMapStyleError = () => {
+ this.props.loadCustomMapStyle({error: true});
+ };
+
+ render() {
+ const {inputStyle, mapState, mapboxApiUrl} = this.props;
+
+ const mapboxApiAccessToken =
+ inputStyle.accessToken || this.props.mapboxApiAccessToken;
+ const mapProps = {
+ ...mapState,
+ mapboxApiUrl,
+ mapboxApiAccessToken,
+ preserveDrawingBuffer: true,
+ transformRequest
+ };
+
+ return (
+ <div className="add-map-style-modal">
+ <StyledModalContent>
+ <InstructionPanel>
+ <StyledModalSection className="modal-section">
+ <div className="modal-section-title">
+ 1. Publish your style at mapbox or provide access token
+ </div>
+ <div className="modal-section-subtitle">
+ You can create your own map style at
+ <InlineLink
+ target="_blank"
+ href="https://www.mapbox.com/studio/styles/"
+ >
+ {' '}
+ mapbox
+ </InlineLink>{' '}
+ and
+ <InlineLink
+ target="_blank"
+ href="https://www.mapbox.com/help/studio-manual-publish/"
+ >
+ {' '}
+ publish
+ </InlineLink>{' '}
+ it.
+ </div>
+ <div className="modal-section-subtitle">
+ To use private style, paste your
+ <InlineLink
+ target="_blank"
+ href="https://www.mapbox.com/help/how-access-tokens-work/"
+ >
+ {' '}
+ access token
+ </InlineLink>{' '}
+ here. *kepler.gl is a client-side application, data stays in
+ your browser..
+ </div>
+ <InputLight
+ type="text"
+ value={inputStyle.accessToken || ''}
+ onChange={({target: {value}}) =>
+ this.props.inputMapStyle({accessToken: value})
+ }
+ placeholder="e.g. pk.abcdefg.xxxxxx"
+ />
+ </StyledModalSection>
+ <StyledModalSection className="modal-section">
+ <div className="modal-section-title">2. Paste style url</div>
+ <div className="modal-section-subtitle">
+ What is a
+ <InlineLink
+ target="_blank"
+ href="https://www.mapbox.com/help/studio-manual-publish/#style-url"
+ >
+ {' '}
+ style URL
+ </InlineLink>
+ </div>
+ <InputLight
+ type="text"
+ value={inputStyle.url || ''}
+ onChange={({target: {value}}) =>
+ this.props.inputMapStyle({url: value})
+ }
+ placeholder="e.g. mapbox://styles/uberdataviz/abcdefghijklmnopq"
+ />
+ </StyledModalSection>
+ <StyledModalSection className="modal-section">
+ <div className="modal-section-title">3. Name your style</div>
+ <InputLight
+ type="text"
+ value={inputStyle.label || ''}
+ onChange={({target: {value}}) =>
+ this.props.inputMapStyle({label: value})
+ }
+ />
+ </StyledModalSection>
+ </InstructionPanel>
+ <PreviewMap>
+ <div
+ className={classnames('preview-title', {
+ error: inputStyle.error
+ })}
+ >
+ {inputStyle.error
+ ? ErrorMsg.styleError
+ : (inputStyle.style && inputStyle.style.name) || ''}
</div>
- <InputLight
- type="text"
- value={inputStyle.url || ''}
- onChange={({target: {value}}) =>
- this.props.inputMapStyle({url: value})
- }
- placeholder="e.g. mapbox://styles/uberdataviz/abcdefghijklmnopq"
- />
- </StyledModalSection>
- <StyledModalSection className="modal-section">
- <div className="modal-section-title">3. Name your style</div>
- <InputLight
- type="text"
- value={inputStyle.label || ''}
- onChange={({target: {value}}) =>
- this.props.inputMapStyle({label: value})
- }
- />
- </StyledModalSection>
- </InstructionPanel>
- <PreviewMap>
- <div
- className={classnames('preview-title', {error: inputStyle.error})}
- >
- {inputStyle.error
- ? ErrorMsg.styleError
- : (inputStyle.style && inputStyle.style.name) || ''}
- </div>
- <StyledPreviewImage className="preview-image">
- {!inputStyle.isValid ? (
- <div className="preview-image-spinner" />
- ) : (
- <StyledMapContainer>
- <MapboxGLMap
- {...mapProps}
- ref={el => {
- this.mapRef = el;
- }}
- key={this.state.reRenderKey}
- width={MapW}
- height={MapH}
- mapStyle={inputStyle.url}
- />
- </StyledMapContainer>
- )}
- </StyledPreviewImage>
- </PreviewMap>
- </StyledModalContent>
- </div>
- );
+ <StyledPreviewImage className="preview-image">
+ {!inputStyle.isValid ? (
+ <div className="preview-image-spinner" />
+ ) : (
+ <StyledMapContainer>
+ <MapboxGLMap
+ {...mapProps}
+ ref={el => {
+ this.mapRef = el;
+ }}
+ key={this.state.reRenderKey}
+ width={MapW}
+ height={MapH}
+ mapStyle={inputStyle.url}
+ />
+ </StyledMapContainer>
+ )}
+ </StyledPreviewImage>
+ </PreviewMap>
+ </StyledModalContent>
+ </div>
+ );
+ }
}
+
+ return polyfill(AddMapStyleModal);
}
-const AddMapStyleModalFactory = () => AddMapStyleModal;
export default AddMapStyleModalFactory;
diff --git a/src/components/plot-container.js b/src/components/plot-container.js
index 424a31545..40fa69939 100644
--- a/src/components/plot-container.js
+++ b/src/components/plot-container.js
@@ -62,17 +62,17 @@ export default function PlotContainerFactory(MapContainer) {
this._onMapRender = debounce(this._onMapRender, 500);
}
- componentWillMount() {
+ componentDidMount() {
this.props.startExportingImage();
}
- componentWillReceiveProps(newProps) {
+ componentDidUpdate(prevProps) {
// re-fetch the new screenshot only when ratio legend or resolution changes
const checks = ['ratio', 'resolution', 'legend'];
const shouldRetrieveScreenshot = checks.some(
item =>
this.props.exportImageSetting[item] !==
- newProps.exportImageSetting[item]
+ prevProps.exportImageSetting[item]
);
if (shouldRetrieveScreenshot) {
this._retrieveNewScreenshot();
diff --git a/src/components/side-panel/layer-panel/layer-config-group.js b/src/components/side-panel/layer-panel/layer-config-group.js
index ed12750be..aa7313f28 100644
--- a/src/components/side-panel/layer-panel/layer-config-group.js
+++ b/src/components/side-panel/layer-panel/layer-config-group.js
@@ -19,6 +19,7 @@
// THE SOFTWARE.
import React, {Component} from 'react';
+import {polyfill} from 'react-lifecycles-compat';
import styled from 'styled-components';
import classnames from 'classnames';
import Switch from 'components/common/switch';
@@ -113,7 +114,7 @@ const ConfigGroupContent = styled.div`
}
`;
-export default class LayerConfigGroup extends Component {
+class LayerConfigGroup extends Component {
static defaultProps = {
collapsible: false,
expanded: false,
@@ -121,24 +122,18 @@ export default class LayerConfigGroup extends Component {
description: null
};
- state = {
- collapsed: true
- };
-
- componentDidMount() {
- this._setCollapseState(this.props.expanded);
- }
+ static getDerivedStateFromProps(props, state) {
+ // invoked after a component is instantiated as well as before it is re-rendered
+ if (props.expanded && state.collapsed) {
+ return {collapsed: false};
+ }
- componentWillReceiveProps(nextProps) {
- this._setCollapseState(nextProps.expanded);
+ return null;
}
- _setCollapseState(expanded) {
- // if props,expanded, and state collapsed, set collapsed to be false
- if (expanded && this.state.collapsed) {
- this.setState({collapsed: false});
- }
- }
+ state = {
+ collapsed: true
+ };
render() {
const {
@@ -194,3 +189,7 @@ export default class LayerConfigGroup extends Component {
);
}
}
+
+polyfill(LayerConfigGroup);
+
+export default LayerConfigGroup;
diff --git a/src/components/side-panel/side-bar.js b/src/components/side-panel/side-bar.js
index e45cd04be..9d766518d 100644
--- a/src/components/side-panel/side-bar.js
+++ b/src/components/side-panel/side-bar.js
@@ -92,12 +92,6 @@ SidebarFactory.deps = [CollapseButtonFactory];
function SidebarFactory(CollapseButton) {
return class SideBar extends Component {
- static defaultProps = {
- width: 300,
- minifiedWidth: 0,
- isOpen: true,
- onOpenOrClose: function noop() {}
- };
static propTypes = {
width: PropTypes.number,
@@ -106,6 +100,13 @@ function SidebarFactory(CollapseButton) {
onOpenOrClose: PropTypes.func
};
+ static defaultProps = {
+ width: 300,
+ minifiedWidth: 0,
+ isOpen: true,
+ onOpenOrClose: function noop() {}
+ };
+
_onOpenOrClose = () => {
this.props.onOpenOrClose({isOpen: !this.props.isOpen});
};
diff --git a/src/connect/with-local-selector.js b/src/connect/with-local-selector.js
index 9a9884d31..6b1dcc070 100644
--- a/src/connect/with-local-selector.js
+++ b/src/connect/with-local-selector.js
@@ -19,19 +19,14 @@
// THE SOFTWARE.
import React, {Component} from 'react';
-import PropTypes from 'prop-types';
+import {createSelector} from 'reselect';
+import KeplerGlContext from 'components/context';
const identity = state => state;
const mergeSelectors = (parentSelector, childSelector) => state =>
childSelector(parentSelector(state));
-const computeSelector = (props, ctx) =>
- mergeSelectors(
- ctx.selector ? ctx.selector : identity,
- props.selector ? props.selector : identity
- );
-
// store the parent selector in the parent context
// and return the parent component
// when a selector is passed to a container component,
@@ -39,40 +34,34 @@ const computeSelector = (props, ctx) =>
// as well as prop to the given component
const withLocalSelector = ParentComponent => {
class WithConnectSelector extends Component {
- constructor(props, ctx) {
- super(props, ctx);
-
- this.selector = computeSelector(props, ctx);
- this.id = props.id;
- }
-
- getChildContext() {
- return {
- selector: this.selector,
- id: this.id
- };
- }
+ static contextType = KeplerGlContext;
- componentWillReceiveProps(nextProps, nextContext) {
- this.selector = computeSelector(nextProps, nextContext);
- this.id = nextProps.id;
- }
+ selectorFromContext = (_, ctx) => ctx.selector ? ctx.selector : identity;
+ selectorFromProps = (props, _) => props.selector ? props.selector : identity;
+ idFromProps = (props, _) => props.id;
+ computedSelector = createSelector(
+ this.selectorFromContext,
+ this.selectorFromProps,
+ (ctx, props) => mergeSelectors(ctx, props)
+ );
+ contextSelector = createSelector(
+ this.computedSelector,
+ this.idFromProps,
+ (selector, id) => ({
+ selector, id
+ })
+ )
render() {
- return <ParentComponent {...this.props} selector={this.selector} />;
+ const computedContext = this.contextSelector(this.props, this.context);
+ return (
+ <KeplerGlContext.Provider value={computedContext}>
+ <ParentComponent {...this.props} selector={computedContext.selector} />;
+ </KeplerGlContext.Provider>
+ );
}
}
- WithConnectSelector.contextTypes = {
- selector: PropTypes.func,
- id: PropTypes.string
- };
-
- WithConnectSelector.childContextTypes = {
- selector: PropTypes.func,
- id: PropTypes.string
- };
-
return WithConnectSelector;
};
diff --git a/src/reducers/vis-state-updaters.js b/src/reducers/vis-state-updaters.js
index f8d13ce45..66579e100 100644
--- a/src/reducers/vis-state-updaters.js
+++ b/src/reducers/vis-state-updaters.js
@@ -434,7 +434,6 @@ export function layerVisConfigChangeUpdater(state, action) {
const {oldLayer} = action;
const idx = state.layers.findIndex(l => l.id === oldLayer.id);
const props = Object.keys(action.newVisConfig);
-
const newVisConfig = {
...oldLayer.config.visConfig,
...action.newVisConfig
diff --git a/test/browser/components/common/file-uploader-test.js b/test/browser/components/common/file-uploader-test.js
new file mode 100644
index 000000000..8490fe4b3
--- /dev/null
+++ b/test/browser/components/common/file-uploader-test.js
@@ -0,0 +1,218 @@
+// Copyright (c) 2019 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 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 FileDrop from 'components/common/file-uploader/file-drop';
+import UploadButton from 'components/common/file-uploader/upload-button';
+
+test('Components -> FileUploader.render', t => {
+ let wrapper;
+
+ t.doesNotThrow(() => {
+ wrapper = mountWithTheme(<FileUplad />);
+ }, 'Show not fail without data');
+
+ t.equal(wrapper.find(FileDrop).length, 1, 'should render FileUploader');
+ t.equal(wrapper.find(UploadButton).length, 1, 'should render UploadButton');
+
+ t.end();
+});
+
+test('Components -> FileUpload.onDrop', t => {
+ const mockFiles = [{type: 'text/csv', name: 'tst-file.csv'}];
+ const onFileUpload = sinon.spy(arg => {
+ t.deepEqual(arg, mockFiles, 'should call onFileUpload with files');
+ });
+ const stopPropagation = sinon.spy();
+ const wrapper = mountWithTheme(<FileUplad onFileUpload={onFileUpload} />);
+
+ t.equal(wrapper.find(FileDrop).length, 1, 'should render FileUploader');
+
+ const FileDropDiv = wrapper.find('.file-uploader__file-drop').at(0);
+ // mock file drop event
+ const mockEvent = {
+ stopPropagation,
+ dataTransfer: {
+ types: ['Files'],
+ files: mockFiles
+ }
+ };
+
+ FileDropDiv.simulate('drop', mockEvent);
+
+ t.ok(onFileUpload.called, 'onFileUpload should get called');
+ t.ok(stopPropagation.called, 'stopPropagation should get called');
+ const files = wrapper.state().files;
+
+ t.deepEqual(files, mockFiles, 'should set files to state');
+ const uploadMsg = wrapper.find('.file-uploader__message');
+
+ t.end();
+});
+
+test('Components -> FileUpload.onDrop -> render loading msg', t => {
+ const mockFiles = [{type: 'text/csv', name: 'tst-file.csv'}];
+ const onFileUpload = sinon.spy(arg => {
+ t.deepEqual(arg, mockFiles, 'should call onFileUpload with files');
+ });
+
+ const wrapper = mountWithTheme(
+ <FileUplad onFileUpload={onFileUpload} fileLoading />
+ );
+
+ const FileDropDiv = wrapper.find('.file-uploader__file-drop').at(0);
+ // mock file drop event
+ const mockEvent = {
+ stopPropagation: () => {},
+ dataTransfer: {
+ types: ['Files'],
+ files: mockFiles
+ }
+ };
+
+ FileDropDiv.simulate('drop', mockEvent);
+
+ t.ok(onFileUpload.called, 'onFileUpload should get called');
+ const uploadMsg = wrapper
+ .find('.file-uploader__message')
+ .at(0)
+ .html();
+
+ t.ok(uploadMsg.includes('tst-file.csv', 'should render upload file msg'));
+
+ t.end();
+});
+
+test('Components -> FileUpload.onDrop -> render error msg', t => {
+ const mockFiles = [{type: 'png', name: 'tst-file.png'}];
+ const onFileUpload = sinon.spy(arg => {
+ t.deepEqual(arg, mockFiles, 'should call onFileUpload with files');
+ });
+
+ const wrapper = mountWithTheme(<FileUplad onFileUpload={onFileUpload} />);
+
+ const FileDropDiv = wrapper.find('.file-uploader__file-drop').at(0);
+ // mock file drop event
+ const mockEvent = {
+ stopPropagation: () => {},
+ dataTransfer: {
+ types: ['Files'],
+ files: mockFiles
+ }
+ };
+
+ FileDropDiv.simulate('drop', mockEvent);
+
+ t.ok(onFileUpload.notCalled, 'onFileUpload should not get called');
+ t.ok(wrapper.find(WarningMsg), 'should render WarningMsg');
+
+ const errorFiles = wrapper.state().errorFiles;
+ t.deepEqual(errorFiles, ['tst-file.png'], 'should save files to errorFiles');
+
+ t.end();
+});
+
+test('Components -> FileUpload.dragOver', t => {
+ const mockFiles = [{type: 'text/csv', name: 'tst-file.csv'}];
+ const onFileUpload = sinon.spy(arg => {
+ t.deepEqual(arg, mockFiles, 'should call onFileUpload with files');
+ });
+ const wrapper = mountWithTheme(<FileUplad onFileUpload={onFileUpload} />);
+
+ t.equal(wrapper.find(FileDrop).length, 1, 'should render FileUploader');
+
+ const FileDropDiv = wrapper.find('.file-uploader__file-drop').at(0);
+ // mock file drop event
+ const mockEvent = {
+ dataTransfer: {
+ types: ['Files'],
+ files: mockFiles
+ }
+ };
+
+ FileDropDiv.simulate('dragover', mockEvent);
+ const dragOver = wrapper.state().dragOver;
+ t.ok(dragOver, 'dragOver should be set to true');
+ t.end();
+});
+
+test('Components -> FileUpload.dragLeave', t => {
+ const mockFiles = [{type: 'text/csv', name: 'tst-file.csv'}];
+ const onFileUpload = sinon.spy(arg => {
+ t.deepEqual(arg, mockFiles, 'should call onFileUpload with files');
+ });
+ const wrapper = mountWithTheme(<FileUplad onFileUpload={onFileUpload} />);
+
+ t.equal(wrapper.find(FileDrop).length, 1, 'should render FileUploader');
+
+ const FileDropDiv = wrapper.find('.file-uploader__file-drop').at(0);
+ // mock file drop event
+ const mockEvent = {
+ dataTransfer: {
+ types: ['Files'],
+ files: mockFiles
+ }
+ };
+
+ FileDropDiv.simulate('dragleave', mockEvent);
+ const dragOver = wrapper.state().dragOver;
+ t.notOk(dragOver, 'dragOver should be set to false');
+ t.end();
+});
+
+test('Components -> UploadButton fileInput', t => {
+ const mockFiles = [{type: 'text/csv', name: 'tst-file.csv'}];
+ const onFileUpload = sinon.spy(arg => {
+ t.deepEqual(arg, mockFiles, 'should call onFileUpload with files');
+ });
+ const wrapper = mountWithTheme(<FileUplad onFileUpload={onFileUpload} />);
+ const uploadButton = wrapper.find(UploadButton);
+ t.equal(uploadButton.length, 1, 'should render UploadButton');
+ const input = uploadButton.find('input');
+
+ // simulate click
+ uploadButton.find('.file-upload__upload-button-span').simulate('click');
+
+ // mock file drop event
+ const mockEvent = {
+ target: {
+ files: mockFiles
+ }
+ };
+
+ // change iwthout file?
+ input.simulate('change', {target: {files: null}});
+ t.ok(onFileUpload.notCalled, 'onFileUpload should not get called');
+
+ input.simulate('change', mockEvent);
+ t.ok(onFileUpload.called, 'onFileUpload should get called');
+ const files = wrapper.state().files;
+
+ t.deepEqual(files, mockFiles, 'should set files to state');
+
+ t.end();
+});
\ No newline at end of file
diff --git a/test/browser/components/common/index.js b/test/browser/components/common/index.js
new file mode 100644
index 000000000..81f627f5c
--- /dev/null
+++ b/test/browser/components/common/index.js
@@ -0,0 +1,21 @@
+// Copyright (c) 2019 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 './file-uploader-test';
diff --git a/test/browser/components/index.js b/test/browser/components/index.js
index 6260a580e..d4c12ec73 100644
--- a/test/browser/components/index.js
+++ b/test/browser/components/index.js
@@ -25,8 +25,10 @@ configure({adapter: new Adapter()});
import './injector-test';
import './container-test';
-import './data-table-modal-test';
-import './notifications';
import './kepler-gl-test';
+
+import './modals';
+import './notifications';
import './map';
import './side-panel';
+import './common';
diff --git a/test/browser/components/injector-test.js b/test/browser/components/injector-test.js
index 9c6f0222b..79a8a7000 100644
--- a/test/browser/components/injector-test.js
+++ b/test/browser/components/injector-test.js
@@ -57,17 +57,20 @@ test('Components -> injector -> injectComponents', t => {
);
// test if custom header is rendered
- t.ok(wrapper.find('.my-test-header').length, 'should render custome header');
+ t.ok(wrapper.find('.my-test-header').length, 'should render custom header');
t.end();
});
test('Components -> injector -> missing deps', t => {
const spy = sinon.spy(Console, 'error');
- const myCustomNameFactory = () => () => <div className="my-test-header-name">name</div>;
+ const myCustomNameFactory = () => () => (
+ <div className="my-test-header-name">name</div>
+ );
const myCustomHeaderFactory = Name => () => (
<div className="my-test-header-1">
- <Name />smoothie
+ <Name />
+ smoothie
</div>
);
myCustomHeaderFactory.deps = [myCustomNameFactory];
@@ -85,11 +88,14 @@ test('Components -> injector -> missing deps', t => {
const wrapper = mount(
<Provider store={store}>
- <KeplerGl id="foo" mapboxApiAccessToken="smoothie_and_milkshake"/>
+ <KeplerGl id="foo" mapboxApiAccessToken="smoothie_and_milkshake" />
</Provider>
);
- t.ok(spy.notCalled, 'Should automatically add custom deps and not call console.error');
+ t.ok(
+ spy.notCalled,
+ 'Should automatically add custom deps and not call console.error'
+ );
t.ok(
wrapper.find('.my-test-header-name').length,
@@ -105,13 +111,12 @@ test('Components -> injector -> wrong factory type', t => {
// const spy = sinon.spy(Console, 'error');
const myCustomHeaderFactory = Name => () => (
<div className="my-test-header-2">
- <Name />smoothie
+ <Name />
+ smoothie
</div>
);
- const KeplerGl = injectComponents([
- [undefined, myCustomHeaderFactory]
- ]);
+ const KeplerGl = injectComponents([[undefined, myCustomHeaderFactory]]);
// assume instance reducer is already mounted
const store = mockStore({
@@ -122,7 +127,7 @@ test('Components -> injector -> wrong factory type', t => {
const wrapper = mount(
<Provider store={store}>
- <KeplerGl id="foo" mapboxApiAccessToken="smoothie_and_milkshake"/>
+ <KeplerGl id="foo" mapboxApiAccessToken="smoothie_and_milkshake" />
</Provider>
);
@@ -130,24 +135,106 @@ test('Components -> injector -> wrong factory type', t => {
t.equal(
spy.getCall(0).args[0],
'Error injecting factory: ',
- 'should warn when cannot find kepler.gl state'
+ 'should warn when default factory is not provided'
);
// test if custom header is rendered
- t.ok(wrapper.find('.side-panel__panel-header').length, 'should render default header');
+ t.ok(
+ wrapper.find('.side-panel__panel-header').length,
+ 'should render default header'
+ );
+
+ spy.restore();
+ t.end();
+});
+
+test('Components -> injector -> wrong replacement type', t => {
+ const spy = sinon.spy(Console, 'error');
+ // const spy = sinon.spy(Console, 'error');
+
+ const KeplerGl = injectComponents([[PanelHeaderFactory, undefined]]);
+
+ // assume instance reducer is already mounted
+ const store = mockStore({
+ keplerGl: {
+ foo: initialCoreState
+ }
+ });
+
+ const wrapper = mount(
+ <Provider store={store}>
+ <KeplerGl id="foo" mapboxApiAccessToken="smoothie_and_milkshake" />
+ </Provider>
+ );
+
+ t.ok(spy.calledTwice, 'should call console.error twice');
+ t.equal(
+ spy.getCall(0).args[0],
+ 'Error injecting replacement for: ',
+ 'should warn when replace factory is not provided'
+ );
+
+ // test if custom header is rendered
+ t.ok(
+ wrapper.find('.side-panel__panel-header').length,
+ 'should render default header'
+ );
+
+ spy.restore();
+ t.end();
+});
+
+test('Components -> injector -> missing dep', t => {
+ const spy = sinon.spy(Console, 'error');
+
+ const myCustomHeaderFactory = Missing => () => <Missing />;
+
+ const KeplerGl = injectComponents([
+ [PanelHeaderFactory, myCustomHeaderFactory]
+ ]);
+
+ // assume instance reducer is already mounted
+ const store = mockStore({
+ keplerGl: {
+ foo: initialCoreState
+ }
+ });
+
+ const wrapper = mount(
+ <Provider store={store}>
+ <KeplerGl id="foo" mapboxApiAccessToken="smoothie_and_milkshake" />
+ </Provider>
+ );
+
+ t.ok(spy.calledOnce, 'should call Console.error twice');
+ t.equal(
+ spy.getCall(0).args[0],
+ `${errorMsg.incompatibleDeps(myCustomHeaderFactory, 0)}`,
+ 'should warn when deps of custom factory is not provided'
+ );
+
+ t.ok(
+ wrapper.find('.factory-missing-deps'),
+ 'should render missing deps component'
+ );
+ t.equal(
+ wrapper.find('.factory-missing-deps').html(),
+ '<div class="factory-missing-deps">myCustomHeaderFactory is missing dependencies</div>',
+ 'should render missing deps component'
+ );
spy.restore();
t.end();
});
-test('Components -> injector -> withState', t => {
+test('Components -> injector -> withState.lens', t => {
const CustomHeader = ({visState}) => (
<div className="my-test-header-3">smoothie</div>
);
const myCustomHeaderFactory = () =>
- withState(
- [visStateLens, mapStateLens, uiStateLens, mapStyleLens]
- )(CustomHeader);
+ withState([visStateLens, mapStateLens, uiStateLens, mapStyleLens])(
+ CustomHeader
+ );
const KeplerGl = injectComponents([
[PanelHeaderFactory, myCustomHeaderFactory]
@@ -162,39 +249,97 @@ test('Components -> injector -> withState', t => {
const wrapper = mount(
<Provider store={store}>
- <KeplerGl id="foo" mapboxApiAccessToken="smoothie_and_milkshake"/>
+ <KeplerGl id="foo" mapboxApiAccessToken="smoothie_and_milkshake" />
</Provider>
);
+ const header = wrapper.find(CustomHeader).at(0);
+ const props = header.props();
+
+ t.ok(header, 'should render CustomHeader');
// test if custom header is rendered
- t.ok(
- wrapper
- .find(CustomHeader)
- .at(0)
- .props().visState,
- 'should add visState to props'
+ t.ok(props.visState, 'should add visState to props');
+ t.ok(props.mapState, 'should add mapState to props');
+ t.ok(props.mapStyle, 'should add mapStyle to props');
+ t.ok(props.uiState, 'should add uiState to props');
+
+ t.end();
+});
+
+test('Components -> injector -> withState.mapStateToProps', t => {
+ const CustomHeader = ({visState}) => (
+ <div className="my-test-header-3">smoothie</div>
);
- t.ok(
- wrapper
- .find(CustomHeader)
- .at(0)
- .props().mapState,
- 'should add mapState to props'
+ const myCustomHeaderFactory = () =>
+ withState([], state => ({ids: Object.keys(state)}))(CustomHeader);
+
+ const KeplerGl = injectComponents([
+ [PanelHeaderFactory, myCustomHeaderFactory]
+ ]);
+
+ // assume instance reducer is already mounted
+ const store = mockStore({
+ keplerGl: {
+ foo: initialCoreState
+ }
+ });
+
+ const wrapper = mount(
+ <Provider store={store}>
+ <KeplerGl id="foo" mapboxApiAccessToken="smoothie_and_milkshake" />
+ </Provider>
);
- t.ok(
- wrapper
- .find(CustomHeader)
- .at(0)
- .props().mapStyle,
- 'should add mapStyle to props'
+
+ // test if custom header is rendered
+ const header = wrapper.find(CustomHeader).at(0);
+ const props = header.props();
+
+ t.ok(header, 'should render CustomHeader');
+ t.deepEqual(props.ids, ['keplerGl'], 'should run mapStateToProps');
+
+ t.end();
+});
+
+test('Components -> injector -> actions', t => {
+ const CustomHeader = ({add}) => (
+ <div className="my-test-header-3" onClick={add}>
+ smoothie
+ </div>
);
- t.ok(
- wrapper
- .find(CustomHeader)
- .at(0)
- .props().uiState,
- 'should add uiState to props'
+
+ const testAction = () => ({type: 'ADD'});
+
+ const myCustomHeaderFactory = () =>
+ withState([], state => state, {add: testAction})(CustomHeader);
+
+ const KeplerGl = injectComponents([
+ [PanelHeaderFactory, myCustomHeaderFactory]
+ ]);
+
+ // assume instance reducer is already mounted
+ const store = mockStore({
+ keplerGl: {
+ foo: initialCoreState
+ }
+ });
+
+ const wrapper = mount(
+ <Provider store={store}>
+ <KeplerGl id="foo" mapboxApiAccessToken="smoothie_and_milkshake" />
+ </Provider>
);
+ // test if custom header is rendered
+ const header = wrapper.find(CustomHeader).at(0);
+ const props = header.props();
+
+ t.ok(header, 'should render CustomHeader');
+ t.ok(typeof props.add === 'function', 'should add actions');
+
+ wrapper.find(CustomHeader).simulate('click');
+
+ const lastAction = store.getActions().pop();
+ t.deepEqual(lastAction, {type: 'ADD'}, 'should dispatch custom actions');
+
t.end();
});
diff --git a/test/browser/components/data-table-modal-test.js b/test/browser/components/modals/data-table-modal-test.js
similarity index 100%
rename from test/browser/components/data-table-modal-test.js
rename to test/browser/components/modals/data-table-modal-test.js
diff --git a/test/browser/components/modals/index.js b/test/browser/components/modals/index.js
new file mode 100644
index 000000000..c86ba9570
--- /dev/null
+++ b/test/browser/components/modals/index.js
@@ -0,0 +1,21 @@
+// Copyright (c) 2019 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 './data-table-modal-test';
diff --git a/website/package.json b/website/package.json
index eecd04b38..2538d7bde 100644
--- a/website/package.json
+++ b/website/package.json
@@ -27,8 +27,8 @@
"react": "^16.8.4",
"react-dom": "^16.8.4",
"react-palm": "^1.1.2",
- "react-redux": "^4.4.5",
- "react-router": "^3.0.5",
+ "react-redux": "^7.1.3",
+ "react-router": "3.2.5",
"react-router-redux": "^4.0.8",
"react-share": "^2.1.1",
"react-swipeable-views": "^0.12.13",
diff --git a/website/webpack.config.js b/website/webpack.config.js
index 25a03e5f2..1ca57b01d 100644
--- a/website/webpack.config.js
+++ b/website/webpack.config.js
@@ -99,6 +99,7 @@ const COMMON_CONFIG = {
'kepler.gl': libSources,
react: resolve(rootDir, './node_modules/react'),
'styled-components': resolve(rootDir, './node_modules/styled-components'),
+ 'react-redux': resolve(rootDir, './node_modules/react-redux'),
'react-palm': resolve(rootDir, './node_modules/react-palm')
}
},
diff --git a/yarn.lock b/yarn.lock
index a0c61f667..dfd2be0ec 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -970,6 +970,13 @@
dependencies:
regenerator-runtime "^0.13.2"
+"@babel/runtime@^7.5.5":
+ version "7.7.2"
+ resolved "https://registry.yarnpkg.com/@babel%2fruntime/-/runtime-7.7.2.tgz#111a78002a5c25fc8e3361bedc9529c696b85a6a"
+ integrity sha1-ERp4ACpcJfyOM2G+3JUpxpa4Wmo=
+ dependencies:
+ regenerator-runtime "^0.13.2"
+
"@babel/template@^7.1.0", "@babel/template@^7.4.0", "@babel/template@^7.4.4", "@babel/template@^7.6.0":
version "7.6.0"
resolved "https://registry.yarnpkg.com/@babel/template/-/template-7.6.0.tgz#7f0159c7f5012230dad64cca42ec9bdb5c9536e6"
@@ -5326,10 +5333,10 @@ [email protected]:
resolved "https://registry.yarnpkg.com/hoek/-/hoek-4.2.1.tgz#9634502aa12c445dd5a7c5734b572bb8738aacbb"
integrity sha512-QLg82fGkfnJ/4iy1xZ81/9SIJiq1NGFUMGs6ParyjBZr6jW2Ufj/snDqTHixNlHdPNwN2RLVD0Pi3igeK9+JfA==
-hoist-non-react-statics@^3.1.0:
- version "3.3.0"
- resolved "https://registry.yarnpkg.com/hoist-non-react-statics/-/hoist-non-react-statics-3.3.0.tgz#b09178f0122184fb95acf525daaecb4d8f45958b"
- integrity sha512-0XsbTXxgiaCDYDIWFcwkmerZPSwywfUqYmwT4jzewKTQSWoE6FCMoUVOeBJWK3E/CrWbxRG3m5GzY4lnIwGRBA==
+hoist-non-react-statics@^3.3.0:
+ version "3.3.1"
+ resolved "https://registry.yarnpkg.com/hoist-non-react-statics/-/hoist-non-react-statics-3.3.1.tgz#101685d3aff3b23ea213163f6e8e12f4f111e19f"
+ integrity sha1-EBaF06/zsj6iExY/bo4S9PER4Z8=
dependencies:
react-is "^16.7.0"
@@ -8337,7 +8344,7 @@ prop-types-exact@^1.2.0:
object.assign "^4.1.0"
reflect.ownkeys "^0.2.0"
-prop-types@^15.5.10, prop-types@^15.5.4, prop-types@^15.5.7, prop-types@^15.5.8, prop-types@^15.6.0, prop-types@^15.6.1, prop-types@^15.6.2, prop-types@^15.7.2:
+prop-types@^15.5.10, prop-types@^15.5.4, prop-types@^15.5.7, prop-types@^15.5.8, prop-types@^15.6.0, prop-types@^15.6.2, prop-types@^15.7.2:
version "15.7.2"
resolved "https://registry.yarnpkg.com/prop-types/-/prop-types-15.7.2.tgz#52c41e75b8c87e72b9d9360e0206b99dcbffa6c5"
integrity sha512-8QQikdH7//R2vurIJSutZ1smHYTcLpRWEOlHnzcWHmBYrOGUysKwSsrC89BCiFj3CbrfJ/nXFdJepOVrY1GCHQ==
@@ -8614,14 +8621,6 @@ react-dom@^16.4.2, react-dom@^16.8.4:
prop-types "^15.6.2"
scheduler "^0.16.2"
-react-file-drop@^0.1.9:
- version "0.1.9"
- resolved "https://registry.yarnpkg.com/react-file-drop/-/react-file-drop-0.1.9.tgz#97102ebdfcddafd948bb20c16bfe3f07ddaf7a52"
- integrity sha512-fKXuOdGHGLpy+pQrUdUVa7yhOrrMQ91edIUi6c99OnUetUrC4Fm6Gg2vLUe9E0DCwtwSG6AadMlWVd0sdSl2rw==
- dependencies:
- create-react-class "^15.5.2"
- prop-types "^15.5.8"
-
react-hot-loader@^3.0.0-beta.6:
version "3.1.3"
resolved "https://registry.yarnpkg.com/react-hot-loader/-/react-hot-loader-3.1.3.tgz#6f92877326958c7cb0134b512474517869126082"
@@ -8727,18 +8726,17 @@ react-reconciler@^0.12.0:
object-assign "^4.1.1"
prop-types "^15.6.0"
-react-redux@^5.1.1:
- version "5.1.1"
- resolved "https://registry.yarnpkg.com/react-redux/-/react-redux-5.1.1.tgz#88e368682c7fa80e34e055cd7ac56f5936b0f52f"
- integrity sha512-LE7Ned+cv5qe7tMV5BPYkGQ5Lpg8gzgItK07c67yHvJ8t0iaD9kPFPAli/mYkiyJYrs2pJgExR2ZgsGqlrOApg==
+react-redux@^7.1.3:
+ version "7.1.3"
+ resolved "https://registry.yarnpkg.com/react-redux/-/react-redux-7.1.3.tgz#717a3d7bbe3a1b2d535c94885ce04cdc5a33fc79"
+ integrity sha1-cXo9e746Gy1TXJSIXOBM3Foz/Hk=
dependencies:
- "@babel/runtime" "^7.1.2"
- hoist-non-react-statics "^3.1.0"
+ "@babel/runtime" "^7.5.5"
+ hoist-non-react-statics "^3.3.0"
invariant "^2.2.4"
- loose-envify "^1.1.0"
- prop-types "^15.6.1"
- react-is "^16.6.0"
- react-lifecycles-compat "^3.0.0"
+ loose-envify "^1.4.0"
+ prop-types "^15.7.2"
+ react-is "^16.9.0"
react-sortable-hoc@^1.8.3:
version "1.10.1"