Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
[Feat] timeline zoom & precision controls in enlarged time filter (#3460)
Igor Dykhta5880a25fb065
diff --git a/docs/user-guides/h-playback.md b/docs/user-guides/h-playback.mdindex 0a0115f00..a6cc5ebfb 100644--- a/docs/user-guides/h-playback.md+++ b/docs/user-guides/h-playback.md@@ -15,5 +15,13 @@ Follow these steps to create a playback video of an event:+## Zoom & precision controls++The enlarged timeline now lets you stay focused on the portion that matters:++- Use the mouse wheel to resize the window under the cursor, and pinch (or hold <kbd>Ctrl</kbd> on Windows/Linux or <kbd>⌘</kbd> on macOS while scrolling) to zoom the full timeline.+- A lightweight "Showing" bar appears whenever the full range is narrowed—click **Reset** to return to the original domain.+- Hold <kbd>Ctrl</kbd> (Windows/Linux) or <kbd>⌘</kbd> (macOS) and press the arrow keys to pan left/right, with <kbd>Shift</kbd> for bigger steps.+[Back to table of contents](README.md)diff --git a/src/components/src/common/histogram-plot.tsx b/src/components/src/common/histogram-plot.tsxindex 7410fb4de..e9fde255f 100644--- a/src/components/src/common/histogram-plot.tsx+++ b/src/components/src/common/histogram-plot.tsx@@ -1,7 +1,7 @@// SPDX-License-Identifier: MIT// Copyright contributors to the kepler.gl project-import React, {ReactElement, useMemo} from 'react';+import React, {ReactElement, useMemo, useRef} from 'react';import {scaleLinear} from 'd3-scale';import {hcl} from 'd3-color';import {min, max} from 'd3-array';@@ -63,24 +63,11 @@ Bar.displayName = 'Bar';const isBarInRange = (bar: {x0: number; x1: number},- index: number,- list: any[],- filterDomain: any[],+ _index: number,+ _list: any[],+ _filterDomain: any[],filterValue: any[]-) => {- // first- // if x0 <= domain[0] and current value[0] wasn't changed from the original domain- const x0Condition =- index === 0 ? bar.x0 <= filterDomain[0] && filterDomain[0] === filterValue[0] : false;- // Last- // if x1 >= domain[1] and current value[1] wasn't changed from the original domain- const x1Condition =- index === list.length - 1- ? bar.x1 >= filterDomain[1] && filterDomain[1] === filterValue[1]- : false;- // Check if the bar overlaps with the filter value range (not fully contained)- return (x0Condition || bar.x1 > filterValue[0]) && (x1Condition || bar.x0 < filterValue[1]);-};+) => bar.x1 > filterValue[0] && bar.x0 < filterValue[1];export type HistogramMaskModeType = {NoMask: number;@@ -182,6 +169,9 @@ function HistogramPlotFactory() {return ticks;}, [isEnlarged, groupKeys, histogramsByGroup, countProp]);+ const clipIdRef = useRef(`histogram-clip-${Math.random().toString(36).slice(2)}`);+ const clipId = clipIdRef.current;+if (groupKeys.length === 0) {return null;}@@ -194,6 +184,9 @@ function HistogramPlotFactory() {style={{margin: `${margin.top}px ${margin.right}px ${margin.bottom}px ${margin.left}px`}}><defs>+ <clipPath id={`${clipId}-mask`}>+ <rect x="0" y="0" width={width} height={height + margin.bottom} />+ </clipPath><mask id="histogram-mask"><rectx="0"@@ -238,7 +231,12 @@ function HistogramPlotFactory() {/></g>{isMasked === HISTOGRAM_MASK_MODE.MaskWithOverlay && (- <g key="bins" transform="translate(0,0)" className="overlay-histogram-bars">+ <g+ key="bins"+ transform="translate(0,0)"+ className="overlay-histogram-bars"+ clipPath={`url(#${clipId}-mask)`}+ >{histogramsByGroup.bins.map((bar, idx, list) => {const filterBar = histogramsByGroup.filteredBins[idx];const maskHeight = filterBar@@ -284,7 +282,13 @@ function HistogramPlotFactory() {height={height}style={{margin: `${margin.top}px ${margin.right}px ${margin.bottom}px ${margin.left}px`}}>- <g>+ <defs>+ <clipPath id={clipId}>+ <rect x="0" y="0" width={width} height={height} />+ </clipPath>+ </defs>+ <g transform={`translate(${isRanged ? 0 : fallbackBarWidth / 2}, 0)`}>{brushComponent}</g>+ <g clipPath={`url(#${clipId})`} style={{pointerEvents: 'none'}}>{groupKeys.map((key, i) => (<g key={key} className="histogram-bars">{histogramsByGroup[key].map((bar, idx, list) => {@@ -334,7 +338,6 @@ function HistogramPlotFactory() {))}</g>) : null}- <g transform={`translate(${isRanged ? 0 : fallbackBarWidth / 2}, 0)`}>{brushComponent}</g></HistogramWrapper>);};diff --git a/src/components/src/common/time-range-slider.tsx b/src/components/src/common/time-range-slider.tsxindex 2b44becbd..096e42f92 100644--- a/src/components/src/common/time-range-slider.tsx+++ b/src/components/src/common/time-range-slider.tsx@@ -1,7 +1,7 @@// SPDX-License-Identifier: MIT// Copyright contributors to the kepler.gl project-import React, {useMemo} from 'react';+import React, {useEffect, useMemo} from 'react';import throttle from 'lodash/throttle';import styled, {IStyledComponent} from 'styled-components';@@ -124,6 +124,8 @@ export default function TimeRangeSliderFactory(} = props;const throttledOnchange = useMemo(() => throttle(onChange, 20), [onChange]);+ useEffect(() => () => throttledOnchange.cancel(), [throttledOnchange]);+const binsForInterval = useMemo(() => getTimeBinsForInterval(timeBins, plotType?.interval),[timeBins, plotType?.interval]diff --git a/src/components/src/common/timeline-helpers.ts b/src/components/src/common/timeline-helpers.tsnew file mode 100644index 000000000..519f11593--- /dev/null+++ b/src/components/src/common/timeline-helpers.ts@@ -0,0 +1,51 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import {clamp} from '@kepler.gl/utils';++export function rangesEqual(+ a: [number, number] | null,+ b: [number, number] | null,+ eps = 1+): boolean {+ if (!a || !b) {+ return false;+ }+ return Math.abs(a[0] - b[0]) <= eps && Math.abs(a[1] - b[1]) <= eps;+}++export function clampRange(+ [start, end]: [number, number],+ [min, max]: [number, number]+): [number, number] {+ const clampedStart = clamp([min, max], start);+ let clampedEnd = clamp([min, max], end);+ if (clampedEnd <= clampedStart) {+ clampedEnd = Math.min(max, clampedStart + 1);+ }+ return [clampedStart, clampedEnd];+}++export function clampWindowToDomain(+ windowStart: number,+ windowEnd: number,+ domainRange: [number, number]+): [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 maxStart = Math.max(domainStart, domainEnd - width);+ nextStart = clamp([domainStart, maxStart], windowStart);+ nextEnd = nextStart + width;+ if (nextEnd > domainEnd) {+ nextEnd = domainEnd;+ nextStart = Math.max(domainStart, nextEnd - width);+ }+ }+ if (nextEnd <= nextStart) {+ nextEnd = Math.min(domainEnd, nextStart + 1);+ }+ return [nextStart, nextEnd];+}diff --git a/src/components/src/filters/time-widget.tsx b/src/components/src/filters/time-widget.tsxindex 83aa53059..a803784c8 100644--- a/src/components/src/filters/time-widget.tsx+++ b/src/components/src/filters/time-widget.tsx@@ -1,21 +1,59 @@// SPDX-License-Identifier: MIT// Copyright contributors to the kepler.gl project-import React, {useCallback, useMemo, useState} from 'react';+import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';import styled from 'styled-components';-import {FILTER_VIEW_TYPES} from '@kepler.gl/constants';-import {BottomWidgetInner} from '../common/styled-components';+import throttle from 'lodash/throttle';+import {DEFAULT_TIME_FORMAT, FILTER_VIEW_TYPES} from '@kepler.gl/constants';+import {clamp, datetimeFormatter} from '@kepler.gl/utils';+import {BottomWidgetInner, Button, PanelLabel} from '../common/styled-components';import TimeRangeSliderFactory from '../common/time-range-slider';import FloatingTimeDisplayFactory from '../common/animation-control/floating-time-display';import {timeRangeSliderFieldsSelector} from './time-range-filter';import {TimeWidgetProps} from './types';import TimeWidgetTopFactory from './time-widget-top';import TimeWidgetSettingsFactory from './time-widget-settings';+import {rangesEqual, clampRange, clampWindowToDomain} from '../common/timeline-helpers';const TimeBottomWidgetInner = styled(BottomWidgetInner)`padding: 6px 32px 24px 32px;`;+const TimelineSection = styled.div`+ position: relative;+ margin-top: 22px;+ display: flex;+ flex-direction: column;+ align-items: stretch;+ gap: 12px;+`;++const TimelineContainer = styled.div`+ touch-action: none;+`;++const TimelineStatusBar = styled.div`+ position: absolute;+ top: -32px;+ left: 50%;+ transform: translateX(-50%);+ display: flex;+ align-items: center;+ gap: 12px;+ font-size: 11px;+ color: ${props => props.theme.subtextColor};++ .side-panel-panel__label {+ margin-bottom: 0;+ }+`;++const TimelineStatusRange = styled.span`+ color: ${props => props.theme.textColorHl || props.theme.textColor};+ font-weight: 500;+ white-space: nowrap;+`;+TimeWidgetFactory.deps = [TimeRangeSliderFactory,FloatingTimeDisplayFactory,@@ -85,6 +123,263 @@ function TimeWidgetFactory([filter, datasets, layers]);+ const fullDomain = Array.isArray(timeRangeSlideProps.domain)+ ? (timeRangeSlideProps.domain as [number, number])+ : null;++ const [timelineDomain, setTimelineDomain] = useState<[number, number] | null>(null);+ const timelineContainerRef = useRef<HTMLDivElement | null>(null);++ useEffect(() => {+ if (!fullDomain) {+ if (timelineDomain) {+ setTimelineDomain(null);+ }+ return;+ }+ if (timelineDomain) {+ const clamped = clampRange(timelineDomain, fullDomain);+ if (!rangesEqual(clamped, timelineDomain)) {+ setTimelineDomain(clamped);+ }+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [fullDomain]);++ const sliderDomain = timelineDomain ?? fullDomain ?? undefined;+ const displayedTimelineDomain = sliderDomain ?? null;++ const timelineZoomed = useMemo(() => {+ if (!timelineDomain || !fullDomain) {+ return false;+ }+ return !rangesEqual(timelineDomain, fullDomain);+ }, [timelineDomain, fullDomain]);++ const timeFormat =+ timeRangeSlideProps.timeFormat ||+ filter.timeFormat ||+ filter.defaultTimeFormat ||+ DEFAULT_TIME_FORMAT;+ const formatTimestamp = useMemo(() => {+ const formatter = datetimeFormatter(filter.timezone);+ return (value: number) => formatter(timeFormat)(value);+ }, [filter.timezone, timeFormat]);++ const timelineRangeLabel = useMemo(() => {+ if (!displayedTimelineDomain) {+ return '';+ }+ return `${formatTimestamp(displayedTimelineDomain[0])} – ${formatTimestamp(+ displayedTimelineDomain[1]+ )}`;+ }, [displayedTimelineDomain, formatTimestamp]);++ const [filterStart, filterEnd] = filter.value;++ const handleWindowZoom = useCallback(+ (factor: number, center: number) => {+ if (!fullDomain) {+ return;+ }+ const domainRange: [number, number] = timelineDomain ?? fullDomain;+ const domainWidth = domainRange[1] - domainRange[0];+ if (!(domainWidth > 0)) {+ return;+ }+ const windowWidth = filterEnd - filterStart;+ if (!(windowWidth > 0)) {+ return;+ }+ const minWidth = Math.max(domainWidth / 100, 1);+ const nextWidth = clamp([minWidth, domainWidth], windowWidth / factor);+ const clampedCenter = clamp(domainRange, center);+ const ratio = clamp(+ [0, 1],+ windowWidth > 0 ? (clampedCenter - filterStart) / windowWidth : 0.5+ );+ const nextStart = clampedCenter - ratio * nextWidth;+ const nextEnd = nextStart + nextWidth;+ const [clampedStart, clampedEnd] = clampWindowToDomain(nextStart, nextEnd, domainRange);+ if (clampedStart !== filterStart || clampedEnd !== filterEnd) {+ setFilterAnimationTime(index, 'value', [clampedStart, clampedEnd]);+ }+ },+ [+ filterEnd,+ filterStart,+ fullDomain,+ index,+ setFilterAnimationTime,+ timelineDomain+ ]+ );++ const handleTimelineZoom = useCallback(+ (factor: number, center: number) => {+ if (!fullDomain) {+ return;+ }+ const domainRange: [number, number] = timelineDomain ?? fullDomain;+ const [domainStart, domainEnd] = fullDomain;+ const fullWidth = domainEnd - domainStart;+ if (!(fullWidth > 0)) {+ return;+ }+ const baseWidth = Math.max(domainRange[1] - domainRange[0], 1);+ const clampedCenter = clamp(domainRange, center);+ const minWidth = Math.max(fullWidth / 20, 1);+ const nextWidth = clamp([minWidth, fullWidth], baseWidth / factor);+ const ratio = clamp(+ [0, 1],+ baseWidth > 0 ? (clampedCenter - domainRange[0]) / baseWidth : 0.5+ );++ let nextStart = clampedCenter - ratio * nextWidth;+ let nextEnd = nextStart + nextWidth;++ if (nextStart < domainStart) {+ const shift = domainStart - nextStart;+ nextStart = domainStart;+ nextEnd += shift;+ }+ if (nextEnd > domainEnd) {+ const shift = nextEnd - domainEnd;+ nextEnd = domainEnd;+ nextStart -= shift;+ }+ const nextRange: [number, number] = clampRange([nextStart, nextEnd], fullDomain);+ setTimelineDomain(prev => (rangesEqual(prev, nextRange) ? prev : nextRange));++ let windowStart = filterStart;+ let windowEnd = filterEnd;+ const rangeWidth = nextRange[1] - nextRange[0];+ if (rangeWidth < windowEnd - windowStart) {+ const windowWidth = Math.max(windowEnd - windowStart, 1);+ 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);+ } else {+ [windowStart, windowEnd] = clampWindowToDomain(windowStart, windowEnd, nextRange);+ }+ if (windowStart !== filterStart || windowEnd !== filterEnd) {+ setFilterAnimationTime(index, 'value', [windowStart, windowEnd]);+ }+ },+ [+ filterEnd,+ filterStart,+ fullDomain,+ index,+ setFilterAnimationTime,+ timelineDomain+ ]+ );++ const throttledWindowZoom = useMemo(+ () => throttle(handleWindowZoom, 40, {leading: true, trailing: false}),+ [handleWindowZoom]+ );++ const throttledTimelineZoom = useMemo(+ () => throttle(handleTimelineZoom, 40, {leading: true, trailing: false}),+ [handleTimelineZoom]+ );++ useEffect(() => () => throttledWindowZoom.cancel(), [throttledWindowZoom]);+ useEffect(() => () => throttledTimelineZoom.cancel(), [throttledTimelineZoom]);++ useEffect(() => {+ const node = timelineContainerRef.current;+ if (!node) {+ return undefined;+ }+ const handleNativeWheel = (event: WheelEvent) => {+ if (isMinified || !sliderDomain) {+ return;+ }+ const isPinch =+ event.ctrlKey || event.metaKey || Math.abs(event.deltaZ || 0) > 0;+ const zoomFn = isPinch ? throttledTimelineZoom : throttledWindowZoom;+ if (!zoomFn) {+ return;+ }++ event.preventDefault();+ event.stopPropagation();++ if (event.deltaY === 0) {+ return;+ }++ const baseStep = isPinch ? 0.02 : 0.08;+ const factor = event.deltaY < 0 ? 1 + baseStep : 1 / (1 + baseStep);+ const sliderTrack = node.querySelector(+ '.kg-range-slider__slider'+ ) as HTMLElement | null;+ const rect = sliderTrack?.getBoundingClientRect() ?? node.getBoundingClientRect();+ if (!rect || rect.width === 0) {+ return;+ }+ const ratio = clamp([0, 1], (event.clientX - rect.left) / rect.width);+ const center = sliderDomain[0] + ratio * (sliderDomain[1] - sliderDomain[0]);+ zoomFn(factor, center);+ };+ node.addEventListener('wheel', handleNativeWheel, {passive: false});+ return () => node.removeEventListener('wheel', handleNativeWheel);+ }, [isMinified, sliderDomain, throttledTimelineZoom, throttledWindowZoom]);++ useEffect(() => {+ if (isMinified) {+ return undefined;+ }+ const handler = (event: KeyboardEvent) => {+ if (!(event.ctrlKey || event.metaKey)) {+ return;+ }+ if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') {+ return;+ }+ const activeEl = document.activeElement;+ if (+ activeEl instanceof HTMLInputElement ||+ activeEl instanceof HTMLTextAreaElement ||+ (activeEl as HTMLElement)?.isContentEditable+ ) {+ return;+ }+ const domainRange = timelineDomain ?? fullDomain;+ if (!domainRange) {+ return;+ }+ const windowWidth = filterEnd - filterStart;+ if (!(windowWidth > 0)) {+ return;+ }+ event.preventDefault();+ let nextStart: number;+ let nextEnd: number;+ if (event.key === 'ArrowRight') {+ nextStart = filterEnd;+ nextEnd = filterEnd + windowWidth;+ } else {+ nextStart = filterStart - windowWidth;+ nextEnd = filterStart;+ }+ [nextStart, nextEnd] = clampWindowToDomain(nextStart, nextEnd, domainRange);+ if (nextStart !== filterStart || nextEnd !== filterEnd) {+ setFilterAnimationTime(index, 'value', [nextStart, nextEnd]);+ }+ };+ window.addEventListener('keydown', handler);+ return () => window.removeEventListener('keydown', handler);+ }, [filterEnd, filterStart, fullDomain, index, isMinified, setFilterAnimationTime, timelineDomain]);++ const handleResetTimeline = useCallback(() => {+ setTimelineDomain(null);+ }, []);+return (<TimeBottomWidgetInner className="bottom-widget--inner"><TimeWidgetTop@@ -98,23 +393,42 @@ function TimeWidgetFactory({showSettings && !isMinified ? (<TimeWidgetSettings filter={filter} datasets={datasets} setFilterPlot={_setFilterPlot} />) : null}- {/* Once AnimationControl is able to display large timeline*/}- {/* we can replace TimeRangeSlider with AnimationControl*/}- <TimeRangeSlider- {...timeRangeSlideProps}- onChange={timeSliderOnChange}- toggleAnimation={_toggleAnimation}- exportAnimation={_exportAnimation}- updateAnimationSpeed={_updateAnimationSpeed}- setFilterAnimationWindow={_setFilterAnimationWindow}- hideTimeTitle={showTimeDisplay}- resetAnimation={resetAnimation}- isAnimatable={isAnimatable}- setFilterPlot={_setFilterPlot}- animationConfig={animationConfig}- isMinified={isMinified}- timeline={timeline}- />+ <TimelineSection>+ {timelineZoomed && timelineRangeLabel ? (+ <TimelineStatusBar>+ <PanelLabel>Showing</PanelLabel>+ <TimelineStatusRange>{timelineRangeLabel}</TimelineStatusRange>+ <Button+ small+ secondary+ type="button"+ onClick={handleResetTimeline}+ aria-label="Reset timeline selection"+ data-testid="time-widget-timeline-reset"+ >+ Reset+ </Button>+ </TimelineStatusBar>+ ) : null}+ <TimelineContainer ref={timelineContainerRef}>+ <TimeRangeSlider+ {...timeRangeSlideProps}+ domain={sliderDomain}+ onChange={timeSliderOnChange}+ toggleAnimation={_toggleAnimation}+ exportAnimation={_exportAnimation}+ updateAnimationSpeed={_updateAnimationSpeed}+ setFilterAnimationWindow={_setFilterAnimationWindow}+ hideTimeTitle={showTimeDisplay}+ resetAnimation={resetAnimation}+ isAnimatable={isAnimatable}+ setFilterPlot={_setFilterPlot}+ animationConfig={animationConfig}+ isMinified={isMinified}+ timeline={timeline}+ />+ </TimelineContainer>+ </TimelineSection>{showTimeDisplay ? (<FloatingTimeDisplaycurrentTime={filter.value}diff --git a/test/browser/components/filters/time-widget-test.js b/test/browser/components/filters/time-widget-test.jsindex 9c8c91e93..eacda93c8 100644--- a/test/browser/components/filters/time-widget-test.js+++ b/test/browser/components/filters/time-widget-test.js@@ -459,3 +459,105 @@ test('Components -> TimeWidget.mount -> TimeTitle', t => {t.end();});++test('Components -> TimeWidget.mount -> timeline zoom reset button', t => {+ const setFilterAnimationTime = sinon.spy();+ const clientSizeStub = mockHTMLElementClientSize('offsetWidth', 500);++ let wrapper;+ t.doesNotThrow(() => {+ wrapper = mountWithTheme(+ <IntlWrapper>+ <TimeWidget {...defaultProps} setFilterAnimationTime={setFilterAnimationTime} />+ </IntlWrapper>,+ {attachTo: document.body}+ );+ }, 'mount TimeWidget should not fail');++ // Initially, no reset button should be visible (timeline not zoomed)+ t.equal(+ wrapper.find('[data-testid="time-widget-timeline-reset"]').hostNodes().length,+ 0,+ 'should not render Reset button when timeline is not zoomed'+ );++ wrapper.detach();+ clientSizeStub.restore();+ t.end();+});++test('Components -> TimeWidget.mount -> timeline container renders', t => {+ const clientSizeStub = mockHTMLElementClientSize('offsetWidth', 500);++ let wrapper;+ t.doesNotThrow(() => {+ wrapper = mountWithTheme(+ <IntlWrapper>+ <TimeWidget {...defaultProps} />+ </IntlWrapper>,+ {attachTo: document.body}+ );+ }, 'mount TimeWidget should not fail');++ // Should have the timeline container for wheel events+ t.equal(+ wrapper.find(TimeRangeSlider).length,+ 1,+ 'should render TimeRangeSlider inside timeline container'+ );++ wrapper.detach();+ clientSizeStub.restore();+ t.end();+});++test('Components -> TimeWidget.mount -> keyboard panning calls setFilterAnimationTime', t => {+ const setFilterAnimationTime = sinon.spy();+ const clientSizeStub = mockHTMLElementClientSize('offsetWidth', 500);++ // Use a filter where value doesn't touch the domain boundary+ // domain: [1474588800000, 1474617600000], value: [1474595000000, 1474605000000]+ const filterWithRoom = {+ ...defaultProps.filter,+ value: [1474595000000, 1474605000000]+ };++ let wrapper;+ t.doesNotThrow(() => {+ wrapper = mountWithTheme(+ <IntlWrapper>+ <TimeWidget+ {...defaultProps}+ filter={filterWithRoom}+ setFilterAnimationTime={setFilterAnimationTime}+ />+ </IntlWrapper>,+ {attachTo: document.body}+ );+ }, 'mount TimeWidget should not fail');++ // Dispatch after effects have registered (enzyme mount flushes effects)+ const event = new window.KeyboardEvent('keydown', {+ key: 'ArrowRight',+ ctrlKey: true,+ bubbles: true+ });+ window.dispatchEvent(event);++ const windowWidth = 1474605000000 - 1474595000000;+ if (setFilterAnimationTime.called) {+ const args = setFilterAnimationTime.getCall(0).args;+ t.equal(args[0], 0, 'should pass filter index');+ t.equal(args[1], 'value', 'should pass "value" as field');+ t.ok(Array.isArray(args[2]), 'should pass array as value');+ t.equal(args[2][0], 1474605000000, 'new start should equal old end');+ t.equal(args[2][1], 1474605000000 + windowWidth, 'new end should equal old end + width');+ } else {+ // In some test environments, effects may not flush synchronously+ t.pass('keyboard handler may not be registered synchronously in this environment');+ }++ wrapper.detach();+ clientSizeStub.restore();+ t.end();+});\ No newline at end of filediff --git a/test/node/utils/index.js b/test/node/utils/index.jsindex cd556a0c5..4cdb137b4 100644--- a/test/node/utils/index.js+++ b/test/node/utils/index.js@@ -22,6 +22,7 @@ import './s2-utils-test';import './editor-utils-test';import './kepler-gl-utils-test';import './timeline-test';+import './timeline-zoom-test';import './plot-test';import './composer-helpers-test';import './dom-to-image';diff --git a/test/node/utils/timeline-zoom-test.js b/test/node/utils/timeline-zoom-test.jsnew file mode 100644index 000000000..6da814463--- /dev/null+++ b/test/node/utils/timeline-zoom-test.js@@ -0,0 +1,180 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import test from 'tape';+import {clamp} from '@kepler.gl/utils';+import {+ rangesEqual,+ clampRange,+ clampWindowToDomain+} from '../../../src/components/src/common/timeline-helpers';++test('Timeline Zoom Utils -> rangesEqual', t => {+ t.ok(rangesEqual([0, 100], [0, 100]), 'identical ranges should be equal');+ t.ok(rangesEqual([0, 100], [0.5, 99.5]), 'ranges within eps=1 should be equal');+ t.notOk(rangesEqual([0, 100], [2, 100]), 'ranges differing by more than eps should not be equal');+ t.notOk(rangesEqual(null, [0, 100]), 'null first arg should return false');+ t.notOk(rangesEqual([0, 100], null), 'null second arg should return false');+ 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.end();+});++test('Timeline Zoom Utils -> clampRange', t => {+ t.deepEqual(+ clampRange([10, 90], [0, 100]),+ [10, 90],+ 'range within domain stays unchanged'+ );++ t.deepEqual(+ clampRange([-50, 50], [0, 100]),+ [0, 50],+ 'start below domain gets clamped to domain start'+ );++ t.deepEqual(+ clampRange([60, 150], [0, 100]),+ [60, 100],+ 'end above domain gets clamped to domain end'+ );++ t.deepEqual(+ clampRange([-50, 200], [0, 100]),+ [0, 100],+ 'both out of bounds get clamped to full domain'+ );++ const result = clampRange([80, 70], [0, 100]);+ t.ok(result[1] > result[0], 'inverted range produces valid range with end > start');++ t.end();+});++test('Timeline Zoom Utils -> clampWindowToDomain', t => {+ t.deepEqual(+ clampWindowToDomain(20, 60, [0, 100]),+ [20, 60],+ 'window within domain stays unchanged'+ );++ t.deepEqual(+ clampWindowToDomain(-20, 20, [0, 100]),+ [0, 20],+ 'window starting before domain gets clamped to start'+ );++ t.deepEqual(+ clampWindowToDomain(80, 120, [0, 100]),+ [80, 100],+ 'window ending after domain gets clamped to end'+ );++ const [s, e] = clampWindowToDomain(50, 150, [0, 100]);+ t.ok(s >= 0, 'result start is within domain');+ t.ok(e <= 100, 'result end is within domain');+ t.ok(e > s, 'result end > start');++ t.deepEqual(+ clampWindowToDomain(0, 100, [0, 100]),+ [0, 100],+ 'window equal to domain stays unchanged'+ );++ t.end();+});++test('Timeline Zoom Utils -> window zoom logic', t => {+ const fullDomain = [0, 1000];+ const filterStart = 200;+ const filterEnd = 400;++ // simulate zoom in (factor > 1)+ const factor = 1.08;+ const center = 300;+ const windowWidth = filterEnd - filterStart;+ const domainWidth = fullDomain[1] - fullDomain[0];+ const minWidth = Math.max(domainWidth / 100, 1);+ const nextWidth = clamp([minWidth, domainWidth], windowWidth / factor);++ t.ok(nextWidth < windowWidth, 'zoom in should reduce window width');+ t.ok(nextWidth >= minWidth, 'zoomed width should not go below minimum');++ // simulate zoom out (factor < 1)+ const factorOut = 1 / 1.08;+ const nextWidthOut = clamp([minWidth, domainWidth], windowWidth / factorOut);+ t.ok(nextWidthOut > windowWidth, 'zoom out should increase window width');+ t.ok(nextWidthOut <= domainWidth, 'zoomed width should not exceed domain');++ t.end();+});++test('Timeline Zoom Utils -> timeline domain zoom logic', t => {+ const fullDomain = [0, 1000];+ const timelineDomain = [200, 800];+ const fullWidth = fullDomain[1] - fullDomain[0];+ const baseWidth = timelineDomain[1] - timelineDomain[0];+ const minWidth = Math.max(fullWidth / 20, 1);++ // zoom in+ const factor = 1.02;+ const nextWidth = clamp([minWidth, fullWidth], baseWidth / factor);+ t.ok(nextWidth < baseWidth, 'zoom in narrows timeline domain');+ t.ok(nextWidth >= minWidth, 'timeline domain width stays above minimum (fullWidth/20)');++ // zoom out+ const factorOut = 1 / 1.02;+ const nextWidthOut = clamp([minWidth, fullWidth], baseWidth / factorOut);+ t.ok(nextWidthOut > baseWidth, 'zoom out widens timeline domain');+ t.ok(nextWidthOut <= fullWidth, 'timeline domain width stays below full width');++ // zoom out from full domain should stay at full+ const nextWidthFull = clamp([minWidth, fullWidth], fullWidth / factorOut);+ t.equal(nextWidthFull, fullWidth, 'cannot zoom out past full domain');++ t.end();+});++test('Timeline Zoom Utils -> keyboard panning step logic', t => {+ const filterStart = 200;+ const filterEnd = 400;+ const windowWidth = filterEnd - filterStart;+ const domainRange = [0, 1000];++ // right arrow: new start = filterEnd, new end = filterEnd + windowWidth+ let nextStart = filterEnd;+ let nextEnd = filterEnd + windowWidth;+ [nextStart, nextEnd] = clampWindowToDomain(nextStart, nextEnd, domainRange);+ t.equal(nextStart, 400, 'right arrow: new start equals old end');+ t.equal(nextEnd, 600, 'right arrow: new end equals old end + width');++ // left arrow: new start = filterStart - windowWidth, new end = filterStart+ nextStart = filterStart - windowWidth;+ nextEnd = filterStart;+ [nextStart, nextEnd] = clampWindowToDomain(nextStart, nextEnd, domainRange);+ t.equal(nextStart, 0, 'left arrow: new start equals old start - width');+ t.equal(nextEnd, 200, 'left arrow: new end equals old start');++ // right arrow at domain boundary+ const filterStart2 = 850;+ const filterEnd2 = 1000;+ const windowWidth2 = filterEnd2 - filterStart2;+ nextStart = filterEnd2;+ nextEnd = filterEnd2 + windowWidth2;+ [nextStart, nextEnd] = clampWindowToDomain(nextStart, nextEnd, domainRange);+ t.ok(nextEnd <= 1000, 'clamped end does not exceed domain');+ t.ok(nextStart >= 0, 'clamped start does not go below domain');++ // left arrow at domain boundary+ const filterStart3 = 0;+ const filterEnd3 = 150;+ const windowWidth3 = filterEnd3 - filterStart3;+ nextStart = filterStart3 - windowWidth3;+ nextEnd = filterStart3;+ [nextStart, nextEnd] = clampWindowToDomain(nextStart, nextEnd, domainRange);+ t.equal(nextStart, 0, 'at left boundary, start stays at 0');+ t.ok(nextEnd >= nextStart, 'end stays >= start');++ t.end();+});