Skip to content

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

feat(filters): enable timeline charts for numeric filters (#3842)

Igor Dykhta63dceb65639a
diff --git a/src/components/src/bottom-widget.tsx b/src/components/src/bottom-widget.tsx
index 3fe57e234..b8b4f6b0d 100644
--- a/src/components/src/bottom-widget.tsx
+++ b/src/components/src/bottom-widget.tsx
@@ -4,10 +4,10 @@
import React, {forwardRef, useMemo, useCallback} from 'react';
import styled, {withTheme, IStyledComponent} from 'styled-components';
-import {FILTER_VIEW_TYPES, EXPORT_VIDEO_ID} from '@kepler.gl/constants';
+import {FILTER_TYPES, FILTER_VIEW_TYPES, EXPORT_VIDEO_ID} from '@kepler.gl/constants';
import {hasPortableWidth, isSideFilter, mergeFilterWithTimeline} from '@kepler.gl/utils';
import {media, breakPointValues} from '@kepler.gl/styles';
-import {TimeRangeFilter} from '@kepler.gl/types';
+import {Filter, RangeFilter, TimeRangeFilter} from '@kepler.gl/types';
import TimeWidgetFactory from './filters/time-widget';
import {bottomWidgetSelector} from './kepler-gl';
@@ -18,6 +18,10 @@ import {BaseComponentProps} from './types';
const maxWidth = 1080;
+function isChartFilter(filter?: Filter): filter is RangeFilter | TimeRangeFilter {
+ return filter?.type === FILTER_TYPES.timeRange || filter?.type === FILTER_TYPES.range;
+}
+
export type BottomWidgetContainerProps = BaseComponentProps & {
$hasPadding?: boolean;
width: number;
@@ -133,17 +137,18 @@ export default function BottomWidgetFactory(
// if filter is not animating, pass in enlarged filter here because
// animation controller needs to call reset on it
const filter = useMemo(
- () => (animatedFilter as TimeRangeFilter) || filters[enlargedFilterIdx],
+ () => animatedFilter || filters[enlargedFilterIdx],
[animatedFilter, filters, enlargedFilterIdx]
);
+ const chartFilter = isChartFilter(filter) ? filter : null;
// we merge filter and timeline if filter is synced
const {filter: enhancedFilter, animationConfig: enhancedAnimationConfig} = useMemo(
() =>
- filter?.syncedWithLayerTimeline
- ? mergeFilterWithTimeline(filter, animationConfig)
- : {filter, animationConfig},
- [filter, animationConfig]
+ chartFilter?.type === FILTER_TYPES.timeRange && chartFilter.syncedWithLayerTimeline
+ ? mergeFilterWithTimeline(chartFilter as TimeRangeFilter, animationConfig)
+ : {filter: chartFilter, animationConfig},
+ [chartFilter, animationConfig]
);
const exportAnimation = useCallback(() => toggleModal(EXPORT_VIDEO_ID), [toggleModal]);
@@ -204,7 +209,7 @@ export default function BottomWidgetFactory(
<TimeWidget
// TimeWidget uses React.memo, here we pass width
// even though it doesnt use it, to force rerender
- filter={enhancedFilter as TimeRangeFilter}
+ filter={enhancedFilter}
index={enlargedFilterIdx}
datasets={datasets}
layers={layers}
diff --git a/src/components/src/common/animation-control/animation-control.tsx b/src/components/src/common/animation-control/animation-control.tsx
index d67660ea2..2fb390c63 100644
--- a/src/components/src/common/animation-control/animation-control.tsx
+++ b/src/components/src/common/animation-control/animation-control.tsx
@@ -83,6 +83,7 @@ export type AnimationControlProps = {
showControls?: boolean;
className?: string;
style?: object;
+ formatTimelineValue?: (value: number) => string;
};
AnimationControlFactory.deps = [
@@ -115,7 +116,8 @@ function AnimationControlFactory(
timeline,
showTimeline = true,
showControls = true,
- showTimeDisplay = true
+ showTimeDisplay = true,
+ formatTimelineValue
}) => {
if (!timeline) {
return null;
@@ -134,6 +136,7 @@ function AnimationControlFactory(
style={TIMELINE_PLAYBACK_STYLE}
timeline={timeline}
setTimelineValue={setTimelineValue}
+ formatValue={formatTimelineValue}
/>
) : null}
{showControls ? (
diff --git a/src/components/src/common/animation-control/animation-controller.ts b/src/components/src/common/animation-control/animation-controller.ts
index 1730f5f28..3ac49523f 100644
--- a/src/components/src/common/animation-control/animation-controller.ts
+++ b/src/components/src/common/animation-control/animation-controller.ts
@@ -19,6 +19,7 @@ interface AnimationControllerProps<T extends number | number[]> {
domain: number[] | null;
value: T;
baseSpeed?: number;
+ minimumIncrement?: number;
children?: (
isAnimating: boolean | undefined,
startAnimation: () => void,
@@ -115,7 +116,7 @@ function AnimationControllerFactory(): typeof AnimationControllerType {
};
_resetAnimationByDomain = () => {
- const {domain, value, animationWindow, updateAnimation} = this.props;
+ const {domain, value, animationWindow, updateAnimation, minimumIncrement} = this.props;
if (!domain) {
return;
}
@@ -124,7 +125,11 @@ function AnimationControllerFactory(): typeof AnimationControllerType {
if (Array.isArray(value)) {
const windowSize = value[1] - value[0];
if (animationWindow === ANIMATION_WINDOW.incremental) {
- setTimelineValue([value[0], value[0] + 1] as T);
+ const resetEnd =
+ minimumIncrement === undefined
+ ? value[0] + 1
+ : Math.min(domain[1], value[0] + minimumIncrement);
+ setTimelineValue([value[0], resetEnd] as T);
} else {
const startValue = domain[0] - windowSize;
setTimelineValue([startValue, startValue + windowSize] as T);
@@ -200,11 +205,21 @@ function AnimationControllerFactory(): typeof AnimationControllerType {
};
_nextFrameByDomain() {
- const {domain, value, speed = 1, baseSpeed = 600, animationWindow, steps} = this.props;
+ const {
+ domain,
+ value,
+ speed = 1,
+ baseSpeed = 600,
+ animationWindow,
+ steps,
+ minimumIncrement
+ } = this.props;
if (!domain) {
return;
}
- const delta = ((domain[1] - domain[0]) / baseSpeed) * speed;
+ const rawDelta = ((domain[1] - domain[0]) / baseSpeed) * speed;
+ const delta =
+ minimumIncrement === undefined ? rawDelta : Math.max(rawDelta, minimumIncrement);
// loop when reaches the end
// current time is a range
@@ -219,7 +234,11 @@ function AnimationControllerFactory(): typeof AnimationControllerType {
// thresholds with the last one popped, so the last bin ends one bin
// width past the last step.
let endOfSweep = domain[1];
- if (Array.isArray(steps) && steps.length > 1) {
+ // Time domains end on their last timestamp while their calendar bin
+ // can extend farther, so retain the existing extrapolation there.
+ // Numeric bins already close on the numeric domain (and can include a
+ // terminal zero-width maximum bin), so never sweep past domain[1].
+ if (minimumIncrement === undefined && Array.isArray(steps) && steps.length > 1) {
const endOfLastBin =
steps[steps.length - 1] + (steps[steps.length - 1] - steps[steps.length - 2]);
if (Number.isFinite(endOfLastBin) && endOfLastBin > endOfSweep) {
@@ -229,7 +248,12 @@ function AnimationControllerFactory(): typeof AnimationControllerType {
value0 = value[0];
// clamp the last step instead of discarding it, and loop back to the
// anchor only after the final frame was emitted
- value1 = value[1] >= endOfSweep ? value[0] + 1 : Math.min(value[1] + delta, endOfSweep);
+ value1 =
+ value[1] >= endOfSweep
+ ? minimumIncrement === undefined
+ ? value[0] + 1
+ : Math.min(domain[1], value[0] + minimumIncrement)
+ : Math.min(value[1] + delta, endOfSweep);
} else {
const lastFrame = value[0] + delta > domain[1];
const startValue = domain[0] - windowSize;
diff --git a/src/components/src/common/animation-control/floating-time-display.tsx b/src/components/src/common/animation-control/floating-time-display.tsx
index f4458d738..27a801530 100644
--- a/src/components/src/common/animation-control/floating-time-display.tsx
+++ b/src/components/src/common/animation-control/floating-time-display.tsx
@@ -107,6 +107,8 @@ interface FloatingTimeDisplayProps {
defaultTimeFormat?: string | null;
timeFormat?: string | null;
timezone?: string | null;
+ formatValue?: (value: number) => string;
+ displayLabel?: string | null;
}
export default function FloatingTimeDisplayFactory() {
@@ -114,10 +116,15 @@ export default function FloatingTimeDisplayFactory() {
currentTime,
defaultTimeFormat,
timeFormat,
- timezone
+ timezone,
+ formatValue,
+ displayLabel
}: FloatingTimeDisplayProps) => {
const {displayDate, displayTime} = useMemo(() => {
const groupTime = Array.isArray(currentTime) ? currentTime : [currentTime];
+ if (formatValue) {
+ return {displayDate: groupTime.map(formatValue), displayTime: []};
+ }
const hasUserFormat = typeof timeFormat === 'string';
const currentFormat = (hasUserFormat ? timeFormat : defaultTimeFormat) || DEFAULT_TIME_FORMAT;
const dateFunc = datetimeFormatter(timezone);
@@ -146,11 +153,15 @@ export default function FloatingTimeDisplayFactory() {
},
{displayDate: [], displayTime: []} as {displayDate: string[]; displayTime: string[]}
);
- }, [currentTime, timeFormat, defaultTimeFormat, timezone]);
+ }, [currentTime, timeFormat, defaultTimeFormat, timezone, formatValue]);
const twoGroups = displayDate.length === 2 && displayTime.length === 2;
const bottomRow = displayTime.length ? displayTime : displayDate.length ? displayDate : null;
- const topRow = displayDate.length && displayTime.length ? displayDate : null;
+ const topRow = displayLabel
+ ? [displayLabel]
+ : displayDate.length && displayTime.length
+ ? displayDate
+ : null;
return (
<StyledTimeDisplayWrapper>
diff --git a/src/components/src/common/line-chart.tsx b/src/components/src/common/line-chart.tsx
index 7b8bc0ea9..d5438d27d 100644
--- a/src/components/src/common/line-chart.tsx
+++ b/src/components/src/common/line-chart.tsx
@@ -6,7 +6,7 @@ import {scaleTime, scaleLinear} from 'd3-scale';
import {bisector} from 'd3-array';
import {LineChart} from '@kepler.gl/types';
import styled, {withTheme} from 'styled-components';
-import {datetimeFormatter} from '@kepler.gl/utils';
+import {datetimeFormatter, formatNumber} from '@kepler.gl/utils';
export interface LineSeriesPoint {
x: number;
@@ -151,6 +151,7 @@ interface LineChartProps {
timeFormat?: string;
range?: number[];
yAxisAutoRange?: boolean;
+ isTime?: boolean;
theme?: any;
}
@@ -172,6 +173,7 @@ function LineChartFactory() {
timeFormat,
range,
yAxisAutoRange,
+ isTime = true,
theme
}: LineChartProps) => {
const svgRef = useRef<SVGSVGElement>(null);
@@ -234,10 +236,12 @@ function LineChartFactory() {
const xScale = useMemo(() => {
if (!effectiveXDomain || effectiveXDomain.length < 2) return null;
- return scaleTime()
- .domain([new Date(effectiveXDomain[0]), new Date(effectiveXDomain[1])])
- .range([0, width]);
- }, [effectiveXDomain, width]);
+ return isTime
+ ? scaleTime()
+ .domain([new Date(effectiveXDomain[0]), new Date(effectiveXDomain[1])])
+ .range([0, width])
+ : scaleLinear().domain(effectiveXDomain).range([0, width]);
+ }, [effectiveXDomain, isTime, width]);
const yScale = useMemo(() => {
if (!paddedYDomain || paddedYDomain.length < 2) return null;
@@ -245,8 +249,11 @@ function LineChartFactory() {
}, [paddedYDomain, height]);
const hintFormatter = useMemo(
- () => datetimeFormatter(timezone)(timeFormat),
- [timezone, timeFormat]
+ () =>
+ isTime
+ ? datetimeFormatter(timezone)(timeFormat)
+ : (value: number) => formatNumber(value),
+ [isTime, timezone, timeFormat]
);
const clampedHoveredDP = useMemo(() => {
@@ -280,28 +287,29 @@ function LineChartFactory() {
paths.push({
key: index,
d: `M${points
- .map(point => `${xScale(new Date(point.x))},${yScale(point.y)}`)
+ .map(point => `${xScale(isTime ? new Date(point.x) : point.x)},${yScale(point.y)}`)
.join('L')}`,
color: markColor
});
} else if (points.length === 1) {
dots.push({
key: index,
- x: xScale(new Date(points[0].x)),
+ x: xScale(isTime ? new Date(points[0].x) : points[0].x),
y: yScale(points[0].y),
color: markColor
});
}
});
return {paths, dots};
- }, [xScale, yScale, series, lineColor]);
+ }, [isTime, xScale, yScale, series, lineColor]);
const bisectX = useMemo(() => bisector<LineSeriesPoint, number>(d => d.x).left, []);
const findNearestPoint = useCallback(
(mouseX: number) => {
if (!xScale || !series?.lines) return null;
- const xValue = xScale.invert(mouseX).getTime();
+ const inverted = xScale.invert(mouseX);
+ const xValue = inverted instanceof Date ? inverted.getTime() : inverted;
let bestX: number | null = null;
let minDist = Infinity;
series.lines.forEach(line => {
@@ -363,14 +371,14 @@ function LineChartFactory() {
const hintPosition = useMemo(() => {
if (!clampedHoveredDP || !xScale || !yScale) return null;
return placeLineChartHint(
- xScale(new Date(clampedHoveredDP.x)),
+ xScale(isTime ? new Date(clampedHoveredDP.x) : clampedHoveredDP.x),
yScale(clampedHoveredDP.y),
hintSize.width,
hintSize.height,
width,
height
);
- }, [clampedHoveredDP, xScale, yScale, hintSize, width, height]);
+ }, [clampedHoveredDP, xScale, yScale, hintSize, width, height, isTime]);
useLayoutEffect(() => {
const node = hintRef.current;
@@ -426,7 +434,7 @@ function LineChartFactory() {
point.y == null ? null : (
<circle
key={`${point.name ?? 'series'}-${index}`}
- cx={xScale(new Date(point.x))}
+ cx={xScale(isTime ? new Date(point.x) : point.x)}
cy={yScale(point.y)}
r={4}
fill={String(point.color || lineColor)}
diff --git a/src/components/src/common/range-plot.tsx b/src/components/src/common/range-plot.tsx
index d8213ef45..f25938e02 100644
--- a/src/components/src/common/range-plot.tsx
+++ b/src/components/src/common/range-plot.tsx
@@ -36,6 +36,7 @@ interface RangePlotProps {
timeFormat?: string;
timezone?: string | null;
playbackControlWidth?: number;
+ isTime?: boolean;
animationWindow?: string;
filter?: Filter;
diff --git a/src/components/src/common/range-slider.tsx b/src/components/src/common/range-slider.tsx
index da7b0b5b9..9c66c259e 100644
--- a/src/components/src/common/range-slider.tsx
+++ b/src/components/src/common/range-slider.tsx
@@ -71,6 +71,7 @@ interface RangeSliderProps {
timezone?: string | null;
timeFormat?: string;
+ isTime?: boolean;
playbackControlWidth?: number;
lineChart?: LineChart;
marks?: number[];
@@ -155,6 +156,9 @@ export default function RangeSliderFactory(
);
_isTimeFilter = () => {
+ if (typeof this.props.isTime === 'boolean') {
+ return this.props.isTime;
+ }
return typeof this.props.timeFormat === 'string';
};
@@ -282,6 +286,7 @@ export default function RangeSliderFactory(
step,
timezone,
timeFormat,
+ isTime,
playbackControlWidth,
setFilterPlot,
animationWindow,
@@ -334,6 +339,7 @@ export default function RangeSliderFactory(
step={step}
timezone={timezone}
timeFormat={timeFormat}
+ isTime={isTime}
playbackControlWidth={playbackControlWidth}
setFilterPlot={setFilterPlot}
style={{paddingLeft: commonPadding}}
@@ -358,6 +364,7 @@ export default function RangeSliderFactory(
timezone={timezone}
domain={displayRange}
isEnlarged={this.props.isEnlarged}
+ isTime={isTime}
/>
</div>
) : null}
diff --git a/src/components/src/common/time-range-slider-time-title.tsx b/src/components/src/common/time-range-slider-time-title.tsx
index 41b17a0a2..86792a36e 100644
--- a/src/components/src/common/time-range-slider-time-title.tsx
+++ b/src/components/src/common/time-range-slider-time-title.tsx
@@ -4,7 +4,7 @@
import React from 'react';
import styled, {IStyledComponent} from 'styled-components';
import {Minus} from './icons';
-import {datetimeFormatter} from '@kepler.gl/utils';
+import {datetimeFormatter, formatNumber} from '@kepler.gl/utils';
import {BaseComponentProps} from '../types';
export type TimeValueWrapperProps = BaseComponentProps & {
@@ -53,20 +53,34 @@ interface TimeTitleProps {
isEnlarged?: boolean;
timezone?: string | null;
timeFormat: string;
+ isTime?: boolean;
+ fieldType?: string;
}
function TimeRangeSliderTimeTitleFactory() {
- const TimeTitle = ({value, isEnlarged, timezone, timeFormat}: TimeTitleProps) => (
- <TimeValueWrapper $isEnlarged={isEnlarged} className="time-range-slider__time-title">
- <TimeValue key={0} value={datetimeFormatter(timezone)(timeFormat)(value[0])} />
- {isEnlarged ? (
- <div className="horizontal-bar">
- <Minus height="12px" />
- </div>
- ) : null}
- <TimeValue key={1} value={datetimeFormatter(timezone)(timeFormat)(value[1])} />
- </TimeValueWrapper>
- );
+ const TimeTitle = ({
+ value,
+ isEnlarged,
+ timezone,
+ timeFormat,
+ isTime = true,
+ fieldType
+ }: TimeTitleProps) => {
+ const formatValue = isTime
+ ? datetimeFormatter(timezone)(timeFormat)
+ : (numericValue: number) => formatNumber(numericValue, fieldType);
+ return (
+ <TimeValueWrapper $isEnlarged={isEnlarged} className="time-range-slider__time-title">
+ <TimeValue key={0} value={formatValue(value[0])} />
+ {isEnlarged ? (
+ <div className="horizontal-bar">
+ <Minus height="12px" />
+ </div>
+ ) : null}
+ <TimeValue key={1} value={formatValue(value[1])} />
+ </TimeValueWrapper>
+ );
+ };
return TimeTitle;
}
diff --git a/src/components/src/common/time-range-slider.tsx b/src/components/src/common/time-range-slider.tsx
index 31c121799..6332df2ea 100644
--- a/src/components/src/common/time-range-slider.tsx
+++ b/src/components/src/common/time-range-slider.tsx
@@ -9,10 +9,10 @@ import RangeSliderFactory from './range-slider';
import TimeSliderMarkerFactory from './time-slider-marker';
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 {LineChart, Timeline, AnimationConfig, TimeBins, Filter, Bins} 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 {intervalBinFromMarks} from '@kepler.gl/utils';
import AnimationControlFactory from './animation-control/animation-control';
import {BaseComponentProps} from '../types';
@@ -29,6 +29,7 @@ type TimeRangeSliderProps = {
timeFormat: string;
timezone?: string | null;
timeBins?: TimeBins;
+ bins?: Bins;
plotType?: {
[key: string]: any;
};
@@ -36,7 +37,7 @@ type TimeRangeSliderProps = {
step: number;
isAnimatable?: boolean;
speed: number;
- animationWindow: string;
+ animationWindow?: string;
resetAnimation?: () => void;
toggleAnimation: () => void;
exportAnimation?: () => void;
@@ -48,6 +49,8 @@ type TimeRangeSliderProps = {
invertTrendColor?: boolean;
animationConfig?: AnimationConfig;
filter?: Filter;
+ isTime?: boolean;
+ formatValue?: (value: number) => string;
};
export type StyledSliderContainerProps = BaseComponentProps & {
@@ -120,13 +123,14 @@ export default function TimeRangeSliderFactory(
timeFormat,
timezone,
timeBins,
+ bins,
plotType,
lineChart,
invertTrendColor,
step,
isAnimatable,
speed,
- animationWindow,
+ animationWindow = ANIMATION_WINDOW.free,
updateAnimationSpeed,
setFilterAnimationWindow,
toggleAnimation,
@@ -134,16 +138,18 @@ export default function TimeRangeSliderFactory(
onChange,
setFilterPlot,
timeline,
- filter
+ filter,
+ isTime = true,
+ formatValue
} = props;
const binMarks = useMemo(() => {
- if (animationWindow !== ANIMATION_WINDOW.interval || !plotType?.interval || !domain) {
+ if (animationWindow !== ANIMATION_WINDOW.interval || !domain) {
return null;
}
- const thresholds = getBinThresholds(plotType.interval, domain);
+ const thresholds = timeline?.marks || [];
return thresholds.length > 1 ? thresholds : null;
- }, [animationWindow, domain, plotType?.interval]);
+ }, [animationWindow, domain, timeline?.marks]);
const byInterval = Boolean(binMarks);
const sliderRange = useMemo(() => {
@@ -162,20 +168,20 @@ export default function TimeRangeSliderFactory(
// 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));
+ onChange(intervalBinFromMarks(binMarks, anchor, isTime ? 1 : 0));
return;
}
onChange(val);
},
- [binMarks, byInterval, onChange]
+ [binMarks, byInterval, isTime, onChange]
);
const throttledOnchange = useMemo(() => throttle(onSliderChange, 20), [onSliderChange]);
useEffect(() => () => throttledOnchange.cancel(), [throttledOnchange]);
const binsForInterval = useMemo(
- () => getTimeBinsForInterval(timeBins, plotType?.interval),
- [timeBins, plotType?.interval]
+ () => (isTime ? getTimeBinsForInterval(timeBins, plotType?.interval) : bins || {}),
+ [bins, isTime, plotType?.interval, timeBins]
);
const width = animationControlWidth + (exportAnimation ? animationControlExportWidth : 0);
@@ -195,6 +201,8 @@ export default function TimeRangeSliderFactory(
timezone={timezone}
value={value}
isEnlarged={isEnlarged}
+ isTime={isTime}
+ fieldType={filter?.fieldType}
/>
</div>
) : null}
@@ -222,6 +230,7 @@ export default function TimeRangeSliderFactory(
animationWindow={animationWindow}
onChange={throttledOnchange}
xAxis={TimeSliderMarker}
+ isTime={isTime}
timezone={timezone}
timeFormat={timeFormat}
setFilterPlot={setFilterPlot}
@@ -241,6 +250,7 @@ export default function TimeRangeSliderFactory(
showTimeDisplay={false}
timeline={timeline}
filter={filter}
+ formatTimelineValue={formatValue}
/>
)}
{isEnlarged && !isMinified ? (
diff --git a/src/components/src/common/time-slider-marker.tsx b/src/components/src/common/time-slider-marker.tsx
index 6114b35fc..36982d1f2 100644
--- a/src/components/src/common/time-slider-marker.tsx
+++ b/src/components/src/common/time-slider-marker.tsx
@@ -3,11 +3,11 @@
import React, {useRef, useEffect, useMemo} from 'react';
import moment from 'moment-timezone';
-import {NumberValue, scaleUtc} from 'd3-scale';
+import {NumberValue, scaleLinear, scaleUtc} from 'd3-scale';
import {select} from 'd3-selection';
import {axisBottom} from 'd3-axis';
import styled from 'styled-components';
-import {datetimeFormatter} from '@kepler.gl/utils';
+import {datetimeFormatter, formatNumber} from '@kepler.gl/utils';
const MIN_TICK_WIDTH_LARGE = 80;
const MIN_TICK_WIDTH_SMALL = 50;
@@ -97,18 +97,25 @@ export function getXAxis(
domain: Date[] | NumberValue[],
width: number,
isEnlarged: boolean,
- timezone: string
+ timezone: string,
+ isTime = true
) {
if (!Array.isArray(domain) || !domain.every(Number.isFinite)) {
return null;
}
- const scale = scaleUtc().domain(domain).range([0, width]);
+ const scale = isTime
+ ? scaleUtc().domain(domain).range([0, width])
+ : scaleLinear().domain(domain.map(Number)).range([0, width]);
if (!scale) {
return null;
}
const ticks = Math.floor(width / (isEnlarged ? MIN_TICK_WIDTH_LARGE : MIN_TICK_WIDTH_SMALL));
- const tickFormat = timezone ? getTickFormat(timezone) : null;
+ const tickFormat = isTime
+ ? timezone
+ ? getTickFormat(timezone)
+ : null
+ : (value: NumberValue) => formatNumber(Number(value));
const xAxis = axisBottom(scale).ticks(ticks).tickSize(4).tickPadding(4);
if (tickFormat) {
xAxis.tickFormat(tickFormat);
@@ -131,6 +138,7 @@ interface TimeSliderMarkerProps {
isEnlarged?: boolean;
height?: number;
timezone: string;
+ isTime?: boolean;
}
function TimeSliderMarkerFactory() {
@@ -139,12 +147,13 @@ function TimeSliderMarkerFactory() {
domain,
isEnlarged = true,
height = HEIGHT,
- timezone
+ timezone,
+ isTime = true
}: TimeSliderMarkerProps) => {
const xAxisRef = useRef(null);
const xAxis = useMemo(
- () => getXAxis(domain, width, isEnlarged, timezone),
- [domain, width, isEnlarged, timezone]
+ () => getXAxis(domain, width, isEnlarged, timezone, isTime),
+ [domain, width, isEnlarged, timezone, isTime]
);
useEffect(() => {
updateAxis(xAxisRef, xAxis);
diff --git a/src/components/src/common/timeline-helpers.ts b/src/components/src/common/timeline-helpers.ts
index 519f11593..682305e12 100644
--- a/src/components/src/common/timeline-helpers.ts
+++ b/src/components/src/common/timeline-helpers.ts
@@ -16,12 +16,13 @@ export function rangesEqual(
export function clampRange(
[start, end]: [number, number],
- [min, max]: [number, number]
+ [min, max]: [number, number],
+ minimumWidth = 1
): [number, number] {
const clampedStart = clamp([min, max], start);
let clampedEnd = clamp([min, max], end);
if (clampedEnd <= clampedStart) {
- clampedEnd = Math.min(max, clampedStart + 1);
+ clampedEnd = Math.min(max, clampedStart + minimumWidth);
}
return [clampedStart, clampedEnd];
}
@@ -29,13 +30,14 @@ export function clampRange(
export function clampWindowToDomain(
windowStart: number,
windowEnd: number,
- domainRange: [number, number]
+ domainRange: [number, number],
+ minimumWidth = 1
): [number, number] {
const [domainStart, domainEnd] = domainRange;
let nextStart = clamp(domainRange, windowStart);
let nextEnd = clamp(domainRange, windowEnd);
if (nextEnd <= nextStart) {
- const width = Math.max(windowEnd - windowStart, 1);
+ const width = Math.max(windowEnd - windowStart, minimumWidth);
const maxStart = Math.max(domainStart, domainEnd - width);
nextStart = clamp([domainStart, maxStart], windowStart);
nextEnd = nextStart + width;
@@ -45,7 +47,7 @@ export function clampWindowToDomain(
}
}
if (nextEnd <= nextStart) {
- nextEnd = Math.min(domainEnd, nextStart + 1);
+ nextEnd = Math.min(domainEnd, nextStart + minimumWidth);
}
return [nextStart, nextEnd];
}
diff --git a/src/components/src/common/timeline-slider.tsx b/src/components/src/common/timeline-slider.tsx
index a362d9c89..5aec58ef3 100644
--- a/src/components/src/common/timeline-slider.tsx
+++ b/src/components/src/common/timeline-slider.tsx
@@ -63,6 +63,7 @@ interface TimelineSliderProps {
height?: number;
className?: string | null;
style?: object;
+ formatValue?: (value: number) => string;
}
function TimelineSliderFactory() {
@@ -74,7 +75,8 @@ function TimelineSliderFactory() {
showDomainTimes = true,
height = PROGRESS_BAR_HEIGHT,
className = null,
- style
+ style,
+ formatValue
}) => {
const onThrottleUpdate = useMemo(() => throttle(setTimelineValue, 20), [setTimelineValue]);
@@ -124,12 +126,18 @@ function TimelineSliderFactory() {
return [null, null];
}
- const hasUserFormat = typeof timeFormat === 'string';
- const currentFormat = (hasUserFormat ? timeFormat : defaultTimeFormat) || DEFAULT_TIME_FORMAT;
- const dateFunc = datetimeFormatter(timezone)(currentFormat);
+ const valueFormatter = formatValue || (() => {
+ const hasUserFormat = typeof timeFormat === 'string';
+ const currentFormat =
+ (hasUserFormat ? timeFormat : defaultTimeFormat) || DEFAULT_TIME_FORMAT;
+ return datetimeFormatter(timezone)(currentFormat);
+ })();
- return [domain ? dateFunc(domain[0]) : '', domain ? dateFunc(domain[1]) : ''];
- }, [domain, timezone, timeFormat, defaultTimeFormat, showDomainTimes]);
+ return [
+ domain ? valueFormatter(domain[0]) : '',
+ domain ? valueFormatter(domain[1]) : ''
+ ];
+ }, [domain, timezone, timeFormat, defaultTimeFormat, showDomainTimes, formatValue]);
const requiresRangeSlider = isRanged && animationWindow !== ANIMATION_WINDOW.interval;
diff --git a/src/components/src/filter-animation-controller.tsx b/src/components/src/filter-animation-controller.tsx
index ea31c109f..2253c9dd3 100644
--- a/src/components/src/filter-animation-controller.tsx
+++ b/src/components/src/filter-animation-controller.tsx
@@ -2,14 +2,19 @@
// Copyright contributors to the kepler.gl project
import React, {useCallback, useMemo} from 'react';
-import {getBinThresholds, getTimelineFromFilter} from '@kepler.gl/utils';
-import {TimeRangeFilter} from '@kepler.gl/types';
-import {ANIMATION_WINDOW} from '@kepler.gl/constants';
+import {
+ getFilterBinThresholds,
+ getNumericRangeMinimum,
+ getTimelineFromFilter,
+ intervalBinFromMarks
+} from '@kepler.gl/utils';
+import {RangeFilter, TimeRangeFilter} from '@kepler.gl/types';
+import {ANIMATION_WINDOW, FILTER_TYPES} from '@kepler.gl/constants';
import AnimationControllerFactory from './common/animation-control/animation-controller';
import {Timeline} from '@kepler.gl/types';
interface FilterAnimationControllerProps {
- filter: TimeRangeFilter & {animationWindow?: string};
+ filter: TimeRangeFilter | RangeFilter;
filterIdx: number;
setFilterAnimationTime: (idx: number, value: string, a: any[]) => void;
children?: (
@@ -33,8 +38,16 @@ function FilterAnimationControllerFactory(
children
}) => {
const binThresholds = useMemo(() => {
- return getBinThresholds(filter.plotType?.interval, filter.domain);
- }, [filter.plotType?.interval, filter.domain]);
+ return getFilterBinThresholds(filter);
+ }, [filter]);
+ const isTimeFilter = filter.type === FILTER_TYPES.timeRange;
+ const intervalEndOffset = isTimeFilter ? 1 : 0;
+ const numericAnimationIncrement = useMemo(() => {
+ if (isTimeFilter) {
+ return undefined;
+ }
+ return getNumericRangeMinimum(filter.domain);
+ }, [filter.domain, isTimeFilter]);
const steps = useMemo(() => {
if (binThresholds) {
@@ -53,10 +66,11 @@ function FilterAnimationControllerFactory(
case ANIMATION_WINDOW.interval: {
const idx = value[1];
if (idx < binThresholds.length - 1) {
- setFilterAnimationTime(filterIdx, 'value', [
- binThresholds[idx],
- binThresholds[idx + 1] - 1
- ]);
+ setFilterAnimationTime(
+ filterIdx,
+ 'value',
+ intervalBinFromMarks(binThresholds, binThresholds[idx], intervalEndOffset)
+ );
}
break;
}
@@ -65,7 +79,7 @@ function FilterAnimationControllerFactory(
break;
}
},
- [filterIdx, binThresholds, filter.animationWindow, setFilterAnimationTime]
+ [filterIdx, binThresholds, filter.animationWindow, intervalEndOffset, setFilterAnimationTime]
);
// if filter is synced merge the filter and animation config
@@ -80,6 +94,7 @@ function FilterAnimationControllerFactory(
isAnimating={filter.isAnimating}
animationWindow={filter.animationWindow}
steps={steps}
+ minimumIncrement={numericAnimationIncrement}
updateAnimation={updateAnimation}
// @ts-expect-error different function type, goes to TimeWidget setFilterAnimationTime()
setTimelineValue={setFilterAnimationTime}
diff --git a/src/components/src/filters/filter-panels/range-filter-panel.tsx b/src/components/src/filters/filter-panels/range-filter-panel.tsx
index 796b10eab..99a4f7f1f 100644
--- a/src/components/src/filters/filter-panels/range-filter-panel.tsx
+++ b/src/components/src/filters/filter-panels/range-filter-panel.tsx
@@ -1,11 +1,12 @@
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
-import React, {useCallback} from 'react';
+import React, {useCallback, useMemo} from 'react';
import RangeFilterFactory from '../range-filter';
-import {RangeFilter} from '@kepler.gl/types';
import FieldPanelWithFieldSelectFactory from './filter-panel-with-field-select';
-import {FilterPanelComponent} from './types';
+import {RangeFilterPanelComponent} from './types';
+import {Clock} from '../../common/icons';
+import {isSideFilter} from '@kepler.gl/utils';
RangeFilterPanelFactory.deps = [FieldPanelWithFieldSelectFactory, RangeFilterFactory];
@@ -13,13 +14,35 @@ function RangeFilterPanelFactory(
FieldPanelWithFieldSelect: ReturnType<typeof FieldPanelWithFieldSelectFactory>,
RangeFilterComponent: ReturnType<typeof RangeFilterFactory>
) {
- const RangeFilterPanel: FilterPanelComponent<RangeFilter> = React.memo(
- ({idx, datasets, allAvailableFields, filter, removeFilter, setFilter, setFilterPlot}) => {
+ const RangeFilterPanel: RangeFilterPanelComponent = React.memo(
+ ({
+ idx,
+ datasets,
+ allAvailableFields,
+ filter,
+ removeFilter,
+ enlargeFilter,
+ setFilter,
+ setFilterPlot
+ }) => {
const onSetFilter = useCallback(value => setFilter(idx, 'value', value), [idx, setFilter]);
const onSetFilterPlot = useCallback(
(newProp, valueIndex) => setFilterPlot(idx, newProp, valueIndex),
[idx, setFilterPlot]
);
+ const isEnlarged = !isSideFilter(filter);
+ const panelActions = useMemo(
+ () => [
+ {
+ id: filter.id,
+ onClick: enlargeFilter,
+ tooltip: 'tooltip.timePlayback',
+ iconComponent: Clock,
+ active: isEnlarged
+ }
+ ],
+ [enlargeFilter, filter.id, isEnlarged]
+ );
return (
<div className="range-filter-panel">
@@ -30,8 +53,9 @@ function RangeFilterPanelFactory(
idx={idx}
removeFilter={removeFilter}
setFilter={setFilter}
+ panelActions={panelActions}
>
- {filter.type && (
+ {filter.type && !isEnlarged && (
<div className="filter-panel__filter">
<RangeFilterComponent
filter={filter}
diff --git a/src/components/src/filters/filter-panels/types.ts b/src/components/src/filters/filter-panels/types.ts
index 663dadfe7..2846e8180 100644
--- a/src/components/src/filters/filter-panels/types.ts
+++ b/src/components/src/filters/filter-panels/types.ts
@@ -2,7 +2,7 @@
// Copyright contributors to the kepler.gl project
import {FunctionComponent, ComponentType, ReactNode} from 'react';
-import {Filter, PolygonFilter, TimeRangeFilter, Field} from '@kepler.gl/types';
+import {Filter, PolygonFilter, RangeFilter, TimeRangeFilter, Field} from '@kepler.gl/types';
import {Layer} from '@kepler.gl/layers';
import {Datasets} from '@kepler.gl/table';
import {setFilter, setFilterPlot, syncTimeFilterWithLayerTimeline} from '@kepler.gl/actions';
@@ -37,6 +37,10 @@ export interface TimeRangeFilterPanelProps extends FilterPanelProps<TimeRangeFil
enlargeFilter: () => void;
toggleAnimation: () => void;
}
+export interface RangeFilterPanelProps extends FilterPanelProps<RangeFilter> {
+ enlargeFilter: () => void;
+ toggleAnimation: () => void;
+}
export interface FilterPanelWithFieldSelectProps extends FilterPanelProps {
panelActions?: ReadonlyArray<PanelAction>;
}
@@ -44,6 +48,7 @@ export interface FilterPanelWithFieldSelectProps extends FilterPanelProps {
export type FilterPanelComponent<F> = FunctionComponent<FilterPanelProps<F>>;
export type PolygonFilterPanelComponent = FunctionComponent<PolygonFilterPanelProps>;
export type TimeRangeFilterPanelComponent = FunctionComponent<TimeRangeFilterPanelProps>;
+export type RangeFilterPanelComponent = FunctionComponent<RangeFilterPanelProps>;
export type FilterPanelWithFieldSelectComponent = FunctionComponent<
Omit<FilterPanelWithFieldSelectProps, 'setFilterPlot'>
>;
diff --git a/src/components/src/filters/range-filter.tsx b/src/components/src/filters/range-filter.tsx
index bdc833d64..8678379da 100644
--- a/src/components/src/filters/range-filter.tsx
+++ b/src/components/src/filters/range-filter.tsx
@@ -18,11 +18,13 @@ export default function RangeFilterFactory(RangeSlider: ReturnType<typeof RangeS
value1={filter.value[1]}
step={filter.step}
bins={filter.bins}
+ lineChart={filter.lineChart}
isEnlarged={filter.view === FILTER_VIEW_TYPES.enlarged}
onChange={setFilter}
setFilterPlot={setFilterPlot}
inputTheme="secondary"
plotType={filter.plotType}
+ isTime={false}
/>
</div>
);
diff --git a/src/components/src/filters/time-range-filter.tsx b/src/components/src/filters/time-range-filter.tsx
index 5384c9420..5ced8c4af 100644
--- a/src/components/src/filters/time-range-filter.tsx
+++ b/src/components/src/filters/time-range-filter.tsx
@@ -4,7 +4,7 @@
import React from 'react';
import TimeRangeSliderFactory from '../common/time-range-slider';
import {DEFAULT_TIME_FORMAT, FILTER_VIEW_TYPES} from '@kepler.gl/constants';
-import {TimeRangeFilter} from '@kepler.gl/types';
+import {RangeFilter, TimeRangeFilter} from '@kepler.gl/types';
import {Datasets} from '@kepler.gl/table';
import {Layer} from '@kepler.gl/layers';
import {TimeRangeFilterProps} from './types';
@@ -12,18 +12,23 @@ import {TimeRangeFilterProps} from './types';
* TimeRangeFilter -> TimeRangeSlider -> RangeSlider
*/
export function timeRangeSliderFieldsSelector(
- filter: TimeRangeFilter,
+ filter: TimeRangeFilter | RangeFilter,
datasets: Datasets,
layers: readonly Layer[]
) {
- const hasUserFormat = typeof filter.timeFormat === 'string';
- const timeFormat =
- (hasUserFormat ? filter.timeFormat : filter.defaultTimeFormat) || DEFAULT_TIME_FORMAT;
+ const isTime = filter.type === 'timeRange';
+ const timeFilter = isTime ? filter : null;
+ const hasUserFormat = typeof timeFilter?.timeFormat === 'string';
+ const timeFormat = isTime
+ ? (hasUserFormat ? timeFilter?.timeFormat : timeFilter?.defaultTimeFormat) ||
+ DEFAULT_TIME_FORMAT
+ : '';
return {
id: filter.id,
- domain: filter.domain,
- timeBins: filter.timeBins,
+ domain: filter.domain as [number, number],
+ timeBins: timeFilter?.timeBins,
+ bins: !isTime ? filter.bins : undefined,
value: filter.value,
plotType: filter.plotType,
lineChart: filter.lineChart,
@@ -32,8 +37,9 @@ export function timeRangeSliderFieldsSelector(
speed: filter.speed,
animationWindow: filter.animationWindow,
isAnimating: filter.isAnimating,
- timezone: filter.timezone,
+ timezone: timeFilter?.timezone,
timeFormat,
+ isTime,
filter,
datasets,
layers,
diff --git a/src/components/src/filters/time-widget-settings.tsx b/src/components/src/filters/time-widget-settings.tsx
index b6ce5ec48..5d21e144f 100644
--- a/src/components/src/filters/time-widget-settings.tsx
+++ b/src/components/src/filters/time-widget-settings.tsx
@@ -23,10 +23,18 @@ import {
durationMonth,
durationYear
} from '@kepler.gl/constants';
-import {TimeRangeFilter, Field, ColorRange, ColorUI, NestedPartial} from '@kepler.gl/types';
+import {
+ TimeRangeFilter,
+ RangeFilter,
+ Field,
+ ColorRange,
+ ColorUI,
+ NestedPartial
+} from '@kepler.gl/types';
import {Datasets} from '@kepler.gl/table';
import {
getDefaultTimeFormat,
+ getNumericPlotInterval,
PLOT_NUM_GROUPS_ALL,
PLOT_NUM_GROUPS_OPTIONS,
DEFAULT_PLOT_NUM_GROUPS,
@@ -53,6 +61,7 @@ const INTERVAL_UNITS = [
];
const TIME_FORMAT_OPTIONS = ['12-hour', '24-hour'] as const;
+const SELECTOR_WIDTH = '120px';
type HourCycle = (typeof TIME_FORMAT_OPTIONS)[number];
@@ -202,7 +211,7 @@ const FieldValue = styled.span`
`;
const SelectorWrapper = styled.div`
- width: 120px;
+ width: ${SELECTOR_WIDTH};
.item-selector__dropdown {
background: ${props => props.theme.secondaryInputBgd};
@@ -227,10 +236,11 @@ const FieldSelectorWrapper = styled.div`
type StepInputProps = {
$hasError?: boolean;
+ $fullWidth?: boolean;
};
const StepInput = styled.input<StepInputProps>`
- width: 48px;
+ width: ${props => (props.$fullWidth ? SELECTOR_WIDTH : '48px')};
height: 28px;
padding: 2px 8px;
font-size: 11px;
@@ -371,7 +381,7 @@ function colorRangeFromColorUI(
}
export type TimeWidgetSettingsProps = {
- filter: TimeRangeFilter;
+ filter: TimeRangeFilter | RangeFilter;
datasets: Datasets;
setFilterPlot: (newProp: any, valueIndex?: number) => void;
onTimezoneChange: (timezone: string) => void;
@@ -400,39 +410,47 @@ function TimeWidgetSettingsFactory(
onTimezoneChange,
onTimeFormatChange
}) => {
+ const isTimeFilter = filter.type === 'timeRange';
const {plotType} = filter;
- const currentInterval = plotType?.interval;
+ const currentInterval = isTimeFilter ? plotType?.interval : undefined;
const currentAggregation = plotType?.aggregation || AGGREGATION_TYPES.average;
const {step: parsedStep, unit: parsedUnit} = useMemo(
() => parseInterval(currentInterval),
[currentInterval]
);
+ const intervalStep = useMemo(
+ () => (isTimeFilter ? parsedStep : getNumericPlotInterval(filter)),
+ [filter, isTimeFilter, parsedStep]
+ );
- const [stepValue, setStepValue] = useState<string>(String(parsedStep));
+ const [stepValue, setStepValue] = useState<string>(String(intervalStep));
const [unitValue, setUnitValue] = useState<string>(parsedUnit);
useEffect(() => {
- setStepValue(String(parsedStep));
- }, [parsedStep]);
+ setStepValue(String(intervalStep));
+ }, [intervalStep]);
useEffect(() => {
setUnitValue(parsedUnit);
}, [parsedUnit]);
const effectiveStep = useMemo(() => {
- const num = parseInt(stepValue, 10);
- return num > 0 ? num : parsedStep;
- }, [stepValue, parsedStep]);
+ const num = isTimeFilter ? parseInt(stepValue, 10) : Number(stepValue);
+ return num > 0 ? num : intervalStep;
+ }, [intervalStep, isTimeFilter, stepValue]);
const isIntervalTooSmall = useCallback(
(step: number, unit: string) => {
const timeSpan = filter.domain ? filter.domain[1] - filter.domain[0] : 0;
+ if (!isTimeFilter) {
+ return timeSpan / step > MAX_BINS;
+ }
const unitDuration = INTERVAL_UNITS.find(u => u.id === unit)?.duration || durationDay;
const count = timeSpan / (step * unitDuration);
return count > MAX_BINS;
},
- [filter.domain]
+ [filter.domain, isTimeFilter]
);
const intervalTooSmall = useMemo(() => {
@@ -464,11 +482,15 @@ function TimeWidgetSettingsFactory(
if (isIntervalTooSmall(step, unit)) {
return;
}
- const intervalId = `${step}-${unit}`;
- const defaultTimeFormat = getDefaultTimeFormat(intervalId);
- setFilterPlot({plotType: {interval: intervalId, defaultTimeFormat}});
+ if (isTimeFilter) {
+ const intervalId = `${step}-${unit}`;
+ const defaultTimeFormat = getDefaultTimeFormat(intervalId);
+ setFilterPlot({plotType: {interval: intervalId, defaultTimeFormat}});
+ } else {
+ setFilterPlot({plotType: {numericInterval: step}});
+ }
},
- [setFilterPlot, isIntervalTooSmall]
+ [setFilterPlot, isIntervalTooSmall, isTimeFilter]
);
const onStepChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
@@ -477,13 +499,13 @@ function TimeWidgetSettingsFactory(
}, []);
const onStepBlur = useCallback(() => {
- const num = parseInt(stepValue, 10);
+ const num = isTimeFilter ? parseInt(stepValue, 10) : Number(stepValue);
if (num > 0) {
applyInterval(num, unitValue);
} else {
- setStepValue(String(parsedStep));
+ setStepValue(String(intervalStep));
}
- }, [stepValue, unitValue, parsedStep, applyInterval]);
+ }, [stepValue, unitValue, intervalStep, applyInterval, isTimeFilter]);
const onStepKeyDown = useCallback((e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') {
@@ -593,9 +615,11 @@ function TimeWidgetSettingsFactory(
[aggregationOptions]
);
+ const timeFilter = isTimeFilter ? filter : null;
const effectiveTimeFormat =
- (typeof filter.timeFormat === 'string' ? filter.timeFormat : filter.defaultTimeFormat) ||
- DEFAULT_TIME_FORMAT;
+ (typeof timeFilter?.timeFormat === 'string'
+ ? timeFilter.timeFormat
+ : timeFilter?.defaultTimeFormat) || DEFAULT_TIME_FORMAT;
const selectedTimeFormat = getHourCycle(effectiveTimeFormat) || getLocaleHourCycle();
const handleTimeFormatChange = useCallback(
@@ -622,58 +646,69 @@ function TimeWidgetSettingsFactory(
</FieldValue>
</FieldBlock>
<FieldBlock>
- <FieldLabel>Interval</FieldLabel>
+ <FieldLabel>{isTimeFilter ? 'Interval' : 'Bin size'}</FieldLabel>
<IntervalGroup>
<StepInput
type="number"
- min={1}
+ data-testid={isTimeFilter ? undefined : 'numeric-bin-size'}
+ min={isTimeFilter ? 1 : filter.step}
+ step={isTimeFilter ? 1 : 'any'}
value={stepValue}
onChange={onStepChange}
onBlur={onStepBlur}
onKeyDown={onStepKeyDown}
$hasError={intervalTooSmall}
+ $fullWidth={!isTimeFilter}
/>
- <UnitSelectorWrapper $hasError={intervalTooSmall}>
- <ItemSelector
- selectedItems={unitValue}
- options={INTERVAL_UNITS}
- multiSelect={false}
- onChange={onUnitChange}
- getOptionValue={o => o.id}
- displayOption={displayUnitOption}
- placement="top"
- searchable={false}
- />
- </UnitSelectorWrapper>
+ {isTimeFilter ? (
+ <UnitSelectorWrapper $hasError={intervalTooSmall}>
+ <ItemSelector
+ selectedItems={unitValue}
+ options={INTERVAL_UNITS}
+ multiSelect={false}
+ onChange={onUnitChange}
+ getOptionValue={o => o.id}
+ displayOption={displayUnitOption}
+ placement="top"
+ searchable={false}
+ />
+ </UnitSelectorWrapper>
+ ) : null}
</IntervalGroup>
</FieldBlock>
- <FieldBlock>
- <FieldLabel>
- <FormattedMessage id="filterManager.timezone" />
- </FieldLabel>
- <TimezoneSelector timezone={filter.timezone} onChange={onTimezoneChange} />
- </FieldBlock>
- <FieldBlock>
- <FieldLabel id="time-widget-time-format-label">
- <FormattedMessage id="filterManager.timeFormat" />
- </FieldLabel>
- <SelectorWrapper
- data-testid="time-widget-time-format"
- aria-labelledby="time-widget-time-format-label"
- >
- <ItemSelector
- size="small"
- selectedItems={selectedTimeFormat}
- options={TIME_FORMAT_OPTIONS}
- multiSelect={false}
- searchable={false}
- placement="top"
- onChange={handleTimeFormatChange}
- />
- </SelectorWrapper>
- </FieldBlock>
+ {isTimeFilter ? (
+ <>
+ <FieldBlock>
+ <FieldLabel>
+ <FormattedMessage id="filterManager.timezone" />
+ </FieldLabel>
+ <TimezoneSelector timezone={filter.timezone} onChange={onTimezoneChange} />
+ </FieldBlock>
+ <FieldBlock>
+ <FieldLabel id="time-widget-time-format-label">
+ <FormattedMessage id="filterManager.timeFormat" />
+ </FieldLabel>
+ <SelectorWrapper
+ data-testid="time-widget-time-format"
+ aria-labelledby="time-widget-time-format-label"
+ >
+ <ItemSelector
+ size="small"
+ selectedItems={selectedTimeFormat}
+ options={TIME_FORMAT_OPTIONS}
+ multiSelect={false}
+ searchable={false}
+ placement="top"
+ onChange={handleTimeFormatChange}
+ />
+ </SelectorWrapper>
+ </FieldBlock>
+ </>
+ ) : null}
</AxisRow>
- {intervalTooSmall ? <ErrorMessage>Interval is too small</ErrorMessage> : null}
+ {intervalTooSmall ? (
+ <ErrorMessage>{isTimeFilter ? 'Interval' : 'Bin size'} is too small</ErrorMessage>
+ ) : null}
</AxisSection>
<AxisSection>
<AxisHeader>
@@ -698,7 +733,7 @@ function TimeWidgetSettingsFactory(
<DisabledBlock $disabled={!filter.yAxis}>
<FieldBlock>
<FieldLabel>Aggregation</FieldLabel>
- <SelectorWrapper>
+ <SelectorWrapper data-testid="time-widget-aggregation">
<ItemSelector
selectedItems={currentAggregation}
options={aggregationOptions}
diff --git a/src/components/src/filters/time-widget-top.tsx b/src/components/src/filters/time-widget-top.tsx
index afa78f2f6..b2c2f3041 100644
--- a/src/components/src/filters/time-widget-top.tsx
+++ b/src/components/src/filters/time-widget-top.tsx
@@ -7,6 +7,9 @@ import {Clock, Close, ArrowDown, ArrowUp, Gear} from '../common/icons';
import {SelectTextBold, IconRoundSmall, CenterFlexbox} from '../common/styled-components';
import {TimeWidgetTopProps, TopSectionWrapperProps} from './types';
import {TIME_AGGREGATION, AGGREGATION_TYPES} from '@kepler.gl/constants';
+import {FILTER_TYPES} from '@kepler.gl/constants';
+import {formatNumber, getNumericPlotInterval} from '@kepler.gl/utils';
+import {RangeFilter} from '@kepler.gl/types';
const TOP_SECTION_HEIGHT = '36px';
@@ -58,6 +61,18 @@ function TimeWidgetTopFactory() {
onToggleSettings
}) => {
const chartTitle = useMemo(() => {
+ if (filter.type === FILTER_TYPES.range) {
+ const rangeFilter = filter as RangeFilter;
+ const xAxisName = Array.isArray(rangeFilter.name) ? rangeFilter.name[0] : rangeFilter.name;
+ const binWidth = getNumericPlotInterval(rangeFilter);
+ const binLabel = binWidth ? ` (${formatNumber(binWidth, rangeFilter.fieldType)} bins)` : '';
+ if (!rangeFilter.yAxis) {
+ return `Count of Rows by ${xAxisName}${binLabel}`;
+ }
+ const aggregation = rangeFilter.plotType?.aggregation || AGGREGATION_TYPES.average;
+ const aggLabel = TIME_AGGREGATION.find(a => a.id === aggregation)?.label || aggregation;
+ return `${aggLabel} ${rangeFilter.yAxis.name} by ${xAxisName}${binLabel}`;
+ }
const interval = filter.plotType?.interval;
let intervalLabel = 'Time';
if (interval) {
@@ -72,7 +87,7 @@ function TimeWidgetTopFactory() {
const aggregation = filter.plotType?.aggregation || AGGREGATION_TYPES.average;
const aggLabel = TIME_AGGREGATION.find(a => a.id === aggregation)?.label || aggregation;
return `${aggLabel} ${filter.yAxis.name} per ${intervalLabel}`;
- }, [filter.yAxis, filter.plotType?.aggregation, filter.plotType?.interval]);
+ }, [filter]);
return (
<TopSectionWrapper>
diff --git a/src/components/src/filters/time-widget.tsx b/src/components/src/filters/time-widget.tsx
index 6f80e8f97..08ede446f 100644
--- a/src/components/src/filters/time-widget.tsx
+++ b/src/components/src/filters/time-widget.tsx
@@ -4,11 +4,18 @@
import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
import styled from 'styled-components';
import throttle from 'es-toolkit/compat/throttle';
-import {ANIMATION_WINDOW, DEFAULT_TIME_FORMAT, FILTER_VIEW_TYPES} from '@kepler.gl/constants';
+import {
+ ANIMATION_WINDOW,
+ DEFAULT_TIME_FORMAT,
+ FILTER_TYPES,
+ FILTER_VIEW_TYPES
+} from '@kepler.gl/constants';
import {
clamp,
datetimeFormatter,
- getBinThresholds,
+ formatNumber,
+ getNumericRangeMinimum,
+ getTimelineFromFilter,
intervalBinFromMarks,
lineChartSeriesLegend
} from '@kepler.gl/utils';
@@ -124,6 +131,12 @@ function TimeWidgetFactory(
timeline
}: TimeWidgetProps) => {
const [showSettings, setShowSettings] = useState(false);
+ const isTimeFilter = filter.type === FILTER_TYPES.timeRange;
+ const timeFilter = isTimeFilter ? filter : null;
+ const filterTimeline = useMemo(
+ () => timeline || getTimelineFromFilter(filter),
+ [filter, timeline]
+ );
const _updateAnimationSpeed = useCallback(
speed => updateAnimationSpeed(index, speed),
@@ -172,6 +185,13 @@ function TimeWidgetFactory(
const fullDomain = Array.isArray(timeRangeSlideProps.domain)
? (timeRangeSlideProps.domain as [number, number])
: null;
+ const minimumRangeWidth = useMemo(() => {
+ if (isTimeFilter || !fullDomain) {
+ return 1;
+ }
+ return getNumericRangeMinimum(fullDomain);
+ }, [fullDomain, isTimeFilter]);
+ const rangeEqualityEpsilon = isTimeFilter ? 1 : 0;
const [timelineDomain, setTimelineDomain] = useState<[number, number] | null>(null);
const timelineContainerRef = useRef<HTMLDivElement | null>(null);
@@ -184,13 +204,13 @@ function TimeWidgetFactory(
return;
}
if (timelineDomain) {
- const clamped = clampRange(timelineDomain, fullDomain);
- if (!rangesEqual(clamped, timelineDomain)) {
+ const clamped = clampRange(timelineDomain, fullDomain, minimumRangeWidth);
+ if (!rangesEqual(clamped, timelineDomain, rangeEqualityEpsilon)) {
setTimelineDomain(clamped);
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [fullDomain]);
+ }, [fullDomain, minimumRangeWidth, rangeEqualityEpsilon]);
const sliderDomain = timelineDomain ?? fullDomain ?? undefined;
const displayedTimelineDomain = sliderDomain ?? null;
@@ -199,27 +219,32 @@ function TimeWidgetFactory(
if (!timelineDomain || !fullDomain) {
return false;
}
- return !rangesEqual(timelineDomain, fullDomain);
- }, [timelineDomain, fullDomain]);
+ return !rangesEqual(timelineDomain, fullDomain, rangeEqualityEpsilon);
+ }, [timelineDomain, fullDomain, rangeEqualityEpsilon]);
const timeFormat =
timeRangeSlideProps.timeFormat ||
- filter.timeFormat ||
- filter.defaultTimeFormat ||
+ timeFilter?.timeFormat ||
+ timeFilter?.defaultTimeFormat ||
DEFAULT_TIME_FORMAT;
const formatTimestamp = useMemo(() => {
- const formatter = datetimeFormatter(filter.timezone);
+ const formatter = datetimeFormatter(timeFilter?.timezone);
return (value: number) => formatter(timeFormat)(value);
- }, [filter.timezone, timeFormat]);
+ }, [timeFilter?.timezone, timeFormat]);
+ const formatNumeric = useCallback(
+ (value: number) => formatNumber(value, filter.fieldType),
+ [filter.fieldType]
+ );
+ const formatTimelineValue = isTimeFilter ? formatTimestamp : formatNumeric;
const timelineRangeLabel = useMemo(() => {
if (!displayedTimelineDomain) {
return '';
}
- return `${formatTimestamp(displayedTimelineDomain[0])} – ${formatTimestamp(
+ return `${formatTimelineValue(displayedTimelineDomain[0])} – ${formatTimelineValue(
displayedTimelineDomain[1]
)}`;
- }, [displayedTimelineDomain, formatTimestamp]);
+ }, [displayedTimelineDomain, formatTimelineValue]);
const [filterStart, filterEnd] = filter.value;
@@ -238,7 +263,9 @@ function TimeWidgetFactory(
if (!(windowWidth > 0)) {
return;
}
- const minWidth = Math.max(domainWidth / 100, 1);
+ const minWidth = isTimeFilter
+ ? Math.max(domainWidth / 100, 1)
+ : Math.max(domainWidth / 100, minimumRangeWidth);
const nextWidth = clamp([minWidth, domainWidth], windowWidth / factor);
const clampedCenter = clamp(domainRange, center);
const ratio = clamp(
@@ -247,7 +274,12 @@ function TimeWidgetFactory(
);
const nextStart = clampedCenter - ratio * nextWidth;
const nextEnd = nextStart + nextWidth;
- const [clampedStart, clampedEnd] = clampWindowToDomain(nextStart, nextEnd, domainRange);
+ const [clampedStart, clampedEnd] = clampWindowToDomain(
+ nextStart,
+ nextEnd,
+ domainRange,
+ minimumRangeWidth
+ );
if (clampedStart !== filterStart || clampedEnd !== filterEnd) {
setFilterAnimationTime(index, 'value', [clampedStart, clampedEnd]);
}
@@ -258,6 +290,8 @@ function TimeWidgetFactory(
filterStart,
fullDomain,
index,
+ isTimeFilter,
+ minimumRangeWidth,
setFilterAnimationTime,
timelineDomain
]
@@ -274,9 +308,13 @@ function TimeWidgetFactory(
if (!(fullWidth > 0)) {
return;
}
- const baseWidth = Math.max(domainRange[1] - domainRange[0], 1);
+ const baseWidth = isTimeFilter
+ ? Math.max(domainRange[1] - domainRange[0], 1)
+ : domainRange[1] - domainRange[0];
const clampedCenter = clamp(domainRange, center);
- const minWidth = Math.max(fullWidth / 20, 1);
+ const minWidth = isTimeFilter
+ ? Math.max(fullWidth / 20, 1)
+ : Math.max(fullWidth / 20, minimumRangeWidth);
const nextWidth = clamp([minWidth, fullWidth], baseWidth / factor);
const ratio = clamp(
[0, 1],
@@ -296,8 +334,14 @@ function TimeWidgetFactory(
nextEnd = domainEnd;
nextStart -= shift;
}
- const nextRange: [number, number] = clampRange([nextStart, nextEnd], fullDomain);
- setTimelineDomain(prev => (rangesEqual(prev, nextRange) ? prev : nextRange));
+ const nextRange: [number, number] = clampRange(
+ [nextStart, nextEnd],
+ fullDomain,
+ minimumRangeWidth
+ );
+ setTimelineDomain(prev =>
+ rangesEqual(prev, nextRange, rangeEqualityEpsilon) ? prev : nextRange
+ );
// Pinch-zoom only changes the visible domain. The selected bin stays put.
if (filter.animationWindow === ANIMATION_WINDOW.interval) {
@@ -308,13 +352,23 @@ function TimeWidgetFactory(
let windowEnd = filterEnd;
const rangeWidth = nextRange[1] - nextRange[0];
if (rangeWidth < windowEnd - windowStart) {
- const windowWidth = Math.max(windowEnd - windowStart, 1);
+ const windowWidth = Math.max(windowEnd - windowStart, minimumRangeWidth);
const windowRatio = clamp([0, 1], (clampedCenter - windowStart) / windowWidth);
const adjustedStart = clampedCenter - windowRatio * rangeWidth;
const adjustedEnd = clampedCenter + (1 - windowRatio) * rangeWidth;
- [windowStart, windowEnd] = clampWindowToDomain(adjustedStart, adjustedEnd, nextRange);
+ [windowStart, windowEnd] = clampWindowToDomain(
+ adjustedStart,
+ adjustedEnd,
+ nextRange,
+ minimumRangeWidth
+ );
} else {
- [windowStart, windowEnd] = clampWindowToDomain(windowStart, windowEnd, nextRange);
+ [windowStart, windowEnd] = clampWindowToDomain(
+ windowStart,
+ windowEnd,
+ nextRange,
+ minimumRangeWidth
+ );
}
if (windowStart !== filterStart || windowEnd !== filterEnd) {
setFilterAnimationTime(index, 'value', [windowStart, windowEnd]);
@@ -326,6 +380,9 @@ function TimeWidgetFactory(
filterStart,
fullDomain,
index,
+ isTimeFilter,
+ minimumRangeWidth,
+ rangeEqualityEpsilon,
setFilterAnimationTime,
timelineDomain
]
@@ -416,18 +473,14 @@ function TimeWidgetFactory(
return;
}
event.preventDefault();
- if (
- filter.animationWindow === ANIMATION_WINDOW.interval &&
- filter.plotType?.interval &&
- fullDomain
- ) {
- const marks = getBinThresholds(filter.plotType.interval, fullDomain);
+ if (filter.animationWindow === ANIMATION_WINDOW.interval && fullDomain) {
+ const marks = filterTimeline.marks || [];
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]);
+ const nextBin = intervalBinFromMarks(marks, marks[nextIdx], isTimeFilter ? 1 : 0);
if (nextBin[0] !== filterStart || nextBin[1] !== filterEnd) {
setFilterAnimationTime(index, 'value', nextBin);
}
@@ -446,7 +499,12 @@ function TimeWidgetFactory(
nextStart = filterStart - windowWidth;
nextEnd = filterStart;
}
- [nextStart, nextEnd] = clampWindowToDomain(nextStart, nextEnd, domainRange);
+ [nextStart, nextEnd] = clampWindowToDomain(
+ nextStart,
+ nextEnd,
+ domainRange,
+ minimumRangeWidth
+ );
if (nextStart !== filterStart || nextEnd !== filterEnd) {
setFilterAnimationTime(index, 'value', [nextStart, nextEnd]);
}
@@ -455,13 +513,16 @@ function TimeWidgetFactory(
return () => window.removeEventListener('keydown', handler);
}, [
filter.animationWindow,
- filter.plotType?.interval,
+ filter.step,
filterEnd,
filterStart,
fullDomain,
index,
isMinified,
+ isTimeFilter,
+ minimumRangeWidth,
setFilterAnimationTime,
+ filterTimeline.marks,
timelineDomain
]);
@@ -520,7 +581,10 @@ function TimeWidgetFactory(
</Button>
</TimelineStatusBar>
) : null}
- <TimelineContainer ref={timelineContainerRef}>
+ <TimelineContainer
+ ref={timelineContainerRef}
+ data-testid="time-widget-timeline-container"
+ >
<TimeRangeSlider
{...timeRangeSlideProps}
domain={sliderDomain}
@@ -535,16 +599,21 @@ function TimeWidgetFactory(
setFilterPlot={_setFilterPlot}
animationConfig={animationConfig}
isMinified={isMinified}
- timeline={timeline}
+ timeline={filterTimeline}
+ formatValue={isTimeFilter ? undefined : formatNumeric}
/>
</TimelineContainer>
</TimelineSection>
{showTimeDisplay ? (
<FloatingTimeDisplay
currentTime={filter.value}
- defaultTimeFormat={filter.defaultTimeFormat}
- timeFormat={filter.timeFormat}
- timezone={filter.timezone}
+ defaultTimeFormat={timeFilter?.defaultTimeFormat}
+ timeFormat={timeFilter?.timeFormat}
+ timezone={timeFilter?.timezone}
+ formatValue={isTimeFilter ? undefined : formatNumeric}
+ displayLabel={
+ isTimeFilter ? undefined : Array.isArray(filter.name) ? filter.name[0] : filter.name
+ }
/>
) : null}
</TimeBottomWidgetInner>
diff --git a/src/components/src/filters/types.ts b/src/components/src/filters/types.ts
index 973ce192f..03d230744 100644
--- a/src/components/src/filters/types.ts
+++ b/src/components/src/filters/types.ts
@@ -79,7 +79,7 @@ export type TimeWidgetTopProps = {
export type TimeWidgetProps = {
layers: Layer[];
datasets: Datasets;
- filter: TimeRangeFilter;
+ filter: TimeRangeFilter | RangeFilter;
index: number;
readOnly: boolean;
showTimeDisplay: boolean;
diff --git a/src/reducers/src/vis-state-updaters.ts b/src/reducers/src/vis-state-updaters.ts
index 44c28fd4e..cfa5d6125 100644
--- a/src/reducers/src/vis-state-updaters.ts
+++ b/src/reducers/src/vis-state-updaters.ts
@@ -190,6 +190,7 @@ import {
Editor,
Field,
LayerVisConfig,
+ RangeFilter,
TimeRangeFilter,
Annotation,
AnnotationPropsPartial,
@@ -1454,12 +1455,12 @@ export function setFilterAnimationWindowUpdater<S extends VisState>(
// Entering or leaving interval playback snaps the window onto histogram bins.
if (
- filter.type === FILTER_TYPES.timeRange &&
+ (filter.type === FILTER_TYPES.timeRange || filter.type === FILTER_TYPES.range) &&
(previousWindow === ANIMATION_WINDOW.interval || animationWindow === ANIMATION_WINDOW.interval)
) {
const adjusted = adjustValueToAnimationWindow(
state,
- nextFilter as TimeRangeFilter,
+ nextFilter as TimeRangeFilter | RangeFilter,
getPlotBaseIndexByDataId(state.datasets, nextFilter, state.layers)
);
if (Array.isArray(adjusted.value) && adjusted.value.every(v => Number.isFinite(v))) {
@@ -1467,13 +1468,28 @@ export function setFilterAnimationWindowUpdater<S extends VisState>(
}
}
+ if (filter.type === FILTER_TYPES.range) {
+ const filterIndex = state.filters.indexOf(filter);
+ return setFilterUpdater(
+ state,
+ setFilter(
+ filterIndex,
+ ['animationWindow', 'value'],
+ [animationWindow, nextFilter.value]
+ )
+ );
+ }
+
const newState = {
...state,
filters: swap_<Filter>(nextFilter)(state.filters)
};
- const newSyncTimelineMode = getSyncAnimationMode(nextFilter as TimeRangeFilter);
+ if (filter.type !== FILTER_TYPES.timeRange) {
+ return newState;
+ }
+ const newSyncTimelineMode = getSyncAnimationMode(nextFilter as TimeRangeFilter);
return setTimeFilterTimelineModeUpdater(newState, {id, mode: newSyncTimelineMode});
}
@@ -1518,7 +1534,10 @@ function updateFilterPlotsAfterFiltering<S extends VisState>(
return updateFilterPlot(state.datasets, filter, undefined, state.layers);
}
- if (filter.type !== FILTER_TYPES.timeRange) {
+ const shouldRefreshNumericPlot =
+ filter.type === FILTER_TYPES.range &&
+ (!isSideFilter(filter) || filter.plotType?.type === PLOT_TYPES.lineChart);
+ if (filter.type !== FILTER_TYPES.timeRange && !shouldRefreshNumericPlot) {
return filter;
}
@@ -1643,8 +1662,7 @@ function _updateFilterDataIdAtValueIndex(filter, valueIndex, value, datasets, fi
const dataset = datasets[value];
const field = dataset?.fields.find(candidate => candidate.name === fieldName);
const canRebindField =
- field &&
- (!filter.fieldType || areFilterFieldTypesCompatible(filter.fieldType, field.type));
+ field && (!filter.fieldType || areFilterFieldTypesCompatible(filter.fieldType, field.type));
const {filter: reboundFilter} = canRebindField
? applyFilterFieldName(nextFilter, datasets, value, fieldName, valueIndex, {
mergeDomain: true
@@ -1920,6 +1938,7 @@ export const setFilterPlotUpdater = (
return state;
}
let newFilter = state.filters[idx];
+ const previousNumericInterval = newFilter.plotType?.numericInterval;
for (const prop in newProp) {
if (prop === 'plotType') {
@@ -1938,12 +1957,36 @@ export const setFilterPlotUpdater = (
}
}
+ const numericIntervalChanged =
+ newFilter.type === FILTER_TYPES.range &&
+ newFilter.plotType?.numericInterval !== previousNumericInterval;
+ if (numericIntervalChanged) {
+ newFilter = {...(newFilter as RangeFilter), bins: undefined, lineChart: undefined};
+ }
+
newFilter = updateFilterPlot(state.datasets, newFilter, undefined, state.layers);
- return {
+ const newState = {
...state,
filters: state.filters.map((f, i) => (i === idx ? newFilter : f))
};
+
+ if (
+ numericIntervalChanged &&
+ newFilter.type === FILTER_TYPES.range &&
+ newFilter.animationWindow === ANIMATION_WINDOW.interval
+ ) {
+ const adjusted = adjustValueToAnimationWindow(
+ newState,
+ newFilter as RangeFilter,
+ getPlotBaseIndexByDataId(newState.datasets, newFilter, newState.layers)
+ );
+ if (Array.isArray(adjusted.value) && adjusted.value.every(Number.isFinite)) {
+ return setFilterUpdater(newState, {idx, prop: 'value', value: adjusted.value});
+ }
+ }
+
+ return newState;
};
/**
@@ -2165,21 +2208,29 @@ export const setFilterViewUpdater = (
) => {
const {view, idx} = action;
const shouldResetOtherFiltersView = view === FILTER_VIEW_TYPES.enlarged;
+ const filters = state.filters.map((f, i) =>
+ i === idx
+ ? {
+ ...f,
+ view
+ }
+ : shouldResetOtherFiltersView
+ ? {
+ ...f,
+ view: FILTER_VIEW_TYPES.side
+ }
+ : f
+ );
+
+ const openedFilter = filters[idx];
+ if (view === FILTER_VIEW_TYPES.enlarged && openedFilter?.type === FILTER_TYPES.range) {
+ const invalidatedFilter = toArray(openedFilter.dataId).reduce(removeFilterPlot, openedFilter);
+ filters[idx] = updateFilterPlot(state.datasets, invalidatedFilter, undefined, state.layers);
+ }
+
return {
...state,
- filters: state.filters.map((f, i) =>
- i === idx
- ? {
- ...f,
- view
- }
- : shouldResetOtherFiltersView
- ? {
- ...f,
- view: FILTER_VIEW_TYPES.side
- }
- : f
- )
+ filters
};
};
diff --git a/src/table/src/gpu-filter-utils.ts b/src/table/src/gpu-filter-utils.ts
index e93fc24f2..a370c1814 100644
--- a/src/table/src/gpu-filter-utils.ts
+++ b/src/table/src/gpu-filter-utils.ts
@@ -4,7 +4,12 @@
import moment from 'moment';
import {MAX_GPU_FILTERS, FILTER_TYPES} from '@kepler.gl/constants';
import {Field, Filter, TimeRangeFilter} from '@kepler.gl/types';
-import {set, DataContainerInterface, isTimeIntervalFilter} from '@kepler.gl/utils';
+import {
+ set,
+ DataContainerInterface,
+ isNumericIntervalFilter,
+ isTimeIntervalFilter
+} from '@kepler.gl/utils';
import {toArray, notNullorUndefined} from '@kepler.gl/common-utils';
import {GpuFilter} from './kepler-table';
@@ -303,6 +308,7 @@ function findFilterOnGpuChannel(
return filters.find(
f =>
f.gpu &&
+ !isNumericIntervalFilter(f) &&
f.dataId.includes(dataId) &&
f.gpuChannel &&
f.gpuChannel[f.dataId.indexOf(dataId)] === channel
@@ -317,6 +323,7 @@ function findFilterOnGpuEndChannel(
return filters.find(
f =>
f.gpu &&
+ !isNumericIntervalFilter(f) &&
f.dataId.includes(dataId) &&
f.gpuEndChannel &&
f.gpuEndChannel[f.dataId.indexOf(dataId)] === channel
diff --git a/src/types/reducers.d.ts b/src/types/reducers.d.ts
index c1489f953..1c3b367c6 100644
--- a/src/types/reducers.d.ts
+++ b/src/types/reducers.d.ts
@@ -158,9 +158,9 @@ export type LineChart = {
// Is this a valid part of LineChart?
aggregation: string;
- interval: string;
+ interval: string | number | null;
yAxis: string;
- bins?: Bins;
+ bins?: Bins | Bin[];
/** Cache key for timeline series grouping. Null when the plot is a single series. */
groupBy?: LineChartGroupBy | null;
};
@@ -181,6 +181,7 @@ export type FilterBase<L extends LineChart> = {
fixedDomain: boolean;
view: FilterViewType;
isAnimating: boolean;
+ animationWindow?: string;
speed: number;
showTimeDisplay?: boolean;
@@ -298,6 +299,7 @@ export interface TimeBins {
export interface PlotType {
interval: ValueOf<Interval>;
+ numericInterval?: number;
type: ValueOf<PlotTypes>;
aggregation: ValueOf<AggregationTypes>;
defaultTimeFormat: string;
@@ -379,16 +381,9 @@ export type AnimationConfig = {
hideControl?: boolean;
};
-export type FilterAnimationConfig = Pick<
- TimeRangeFilter,
- | 'dataId'
- | 'value'
- | 'animationWindow'
- | 'speed'
- | 'syncedWithLayerTimeline'
- | 'syncTimelineMode'
- | 'timezone'
->;
+export type FilterAnimationConfig = Pick<Filter, 'dataId' | 'value' | 'speed'> &
+ Required<Pick<Filter, 'animationWindow'>> &
+ Partial<Pick<TimeRangeFilter, 'syncedWithLayerTimeline' | 'syncTimelineMode' | 'timezone'>>;
export type Timeline = {
domain: [number, number] | null;
diff --git a/src/utils/src/filter-utils.ts b/src/utils/src/filter-utils.ts
index 3277550fd..1d54d96a9 100644
--- a/src/utils/src/filter-utils.ts
+++ b/src/utils/src/filter-utils.ts
@@ -151,6 +151,17 @@ export function isTimeIntervalFilter(filter: Filter, datasetIdx = 0): boolean {
);
}
+/**
+ * Numeric interval playback uses half-open histogram bins. GPU range filters
+ * are inclusive and use Float32 precision, so exact bin membership must use
+ * the CPU path while this mode is active.
+ */
+export function isNumericIntervalFilter(filter: Filter): boolean {
+ return (
+ filter?.type === FILTER_TYPES.range && filter.animationWindow === ANIMATION_WINDOW.interval
+ );
+}
+
function isFullTimeDomainValue(filter: TimeRangeFilter): boolean {
return (
Array.isArray(filter.value) &&
@@ -921,7 +932,10 @@ export function getFilterRecord(
: filterRecord.dynamicDomain
).push(f);
- (f.gpu && !opt.cpuOnly ? filterRecord.gpu : filterRecord.cpu).push(f);
+ (f.gpu && !opt.cpuOnly && !isNumericIntervalFilter(f)
+ ? filterRecord.gpu
+ : filterRecord.cpu
+ ).push(f);
}
});
@@ -1349,6 +1363,42 @@ export function applyFilterFieldName<K extends KeplerTableModel<K, L>, L>(
...(filter.plotType ? {plotType: filter.plotType} : {})
};
+ if (filter.type === FILTER_TYPES.range && newFilter.type === FILTER_TYPES.range) {
+ newFilter = {...newFilter, view: filter.view};
+ }
+
+ if (filter.type === FILTER_TYPES.timeRange && newFilter.type === FILTER_TYPES.range) {
+ const {
+ timeBins: _timeBins,
+ timezone: _timezone,
+ timeFormat: _timeFormat,
+ defaultTimeFormat: _defaultTimeFormat,
+ syncedWithLayerTimeline: _syncedWithLayerTimeline,
+ syncTimelineMode: _syncTimelineMode,
+ ...numericFilter
+ } = newFilter as TimeRangeFilter;
+ const {
+ interval: _interval,
+ defaultTimeFormat: _plotTimeFormat,
+ ...numericPlotType
+ } = numericFilter.plotType || {};
+ newFilter = {
+ ...numericFilter,
+ isAnimating: false,
+ animationWindow: ANIMATION_WINDOW.free,
+ plotType: numericPlotType,
+ lineChart: undefined
+ };
+ } else if (filter.type === FILTER_TYPES.range && newFilter.type === FILTER_TYPES.timeRange) {
+ const {numericInterval: _numericInterval, ...timePlotType} = newFilter.plotType || {};
+ newFilter = {
+ ...newFilter,
+ bins: undefined,
+ plotType: timePlotType,
+ lineChart: undefined
+ };
+ }
+
if (newFilter.type !== FILTER_TYPES.timeRange) {
newFilter = omitTimeIntervalFields(newFilter);
} else if (toArray(newFilter.endName)[filterDatasetIndex] === fieldName) {
diff --git a/src/utils/src/index.ts b/src/utils/src/index.ts
index 62fa317e8..68a31faec 100644
--- a/src/utils/src/index.ts
+++ b/src/utils/src/index.ts
@@ -50,6 +50,12 @@ export type {
export {
adjustValueToAnimationWindow,
getBinThresholds,
+ getNumericBinThresholds,
+ getNumericPlotInterval,
+ getNumericRangeMinimum,
+ nextDown,
+ nextUp,
+ getFilterBinThresholds,
intervalBinFromMarks,
histogramFromThreshold,
histogramFromValues,
diff --git a/src/utils/src/plot.ts b/src/utils/src/plot.ts
index 3ce95ba34..b0396b48e 100644
--- a/src/utils/src/plot.ts
+++ b/src/utils/src/plot.ts
@@ -35,6 +35,7 @@ import {
ANIMATION_WINDOW,
BINS,
durationDay,
+ FILTER_TYPES,
TIME_AGGREGATION,
AGGREGATION_TYPES,
PLOT_TYPES,
@@ -355,6 +356,167 @@ export function getBinThresholds(interval: string, domain: number[]): number[] {
return binThresholds;
}
+const MAX_NUMERIC_BINS = 2048;
+
+function getNumericBinCount(domain: number[], interval: number): number {
+ const [start, end] = domain;
+ const rawCount = (end - start) / interval;
+ const roundedCount = Math.round(rawCount);
+ return Math.abs(rawCount - roundedCount) <= Number.EPSILON * Math.max(1, Math.abs(rawCount)) * 16
+ ? roundedCount
+ : Math.ceil(rawCount);
+}
+
+function normalizeNumericInterval(domain: number[], interval?: number): number | undefined {
+ if (!Number.isFinite(interval) || !(Number(interval) > 0)) {
+ return undefined;
+ }
+ if (
+ Array.isArray(domain) &&
+ domain.length >= 2 &&
+ domain.every(Number.isFinite) &&
+ domain[1] > domain[0] &&
+ getNumericBinCount(domain, Number(interval)) > MAX_NUMERIC_BINS
+ ) {
+ return undefined;
+ }
+ return Number(interval);
+}
+
+/**
+ * Build histogram thresholds in the numeric field's own units.
+ * Unlike time intervals, numeric intervals are anchored to the filter domain
+ * and never pass through calendar conversion.
+ */
+export function getNumericBinThresholds(
+ domain: number[],
+ interval?: number,
+ numBins = BINS
+): number[] {
+ if (!Array.isArray(domain) || domain.length < 2 || !domain.every(Number.isFinite)) {
+ return [];
+ }
+
+ const [start, end] = domain;
+ if (!(end > start)) {
+ return [start, end];
+ }
+
+ if (!Number.isFinite(interval) || !(Number(interval) > 0)) {
+ const numericTicks = ticks(start, end, numBins).filter(value => value > start && value < end);
+ return [start, ...numericTicks, end];
+ }
+
+ const width = Number(interval);
+ const count = getNumericBinCount(domain, width);
+ if (count > MAX_NUMERIC_BINS) {
+ return getNumericBinThresholds(domain, undefined, numBins);
+ }
+
+ const thresholds = [start];
+ for (let index = 1; index < count; index++) {
+ const boundary = start + index * width;
+ if (boundary > thresholds[thresholds.length - 1] && boundary < end) {
+ thresholds.push(boundary);
+ }
+ }
+ if (end > thresholds[thresholds.length - 1]) {
+ thresholds.push(end);
+ }
+ return thresholds;
+}
+
+const float64View = new DataView(new ArrayBuffer(8));
+
+function adjacentFloat(value: number, direction: -1 | 1): number {
+ if (Number.isNaN(value) || value === direction * Infinity) {
+ return value;
+ }
+ if (value === 0) {
+ return direction > 0 ? Number.MIN_VALUE : -Number.MIN_VALUE;
+ }
+
+ float64View.setFloat64(0, value, false);
+ let high = float64View.getUint32(0, false);
+ let low = float64View.getUint32(4, false);
+ const incrementBits = value > 0 === direction > 0;
+
+ if (incrementBits) {
+ low = (low + 1) >>> 0;
+ if (low === 0) {
+ high = (high + 1) >>> 0;
+ }
+ } else if (low === 0) {
+ low = 0xffffffff;
+ high = (high - 1) >>> 0;
+ } else {
+ low = (low - 1) >>> 0;
+ }
+
+ float64View.setUint32(0, high, false);
+ float64View.setUint32(4, low, false);
+ return float64View.getFloat64(0, false);
+}
+
+/** Return the next representable IEEE-754 number above value. */
+export function nextUp(value: number): number {
+ return adjacentFloat(value, 1);
+}
+
+/** Return the next representable IEEE-754 number below value. */
+export function nextDown(value: number): number {
+ return adjacentFloat(value, -1);
+}
+
+/**
+ * Smallest useful range width across a numeric domain. It is large enough to
+ * move either endpoint by one representable value and never exceeds the span.
+ */
+export function getNumericRangeMinimum(domain: number[]): number {
+ if (!Array.isArray(domain) || domain.length < 2 || !domain.every(Number.isFinite)) {
+ return 0;
+ }
+ const [start, end] = domain;
+ const span = end - start;
+ if (!(span > 0)) {
+ return 0;
+ }
+ const startResolution = nextUp(start) - start;
+ const endResolution = end - nextDown(end);
+ return Math.min(span, Math.max(startResolution, endResolution));
+}
+
+/** Infer the regular numeric bin width, ignoring tiny padded edge bins. */
+export function getNumericPlotInterval(filter: RangeFilter): number {
+ if (Number.isFinite(filter.plotType?.numericInterval) && filter.plotType.numericInterval > 0) {
+ return filter.plotType.numericInterval;
+ }
+ const bins = Object.values(filter.bins || {}).find(value => value?.length);
+ const binWidths = (bins || [])
+ .map(bin => bin.x1 - bin.x0)
+ .filter(width => Number.isFinite(width) && width > 0)
+ .sort((a, b) => a - b);
+ const binWidth = binWidths.length ? binWidths[Math.floor(binWidths.length / 2)] : 0;
+ if (binWidth > 0) {
+ return Number(binWidth.toPrecision(10));
+ }
+ const span = filter.domain?.[1] - filter.domain?.[0];
+ return span > 0 ? Number((span / BINS).toPrecision(10)) : filter.step;
+}
+
+/** Return the plotted bin boundaries for either a time or numeric range filter. */
+export function getFilterBinThresholds(filter: TimeRangeFilter | RangeFilter): number[] {
+ if (filter.type === FILTER_TYPES.timeRange) {
+ return getBinThresholds(filter.plotType?.interval, filter.domain);
+ }
+
+ const firstBins = Object.values(filter.bins || {}).find(Boolean) || [];
+ if (firstBins.length) {
+ return [...firstBins.map(bin => bin.x0), firstBins[firstBins.length - 1].x1];
+ }
+ return getNumericBinThresholds(filter.domain, filter.plotType?.numericInterval);
+}
+
/**
* Run GPU filter on current filter result to generate indexes for ploting chart
* Skip ruuning for the same field
@@ -467,11 +629,16 @@ export function validBin(b) {
/**
* 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.
+ * Interval playback steps by bin, and the filter comparison is inclusive.
+ * Time bins preserve their millisecond offset. Numeric bins use the immediate
+ * representable predecessor of the next mark so their membership matches D3's
+ * half-open bins; only the final numeric bin includes its upper boundary.
*/
-export function intervalBinFromMarks(marks: number[], value: number): [number, number] {
+export function intervalBinFromMarks(
+ marks: number[],
+ value: number,
+ endOffset = 1
+): [number, number] {
if (!marks.length || !Number.isFinite(value)) {
return [value, value];
}
@@ -487,7 +654,13 @@ export function intervalBinFromMarks(marks: number[], value: number): [number, n
if (idx > lastBin) {
idx = lastBin;
}
- return [marks[idx], marks[idx + 1] - 1];
+ const start = marks[idx];
+ const end = marks[idx + 1];
+ if (endOffset === 0) {
+ return [start, idx === lastBin ? end : Math.max(start, nextDown(end))];
+ }
+ const offset = Number.isFinite(endOffset) && endOffset > 0 ? Math.min(endOffset, end - start) : 0;
+ return [start, Math.max(start, end - offset)];
}
export function snapToMarks(value: number, marks: number[]): number {
@@ -581,7 +754,7 @@ export const getAggregationOptiosnBasedOnField = field => {
function getDelta(
bins: LineDatum[],
y: unknown,
- _interval: PlotType['interval']
+ _interval: PlotType['interval'] | number | null
): Partial<LineDatum> & {delta: 'last'; pct: number | null} {
// if (WOW[interval]) return getWow(bins, y, interval);
const lastBin = bins[bins.length - 1];
@@ -816,7 +989,7 @@ function buildGroupedLineSeries({
dataset: Datasets[string];
plotType: Filter['plotType'];
getYValue: (bin: Bin) => number;
- interval: PlotType['interval'];
+ interval: PlotType['interval'] | number | null;
}): {series: LineChartSeries; points: LineDatum[]} | null {
const cache = groupByCacheValue(plotType);
if (!cache) {
@@ -932,15 +1105,20 @@ export function lineChartSeriesLegend(
*/
export function getLineChart(datasets: Datasets, filter: Filter): LineChart {
const {dataId, yAxis, plotType, lineChart} = filter;
- const {aggregation, interval} = plotType;
+ const {interval} = plotType;
+ const aggregation = plotType.aggregation || AGGREGATION_TYPES.average;
const seriesDataId = dataId[0];
- const bins = (filter as TimeRangeFilter).timeBins?.[seriesDataId]?.[interval];
+ const isNumericFilter = filter.type === FILTER_TYPES.range;
+ const binning = isNumericFilter ? plotType.numericInterval ?? null : interval;
+ const bins = isNumericFilter
+ ? (filter as RangeFilter).bins?.[seriesDataId]
+ : (filter as TimeRangeFilter).timeBins?.[seriesDataId]?.[interval];
const groupBy = groupByCacheValue(plotType);
if (
lineChart &&
lineChart.aggregation === aggregation &&
- lineChart.interval === interval &&
+ lineChart.interval === binning &&
lineChart.yAxis === yAxis?.name &&
isEqual(lineChart.groupBy ?? null, groupBy) &&
// we need to make sure we validate bins because of cross filter data changes
@@ -954,7 +1132,7 @@ export function getLineChart(datasets: Datasets, filter: Filter): LineChart {
const getYValue = getValueAggrFunc(yAxis, aggregation, dataset);
const grouped =
groupBy && bins?.length
- ? buildGroupedLineSeries({bins, dataset, plotType, getYValue, interval})
+ ? buildGroupedLineSeries({bins, dataset, plotType, getYValue, interval: binning})
: null;
const init: LineDatum[] = [];
@@ -962,7 +1140,7 @@ export function getLineChart(datasets: Datasets, filter: Filter): LineChart {
? grouped.points
: (bins || []).reduce((accu, bin) => {
const y = getYValue(bin);
- const delta = getDelta(accu, y, interval);
+ const delta = getDelta(accu, y, binning);
accu.push({
x: bin.x0,
y,
@@ -983,7 +1161,7 @@ export function getLineChart(datasets: Datasets, filter: Filter): LineChart {
yDomain,
// @ts-ignore
xDomain,
- interval,
+ interval: binning,
aggregation,
// @ts-ignore
series: split,
@@ -991,10 +1169,9 @@ export function getLineChart(datasets: Datasets, filter: Filter): LineChart {
fieldType: yAxis ? yAxis.type : 'integer',
yAxis: yAxis ? yAxis.name : null,
allTime: {
- title: `All Time Average`,
+ title: isNumericFilter ? `All Range Average` : `All Time Average`,
value: aggregate(series, AGGREGATION_TYPES.average, d => d.y)
},
- // @ts-expect-error bins is Bins[], not a Bins map. Refactor to use correct types.
bins,
...(groupBy ? {groupBy} : {})
};
@@ -1030,7 +1207,7 @@ type MinVisStateForAnimationWindow = {
export function adjustValueToAnimationWindow<S extends MinVisStateForAnimationWindow>(
state: S,
- filter: TimeRangeFilter,
+ filter: TimeRangeFilter | RangeFilter,
plotBaseIndexByDataId?: Record<string, number[]>
) {
const {
@@ -1039,10 +1216,19 @@ export function adjustValueToAnimationWindow<S extends MinVisStateForAnimationWi
animationWindow
} = filter;
- const interval = plotType.interval || getInitialInterval(filter, state.datasets);
- const bins = getTimeBins(filter, state.datasets, interval, plotBaseIndexByDataId);
- const datasetBins = bins && Object.keys(bins).length && Object.values(bins)[0][interval];
+ const isTimeFilter = filter.type === FILTER_TYPES.timeRange;
+ const interval = isTimeFilter
+ ? plotType.interval || getInitialInterval(filter, state.datasets)
+ : undefined;
+ const bins = isTimeFilter
+ ? getTimeBins(filter, state.datasets, interval, plotBaseIndexByDataId)
+ : getRangeFilterBins(filter, state.datasets, BINS, plotBaseIndexByDataId);
+ const firstBins = bins && Object.keys(bins).length ? Object.values(bins)[0] : null;
+ const datasetBins = isTimeFilter ? firstBins?.[interval] : firstBins;
const thresholds = (datasetBins || []).map(b => b.x0);
+ const numericIntervalMarks = datasetBins?.length
+ ? [...thresholds, datasetBins[datasetBins.length - 1].x1]
+ : thresholds;
let val0 = value0;
let val1 = value1;
@@ -1050,10 +1236,18 @@ export function adjustValueToAnimationWindow<S extends MinVisStateForAnimationWi
if (animationWindow === ANIMATION_WINDOW.interval) {
val0 = snapToMarks(value1, thresholds);
idx = thresholds.indexOf(val0);
- // 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;
+ if (isTimeFilter) {
+ // Time histograms discard empty bins. Use the selected cached bin's
+ // actual end instead of the next non-empty bin's start so sparse
+ // calendar intervals do not absorb the empty gap between them.
+ const binEnd = idx > -1 ? datasetBins?.[idx]?.x1 : NaN;
+ val1 =
+ Number.isFinite(binEnd) && binEnd > val0
+ ? Math.max(val0, binEnd - Math.min(1, binEnd - val0))
+ : binEnd;
+ } else {
+ [, val1] = intervalBinFromMarks(numericIntervalMarks, val0, 0);
+ }
} else {
// fit current value to window
val0 = snapToMarks(value0, thresholds);
@@ -1069,17 +1263,16 @@ export function adjustValueToAnimationWindow<S extends MinVisStateForAnimationWi
}
}
- const updatedFilter = {
+ return {
...filter,
- plotType: {
- ...filter.plotType,
- interval
- },
- timeBins: bins,
+ ...(isTimeFilter
+ ? {
+ plotType: {...filter.plotType, interval},
+ timeBins: bins
+ }
+ : {bins}),
value: [val0, val1]
};
-
- return updatedFilter;
}
/**
@@ -1179,7 +1372,16 @@ export function getRangeFilterBins(
plotBaseIndexByDataId?.[dataId]
);
const valueAccessor = index => field.valueAccessor({index});
- acc[dataId] = histogramFromDomain(domain, indexes, numBins, valueAccessor);
+ const numericInterval = filter.plotType?.numericInterval;
+ acc[dataId] =
+ Number.isFinite(numericInterval) && numericInterval > 0
+ ? histogramFromThreshold(
+ getNumericBinThresholds(domain, numericInterval, numBins),
+ indexes,
+ valueAccessor,
+ false
+ )
+ : histogramFromDomain(domain, indexes, numBins, valueAccessor);
}
}
return acc;
@@ -1193,11 +1395,6 @@ export function updateRangeFilterPlotType(
_dataId?: string,
plotBaseIndexByDataId?: Record<string, number[]>
): RangeFilter {
- const nextFilter = {
- ...filter,
- plotType
- };
-
// if (dataId) {
// // clear bins
// nextFilter = {
@@ -1209,11 +1406,36 @@ export function updateRangeFilterPlotType(
// };
// }
- return {
+ const configuredNumericInterval = plotType?.numericInterval;
+ const numericInterval = normalizeNumericInterval(filter.domain, configuredNumericInterval);
+ const shouldUseAutomaticBins =
+ configuredNumericInterval !== undefined && numericInterval === undefined;
+ let nextPlotType = plotType;
+ if (shouldUseAutomaticBins) {
+ const {numericInterval: _numericInterval, ...automaticPlotType} = nextPlotType || {};
+ nextPlotType = automaticPlotType;
+ }
+ if (filter.dataId.length > 1) {
+ nextPlotType = {
+ ...nextPlotType,
+ colorsByDataId: getFilterPlotColorsByDataId(filter, datasets, nextPlotType.colorsByDataId)
+ };
+ }
+
+ const nextFilter = {
...filter,
- plotType,
+ ...(shouldUseAutomaticBins ? {bins: undefined, lineChart: undefined} : {}),
+ plotType: nextPlotType
+ };
+
+ let updatedFilter = {
+ ...nextFilter,
bins: getRangeFilterBins(nextFilter, datasets, BINS, plotBaseIndexByDataId)
};
+ if (nextPlotType.type === PLOT_TYPES.lineChart) {
+ updatedFilter = {...updatedFilter, lineChart: getLineChart(datasets, updatedFilter)};
+ }
+ return updatedFilter;
}
export function getChartTitle(yAxis: Field, plotType: PlotType): string {
diff --git a/src/utils/src/time.ts b/src/utils/src/time.ts
index a979058cd..97bdbea96 100644
--- a/src/utils/src/time.ts
+++ b/src/utils/src/time.ts
@@ -14,10 +14,10 @@ import {
TickInterval
} from '@kepler.gl/constants';
import {toArray} from '@kepler.gl/common-utils';
-import {AnimationConfig, Timeline, TimeRangeFilter, Filter} from '@kepler.gl/types';
+import {AnimationConfig, Timeline, TimeRangeFilter, RangeFilter, Filter} from '@kepler.gl/types';
import {getFrequency} from './aggregation';
-import {getBinThresholds} from './plot';
+import {getFilterBinThresholds} from './plot';
import {KeplerTableModel} from './types';
export const TIMELINE_MODES = {
@@ -317,7 +317,8 @@ export function filterIntervalOptions(options, domain) {
* @param filter TimeRangeFilter filter
* @returns Timeline
*/
-export const getTimelineFromFilter = (filter: TimeRangeFilter): Timeline => {
+export const getTimelineFromFilter = (filter: TimeRangeFilter | RangeFilter): Timeline => {
+ const timeFilter = filter.type === 'timeRange' ? filter : null;
const {
value,
domain,
@@ -326,27 +327,22 @@ export const getTimelineFromFilter = (filter: TimeRangeFilter): Timeline => {
step,
// @ts-expect-error
timeSteps,
- defaultTimeFormat,
- timeFormat,
- timezone,
- timeBins,
- animationWindow,
- plotType
+ animationWindow
} = filter;
return {
value,
enableInteraction: true,
- domain,
+ domain: domain as [number, number],
speed,
isAnimating,
step,
timeSteps,
- defaultTimeFormat,
- timeFormat,
- timezone,
- timeBins,
+ defaultTimeFormat: timeFilter?.defaultTimeFormat,
+ timeFormat: timeFilter?.timeFormat,
+ timezone: timeFilter?.timezone,
+ timeBins: timeFilter?.timeBins,
animationWindow,
- marks: getBinThresholds(plotType?.interval, domain)
+ marks: getFilterBinThresholds(filter)
};
};
diff --git a/test/browser/components/bottom-widget-test.js b/test/browser/components/bottom-widget-test.js
index e621e48c3..a3e38ea0d 100644
--- a/test/browser/components/bottom-widget-test.js
+++ b/test/browser/components/bottom-widget-test.js
@@ -3,21 +3,26 @@
import React from 'react';
import test from 'tape';
+import cloneDeep from 'es-toolkit/compat/cloneDeep';
import {IntlWrapper, mountWithTheme} from 'test/helpers/component-utils';
import {
BottomWidgetFactory,
TimeWidgetFactory,
AnimationControlFactory,
+ Icons,
+ TimezoneSelector,
appInjector
} from '@kepler.gl/components';
import {VisStateActions} from '@kepler.gl/actions';
+import {visStateReducer as reducer} from '@kepler.gl/reducers';
+import {FILTER_VIEW_TYPES} from '@kepler.gl/constants';
const BottomWidget = appInjector.get(BottomWidgetFactory);
const TimeWidget = appInjector.get(TimeWidgetFactory);
const AnimationControl = appInjector.get(AnimationControlFactory);
// mock state
-import {InitialState} from 'test/helpers/mock-state';
+import {InitialState, StateWFilters} from 'test/helpers/mock-state';
// default props from initial state
const defaultProps = {
@@ -46,3 +51,81 @@ test('Components -> BottomWidget.mount -> initial state', t => {
t.end();
});
+
+test('Components -> BottomWidget.mount -> datetime and opt-in numeric filters', t => {
+ const mountWidget = visState =>
+ mountWithTheme(
+ <IntlWrapper>
+ <BottomWidget
+ {...defaultProps}
+ datasets={visState.datasets}
+ filters={visState.filters}
+ layers={visState.layers}
+ />
+ </IntlWrapper>
+ );
+
+ let wrapper = mountWidget(StateWFilters.visState);
+ t.equal(wrapper.find(TimeWidget).length, 1, 'should preserve the enlarged datetime widget');
+ wrapper.unmount();
+
+ let numericState = reducer(
+ cloneDeep(StateWFilters.visState),
+ VisStateActions.setFilter(0, 'name', 'gps_data.lat')
+ );
+ wrapper = mountWidget(numericState);
+ t.equal(wrapper.find(TimeWidget).length, 0, 'should leave an ordinary numeric filter disabled');
+ wrapper.unmount();
+
+ numericState = reducer(
+ numericState,
+ VisStateActions.setFilterView(0, FILTER_VIEW_TYPES.enlarged)
+ );
+ const numericDataId = numericState.filters[0].dataId[0];
+ const numericBins = numericState.filters[0].bins[numericDataId];
+ numericState = {
+ ...numericState,
+ filters: [
+ {
+ ...numericState.filters[0],
+ bins: {
+ ...numericState.filters[0].bins,
+ [numericDataId]: [
+ {...numericBins[0], x1: numericBins[0].x0 + 1e-12},
+ ...numericBins.slice(1)
+ ]
+ }
+ },
+ ...numericState.filters.slice(1)
+ ]
+ };
+ wrapper = mountWidget(numericState);
+ t.equal(wrapper.find(TimeWidget).length, 1, 'should render the numeric widget when enlarged');
+
+ wrapper.find(Icons.Gear).at(0).simulate('click');
+ wrapper.update();
+ t.ok(wrapper.text().includes('Bin size'), 'should show numeric binning controls');
+ t.equal(
+ wrapper.find('[data-testid="numeric-bin-size"]').hostNodes().prop('value'),
+ '0.002',
+ 'should infer the regular bin size instead of a tiny padded edge bin'
+ );
+ t.equal(
+ window.getComputedStyle(
+ wrapper.find('[data-testid="numeric-bin-size"]').hostNodes().getDOMNode()
+ ).width,
+ window.getComputedStyle(
+ wrapper.find('[data-testid="time-widget-aggregation"]').hostNodes().getDOMNode()
+ ).width,
+ 'should match the aggregation control width'
+ );
+ t.equal(wrapper.find(TimezoneSelector).length, 0, 'should hide the timezone control');
+ t.equal(
+ wrapper.find('[data-testid="time-widget-time-format"]').hostNodes().length,
+ 0,
+ 'should hide the calendar time-format control'
+ );
+
+ wrapper.unmount();
+ t.end();
+});
diff --git a/test/browser/components/common/animation-control-test.js b/test/browser/components/common/animation-control-test.js
index dfb637d59..d97dc40ca 100644
--- a/test/browser/components/common/animation-control-test.js
+++ b/test/browser/components/common/animation-control-test.js
@@ -5,20 +5,27 @@ import React from 'react';
import test from 'tape';
import sinon from 'sinon';
import moment from 'moment';
-import {setLayerAnimationTimeConfig} from '@kepler.gl/actions';
-import {getTimelineFromAnimationConfig} from '@kepler.gl/utils';
+import {
+ setFilter,
+ setFilterAnimationTime,
+ setFilterAnimationWindow,
+ setFilterPlot,
+ setLayerAnimationTimeConfig
+} from '@kepler.gl/actions';
+import {getNumericRangeMinimum, getTimelineFromAnimationConfig} from '@kepler.gl/utils';
import {ANIMATION_WINDOW} from '@kepler.gl/constants';
import {IntlWrapper, mountWithTheme} from 'test/helpers/component-utils';
import {
AnimationControlFactory,
AnimationControllerFactory,
+ FilterAnimationControllerFactory,
PlaybackControlsFactory,
FloatingTimeDisplayFactory,
appInjector,
IconButton
} from '@kepler.gl/components';
-import {StateWTripGeojson} from 'test/helpers/mock-state';
+import {StateWFilters, StateWTripGeojson} from 'test/helpers/mock-state';
import {visStateReducer as reducer} from '@kepler.gl/reducers';
@@ -250,6 +257,152 @@ test('Components -> AnimationController -> incremental window sweeps to the end
t.end();
});
+test('Components -> AnimationController -> fractional incremental window resets in numeric units', t => {
+ const AnimationController = AnimationControllerFactory();
+ const setTimelineValue = sinon.spy();
+ const controller = new AnimationController({
+ animationWindow: ANIMATION_WINDOW.incremental,
+ domain: [0, 0.1],
+ value: [0, 0.1],
+ speed: 1,
+ baseSpeed: 10,
+ minimumIncrement: 0.001,
+ setTimelineValue
+ });
+
+ t.deepEqual(
+ controller._nextFrameByDomain(),
+ [0, 0.001],
+ 'numeric playback should loop to a fractional window inside its domain'
+ );
+
+ controller._resetAnimationByDomain();
+ t.deepEqual(
+ setTimelineValue.firstCall.args[0],
+ [0, 0.001],
+ 'numeric reset should use its supplied fractional minimum increment'
+ );
+
+ const midSweep = new AnimationController({
+ animationWindow: ANIMATION_WINDOW.incremental,
+ domain: [0, 0.1],
+ value: [0, 0.095],
+ speed: 1,
+ baseSpeed: 10,
+ minimumIncrement: 0.001,
+ setTimelineValue: () => {}
+ })._nextFrameByDomain();
+ t.deepEqual(midSweep, [0, 0.1], 'numeric playback should clamp its final frame to the maximum');
+
+ t.end();
+});
+
+test('Components -> AnimationController -> numeric playback advances at representable extremes', t => {
+ const AnimationController = AnimationControllerFactory();
+
+ for (const domain of [
+ [0, 1e-20],
+ [1e12, 1e12 + 0.001],
+ [0, 0.1]
+ ]) {
+ const minimumIncrement = getNumericRangeMinimum(domain);
+ const reset = new AnimationController({
+ animationWindow: ANIMATION_WINDOW.incremental,
+ domain,
+ value: [...domain],
+ speed: 1,
+ minimumIncrement,
+ setTimelineValue: () => {}
+ })._nextFrameByDomain();
+ t.ok(reset[1] > domain[0], `${domain} reset should advance beyond its anchor`);
+ t.ok(reset[1] < domain[1], `${domain} reset should not jump to the domain maximum`);
+
+ const advanced = new AnimationController({
+ animationWindow: ANIMATION_WINDOW.incremental,
+ domain,
+ value: reset,
+ speed: 1,
+ minimumIncrement,
+ setTimelineValue: () => {}
+ })._nextFrameByDomain();
+ t.ok(advanced[1] > reset[1], `${domain} should advance after looping instead of freezing`);
+ t.ok(advanced[1] <= domain[1], `${domain} should remain inside its domain`);
+ }
+
+ t.end();
+});
+
+test('Components -> FilterAnimationController -> numeric incremental bins stay in domain', t => {
+ const AnimationController = AnimationControllerFactory();
+ const FilterAnimationController = FilterAnimationControllerFactory(AnimationController);
+ let visState = reducer(StateWFilters.visState, setFilter(0, 'name', 'gps_data.lat'));
+ visState = reducer(
+ visState,
+ setFilterPlot(0, {plotType: {numericInterval: 0.01}})
+ );
+ visState = reducer(
+ visState,
+ setFilterAnimationWindow({
+ id: visState.filters[0].id,
+ animationWindow: ANIMATION_WINDOW.incremental
+ })
+ );
+
+ const filter = visState.filters[0];
+ const domain = [29.987000000000005, 30.061420000000005];
+ t.deepEqual(filter.domain, domain, 'fixture should use the gps_data.lat numeric domain');
+
+ const wrapper = mountWithTheme(
+ <FilterAnimationController
+ filter={filter}
+ filterIdx={0}
+ setFilterAnimationTime={(idx, prop, value) => {
+ visState = reducer(visState, setFilterAnimationTime(idx, prop, value));
+ }}
+ >
+ {() => null}
+ </FilterAnimationController>
+ );
+ const controllerProps = wrapper.find(AnimationController).props();
+ t.equal(
+ controllerProps.steps[controllerProps.steps.length - 1],
+ domain[1],
+ 'explicit numeric bins should exercise the terminal maximum step'
+ );
+
+ let value = [...domain];
+ let resets = 0;
+ let reachedMaximum = false;
+ const violations = [];
+ for (let frame = 0; frame < 1300 && resets < 2; frame++) {
+ const nextValue = new AnimationController({
+ ...controllerProps,
+ value,
+ baseSpeed: 600
+ })._nextFrameByDomain();
+ if (
+ !Array.isArray(nextValue) ||
+ nextValue[0] !== domain[0] ||
+ nextValue[1] < domain[0] ||
+ nextValue[1] > domain[1]
+ ) {
+ violations.push({frame, value: nextValue});
+ }
+ reachedMaximum ||= nextValue[1] === domain[1];
+ if (nextValue[1] < value[1]) {
+ resets++;
+ }
+ controllerProps.updateAnimation(nextValue);
+ value = visState.filters[0].value;
+ }
+
+ t.deepEqual(violations, [], 'every reducer-applied frame should stay inside the numeric domain');
+ t.ok(reachedMaximum, 'a complete numeric sweep should include the exact domain maximum');
+ t.equal(resets, 2, 'numeric incremental playback should complete and restart two cycles');
+ wrapper.unmount();
+ t.end();
+});
+
test('Components -> PlaybackControls -> offers Step by Interval', t => {
const setFilterAnimationWindow = sinon.spy();
const wrapper = mountWithTheme(
diff --git a/test/browser/components/filters/time-widget-test.js b/test/browser/components/filters/time-widget-test.js
index 880d87b08..638020d58 100644
--- a/test/browser/components/filters/time-widget-test.js
+++ b/test/browser/components/filters/time-widget-test.js
@@ -2,14 +2,18 @@
// Copyright contributors to the kepler.gl project
/* eslint-disable max-statements */
-import React from 'react';
+import React, {act} from 'react';
import test from 'tape';
import sinon from 'sinon';
import moment from 'moment';
import 'moment/locale/en-gb';
import {IntlWrapper, mountWithTheme, mockHTMLElementClientSize} from 'test/helpers/component-utils';
-import {setFilterAnimationTimeConfig, setFilterAnimationWindow} from '@kepler.gl/actions';
+import {
+ setFilter,
+ setFilterAnimationTimeConfig,
+ setFilterAnimationWindow
+} from '@kepler.gl/actions';
import {visStateReducer as reducer, DEFAULT_ANIMATION_CONFIG} from '@kepler.gl/reducers';
import {
@@ -30,6 +34,7 @@ import {
TimezoneSelector,
appInjector
} from '@kepler.gl/components';
+import {FILTER_VIEW_TYPES} from '@kepler.gl/constants';
moment.locale('en');
@@ -713,6 +718,130 @@ test('Components -> TimeWidget.mount -> timeline zoom reset button', t => {
t.end();
});
+test('Components -> TimeWidget.mount -> fractional numeric timeline zoom and reset', t => {
+ const setFilterAnimationTime = sinon.spy();
+ const numericState = reducer(StateWFilters.visState, setFilter(0, 'name', 'gps_data.lat'));
+ const numericFilter = {
+ ...numericState.filters[0],
+ domain: [0, 0.1],
+ value: [0.02, 0.08]
+ };
+ const rectStub = sinon.stub(HTMLElement.prototype, 'getBoundingClientRect').returns({
+ left: 0,
+ right: 500,
+ top: 0,
+ bottom: 100,
+ width: 500,
+ height: 100,
+ x: 0,
+ y: 0,
+ toJSON: () => ({})
+ });
+
+ const wrapper = mountWithTheme(
+ <IntlWrapper>
+ <TimeWidget
+ {...defaultProps}
+ filter={numericFilter}
+ setFilterAnimationTime={setFilterAnimationTime}
+ />
+ </IntlWrapper>,
+ {attachTo: document.body}
+ );
+ const timeDisplay = wrapper.find(FloatingTimeDisplay);
+ t.equal(
+ timeDisplay.find('.animation-control__time-display__top').text(),
+ 'gps_data.lat',
+ 'numeric range badge should identify its column'
+ );
+ t.deepEqual(
+ timeDisplay
+ .find('.animation-control__time-display__bottom')
+ .find('.time-value')
+ .map(n => n.text()),
+ ['0.02', '0.08'],
+ 'numeric range badge should keep the selected values below the column name'
+ );
+ const container = wrapper
+ .find('[data-testid="time-widget-timeline-container"]')
+ .hostNodes()
+ .getDOMNode();
+
+ act(() => {
+ container.dispatchEvent(
+ new window.WheelEvent('wheel', {
+ bubbles: true,
+ cancelable: true,
+ clientX: 250,
+ ctrlKey: true,
+ deltaY: -100
+ })
+ );
+ });
+ wrapper.update();
+ t.equal(
+ wrapper.find('[data-testid="time-widget-timeline-reset"]').hostNodes().length,
+ 1,
+ 'fractional numeric timeline can zoom below a one-unit domain'
+ );
+
+ act(() => {
+ wrapper.find('[data-testid="time-widget-timeline-reset"]').hostNodes().simulate('click');
+ });
+ wrapper.update();
+ t.equal(
+ wrapper.find('[data-testid="time-widget-timeline-reset"]').hostNodes().length,
+ 0,
+ 'reset restores the full fractional numeric domain'
+ );
+
+ act(() => {
+ container.dispatchEvent(
+ new window.WheelEvent('wheel', {
+ bubbles: true,
+ cancelable: true,
+ clientX: 250,
+ deltaY: -100
+ })
+ );
+ });
+ const selectedRange = setFilterAnimationTime.lastCall.args[2];
+ t.ok(selectedRange[1] - selectedRange[0] < 0.06, 'fractional selection can zoom in');
+ t.ok(selectedRange[1] > selectedRange[0], 'fractional selection keeps a positive width');
+
+ wrapper.detach();
+ rectStub.restore();
+ t.end();
+});
+
+test('Components -> TimeWidget.mount -> minimized numeric timeline formats numeric bounds', t => {
+ const numericState = reducer(StateWFilters.visState, setFilter(0, 'name', 'gps_data.lat'));
+ const numericFilter = {
+ ...numericState.filters[0],
+ domain: [0.02, 0.08],
+ value: [0.02, 0.08],
+ view: FILTER_VIEW_TYPES.minified
+ };
+ const wrapper = mountWithTheme(
+ <IntlWrapper>
+ <TimeWidget {...defaultProps} filter={numericFilter} />
+ </IntlWrapper>
+ );
+
+ t.equal(
+ wrapper.find('.animation-control__time-domain.domain-start').find('span').text(),
+ '0.02',
+ 'compact numeric timeline formats its domain start as a number'
+ );
+ t.equal(
+ wrapper.find('.animation-control__time-domain.domain-end').find('span').text(),
+ '0.08',
+ 'compact numeric timeline formats its domain end as a number'
+ );
+
+ t.end();
+});
+
test('Components -> TimeWidget.mount -> timeline container renders', t => {
const clientSizeStub = mockHTMLElementClientSize('offsetWidth', 500);
diff --git a/test/browser/components/side-panel/filter-manager-test.js b/test/browser/components/side-panel/filter-manager-test.js
index 2870d02d5..ea829bd9d 100644
--- a/test/browser/components/side-panel/filter-manager-test.js
+++ b/test/browser/components/side-panel/filter-manager-test.js
@@ -4,6 +4,7 @@
import React from 'react';
import sinon from 'sinon';
import test from 'tape';
+import cloneDeep from 'es-toolkit/compat/cloneDeep';
import {
FilterManagerFactory,
SourceDataCatalogFactory,
@@ -13,13 +14,15 @@ import {
FilterPanelHeaderFactory,
NewFilterPanelFactory,
appInjector,
- AddFilterButtonFactory
+ AddFilterButtonFactory,
+ RangeSliderFactory,
+ Icons
} from '@kepler.gl/components';
import {mountWithTheme, IntlWrapper} from 'test/helpers/component-utils';
import {keplerGlReducerCore as keplerGlReducer} from '@kepler.gl/reducers';
import {VisStateActions} from '@kepler.gl/actions';
import {testFields, testAllData} from 'test/fixtures/test-csv-data';
-import {ALL_FIELD_TYPES} from '@kepler.gl/constants';
+import {ALL_FIELD_TYPES, FILTER_VIEW_TYPES} from '@kepler.gl/constants';
import {assertDatasetIsTable} from '../../../helpers/comparison-utils';
// components
@@ -30,6 +33,7 @@ const NewFilterPanel = appInjector.get(NewFilterPanelFactory);
const FilterPanelHeader = appInjector.get(FilterPanelHeaderFactory);
const FieldSelector = appInjector.get(FieldSelectorFactory);
const AddFilterButton = appInjector.get(AddFilterButtonFactory);
+const RangeSlider = appInjector.get(RangeSliderFactory);
// mock state
import {StateWFilters, InitialState, applyActions, csvInfo} from 'test/helpers/mock-state';
@@ -149,6 +153,81 @@ test('Components -> FilterManager.mount -> order by dataset view', t => {
t.end();
});
+test('Components -> FilterManager.mount -> numeric filter exposes timeline action', t => {
+ let numericState = keplerGlReducer(
+ cloneDeep(StateWFilters),
+ VisStateActions.setFilter(0, 'name', 'gps_data.lat')
+ );
+ const numericFilter = numericState.visState.filters[0];
+ const yAxis = numericState.visState.datasets[numericFilter.dataId[0]].fields.find(
+ field => field.name === 'gps_data.lng'
+ );
+ numericState = keplerGlReducer(numericState, VisStateActions.setFilterPlot(0, {yAxis}));
+ const setFilterView = sinon.spy();
+ const wrapper = mountWithTheme(
+ <IntlWrapper>
+ <FilterManager
+ {...filterManagerProps}
+ filters={numericState.visState.filters}
+ datasets={numericState.visState.datasets}
+ layers={numericState.visState.layers}
+ visStateActions={{...VisStateActions, setFilterView}}
+ />
+ </IntlWrapper>
+ );
+
+ t.equal(
+ wrapper.find(Icons.Clock).length,
+ 1,
+ 'should render the playback action for numeric data'
+ );
+ const numericRangeSlider = wrapper.find('.range-filter-panel').find(RangeSlider).at(0);
+ t.equal(
+ numericRangeSlider.props().lineChart,
+ numericState.visState.filters[0].lineChart,
+ 'should render the numeric Y-axis chart after playback is closed'
+ );
+ t.equal(
+ numericRangeSlider.props().isTime,
+ false,
+ 'should keep numeric side-panel chart labels out of datetime mode'
+ );
+ t.equal(
+ wrapper.find('.range-filter-panel').find('.filter-panel__filter').length,
+ 1,
+ 'should render the numeric histogram while it is a side filter'
+ );
+ wrapper.find(Icons.Clock).at(0).simulate('click');
+ t.deepEqual(
+ setFilterView.firstCall.args,
+ [0, FILTER_VIEW_TYPES.enlarged],
+ 'should enable the numeric bottom widget through the existing view action'
+ );
+
+ const enlargedNumericState = keplerGlReducer(
+ numericState,
+ VisStateActions.setFilterView(0, FILTER_VIEW_TYPES.enlarged)
+ );
+ const enlargedWrapper = mountWithTheme(
+ <IntlWrapper>
+ <FilterManager
+ {...filterManagerProps}
+ filters={enlargedNumericState.visState.filters}
+ datasets={enlargedNumericState.visState.datasets}
+ layers={enlargedNumericState.visState.layers}
+ />
+ </IntlWrapper>
+ );
+
+ t.equal(
+ enlargedWrapper.find('.range-filter-panel').find('.filter-panel__filter').length,
+ 0,
+ 'should hide the numeric histogram while it is rendered in the bottom widget'
+ );
+
+ t.end();
+});
+
test('Components -> FilterManager.mount -> with supportedFilterTypes', t => {
// load csv and geojson
const updatedState = applyActions(keplerGlReducer, InitialState, [
diff --git a/test/node/reducers/vis-state-test.js b/test/node/reducers/vis-state-test.js
index 58c07f823..993a43629 100644
--- a/test/node/reducers/vis-state-test.js
+++ b/test/node/reducers/vis-state-test.js
@@ -39,6 +39,9 @@ import {
applyFilterFieldName,
getAnimatableVisibleLayers,
getBinThresholds,
+ getFilterBinThresholds,
+ getNumericPlotInterval,
+ intervalBinFromMarks,
getDefaultFilter,
histogramFromDomain,
LayerTimeInterval,
@@ -2940,10 +2943,8 @@ test('#visStateReducer -> SET_FILTER.dataId replaces synced datasets in place',
'rebuilds the domain after replacing the first dataset'
);
- const replaceSecond = reducer(
- state,
- VisStateActions.setFilter(0, 'dataId', 'replacement', 1)
- ).filters[0];
+ const replaceSecond = reducer(state, VisStateActions.setFilter(0, 'dataId', 'replacement', 1))
+ .filters[0];
t.deepEqual(replaceSecond.dataId, ['first', 'replacement'], 'replaces a later dataset');
t.deepEqual(replaceSecond.name, ['value', 'value'], 'keeps later field names aligned');
t.deepEqual(replaceSecond.fieldIdx, [0, 1], 'rebinds a later field index by name');
@@ -2992,10 +2993,8 @@ test('#visStateReducer -> SET_FILTER.dataId rebinds interval fields on replaceme
state = reducer(state, VisStateActions.addFilter('replacement'));
state = reducer(state, VisStateActions.setFilter(1, 'name', 'other'));
- const replaced = reducer(
- state,
- VisStateActions.setFilter(0, 'dataId', 'replacement', 1)
- ).filters[0];
+ const replaced = reducer(state, VisStateActions.setFilter(0, 'dataId', 'replacement', 1))
+ .filters[0];
const replacementEndProps = replacementDataset.replacement.getColumnFilterProps('end');
t.deepEqual(replaced.fieldIdx, [0, 2], 'rebinds the interval start field index');
t.deepEqual(replaced.endFieldIdx, [1, 1], 'rebinds the interval end field index');
@@ -3007,10 +3006,8 @@ test('#visStateReducer -> SET_FILTER.dataId rebinds interval fields on replaceme
t.deepEqual(replaced.gpuChannel, [0, 1], 'allocates a free replacement start channel');
t.deepEqual(replaced.gpuEndChannel, [1, 2], 'allocates a free replacement end channel');
- const missingEnd = reducer(
- state,
- VisStateActions.setFilter(0, 'dataId', 'missing-end', 1)
- ).filters[0];
+ const missingEnd = reducer(state, VisStateActions.setFilter(0, 'dataId', 'missing-end', 1))
+ .filters[0];
t.equal(missingEnd.name[1], 'start', 'keeps an available start selection');
t.equal(missingEnd.endName[1], null, 'clears a missing end selection');
t.equal(missingEnd.endFieldIdx[1], null, 'clears a missing end field index');
@@ -3587,6 +3584,315 @@ test('#visStateReducer -> SET_FILTER_ANIMATION_WINDOW interval snaps to one hist
t.end();
});
+test('#visStateReducer -> sparse datetime interval uses the cached bin end', t => {
+ const initialState = CloneDeep(StateWFilters.visState);
+ const filter = initialState.filters[0];
+ const dataId = filter.dataId[0];
+ const interval = '1-minute';
+ filter.domain = [0, 180000];
+ filter.value = [0, 0];
+ filter.animationWindow = ANIMATION_WINDOW.free;
+ filter.plotType = {...filter.plotType, interval};
+ filter.timeBins = {
+ [dataId]: {
+ [interval]: [
+ {count: 1, indexes: [0], x0: 0, x1: 60000},
+ {count: 1, indexes: [1], x0: 120000, x1: 180000}
+ ]
+ }
+ };
+
+ const nextState = reducer(
+ initialState,
+ VisStateActions.setFilterAnimationWindow({
+ id: filter.id,
+ animationWindow: ANIMATION_WINDOW.interval
+ })
+ );
+
+ t.deepEqual(
+ nextState.filters[0].value,
+ [0, 59999],
+ 'should stop at the selected cached calendar bin instead of the next non-empty bin'
+ );
+ t.end();
+});
+
+test('#visStateReducer -> numeric filter timeline uses numeric bins and no time-only state', t => {
+ let state = CloneDeep(StateWFilters.visState);
+ state = reducer(state, VisStateActions.setFilter(0, 'name', 'gps_data.lat'));
+
+ t.equal(state.filters[0].type, 'range', 'should switch the selected X field to a range filter');
+ t.equal(
+ state.filters[0].view,
+ FILTER_VIEW_TYPES.side,
+ 'should keep the numeric timeline disabled by default'
+ );
+
+ state = reducer(state, VisStateActions.setFilterPlot(0, {plotType: {numericInterval: 0.01}}));
+ state = reducer(state, VisStateActions.setFilterView(0, FILTER_VIEW_TYPES.enlarged));
+ state = reducer(state, VisStateActions.setFilter(0, 'name', 'gps_data.lng'));
+ t.equal(
+ state.filters[0].view,
+ FILTER_VIEW_TYPES.enlarged,
+ 'should keep an opted-in numeric timeline open when changing numeric fields'
+ );
+ state = reducer(state, VisStateActions.setFilter(0, 'name', 'gps_data.lat'));
+ state = reducer(
+ state,
+ VisStateActions.setFilterAnimationWindow({
+ id: state.filters[0].id,
+ animationWindow: ANIMATION_WINDOW.interval
+ })
+ );
+
+ const filter = state.filters[0];
+ const marks = getFilterBinThresholds(filter);
+ const markIndex = marks.indexOf(filter.value[0]);
+ t.ok(markIndex >= 0 && markIndex < marks.length - 1, 'should snap to a numeric histogram bin');
+ t.equal(
+ filter.value[1],
+ intervalBinFromMarks(marks, filter.value[0], 0)[1],
+ 'should match the selected histogram bin without sharing its next boundary'
+ );
+ t.equal(filter.plotType.numericInterval, 0.01, 'should persist the numeric bin size');
+ t.notOk(filter.timeBins, 'should not create calendar time bins');
+ t.notOk(filter.timezone, 'should not add a timezone');
+ t.notOk(
+ Object.prototype.hasOwnProperty.call(filter, 'syncTimelineMode'),
+ 'should not apply time timeline synchronization state'
+ );
+
+ const yAxis = state.datasets[filter.dataId[0]].fields.find(
+ field => field.name === 'gps_data.lng'
+ );
+ state = reducer(state, VisStateActions.setFilterPlot(0, {yAxis}));
+ state = reducer(state, VisStateActions.setFilterPlot(0, {plotType: {aggregation: 'sum'}}));
+ t.equal(state.filters[0].plotType.type, 'lineChart', 'should enable the Y-axis line chart');
+ t.ok(state.filters[0].lineChart?.series, 'should aggregate the selected Y field by numeric bins');
+
+ state = reducer(state, VisStateActions.setFilter(0, 'name', 'time'));
+ t.equal(state.filters[0].type, 'timeRange', 'should switch back to datetime behavior');
+ t.notOk(
+ state.filters[0].plotType.numericInterval,
+ 'should not apply the numeric bin size to datetime'
+ );
+ t.ok(state.filters[0].plotType.interval, 'should restore a calendar interval for datetime');
+ state = reducer(
+ state,
+ VisStateActions.setFilterAnimationTimeConfig(0, {timezone: 'America/New_York'})
+ );
+ state = reducer(state, VisStateActions.setFilter(0, 'name', 'gps_data.lat'));
+ t.equal(state.filters[0].type, 'range', 'should switch back to numeric behavior');
+ t.notOk(state.filters[0].timezone, 'should clear timezone state from a numeric filter');
+ t.notOk(state.filters[0].plotType.interval, 'should clear calendar binning from numeric mode');
+
+ t.end();
+});
+
+test('#visStateReducer -> oversized numeric intervals use coherent automatic bins', t => {
+ const {fields, rows} = processCsvData(`x
+0
+100`);
+ const payload = [
+ {
+ info: {id: 'numeric-bin-limit', label: 'numeric bin limit'},
+ data: {fields, rows}
+ }
+ ];
+ let state = applyActions(reducer, INITIAL_VIS_STATE, [
+ {
+ action: VisStateActions.updateVisData,
+ payload: [payload]
+ }
+ ]);
+ state = reducer(state, VisStateActions.addFilter('numeric-bin-limit'));
+ state = reducer(state, VisStateActions.setFilter(0, 'name', 'x'));
+ state = reducer(state, VisStateActions.setFilterPlot(0, {plotType: {numericInterval: 10}}));
+ t.equal(state.filters[0].plotType.numericInterval, 10, 'should keep a valid numeric interval');
+
+ state = reducer(state, VisStateActions.setFilterPlot(0, {plotType: {numericInterval: 0.01}}));
+
+ const filter = state.filters[0];
+ const effectiveInterval = getNumericPlotInterval(filter);
+ t.notOk(
+ Object.prototype.hasOwnProperty.call(filter.plotType, 'numericInterval'),
+ 'should discard an interval that exceeds the numeric bin limit'
+ );
+ t.ok(effectiveInterval > 0.01, 'should report the effective automatic bin width');
+ t.equal(
+ effectiveInterval,
+ filter.bins['numeric-bin-limit'][0].x1 - filter.bins['numeric-bin-limit'][0].x0,
+ 'the displayed interval should match the bins used by the filter plot'
+ );
+
+ t.end();
+});
+
+test('#visStateReducer -> numeric interval playback refilters exact bins', t => {
+ const {fields, rows} = processCsvData(`x
+-1.5
+-1
+-0.75
+0
+0.25
+0.5
+1`);
+ const payload = [
+ {
+ info: {id: 'numeric-interval', label: 'numeric interval'},
+ data: {fields, rows}
+ }
+ ];
+ let state = applyActions(reducer, INITIAL_VIS_STATE, [
+ {
+ action: VisStateActions.updateVisData,
+ payload: [payload]
+ }
+ ]);
+ state = reducer(state, VisStateActions.addFilter('numeric-interval'));
+ state = reducer(state, VisStateActions.setFilter(0, 'name', 'x'));
+ state = reducer(state, VisStateActions.setFilter(0, 'value', [-1.5, -1]));
+ state = reducer(state, VisStateActions.setFilterPlot(0, {plotType: {numericInterval: 1.5}}));
+ state = reducer(
+ state,
+ VisStateActions.setFilterAnimationWindow({
+ id: state.filters[0].id,
+ animationWindow: ANIMATION_WINDOW.interval
+ })
+ );
+
+ let filter = state.filters[0];
+ let dataset = state.datasets['numeric-interval'];
+ let marks = getFilterBinThresholds(filter);
+ t.deepEqual(
+ filter.value,
+ intervalBinFromMarks(marks, marks[0], 0),
+ 'entering interval mode snaps the paused selection to one numeric bin'
+ );
+ t.ok(
+ dataset.filterRecord.cpu.some(candidate => candidate.id === filter.id),
+ 'numeric interval membership uses the exact CPU filtering path'
+ );
+ t.notOk(
+ dataset.filterRecord.gpu.some(candidate => candidate.id === filter.id),
+ 'numeric interval membership does not use inclusive Float32 GPU bounds'
+ );
+ t.deepEqual(
+ dataset.filteredIndex,
+ [0, 1, 2],
+ 'the first bin excludes the exact boundary assigned to the next bin'
+ );
+
+ state = reducer(state, VisStateActions.setFilterPlot(0, {plotType: {numericInterval: 0.5}}));
+ filter = state.filters[0];
+ dataset = state.datasets['numeric-interval'];
+ marks = getFilterBinThresholds(filter);
+ const selectedMark = marks.indexOf(filter.value[0]);
+ t.ok(selectedMark >= 0 && selectedMark < marks.length - 1, 'uses a new histogram mark');
+ t.deepEqual(
+ filter.value,
+ intervalBinFromMarks(marks, filter.value[0], 0),
+ 'changing the numeric bin size resnaps a paused interval to one new bin'
+ );
+ t.deepEqual(
+ dataset.filteredIndex,
+ [3, 4],
+ 'changing the numeric bin size immediately reapplies the resnapped selection'
+ );
+
+ state = reducer(
+ state,
+ VisStateActions.setFilterAnimationWindow({
+ id: filter.id,
+ animationWindow: ANIMATION_WINDOW.free
+ })
+ );
+ filter = state.filters[0];
+ dataset = state.datasets['numeric-interval'];
+ t.ok(
+ dataset.filterRecord.gpu.some(candidate => candidate.id === filter.id),
+ 'leaving interval playback restores ordinary numeric GPU filtering'
+ );
+
+ t.end();
+});
+
+test('#visStateReducer -> visible numeric side charts refresh after sibling filters', t => {
+ const {fields, rows} = processCsvData(`x,category,value
+0,A,10
+0.05,A,20
+0.075,B,30
+0.1,B,40`);
+ const payload = [
+ {
+ info: {id: 'numeric-shared', label: 'numeric shared'},
+ data: {fields, rows}
+ }
+ ];
+
+ let state = applyActions(reducer, INITIAL_VIS_STATE, [
+ {
+ action: VisStateActions.updateVisData,
+ payload: [payload]
+ }
+ ]);
+ state = reducer(state, VisStateActions.addFilter('numeric-shared'));
+ state = reducer(state, VisStateActions.setFilter(0, 'name', 'x'));
+ state = reducer(state, VisStateActions.setFilterPlot(0, {plotType: {numericInterval: 0.05}}));
+ state = reducer(state, VisStateActions.addFilter('numeric-shared'));
+ state = reducer(state, VisStateActions.setFilter(1, 'name', 'category'));
+ const cachedHistogram = state.filters[0];
+ state = reducer(state, VisStateActions.setFilter(1, 'value', ['A']));
+ t.equal(
+ state.filters[0],
+ cachedHistogram,
+ 'an unconfigured numeric side histogram stays cached after sibling filtering'
+ );
+ state = reducer(state, VisStateActions.removeFilter(1));
+
+ const yAxis = state.datasets['numeric-shared'].fields.find(field => field.name === 'value');
+ state = reducer(state, VisStateActions.setFilterPlot(0, {yAxis}));
+ state = reducer(state, VisStateActions.setFilterView(0, FILTER_VIEW_TYPES.enlarged));
+
+ t.deepEqual(state.filters[0].lineChart.yDomain, [10, 40], 'open plot starts with all rows');
+
+ state = reducer(state, VisStateActions.setFilterView(0, FILTER_VIEW_TYPES.side));
+ state = reducer(state, VisStateActions.addFilter('numeric-shared'));
+ state = reducer(state, VisStateActions.setFilter(1, 'name', 'category'));
+ state = reducer(state, VisStateActions.setFilter(1, 'value', ['A']));
+
+ t.deepEqual(
+ state.filters[0].lineChart.yDomain,
+ [10, 20],
+ 'visible side chart rebuilds its Y domain after sibling filtering'
+ );
+ t.equal(
+ state.filters[0].lineChart.allTime.value,
+ 15,
+ 'visible side chart rebuilds its Y aggregate after sibling filtering'
+ );
+ t.deepEqual(
+ state.filters[0].bins['numeric-shared'].map(bin => bin.count),
+ [1, 1, 0],
+ 'visible side chart rebuilds bin counts after sibling filtering'
+ );
+
+ state = reducer(state, VisStateActions.removeFilter(1));
+ t.deepEqual(
+ state.filters[0].lineChart.yDomain,
+ [10, 40],
+ 'removing the sibling filter restores the visible side chart Y domain'
+ );
+ t.equal(
+ state.filters[0].lineChart.allTime.value,
+ 25,
+ 'removing the sibling filter restores the visible side chart aggregate'
+ );
+
+ t.end();
+});
+
test('#visStateReducer -> UPDATE_FILTER_ANIMATION_SPEED', t => {
const initialState = CloneDeep(StateWFilters.visState);
diff --git a/test/node/schemas/vis-state-schema-test.js b/test/node/schemas/vis-state-schema-test.js
index 74eb9518d..01ccb9670 100644
--- a/test/node/schemas/vis-state-schema-test.js
+++ b/test/node/schemas/vis-state-schema-test.js
@@ -28,6 +28,7 @@ import {
} from 'test/helpers/mock-state';
import {keplerGlReducerCore as keplerGlReducer, validateLayerWithData} from '@kepler.gl/reducers';
import {VisStateActions} from '@kepler.gl/actions';
+import {FILTER_VIEW_TYPES} from '@kepler.gl/constants';
const expectedVisStateEntries = [
'filters',
@@ -142,6 +143,29 @@ test('#visStateSchema -> v1 -> save load filters', t => {
t.end();
});
+test('#visStateSchema -> v1 -> persists opt-in numeric timeline configuration', t => {
+ let state = keplerGlReducer(
+ cloneDeep(StateWFilesFiltersLayerColor),
+ VisStateActions.setFilter(0, 'name', 'gps_data.lat')
+ );
+ state = keplerGlReducer(
+ state,
+ VisStateActions.setFilterPlot(0, {plotType: {numericInterval: 0.01}})
+ );
+ state = keplerGlReducer(state, VisStateActions.setFilterView(0, FILTER_VIEW_TYPES.enlarged));
+
+ const savedState = SchemaManager.getConfigToSave(state);
+ const savedFilter = savedState.config.visState.filters[0];
+ const loadedFilter = SchemaManager.parseSavedConfig(savedState).visState.filters[0];
+
+ t.equal(savedFilter.view, FILTER_VIEW_TYPES.enlarged, 'should save numeric timeline enablement');
+ t.equal(savedFilter.plotType.numericInterval, 0.01, 'should save the numeric bin size');
+ t.equal(loadedFilter.view, FILTER_VIEW_TYPES.enlarged, 'should restore numeric enablement');
+ t.equal(loadedFilter.plotType.numericInterval, 0.01, 'should restore numeric binning');
+ t.notOk(loadedFilter.timezone, 'should not load time-only configuration');
+ t.end();
+});
+
test('#visStateSchema -> v1 -> save and validate filters', t => {
const initialState = cloneDeep(StateWFilesFiltersLayerColor);
diff --git a/test/node/utils/plot-test.js b/test/node/utils/plot-test.js
index a580e840f..e72c33b60 100644
--- a/test/node/utils/plot-test.js
+++ b/test/node/utils/plot-test.js
@@ -6,7 +6,12 @@ import {
histogramFromThreshold,
histogramFromValues,
histogramFromTimeIntervals,
+ getNumericBinThresholds,
+ getNumericPlotInterval,
+ getNumericRangeMinimum,
intervalBinFromMarks,
+ nextDown,
+ nextUp,
mergePolygonLayerIndexes,
runGpuFilterForPlot,
getLineChart,
@@ -19,6 +24,90 @@ import {
const values1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
+test('Utils -> getNumericBinThresholds uses numeric units', t => {
+ t.deepEqual(
+ getNumericBinThresholds([-1.5, 1], 0.5),
+ [-1.5, -1, -0.5, 0, 0.5, 1],
+ 'should preserve negative and fractional numeric boundaries'
+ );
+ t.deepEqual(
+ getNumericBinThresholds([7, 8], 0.25),
+ [7, 7.25, 7.5, 7.75, 8],
+ 'should bin the padded domain of a constant numeric field'
+ );
+ t.deepEqual(
+ getNumericBinThresholds([-0.2, -0.19], 0.01),
+ [-0.2, -0.19],
+ 'should not duplicate a decimal domain end because of floating-point division'
+ );
+ const maximumBins = getNumericBinThresholds([-4.42, 16.060000000000002], 0.01);
+ t.equal(maximumBins.length, 2049, 'should keep exactly 2048 bins at the safety cap');
+ t.equal(maximumBins[0], -4.42, 'should preserve the capped domain start');
+ t.equal(
+ maximumBins[maximumBins.length - 1],
+ 16.060000000000002,
+ 'should preserve the capped domain end'
+ );
+ t.ok(
+ maximumBins.every((boundary, index) => index === 0 || boundary > maximumBins[index - 1]),
+ 'should generate only strictly increasing numeric boundaries'
+ );
+ const fallback = getNumericBinThresholds([0, 1], -1);
+ t.ok(fallback.length > 2 && fallback.length < 100, 'should safely replace an invalid bin size');
+ t.equal(fallback[0], 0, 'should keep the numeric domain start');
+ t.equal(fallback[fallback.length - 1], 1, 'should keep the numeric domain end');
+ t.end();
+});
+
+test('Utils -> getNumericPlotInterval ignores padded edge bins', t => {
+ const filter = {
+ domain: [-0.20000000000000004, -0.18999],
+ step: 0.00001,
+ plotType: {},
+ bins: {
+ dataset: [
+ {x0: -0.20000000000000004, x1: -0.2},
+ {x0: -0.2, x1: -0.1995},
+ {x0: -0.1995, x1: -0.199}
+ ]
+ }
+ };
+
+ t.equal(
+ getNumericPlotInterval(filter),
+ 0.0005,
+ 'should use the median positive width instead of a floating-point edge sliver'
+ );
+ t.equal(
+ getNumericPlotInterval({...filter, plotType: {numericInterval: 0.0025}}),
+ 0.0025,
+ 'should preserve an explicit numeric interval'
+ );
+ t.end();
+});
+
+test('Utils -> numeric range precision follows representable domain spacing', t => {
+ const domains = [
+ [0, 1e-20],
+ [1e12, 1e12 + 0.001],
+ [0, 0.1]
+ ];
+
+ for (const domain of domains) {
+ const [start, end] = domain;
+ const span = end - start;
+ const minimum = getNumericRangeMinimum(domain);
+ t.ok(minimum > 0, `${domain} should have a positive representable minimum`);
+ t.ok(minimum <= span, `${domain} minimum should not exceed its span`);
+ t.ok(start + minimum > start, `${domain} minimum should advance the lower endpoint`);
+ t.ok(end - minimum < end, `${domain} minimum should retreat the upper endpoint`);
+ }
+
+ t.equal(nextDown(nextUp(1e12)), 1e12, 'adjacent numeric values should round-trip');
+ t.equal(nextDown(0), -Number.MIN_VALUE, 'zero should have a negative predecessor');
+ t.end();
+});
+
test('Utils -> mergePolygonLayerIndexes', t => {
const baseIndex = [0, 1, 2, 3];
@@ -417,6 +506,54 @@ function seriesSummary(lineChart) {
};
}
+test('Utils -> getLineChart aggregates numeric range bins on a numeric X axis', t => {
+ const rows = [
+ {x: -1.25, y: 2},
+ {x: -0.75, y: 3},
+ {x: -0.25, y: null},
+ {x: 0.25, y: 5}
+ ];
+ const bins = [
+ {count: 1, indexes: [0], x0: -1.5, x1: -1},
+ {count: 1, indexes: [1], x0: -1, x1: -0.5},
+ {count: 1, indexes: [2], x0: -0.5, x1: 0},
+ {count: 1, indexes: [3], x0: 0, x1: 0.5}
+ ];
+ const chart = getLineChart(
+ {
+ ds: {
+ fields: [
+ {name: 'x', type: 'real', valueAccessor: ({index}) => rows[index].x},
+ {name: 'y', type: 'real', valueAccessor: ({index}) => rows[index].y}
+ ]
+ }
+ },
+ {
+ type: 'range',
+ dataId: ['ds'],
+ yAxis: {name: 'y', type: 'real'},
+ plotType: {type: 'lineChart', aggregation: 'sum', numericInterval: 0.5},
+ bins: {ds: bins}
+ }
+ );
+
+ t.deepEqual(chart.xDomain, [-1.5, 0.5], 'should keep numeric X-domain values');
+ t.equal(chart.interval, 0.5, 'should cache the numeric bin size without calendar conversion');
+ t.deepEqual(
+ chart.series.lines.map(line => line.map(point => [point.x, point.y])),
+ [
+ [
+ [-1.5, 2],
+ [-1, 3],
+ [-0.5, 0],
+ [0, 5]
+ ]
+ ],
+ 'should aggregate each numeric bin and tolerate missing Y values'
+ );
+ t.end();
+});
+
test('Utils -> getLineChart groupBy splits series and folds the rest into Others', t => {
const datasets = {ds: groupedDataset()};
const colors = ['#111111', '#222222', '#333333'];
@@ -624,6 +761,59 @@ test('Utils -> intervalBinFromMarks snaps a brush position to one histogram bin'
[10, 10],
'should leave the value unchanged without marks'
);
+ t.deepEqual(
+ intervalBinFromMarks([-1.5, -1, -0.5], -1.3, 0),
+ [-1.5, nextDown(-1)],
+ 'should end a numeric bin at the representable value before its next boundary'
+ );
+ t.deepEqual(
+ intervalBinFromMarks([0, 0.05, 0.1], 0, 0),
+ [0, nextDown(0.05)],
+ 'should exclude the next fractional bin boundary without subtracting a nominal step'
+ );
+ t.deepEqual(
+ intervalBinFromMarks([0, 0.05, 0.1], 0.1, 0),
+ [0.05, 0.1],
+ 'should include the numeric domain maximum in the final interval'
+ );
+
+ t.end();
+});
+
+test('Utils -> numeric interval selection matches histogram row membership', t => {
+ const values = [0, 0.05, 0.075, 0.1];
+ const rowIds = values.map((_, index) => index);
+ const thresholds = getNumericBinThresholds([0, 0.1], 0.05);
+ const bins = histogramFromThreshold(thresholds, rowIds, index => values[index], false);
+ const marks = [...bins.map(bin => bin.x0), bins[bins.length - 1].x1];
+ const dataset = {
+ dataContainer: {},
+ filteredIndex: rowIds,
+ filteredIndexByLayer: {},
+ gpuFilter: {
+ filterValueUpdateTriggers: {gpuFilter_0: {name: 'x'}},
+ filterRange: [[0, 0]],
+ filterValueAccessor:
+ () =>
+ () =>
+ ({index}) =>
+ [values[index]]
+ }
+ };
+
+ t.deepEqual(
+ bins.map(bin => bin.count),
+ [1, 2, 1],
+ 'fixture should exercise two half-open boundaries and the final maximum bin'
+ );
+ bins.forEach((bin, index) => {
+ dataset.gpuFilter.filterRange = [intervalBinFromMarks(marks, bin.x0, 0)];
+ t.deepEqual(
+ runGpuFilterForPlot(dataset),
+ [...bin.indexes],
+ `interval ${index} should select exactly the row IDs assigned to its histogram bin`
+ );
+ });
t.end();
});
diff --git a/test/node/utils/timeline-zoom-test.js b/test/node/utils/timeline-zoom-test.js
index 8a82fe25d..0b0df568e 100644
--- a/test/node/utils/timeline-zoom-test.js
+++ b/test/node/utils/timeline-zoom-test.js
@@ -2,7 +2,7 @@
// Copyright contributors to the kepler.gl project
import test from 'tape';
-import {clamp} from '@kepler.gl/utils';
+import {clamp, getNumericRangeMinimum, nextUp} from '@kepler.gl/utils';
import {
rangesEqual,
clampRange,
@@ -18,6 +18,14 @@ test('Timeline Zoom Utils -> rangesEqual', t => {
t.notOk(rangesEqual(null, null), 'both null should return false');
t.ok(rangesEqual([1000, 5000], [1000, 5000], 0), 'exact match with eps=0');
t.notOk(rangesEqual([1000, 5000], [1001, 5000], 0), 'off by 1 with eps=0 should not match');
+ t.notOk(
+ rangesEqual([0, 0.1], [0.02, 0.08], 0),
+ 'fractional numeric ranges should use exact equality'
+ );
+ t.notOk(
+ rangesEqual([1e12, 1e12 + 0.001], [nextUp(1e12), 1e12 + 0.001], 0),
+ 'a one-representable-step change at a high offset should stay observable'
+ );
t.end();
});
@@ -78,6 +86,22 @@ test('Timeline Zoom Utils -> clampWindowToDomain', t => {
'window equal to domain stays unchanged'
);
+ const numericMinimum = getNumericRangeMinimum([0, 0.1]);
+ const [numericStart, numericEnd] = clampWindowToDomain(0.05, 0.05, [0, 0.1], numericMinimum);
+ t.equal(numericStart, 0.05, 'fractional numeric window keeps its start');
+ t.ok(numericEnd > numericStart, 'fractional numeric window gets a representable positive width');
+ t.ok(numericEnd < 0.1, 'fractional numeric window does not expand by one whole unit');
+
+ for (const domain of [
+ [0, 1e-20],
+ [1e12, 1e12 + 0.001]
+ ]) {
+ const minimum = getNumericRangeMinimum(domain);
+ const [start, end] = clampWindowToDomain(domain[0], domain[0], domain, minimum);
+ t.ok(end > start, `${domain} should expand a collapsed window by a representable amount`);
+ t.ok(end <= domain[1], `${domain} should keep the expanded window inside its domain`);
+ }
+
t.end();
});
@@ -132,6 +156,21 @@ test('Timeline Zoom Utils -> timeline domain zoom logic', t => {
t.end();
});
+test('Timeline Zoom Utils -> fractional numeric zoom uses domain-relative minimums', t => {
+ const fullDomain = [0, 0.1];
+ const selection = [0.02, 0.08];
+ const domainWidth = fullDomain[1] - fullDomain[0];
+ const selectionWidth = selection[1] - selection[0];
+ const nextSelectionWidth = clamp([domainWidth / 100, domainWidth], selectionWidth / 1.08);
+ const nextTimelineWidth = clamp([domainWidth / 20, domainWidth], domainWidth / 1.02);
+
+ t.ok(nextSelectionWidth < selectionWidth, 'fractional selection can zoom below one unit');
+ t.ok(nextSelectionWidth > 0, 'fractional selection keeps a positive width');
+ t.ok(nextTimelineWidth < domainWidth, 'fractional visible timeline can zoom below one unit');
+ t.ok(nextTimelineWidth >= domainWidth / 20, 'fractional timeline respects its relative floor');
+ t.end();
+});
+
test('Timeline Zoom Utils -> keyboard panning step logic', t => {
const filterStart = 200;
const filterEnd = 400;