Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
[Enhancement] Improve animation sliders (#1157)
Shan He901ffdf01fa8
diff --git a/.travis.yml b/.travis.ymlindex ad0f0fe8a..ba51ddb74 100644--- a/.travis.yml+++ b/.travis.yml@@ -23,7 +23,8 @@ node_js:- 10before_script:- "curl -H 'Cache-Control: no-cache' https://raw.githubusercontent.com/fossas/fossa-cli/master/install.sh | sudo bash"- - ulimit -c unlimited -S # enable core dumps+ - ulimit -c unlimited -S # enable core dumps+ - echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p # avoid Node.JS Error: ENOSPCafter_success:- cat coverage/lcov.info | coverallsscript:diff --git a/src/components/common/animation-control/animation-control.js b/src/components/common/animation-control/animation-control.jsindex 5d89a775b..c50e88846 100644--- a/src/components/common/animation-control/animation-control.js+++ b/src/components/common/animation-control/animation-control.js@@ -18,17 +18,18 @@// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN// THE SOFTWARE.-import React, {Component} from 'react';+import React from 'react';import styled from 'styled-components';import moment from 'moment';-import {requestAnimationFrame, cancelAnimationFrame} from 'global/window';import Slider from 'components/common/slider/slider';import {BottomWidgetInner} from 'components/common/styled-components';import SpeedControlFactory from './speed-control';import AnimationPlaybacksFactory from './playback-controls';import FloatingTimeDisplayFactory from './floating-time-display';-import {BASE_SPEED} from 'constants/default-settings';+import AnimationControllerFactory from './animation-controller';+import {snapToMarks} from 'utils/data-utils';+import {DEFAULT_TIME_FORMAT, ANIMATION_TYPE} from 'constants';const SliderWrapper = styled.div`display: flex;@@ -59,67 +60,35 @@ const StyledDomain = styled.div`font-size: 10px;`;-const defaultTimeFormat = 'MM/DD/YY hh:mm:ss';const BUTTON_HEIGHT = '18px';AnimationControlFactory.deps = [SpeedControlFactory,AnimationPlaybacksFactory,- FloatingTimeDisplayFactory+ FloatingTimeDisplayFactory,+ AnimationControllerFactory];-function AnimationControlFactory(SpeedControl, AnimationPlaybacks, FloatingTimeDisplay) {- class AnimationControl extends Component {- constructor(props) {- super(props);- this.state = {- isAnimating: false,- width: 288,- showSpeedControl: false- };- this._animation = null;- }-- componentDidUpdate() {- if (!this._animation && this.state.isAnimating) {- this._animation = requestAnimationFrame(this._nextFrame);- }- }-+function AnimationControlFactory(+ SpeedControl,+ AnimationPlaybacks,+ FloatingTimeDisplay,+ AnimationController+) {+ class AnimationControl extends React.PureComponent {+ state = {+ showSpeedControl: false+ };onSlider1Change = val => {const {domain} = this.props.animationConfig;- if (val >= domain[0] && val <= domain[1]) {+ if (Array.isArray(this.props.timeSteps)) {+ this.props.updateAnimationTime(snapToMarks(val, this.props.timeSteps));+ // TODO: merge slider in to avoid this step+ } else if (val >= domain[0] && val <= domain[1]) {this.props.updateAnimationTime(val);}};- _updateAnimationTime = () => {- const {domain} = this.props.animationConfig;- this.props.updateAnimationTime(domain[0]);- this._startAnimation();- };-- _startAnimation = () => {- this._pauseAnimation();- this.setState({isAnimating: true});- };-- _nextFrame = () => {- this._animation = null;- const {currentTime, domain, speed = 1} = this.props.animationConfig;- const adjustedSpeed = ((domain[1] - domain[0]) / BASE_SPEED) * speed;- const nextTime = currentTime + speed > domain[1] ? domain[0] : currentTime + adjustedSpeed;- this.props.updateAnimationTime(nextTime);- };-- _pauseAnimation = () => {- if (this._animation) {- cancelAnimationFrame(this._animation);- this._animation = null;- }- this.setState({isAnimating: false});- };-toggleSpeedControl = () => {this.setState({showSpeedControl: !this.state.showSpeedControl});};@@ -128,31 +97,50 @@ function AnimationControlFactory(SpeedControl, AnimationPlaybacks, FloatingTimeDthis.toggleSpeedControl();};+ _updateAnimation = value => {+ this.props.updateAnimationTime(Array.isArray(value) ? value[0] : value);+ };+render() {- const {currentTime, domain, speed} = this.props.animationConfig;+ const {currentTime, domain, speed, step, timeSteps} = this.props.animationConfig;const {showSpeedControl} = this.state;+ const animationType = Array.isArray(timeSteps)+ ? ANIMATION_TYPE.interval+ : ANIMATION_TYPE.continuous;return (<BottomWidgetInner className="bottom-widget--inner"><AnimationWidgetInner className="animation-widget--inner"><div style={{marginLeft: '-10px'}}>- <AnimationPlaybacks- className="animation-control-playpause"- startAnimation={this._startAnimation}- isAnimating={this.state.isAnimating}- pauseAnimation={this._pauseAnimation}- resetAnimation={this._resetAnimation}- buttonHeight={BUTTON_HEIGHT}- buttonStyle="link"- />+ <AnimationController+ value={currentTime}+ domain={domain}+ speed={speed}+ updateAnimation={this._updateAnimation}+ steps={timeSteps}+ animationType={animationType}+ >+ {(isAnimating, start, pause, reset) => (+ <AnimationPlaybacks+ className="animation-control-playpause"+ startAnimation={start}+ isAnimating={isAnimating}+ pauseAnimation={pause}+ resetAnimation={reset}+ buttonHeight={BUTTON_HEIGHT}+ buttonStyle="link"+ />+ )}+ </AnimationController></div><StyledDomain className="animation-control__time-domain">- <span>{moment.utc(domain[0]).format(defaultTimeFormat)}</span>+ <span>{moment.utc(domain[0]).format(DEFAULT_TIME_FORMAT)}</span></StyledDomain><SliderWrapper className="animation-control__slider"><SlidershowValues={false}isRanged={false}+ step={step}minValue={domain ? domain[0] : 0}maxValue={domain ? domain[1] : 1}value1={currentTime}@@ -161,7 +149,7 @@ function AnimationControlFactory(SpeedControl, AnimationPlaybacks, FloatingTimeD/></SliderWrapper><StyledDomain className="animation-control__time-domain">- <span>{moment.utc(domain[1]).format(defaultTimeFormat)}</span>+ <span>{moment.utc(domain[1]).format(DEFAULT_TIME_FORMAT)}</span></StyledDomain><div className="animation-control__speed-control"><SpeedControldiff --git a/src/components/common/animation-control/animation-controller.js b/src/components/common/animation-control/animation-controller.jsnew file mode 100644index 000000000..71eebbd69--- /dev/null+++ b/src/components/common/animation-control/animation-controller.js@@ -0,0 +1,167 @@+// Copyright (c) 2020 Uber Technologies, Inc.+//+// Permission is hereby granted, free of charge, to any person obtaining a copy+// of this software and associated documentation files (the "Software"), to deal+// in the Software without restriction, including without limitation the rights+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+// copies of the Software, and to permit persons to whom the Software is+// furnished to do so, subject to the following conditions:+//+// The above copyright notice and this permission notice shall be included in+// all copies or substantial portions of the Software.+//+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+// THE SOFTWARE.++import {Component} from 'react';+import {bisectLeft} from 'd3-array';+import {requestAnimationFrame, cancelAnimationFrame} from 'global/window';+import {BASE_SPEED, FPS, ANIMATION_TYPE} from 'constants';+import Console from 'global/console';+function AnimationControllerFactory() {+ class AnimationController extends Component {+ static defaultProps = {+ baseSpeed: BASE_SPEED,+ speed: 1,+ animationType: ANIMATION_TYPE.continuous+ };++ state = {+ isAnimating: false+ };++ componentDidUpdate() {+ if (!this._timer && this.state.isAnimating) {+ if (this.props.animationType === ANIMATION_TYPE.continuous) {+ this._timer = requestAnimationFrame(this._nextFrame);+ } else {+ // animate by interval+ // 30*600+ const {steps, speed} = this.props;+ if (!Array.isArray(steps) || !steps.length) {+ Console.warn('animation steps should be an array');+ return;+ }+ // when speed = 1, animation should loop through 600 frames at 60 FPS+ // calculate delay based on # steps+ const delay = (BASE_SPEED * (1000 / FPS)) / steps.length / (speed || 1);+ this._animate(delay);+ }+ }+ }++ _timer = null;++ _animate = delay => {+ this._startTime = new Date().getTime();++ const loop = () => {+ const current = new Date().getTime();+ // @ts-ignore+ const delta = current - this._startTime;++ if (delta >= delay) {+ this._nextFrame();+ this._startTime = new Date().getTime();+ } else {+ this._timer = requestAnimationFrame(loop);+ }+ };++ this._timer = requestAnimationFrame(loop);+ };++ _resetAnimationWindow = () => {+ const {domain, value} = this.props;+ if (Array.isArray(value)) {+ const value0 = domain[0];+ const value1 = value0 + value[1] - value[0];+ this.props.updateAnimation([value0, value1]);+ } else {+ this.props.updateAnimation(domain[0]);+ }+ };++ _resetAnimtionStep = () => {+ // go to the first steps+ this.props.updateAnimation([this.props.steps[0], 0]);+ };++ _resetAnimation = () => {+ if (this.props.animationType === ANIMATION_TYPE.continuous) {+ this._resetAnimationWindow();+ } else {+ this._resetAnimtionStep();+ }+ };++ _startAnimation = () => {+ this._pauseAnimation();+ if (typeof this.props.startAnimation === 'function') {+ this.props.startAnimation();+ }+ this.setState({isAnimating: true});+ };++ _pauseAnimation = () => {+ if (this._timer) {+ cancelAnimationFrame(this._timer);+ if (typeof this.props.pauseAnimation === 'function') {+ this.props.pauseAnimation();+ }+ this._timer = null;+ }+ this.setState({isAnimating: false});+ };++ _nextFrame = () => {+ this._timer = null;+ const nextValue =+ this.props.animationType === ANIMATION_TYPE.continuous+ ? this._nextFrameByWindow()+ : this._nextFrameByStep();++ this.props.updateAnimation(nextValue);+ };++ _nextFrameByWindow() {+ const {domain, value, speed, baseSpeed} = this.props;+ const delta = ((domain[1] - domain[0]) / baseSpeed) * speed;++ // loop when reaches the end+ if (Array.isArray(value)) {+ const value0 = value[1] + delta > domain[1] ? domain[0] : value[0] + delta;+ const value1 = value0 + value[1] - value[0];+ return [value0, value1];+ }+ return value + delta > domain[1] ? domain[0] : value + delta;+ }++ _nextFrameByStep() {+ const {steps, value} = this.props;+ const val = Array.isArray(value) ? value[0] : value;+ const index = bisectLeft(steps, val);+ const nextIdx = index >= steps.length - 1 ? 0 : index + 1;++ return [steps[nextIdx], nextIdx];+ }++ render() {+ const {isAnimating} = this.state;+ const {children} = this.props;++ return typeof children === 'function'+ ? children(isAnimating, this._startAnimation, this._pauseAnimation, this._resetAnimation)+ : null;+ }+ }++ return AnimationController;+}++export default AnimationControllerFactory;diff --git a/src/components/common/range-brush.js b/src/components/common/range-brush.jsindex 604078cd6..9265cbc9c 100644--- a/src/components/common/range-brush.js+++ b/src/components/common/range-brush.js@@ -23,117 +23,189 @@ import PropTypes from 'prop-types';import styled from 'styled-components';import {event, select} from 'd3-selection';import {brushX} from 'd3-brush';+import {normalizeSliderValue} from 'utils/data-utils';const StyledG = styled.g`.selection {stroke: none;- fill: ${props => props.theme.rangeBrushBgd};- opacity: 1;+ fill: ${props => (props.isRanged ? props.theme.rangeBrushBgd : props.theme.BLUE2)};+ fill-opacity: ${props => (props.isRanged ? 0.3 : 1)};+ }+ .handle {+ fill: ${props => props.theme.BLUE2};+ fill-opacity: 0.3;}`;-export default class RangeBrush extends Component {- static propTypes = {- domain: PropTypes.arrayOf(PropTypes.number).isRequired,- onBrush: PropTypes.func.isRequired,- range: PropTypes.arrayOf(PropTypes.number).isRequired,- value: PropTypes.arrayOf(PropTypes.number).isRequired,- width: PropTypes.number.isRequired- };-- componentDidMount() {- // We want the React app to respond to brush state and vice-versa- // but d3-brush fires the same events for both user-initiated brushing- // and programmatic brushing (brush.move). We need these flags to- // distinguish between the uses.- //- // We don't use state because that would trigger another `componentDidUpdate`-- this.brushing = false;- this.moving = false;-- this.root = select(this.rootContainer.current);- this.brush = brushX()- .on('start', () => {- this.brushing = true;- })- .on('brush', () => {- if (this.moving) {- return;- }- event.selection === null ? this._reset() : this._brush(event.selection);- })- .on('end', () => {- if (!this.moving && event.selection === null) {- this._reset();- }+function moveRight(startSel, selection) {+ const [startSel0] = startSel;+ const [sel0] = selection;- this.brushing = false;- this.moving = false;- });+ return Boolean(startSel0 === sel0);+}- this.root.call(this.brush);- }+function RangeBrushFactory() {+ class RangeBrush extends Component {+ static propTypes = {+ onBrush: PropTypes.func.isRequired,+ range: PropTypes.arrayOf(PropTypes.number).isRequired,+ value: PropTypes.arrayOf(PropTypes.number).isRequired,+ width: PropTypes.number.isRequired,+ isRanged: PropTypes.bool+ };++ static defaultProps = {+ isRanged: true+ };++ componentDidMount() {+ // We want the React app to respond to brush state and vice-versa+ // but d3-brush fires the same events for both user-initiated brushing+ // and programmatic brushing (brush.move). We need these flags to+ // distinguish between the uses.+ //+ // We don't use state because that would trigger another `componentDidUpdate`++ this.brushing = false;+ this.moving = false;++ this.root = select(this.rootContainer.current);+ this.brush = brushX()+ .handleSize(3)+ .on('start', () => {+ if (typeof this.props.onBrushStart === 'function') this.props.onBrushStart();+ this._startSel = event.selection;+ })+ .on('brush', () => {+ if (this.moving) {+ return;+ }+ if (event.selection) {+ this.brushing = true;+ this._brushed(event);+ }+ })+ .on('end', () => {+ if (!this.brushing && this._startSel && !event.selection) {+ // handle click++ this._click(this._startSel);+ }+ if (typeof this.props.onBrushEnd === 'function') this.props.onBrushEnd();++ this.brushing = false;+ this.moving = false;+ });- componentDidUpdate(prevProps) {- const {- value: [val0, val1],- width- } = this.props;- const [prevVal0, prevVal1] = prevProps.value;+ this.root.call(this.brush);- if (prevProps.width !== width) {- // width change should not trigger this._brush+ const {+ value: [val0, val1]+ } = this.props;this.moving = true;- this.root.call(this.brush);this._move(val0, val1);}- if (!this.brushing && !this.moving) {- if (prevVal0 !== val0 || prevVal1 !== val1) {+ componentDidUpdate(prevProps) {+ const {+ value: [val0, val1],+ width+ } = this.props;+ const [prevVal0, prevVal1] = prevProps.value;++ if (prevProps.width !== width) {+ // width change should not trigger this._brushedthis.moving = true;+ this.root.call(this.brush);this._move(val0, val1);}- }- }- rootContainer = createRef();+ if (!this.brushing && !this.moving) {+ if (prevVal0 !== val0 || prevVal1 !== val1) {+ this.moving = true;+ this._move(val0, val1);+ }+ }+ }- _reset() {- const [minValue, maxValue] = this.props.range;- this._onBrush(minValue, maxValue);- }+ rootContainer = createRef();- _move(val0, val1) {- const {- domain: [min, max],- width- } = this.props;- const scale = x => ((x - min) * width) / (max - min);- this.brush.move(this.root, [scale(val0), scale(val1)]);- }+ _click(selection) {+ // fake brush+ this.brushing = true;+ this._brushed({sourceEvent: {}, selection});+ }- _brush([sel0, sel1]) {- const {- domain: [min, max],- width- } = this.props;- const invert = x => (x * (max - min)) / width + min;- this._onBrush(invert(sel0), invert(sel1));- }+ _move(val0, val1) {+ const {+ range: [min, max],+ width,+ isRanged+ } = this.props;++ if (width && max - min) {+ const scale = x => ((x - min) * width) / (max - min);+ if (!isRanged) {+ // only draw a 1 pixel line+ this.brush.move(this.root, [scale(val0), scale(val0) + 1]);+ } else {+ this.brush.move(this.root, [scale(val0), scale(val1)]);+ }+ }+ }- _onBrush(val0, val1) {- const {- value: [currentVal0, currentVal1]- } = this.props;+ _brushed = evt => {+ if (evt.sourceEvent.type === 'brush') return;+ const [sel0, sel1] = evt.selection;+ const right = moveRight(this._startSel, evt.selection);++ const {+ range: [min, max],+ step,+ width,+ marks,+ isRanged+ } = this.props;+ const invert = x => (x * (max - min)) / width + min;+ let d0 = invert(sel0);+ let d1 = invert(sel1);++ d0 = normalizeSliderValue(d0, min, step, marks);+ d1 = normalizeSliderValue(d1, min, step, marks);++ if (isRanged) this._move(d0, d1);+ else this._move(right ? d1 : d0);++ if (isRanged) this._onBrush(d0, d1);+ else this._onBrush(right ? d1 : d0);+ };++ _onBrush(val0, val1) {+ const {+ isRanged,+ value: [currentVal0, currentVal1]+ } = this.props;++ if (currentVal0 === val0 && currentVal1 === val1) {+ return;+ }- if (currentVal0 === val0 && currentVal1 === val1) {- return;+ if (isRanged) {+ this.props.onBrush(val0, val1);+ } else {+ this.props.onBrush(val0, val0);+ }}- this.props.onBrush(val0, val1);- }- render() {- return <StyledG className="kg-range-slider__brush" ref={this.rootContainer} />;+ render() {+ const {isRanged} = this.props;++ return (+ <StyledG className="kg-range-slider__brush" isRanged={isRanged} ref={this.rootContainer} />+ );+ }}+ return RangeBrush;}++export default RangeBrushFactory;diff --git a/src/components/common/range-plot.js b/src/components/common/range-plot.jsindex 04805b250..c6e7ef458 100644--- a/src/components/common/range-plot.js+++ b/src/components/common/range-plot.js@@ -28,7 +28,7 @@ import {LineSeries, XYPlot, CustomSVGSeries, Hint, MarkSeries} from 'react-vis';import styled from 'styled-components';import classnames from 'classnames';-import RangeBrush from './range-brush';+import RangeBrushFactory from './range-brush';import {getTimeWidgetHintFormatter} from 'utils/filter-utils';const chartMargin = {top: 8, bottom: 0, left: 0, right: 0};@@ -39,7 +39,9 @@ const histogramStyle = {unHighlightedW: 0.4};-export default function RangePlotFactory() {+RangePlotFactory.deps = [RangeBrushFactory];++export default function RangePlotFactory(RangeBrush) {class RangePlot extends Component {static propTypes = {value: PropTypes.arrayOf(PropTypes.number).isRequired,diff --git a/src/components/common/range-slider.js b/src/components/common/range-slider.jsindex ea23c2de4..e45e1ed1f 100644--- a/src/components/common/range-slider.js+++ b/src/components/common/range-slider.js@@ -20,7 +20,7 @@import React, {Component, createRef} from 'react';import {polyfill} from 'react-lifecycles-compat';-+import {createSelector} from 'reselect';import PropTypes from 'prop-types';import styled from 'styled-components';import RangePlotFactory from './range-plot';@@ -107,6 +107,13 @@ export default function RangeSliderFactory(RangePlot) {sliderContainer = createRef();inputValue0 = createRef();inputValue1 = createRef();+ value0Selector = props => props.value0;+ value1Selector = props => props.value1;+ filterValueSelector = createSelector(+ this.value0Selector,+ this.value1Selector,+ (value0, value1) => [value0, value1]+ );_isVal0InRange = val => {const {value1, range} = this.props;@@ -128,9 +135,9 @@ export default function RangeSliderFactory(RangePlot) {_setRangeVal1 = val => {const {value0, onChange} = this.props;- val = Number(val);- if (this._isVal1InRange(val)) {- onChange([value0, this._roundValToStep(val)]);+ const val1 = Number(val);+ if (this._isVal1InRange(val1)) {+ onChange([value0, this._roundValToStep(val1)]);return true;}return false;@@ -192,20 +199,7 @@ export default function RangeSliderFactory(RangePlot) {}render() {- const {- isRanged,- showInput,- histogram,- lineChart,- plotType,- isEnlarged,- range,- onChange,- value0,- value1,- sliderHandleWidth,- step- } = this.props;+ const {isRanged, showInput, histogram, range, onChange, sliderHandleWidth, step} = this.props;const height = isRanged && showInput ? '16px' : '24px';const {width} = this.state;@@ -220,26 +214,28 @@ export default function RangeSliderFactory(RangePlot) {{histogram && histogram.length ? (<RangePlothistogram={histogram}- lineChart={lineChart}- plotType={plotType}- isEnlarged={isEnlarged}- onBrush={(val0, val1) => {- onChange([this._roundValToStep(val0), this._roundValToStep(val1)]);- }}+ lineChart={this.props.lineChart}+ plotType={this.props.plotType}+ isEnlarged={this.props.isEnlarged}+ onBrush={(val0, val1) => onChange([val0, val1])}+ marks={this.props.marks}range={range}- value={[value0, value1]}+ value={this.filterValueSelector(this.props)}width={plotWidth}+ isRanged={isRanged}+ step={step}/>) : null}<SliderWrapper style={{height}} className="kg-range-slider__slider">{this.props.xAxis ? <this.props.xAxis width={plotWidth} domain={range} /> : null}<Slider+ marks={this.props.marks}showValues={false}isRanged={isRanged}minValue={range[0]}maxValue={range[1]}- value0={value0}- value1={value1}+ value0={this.props.value0}+ value1={this.props.value1}step={step}handleWidth={sliderHandleWidth}onSlider0Change={this._setRangeVal0}@@ -249,6 +245,7 @@ export default function RangeSliderFactory(RangePlot) {}}enableBarDrag/>+{!isRanged && showInput ? this._renderInput('value1') : null}</SliderWrapper>{isRanged && showInput ? (diff --git a/src/components/common/slider/mouse-event.js b/src/components/common/slider/mouse-event.jsindex 1db59debc..1c3abf9a1 100644--- a/src/components/common/slider/mouse-event.js+++ b/src/components/common/slider/mouse-event.js@@ -20,40 +20,39 @@import document from 'global/document';-function nope() {}+function nope(...args) {}export default class MouseEventHandler {- constructor({vertical = false, valueListener = nope, toggleMouseOver = nope}) {+ constructor({+ vertical = false,+ valueListener = nope,+ toggleMouseOver = nope,+ track,+ setAnchor = null+ }) {this._vertical = vertical;this._valueListener = valueListener;this._toggleMouseOver = toggleMouseOver;-- this._prev = 0;+ this._track = track;+ this._setAnchor = setAnchor;}handleMouseDown = e => {document.addEventListener('mouseup', this._mouseup);document.addEventListener('mousemove', this._mousemove);- this._prev = this._getMousePos(e);+ if (this._setAnchor) {+ const pos = this._getMousePos(e);+ this._setAnchor(this._getDistanceToTrack(pos));+ }this._toggleMouseOver();};_getMousePos(e) {- return this._vertical ? e.clientY : e.pageX;- }- _getTouchPosition(e) {- return this._vertical ? e.touches[0].clientY : e.touches[0].pageX;+ return this._vertical ? e.clientY : e.clientX;}- _getMouseDelta(e) {- // movementX might not be supported in some browser- // https://stackoverflow.com/questions/41774726/mouseevent-movementx-property-apparently-not-supported-in-internet-explorer- const mouseCoord = this._vertical ? e.movementY : e.movementX;- const clientCoord = this._getMousePos(e);-- const delta = mouseCoord === 0 ? clientCoord - this._prev : mouseCoord;-- return delta;+ _getTouchPosition(e) {+ return this._vertical ? e.touches[0].clientY : e.touches[0].clientX;}_mouseup = () => {@@ -62,26 +61,32 @@ export default class MouseEventHandler {this._toggleMouseOver();};+ _getDistanceToTrack(pos) {+ const trackRect = this._track.current.getBoundingClientRect();+ return pos - (this._vertical ? trackRect.bottom : trackRect.left);+ }+_mousemove = e => {e.preventDefault();-- const delta = this._getMouseDelta(e);- this._prev = this._getMousePos(e);-- this._valueListener(delta);+ const pos = this._getMousePos(e);+ this._valueListener(this._getDistanceToTrack(pos));};handleTouchStart = e => {+ // TODO: fix touch eventdocument.addEventListener('touchend', this._touchend);document.addEventListener('touchmove', this._touchmove);- this._prev = this._getTouchPosition(e);+ if (this._setAnchor) {+ const pos = this._getTouchPosition(e);+ this._setAnchor(this._getDistanceToTrack(pos));+ }this._toggleMouseOver();};_touchmove = e => {- const delta = this._getTouchPosition(e) - this._prev;- this._prev = this._getTouchPosition(e);- this.props._valueListener(delta);+ // TODO: touch not tested+ const pos = this._getTouchPosition(e);+ this._valueListener(this._getDistanceToTrack(pos));};_touchend = () => {diff --git a/src/components/common/slider/slider-bar-handle.js b/src/components/common/slider/slider-bar-handle.jsindex d44083ad4..48298117c 100644--- a/src/components/common/slider/slider-bar-handle.js+++ b/src/components/common/slider/slider-bar-handle.js@@ -58,7 +58,9 @@ export default class SliderBarHandle extends Component {this.mouseEvent = new MouseEventHandler({vertical: props.vertical,valueListener: props.sliderBarListener,- toggleMouseOver: this.toggleMouseOver+ toggleMouseOver: this.toggleMouseOver,+ track: props.track,+ setAnchor: props.setAnchor});}diff --git a/src/components/common/slider/slider-handle.js b/src/components/common/slider/slider-handle.jsindex 58c5d8809..f918f3682 100644--- a/src/components/common/slider/slider-handle.js+++ b/src/components/common/slider/slider-handle.js@@ -18,7 +18,7 @@// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN// THE SOFTWARE.-import React, {Component} from 'react';+import React, {Component, createRef} from 'react';import PropTypes from 'prop-types';import classnames from 'classnames';import styled from 'styled-components';@@ -27,8 +27,8 @@ import MouseEventHandler from './mouse-event';const StyledSliderHandle = styled.span`position: absolute;z-index: 10;- margin-${props => (props.vertical ? 'left' : 'top')}: -${props =>- (props.sliderHandleWidth - props.theme.sliderBarHeight) / 2}px;+ ${props => (props.vertical ? 'margin-left' : 'margin-top')}: -${props => (props.sliderHandleWidth - props.theme.sliderBarHeight) / 2}px;+height: ${props =>Number.isFinite(props.sliderHandleWidth)? props.sliderHandleWidth@@ -125,11 +125,13 @@ export default class SliderHandle extends Component {this.mouseEvent = new MouseEventHandler({vertical: props.vertical,valueListener: props.valueListener,- toggleMouseOver: this.toggleMouseOver+ toggleMouseOver: this.toggleMouseOver,+ track: props.track});}state = {mouseOver: false};+ ref = createRef();toggleMouseOver = () => {this.setState({mouseOver: !this.state.mouseOver});@@ -151,6 +153,7 @@ export default class SliderHandle extends Component {className={classnames('kg-range-slider__handle', {'kg-range-slider__handle--active': this.state.mouseOver})}+ ref={this.ref}sliderHandleWidth={this.props.sliderHandleWidth}active={this.state.mouseOver}vertical={this.props.vertical}diff --git a/src/components/common/slider/slider.js b/src/components/common/slider/slider.jsindex 0984d1272..4eda98b6d 100644--- a/src/components/common/slider/slider.js+++ b/src/components/common/slider/slider.js@@ -25,7 +25,7 @@ import styled from 'styled-components';import SliderHandle from './slider-handle';import SliderBarHandle from './slider-bar-handle';-import {roundValToStep} from 'utils/data-utils';+import {normalizeSliderValue} from 'utils/data-utils';function noop() {}@@ -39,8 +39,7 @@ const StyledRangeSlider = styled.div`const SliderWrapper = styled.div`flex-grow: 1;- margin-top: ${props =>- props.isRanged ? props.theme.sliderMarginTopIsRange : props.theme.sliderMarginTop}px;+ margin-top: ${props => props.theme.sliderMarginTop}px;`;export default class Slider extends Component {@@ -83,22 +82,33 @@ export default class Slider extends Component {};ref = createRef();+ track = createRef();++ _setAnchor = x => {+ // used to calculate delta+ this._anchor = x;+ };_getBaseDistance() {return this.props.vertical ? this.ref.current.offsetHeight : this.ref.current.offsetWidth;}- _getValDelta(x) {+ _getDeltaVal(x) {const percent = x / this._getBaseDistance();const maxDelta = this.props.maxValue - this.props.minValue;return percent * maxDelta;}+ _getDeltaX(v) {+ const percent = v / (this.props.maxValue - this.props.minValue);+ const maxDelta = this._getBaseDistance();+ return percent * maxDelta;+ }- _getValue(val, offset) {- const delta = this._getValDelta(offset);- const rawValue = this.props.vertical ? val - delta : val + delta;+ _getValue(baseV, offset) {+ // offset is the distance between slider handle and track left+ const rawValue = baseV + this._getDeltaVal(offset);- return this._roundValToStep(rawValue);+ return this._normalizeValue(rawValue);}_isVal0InRange = val => {@@ -111,30 +121,38 @@ export default class Slider extends Component {return Boolean(val <= maxValue && val >= value0);};- _roundValToStep(val) {- const {minValue, step} = this.props;- return roundValToStep(minValue, step, val);+ _normalizeValue(val) {+ const {minValue, step, marks} = this.props;+ return normalizeSliderValue(val, minValue, step, marks);}slide0Listener = x => {- const val = this._getValue(this.props.value0, x);+ const val = this._getValue(this.props.minValue, x);+if (this._isVal0InRange(val)) {this.props.onSlider0Change(val);}};slide1Listener = x => {- const val = this._getValue(this.props.value1, x);+ const val = this._getValue(this.props.minValue, x);if (this._isVal1InRange(val)) {this.props.onSlider1Change(val);}};sliderBarListener = x => {- const val0 = this._getValue(this.props.value0, x);- const val1 = this._getValue(this.props.value1, x);- if (this._isVal1InRange(val1) && this._isVal0InRange(val0)) {+ const {minValue, maxValue} = this.props;+ // for slider bar, we use distance delta+ const anchor = this._anchor;+ const val0 = this._getValue(this.props.value0, x - anchor);+ const val1 = this._getValue(this.props.value1, x - anchor);++ if (val0 >= minValue && val1 <= maxValue && val1 >= val0) {+ const deltaX = this._getDeltaX(val0 - this.props.value0);this.props.onSliderBarChange(val0, val1);+ // update anchor+ this._anchor = this._anchor + deltaX;}};@@ -176,7 +194,7 @@ export default class Slider extends Component {isRanged={isRanged}vertical={vertical}>- <StyledRangeSlider className="kg-range-slider" vertical={vertical}>+ <StyledRangeSlider className="kg-range-slider" vertical={vertical} ref={this.track}><SliderHandleclassName="kg-range-slider__handle"left={this.calcHandleLeft0(width, v0Left)}@@ -185,6 +203,7 @@ export default class Slider extends Component {display={isRanged}vertical={vertical}showTooltip={showTooltip}+ track={this.track}/><SliderHandleclassName="kg-range-slider__handle"@@ -194,6 +213,7 @@ export default class Slider extends Component {vertical={vertical}value={value1}showTooltip={showTooltip}+ track={this.track}/><SliderBarHandlewidth={width}@@ -201,6 +221,8 @@ export default class Slider extends Component {enableBarDrag={this.props.enableBarDrag}sliderBarListener={this.sliderBarListener}vertical={vertical}+ track={this.track}+ setAnchor={this._setAnchor}/></StyledRangeSlider></SliderWrapper>diff --git a/src/components/common/time-range-slider.js b/src/components/common/time-range-slider.jsindex 50ec8b95d..6918c59ec 100644--- a/src/components/common/time-range-slider.js+++ b/src/components/common/time-range-slider.js@@ -21,7 +21,6 @@import React, {Component} from 'react';import PropTypes from 'prop-types';import moment from 'moment';-import {requestAnimationFrame, cancelAnimationFrame} from 'global/window';import throttle from 'lodash.throttle';import styled from 'styled-components';import {createSelector} from 'reselect';@@ -29,9 +28,11 @@ import {createSelector} from 'reselect';import {Minus} from 'components/common/icons';import {SelectTextBold, SelectText} from 'components/common/styled-components';import RangeSliderFactory from 'components/common/range-slider';-import TimeSliderMarker from 'components/common/time-slider-marker';+import TimeSliderMarkerFactory from 'components/common/time-slider-marker';import PlaybackControlsFactory from 'components/common/animation-control/playback-controls';-import {BASE_SPEED, DEFAULT_TIME_FORMAT} from 'constants/default-settings';+import AnimationControllerFactory from 'components/common/animation-control/animation-controller';++import {DEFAULT_TIME_FORMAT} from 'constants/default-settings';const animationControlWidth = 140;@@ -49,11 +50,25 @@ const StyledSliderContainer = styled.div`.playback-control-button {padding: 9px 12px;}-`;-TimeRangeSliderFactory.deps = [PlaybackControlsFactory, RangeSliderFactory];+ .kg-range-slider__slider .kg-slider {+ margin-top: ${props => props.theme.sliderMarginTopIsTime}px;+ }+`;-export default function TimeRangeSliderFactory(PlaybackControls, RangeSlider) {+TimeRangeSliderFactory.deps = [+ PlaybackControlsFactory,+ RangeSliderFactory,+ TimeSliderMarkerFactory,+ AnimationControllerFactory+];++export default function TimeRangeSliderFactory(+ PlaybackControls,+ RangeSlider,+ TimeSliderMarker,+ AnimationController+) {class TimeRangeSlider extends Component {static propTypes = {onChange: PropTypes.func.isRequired,@@ -73,20 +88,9 @@ export default function TimeRangeSliderFactory(PlaybackControls, RangeSlider) {constructor(props) {super(props);- this.state = {- isAnimating: false,- width: 288- };- this._animation = null;this._sliderThrottle = throttle((...value) => this.props.onChange(...value), 20);}- componentDidUpdate() {- if (!this._animation && this.state.isAnimating) {- this._animation = requestAnimationFrame(this._nextFrame);- }- }-timeSelector = props => props.currentTime;formatSelector = props => props.format;displayTimeSelector = createSelector(@@ -116,43 +120,8 @@ export default function TimeRangeSliderFactory(PlaybackControls, RangeSlider) {this._sliderThrottle(args);};- _resetAnimation = () => {- const {domain, value} = this.props;- const value0 = domain[0];- const value1 = value0 + value[1] - value[0];- this.props.onChange([value0, value1]);- };-- _startAnimation = () => {- this._pauseAnimation();- this.props.toggleAnimation();- this.setState({isAnimating: true});- };-- _pauseAnimation = () => {- if (this._animation) {- cancelAnimationFrame(this._animation);- this.props.toggleAnimation();- this._animation = null;- }- this.setState({isAnimating: false});- };-- _nextFrame = () => {- this._animation = null;-- const {domain, value} = this.props;- const speed = ((domain[1] - domain[0]) / BASE_SPEED) * this.props.speed;-- // loop when reaches the end- const value0 = value[1] + speed > domain[1] ? domain[0] : value[0] + speed;- const value1 = value0 + value[1] - value[0];- this.props.onChange([value0, value1]);- };-render() {const {domain, value, isEnlarged, hideTimeTitle} = this.props;- const {isAnimating} = this.state;return (<div className="time-range-slider">@@ -161,16 +130,27 @@ export default function TimeRangeSliderFactory(PlaybackControls, RangeSlider) {) : null}<StyledSliderContainer className="time-range-slider__container" isEnlarged={isEnlarged}>{isEnlarged ? (- <PlaybackControls- isAnimatable={this.props.isAnimatable}- isEnlarged={isEnlarged}- isAnimating={isAnimating}- pauseAnimation={this._pauseAnimation}- resetAnimation={this._resetAnimation}- startAnimation={this._startAnimation}- buttonHeight="12px"- buttonStyle="secondary"- />+ <AnimationController+ value={this.props.value}+ domain={this.props.domain}+ speed={this.props.speed}+ startAnimation={this.props.toggleAnimation}+ pauseAnimation={this.props.toggleAnimation}+ updateAnimation={this.props.onChange}+ >+ {(isAnimating, start, pause, reset) => (+ <PlaybackControls+ isAnimatable={this.props.isAnimatable}+ isAnimating={isAnimating}+ width={animationControlWidth}+ pauseAnimation={pause}+ resetAnimation={reset}+ startAnimation={start}+ buttonHeight="12px"+ buttonStyle="secondary"+ />+ )}+ </AnimationController>) : null}<divstyle={{diff --git a/src/components/common/time-slider-marker.js b/src/components/common/time-slider-marker.jsindex 608d8d58a..290593c4e 100644--- a/src/components/common/time-slider-marker.js+++ b/src/components/common/time-slider-marker.js@@ -26,10 +26,12 @@ import {axisBottom} from 'd3-axis';import {createSelector} from 'reselect';import styled from 'styled-components';+const MIN_TICK_WIDTH = 50;+const TimeSliderContainer = styled.svg`pointer-events: none;position: absolute;- top: 0;+.axis text {font-size: 9px;fill: ${props => props.theme.textColor};@@ -63,51 +65,65 @@ const TimeSliderContainer = styled.svg`const height = 30;-export default class TimeSliderMarker extends Component {- static propTypes = {- domain: PropTypes.arrayOf(PropTypes.any).isRequired,- width: PropTypes.number.isRequired- };-- componentDidMount() {- this._updateAxis(this.scaleSelector(this.props));- }+function TimeSliderMarkerFactory() {+ class TimeSliderMarker extends Component {+ static propTypes = {+ domain: PropTypes.arrayOf(PropTypes.any).isRequired,+ width: PropTypes.number.isRequired+ };- componentDidUpdate(prevProps) {- if (this.scaleSelector(this.props) !== this.scaleSelector(prevProps)) {+ componentDidMount() {this._updateAxis(this.scaleSelector(this.props));}- }- xAxis = createRef();-- domainSelector = props => props.domain;- widthSelector = props => props.width;- scaleSelector = createSelector(this.domainSelector, this.widthSelector, (domain, width) =>- Array.isArray(domain)- ? scaleUtc()- .domain(domain)- .range([0, width])- : null- );-- _updateAxis(scale) {- if (!scale) {- return;+ componentDidUpdate(prevProps) {+ if (this.scaleSelector(this.props) !== this.scaleSelector(prevProps)) {+ this._updateAxis(this.scaleSelector(this.props));+ }}- const xAxis = axisBottom(scale)- .ticks(4)- .tickSize(8)- .tickPadding(6);- select(this.xAxis.current).call(xAxis);- }+ xAxis = createRef();- render() {- return (- <TimeSliderContainer className="time-slider-marker" width={this.props.width} height={height}>- <g className="x axis" ref={this.xAxis} transform="translate(0, 0)" />- </TimeSliderContainer>+ domainSelector = props => props.domain;+ widthSelector = props => props.width;+ scaleSelector = createSelector(this.domainSelector, this.widthSelector, (domain, width) =>+ Array.isArray(domain)+ ? scaleUtc()+ .domain(domain)+ .range([0, width])+ : null);++ _updateAxis(scale) {+ if (!scale) {+ return;+ }++ // TODO: pass in ticks if interval is defined+ const ticks = Math.floor(this.props.width / MIN_TICK_WIDTH);++ const xAxis = axisBottom(scale)+ .ticks(ticks)+ .tickSize(8)+ .tickPadding(6);++ select(this.xAxis.current).call(xAxis);+ }++ render() {+ return (+ <TimeSliderContainer+ className="time-slider-marker"+ width={this.props.width}+ height={height}+ >+ <g className="x axis" ref={this.xAxis} transform="translate(0, 0)" />+ </TimeSliderContainer>+ );+ }}++ return TimeSliderMarker;}++export default TimeSliderMarkerFactory;diff --git a/src/components/filters/time-widget.js b/src/components/filters/time-widget.jsindex f4764d64f..0bb693b05 100644--- a/src/components/filters/time-widget.js+++ b/src/components/filters/time-widget.js@@ -37,6 +37,9 @@ import FloatingTimeDisplayFactory from 'components/common/animation-control/floaconst TOP_SECTION_HEIGHT = '36px';+const TimeBottomWidgetInner = styled(BottomWidgetInner)`+ padding: 6px 32px 16px 32px;+`;const TopSectionWrapper = styled.div`display: flex;justify-content: space-between;@@ -130,7 +133,7 @@ function TimeWidgetFactory(SpeedControl, TimeRangeFilter, FloatingTimeDisplay) {const {showSpeedControl} = this.state;return (- <BottomWidgetInner className="bottom-widget--inner">+ <TimeBottomWidgetInner className="bottom-widget--inner"><TopSectionWrapper><StyledTitle className="bottom-widget__field"><CenterFlexbox className="bottom-widget__icon">@@ -179,7 +182,7 @@ function TimeWidgetFactory(SpeedControl, TimeRangeFilter, FloatingTimeDisplay) {isAnimatable/>{showTimeDisplay ? <FloatingTimeDisplay currentTime={filter.value} /> : null}- </BottomWidgetInner>+ </TimeBottomWidgetInner>);}}diff --git a/src/components/index.js b/src/components/index.jsindex 6930a2fec..ec5168d41 100644--- a/src/components/index.js+++ b/src/components/index.js@@ -91,13 +91,15 @@ export {default as ExportHtmlMapFactory} from './modals/export-map-modal/export-// // common factoryexport {default as AnimationControlFactory} from './common/animation-control/animation-control';+export {default as AnimationControllerFactory} from './common/animation-control/animation-controller';export {default as SpeedControlFactory} from './common/animation-control/speed-control';export {default as AnimationPlaybacksFactory} from './common/animation-control/playback-controls';export {default as FloatingTimeDisplayFactory} from './common/animation-control/floating-time-display';-export {default as DatasetSquare} from './common/styled-components';export {default as AnimationSpeedSliderFactory} from './common/animation-control/animation-speed-slider';export {default as RangePlotFactory} from './common/range-plot';+export {default as RangeBrushFactory} from './common/range-brush';export {FieldListItemFactory} from './common/field-selector';+export {default as TimeSliderMarkerFactory} from './common/time-slider-marker';// // Filters factoryexport {default as TimeWidgetFactory} from './filters/time-widget';@@ -129,6 +131,9 @@ export {default as Portaled} from './common/portaled';export {default as DropdownList} from './common/item-selector/dropdown-list';export {default as ProgressBar} from './common/progress-bar';export {default as FileUploadProgress} from './common/file-uploader/file-upload-progress';+export {default as Slider} from './common/slider/slider';+export {default as DatasetSquare} from './common/styled-components';+export * from './common/styled-components';import * as Icons from './common/icons';export {Icons};diff --git a/src/constants/default-settings.js b/src/constants/default-settings.jsindex eac7108c8..8bc323ace 100644--- a/src/constants/default-settings.js+++ b/src/constants/default-settings.js@@ -793,6 +793,11 @@ export const DEFAULT_NOTIFICATION_TOPICS = keyMirror({// Animationexport const BASE_SPEED = 600;+export const FPS = 60;+export const ANIMATION_TYPE = keyMirror({+ interval: null,+ continuous: null+});export const DEFAULT_TIME_FORMAT = 'MM/DD/YY HH:mm:ssa';export const SPEED_CONTROL_RANGE = [0, 10];export const SPEED_CONTROL_STEP = 0.001;diff --git a/src/constants/index.js b/src/constants/index.jsindex 93bd49aa6..ecdceef93 100644--- a/src/constants/index.js+++ b/src/constants/index.js@@ -57,7 +57,12 @@ export {SCALE_TYPES,THEME,TRIP_ARC_FIELDS,- TRIP_POINT_FIELDS+ TRIP_POINT_FIELDS,+ BASE_SPEED,+ FPS,+ ANIMATION_TYPE,+ DEFAULT_TIME_FORMAT,+ SPEED_CONTROL_RANGE} from './default-settings';export {BUG_REPORT_LINK, USER_GUIDE_DOC} from './user-guides';diff --git a/src/styles/base.js b/src/styles/base.jsindex 926e19490..fcd03cad7 100644--- a/src/styles/base.js+++ b/src/styles/base.js@@ -246,7 +246,7 @@ export const sliderHandleHoverColor = '#FFFFFF';export const sliderHandleShadow = '0 2px 4px 0 rgba(0,0,0,0.40)';export const sliderInputHeight = 24;export const sliderInputWidth = 56;-export const sliderMarginTopIsRange = 0;+export const sliderMarginTopIsTime = -12;export const sliderMarginTop = 12;// Plot@@ -1088,7 +1088,7 @@ export const theme = {sliderHandleShadow,sliderInputHeight,sliderInputWidth,- sliderMarginTopIsRange,+ sliderMarginTopIsTime,sliderMarginTop,// Plotdiff --git a/src/utils/data-utils.d.ts b/src/utils/data-utils.d.tsindex e822eb668..260104144 100644--- a/src/utils/data-utils.d.ts+++ b/src/utils/data-utils.d.ts@@ -17,4 +17,12 @@ export function getSampleData(data: any[], sampleSize?: number, getValue?: any):export function findMapBounds(layers: Layer[]): Bounds | null;function formatter(v: any): any;export function getFormatter(format: any, field?: Field): formatter;-export function defaultFormatter(v: any): string;\ No newline at end of file+export function defaultFormatter(v: any): string;+export function snapToMarks(value: number, marks: number[]): number;+export function normalizeSliderValue(+ val: number,+ minValue: number,+ step: number,+ marks?: number[]+): number;+export function roundValToStep(minValue: number, step: number, val: number): number;diff --git a/src/utils/data-utils.js b/src/utils/data-utils.jsindex b1e852cfd..d4a32c0f4 100644--- a/src/utils/data-utils.js+++ b/src/utils/data-utils.js@@ -23,6 +23,7 @@ import assert from 'assert';import {ALL_FIELD_TYPES} from 'constants/default-settings';import {TOOLTIP_FORMATS, TOOLTIP_FORMAT_TYPES, TOOLTIP_KEY} from 'constants/tooltip';import {format as d3Format} from 'd3-format';+import {bisectLeft} from 'd3-array';const MAX_LATITUDE = 90;const MIN_LATITUDE = -90;@@ -211,15 +212,50 @@ export function getRoundingDecimalFromStep(step) {return splitZero[1].length;}+/**+ * Use in slider, given a number and an array of numbers, return the nears number from the array+ * @type {typeof import('./data-utils').snapToMarks}+ * @param value+ * @param marks+ */+export function snapToMarks(value, marks) {+ // always use bin x0+ const i = bisectLeft(marks, value);+ if (i === 0) {+ return marks[i];+ } else if (i === marks.length) {+ return marks[i - 1];+ }+ const idx = marks[i] - value < value - marks[i - 1] ? i : i - 1;+ return marks[idx];+}++/**+ * If marks is provided, snap to marks, if not normalize to step+ * @type {typeof import('./data-utils').normalizeSliderValue}+ * @param val+ * @param minValue+ * @param step+ * @param marks+ */+export function normalizeSliderValue(val, minValue, step, marks) {+ if (marks && marks.length) {+ return snapToMarks(val, marks);+ }++ return roundValToStep(minValue, step, val);+}+/*** round the value to step for the slider- * @param {number} minValue- * @param {number} step- * @param {number} val- * @returns {number} - rounded number+ * @type {typeof import('./data-utils').roundValToStep}+ * @param minValue+ * @param step+ * @param val+ * @returns - rounded number*/export function roundValToStep(minValue, step, val) {- if (isNaN(step)) {+ if (!isNumber(step) || !isNumber(minValue)) {return val;}@@ -245,8 +281,6 @@ export function roundValToStep(minValue, step, val) {return Number(rounded);}-const identity = d => d;-/*** Get the value format based on field and format options* Used in render tooltip value@@ -287,25 +321,18 @@ const arrayMoveMutate = (array, from, to) => {array.splice(to < 0 ? array.length + to : to, 0, array.splice(from, 1)[0]);};+/**+ *+ * @param {*} array+ * @param {*} from+ * @param {*} to+ */export const arrayMove = (array, from, to) => {array = array.slice();arrayMoveMutate(array, from, to);return array;};-export function findFirstNoneEmpty(data, count = 1, getValue = identity) {- let c = 0;- const found = [];- while (c < count && c < data.length) {- const value = getValue(data[c]);- if (notNullorUndefined(value)) {- found.push(value);- }- c++;- }- return found;-}-/*** Get the value format based on field and format options* Used in render tooltip valuediff --git a/src/utils/layer-utils.d.ts b/src/utils/layer-utils.d.tsindex 0601d9b01..50e038c59 100644--- a/src/utils/layer-utils.d.ts+++ b/src/utils/layer-utils.d.ts@@ -1,5 +1,25 @@+// Copyright (c) 2020 Uber Technologies, Inc.+//+// Permission is hereby granted, free of charge, to any person obtaining a copy+// of this software and associated documentation files (the "Software"), to deal+// in the Software without restriction, including without limitation the rights+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+// copies of the Software, and to permit persons to whom the Software is+// furnished to do so, subject to the following conditions:+//+// The above copyright notice and this permission notice shall be included in+// all copies or substantial portions of the Software.+//+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+// THE SOFTWARE.+import {Layer, LayerClasses} from 'layers';-import {VisState, Dataset, InteractionConfig, Tooltip, TooltipField} from 'reducers/vis-state-updaters';+import {VisState, Dataset, TooltipField} from 'reducers/vis-state-updaters';export function calculateLayerData(layer: Layer,diff --git a/test/browser/components/common/index.js b/test/browser/components/common/index.jsindex 2a0cc1486..bb2709f1b 100644--- a/test/browser/components/common/index.js+++ b/test/browser/components/common/index.js@@ -20,3 +20,4 @@import './file-uploader-test';import './color-legend-test';+import './range-slider';diff --git a/test/browser/components/common/range-slider.js b/test/browser/components/common/range-slider.jsnew file mode 100644index 000000000..7a313b7dd--- /dev/null+++ b/test/browser/components/common/range-slider.js@@ -0,0 +1,44 @@+// Copyright (c) 2020 Uber Technologies, Inc.+//+// Permission is hereby granted, free of charge, to any person obtaining a copy+// of this software and associated documentation files (the "Software"), to deal+// in the Software without restriction, including without limitation the rights+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+// copies of the Software, and to permit persons to whom the Software is+// furnished to do so, subject to the following conditions:+//+// The above copyright notice and this permission notice shall be included in+// all copies or substantial portions of the Software.+//+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+// THE SOFTWARE.++import React from 'react';+import test from 'tape';+import {IntlWrapper, mountWithTheme} from 'test/helpers/component-utils';+import {RangeSlider, Slider} from 'components';+import SliderHandle from 'components/common/slider/slider-handle';+import SliderBarHandle from 'components/common/slider/slider-bar-handle';++test('Components -> RangeSlider.render', t => {+ let wrapper;+ const onChange = () => {};+ t.doesNotThrow(() => {+ wrapper = mountWithTheme(+ <IntlWrapper>+ <RangeSlider range={[0, 10]} value0={1} value1={3} onChange={onChange} />+ </IntlWrapper>+ );+ }, 'Show not fail without props');++ t.equal(wrapper.find(Slider).length, 1, 'should render Slider');+ t.equal(wrapper.find(SliderHandle).length, 2, 'should render 2 Slider handle');+ t.equal(wrapper.find(SliderBarHandle).length, 1, 'should render 1 Slider bar');++ t.end();+});diff --git a/test/node/utils/data-utils-test.js b/test/node/utils/data-utils-test.jsindex dfa9ff561..c4a3dffa5 100644--- a/test/node/utils/data-utils-test.js+++ b/test/node/utils/data-utils-test.js@@ -20,7 +20,17 @@import test from 'tape';-import {getRoundingDecimalFromStep, preciseRound, roundValToStep} from 'utils/data-utils';+import {+ getRoundingDecimalFromStep,+ preciseRound,+ normalizeSliderValue,+ roundValToStep,+ snapToMarks,+ arrayMove,+ getFormatter,+ defaultFormatter+} from 'utils/data-utils';+import {ALL_FIELD_TYPES} from 'constants';test('dataUtils -> preciseRound', t => {t.equal(preciseRound(1.234, 2), '1.23', 'should round 1.234 correctly');@@ -58,3 +68,99 @@ test('dataUtils -> getRoundingDecimalFromStep', t => {t.equal(roundValToStep(-30, 1, -14.5), -14, 'should round -14.5 to -14');t.end();});++test('dataUtils -> snapToMarks', t => {+ const marks = [0, 1, 3, 4.7, 5, 6.4, 10];+ t.equal(snapToMarks(0, marks), 0, 'should snap to nearest mark');+ t.equal(snapToMarks(-1, marks), 0, 'should snap to nearest mark');+ t.equal(snapToMarks(2.2, marks), 3, 'should snap to nearest mark');+ t.equal(snapToMarks(10, marks), 10, 'should snap to nearest mark');+ t.equal(snapToMarks(11, marks), 10, 'should snap to nearest mark');+ t.equal(snapToMarks(5, marks), 5, 'should snap to nearest mark');+ t.equal(snapToMarks(2, marks), 1, 'should snap to nearest mark');++ t.end();+});++test('dataUtils -> normalizeSliderValue', t => {+ t.equal(normalizeSliderValue(-1.1, 0, 1), -1, 'should normalize slider value based on step');+ t.equal(normalizeSliderValue(4.4, 0, 1), 4, 'should round Val To Step');+ t.equal(normalizeSliderValue(4.4, 0, 1, [1, 2, 3, 4.1, 5]), 4.1, 'should snap To Marks');+ t.equal(normalizeSliderValue(4.4, 0, undefined), 4.4, 'is step is not defined return value');+ t.equal(normalizeSliderValue(4.4, undefined, 1), 4.4, 'is minValue is not defined return value');++ t.end();+});++test('dataUtils -> arrayMove', t => {+ const arr = [4, 1, 9, 3, 11];+ t.deepEqual(arrayMove(arr, 2, 1), [4, 9, 1, 3, 11], 'should move array');+ t.deepEqual(arrayMove(arr, 2, 5), [4, 1, 3, 11, 9], 'should move array');+ t.deepEqual(arrayMove(arr, 2, -1), [4, 1, 3, 11, 9], 'should move array');+ t.end();+});++test('dataUtils -> defaultFormatter', t => {+ t.equal(defaultFormatter(1), '1', 'defaultFormatter should be correct');+ t.equal(defaultFormatter('a'), 'a', 'defaultFormatter should be correct');+ t.equal(defaultFormatter(undefined), '', 'defaultFormatter should be correct');+ t.equal(defaultFormatter(NaN), 'NaN', 'defaultFormatter should be correct');+ t.equal(defaultFormatter(null), '', 'defaultFormatter should be correct');++ t.end();+});++test('dataUtils -> getFormatter', t => {+ const TEST_CASES = [+ {+ input: [undefined],+ assert: formatter => {+ t.equal(formatter, defaultFormatter, 'should return defaultformatter');+ }+ },+ {+ input: ['.1s'],+ assert: [134, '100']+ },+ {+ input: ['%'],+ assert: ['12.345', '12.35%']+ },+ {+ input: ['none exist'],+ assert: formatter => {+ t.equal(formatter, defaultFormatter, 'should return defaultformatter');+ }+ },+ {+ // custom format+ input: [+ 'YYYY-MM-DD',+ {+ type: ALL_FIELD_TYPES.timestamp+ }+ ],+ assert: [1593724860289, '2020-07-02']+ },+ {+ // custom format+ input: [+ ',.2r',+ {+ type: ALL_FIELD_TYPES.integer+ }+ ],+ assert: [4223, '4,200']+ }+ ];++ TEST_CASES.forEach(tc => {+ const formatter = getFormatter(...tc.input);+ if (typeof tc.assert === 'function') {+ tc.assert(formatter);+ } else {+ t.equal(formatter(tc.assert[0]), tc.assert[1], 'should return correct formatter');+ }+ });+ t.end();+});