Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
[Enhancement] improve Geojson processing performance and error handling (#781)
Shan He884ada412153
diff --git a/.travis.yml b/.travis.ymlindex ee140fa8c..e75818a34 100644--- a/.travis.yml+++ b/.travis.yml@@ -24,6 +24,6 @@ after_success:- cat coverage/lcov.info | coverallsscript:- npm run lint- - npm run cover+ - npm run coveralls- fossacache: yarndiff --git a/bindings/kepler.gl-jupyter/.gitignore b/bindings/kepler.gl-jupyter/.gitignoreindex af7afd15e..7e5a9e0c2 100644--- a/bindings/kepler.gl-jupyter/.gitignore+++ b/bindings/kepler.gl-jupyter/.gitignore@@ -7,6 +7,7 @@ dist/build/*.py[cod]node_modules/+env/ENV/ENV3/diff --git a/examples/demo-app/src/components/load-data-modal/load-data-modal.js b/examples/demo-app/src/components/load-data-modal/load-data-modal.jsindex 48299a844..5e9615919 100644--- a/examples/demo-app/src/components/load-data-modal/load-data-modal.js+++ b/examples/demo-app/src/components/load-data-modal/load-data-modal.js@@ -59,7 +59,7 @@ const ModalTab = styled.div`border-bottom: 3px solid ${props => props.theme.textColorLT};font-weight: 500;}-+${media.portable`font-size: 12px;`};@@ -73,12 +73,12 @@ const StyledLoadDataModalTabItem = styled.div`font-size: 14px;font-weight: 400;color: ${props => props.theme.subtextColorLT};-+${media.portable`margin-left: 16px;font-size: 12px;`};-+:first-child {margin-left: 0;padding-left: 0;@@ -96,7 +96,7 @@ const StyledMapIcon = styled.div`width: 64px;height: 48px;border-radius: 2px;-+${media.portable`width: 48px;height: 32px;@@ -117,7 +117,7 @@ const StyledTrySampleData = styled.div`.demo-map-label {font-size: 11px;color: ${props => props.theme.labelColorLT};-+${media.portable`font-size: 10px;`};@@ -133,7 +133,7 @@ const StyledTrySampleData = styled.div`${media.portable`font-size: 12px;`};-+:hover {font-weight: 500;}@@ -179,7 +179,7 @@ class LoadDataModal extends Component {/>) : null}{loadingMethod.id === 'upload' ? (- <FileUpload onFileUpload={this.props.onFileUpload} />+ <FileUpload {...this.props} />) : null}{loadingMethod.id === 'remote' ? (<LoadRemoteMapdiff --git a/package.json b/package.jsonindex 9e9f46a8e..4fce9c08c 100644--- a/package.json+++ b/package.json@@ -30,7 +30,8 @@"test-browser": "NODE_ENV=test babel-tape-runner -r ./test/setup-browser-env.js ./test/browser.js | tap-spec","test-node": "NODE_ENV=test babel-tape-runner ./test/node.js | tap-spec","test": "npm run lint && npm run test-node && npm run test-browser",- "cover": "nyc npm test && nyc report --reporter html --reporter cobertura --reporter=text-lcov | coveralls",+ "cover": "nyc --reporter html --reporter cobertura --reporter json-summary npm test && nyc report",+ "coveralls": "nyc npm test && nyc report --reporter cobertura --reporter=text-lcov | coveralls","start": "npm run install-and-start -- examples/demo-app start-local","start:deck": "npm run install-and-start -- examples/demo-app start-local-deck","start:open-modal": "npm run install-and-start -- examples/open-modal start-local",@@ -109,7 +110,7 @@"react-markdown": "^4.0.6","react-modal": "^3.8.1","react-onclickoutside": "^6.7.1",- "react-palm": "^2.0.0",+ "react-palm": "^3.1.2","react-redux": "^5.1.1","react-sortable-hoc": "^1.8.3","react-tooltip": "^3.10.0",@@ -119,7 +120,7 @@"redux-actions": "^2.2.1","reselect": "^3.0.1","supercluster": "^6.0.1",- "type-analyzer": "0.2.1",+ "type-analyzer": "0.2.3","uber-licence": "^3.1.1","viewport-mercator-project": "^6.0.0","wellknown": "^0.5.0"diff --git a/src/components/common/datagrid.js b/src/components/common/datagrid.jsindex 5d7e1d471..5cdd34dc8 100644--- a/src/components/common/datagrid.js+++ b/src/components/common/datagrid.js@@ -30,6 +30,9 @@ import {parseFieldValue} from 'utils/data-utils';import {ALL_FIELD_TYPES} from 'constants';const DataGridWrapper = styled.div`+ width: 100%;+ overflow-x: auto;+.ReactVirtualized__Grid:focus,.ReactVirtualized__Grid:active {outline: 0;@@ -37,47 +40,53 @@ const DataGridWrapper = styled.div`.ReactVirtualized__Grid__innerScrollContainer {${props => props.theme.modalScrollBar};}-+.ReactVirtualized__Grid {.column-0 .cell {- padding-left: 24px;+ padding-left: ${props => props.theme.gridPaddingSide}px;}-++ .header-0 .header-cell {+ padding-left: ${props => props.theme.gridPaddingSide}px;+ }+.cell {- overflow-y: scroll;+ overflow-y: auto;overflow-x: hidden;-- &.geojson {- span {- text-align: left;- }- }+ padding-right: ${props => props.theme.cellPaddingSide}px;}-- .last .cell {- padding-right: 24px;+ .last {+ .cell {+ padding-right: ${props => props.theme.gridPaddingSide}px;+ }+ .header-cell {+ padding-right: ${props => props.theme.gridPaddingSide}px;+ }}}`;const StyledFieldHeader = styled.div`display: flex;- flex-direction: column;align-items: center;- justify-content: center;- text-align: center;+ justify-content: left;border-right: 0;border-bottom: 0;background: ${props => props.theme.panelBackgroundLT};color: ${props => props.theme.titleColorLT};height: 100%;-++ .header-content {+ display: flex;+ flex-direction: column;+ }+.label-wrapper {display: flex;align-items: center;}-+.icon-wrapper {margin-right: ${props => props.type === 'timestamp' ? '2px' : '0'};height: 16px;@@ -87,14 +96,16 @@ const StyledFieldHeader = styled.div`export const FieldHeaderFactory = () => {const Header = ({className, value, type}) => (<StyledFieldHeader className={className || ''} type={type} title={value}>- <div className="label-wrapper">- <div className="icon-wrapper">- {type === 'timestamp' ? <Clock height="16px" /> : null}+ <div className="field-header-content">+ <div className="label-wrapper">+ <div className="icon-wrapper">+ {type === 'timestamp' ? <Clock height="16px" /> : null}+ </div>+ <span>{value}</span>+ </div>+ <div className="field-wrapper">+ <FieldToken type={type} /></div>- <span>{value}</span>- </div>- <div className="field-wrapper">- <FieldToken type={type} /></div></StyledFieldHeader>);@@ -109,16 +120,14 @@ const StyledCell = styled.div`flex-direction: column;align-items: center;justify-content: center;- text-align: center;border-right: 0;border-bottom: ${props => props.theme.panelBorderLT};color: ${props => props.theme.labelColorLT};text-overflow: ellipsis;height: 100%;width: 100%;-+span {- overflow: scroll;text-overflow: ellipsis;white-space: pre-wrap;word-wrap: break-word;@@ -163,9 +172,7 @@ function DataGridFactory(_cellRenderer = ({columnIndex, key, rowIndex, style}) => {const {columns, rows} = this.props;-const isLast = columnIndex === columns.length - 1-const type = columns[columnIndex].type;// rowIndex -1 because data rows start rendering at index 1 and we normalize back using the -1 paramdiff --git a/src/components/common/error-boundary.js b/src/components/common/error-boundary.jsnew file mode 100644index 000000000..5c32a8e97--- /dev/null+++ b/src/components/common/error-boundary.js@@ -0,0 +1,43 @@+// 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 console from 'global/console';++export default class ErrorBoundary extends React.Component {+ static getDerivedStateFromError(error) {+ // Update state so the next render will show the fallback UI.+ return {hasError: true, error};+ }+ state = {hasError: false}+ componentDidCatch(error, errorInfo) {+ // You can also log the error to an error reporting service+ console.error(error, errorInfo);+ }++ render() {+ if (this.state.hasError) {+ // You can render any custom fallback UI+ return <h1>Something went wrong.</h1>;+ }++ return this.props.children;+ }+}diff --git a/src/components/common/file-uploader/file-upload.js b/src/components/common/file-uploader/file-upload.jsindex 3a9de50ce..05eb986e0 100644--- a/src/components/common/file-uploader/file-upload.js+++ b/src/components/common/file-uploader/file-upload.js@@ -52,6 +52,7 @@ const DISCLAIMER = '*kepler.gl is a client-side application with no server backe'No information or map data is sent to any server.';const CONFIG_UPLOAD_MESSAGE = `Upload **CSV**, **GeoJson** or saved map **Json**. Read more about [**supported file formats**](${GUIDES_FILE_FORMAT}).`;+const fileIconColor = '#D3D8E0';const LinkRenderer = props => {@@ -74,10 +75,14 @@ const StyledUploadMessage = styled.div`const WarningMsg = styled.span`margin-top: 10px;color: ${props => props.theme.errorColor};+ font-weight: 500;`;const PositiveMsg = styled.span`+ display: inline-block;color: ${props => props.theme.primaryBtnActBgd};+ font-weight: 500;+ margin-right: 8px;`;const StyledFileDrop = styled.div`@@ -144,6 +149,14 @@ const StyledMessage = styled.div`display: flex;justify-content: center;align-items: center;+ margin-bottom: 32px;++ .loading-action {+ margin-right: 10px;+ }+ .loading-spinner {+ margin-left: 10px;+ }`;const StyledDragFileWrapper = styled.div`@@ -167,15 +180,33 @@ export default class FileUpload extends Component {static propTypes = {onFileUpload: PropTypes.func.isRequired,- validFileExt: PropTypes.arrayOf(PropTypes.string)+ validFileExt: PropTypes.arrayOf(PropTypes.string),+ fileLoading: PropTypes.bool};state = {dragOver: false,+ fileLoading: false,files: [],errorFiles: []};+ static getDerivedStateFromProps(props, state) {+ if (+ state.fileLoading &&+ props.fileLoading === false &&+ state.files.length+ ) {+ return {+ files: [],+ fileLoading: props.fileLoading+ };+ }+ return {+ fileLoading: props.fileLoading+ };+ }+frame = createRef();_isValidFileType = filename => {@@ -201,10 +232,8 @@ export default class FileUpload extends Component {}}- this.setState(- nextState,- () =>- nextState.files.length ? this.props.onFileUpload(nextState.files) : null+ this.setState(nextState, () =>+ nextState.files.length ? this.props.onFileUpload(nextState.files) : null);};@@ -214,38 +243,38 @@ export default class FileUpload extends Component {_renderMessage() {const {errorFiles, files} = this.state;-if (errorFiles.length) {return (<WarningMsg>{`File ${errorFiles.join(', ')} is not supported.`}</WarningMsg>);+ } else if (this.props.fileLoading && files.length) {+ return (+ <StyledMessage className="file-uploader__message">+ <div className="loading-action">Uploading</div>+ <div>+ {files.map((f, i) => (+ <PositiveMsg key={i}>{f.name}</PositiveMsg>+ ))}+ ...+ </div>+ <div className="loading-spinner">+ <LoadingSpinner size={20} />+ </div>+ </StyledMessage>+ );}- if (!files.length) {- return null;- }-- return (- <StyledMessage className="file-uploader__message">- <div>Uploading...</div>- <PositiveMsg>- {`${files.map(f => f.name).join(' and ')}...`}- </PositiveMsg>- <LoadingSpinner size={20} />- </StyledMessage>- );+ return null;}render() {const {dragOver, files} = this.state;const {validFileExt} = this.props;+return (- <StyledFileUpload- className="file-uploader"- ref={this.frame}- >+ <StyledFileUpload className="file-uploader" ref={this.frame}><inputclassName="filter-upload__input"type="file"@@ -270,7 +299,12 @@ export default class FileUpload extends Component {<StyledDragNDropIcon><StyledFileTypeFow className="file-type-row">{validFileExt.map(ext => (- <FileType key={ext} ext={ext} height="50px" fontSize="9px"/>+ <FileType+ key={ext}+ ext={ext}+ height="50px"+ fontSize="9px"+ />))}</StyledFileTypeFow><DragNDrop height="44px" />@@ -278,13 +312,13 @@ export default class FileUpload extends Component {<div>{this._renderMessage()}</div></div>{!files.length ? (- <StyledDragFileWrapper>- <MsgWrapper>{MESSAGE}</MsgWrapper>- <span className="file-upload-or">or</span>- <UploadButton onUpload={this._handleFileInput}>- browse your files- </UploadButton>- </StyledDragFileWrapper>+ <StyledDragFileWrapper>+ <MsgWrapper>{MESSAGE}</MsgWrapper>+ <span className="file-upload-or">or</span>+ <UploadButton onUpload={this._handleFileInput}>+ browse your files+ </UploadButton>+ </StyledDragFileWrapper>) : null}<StyledDisclaimer>{DISCLAIMER}</StyledDisclaimer></StyledFileDrop>diff --git a/src/components/map/layer-hover-info.js b/src/components/map/layer-hover-info.jsindex 930a95592..284f14404 100644--- a/src/components/map/layer-hover-info.js+++ b/src/components/map/layer-hover-info.js@@ -22,8 +22,8 @@ import React from 'react';import styled from 'styled-components';import {CenterFlexbox} from 'components/common/styled-components';import {Layers} from 'components/common/icons';-import {FIELD_DISPLAY_FORMAT} from 'constants/default-settings';import PropTypes from 'prop-types';+import {parseFieldValue} from 'utils/data-utils';export const StyledLayerName = styled(CenterFlexbox)`color: ${props => props.theme.textColorHl};@@ -78,10 +78,10 @@ const EntryInfoRow = ({name, fields, data}) => {}const valueIdx = field.tableFieldIndex - 1;- const format = _getCellFormat(field.type);+ const displayValue = parseFieldValue(data[valueIdx], field.type);return (- <Row name={name} value={format ? format(data[valueIdx]) : data[valueIdx]} />+ <Row name={name} value={displayValue} />);};@@ -113,10 +113,6 @@ const CellInfo = ({data, layer}) => {);};-function _getCellFormat(type) {- return FIELD_DISPLAY_FORMAT[type];-}-const LayerHoverInfoFactory = () => {const LayerHoverInfo = props => {const {data, layer, fieldsToShow} = props;diff --git a/src/components/map/map-popover.js b/src/components/map/map-popover.jsindex 9786c22b0..11c06b5ae 100644--- a/src/components/map/map-popover.js+++ b/src/components/map/map-popover.js@@ -24,6 +24,7 @@ import PropTypes from 'prop-types';import LayerHoverInfoFactory from './layer-hover-info';import CoordinateInfoFactory from './coordinate-info';import {Pin} from 'components/common/icons';+import ErrorBoundary from 'components/common/error-boundary';const MAX_WIDTH = 500;const MAX_HEIGHT = 600;@@ -153,27 +154,29 @@ export default function MapPopoverFactory(LayerHoverInfo, CoordinateInfo) {Number.isFinite(x) && Number.isFinite(y) ? this._getPosition(x, y) : {};return (- <StyledMapPopover- ref={this.popover}- className="map-popover"- style={{- ...style,- maxWidth: MAX_WIDTH- }}- >- {freezed ? (- <div className="map-popover__top">- <div className="gutter" />- <StyledPin className="popover-pin" onClick={this.props.onClose}>- <Pin height="16px" />- </StyledPin>- </div>- ) : null}- {Array.isArray(coordinate) && (- <CoordinateInfo coordinate={coordinate} />- )}- {layerHoverProp && <LayerHoverInfo {...layerHoverProp} />}- </StyledMapPopover>+ <ErrorBoundary>+ <StyledMapPopover+ ref={this.popover}+ className="map-popover"+ style={{+ ...style,+ maxWidth: MAX_WIDTH+ }}+ >+ {freezed ? (+ <div className="map-popover__top">+ <div className="gutter" />+ <StyledPin className="popover-pin" onClick={this.props.onClose}>+ <Pin height="16px" />+ </StyledPin>+ </div>+ ) : null}+ {Array.isArray(coordinate) && (+ <CoordinateInfo coordinate={coordinate} />+ )}+ {layerHoverProp && <LayerHoverInfo {...layerHoverProp} />}+ </StyledMapPopover>+ </ErrorBoundary>);}}diff --git a/src/components/modal-container.js b/src/components/modal-container.jsindex 71390e055..7bb913e60 100644--- a/src/components/modal-container.js+++ b/src/components/modal-container.js@@ -302,6 +302,7 @@ export default function ModalContainerFactory(<LoadDataModalonClose={this._closeModal}onFileUpload={this._onFileUpload}+ {...uiState.loadFiles}/>);modalProps = {diff --git a/src/components/modals/load-data-modal.js b/src/components/modals/load-data-modal.jsindex 432ef14a3..6c1612ce0 100644--- a/src/components/modals/load-data-modal.js+++ b/src/components/modals/load-data-modal.js@@ -28,20 +28,22 @@ const StyledLoadDataModal = styled.div`padding: ${props => props.theme.modalPadding};`;-const propTypes = {- // call backs- onFileUpload: PropTypes.func.isRequired-};+const loadDataModalFactory = () => {+ const LoadDataModal = props => (+ <StyledLoadDataModal>+ <div className="load-data-modal">+ <FileUpload {...props}/>+ </div>+ </StyledLoadDataModal>+ );-export const LoadDataModal = props => (- <StyledLoadDataModal>- <div className="load-data-modal">- <FileUpload onFileUpload={props.onFileUpload} />- </div>- </StyledLoadDataModal>-);+ LoadDataModal.propTypes = {+ // call backs+ onFileUpload: PropTypes.func.isRequired,+ fileLoading: PropTypes.bool+ };-LoadDataModal.propTypes = propTypes;+ return LoadDataModal;+};-const loadDataModalFactory = () => LoadDataModal;export default loadDataModalFactory;diff --git a/src/constants/default-settings.js b/src/constants/default-settings.jsindex 41b76275f..f64579171 100644--- a/src/constants/default-settings.js+++ b/src/constants/default-settings.js@@ -330,17 +330,6 @@ export const FILED_TYPE_DISPLAY = {}};-export const defaultFormat = d => d;--export const FIELD_DISPLAY_FORMAT = {- [ALL_FIELD_TYPES.string]: defaultFormat,- [ALL_FIELD_TYPES.timestamp]: defaultFormat,- [ALL_FIELD_TYPES.integer]: defaultFormat,- [ALL_FIELD_TYPES.boolean]: d => String(d),- [ALL_FIELD_TYPES.date]: defaultFormat,- [ALL_FIELD_TYPES.geojson]: defaultFormat-};-export const CHANNEL_SCALES = keyMirror({color: null,radius: null,diff --git a/src/layers/trip-layer/trip-utils.js b/src/layers/trip-layer/trip-utils.jsindex afa700c5d..86fd08791 100644--- a/src/layers/trip-layer/trip-utils.js+++ b/src/layers/trip-layer/trip-utils.js@@ -18,7 +18,7 @@// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN// THE SOFTWARE.-import {Analyzer} from 'type-analyzer';+import {Analyzer, DATA_TYPES} from 'type-analyzer';import {getSampleData,@@ -55,7 +55,11 @@ export function coordHasLength4(samples) {export function containValidTime(timestamps) {const formattedTimeStamps = timestamps.map(ts => ({ts}));- const analyzedType = Analyzer.computeColMeta(formattedTimeStamps)[0];+ const ignoredDataTypes = Object.keys(DATA_TYPES).filter(type =>+ ![DATA_TYPES.TIME, DATA_TYPES.DATETIME].includes(type));++ // ignore all types but TIME to improve performance+ const analyzedType = Analyzer.computeColMeta(formattedTimeStamps, [], {ignoredDataTypes})[0];if (!analyzedType || analyzedType.category !== 'TIME') {return false;diff --git a/src/processors/data-processor.js b/src/processors/data-processor.jsindex 87fb0135b..a00fdb519 100644--- a/src/processors/data-processor.js+++ b/src/processors/data-processor.js@@ -25,11 +25,60 @@ import assert from 'assert';import {Analyzer, DATA_TYPES as AnalyzerDATA_TYPES} from 'type-analyzer';import normalize from '@mapbox/geojson-normalize';import {ALL_FIELD_TYPES} from 'constants/default-settings';-import {notNullorUndefined, parseFieldValue} from 'utils/data-utils';+import {+ notNullorUndefined,+ parseFieldValue,+ getSampleData+} from 'utils/data-utils';import KeplerGlSchema from 'schemas';+import {GUIDES_FILE_FORMAT} from 'constants/user-guides';+import {isPlainObject} from 'utils/utils';++export const ACCEPTED_ANALYZER_TYPES = [+ AnalyzerDATA_TYPES.DATE,+ AnalyzerDATA_TYPES.TIME,+ AnalyzerDATA_TYPES.DATETIME,+ AnalyzerDATA_TYPES.NUMBER,+ AnalyzerDATA_TYPES.INT,+ AnalyzerDATA_TYPES.FLOAT,+ AnalyzerDATA_TYPES.BOOLEAN,+ AnalyzerDATA_TYPES.STRING,+ AnalyzerDATA_TYPES.GEOMETRY,+ AnalyzerDATA_TYPES.GEOMETRY_FROM_STRING,+ AnalyzerDATA_TYPES.PAIR_GEOMETRY_FROM_STRING,+ AnalyzerDATA_TYPES.ZIPCODE,+ AnalyzerDATA_TYPES.ARRAY,+ AnalyzerDATA_TYPES.OBJECT+];// if any of these value occurs in csv, parse it to null;-const CSV_NULLS = ['', 'null', 'NULL', 'Null', 'NaN'];+const CSV_NULLS = ['', 'null', 'NULL', 'Null', 'NaN', '\N'];++const IGNORE_DATA_TYPES = Object.keys(AnalyzerDATA_TYPES).filter(+ type => !ACCEPTED_ANALYZER_TYPES.includes(type)+);++export const PARSE_FIELD_VALUE_FROM_STRING = {+ [ALL_FIELD_TYPES.boolean]: {+ valid: d => typeof d === 'boolean',+ parse: d => d === 'true' || d === 'True' || d === '1'+ },+ [ALL_FIELD_TYPES.integer]: {+ valid: d => parseInt(d, 10) === d,+ parse: d => parseInt(d, 10)+ },+ [ALL_FIELD_TYPES.timestamp]: {+ valid: (d, field) =>+ ['x', 'X'].includes(field.format)+ ? typeof d === 'number'+ : typeof d === 'string',+ parse: (d, field) => (['x', 'X'].includes(field.format) ? Number(d) : d)+ },+ [ALL_FIELD_TYPES.real]: {+ valid: d => parseFloat(d) === d,+ parse: parseFloat+ }+};/*** Process csv data, output a data object with `{fields: [], rows: []}`.@@ -60,14 +109,14 @@ export function processCsvData(rawData) {// here we assume the csv file that people uploaded will have first row// as name of the column// TODO: add a alert at upload csv to remind define first row- const [headerRow, ...rows] = csvParseRows(rawData);-- if (!rows.length || !headerRow) {- // looks like an empty file- // resolve null, and catch them later in one place- return null;+ const result = csvParseRows(rawData);+ if (!Array.isArray(result) || result.length < 2) {+ // looks like an empty file, throw error to be catch+ throw new Error('Read File Failed: CSV is empty');}+ const [headerRow, ...rows] = result;+cleanUpFalsyCsvValue(rows);// No need to run type detection on every data point// here we get a list of none null values to run analyze on@@ -75,7 +124,7 @@ export function processCsvData(rawData) {const fields = getFieldsFromData(sample, headerRow);- const parsedRows = parseCsvByFields(rows, fields);+ const parsedRows = parseRowsByFields(rows, fields);return {fields, rows: parsedRows};}@@ -85,9 +134,10 @@ export function processCsvData(rawData) {* @param {Array<Array>} rows* @param {Array<Object} fields*/-export function parseCsvByFields(rows, fields) {+export function parseRowsByFields(rows, fields) {// Edit rows in place- fields.forEach(parseCsvRowsByFieldType.bind(null, rows));+ const geojsonFieldIdx = fields.findIndex(f => f.name === '_geojson');+ fields.forEach(parseCsvRowsByFieldType.bind(null, rows, geojsonFieldIdx));return rows;}@@ -148,6 +198,7 @@ function cleanUpFalsyCsvValue(rows) {}}}+/*** Process uploaded csv file to parse value by field type*@@ -156,36 +207,24 @@ function cleanUpFalsyCsvValue(rows) {* @param {Number} i* @returns {void}*/-export function parseCsvRowsByFieldType(rows, field, i) {- const unixFormat = ['x', 'X'];-- rows.forEach(row => {- if (row[i] !== null) {- switch (field.type) {- case ALL_FIELD_TYPES.real:- row[i] = parseFloat(row[i]);- break;-- // TODO: timestamp can be either '1495827326' or '2016-03-10 11:20'- // if it's '1495827326' we pass it to int- case ALL_FIELD_TYPES.timestamp:- row[i] = unixFormat.includes(field.format) ? Number(row[i]) : row[i];- break;-- case ALL_FIELD_TYPES.integer:- row[i] = parseInt(row[i], 10);- break;-- case ALL_FIELD_TYPES.boolean:- // 0 and 1 only field can also be boolean- row[i] = row[i] === 'true' || row[i] === 'True' || row[i] === '1';- break;-- default:- break;- }+export function parseCsvRowsByFieldType(rows, geoFieldIdx, field, i) {+ const parser = PARSE_FIELD_VALUE_FROM_STRING[field.type];+ if (parser) {+ // check first not null value of it's already parsed+ const first = rows.find(r => notNullorUndefined(r[i]));+ if (!first || parser.valid(first[i], field)) {+ return;}- });+ rows.forEach(row => {+ // parse string value based on field type+ if (row[i] !== null) {+ row[i] = parser.parse(row[i], field);+ if (geoFieldIdx > -1 && row[geoFieldIdx] && row[geoFieldIdx].properties) {+ row[geoFieldIdx].properties[field.name] = row[i];+ }+ }+ });+ }}/**@@ -231,14 +270,17 @@ export function parseCsvRowsByFieldType(rows, field, i) {*/export function getFieldsFromData(data, fieldOrder) {// add a check for epoch timestamp- const metadata = Analyzer.computeColMeta(data, [- {regex: /.*geojson|all_points/g, dataType: 'GEOMETRY'}- ]);+ const metadata = Analyzer.computeColMeta(+ data,+ [{regex: /.*geojson|all_points/g, dataType: 'GEOMETRY'}],+ {ignoredDataTypes: IGNORE_DATA_TYPES}+ );const {fieldByIndex} = renameDuplicateFields(fieldOrder);- return fieldOrder.reduce((orderedArray, field, index) => {+ const result = fieldOrder.reduce((orderedArray, field, index) => {const name = fieldByIndex[index];+const fieldMeta = metadata.find(m => m.key === field);const {type, format} = fieldMeta || {};@@ -248,9 +290,10 @@ export function getFieldsFromData(data, fieldOrder) {tableFieldIndex: index + 1,type: analyzerTypeToFieldType(type)};-return orderedArray;}, []);++ return result;}/**@@ -301,11 +344,12 @@ export function analyzerTypeToFieldType(aType) {FLOAT,BOOLEAN,STRING,- CITY,GEOMETRY,GEOMETRY_FROM_STRING,+ PAIR_GEOMETRY_FROM_STRING,ZIPCODE,- PAIR_GEOMETRY_FROM_STRING+ ARRAY,+ OBJECT} = AnalyzerDATA_TYPES;// TODO: un recognized types@@ -326,9 +370,11 @@ export function analyzerTypeToFieldType(aType) {case GEOMETRY:case GEOMETRY_FROM_STRING:case PAIR_GEOMETRY_FROM_STRING:+ case ARRAY:+ case OBJECT:+ // TODO: create a new data type for objects and arraysreturn ALL_FIELD_TYPES.geojson;case STRING:- case CITY:case ZIPCODE:return ALL_FIELD_TYPES.string;default:@@ -340,7 +386,7 @@ export function analyzerTypeToFieldType(aType) {/*** Process data where each row is an object, output can be passed to [`addDataToMap`](../actions/actions.md#adddatatomap)- * @param {Object} rawData an array of object+ * @param {Array<Object>} rawData an array of row object, each object should have the same number of keys* @returns {Object} dataset containing `fields` and `rows`* @public* @example@@ -360,17 +406,21 @@ export function analyzerTypeToFieldType(aType) {* }));*/export function processRowObject(rawData) {- if (!rawData.length) {+ if (!Array.isArray(rawData) || !rawData.length) {return null;}const keys = Object.keys(rawData[0]);const rows = rawData.map(d => keys.map(key => d[key]));- const fields = getFieldsFromData(rawData, keys);++ // pick samples+ const sampleData = getSampleData(rawData, 500);+ const fields = getFieldsFromData(sampleData, keys);+ const parsedRows = parseRowsByFields(rows, fields);return {fields,- rows+ rows: parsedRows};}@@ -415,21 +465,16 @@ export function processGeojson(rawData) {const normalizedGeojson = normalize(rawData);if (!normalizedGeojson || !Array.isArray(normalizedGeojson.features)) {+ const error = new Error(+ `Read File Failed: File is not a valid GeoJSON. Read more about [supported file format](${GUIDES_FILE_FORMAT})`+ );+ throw error;// fail to normalize geojson- return null;}// getting all feature fieldsconst allData = normalizedGeojson.features.reduce((accu, f, i) => {if (f.geometry) {- // check if properties contains object and stringfy this- if (typeof f.properties === 'object' && f.properties !== null) {- Object.keys(f.properties).forEach(key => {- if (typeof f.properties[key] === 'object') {- f.properties[key] = JSON.stringify(f.properties[key]);- }- });- }accu.push({// add feature to _geojson field_geojson: f,@@ -457,6 +502,7 @@ export function processGeojson(rawData) {}});});+const processRow = processRowObject(allData);return processRow;}@@ -481,31 +527,20 @@ export function formatCsv(data, fields) {/*** Validate input data, adding missing field types, rename duplicate columns- * @param data+ * @param {Object} data dataset.data+ * @param {Array<Object>} data.fields an array of fields+ * @param {Array<Object>} data.rows an array of data rows* @returns {{allData: Array, fields: Array}}*/export function validateInputData(data) {- // TODO: add test- /*- * expected input data format- * {- * fields: [],- * rows: []- * }- */- let proceed = true;- if (!data) {- assert('receiveVisData: data cannot be null');- proceed = false;+ if (!isPlainObject(data)) {+ assert('addDataToMap Error: dataset.data cannot be null');+ return null;} else if (!Array.isArray(data.fields)) {- assert('receiveVisData: expect data.fields to be an array');- proceed = false;+ assert('addDataToMap Error: expect dataset.data.fields to be an array');+ return null;} else if (!Array.isArray(data.rows)) {- assert('receiveVisData: expect data.rows to be an array');- proceed = false;- }-- if (!proceed) {+ assert('addDataToMap Error: expect dataset.data.rows to be an array');return null;}@@ -513,17 +548,18 @@ export function validateInputData(data) {// check if all fields has name, format and typeconst allValid = fields.every((f, i) => {- if (typeof f !== 'object') {++ if (!isPlainObject(f)) {assert(`fields needs to be an array of object, but find ${typeof f}`);- return false;+ fields[i] = {};}if (!f.name) {assert(- `field.name is required but missing in field ${JSON.stringify(f)}`+ `field.name is required but missing in ${JSON.stringify(f)}`);// assign a name- f.name = `column_${i}`;+ fields[i].name = `column_${i}`;}if (!ALL_FIELD_TYPES[f.type]) {@@ -531,7 +567,15 @@ export function validateInputData(data) {return false;}- return f.type !== ALL_FIELD_TYPES.timestamp || typeof f.format === 'string';+ // check time format is correct based on first 10 not empty element+ if (f.type === ALL_FIELD_TYPES.timestamp) {+ const sample = findNonEmptyRowsAtField(rows, i, 10)+ .map(r => ({ts: r[i]}));+ const analyzedType = Analyzer.computeColMeta(sample)[0];+ return analyzedType.category === 'TIME' && analyzedType.format === f.format;+ }++ return true;});if (allValid) {@@ -555,6 +599,17 @@ export function validateInputData(data) {return {fields: updatedFields, rows};}+function findNonEmptyRowsAtField(rows, fieldIdx, total) {+ const sample = [];+ let i = 0;+ while (sample.length < total && i < rows.length) {+ if (notNullorUndefined(rows[i][fieldIdx])) {+ sample.push(rows[i]);+ }+ i++;+ }+ return sample;+}/*** Process saved kepler.gl json to be pass to [`addDataToMap`](../actions/actions.md#adddatatomap).* The json object should contain `datasets` and `config`.@@ -580,5 +635,6 @@ export const Processors = {processKeplerglJSON,analyzerTypeToFieldType,getFieldsFromData,- parseCsvRowsByFieldType+ parseCsvRowsByFieldType,+ formatCsv};diff --git a/src/reducers/combined-updaters.js b/src/reducers/combined-updaters.jsindex f519cc06f..cc6d0e191 100644--- a/src/reducers/combined-updaters.js+++ b/src/reducers/combined-updaters.js@@ -18,13 +18,13 @@// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN// THE SOFTWARE.-import {toggleModalUpdater} from './ui-state-updaters';+import {toggleModalUpdater, loadFilesSuccessUpdater} from './ui-state-updaters';import {updateVisDataUpdater as visStateUpdateVisDataUpdater} from './vis-state-updaters';import {receiveMapConfigUpdater as stateMapConfigUpdater} from './map-state-updaters';import {receiveMapConfigUpdater as styleMapConfigUpdater} from './map-style-updaters';import {findMapBounds} from 'utils/data-utils';import KeplerGlSchema from 'schemas';-import {isObject} from 'util';+import {isPlainObject} from 'utils/utils';// compose action to apply result multiple reducers, with the output of one@@ -73,7 +73,8 @@ import {isObject} from 'util';const combinedUpdaters = null;/* eslint-enable no-unused-vars */-export const isValidConfig = config => isObject(config) && isObject(config.config) && config.version;+export const isValidConfig = config =>+ isPlainObject(config) && isPlainObject(config.config) && config.version;export const defaultAddDataToMapOptions = {centerMap: true,keepExistingConfig: false@@ -111,7 +112,7 @@ export const addDataToMapUpdater = (state, {payload}) => {if (isValidConfig(config)) {// if passed in saved config- parsedConfig = KeplerGlSchema.parseSavedConfig(config)+ parsedConfig = KeplerGlSchema.parseSavedConfig(config);}const oldLayers = state.visState.layers;@@ -154,9 +155,12 @@ export const addDataToMapUpdater = (state, {payload}) => {mergedState = {...mergedState,uiState: {- ...mergedState.uiState,- ...toggleModalUpdater(mergedState.uiState, {payload: null}),- ...(options.hasOwnProperty('readOnly') ? {readOnly: options.readOnly} : {})+ ...toggleModalUpdater(loadFilesSuccessUpdater(mergedState.uiState), {+ payload: null+ }),+ ...(options.hasOwnProperty('readOnly')+ ? {readOnly: options.readOnly}+ : {})}};diff --git a/src/reducers/ui-state-updaters.js b/src/reducers/ui-state-updaters.jsindex 876095954..791fa0155 100644--- a/src/reducers/ui-state-updaters.js+++ b/src/reducers/ui-state-updaters.js@@ -25,9 +25,10 @@ import {RATIOS,RESOLUTIONS,EXPORT_MAP_FORMATS,- EXPORT_HTML_MAP_MODES+ EXPORT_HTML_MAP_MODES,+ DEFAULT_NOTIFICATION_TOPICS} from 'constants/default-settings';-import {createNotification} from 'utils/notifications-utils';+import {createNotification, errorNotification} from 'utils/notifications-utils';export const DEFAULT_ACTIVE_SIDE_PANEL = 'layer';export const DEFAULT_MODAL = ADD_DATA_ID;@@ -123,6 +124,10 @@ export const DEFAULT_EXPORT_IMAGE = {error: false};+export const DEFAULT_LOAD_FILES = {+ fileLoading: false+};+/*** Default initial `exportData` settings* @memberof uiStateUpdaters@@ -200,7 +205,8 @@ export const INITIAL_UI_STATE = {// map control panelsmapControls: DEFAULT_MAP_CONTROLS,// ui notifications- notifications: DEFAULT_NOTIFICATIONS+ notifications: DEFAULT_NOTIFICATIONS,+ loadFiles: DEFAULT_LOAD_FILES};/* Updaters */@@ -300,7 +306,10 @@ export const toggleMapControlUpdater = (state, {payload: panelId}) => ({* @returns {Object} nextState* @public*/-export const openDeleteModalUpdater = (state, {payload: datasetKeyToRemove}) => ({+export const openDeleteModalUpdater = (+ state,+ {payload: datasetKeyToRemove}+) => ({...state,currentModal: DELETE_DATA_ID,datasetKeyToRemove@@ -563,3 +572,42 @@ export const removeNotificationUpdater = (state, {payload: id}) => ({...state,notifications: state.notifications.filter(n => n.id !== id)});++/**+ * Fired when file loading begin+ * @memberof uiStateUpdaters+ * @param {Object} state `uiState`+ * @param {Object} action+ */+export const loadFilesUpdater = (state) => ({+ ...state,+ loadFiles: {+ ...state.loadFiles,+ fileLoading: true+ }+});++export const loadFilesSuccessUpdater = (state) => ({+ ...state,+ loadFiles: {+ ...state.loadFiles,+ fileLoading: false+ }+});++export const loadFilesErrUpdater = (state, {error}) =>+ addNotificationUpdater(+ {+ ...state,+ loadFiles: {+ ...state.loadFiles,+ fileLoading: false+ }+ },+ {+ payload: errorNotification({+ message: (error || {}).message || 'Failde to upload files',+ topic: DEFAULT_NOTIFICATION_TOPICS.global+ })+ }+ );diff --git a/src/reducers/ui-state.js b/src/reducers/ui-state.jsindex f9931042f..e701cff26 100644--- a/src/reducers/ui-state.js+++ b/src/reducers/ui-state.js@@ -50,7 +50,10 @@ const actionHandler = {[ActionTypes.SET_EXPORT_DATA]: uiStateUpdaters.setExportDataUpdater,[ActionTypes.SET_USER_MAPBOX_ACCESS_TOKEN]: uiStateUpdaters.setUserMapboxAccessTokenUpdater,[ActionTypes.SET_EXPORT_MAP_FORMAT]: uiStateUpdaters.setExportMapFormat,- [ActionTypes.SET_EXPORT_MAP_HTML_MODE]: uiStateUpdaters.setExportMapHTMLMode+ [ActionTypes.SET_EXPORT_MAP_HTML_MODE]: uiStateUpdaters.setExportMapHTMLMode,++ [ActionTypes.LOAD_FILES]: uiStateUpdaters.loadFilesUpdater,+ [ActionTypes.LOAD_FILES_ERR]: uiStateUpdaters.loadFilesErrUpdater};/* Reducer */diff --git a/src/reducers/vis-state-updaters.js b/src/reducers/vis-state-updaters.jsindex 7f9d56373..0c7d3a099 100644--- a/src/reducers/vis-state-updaters.js+++ b/src/reducers/vis-state-updaters.js@@ -134,8 +134,6 @@ export const defaultAnimationConfig = {* @property {Object} hoverInfo* @property {Object} clicked* @property {Object} mousePos- * @property {boolean} fileLoading- * @property {*} fileLoadingErr* @property {Array} splitMaps - a list of objects of layer availabilities and visibilities for each map* @property {Object} layerClasses* @property {Object} animationConfig@@ -164,10 +162,6 @@ export const INITIAL_VIS_STATE = {clicked: undefined,mousePos: {},- // TODO: not used anywhere, delete it- fileLoading: false,- fileLoadingErr: null,-// this is used when user split mapssplitMaps: [// this will contain a list of objects to@@ -1242,6 +1236,7 @@ export const updateVisDataUpdater = (state, action) => {// register layer animation domain,// need to be called after layer data is calculatedupdatedState = updateAnimationDomain(updatedState);+return updatedState;};/* eslint-enable max-statements */@@ -1289,6 +1284,7 @@ function closeSpecificMapAtIndex(state, action) {* @public*/export const loadFilesUpdater = (state, action) => {+const {files} = action;const filesToLoad = files.map(fileBlob => processFileToLoad(fileBlob));// reader -> parser -> augment -> receiveVisData@@ -1310,34 +1306,16 @@ export const loadFilesUpdater = (state, action) => {);return addDataToMap(data);},- error => loadFilesErr(error)+ loadFilesErr)];return withTask(- {- ...state,- fileLoading: true- },+ state,loadFileTasks);};-/**- * Trigger loading file error- * @memberof visStateUpdaters- * @param {Object} state `visState`- * @param {Object} action action- * @param {*} action.error- * @returns {Object} nextState- * @public- */-export const loadFilesErrUpdater = (state, {error}) => ({- ...state,- fileLoading: false,- fileLoadingErr: error-});-/*** Helper function to update All layer domain and layer data of state* @memberof visStateUpdatersdiff --git a/src/styles/base.js b/src/styles/base.jsindex f18ba29b0..0e1e8b692 100644--- a/src/styles/base.js+++ b/src/styles/base.js@@ -253,11 +253,13 @@ export const notificationPanelItemHeight = 60;// Datagridconst columnWidth = 200;const cellHeaderHeight = 72;-const cellHeight = 48;+const cellHeight = 24;+const cellPaddingSide = 18;const extendCellHeight = 2 * cellHeight;const extendColumnWidth = 2 * columnWidth;const gridDefaultWidth = 800;const gridDefaultHeight = 600;+const gridPaddingSide = 24;// Floating Time displayconst timeDisplayBorderRadius = 32;@@ -1037,9 +1039,11 @@ export const theme = {extendColumnWidth,cellHeaderHeight,cellHeight,+ cellPaddingSide,extendCellHeight,gridDefaultWidth,gridDefaultHeight,+ gridPaddingSide,// time displaytimeDisplayBorderRadius,diff --git a/src/tasks/tasks.js b/src/tasks/tasks.jsindex 85d0f7058..1254cd587 100644--- a/src/tasks/tasks.js+++ b/src/tasks/tasks.js@@ -20,27 +20,36 @@import {taskCreator} from 'react-palm/tasks';import {json as requestJson} from 'd3-request';+import console from 'global/console';export const LOAD_FILE_TASK = taskCreator(- ({fileBlob, info, handler, processor}, success, error) =>- handler(fileBlob, processor)+ ({fileBlob, info, handler, processor}, success, error) => {+ console.time('loadFileTask')+ return handler(fileBlob, processor).then(result => {if (!result) {// TODO: capture in the UI and show message- throw new Error('fail to load data');+ error(new Error('File to load data, result is empty'));} else {// we are trying to standardize the shape of our return// since we start using the kepler.json format// result has both datasets and info// TODO: I think we should pass info to the handler and return// the same format back from the file handler+ console.timeEnd('loadFileTask')+if (result.datasets) { // this is coming from parsing keplergl.json filesuccess(result); // info is already part of datasets}success({datasets: {data: result, info}});}})- .catch(err => error(err)),+ .catch(err => {+ console.log(err);+ error(err)+ })++ },'LOAD_FILE_TASK');diff --git a/src/utils/data-utils.js b/src/utils/data-utils.jsindex 78ceccd42..01863bebd 100644--- a/src/utils/data-utils.js+++ b/src/utils/data-utils.js@@ -59,20 +59,23 @@ export function findMapBounds(layers) {res.push(l.meta.bounds);}return res;- }, [])+ }, []);// return null if no layer is availableif (availableLayerBounds.length === 0) {return null;}// merge bounds in each layer- const newBounds = availableLayerBounds.reduce((res, b) => {- return [- Math.min(res[0], b[0]),- Math.min(res[1], b[1]),- Math.max(res[2], b[2]),- Math.max(res[3], b[3])- ];- }, [MAX_LONGITUDE, MAX_LATITUDE, MIN_LONGITUDE, MIN_LATITUDE]);+ const newBounds = availableLayerBounds.reduce(+ (res, b) => {+ return [+ Math.min(res[0], b[0]),+ Math.min(res[1], b[1]),+ Math.max(res[2], b[2]),+ Math.max(res[3], b[3])+ ];+ },+ [MAX_LONGITUDE, MAX_LATITUDE, MIN_LONGITUDE, MIN_LATITUDE]+ );return newBounds;}/* eslint-enable max-statements */@@ -96,7 +99,7 @@ export function getLatLngBounds(points, idx, limit) {export function clamp([min, max], val) {return val <= min ? min : val >= max ? max : val;-};+}export function getSampleData(data, sampleSize = 500, getValue = d => d) {const sampleStep = Math.max(Math.floor(data.length / sampleSize), 1);@@ -117,7 +120,9 @@ export function timeToUnixMilli(value, format) {if (notNullorUndefined(value)) {return typeof value === 'string'? moment.utc(value, format).valueOf()- : format === 'x' ? value * 1000 : value;+ : format === 'x'+ ? value * 1000+ : value;}return null;}@@ -229,6 +234,25 @@ export function roundValToStep(minValue, step, val) {return Number(rounded);}+const identity = d => d;++export const FIELD_DISPLAY_FORMAT = {+ [ALL_FIELD_TYPES.string]: identity,+ [ALL_FIELD_TYPES.timestamp]: identity,+ [ALL_FIELD_TYPES.integer]: identity,+ [ALL_FIELD_TYPES.real]: identity,+ [ALL_FIELD_TYPES.boolean]: d => String(d),+ [ALL_FIELD_TYPES.date]: identity,+ [ALL_FIELD_TYPES.geojson]: d =>+ typeof d === 'string'+ ? d+ : isPlainObject(d)+ ? JSON.stringify(d)+ : Array.isArray(d)+ ? `[${String(d)}]`+ : ''+};+/*** Parse field value and type and return a string representation* @param {string} value the field value@@ -240,24 +264,17 @@ export const parseFieldValue = (value, type) => {return '';}- switch (type) {- case ALL_FIELD_TYPES.boolean:- return String(value);- case ALL_FIELD_TYPES.geojson:- return typeof value === 'string' ? value :- isPlainObject(value) ? JSON.stringify(value) :- Array.isArray(value) ? `[${String(value)}]` : '';- default:- return value;- }+ return FIELD_DISPLAY_FORMAT[type]+ ? FIELD_DISPLAY_FORMAT[type](value)+ : String(value);};const arrayMoveMutate = (array, from, to) => {- array.splice(to < 0 ? array.length + to : to, 0, array.splice(from, 1)[0]);+ array.splice(to < 0 ? array.length + to : to, 0, array.splice(from, 1)[0]);};export const arrayMove = (array, from, to) => {- array = array.slice();- arrayMoveMutate(array, from, to);- return array;+ array = array.slice();+ arrayMoveMutate(array, from, to);+ return array;};diff --git a/test/browser/components/data-table-modal-test.js b/test/browser/components/data-table-modal-test.jsindex fc0912c6e..ba0206085 100644--- a/test/browser/components/data-table-modal-test.js+++ b/test/browser/components/data-table-modal-test.js@@ -20,18 +20,26 @@import React from 'react';import test from 'tape';-import {mount} from 'enzyme';import {mountWithTheme} from 'test/helpers/component-utils';-import DataTableModalFactory, {DatasetTabs, DatasetModalTab} from- 'components/modals/data-table-modal';-import DataGridFactory, {FieldHeaderFactory, CellFactory} from 'components/common/datagrid';+import DataTableModalFactory, {+ DatasetTabs,+ DatasetModalTab+} from 'components/modals/data-table-modal';+import DataGridFactory, {+ FieldHeaderFactory,+ CellFactory+} from 'components/common/datagrid';const FieldHeader = FieldHeaderFactory();const Cell = CellFactory();const DataGrid = DataGridFactory(FieldHeader, Cell);const DataTableModal = DataTableModalFactory(DataGrid);import {testFields, testAllData} from 'test/fixtures/test-csv-data';+import {+ geoStyleFields,+ geoStyleRows+} from 'test/fixtures/geojson';// This makes sure react-virtualized renders the full gridconst WIDTH = 1400;@@ -39,14 +47,9 @@ const HEIGHT = 800;const rows = 10;/* eslint-disable max-statements */-test('Components -> DataTableModal.render', t => {+test('Components -> DataTableModal.render: csv', t => {t.doesNotThrow(() => {- mountWithTheme(- <DataTableModal- width={WIDTH}- height={HEIGHT}- />- );+ mountWithTheme(<DataTableModal width={WIDTH} height={HEIGHT} />);}, 'Show not fail without data');const wrapper = mountWithTheme(@@ -66,12 +69,32 @@ test('Components -> DataTableModal.render', t => {/>);- t.equal(wrapper.find(DataTableModal).length, 1, 'should render DataTableModal data');+ t.equal(+ wrapper.find(DataTableModal).length,+ 1,+ 'should render DataTableModal data'+ );t.equal(wrapper.find(DatasetTabs).length, 1, 'should render DatasetTabs');- t.equal(wrapper.find(DatasetModalTab).length, 1, 'should render 1 dataset-modal-catalog');- t.equal(wrapper.find('Header').length, testFields.length, `should render ${testFields.length} headers`);- t.equal(wrapper.find('Cell').length, testFields.length * rows, `should render ${testFields.length * rows} cells`);- t.equal(wrapper.find('StyledComponent.cell.boolean').length, 10, 'should render 10 cells');+ t.equal(+ wrapper.find(DatasetModalTab).length,+ 1,+ 'should render 1 dataset-modal-catalog'+ );+ t.equal(+ wrapper.find('Header').length,+ testFields.length,+ `should render ${testFields.length} headers`+ );+ t.equal(+ wrapper.find('Cell').length,+ testFields.length * rows,+ `should render ${testFields.length * rows} cells`+ );+ t.equal(+ wrapper.find('StyledComponent.cell.boolean').length,+ 10,+ 'should render 10 boolean cells'+ );const expectedRows = {0: [@@ -109,8 +132,104 @@ test('Components -> DataTableModal.render', t => {t.equal(cells.length, 11, 'should render 11 cells');for (let c = 0; c < cells.length; c++) {- const cellText = cells.at(c).find('span').text();- t.equal(cellText, expectedRow[c], `should render cell ${expectedRow[c]} correctly`);+ const cellText = cells+ .at(c)+ .find('span')+ .text();+ t.equal(+ cellText,+ expectedRow[c],+ `should render cell ${expectedRow[c]} correctly`+ );+ }+ });++ t.end();+});++test('Components -> DataTableModal.render: csv', t => {+ const wrapper = mountWithTheme(+ <DataTableModal+ width={WIDTH}+ height={HEIGHT}+ datasets={{+ smoothie: {+ id: 'smoothie',+ allData: geoStyleRows,+ fields: geoStyleFields,+ color: [113, 113, 113],+ data: geoStyleRows+ }+ }}+ dataId="smoothie"+ />+ );++ t.equal(+ wrapper.find(DataTableModal).length,+ 1,+ 'should render DataTableModal data'+ );+ t.equal(wrapper.find(DatasetTabs).length, 1, 'should render DatasetTabs');+ t.equal(+ wrapper.find(DatasetModalTab).length,+ 1,+ 'should render 1 dataset-modal-catalog'+ );+ t.equal(+ wrapper.find('Header').length,+ geoStyleFields.length,+ `should render ${geoStyleFields.length} headers`+ );+ t.equal(+ wrapper.find('Cell').length,+ geoStyleFields.length * geoStyleRows.length,+ `should render ${geoStyleFields.length * geoStyleRows.length} cells`+ );++ const expectedRows = {+ 0: [+ '{"type":"Feature","properties":{"fillColor":[1,2,3],"lineColor":[4,5,6],"lineWidth":1,"elevation":10,"radius":5},"geometry":{"type":"Point","coordinates":[[-122,37]]}}',+ '[1,2,3]',+ '[4,5,6]',+ '1',+ '10',+ '5'+ ],+ 1: [+ '{"type":"Feature","properties":{"fillColor":[7,8,9],"lineColor":[4,5,6],"lineWidth":3,"elevation":10,"radius":5},"geometry":{"type":"Point","coordinates":[[-122,37]]}}',+ '[7,8,9]',+ '[4,5,6]',+ '3',+ '10',+ '5'+ ],+ 2: [+ '{"type":"Feature","properties":{"fillColor":[1,2,3],"lineColor":[4,5,6],"lineWidth":4,"elevation":10,"radius":5},"geometry":{"type":"Point","coordinates":[[-122,37]]}}',+ '[1,2,3]',+ '[4,5,6]',+ '4',+ '10',+ '5'+ ]+ };++ Object.entries(expectedRows).forEach(keyAndRow => {+ const [index, expectedRow] = keyAndRow;++ const cells = wrapper.find(`.row-${index}`);+ t.equal(cells.length, 6, 'should render 6 cells');++ for (let c = 0; c < cells.length; c++) {+ const cellText = cells+ .at(c)+ .find('span')+ .text();+ t.equal(+ cellText,+ expectedRow[c],+ `should render cell ${expectedRow[c]} correctly`+ );}});diff --git a/test/fixtures/geojson.js b/test/fixtures/geojson.jsindex 4ea660da4..5d5f1b39a 100644--- a/test/fixtures/geojson.js+++ b/test/fixtures/geojson.js@@ -308,3 +308,58 @@ export const geoBounds = [-122.39166672864975,37.79427854456892];++export const geoJsonWithStyle = {+ type: 'FeatureCollection',+ features: [+ {+ type: 'Feature',+ properties: {+ fillColor: [1,2,3],+ lineColor: [4,5,6],+ lineWidth: 1,+ elevation: 10,+ radius: 5+ },+ geometry: {type: 'Point', coordinates: [[-122, 37]]}+ },+ {+ type: 'Feature',+ properties: {+ fillColor: [7,8,9],+ lineColor: [4,5,6],+ lineWidth: 3,+ elevation: 10,+ radius: 5+ },+ geometry: {type: 'Point', coordinates: [[-122, 37]]}+ },+ {+ type: 'Feature',+ properties: {+ fillColor: [1,2,3],+ lineColor: [4,5,6],+ lineWidth: 4,+ elevation: 10,+ radius: 5+ },+ geometry: {type: 'Point', coordinates: [[-122, 37]]}+ }+ ]+};++// parsed fields and rows+export const geoStyleFields = [+ {name: '_geojson', format: '', tableFieldIndex: 1, type: 'geojson'},+ {name: 'fillColor', format: '', tableFieldIndex: 2, type: 'geojson'},+ {name: 'lineColor', format: '', tableFieldIndex: 3, type: 'geojson'},+ {name: 'lineWidth', format: '', tableFieldIndex: 4, type: 'integer'},+ {name: 'elevation', format: '', tableFieldIndex: 5, type: 'integer'},+ {name: 'radius', format: '', tableFieldIndex: 6, type: 'integer'}+];++export const geoStyleRows = [+ [geoJsonWithStyle.features[0], [1, 2, 3], [4, 5, 6], 1, 10, 5],+ [geoJsonWithStyle.features[1], [7, 8, 9], [4, 5, 6], 3, 10, 5],+ [geoJsonWithStyle.features[2], [1, 2, 3], [4, 5, 6], 4, 10, 5]+];diff --git a/test/node/reducers/ui-state-test.js b/test/node/reducers/ui-state-test.jsindex b64778779..b068ee98f 100644--- a/test/node/reducers/ui-state-test.js+++ b/test/node/reducers/ui-state-test.js@@ -31,16 +31,24 @@ import {setExportSelectedDataset,setExportDataType,setExportFiltered,- addNotification+ addNotification,+ loadFilesErrUpdater} from 'actions/ui-state-actions';-import reducer, {uiStateReducerFactory} from 'reducers/ui-state';+import {loadFiles, loadFilesErr} from 'actions/vis-state-actions';+import reducer, {uiStateReducerFactory} from 'reducers/ui-state';import {INITIAL_UI_STATE} from 'reducers/ui-state-updaters';-import {RATIOS, RESOLUTIONS, EXPORT_DATA_TYPE} from 'constants/default-settings';-import {DEFAULT_NOTIFICATION_TOPICS, DEFAULT_NOTIFICATION_TYPES} from 'constants/default-settings';+import {+ RATIOS,+ RESOLUTIONS,+ EXPORT_DATA_TYPE+} from 'constants/default-settings';+import {+ DEFAULT_NOTIFICATION_TOPICS,+ DEFAULT_NOTIFICATION_TYPES+} from 'constants/default-settings';import {removeNotification} from 'actions/ui-state-actions';test('#uiStateReducer', t => {-t.deepEqual(reducer(undefined, {}),{...INITIAL_UI_STATE, initialState: {}},@@ -61,7 +69,6 @@ test('#uiStateReducerFactory', t => {});test('#uiStateReducer -> TOGGLE_SIDE_PANEL', t => {-const newReducer = reducer(INITIAL_UI_STATE, toggleSidePanel('foo'));const expectedState = {@@ -93,7 +100,6 @@ test('#uiStateReducer -> TOGGLE_SIDE_PANEL', t => {});test('#uiStateReducer -> OPEN_DELETE_MODAL', t => {-const newReducer = reducer(INITIAL_UI_STATE, openDeleteModal('chai'));const expectedState = {@@ -102,14 +108,20 @@ test('#uiStateReducer -> OPEN_DELETE_MODAL', t => {datasetKeyToRemove: 'chai'};- t.deepEqual(newReducer, expectedState, 'should open delete data modal and save key to remove');+ t.deepEqual(+ newReducer,+ expectedState,+ 'should open delete data modal and save key to remove'+ );t.end();});test('#uiStateReducer -> SET_RATIO', t => {-- const newReducer = reducer(INITIAL_UI_STATE, setRatio({ratio: RATIOS.SIXTEEN_BY_NINE}));+ const newReducer = reducer(+ INITIAL_UI_STATE,+ setRatio({ratio: RATIOS.SIXTEEN_BY_NINE})+ );const expectedState = {...INITIAL_UI_STATE,@@ -119,14 +131,20 @@ test('#uiStateReducer -> SET_RATIO', t => {}};- t.deepEqual(newReducer, expectedState, 'should set the ratio to SIXTEEN_BY_NINE');+ t.deepEqual(+ newReducer,+ expectedState,+ 'should set the ratio to SIXTEEN_BY_NINE'+ );t.end();});test('#uiStateReducer -> SET_RESOLUTION', t => {-- const newReducer = reducer(INITIAL_UI_STATE, setResolution({resolution: RESOLUTIONS.TWO_X}));+ const newReducer = reducer(+ INITIAL_UI_STATE,+ setResolution({resolution: RESOLUTIONS.TWO_X})+ );const expectedState = {...INITIAL_UI_STATE,@@ -142,7 +160,6 @@ test('#uiStateReducer -> SET_RESOLUTION', t => {});test('#uiStateReducer -> TOGGLE_LEGEND', t => {-const newReducer = reducer(INITIAL_UI_STATE, toggleLegend());const expectedState = {@@ -159,27 +176,25 @@ test('#uiStateReducer -> TOGGLE_LEGEND', t => {});test('#uiStateReducer -> TOGGLE_MAP_CONTROL', t => {+ const newReducer = reducer(INITIAL_UI_STATE, toggleMapControl('mapLegend'));- const newReducer = reducer(INITIAL_UI_STATE, toggleMapControl('mapLegend'));-- const expectedState = {- ...INITIAL_UI_STATE,- mapControls: {- ...INITIAL_UI_STATE.mapControls,- mapLegend: {- show: INITIAL_UI_STATE.mapControls.mapLegend.show,- active: !INITIAL_UI_STATE.mapControls.mapLegend.active- },- }- };+ const expectedState = {+ ...INITIAL_UI_STATE,+ mapControls: {+ ...INITIAL_UI_STATE.mapControls,+ mapLegend: {+ show: INITIAL_UI_STATE.mapControls.mapLegend.show,+ active: !INITIAL_UI_STATE.mapControls.mapLegend.active+ }+ }+ };- t.deepEqual(newReducer, expectedState, 'should set map legend to be seen');+ t.deepEqual(newReducer, expectedState, 'should set map legend to be seen');- t.end();+ t.end();});test('#uiStateReducer -> SET_EXPORT_SELECTED_DATASET', t => {-const newReducer = reducer(INITIAL_UI_STATE, setExportSelectedDataset('a'));const expectedState = {@@ -196,8 +211,10 @@ test('#uiStateReducer -> SET_EXPORT_SELECTED_DATASET', t => {});test('#uiStateReducer -> SET_EXPORT_DATA_TYPE', t => {-- const newReducer = reducer(INITIAL_UI_STATE, setExportDataType(EXPORT_DATA_TYPE.JSON));+ const newReducer = reducer(+ INITIAL_UI_STATE,+ setExportDataType(EXPORT_DATA_TYPE.JSON)+ );const expectedState = {...INITIAL_UI_STATE,@@ -213,7 +230,6 @@ test('#uiStateReducer -> SET_EXPORT_DATA_TYPE', t => {});test('#uiStateReducer -> SET_EXPORT_FILTERED', t => {-const newReducer = reducer(INITIAL_UI_STATE, setExportFiltered(false));const expectedState = {@@ -230,43 +246,101 @@ test('#uiStateReducer -> SET_EXPORT_FILTERED', t => {});test('#uiStateReducer -> ADD_NOTIFICATION', t => {- const newState = reducer(INITIAL_UI_STATE, addNotification({- type: DEFAULT_NOTIFICATION_TYPES.error,- message: 'TEST',- topic: DEFAULT_NOTIFICATION_TOPICS.global,- id: 'test-1'- }));-- t.equal(newState.notifications.length, 1, 'AddNotification should add one new notification');- t.deepEqual(newState.notifications[0], {- type: DEFAULT_NOTIFICATION_TYPES.error,- message: 'TEST',- topic: DEFAULT_NOTIFICATION_TOPICS.global,- id: 'test-1'- }, 'AddNotification should have propagated data correctly ');+ const newState = reducer(+ INITIAL_UI_STATE,+ addNotification({+ type: DEFAULT_NOTIFICATION_TYPES.error,+ message: 'TEST',+ topic: DEFAULT_NOTIFICATION_TOPICS.global,+ id: 'test-1'+ })+ );++ t.equal(+ newState.notifications.length,+ 1,+ 'AddNotification should add one new notification'+ );+ t.deepEqual(+ newState.notifications[0],+ {+ type: DEFAULT_NOTIFICATION_TYPES.error,+ message: 'TEST',+ topic: DEFAULT_NOTIFICATION_TOPICS.global,+ id: 'test-1'+ },+ 'AddNotification should have propagated data correctly '+ );t.end();});test('#uiStateReducer -> REMOVE_NOTIFICATION', t => {- const newState = reducer(INITIAL_UI_STATE, addNotification({- type: DEFAULT_NOTIFICATION_TYPES.error,- message: 'TEST',- topic: DEFAULT_NOTIFICATION_TOPICS.global,- id: 'test-1'- }));-- t.equal(newState.notifications.length, 1, 'AddNotification should add one new notification');- t.deepEqual(newState.notifications[0], {- type: DEFAULT_NOTIFICATION_TYPES.error,- message: 'TEST',- topic: DEFAULT_NOTIFICATION_TOPICS.global,- id: 'test-1'- }, 'AddNotification should have propagated data correctly ');+ const newState = reducer(+ INITIAL_UI_STATE,+ addNotification({+ type: DEFAULT_NOTIFICATION_TYPES.error,+ message: 'TEST',+ topic: DEFAULT_NOTIFICATION_TOPICS.global,+ id: 'test-1'+ })+ );++ t.equal(+ newState.notifications.length,+ 1,+ 'AddNotification should add one new notification'+ );+ t.deepEqual(+ newState.notifications[0],+ {+ type: DEFAULT_NOTIFICATION_TYPES.error,+ message: 'TEST',+ topic: DEFAULT_NOTIFICATION_TOPICS.global,+ id: 'test-1'+ },+ 'AddNotification should have propagated data correctly '+ );const nextState = reducer(newState, removeNotification('test-1'));- t.equal(nextState.notifications.length, 0, 'RemoveNotification removed one notification');+ t.equal(+ nextState.notifications.length,+ 0,+ 'RemoveNotification removed one notification'+ );++ t.end();+});++test('#uiStateReducer -> LOAD_FILES_ERR', t => {+ const newState = reducer(INITIAL_UI_STATE, loadFiles());+ t.equal(+ newState.loadFiles.fileLoading,+ true,+ 'should set fileLoading to true'+ );++ const newState1 = reducer(+ newState,+ loadFilesErr(new Error('this is an error'))+ );+ const expectedId = newState1.notifications.length ? newState1.notifications[0].id : 'error'+ t.equal(+ newState1.loadFiles.fileLoading,+ false,+ 'should set fileLoading to false when loadFilesErr'+ );+ t.deepEqual(+ newState1.notifications,+ [{+ type: 'error',+ topic: 'global',+ message: 'this is an error',+ id: expectedId+ }],+ 'should add an error notification'+ );t.end();});diff --git a/test/node/utils/data-processor-test.js b/test/node/utils/data-processor-test.jsindex 46dc1a41b..ff3029749 100644--- a/test/node/utils/data-processor-test.js+++ b/test/node/utils/data-processor-test.js@@ -19,80 +19,125 @@// THE SOFTWARE.import test from 'tape';-import testData, {dataWithNulls, parsedDataWithNulls, testFields, testAllData, wktCsv, wktCsvFields} from 'test/fixtures/test-csv-data';-import {geojsonData, fields as geojsonFields, rows as geojsonRows} from 'test/fixtures/geojson';+import sinon from 'sinon';+import {console as Console} from 'global/window';+import {DATA_TYPES} from 'type-analyzer';++import testData, {+ dataWithNulls,+ parsedDataWithNulls,+ testFields,+ testAllData,+ wktCsv,+ wktCsvFields+} from 'test/fixtures/test-csv-data';+import {+ geojsonData,+ geoJsonWithStyle,+ geoStyleFields,+ geoStyleRows,+ fields as geojsonFields,+ rows as geojsonRows+} from 'test/fixtures/geojson';import {+ ACCEPTED_ANALYZER_TYPES,+ analyzerTypeToFieldType,+ formatCsv,getFieldsFromData,getSampleForTypeAnalyze,parseCsvRowsByFieldType,processCsvData,- processGeojson+ processGeojson,+ processRowObject,+ validateInputData} from 'processors/data-processor';-import {- ALL_FIELD_TYPES-} from 'constants/default-settings';+import {ALL_FIELD_TYPES} from 'constants/default-settings';test('Processor -> getFieldsFromData', t => {- const data = [{- time: '2016-09-17 00:09:55',- trip_epoch: '1472688000000',- time_str: 'January 1st 2017 11:00pm ',- value: '4',- surge: '1.2',- isTrip: 'true',- zeroOnes: '0'- }, {- time: '2016-09-17 00:30:08',- trip_epoch: '1472860800000',- time_str: 'January 1st 2017 11:01pm ',- value: '3',- surge: null,- isTrip: 'false',- zeroOnes: '1'- }, {- time: null,- trip_epoch: null,- time_str: 'January 1st, 2017 11:02pm ',- value: '2',- surge: '1.3',- isTrip: null,- zeroOnes: '1'- }, {- time: null,- trip_epoch: null,- time_str: 'January 1st, 2017 11:02pm ',- value: '0',- surge: '1.4',- isTrip: null,- zeroOnes: '0'- }];+ const data = [+ {+ time: '2016-09-17 00:09:55',+ trip_epoch: '1472688000000',+ time_str: 'January 1st 2017 11:00pm ',+ value: '4',+ surge: '1.2',+ isTrip: 'true',+ zeroOnes: '0'+ },+ {+ time: '2016-09-17 00:30:08',+ trip_epoch: '1472860800000',+ time_str: 'January 1st 2017 11:01pm ',+ value: '3',+ surge: null,+ isTrip: 'false',+ zeroOnes: '1'+ },+ {+ time: null,+ trip_epoch: null,+ time_str: 'January 1st, 2017 11:02pm ',+ value: '2',+ surge: '1.3',+ isTrip: null,+ zeroOnes: '1'+ },+ {+ time: null,+ trip_epoch: null,+ time_str: 'January 1st, 2017 11:02pm ',+ value: '0',+ surge: '1.4',+ isTrip: null,+ zeroOnes: '0'+ }+ ];const headerRow = Object.keys(data[0]);const fields = getFieldsFromData(data, headerRow);- const expectedFieldTypes =- ['timestamp', 'timestamp', 'timestamp', 'integer', 'real', 'boolean', 'integer'];+ const expectedFieldTypes = [+ 'timestamp',+ 'timestamp',+ 'timestamp',+ 'integer',+ 'real',+ 'boolean',+ 'integer'+ ];fields.forEach((f, i) =>- t.equal(f.type, expectedFieldTypes[i],- `should find field type as ${expectedFieldTypes[i]}`)+ t.equal(+ f.type,+ expectedFieldTypes[i],+ `should find field type as ${expectedFieldTypes[i]}`+ ));t.end();});test('Processor -> processCsvData', t => {+ t.throws(() => processCsvData(''), 'should throw if csv is empty');// load sample dataset csv as textconst {fields, rows} = processCsvData(testData);- t.equal(rows.length, testAllData.length, `should return ${testAllData.length} rows`);+ t.equal(+ rows.length,+ testAllData.length,+ `should return ${testAllData.length} rows`+ );t.deepEqual(fields, testFields, 'should parse fields correctly');t.deepEqual(rows, testAllData, 'should parse rows correctly');fields.forEach((f, i) => {- t.deepEqual(f, testFields[i], `should parse correct field ${testFields[i].name}`);+ t.deepEqual(+ f,+ testFields[i],+ `should parse correct field ${testFields[i].name}`+ );});rows.forEach((r, i) => {@@ -102,12 +147,41 @@ test('Processor -> processCsvData', t => {t.end();});+test('Processor -> processCsvData: duplicated field name', t => {+ const testData1 = `column1,column1,column1,column2\na,b,c,d\nc,d,e,f`;++ // load sample dataset csv as text+ const result = processCsvData(testData1);++ const expectedResult = {+ fields: [+ {name: 'column1', format: '', tableFieldIndex: 1, type: 'string'},+ {name: 'column1-0', format: '', tableFieldIndex: 2, type: 'string'},+ {name: 'column1-1', format: '', tableFieldIndex: 3, type: 'string'},+ {name: 'column2', format: '', tableFieldIndex: 4, type: 'string'}+ ],+ rows: [['a', 'b', 'c', 'd'], ['c', 'd', 'e', 'f']]+ };++ t.deepEqual(+ result,+ expectedResult,+ `should return ${testAllData.length} rows`+ );++ t.end();+});+test('Processor -> processCsvData -> with nulls', t => {const {fields, rows} = processCsvData(dataWithNulls);t.deepEqual(fields, testFields, 'should parse fields correctly');fields.forEach((f, i) => {- t.deepEqual(f, testFields[i], `should parse correct field ${testFields[i].name}`);+ t.deepEqual(+ f,+ testFields[i],+ `should parse correct field ${testFields[i].name}`+ );});t.deepEqual(rows, parsedDataWithNulls, 'should parse rows correctly');@@ -120,13 +194,16 @@ test('Processor -> processCsvData -> with nulls', t => {test('Processor -> processCsv.wkt', t => {const {fields} = processCsvData(wktCsv);- t.deepEqual(fields, wktCsvFields, 'should find geometry fields as type:geojson');+ t.deepEqual(+ fields,+ wktCsvFields,+ 'should find geometry fields as type:geojson'+ );t.end();});test('Processor => processGeojson', t => {-const {fields, rows} = processGeojson(geojsonData);t.deepEqual(fields, geojsonFields, 'should format geojson fields');@@ -135,9 +212,106 @@ test('Processor => processGeojson', t => {t.end();});+test('Processor => processGeojson: with style property', t => {+ const {fields, rows} = processGeojson(geoJsonWithStyle);-test('Processor -> parseCsvRowsByFieldType -> real', t => {+ t.deepEqual(fields, geoStyleFields, 'should preserve objects in geojson properties');+ t.deepEqual(rows, geoStyleRows, 'should preserve objects in geojson properties');+ t.end();+});++test('Processor => processGeojson:invalid geojson', t => {+ t.throws(+ () => processGeojson({fields: [], rows: []}),+ 'Should throw error with invalid geojson type'+ );++ t.end();+});++test('Processor => processGeojson: parse rows', t => {+ const testGeoData = {+ type: 'FeatureCollection',+ features: [+ {+ type: 'Feature',+ properties: {TRIPS: '11', RATE: 'a', TIME: '1570749707'},+ geometry: {type: 'Point', coordinates: [[-122, 37]]}+ },+ {+ type: 'Feature',+ properties: {TRIPS: '10', RATE: 'b', TIME: '1570749707'},+ geometry: {type: 'Point', coordinates: [[-122, 37]]}+ },+ {+ type: 'Feature',+ properties: {TRIPS: '9', RATE: 'b', TIME: '1570749707'},+ geometry: {type: 'Point', coordinates: [[-122, 37]]}+ }+ ]+ };++ const expectedFields = [+ {name: '_geojson', format: '', tableFieldIndex: 1, type: 'geojson'},+ {name: 'TRIPS', format: '', tableFieldIndex: 2, type: 'integer'},+ {name: 'RATE', format: '', tableFieldIndex: 3, type: 'string'},+ {name: 'TIME', format: 'x', tableFieldIndex: 4, type: 'timestamp'}+ ];++ const expectedRows = [+ [+ {+ type: 'Feature',+ properties: {TRIPS: 11, RATE: 'a', TIME: 1570749707},+ geometry: {type: 'Point', coordinates: [[-122, 37]]}+ },+ 11,+ 'a',+ 1570749707+ ],+ [+ {+ type: 'Feature',+ properties: {TRIPS: 10, RATE: 'b', TIME: 1570749707},+ geometry: {type: 'Point', coordinates: [[-122, 37]]}+ },+ 10,+ 'b',+ 1570749707+ ],+ [+ {+ type: 'Feature',+ properties: {TRIPS: 9, RATE: 'b', TIME: 1570749707},+ geometry: {type: 'Point', coordinates: [[-122, 37]]}+ },+ 9,+ 'b',+ 1570749707+ ]+ ];+ const result = processGeojson(testGeoData);+ t.deepEqual(+ Object.keys(result),+ ['fields', 'rows'],+ 'should contain fields and rows'+ );+ t.deepEqual(+ result.fields,+ expectedFields,+ 'should parse correct fields when geojson input contain string'+ );+ t.deepEqual(+ result.rows,+ expectedRows,+ 'should parse correct rows when geojson input contain string'+ );++ t.end();+});++test('Processor -> parseCsvRowsByFieldType -> real', t => {const field = {type: ALL_FIELD_TYPES.real};@@ -164,42 +338,26 @@ test('Processor -> parseCsvRowsByFieldType -> real', t => {[1550.0]];- parseCsvRowsByFieldType(rows, field, 0);+ parseCsvRowsByFieldType(rows, -1, field, 0);t.same(rows, expected, 'should parsed reals properly');t.end();});test('Processor -> parseCsvRowsByFieldType -> integer', t => {-const field = {type: ALL_FIELD_TYPES.integer};- const rows = [- ['0'],- ['1'],- ['-1'],- ['155'],- [' 155 '],- [' 155 xyz']- ];+ const rows = [['0'], ['1'], ['-1'], ['155'], [' 155 '], [' 155 xyz']];- const expected = [- [0],- [1],- [-1],- [155],- [155],- [155]- ];+ const expected = [[0], [1], [-1], [155], [155], [155]];- parseCsvRowsByFieldType(rows, field, 0);+ parseCsvRowsByFieldType(rows, -1, field, 0);t.same(rows, expected, 'should parsed ints properly');t.end();});test('Processor -> parseCsvRowsByFieldType -> boolean', t => {-const field = {type: ALL_FIELD_TYPES.boolean};@@ -227,13 +385,13 @@ test('Processor -> parseCsvRowsByFieldType -> boolean', t => {[true]];- parseCsvRowsByFieldType(rows, field, 0);+ parseCsvRowsByFieldType(rows, -1, field, 0);t.same(rows, expected, 'should parsed boolean properly');t.end();});-test('dataUtils -> getSampleForTypeAnalyze', t => {- const fields =['string','int','bool','time'];+test('Processor -> getSampleForTypeAnalyze', t => {+ const fields = ['string', 'int', 'bool', 'time'];const allData = [['a', 0, true, null],@@ -248,33 +406,250 @@ test('dataUtils -> getSampleForTypeAnalyze', t => {];const sample = getSampleForTypeAnalyze({fields, allData, sampleCount: 5});- const expected = [{- string: 'a',- int: 0,- bool: true,- time: '2017-01-01'- }, {- string: 'b',- int: 2,- bool: false,- time: '2017-01-02'- }, {- string: 'c',- int: 3,- bool: true,- time: '2017-01-03'- }, {- string: 'd',- int: 1,- bool: false,- time: '2017-01-04'- }, {- string: 'e',- int: 6,- bool: false,- time: null- }];+ const expected = [+ {+ string: 'a',+ int: 0,+ bool: true,+ time: '2017-01-01'+ },+ {+ string: 'b',+ int: 2,+ bool: false,+ time: '2017-01-02'+ },+ {+ string: 'c',+ int: 3,+ bool: true,+ time: '2017-01-03'+ },+ {+ string: 'd',+ int: 1,+ bool: false,+ time: '2017-01-04'+ },+ {+ string: 'e',+ int: 6,+ bool: false,+ time: null+ }+ ];t.deepEqual(sample, expected, 'Should find correct sample for type analyzer');t.end();});++test('Processor -> validateInputData', t => {+ t.equal(validateInputData(null), null, 'Should throw error if data is null');+ t.equal(+ validateInputData({rows: 'hello'}),+ null,+ 'Should throw error if data.rows is null'+ );+ t.equal(+ validateInputData({rows: [], fields: null}),+ null,+ 'Should throw error if data.fields is null'+ );++ const cases = [+ {+ input: {+ rows: [[1], [2], [3]],+ fields: ['a']+ },+ expected: {+ rows: [[1], [2], [3]],+ fields: [{type: ALL_FIELD_TYPES.integer, format: '', name: 'column_0'}]+ },+ msg: 'should re generate field if not an object'+ },+ {+ input: {+ rows: [[1], [2], [3]],+ fields: [{type: ALL_FIELD_TYPES.integer, format: ''}]+ },+ expected: {+ rows: [[1], [2], [3]],+ fields: [{type: ALL_FIELD_TYPES.integer, format: '', name: 'column_0'}]+ },+ msg: 'should reassign field name'+ },+ {+ input: {+ rows: [[1], [2], [3]],+ fields: [{type: 'hello', format: '', name: 'taro'}]+ },+ expected: {+ rows: [[1], [2], [3]],+ fields: [{type: ALL_FIELD_TYPES.integer, format: '', name: 'taro'}]+ },+ msg: 'should reassign field type'+ },+ {+ input: {+ rows: [+ ['2018-09-01 00:00'],+ ['2018-09-01 01:00'],+ ['2018-09-01 02:00']+ ],+ fields: [{type: ALL_FIELD_TYPES.timestamp, format: '', name: 'taro'}]+ },+ expected: {+ rows: [+ ['2018-09-01 00:00'],+ ['2018-09-01 01:00'],+ ['2018-09-01 02:00']+ ],+ fields: [+ {+ type: ALL_FIELD_TYPES.timestamp,+ format: 'YYYY-M-D H:m',+ name: 'taro'+ }+ ]+ },+ msg: 'should reassign field type'+ }+ ];++ cases.forEach(({input, expected, msg}) => {+ t.deepEqual(validateInputData(input), expected, msg);+ });++ t.end();+});++test('Processor -> processRowObject', t => {+ t.equal(+ processRowObject({}),+ null,+ 'Should return null when rawData is empty'+ );+ const cases = [+ {+ input: [+ {a: 1, b: 'c', c: true, d: '1.2'},+ {a: 2, b: 'c', c: false, d: '1.3'},+ {a: 3, b: 'd', c: true, d: '1.4'}+ ],+ expected: {+ rows: [[1, 'c', true, 1.2], [2, 'c', false, 1.3], [3, 'd', true, 1.4]],+ fields: [+ {+ name: 'a',+ type: 'integer',+ format: '',+ tableFieldIndex: 1+ },+ {+ name: 'b',+ type: 'string',+ format: '',+ tableFieldIndex: 2+ },+ {+ name: 'c',+ type: 'boolean',+ format: '',+ tableFieldIndex: 3+ },+ {+ name: 'd',+ type: 'real',+ format: '',+ tableFieldIndex: 4+ }+ ]+ },+ msg: 'should parse correct row objects'+ }+ ];++ cases.forEach(({input, expected, msg}) => {+ t.deepEqual(processRowObject(input), expected, msg);+ });+ t.end();+});++test('Processor -> formatCsv', t => {+ const geojsonFc = {+ type: 'FeatureCollection',+ features: [+ {+ type: 'Feature',+ properties: {TRIPS: '11'},+ geometry: {type: 'Point', coordinates: [[-122, 37]]}+ },+ {+ type: 'Feature',+ properties: {TRIPS: '10'},+ geometry: {type: 'Point', coordinates: [[-122, 37]]}+ },+ {+ type: 'Feature',+ properties: {TRIPS: '9'},+ geometry: {type: 'Point', coordinates: [[-122, 37]]}+ }+ ]+ };++ const cases = [+ {+ input: `gps_data.lat,gps_data.types,epoch,has_result,id,begintrip_ts_local,date+ 29.9900937,driver_analytics,1472688000000,False,1,2016-10-01 09:41:39+00:00,2016-09-23+ 29.9927699,driver_analytics,1472688000000,False,2,2016-10-01 16:46:37+00:00,2016-09-23+ 29.9907261,driver_analytics,1472688000000,False,3,,2016-09-23`,+ expected:+ `gps_data.lat,gps_data.types,epoch,has_result,id,begintrip_ts_local,date\n` ++ `29.9900937,driver_analytics,1472688000000,false,1,2016-10-01 09:41:39+00:00,2016-09-23\n` ++ `29.9927699,driver_analytics,1472688000000,false,2,2016-10-01 16:46:37+00:00,2016-09-23\n` ++ `29.9907261,driver_analytics,1472688000000,false,3,,2016-09-23`,+ processor: processCsvData,+ msg: 'should format correct csv'+ },+ {+ input: geojsonFc,+ expected:+ '_geojson,TRIPS\n"{""type"":""Feature"",""properties"":{""TRIPS"":11},""geometry"":{""type"":""Point"",""coordinates"":[[-122,37]]}}",11\n"{""type"":""Feature"",""properties"":{""TRIPS"":10},""geometry"":{""type"":""Point"",""coordinates"":[[-122,37]]}}",10\n"{""type"":""Feature"",""properties"":{""TRIPS"":9},""geometry"":{""type"":""Point"",""coordinates"":[[-122,37]]}}",9',+ processor: processGeojson,+ msg: 'should format correct csv from geojsonInput'+ }+ ];++ cases.forEach(({input, expected, msg, processor}) => {+ const {fields, rows} = processor(input);++ t.deepEqual(formatCsv(rows, fields), expected, msg);+ });+ t.end();+});++test('Processor -> analyzerTypeToFieldType', t => {+ Object.keys(DATA_TYPES).forEach(atype => {+ const spy = sinon.spy(Console, 'warn');++ if (!ACCEPTED_ANALYZER_TYPES.includes(atype)) {+ t.equal(+ analyzerTypeToFieldType(atype),+ 'string',+ 'should return string if type not recognized'+ );+ t.ok(spy.calledOnce, `should warn when pass unrecognized type ${atype}`);+ } else {+ const fieldType = analyzerTypeToFieldType(atype);+ t.ok(+ ALL_FIELD_TYPES[fieldType],+ `should assign ${atype} to one of ALL_FIELD_TYPES`+ );+ }++ spy.restore();+ });++ t.end();+});diff --git a/yarn.lock b/yarn.lockindex 94ecf6c6d..19ca2e5d0 100644--- a/yarn.lock+++ b/yarn.lock@@ -1726,10 +1726,6 @@ babel-plugin-syntax-jsx@^6.18.0:version "6.18.0"resolved "https://registry.yarnpkg.com/babel-plugin-syntax-jsx/-/babel-plugin-syntax-jsx-6.18.0.tgz#0af32a9a6e13ca7a3fd5069e62d7b0f58d0d8946"-babel-plugin-syntax-object-rest-spread@^6.8.0:- version "6.13.0"- resolved "https://registry.yarnpkg.com/babel-plugin-syntax-object-rest-spread/-/babel-plugin-syntax-object-rest-spread-6.13.0.tgz#fd6536f2bce13836ffa3a5458c4903a597bb3bf5"-babel-plugin-transform-builtin-extend@^1.1.0:version "1.1.2"resolved "https://registry.yarnpkg.com/babel-plugin-transform-builtin-extend/-/babel-plugin-transform-builtin-extend-1.1.2.tgz#5e96fecf58b8fa1ed74efcad88475b2af3c9116e"@@ -1737,13 +1733,6 @@ babel-plugin-transform-builtin-extend@^1.1.0:babel-runtime "^6.2.0"babel-template "^6.3.0"-babel-plugin-transform-object-rest-spread@^6.26.0:- version "6.26.0"- resolved "https://registry.yarnpkg.com/babel-plugin-transform-object-rest-spread/-/babel-plugin-transform-object-rest-spread-6.26.0.tgz#0f36692d50fef6b7e2d4b3ac1478137a963b7b06"- dependencies:- babel-plugin-syntax-object-rest-spread "^6.8.0"- babel-runtime "^6.26.0"-babel-runtime@^6.2.0, babel-runtime@^6.22.0, babel-runtime@^6.26.0:version "6.26.0"resolved "https://registry.yarnpkg.com/babel-runtime/-/babel-runtime-6.26.0.tgz#965c7058668e82b55d7bfe04ff2337bc8b5647fe"@@ -7524,11 +7513,11 @@ react-onclickoutside@^6.7.1:version "6.9.0"resolved "https://registry.yarnpkg.com/react-onclickoutside/-/react-onclickoutside-6.9.0.tgz#a54bc317ae8cf6131a5d78acea55a11067f37a1f"-react-palm@^2.0.0:- version "2.0.0"- resolved "https://registry.yarnpkg.com/react-palm/-/react-palm-2.0.0.tgz#03be811ced642e9f1ca0fb437e99b8f55419413b"+react-palm@^3.1.2:+ version "3.1.2"+ resolved "https://registry.yarnpkg.com/react-palm/-/react-palm-3.1.2.tgz#8a20fe07e3999e4e5593af90d020eafa769f9ed0"+ integrity sha512-DSOSWlRf9e3v0IHy28WYEOP7kanrbAiZbcj1TvVcVg9xHXkftFBSmhogpc7OP7s8UrEGGTVs95YJ8iqgoXoGfA==dependencies:- babel-plugin-transform-object-rest-spread "^6.26.0"function.prototype.name "^1.1.0"react-dom "^16.4.2"react-reconciler "^0.12.0"@@ -9230,9 +9219,10 @@ tweetnacl@^0.14.3, tweetnacl@~0.14.0:version "0.14.5"resolved "https://registry.yarnpkg.com/tweetnacl/-/tweetnacl-0.14.5.tgz#5ae68177f192d4456269d108afa93ff8743f4f64"- version "0.2.1"- resolved "https://registry.yarnpkg.com/type-analyzer/-/type-analyzer-0.2.1.tgz#c3a04552be0114d079a54b5def72a828605f9cf9"+ version "0.2.3"+ resolved "https://registry.yarnpkg.com/type-analyzer/-/type-analyzer-0.2.3.tgz#a265b29b33290e465e2c611c3daaaf979c780e71"+ integrity sha512-CwHct29PabC8ze2QIczh82/9r277ljuxctCmriwxx63kIXDObe2BhF2iGU/iOnyjU/c+aiSEdWAVqR27rnp4mw==type-check@~0.3.2:version "0.3.2"