Skip to content

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

fix: Light & Shadow day slider max update depth crash (#3679)

Igor Dykhta4c8c8f7a3c91
diff --git a/src/components/src/effects/effect-configurator.tsx b/src/components/src/effects/effect-configurator.tsx
index 6e02e92c3..53b6db9b4 100644
--- a/src/components/src/effects/effect-configurator.tsx
+++ b/src/components/src/effects/effect-configurator.tsx
@@ -255,7 +255,7 @@ export default function EffectConfiguratorFactory(
parameters => {
updateEffectConfig(null, id, {
parameters: {
- ...(parameters.timestamp ? {timestamp: parameters.timestamp} : null),
+ ...(parameters.timestamp != null ? {timestamp: parameters.timestamp} : null),
...(parameters.timezone ? {timezone: parameters.timezone} : null),
...(parameters.timeMode ? {timeMode: parameters.timeMode} : null)
}
diff --git a/src/components/src/effects/effect-manager.tsx b/src/components/src/effects/effect-manager.tsx
index a476e3669..43331b098 100644
--- a/src/components/src/effects/effect-manager.tsx
+++ b/src/components/src/effects/effect-manager.tsx
@@ -1,7 +1,8 @@
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
-import React, {useMemo, useState, useCallback} from 'react';
+import React, {useMemo, useState, useCallback, useContext} from 'react';
+import {useDispatch, useSelector} from 'react-redux';
import styled from 'styled-components';
import {injectIntl, IntlShape} from 'react-intl';
@@ -18,11 +19,10 @@ import {
DISTANCE_FOG_TYPE,
SURFACE_FOG_TYPE
} from '@kepler.gl/constants';
-import {visStateLens} from '@kepler.gl/reducers';
import {Effect} from '@kepler.gl/types';
import {VisState} from '@kepler.gl/schemas';
-import {withState} from '../injector';
+import KeplerGlContext from '../context';
import SidePanelTitleFactory from './side-panel-title';
import EffectListFactory from './effect-list';
import EffectTypeSelectorFactory, {EffectTypeSelectorProps} from './effect-type-selector';
@@ -39,7 +39,7 @@ export type EffectManagerState = {
effectOrder: string[];
children: React.ReactNode;
};
-export type EffectManagerProps = EffectManagerWithIntlProp & EffectManagerState;
+export type EffectManagerProps = EffectManagerWithIntlProp & Partial<EffectManagerState>;
export type EffectManagerWithIntlProp = {intl: IntlShape};
@@ -92,9 +92,25 @@ function EffectManagerFactory(
SidePanelTitle: ReturnType<typeof SidePanelTitleFactory>,
EffectTypeSelector: ReturnType<typeof EffectTypeSelectorFactory>
): React.FC<EffectManagerProps> {
- const EffectManager = (props: EffectManagerWithIntlProp & EffectManagerState) => {
- const {intl, visStateActions, visState, children} = props;
- const {effects, effectOrder} = visState;
+ const EffectManager = (props: EffectManagerWithIntlProp & Partial<EffectManagerState>) => {
+ const {intl, children} = props;
+ const dispatch = useDispatch();
+ const {selector} = useContext(KeplerGlContext);
+ const visStateFromStore = useSelector(state => selector(state)?.visState);
+ const visState = props.visState ?? visStateFromStore;
+ const visStateActions = useMemo(
+ () =>
+ props.visStateActions ?? {
+ addEffect: payload => dispatch(addEffect(payload)),
+ updateEffect: (id, next) => dispatch(updateEffect(id, next)),
+ removeEffect: id => dispatch(removeEffect(id)),
+ reorderEffect: order => dispatch(reorderEffect(order))
+ },
+ [dispatch, props.visStateActions]
+ );
+
+ const effects = visState?.effects ?? [];
+ const effectOrder = visState?.effectOrder ?? [];
const {addEffect: visStateAddEffect} = visStateActions;
const [typeSelectorOpened, setTypeSelectorOpened] = useState(false);
@@ -168,9 +184,7 @@ function EffectManagerFactory(
);
};
- return withState([visStateLens], state => state, {
- visStateActions: {addEffect, updateEffect, removeEffect, reorderEffect}
- })(injectIntl(EffectManager)) as React.FC<EffectManagerProps>;
+ return injectIntl(EffectManager) as React.FC<EffectManagerProps>;
}
export default EffectManagerFactory;
diff --git a/src/components/src/effects/effect-time-configurator.tsx b/src/components/src/effects/effect-time-configurator.tsx
index ac0b98ce0..dd0be7be0 100644
--- a/src/components/src/effects/effect-time-configurator.tsx
+++ b/src/components/src/effects/effect-time-configurator.tsx
@@ -1,13 +1,13 @@
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
-import React, {useCallback, useMemo} from 'react';
+import React, {useCallback, useContext, useEffect, useMemo, useRef, useState} from 'react';
+import {useSelector} from 'react-redux';
import {injectIntl, IntlShape} from 'react-intl';
import styled from 'styled-components';
import moment from 'moment-timezone';
import SunCalc from 'suncalc';
-import {MapState} from '@kepler.gl/types';
import {FormattedMessage} from '@kepler.gl/localization';
import {clamp} from '@kepler.gl/utils';
import {
@@ -15,9 +15,8 @@ import {
LightAndShadowEffectTimeMode,
DEFAULT_TIMEZONE
} from '@kepler.gl/constants';
-import {mapStateLens} from '@kepler.gl/reducers';
-import {withState} from '../injector';
+import KeplerGlContext from '../context';
import {StyledDatePicker as DatePicker, Tooltip} from '../common/styled-components';
import Checkbox from '../common/checkbox';
import Button from '../common/data-table/button';
@@ -174,6 +173,26 @@ const getDayRatio = (date: moment.Moment) => {
return ((date.hours() * 60 + date.minutes()) * 60 * 1000) / DAY_MILISECONDS;
};
+/**
+ * Normalize TimePicker output (HH:mm, h:mm a, or Date) to HH:mm.
+ * react-time-picker with format "hh:mm a" can echo a 12-hour string when its
+ * controlled value is rewritten, which would otherwise parse as a different UTC time.
+ */
+const normalizeTimeInput = (newTime: unknown): string | null => {
+ if (newTime instanceof Date && Number.isFinite(newTime.getTime())) {
+ return moment(newTime).format('HH:mm');
+ }
+ if (typeof newTime !== 'string' || !newTime) {
+ return null;
+ }
+ const trimmed = newTime.trim();
+ if (/^\d{2}:\d{2}/.test(trimmed)) {
+ return trimmed.slice(0, 5);
+ }
+ const parsed = moment(trimmed, ['HH:mm', 'H:mm', 'hh:mm A', 'h:mm A', 'hh:mm a', 'h:mm a'], true);
+ return parsed.isValid() ? parsed.format('HH:mm') : null;
+};
+
EffectTimeConfiguratorFactory.deps = [
TimezoneSelectorFactory,
EffectTimeSliderFactory,
@@ -190,39 +209,62 @@ export default function EffectTimeConfiguratorFactory(
timezone: _timezone,
timeMode,
onChange: onTimeParametersChanged,
- mapState,
intl
- }: EffectTimeConfiguratorProps & {intl: IntlShape; mapState: MapState}) => {
+ }: EffectTimeConfiguratorProps & {intl: IntlShape}) => {
+ // Subscribe only to lat/lon. Connecting this panel to the full store (via
+ // withState) re-rendered it on every effect timestamp tick while dragging
+ // the day-time slider, and react-redux nested connect layout effects then
+ // hit "Maximum update depth exceeded".
+ const {selector} = useContext(KeplerGlContext);
+ const latitude = useSelector(state => selector(state)?.mapState?.latitude ?? 0);
+ const longitude = useSelector(state => selector(state)?.mapState?.longitude ?? 0);
+
const timezone = useMemo(() => {
return moment.tz.names().includes(_timezone) ? _timezone : DEFAULT_TIMEZONE;
}, [_timezone]);
- const [datePickerDate, fullDate, formattedTime, formattedDate, dayTimeProgress] =
- useMemo(() => {
- // Guard against an invalid stored timestamp so we never build an
- // "Invalid Date" for the date picker (react-date-picker throws on it).
- const safeTimestamp = Number.isFinite(timestamp) ? timestamp : Date.now();
- const currentMoment = moment.tz(safeTimestamp, timezone);
-
- // Slider value from 0 to 1
- const dayProgress = getDayRatio(currentMoment);
-
- // Date picker always renders Date in local timezone
- const date = new Date();
- date.setFullYear(currentMoment.year(), currentMoment.month(), currentMoment.date());
- date.setHours(0, 0, 0, 0);
-
- return [
- date,
- currentMoment.toDate(),
- currentMoment.format('HH:mm'),
- currentMoment.format('YYYY-MM-DD'),
- dayProgress
- ];
- }, [timestamp, timezone]);
+ const {fullDate, formattedTime, formattedDate, dayTimeProgress} = useMemo(() => {
+ // Guard against an invalid stored timestamp so we never build an
+ // "Invalid Date" for the date picker (react-date-picker throws on it).
+ const safeTimestamp = Number.isFinite(timestamp) ? timestamp : Date.now();
+ const currentMoment = moment.tz(safeTimestamp, timezone);
+
+ return {
+ fullDate: currentMoment.toDate(),
+ formattedTime: currentMoment.format('HH:mm'),
+ formattedDate: currentMoment.format('YYYY-MM-DD'),
+ dayTimeProgress: getDayRatio(currentMoment)
+ };
+ }, [timestamp, timezone]);
+
+ // Only allocate a new Date when the calendar day changes. A new object on
+ // every timestamp tick makes react-date-picker fire onChange while dragging.
+ const datePickerDate = useMemo(() => {
+ const [year, month, day] = formattedDate.split('-').map(Number);
+ return new Date(year, month - 1, day);
+ }, [formattedDate]);
+
+ // Keep the slider on the pointer while dragging so Redux minute-quantization
+ // cannot snap it (and so date/time widgets cannot echo onChange mid-gesture).
+ const [sliderDragProgress, setSliderDragProgress] = useState<number | null>(null);
+ const isSliderDraggingRef = useRef(false);
+
+ const endSliderDrag = useCallback(() => {
+ isSliderDraggingRef.current = false;
+ setSliderDragProgress(null);
+ }, []);
+
+ useEffect(() => {
+ document.addEventListener('mouseup', endSliderDrag);
+ document.addEventListener('touchend', endSliderDrag);
+ return () => {
+ document.removeEventListener('mouseup', endSliderDrag);
+ document.removeEventListener('touchend', endSliderDrag);
+ };
+ }, [endSliderDrag]);
const timeSliderConfig = useMemo(() => {
- const times = SunCalc.getTimes(fullDate, mapState.latitude, mapState.longitude);
+ const times = SunCalc.getTimes(fullDate, latitude, longitude);
const {dawn, sunrise, sunset, dusk} = times;
return {
@@ -233,41 +275,60 @@ export default function EffectTimeConfiguratorFactory(
sunriseTime: moment.tz(sunrise.valueOf(), timezone).format('hh:mm A'),
sunsetTime: moment.tz(sunset.valueOf(), timezone).format('hh:mm A')
};
- }, [fullDate, timezone, mapState.latitude, mapState.longitude]);
+ }, [fullDate, timezone, latitude, longitude]);
+
+ // Date/time widgets (and the slider itself) can echo onChange when their
+ // controlled value is rewritten from the store. Skip no-op timestamp
+ // updates so those echoes cannot dispatch in a loop.
+ const timestampRef = useRef(timestamp);
+ timestampRef.current = timestamp;
+
+ const commitTimestamp = useCallback(
+ (newTimestamp: number | null | undefined) => {
+ if (newTimestamp == null || newTimestamp === timestampRef.current) return;
+ onTimeParametersChanged({timestamp: newTimestamp});
+ },
+ [onTimeParametersChanged]
+ );
const onTimeSliderChange = useCallback(
value => {
- const hours = clamp([0, 23], Math.floor(value[1] * 24));
- const minutes = clamp([0, 59], Math.floor((value[1] * 24 - hours) * 60));
+ isSliderDraggingRef.current = true;
+ setSliderDragProgress(value[1]);
+ // Round to the nearest minute. Flooring (value * 24) then (fraction * 60)
+ // can drop a minute to floating point (e.g. 16:46 → 16:45) and dispatch
+ // a false change when the handle is already on the current time.
+ const totalMinutes = clamp([0, 24 * 60 - 1], Math.round(value[1] * 24 * 60));
+ const hours = Math.floor(totalMinutes / 60);
+ const minutes = totalMinutes % 60;
const newFormattedTime = `${hours < 10 ? `0${hours}` : hours}:${
minutes < 10 ? `0${minutes}` : minutes
}`;
- const newTimestamp = getTimestamp(formattedDate, newFormattedTime, timezone);
- onTimeParametersChanged({timestamp: newTimestamp});
+ commitTimestamp(getTimestamp(formattedDate, newFormattedTime, timezone));
},
- [formattedDate, timezone, onTimeParametersChanged]
+ [formattedDate, timezone, commitTimestamp]
);
const setDate = useCallback(
newDate => {
- if (!newDate) return;
+ if (isSliderDraggingRef.current || !newDate) return;
const newFormattedDate = moment(newDate).format('YYYY-MM-DD');
- const newTimestamp = getTimestamp(newFormattedDate, formattedTime, timezone);
- onTimeParametersChanged({timestamp: newTimestamp});
+ commitTimestamp(getTimestamp(newFormattedDate, formattedTime, timezone));
},
- [formattedTime, timezone, onTimeParametersChanged]
+ [formattedTime, timezone, commitTimestamp]
);
const setTime = useCallback(
newTime => {
- if (!newTime) return;
+ if (isSliderDraggingRef.current || !newTime) return;
- const newTimestamp = getTimestamp(formattedDate, newTime, timezone);
- onTimeParametersChanged({timestamp: newTimestamp});
+ const timeStr = normalizeTimeInput(newTime);
+ if (!timeStr) return;
+ commitTimestamp(getTimestamp(formattedDate, timeStr, timezone));
},
- [formattedDate, timezone, onTimeParametersChanged]
+ [formattedDate, timezone, commitTimestamp]
);
const setTimezone = useCallback(
@@ -309,7 +370,7 @@ export default function EffectTimeConfiguratorFactory(
<SliderWrapper hidden={disableDateTimePick}>
<EffectTimeSlider
- value={dayTimeProgress}
+ value={sliderDragProgress ?? dayTimeProgress}
onChange={onTimeSliderChange}
config={timeSliderConfig}
/>
@@ -397,6 +458,5 @@ export default function EffectTimeConfiguratorFactory(
);
};
- // @ts-expect-error how to properly type?
- return withState([mapStateLens])(injectIntl(EffectTimeConfigurator));
+ return injectIntl(EffectTimeConfigurator);
}
diff --git a/src/reducers/src/vis-state-updaters.ts b/src/reducers/src/vis-state-updaters.ts
index b165dd4da..31531714a 100644
--- a/src/reducers/src/vis-state-updaters.ts
+++ b/src/reducers/src/vis-state-updaters.ts
@@ -2377,6 +2377,22 @@ export const updateEffectUpdater = (
);
}
+ const effect = state.effects[idx];
+ const nextParams = props.parameters;
+ // A timestamp-only no-op still used to allocate a new visState (setProps
+ // mutates in place). That retriggered nested react-redux connect subscribers
+ // while dragging the Light & Shadow day-time slider until React threw
+ // "Maximum update depth exceeded".
+ if (
+ nextParams &&
+ Object.keys(props).length === 1 &&
+ Object.keys(nextParams).length === 1 &&
+ nextParams.timestamp != null &&
+ nextParams.timestamp === effect.parameters.timestamp
+ ) {
+ return state;
+ }
+
const newEffects = [...state.effects];
newEffects[idx].setProps(props);
@@ -3735,7 +3751,9 @@ export function updateDatasetUpdater(
if (fieldIdx === -1) {
// column is gone: drop a single-dataset filter, splice it out of a synced one
- return filter.dataId.length === 1 ? null : _removeFilterDataIdAtValueIndex(filter, vi, newDatasets);
+ return filter.dataId.length === 1
+ ? null
+ : _removeFilterDataIdAtValueIndex(filter, vi, newDatasets);
}
// column present (possibly renamed): re-resolve name/fieldIdx/domain
@@ -3752,8 +3770,8 @@ export function updateDatasetUpdater(
(renames[updated.yAxis.name]
? {...updated.yAxis, name: renames[updated.yAxis.name]}
: newFieldsByName.has(updated.yAxis.name)
- ? updated.yAxis
- : null);
+ ? updated.yAxis
+ : null);
return {
...updated,
diff --git a/test/browser/components/effects/effect-time-configurator-test.js b/test/browser/components/effects/effect-time-configurator-test.js
index 7a6261aaa..54f59a1d5 100644
--- a/test/browser/components/effects/effect-time-configurator-test.js
+++ b/test/browser/components/effects/effect-time-configurator-test.js
@@ -308,3 +308,86 @@ test('Components -> EffectTimeConfigurator -> date with custom timezone update',
t.end();
});
+
+test('Components -> EffectTimeConfigurator -> day time slider does not echo same timestamp', t => {
+ const store = mockStore(ititialState);
+ const onDateTimeChange = sinon.spy();
+ // Already quantized to HH:mm:00 so a same-minute slider echo is a true no-op.
+ const quantizedTimestamp = Date.UTC(2023, 6, 25, 16, 46, 0, 0);
+ const props = {
+ timestamp: quantizedTimestamp,
+ timezone: 'UTC',
+ timeMode: LIGHT_AND_SHADOW_EFFECT_TIME_MODES.pick,
+ onChange: onDateTimeChange
+ };
+
+ let wrapper;
+ t.doesNotThrow(() => {
+ wrapper = mountWithTheme(
+ <IntlWrapper>
+ <Provider store={store}>
+ <EffectTimeConfigurator {...props} />
+ </Provider>
+ </IntlWrapper>
+ );
+ }, `EffectTimeConfigurator should not fail`);
+
+ const sliderOnChange = wrapper.find('RangeSlider').at(0).props().onChange;
+ sliderOnChange([0, (16 * 60 + 46) / (24 * 60)]);
+ t.equal(
+ onDateTimeChange.callCount,
+ 0,
+ 'slider should not dispatch when quantized time matches the current timestamp'
+ );
+
+ sliderOnChange([0, (17 * 60 + 0) / (24 * 60)]);
+ t.equal(onDateTimeChange.callCount, 1, 'slider should dispatch when the minute actually changes');
+ t.ok(onDateTimeChange.lastCall.args[0].timestamp, 'updated timestamp should be set');
+
+ wrapper.unmount();
+ t.end();
+});
+
+test('Components -> EffectTimeConfigurator -> slider drag ignores time picker echo', t => {
+ const store = mockStore(ititialState);
+ const onDateTimeChange = sinon.spy();
+ const quantizedTimestamp = Date.UTC(2023, 6, 25, 16, 46, 0, 0);
+ const props = {
+ timestamp: quantizedTimestamp,
+ timezone: 'UTC',
+ timeMode: LIGHT_AND_SHADOW_EFFECT_TIME_MODES.pick,
+ onChange: onDateTimeChange
+ };
+
+ let wrapper;
+ t.doesNotThrow(() => {
+ wrapper = mountWithTheme(
+ <IntlWrapper>
+ <Provider store={store}>
+ <EffectTimeConfigurator {...props} />
+ </Provider>
+ </IntlWrapper>
+ );
+ }, `EffectTimeConfigurator should not fail`);
+
+ const sliderOnChange = wrapper.find('RangeSlider').at(0).props().onChange;
+ sliderOnChange([0, (17 * 60 + 0) / (24 * 60)]);
+ t.equal(onDateTimeChange.callCount, 1, 'slider should dispatch once');
+
+ // TimePicker can echo a 12-hour string when its controlled value is rewritten
+ // from the store. That echo must not dispatch while the pointer is down.
+ wrapper.update();
+ const timePickerOnChange = wrapper.find('TimePicker').at(0).props().onChange;
+ timePickerOnChange('04:00');
+ t.equal(onDateTimeChange.callCount, 1, 'time picker echo during slider drag should be ignored');
+
+ // jsdom's dispatchEvent rejects Node's Event; use the window constructor.
+ const MouseUpEvent = window.MouseEvent || window.Event;
+ document.dispatchEvent(new MouseUpEvent('mouseup'));
+ wrapper.update();
+ timePickerOnChange('18:00');
+ t.equal(onDateTimeChange.callCount, 2, 'time picker should work after drag ends');
+
+ wrapper.unmount();
+ t.end();
+});
diff --git a/test/node/reducers/vis-state-test.js b/test/node/reducers/vis-state-test.js
index 58e7e0ccf..0ac57c25d 100644
--- a/test/node/reducers/vis-state-test.js
+++ b/test/node/reducers/vis-state-test.js
@@ -7590,6 +7590,39 @@ test('#VisStateUpdater -> updateEffect', t => {
t.end();
});
+test('#VisStateUpdater -> updateEffect: skip no-op timestamp', t => {
+ const initialState = InitialState.visState;
+ let nextState = reducer(
+ initialState,
+ VisStateActions.addEffect({id: 'e_shadow', type: LIGHT_AND_SHADOW_EFFECT.type})
+ );
+ const shadow = nextState.effects.find(e => e.id === 'e_shadow');
+ const timestamp = shadow.parameters.timestamp;
+
+ const afterSameTimestamp = reducer(
+ nextState,
+ VisStateActions.updateEffect('e_shadow', {parameters: {timestamp}})
+ );
+ t.equal(
+ afterSameTimestamp,
+ nextState,
+ 'timestamp-only no-op should return the same visState reference'
+ );
+
+ const afterNewTimestamp = reducer(
+ nextState,
+ VisStateActions.updateEffect('e_shadow', {parameters: {timestamp: timestamp + 60000}})
+ );
+ t.notEqual(afterNewTimestamp, nextState, 'a new timestamp should still produce a new visState');
+ t.equal(
+ afterNewTimestamp.effects.find(e => e.id === 'e_shadow').parameters.timestamp,
+ timestamp + 60000,
+ 'timestamp should update when the value actually changes'
+ );
+
+ t.end();
+});
+
test('#VisStateUpdater -> addEffect: invalid effect parameters', t => {
const initialState = InitialState.visState;