Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
feat: add Step by Interval to the playback bar (#3788)
Igor Dykhtaf7c6a37f3975
diff --git a/docs/user-guides/h-playback.md b/docs/user-guides/h-playback.mdindex e609f5898..612960308 100644--- a/docs/user-guides/h-playback.md+++ b/docs/user-guides/h-playback.md@@ -21,6 +21,7 @@ Use the animation window control on the playback bar to choose how the time rang- **Moving Time Window** (default): a fixed-length window slides forward. Features appear while their time falls inside the window, then disappear when the window moves past them.- **Incremental Time Window**: the window start stays fixed and only the end advances. Features accumulate once their timestamp is reached and stay visible until the animation loops or resets (then the window shrinks again and accumulation starts over). Use this when you have a single timestamp field and want cumulative playback (similar to “accumulate” in other GIS tools).+- **Step by Interval**: the window is one histogram bin wide and jumps to the next bin on each frame. Dragging the histogram selects a single bin; the brush stays locked to that bin while this mode is on. Wheel-resizing the time window is turned off so the selection cannot stretch across bins.## Start and end time (duration)diff --git a/src/components/src/common/animation-control/playback-controls.tsx b/src/components/src/common/animation-control/playback-controls.tsxindex 205d110d7..2c09c7f23 100644--- a/src/components/src/common/animation-control/playback-controls.tsx+++ b/src/components/src/common/animation-control/playback-controls.tsx@@ -4,7 +4,7 @@import React, {useState, useCallback} from 'react';import styled, {IStyledComponent} from 'styled-components';import classnames from 'classnames';-import {Reset, Play, Pause, Save, Speed, AnchorWindow, FreeWindow} from '../icons';+import {Reset, Play, Pause, Save, Speed, AnchorWindow, FreeWindow, Interval} from '../icons';import {ANIMATION_WINDOW} from '@kepler.gl/constants';import {Filter, TimeRangeFilter} from '@kepler.gl/types';import AnimationSpeedSliderFactory from './animation-speed-slider';@@ -45,7 +45,8 @@ const DEFAULT_ICONS = {/* eslint-enable react/display-name */speed: () => <Speed height="16px" />,animationFree: FreeWindow,- animationIncremental: AnchorWindow+ animationIncremental: AnchorWindow,+ animationInterval: Interval};function nop() {@@ -62,6 +63,11 @@ const DEFAULT_ANIMATE_ITEMS = {id: ANIMATION_WINDOW.incremental,icon: DEFAULT_ICONS.animationIncremental,tooltip: 'tooltip.animationByIncremental'+ },+ [ANIMATION_WINDOW.interval]: {+ id: ANIMATION_WINDOW.interval,+ icon: DEFAULT_ICONS.animationInterval,+ tooltip: 'tooltip.animationByInterval'}};export interface PlaybackControlsProps {diff --git a/src/components/src/common/icons/index.tsx b/src/components/src/common/icons/index.tsxindex cfe25080f..9fa198f2d 100644--- a/src/components/src/common/icons/index.tsx+++ b/src/components/src/common/icons/index.tsx@@ -53,6 +53,7 @@ export {default as Histogram} from './histogram';export {default as HorizontalResizeHandle} from './horizontal-resize-handle';export {default as IconWrapper} from './base';export {default as Info} from './info';+export {default as Interval} from './interval';export {default as Join} from './join';export {default as Layers} from './layers';export {default as LeftArrow} from './left-arrow';diff --git a/src/components/src/common/icons/interval.tsx b/src/components/src/common/icons/interval.tsxnew file mode 100644index 000000000..91b1d7087--- /dev/null+++ b/src/components/src/common/icons/interval.tsx@@ -0,0 +1,30 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import React from 'react';+import Base, {BaseProps} from './base';++const Interval = ({+ height = '16px',+ viewBox = '0 0 16 16',+ predefinedClassName = 'data-ex-icons-interval',+ ...restProps+}: Partial<BaseProps>) => {+ const props = {+ height,+ viewBox,+ predefinedClassName,+ ...restProps+ };+ return (+ <Base {...props}>+ <path+ fillRule="evenodd"+ clipRule="evenodd"+ d="M12.5845 7.3118C12.6988 7.3118 12.8083 7.26693 12.8891 7.18706C12.9699 7.10719 13.0153 6.99886 13.0153 6.88591V4.13278C13.0153 3.89757 12.8224 3.7069 12.5845 3.7069C12.3466 3.7069 12.1537 3.89757 12.1537 4.13278V5.95384C10.9672 5.07305 9.51654 4.58893 8.01543 4.58893C6.18745 4.58893 4.43433 5.30685 3.14175 6.58476C2.97352 6.75108 2.97352 7.02074 3.14175 7.18706C3.30998 7.35338 3.58273 7.35338 3.75096 7.18706C4.88197 6.06888 6.41594 5.4407 8.01543 5.4407C9.22584 5.4407 10.3987 5.80044 11.3879 6.46002H10.1692C9.93128 6.46002 9.73842 6.6507 9.73842 6.88591C9.73842 7.12112 9.93128 7.3118 10.1692 7.3118L12.5845 7.3118ZM2.67358 11.1339C3.08811 10.7241 3.08811 10.0597 2.67358 9.64985C2.25906 9.24003 1.58698 9.24003 1.17245 9.64985C0.757923 10.0597 0.757923 10.7241 1.17245 11.1339C1.58698 11.5438 2.25906 11.5438 2.67358 11.1339ZM3.2828 9.04755C4.03378 9.79002 4.03378 10.9938 3.2828 11.7362C2.53181 12.4787 1.31422 12.4787 0.563239 11.7362C-0.187746 10.9938 -0.187746 9.79002 0.563239 9.04755C1.31422 8.30509 2.53181 8.30509 3.2828 9.04755ZM12.7691 9.06881C12.03 9.79953 12.03 10.9843 12.7691 11.715C13.5082 12.4457 14.7066 12.4457 15.4457 11.715C16.1848 10.9843 16.1848 9.79953 15.4457 9.06881C14.7066 8.33808 13.5082 8.33808 12.7691 9.06881Z"+ />+ </Base>+ );+};++export default Interval;diff --git a/src/components/src/common/time-range-slider.tsx b/src/components/src/common/time-range-slider.tsxindex 5ecc4a7ef..31c121799 100644--- a/src/components/src/common/time-range-slider.tsx+++ b/src/components/src/common/time-range-slider.tsx@@ -1,7 +1,7 @@// SPDX-License-Identifier: MIT// Copyright contributors to the kepler.gl project-import React, {useEffect, useMemo} from 'react';+import React, {useCallback, useEffect, useMemo} from 'react';import throttle from 'es-toolkit/compat/throttle';import styled, {IStyledComponent} from 'styled-components';@@ -11,6 +11,8 @@ import PlaybackControlsFactory from './animation-control/playback-controls';import TimeRangeSliderTimeTitleFactory from './time-range-slider-time-title';import {LineChart, Timeline, AnimationConfig, TimeBins, Filter} from '@kepler.gl/types';import {ActionHandler, setFilterPlot} from '@kepler.gl/actions';+import {ANIMATION_WINDOW} from '@kepler.gl/constants';+import {getBinThresholds, intervalBinFromMarks} from '@kepler.gl/utils';import AnimationControlFactory from './animation-control/animation-control';import {BaseComponentProps} from '../types';@@ -50,6 +52,7 @@ type TimeRangeSliderProps = {export type StyledSliderContainerProps = BaseComponentProps & {$isEnlarged?: boolean;+ $interval?: boolean;};const StyledSliderContainer: IStyledComponent<@@ -69,6 +72,15 @@ const StyledSliderContainer: IStyledComponent<.playback-controls {margin-left: 22px;}++ ${props =>+ props.$interval+ ? `+ .kg-range-slider__bar {+ background-color: transparent;+ }+ `+ : ''}`;const ANIMATION_CONTROL_STYLE = {flex: 1, padding: 0, marginTop: 0};@@ -125,7 +137,40 @@ export default function TimeRangeSliderFactory(filter} = props;- const throttledOnchange = useMemo(() => throttle(onChange, 20), [onChange]);+ const binMarks = useMemo(() => {+ if (animationWindow !== ANIMATION_WINDOW.interval || !plotType?.interval || !domain) {+ return null;+ }+ const thresholds = getBinThresholds(plotType.interval, domain);+ return thresholds.length > 1 ? thresholds : null;+ }, [animationWindow, domain, plotType?.interval]);++ const byInterval = Boolean(binMarks);+ const sliderRange = useMemo(() => {+ if (!domain) {+ return domain;+ }+ if (binMarks) {+ return [domain[0], Math.max(binMarks[binMarks.length - 1], domain[1])] as [number, number];+ }+ return domain;+ }, [binMarks, domain]);++ const onSliderChange = useCallback(+ (val: number[]) => {+ if (byInterval && binMarks) {+ // A point brush reports the same mark twice. The single handle reports+ // [domain start, handle], so the moving edge picks the bin.+ const anchor = val[0] === val[1] ? val[0] : val[1];+ onChange(intervalBinFromMarks(binMarks, anchor));+ return;+ }+ onChange(val);+ },+ [binMarks, byInterval, onChange]+ );++ const throttledOnchange = useMemo(() => throttle(onSliderChange, 20), [onSliderChange]);useEffect(() => () => throttledOnchange.cancel(), [throttledOnchange]);const binsForInterval = useMemo(@@ -153,13 +198,18 @@ export default function TimeRangeSliderFactory(/></div>) : null}- <StyledSliderContainer className="time-range-slider__container" $isEnlarged={isEnlarged}>+ <StyledSliderContainer+ className="time-range-slider__container"+ $isEnlarged={isEnlarged}+ $interval={byInterval}+ >{!isMinified ? (<div className="timeline-container" style={style}><RangeSlider- range={domain}- value0={value[0]}- value1={value[1]}+ range={byInterval ? sliderRange : domain}+ value0={byInterval && sliderRange ? sliderRange[0] : value[0]}+ value1={byInterval ? value[0] : value[1]}+ plotValue={byInterval ? value : undefined}bins={binsForInterval}lineChart={lineChart}invertTrendColor={invertTrendColor}@@ -167,6 +217,9 @@ export default function TimeRangeSliderFactory(isEnlarged={isEnlarged}showInput={false}step={step}+ isRanged={!byInterval}+ marks={byInterval ? binMarks || undefined : undefined}+ animationWindow={animationWindow}onChange={throttledOnchange}xAxis={TimeSliderMarker}timezone={timezone}diff --git a/src/components/src/filters/time-widget.tsx b/src/components/src/filters/time-widget.tsxindex d60c004ab..af3bef9ba 100644--- a/src/components/src/filters/time-widget.tsx+++ b/src/components/src/filters/time-widget.tsx@@ -4,8 +4,14 @@import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';import styled from 'styled-components';import throttle from 'es-toolkit/compat/throttle';-import {DEFAULT_TIME_FORMAT, FILTER_VIEW_TYPES} from '@kepler.gl/constants';-import {clamp, datetimeFormatter, lineChartSeriesLegend} from '@kepler.gl/utils';+import {ANIMATION_WINDOW, DEFAULT_TIME_FORMAT, FILTER_VIEW_TYPES} from '@kepler.gl/constants';+import {+ clamp,+ datetimeFormatter,+ getBinThresholds,+ intervalBinFromMarks,+ lineChartSeriesLegend+} from '@kepler.gl/utils';import {BottomWidgetInner,Button,@@ -214,7 +220,8 @@ function TimeWidgetFactory(const handleWindowZoom = useCallback((factor: number, center: number) => {- if (!fullDomain) {+ // Interval mode keeps the selection on one histogram bin.+ if (!fullDomain || filter.animationWindow === ANIMATION_WINDOW.interval) {return;}const domainRange: [number, number] = timelineDomain ?? fullDomain;@@ -240,7 +247,15 @@ function TimeWidgetFactory(setFilterAnimationTime(index, 'value', [clampedStart, clampedEnd]);}},- [filterEnd, filterStart, fullDomain, index, setFilterAnimationTime, timelineDomain]+ [+ filter.animationWindow,+ filterEnd,+ filterStart,+ fullDomain,+ index,+ setFilterAnimationTime,+ timelineDomain+ ]);const handleTimelineZoom = useCallback(@@ -279,6 +294,11 @@ function TimeWidgetFactory(const nextRange: [number, number] = clampRange([nextStart, nextEnd], fullDomain);setTimelineDomain(prev => (rangesEqual(prev, nextRange) ? prev : nextRange));+ // Pinch-zoom only changes the visible domain. The selected bin stays put.+ if (filter.animationWindow === ANIMATION_WINDOW.interval) {+ return;+ }+let windowStart = filterStart;let windowEnd = filterEnd;const rangeWidth = nextRange[1] - nextRange[0];@@ -295,7 +315,15 @@ function TimeWidgetFactory(setFilterAnimationTime(index, 'value', [windowStart, windowEnd]);}},- [filterEnd, filterStart, fullDomain, index, setFilterAnimationTime, timelineDomain]+ [+ filter.animationWindow,+ filterEnd,+ filterStart,+ fullDomain,+ index,+ setFilterAnimationTime,+ timelineDomain+ ]);const throttledWindowZoom = useMemo(@@ -382,11 +410,28 @@ function TimeWidgetFactory(if (!domainRange) {return;}+ event.preventDefault();+ if (+ filter.animationWindow === ANIMATION_WINDOW.interval &&+ filter.plotType?.interval &&+ fullDomain+ ) {+ const marks = getBinThresholds(filter.plotType.interval, fullDomain);+ const currentIdx = marks.indexOf(intervalBinFromMarks(marks, filterStart)[0]);+ const nextIdx = event.key === 'ArrowRight' ? currentIdx + 1 : currentIdx - 1;+ if (nextIdx < 0 || nextIdx >= marks.length - 1) {+ return;+ }+ const nextBin = intervalBinFromMarks(marks, marks[nextIdx]);+ if (nextBin[0] !== filterStart || nextBin[1] !== filterEnd) {+ setFilterAnimationTime(index, 'value', nextBin);+ }+ return;+ }const windowWidth = filterEnd - filterStart;if (!(windowWidth > 0)) {return;}- event.preventDefault();let nextStart: number;let nextEnd: number;if (event.key === 'ArrowRight') {@@ -404,6 +449,8 @@ function TimeWidgetFactory(window.addEventListener('keydown', handler);return () => window.removeEventListener('keydown', handler);}, [+ filter.animationWindow,+ filter.plotType?.interval,filterEnd,filterStart,fullDomain,diff --git a/src/localization/src/translations/ca.ts b/src/localization/src/translations/ca.tsindex adf74606e..18024d7bf 100644--- a/src/localization/src/translations/ca.ts+++ b/src/localization/src/translations/ca.ts@@ -376,6 +376,7 @@ export default {'3DMap': 'Mapa 3D',animationByWindow: 'Finestra Temporal Mòbil',animationByIncremental: 'Finestra Temporal Incremental',+ animationByInterval: 'Pas per interval',speed: 'velocitat',play: 'iniciar',pause: 'pausar',diff --git a/src/localization/src/translations/cn.ts b/src/localization/src/translations/cn.tsindex 1ec8c2159..2d3dc34c9 100644--- a/src/localization/src/translations/cn.ts+++ b/src/localization/src/translations/cn.ts@@ -360,6 +360,7 @@ export default {'3DMap': '3D 地图',animationByWindow: '移动时间窗口',animationByIncremental: '增量时间窗口',+ animationByInterval: '按间隔步进',speed: '速度',play: '播放',pause: '暂停',diff --git a/src/localization/src/translations/en.ts b/src/localization/src/translations/en.tsindex 8f7a44f73..df5383341 100644--- a/src/localization/src/translations/en.ts+++ b/src/localization/src/translations/en.ts@@ -567,6 +567,7 @@ export default {'3DMap': '3D Map',animationByWindow: 'Moving Time Window',animationByIncremental: 'Incremental Time Window',+ animationByInterval: 'Step by Interval',speed: 'Speed',play: 'Play',pause: 'Pause',diff --git a/src/localization/src/translations/es.ts b/src/localization/src/translations/es.tsindex 6b62353dd..bf5026be7 100644--- a/src/localization/src/translations/es.ts+++ b/src/localization/src/translations/es.ts@@ -377,6 +377,7 @@ export default {'3DMap': 'Mapa 3D',animationByWindow: 'Ventana Temporal Móvil',animationByIncremental: 'Ventana Temporal Incremental',+ animationByInterval: 'Paso por intervalo',speed: 'velocidad',play: 'iniciar',pause: 'pausar',diff --git a/src/localization/src/translations/fi.ts b/src/localization/src/translations/fi.tsindex 0b7d76d23..f7e3fb7e8 100644--- a/src/localization/src/translations/fi.ts+++ b/src/localization/src/translations/fi.ts@@ -374,6 +374,7 @@ export default {'3DMap': '3D-näkymä',animationByWindow: 'Liukuva aikaikkuna',animationByIncremental: 'Kasvava aikaikkuna',+ animationByInterval: 'Askel intervallin mukaan',speed: 'nopeus',play: 'toista',pause: 'tauko',diff --git a/src/localization/src/translations/ja.ts b/src/localization/src/translations/ja.tsindex 1be8483d0..c85880f5f 100644--- a/src/localization/src/translations/ja.ts+++ b/src/localization/src/translations/ja.ts@@ -369,6 +369,7 @@ export default {'3DMap': '3D地図',animationByWindow: '時間枠を移動',animationByIncremental: '時間枠を増加',+ animationByInterval: '間隔ごとに進む',speed: '速度',play: '再生',pause: '一時停止',diff --git a/src/localization/src/translations/pt.ts b/src/localization/src/translations/pt.tsindex d0b6784a2..e203a47a8 100644--- a/src/localization/src/translations/pt.ts+++ b/src/localization/src/translations/pt.ts@@ -376,6 +376,7 @@ export default {'3DMap': ' Mapa 3D',animationByWindow: 'Janela de tempo móvel',animationByIncremental: 'Janela de tempo incremental',+ animationByInterval: 'Passo por intervalo',speed: 'velocidade',play: 'reproduzir',pause: 'pausar',diff --git a/src/localization/src/translations/ru.ts b/src/localization/src/translations/ru.tsindex a85f2d581..9cbcc4ddc 100644--- a/src/localization/src/translations/ru.ts+++ b/src/localization/src/translations/ru.ts@@ -372,6 +372,7 @@ export default {'3DMap': '3D Карта',animationByWindow: 'Перемещение временного окна',animationByIncremental: 'Дополнительное временное окно',+ animationByInterval: 'Шаг по интервалу',speed: 'скорость',play: 'проиграть',pause: 'пауза',diff --git a/src/reducers/src/vis-state-updaters.ts b/src/reducers/src/vis-state-updaters.tsindex ed6577224..eee7d3088 100644--- a/src/reducers/src/vis-state-updaters.ts+++ b/src/reducers/src/vis-state-updaters.ts@@ -1353,17 +1353,26 @@ export function setFilterAnimationWindowUpdater<S extends VisState>(return state;}- const newFilter = {- ...filter,- animationWindow- };+ const previousWindow = (filter as TimeRangeFilter).animationWindow;+ let nextFilter = {...filter, animationWindow} as Filter;++ // Entering or leaving interval playback snaps the window onto histogram bins.+ if (+ filter.type === FILTER_TYPES.timeRange &&+ (previousWindow === ANIMATION_WINDOW.interval || animationWindow === ANIMATION_WINDOW.interval)+ ) {+ const adjusted = adjustValueToAnimationWindow(state, nextFilter as TimeRangeFilter);+ if (Array.isArray(adjusted.value) && adjusted.value.every(v => Number.isFinite(v))) {+ nextFilter = adjusted;+ }+ }const newState = {...state,- filters: swap_<Filter>(newFilter)(state.filters)+ filters: swap_<Filter>(nextFilter)(state.filters)};- const newSyncTimelineMode = getSyncAnimationMode(newFilter as TimeRangeFilter);+ const newSyncTimelineMode = getSyncAnimationMode(nextFilter as TimeRangeFilter);return setTimeFilterTimelineModeUpdater(newState, {id, mode: newSyncTimelineMode});}diff --git a/src/utils/src/index.ts b/src/utils/src/index.tsindex 3cc09554a..247cac525 100644--- a/src/utils/src/index.ts+++ b/src/utils/src/index.ts@@ -50,6 +50,7 @@ export type {export {adjustValueToAnimationWindow,getBinThresholds,+ intervalBinFromMarks,histogramFromThreshold,histogramFromValues,histogramFromDomain,diff --git a/src/utils/src/plot.ts b/src/utils/src/plot.tsindex f45b99818..e96312665 100644--- a/src/utils/src/plot.ts+++ b/src/utils/src/plot.ts@@ -1,7 +1,14 @@// SPDX-License-Identifier: MIT// Copyright contributors to the kepler.gl project-import {bisectLeft, bisectRight, extent, histogram as d3Histogram, ticks} from 'd3-array';+import {+ bisectCenter,+ bisectLeft,+ bisectRight,+ extent,+ histogram as d3Histogram,+ ticks+} from 'd3-array';import isEqual from 'es-toolkit/compat/isEqual';import {getFilterMappedValue, getInitialInterval, intervalToFunction} from './time';import moment from 'moment';@@ -324,14 +331,14 @@ export function binByTime(indexes, dataset, interval, filter) {export function getBinThresholds(interval: string, domain: number[]): number[] {const timeInterval = intervalToFunction(interval);const [t0, t1] = domain;- const floor = timeInterval.floor(t0).getTime();- const ceiling = timeInterval.ceil(t1).getTime();if (!timeInterval) {// if time interval is not defined// this should not happenreturn [t0, t0 + durationDay];}+ const floor = timeInterval.floor(t0).getTime();+ const ceiling = timeInterval.ceil(t1).getTime();const binThresholds = timeInterval.range(floor, ceiling + 1).map(t => moment.utc(t).valueOf());const lastStep = binThresholds[binThresholds.length - 1];if (lastStep === t1) {@@ -432,11 +439,30 @@ export function validBin(b) {}/**- * Use in slider, given a number and an array of numbers, return the nears number from the array.- * Takes a value, timesteps and return the actual step.- * @param value- * @param marks+ * Turn a histogram brush or slider position into one bin.+ * Interval playback steps by bin, and the filter comparison is inclusive, so+ * the window is [binStart, nextBinStart - 1]. The last threshold is the end+ * of the domain, not the start of another bin.*/+export function intervalBinFromMarks(marks: number[], value: number): [number, number] {+ if (!marks.length || !Number.isFinite(value)) {+ return [value, value];+ }+ if (marks.length === 1) {+ return [marks[0], marks[0]];+ }+ let idx = bisectCenter(marks, value);+ if (idx < 0) {+ idx = 0;+ }+ // The last mark closes the final bin. Keep a drag there on that bin.+ const lastBin = marks.length - 2;+ if (idx > lastBin) {+ idx = lastBin;+ }+ return [marks[idx], marks[idx + 1] - 1];+}+export function snapToMarks(value: number, marks: number[]): number {// always use bin x0if (!marks.length) {@@ -996,7 +1022,10 @@ export function adjustValueToAnimationWindow<S extends MinVisStateForAnimationWiif (animationWindow === ANIMATION_WINDOW.interval) {val0 = snapToMarks(value1, thresholds);idx = thresholds.indexOf(val0);- val1 = idx > -1 ? datasetBins[idx].x1 : NaN;+ // x1 is the next bin's start. The filter keeps rows where value <= end,+ // so stop one millisecond early and leave that boundary to the next bin.+ const binEnd = idx > -1 ? datasetBins[idx].x1 : NaN;+ val1 = Number.isFinite(binEnd) && binEnd > val0 ? binEnd - 1 : binEnd;} else {// fit current value to windowval0 = snapToMarks(value0, thresholds);diff --git a/test/browser/components/common/animation-control-test.js b/test/browser/components/common/animation-control-test.jsindex 93b1cf118..dfb637d59 100644--- a/test/browser/components/common/animation-control-test.js+++ b/test/browser/components/common/animation-control-test.js@@ -249,3 +249,35 @@ test('Components -> AnimationController -> incremental window sweeps to the endt.end();});++test('Components -> PlaybackControls -> offers Step by Interval', t => {+ const setFilterAnimationWindow = sinon.spy();+ const wrapper = mountWithTheme(+ <IntlWrapper>+ <PlaybackControls+ isAnimatable+ speed={1}+ animationWindow={ANIMATION_WINDOW.free}+ setFilterAnimationWindow={setFilterAnimationWindow}+ startAnimation={() => {}}+ pauseAnimation={() => {}}+ resetAnimation={() => {}}+ />+ </IntlWrapper>+ );++ t.equal(wrapper.find('.animation-window-control').length, 0, 'menu starts closed');+ wrapper.find('button[data-for="animate-window"]').simulate('click');+ wrapper.update();++ const intervalButton = wrapper.find('button[data-for="interval-tooltip"]');+ t.equal(intervalButton.length, 1, 'should offer Step by Interval');+ intervalButton.simulate('click');+ t.equal(+ setFilterAnimationWindow.args[0][0],+ ANIMATION_WINDOW.interval,+ 'should select the interval window'+ );++ t.end();+});diff --git a/test/browser/components/filters/time-widget-test.js b/test/browser/components/filters/time-widget-test.jsindex 1fd6e95f0..155e9f8be 100644--- a/test/browser/components/filters/time-widget-test.js+++ b/test/browser/components/filters/time-widget-test.js@@ -8,7 +8,7 @@ import sinon from 'sinon';import moment from 'moment';import {IntlWrapper, mountWithTheme, mockHTMLElementClientSize} from 'test/helpers/component-utils';-import {setFilterAnimationTimeConfig} from '@kepler.gl/actions';+import {setFilterAnimationTimeConfig, setFilterAnimationWindow} from '@kepler.gl/actions';import {visStateReducer as reducer, DEFAULT_ANIMATION_CONFIG} from '@kepler.gl/reducers';import {@@ -246,8 +246,8 @@ test('Components -> TimeWidget.mount -> test actions', t => {);t.equal(wrapper.find('.animation-window-control').at(0).find(IconButton).length,- 1,- 'should render 1 animate window options'+ 2,+ 'should render incremental and interval window options');// select an animation option@@ -672,3 +672,44 @@ test('Components -> TimeWidget.mount -> group by field', t => {wrapper.detach();t.end();});++test('Components -> TimeWidget -> interval window locks the histogram brush to one bin', t => {+ const filterId = StateWFilters.visState.filters[0].id;+ const visState = reducer(+ StateWFilters.visState,+ setFilterAnimationWindow({id: filterId, animationWindow: 'interval'})+ );+ const setFilterAnimationTime = sinon.spy();+ let wrapper;++ t.doesNotThrow(() => {+ wrapper = mountWithTheme(+ <IntlWrapper>+ <TimeWidget+ {...defaultProps}+ datasets={visState.datasets}+ filter={visState.filters[0]}+ setFilterAnimationTime={setFilterAnimationTime}+ />+ </IntlWrapper>+ );+ }, 'TimeWidget should render in interval mode');++ const slider = wrapper.find(RangeSlider);+ t.equal(slider.length, 1, 'should render the histogram slider');+ t.equal(slider.first().props().isRanged, false, 'brush should select one bin, not a free range');++ const marks = slider.first().props().marks;+ t.ok(Array.isArray(marks) && marks.length > 1, 'brush should snap to histogram bin edges');++ slider.first().props().onChange([marks[0], marks[0]]);+ t.deepEqual(+ setFilterAnimationTime.lastCall.args[2],+ [marks[0], marks[1] - 1],+ 'should set the filter to that bin'+ );+ t.equal(wrapper.find(Icons.Interval).length, 1, 'playback bar shows Step by Interval');++ wrapper.detach();+ t.end();+});diff --git a/test/node/reducers/vis-state-test.js b/test/node/reducers/vis-state-test.jsindex 3ac07c3ca..a22e17560 100644--- a/test/node/reducers/vis-state-test.js+++ b/test/node/reducers/vis-state-test.js@@ -33,6 +33,7 @@ import {createDataContainer,applyFilterFieldName,getAnimatableVisibleLayers,+ getBinThresholds,getDefaultFilter,histogramFromDomain,LayerTimeInterval,@@ -3012,6 +3013,46 @@ test('#visStateReducer -> SET_FILTER_ANIMATION_WINDOW', t => {t.end();});+test('#visStateReducer -> SET_FILTER_ANIMATION_WINDOW interval snaps to one histogram bin', t => {+ const initialState = CloneDeep(StateWFilters.visState);+ const filter = initialState.filters[0];++ const nextState = reducer(+ initialState,+ VisStateActions.setFilterAnimationWindow({+ id: filter.id,+ animationWindow: ANIMATION_WINDOW.interval+ })+ );++ const updated = nextState.filters[0];+ t.equal(updated.animationWindow, ANIMATION_WINDOW.interval, 'should set interval window');+ t.ok(updated.plotType.interval, 'should keep a histogram interval');++ const thresholds = getBinThresholds(updated.plotType.interval, updated.domain);+ t.ok(thresholds.includes(updated.value[0]), 'bin start should be a histogram threshold');+ const idx = thresholds.indexOf(updated.value[0]);+ t.ok(idx > -1 && idx < thresholds.length - 1, 'should land on a bin, not the domain end');+ t.equal(+ updated.value[1],+ thresholds[idx + 1] - 1,+ 'bin end should stop before the next histogram threshold'+ );++ const backToFree = reducer(+ nextState,+ VisStateActions.setFilterAnimationWindow({+ id: filter.id,+ animationWindow: ANIMATION_WINDOW.free+ })+ );+ const freed = backToFree.filters[0];+ t.equal(freed.animationWindow, ANIMATION_WINDOW.free, 'should leave interval mode');+ t.ok(freed.value[1] > freed.value[0], 'should widen back to a range of at least one bin');++ t.end();+});+test('#visStateReducer -> UPDATE_FILTER_ANIMATION_SPEED', t => {const initialState = CloneDeep(StateWFilters.visState);diff --git a/test/node/utils/plot-test.js b/test/node/utils/plot-test.jsindex d59f12c43..2dd14937f 100644--- a/test/node/utils/plot-test.js+++ b/test/node/utils/plot-test.js@@ -6,6 +6,7 @@ import {histogramFromThreshold,histogramFromValues,histogramFromTimeIntervals,+ intervalBinFromMarks,mergePolygonLayerIndexes,runGpuFilterForPlot,getLineChart,@@ -534,3 +535,42 @@ test('Utils -> mergePlotGroupBy fills defaults and clears', t => {t.end();});++test('Utils -> intervalBinFromMarks snaps a brush position to one histogram bin', t => {+ const marks = [0, 100, 200, 300];++ t.deepEqual(intervalBinFromMarks(marks, 0), [0, 99], 'should select the first bin');+ t.deepEqual(+ intervalBinFromMarks(marks, 100),+ [100, 199],+ 'should select the bin that starts on the mark'+ );+ t.deepEqual(+ intervalBinFromMarks(marks, 149),+ [100, 199],+ 'should snap toward the nearer bin start'+ );+ t.deepEqual(+ intervalBinFromMarks(marks, 150),+ [200, 299],+ 'should snap to the next bin at the midpoint'+ );+ t.deepEqual(+ intervalBinFromMarks(marks, 250),+ [200, 299],+ 'should keep the right half of the last bin on that bin'+ );+ t.deepEqual(+ intervalBinFromMarks(marks, 300),+ [200, 299],+ 'should keep the final mark on the last bin'+ );+ t.deepEqual(intervalBinFromMarks([10], 10), [10, 10], 'should keep a single mark as a point');+ t.deepEqual(+ intervalBinFromMarks([], 10),+ [10, 10],+ 'should leave the value unchanged without marks'+ );++ t.end();+});