Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
feat: timezone selector for time filter settings (#3743)
Igor Dykhta524add9e8fba
diff --git a/src/components/src/bottom-widget.tsx b/src/components/src/bottom-widget.tsxindex bf50e933c..3fe57e234 100644--- a/src/components/src/bottom-widget.tsx+++ b/src/components/src/bottom-widget.tsx@@ -212,6 +212,7 @@ export default function BottomWidgetFactory(showTimeDisplay={showFloatingTimeDisplay}setFilterPlot={visStateActions.setFilterPlot}setFilterAnimationTime={setTimelineValue}+ setFilterAnimationTimeConfig={visStateActions.setFilterAnimationTimeConfig}setFilterAnimationWindow={visStateActions.setFilterAnimationWindow}setFilterSyncTimelineMode={visStateActions.setTimeFilterSyncTimelineMode}toggleAnimation={visStateActions.toggleFilterAnimation}diff --git a/src/components/src/filters/index.ts b/src/components/src/filters/index.tsindex c07bf1948..3fcffa90b 100644--- a/src/components/src/filters/index.ts+++ b/src/components/src/filters/index.ts@@ -9,3 +9,4 @@ export {default as PolygonFilter} from './polygon-filter';export {default as TimeWidget} from './time-widget';export {default as TimeWidgetTop} from './time-widget-top';export {default as TimeWidgetSettings} from './time-widget-settings';+export {default as TimezoneSelector} from './timezone-selector';diff --git a/src/components/src/filters/time-widget-settings.tsx b/src/components/src/filters/time-widget-settings.tsxindex 23eb5a1d5..3bf6e4be9 100644--- a/src/components/src/filters/time-widget-settings.tsx+++ b/src/components/src/filters/time-widget-settings.tsx@@ -22,6 +22,9 @@ import {import {TimeRangeFilter, Field} from '@kepler.gl/types';import {Datasets} from '@kepler.gl/table';import {getDefaultTimeFormat} from '@kepler.gl/utils';+import {FormattedMessage} from '@kepler.gl/localization';++import TimezoneSelector from './timezone-selector';const MAX_BINS = 2048;@@ -62,6 +65,7 @@ const AxisHeader = styled.div`const AxisRow = styled.div`display: flex;align-items: flex-end;+ flex-wrap: wrap;gap: 25px;`;@@ -189,6 +193,7 @@ export type TimeWidgetSettingsProps = {filter: TimeRangeFilter;datasets: Datasets;setFilterPlot: (newProp: any, valueIndex?: number) => void;+ onTimezoneChange: (timezone: string) => void;};function parseInterval(intervalId: string | undefined): {step: number; unit: string} {@@ -206,7 +211,8 @@ function TimeWidgetSettingsFactory(FieldSelector: ReturnType<typeof FieldSelectoconst TimeWidgetSettings: React.FC<TimeWidgetSettingsProps> = ({filter,datasets,- setFilterPlot+ setFilterPlot,+ onTimezoneChange}) => {const {plotType} = filter;const currentInterval = plotType?.interval;@@ -376,6 +382,12 @@ function TimeWidgetSettingsFactory(FieldSelector: ReturnType<typeof FieldSelecto</UnitSelectorWrapper></IntervalGroup></FieldBlock>+ <FieldBlock>+ <FieldLabel>+ <FormattedMessage id="filterManager.timezone" />+ </FieldLabel>+ <TimezoneSelector timezone={filter.timezone} onChange={onTimezoneChange} />+ </FieldBlock></AxisRow>{intervalTooSmall ? <ErrorMessage>Interval is too small</ErrorMessage> : null}</AxisSection>diff --git a/src/components/src/filters/time-widget.tsx b/src/components/src/filters/time-widget.tsxindex ba0d41a0b..e2e55c005 100644--- a/src/components/src/filters/time-widget.tsx+++ b/src/components/src/filters/time-widget.tsx@@ -83,6 +83,7 @@ function TimeWidgetFactory(toggleAnimation,exportAnimation,setFilterPlot,+ setFilterAnimationTimeConfig,setFilterAnimationWindow,animationConfig,timeline@@ -114,6 +115,11 @@ function TimeWidgetFactory([index, setFilterPlot]);+ const _onTimezoneChange = useCallback(+ (timezone: string) => setFilterAnimationTimeConfig(index, {timezone}),+ [index, setFilterAnimationTimeConfig]+ );+const _onToggleSettings = useCallback(() => {setShowSettings(prev => !prev);}, []);@@ -382,7 +388,12 @@ function TimeWidgetFactory(isMinified={isMinified}/>{showSettings && !isMinified ? (- <TimeWidgetSettings filter={filter} datasets={datasets} setFilterPlot={_setFilterPlot} />+ <TimeWidgetSettings+ filter={filter}+ datasets={datasets}+ setFilterPlot={_setFilterPlot}+ onTimezoneChange={_onTimezoneChange}+ />) : null}<TimelineSection>{timelineZoomed && timelineRangeLabel ? (diff --git a/src/components/src/filters/timezone-selector.spec.tsx b/src/components/src/filters/timezone-selector.spec.tsxnew file mode 100644index 000000000..8cf49d590--- /dev/null+++ b/src/components/src/filters/timezone-selector.spec.tsx@@ -0,0 +1,32 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import React from 'react';+import {screen} from '@testing-library/react';++import {DEFAULT_TIMEZONE} from '@kepler.gl/constants';++import {renderWithTheme} from 'test/helpers/component-jest-utils';+import TimezoneSelector, {getTimezoneOptions, getTimezonesFromMoment} from './timezone-selector';++describe('TimezoneSelector', () => {+ test('lists IANA zones with UTC first', () => {+ const timezones = getTimezonesFromMoment();+ expect(timezones[DEFAULT_TIMEZONE]).toBe(0);+ expect(timezones['America/New_York']).toEqual(expect.any(Number));++ const options = getTimezoneOptions(timezones);+ expect(options[0]).toEqual({name: DEFAULT_TIMEZONE, label: 'UTC (Default)'});+ expect(options.find(option => option.name === 'America/Los_Angeles')?.label).toMatch(+ /America\/Los_Angeles \(UTC -?\d+(\.\d+)? hours\)/+ );+ });++ test('renders the current timezone label', () => {+ const onChange = jest.fn();+ renderWithTheme(<TimezoneSelector timezone="America/New_York" onChange={onChange} />);++ expect(screen.getByTestId('time-widget-timezone')).toBeInTheDocument();+ expect(screen.getByText(/America\/New_York/)).toBeInTheDocument();+ });+});diff --git a/src/components/src/filters/timezone-selector.tsx b/src/components/src/filters/timezone-selector.tsxnew file mode 100644index 000000000..e47b58437--- /dev/null+++ b/src/components/src/filters/timezone-selector.tsx@@ -0,0 +1,124 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import React, {useCallback, useMemo} from 'react';+import styled from 'styled-components';+import moment from 'moment-timezone';++import {DEFAULT_TIMEZONE} from '@kepler.gl/constants';++import ItemSelector from '../common/item-selector/item-selector';++export type TimezoneOption = {+ name: string;+ label: string;+};++const UTC_DEFAULT_LABEL = 'UTC (Default)';++/**+ * Unique IANA zones keyed by current UTC offset in minutes (from UTC).+ * `zonesForCountry` returns minutes *to* UTC, so the sign is inverted.+ */+export function getTimezonesFromMoment(): Record<string, number> {+ return moment.tz.countries().reduce<Record<string, number>>(+ (accu, country) => {+ moment.tz.zonesForCountry(country, true).forEach(zone => {+ accu[zone.name] = -zone.offset;+ });+ return accu;+ },+ {[DEFAULT_TIMEZONE]: 0}+ );+}++export function getTimezoneOptions(timezones: Record<string, number>): TimezoneOption[] {+ return Object.entries(timezones)+ .map(([name, offsetMinutes]) => {+ const hours = offsetMinutes / 60;+ const sign = hours > 0 ? '+' : '';+ const label =+ name === DEFAULT_TIMEZONE+ ? UTC_DEFAULT_LABEL+ : hours === 0+ ? name+ : `${name} (UTC ${sign}${hours} hours)`;+ return {name, label};+ })+ .sort((a, b) => {+ if (a.name === DEFAULT_TIMEZONE) return -1;+ if (b.name === DEFAULT_TIMEZONE) return 1;+ return a.label.localeCompare(b.label);+ });+}++const TIMEZONE_OFFSETS = getTimezonesFromMoment();+const TIMEZONE_OPTIONS = getTimezoneOptions(TIMEZONE_OFFSETS);++const StyledFieldSelector = styled.div`+ width: 220px;++ .item-selector__dropdown {+ background: ${props => props.theme.secondaryInputBgd};+ border-color: ${props => props.theme.secondaryInputBorderColor};+ height: 28px;+ padding: 2px 8px;+ font-size: 11px;+ }+`;++export type TimezoneSelectorProps = {+ timezone?: string | null;+ onChange: (timezone: string) => void;+};++const TimezoneSelector: React.FC<TimezoneSelectorProps> = ({timezone, onChange}) => {+ const selectedName = timezone || DEFAULT_TIMEZONE;+ const selectedItems = useMemo(() => {+ const match = TIMEZONE_OPTIONS.find(option => option.name === selectedName);+ return match ? [match] : [{name: selectedName, label: selectedName}];+ }, [selectedName]);++ const displayOption = useCallback((option: TimezoneOption | string) => {+ if (typeof option === 'string') {+ return TIMEZONE_OPTIONS.find(item => item.name === option)?.label || option;+ }+ return option?.label || option?.name || '';+ }, []);++ const onSelect = useCallback(+ (value: ReadonlyArray<TimezoneOption> | string | number | boolean | object | null) => {+ const name =+ typeof value === 'string'+ ? value+ : value && typeof value === 'object' && !Array.isArray(value)+ ? (value as TimezoneOption).name+ : undefined;+ if (name) {+ onChange(name);+ }+ },+ [onChange]+ );++ return (+ <StyledFieldSelector className="timezone-field-selector" data-testid="time-widget-timezone">+ <ItemSelector+ size="small"+ selectedItems={selectedItems}+ options={TIMEZONE_OPTIONS}+ multiSelect={false}+ searchable={true}+ closeOnSelect={true}+ placeholder="filterManager.selectTimezone"+ placement="top"+ getOptionValue={(option: TimezoneOption) => option.name}+ displayOption={displayOption}+ filterOption="label"+ onChange={onSelect}+ />+ </StyledFieldSelector>+ );+};++export default TimezoneSelector;diff --git a/src/components/src/filters/types.ts b/src/components/src/filters/types.tsindex e83a4f899..973ce192f 100644--- a/src/components/src/filters/types.ts+++ b/src/components/src/filters/types.ts@@ -15,6 +15,7 @@ import {Layer} from '@kepler.gl/layers';import {ActionHandler,setFilterAnimationTime,+ setFilterAnimationTimeConfig,setFilterAnimationWindow,setTimeFilterSyncTimelineMode,setFilterPlot,@@ -91,6 +92,7 @@ export type TimeWidgetProps = {updateAnimationSpeed: ActionHandler<typeof updateFilterAnimationSpeed>;toggleAnimation: ActionHandler<typeof toggleFilterAnimation>;setFilterPlot: ActionHandler<typeof setFilterPlot>;+ setFilterAnimationTimeConfig: ActionHandler<typeof setFilterAnimationTimeConfig>;setFilterAnimationWindow: ActionHandler<typeof setFilterAnimationWindow>;setFilterSyncTimelineMode: ActionHandler<typeof setTimeFilterSyncTimelineMode>;timeline: Timeline;diff --git a/src/components/src/index.ts b/src/components/src/index.tsindex 39e8e8e07..e9e200873 100644--- a/src/components/src/index.ts+++ b/src/components/src/index.ts@@ -264,6 +264,12 @@ export {} from './filters/time-range-filter';export {default as TimeWidgetFactory} from './filters/time-widget';export {default as TimeWidgetTopFactory} from './filters/time-widget-top';+export {default as TimeWidgetSettingsFactory} from './filters/time-widget-settings';+export {+ default as TimezoneSelector,+ getTimezonesFromMoment,+ getTimezoneOptions+} from './filters/timezone-selector';// // Editor Factoryexport {default as EditorFactory} from './editor/editor';diff --git a/src/localization/src/translations/ca.ts b/src/localization/src/translations/ca.tsindex 1e22e9bbc..c8ac6144a 100644--- a/src/localization/src/translations/ca.ts+++ b/src/localization/src/translations/ca.ts@@ -298,7 +298,9 @@ export default {column: 'Columna',timeIntervalEndField: 'Hora de fi',timeIntervalEndFieldHint:- 'Opcional. Les entitats romanen visibles mentre la finestra de reproducció se superposa a aquest interval.'+ 'Opcional. Les entitats romanen visibles mentre la finestra de reproducció se superposa a aquest interval.',+ timezone: 'Zona horària',+ selectTimezone: 'Selecciona la zona horària de visualització'},datasetTitle: {showDataTable: 'Mostra taula de dades',diff --git a/src/localization/src/translations/cn.ts b/src/localization/src/translations/cn.tsindex 58367acf9..4b0892d27 100644--- a/src/localization/src/translations/cn.ts+++ b/src/localization/src/translations/cn.ts@@ -283,7 +283,9 @@ export default {timeLayerUnsync: '取消与图层时间线联动',column: '列',timeIntervalEndField: '结束时间',- timeIntervalEndFieldHint: '可选。当播放窗口与该时间范围重叠时,要素保持可见。'+ timeIntervalEndFieldHint: '可选。当播放窗口与该时间范围重叠时,要素保持可见。',+ timezone: '时区',+ selectTimezone: '选择显示时区'},datasetTitle: {showDataTable: '显示数据表',diff --git a/src/localization/src/translations/en.ts b/src/localization/src/translations/en.tsindex 529c046c5..1ab9baf84 100644--- a/src/localization/src/translations/en.ts+++ b/src/localization/src/translations/en.ts@@ -382,7 +382,9 @@ export default {column: 'Column',timeIntervalEndField: 'End time',timeIntervalEndFieldHint:- 'Optional. Features stay visible while the playback window overlaps this time span.'+ 'Optional. Features stay visible while the playback window overlaps this time span.',+ timezone: 'Time Zone',+ selectTimezone: 'Select display timezone'},datasetTitle: {showDataTable: 'Show data table',diff --git a/src/localization/src/translations/es.ts b/src/localization/src/translations/es.tsindex dc1f9d1fc..b9f5c6a23 100644--- a/src/localization/src/translations/es.ts+++ b/src/localization/src/translations/es.ts@@ -299,7 +299,9 @@ export default {column: 'Columna',timeIntervalEndField: 'Hora de fin',timeIntervalEndFieldHint:- 'Opcional. Las entidades permanecen visibles mientras la ventana de reproducción se superpone a este intervalo.'+ 'Opcional. Las entidades permanecen visibles mientras la ventana de reproducción se superpone a este intervalo.',+ timezone: 'Zona horaria',+ selectTimezone: 'Seleccionar zona horaria de visualización'},datasetTitle: {showDataTable: 'Mostar la tabla de datos',diff --git a/src/localization/src/translations/fi.ts b/src/localization/src/translations/fi.tsindex d307f7e70..222f7d55f 100644--- a/src/localization/src/translations/fi.ts+++ b/src/localization/src/translations/fi.ts@@ -297,7 +297,9 @@ export default {column: 'Sarake',timeIntervalEndField: 'Päättymisaika',timeIntervalEndFieldHint:- 'Valinnainen. Kohteet pysyvät näkyvissä, kun toistoikkuna osuu tälle aikavälille.'+ 'Valinnainen. Kohteet pysyvät näkyvissä, kun toistoikkuna osuu tälle aikavälille.',+ timezone: 'Aikavyöhyke',+ selectTimezone: 'Valitse näyttöaikavyöhyke'},datasetTitle: {showDataTable: 'Näytä attribuuttitaulu',diff --git a/src/localization/src/translations/ja.ts b/src/localization/src/translations/ja.tsindex 04a11dc63..3dbb90f30 100644--- a/src/localization/src/translations/ja.ts+++ b/src/localization/src/translations/ja.ts@@ -296,7 +296,9 @@ export default {column: '列',timeIntervalEndField: '終了時刻',timeIntervalEndFieldHint:- '任意。再生ウィンドウがこの期間と重なっている間、フィーチャは表示されたままになります。'+ '任意。再生ウィンドウがこの期間と重なっている間、フィーチャは表示されたままになります。',+ timezone: 'タイムゾーン',+ selectTimezone: '表示タイムゾーンを選択'},datasetTitle: {showDataTable: 'データ表を表示',diff --git a/src/localization/src/translations/pt.ts b/src/localization/src/translations/pt.tsindex 5666ac47a..d4bc0a0c5 100644--- a/src/localization/src/translations/pt.ts+++ b/src/localization/src/translations/pt.ts@@ -299,7 +299,9 @@ export default {column: 'Coluna',timeIntervalEndField: 'Hora de término',timeIntervalEndFieldHint:- 'Opcional. As entidades permanecem visíveis enquanto a janela de reprodução se sobrepõe a este intervalo.'+ 'Opcional. As entidades permanecem visíveis enquanto a janela de reprodução se sobrepõe a este intervalo.',+ timezone: 'Fuso horário',+ selectTimezone: 'Selecionar fuso horário de exibição'},datasetTitle: {showDataTable: 'Mostrar tabela de dados',diff --git a/src/localization/src/translations/ru.ts b/src/localization/src/translations/ru.tsindex 84ad5a72e..837b85ed1 100644--- a/src/localization/src/translations/ru.ts+++ b/src/localization/src/translations/ru.ts@@ -298,7 +298,9 @@ export default {column: 'Столбец',timeIntervalEndField: 'Время окончания',timeIntervalEndFieldHint:- 'Необязательно. Объекты остаются видимыми, пока окно воспроизведения пересекается с этим интервалом.'+ 'Необязательно. Объекты остаются видимыми, пока окно воспроизведения пересекается с этим интервалом.',+ timezone: 'Часовой пояс',+ selectTimezone: 'Выберите часовой пояс отображения'},datasetTitle: {showDataTable: 'Показать таблицу данных ',diff --git a/test/browser/components/filters/time-widget-test.js b/test/browser/components/filters/time-widget-test.jsindex 4509145d2..5e3de1b14 100644--- a/test/browser/components/filters/time-widget-test.js+++ b/test/browser/components/filters/time-widget-test.js@@ -25,6 +25,7 @@ import {IconButton,SliderHandle,Typeahead,+ TimezoneSelector,appInjector} from '@kepler.gl/components';@@ -57,6 +58,7 @@ const defaultProps = {onClose: nop,onToggleMinify: nop,setFilterPlot: nop,+ setFilterAnimationTimeConfig: nop,setFilterAnimationWindow: nop,animationConfig: DEFAULT_ANIMATION_CONFIG};@@ -91,6 +93,7 @@ test('Components -> TimeWidget.mount -> with time filter', t => {wrapper.update();t.equal(wrapper.find(FieldSelector).length, 1, 'should render FieldSelector');+ t.equal(wrapper.find(TimezoneSelector).length, 1, 'should render TimezoneSelector');// check yAxisFieldsconst yAxisFields = wrapper.find(FieldSelector).at(0).props().fields;@@ -103,6 +106,58 @@ test('Components -> TimeWidget.mount -> with time filter', t => {t.end();});+test('Components -> TimeWidget.mount -> timezone selector', t => {+ const setFilterAnimationTimeConfig = sinon.spy();+ let wrapper;+ t.doesNotThrow(() => {+ wrapper = mountWithTheme(+ <IntlWrapper>+ <TimeWidget {...defaultProps} setFilterAnimationTimeConfig={setFilterAnimationTimeConfig} />+ </IntlWrapper>+ );+ }, 'TimeWidget should not fail without props');++ wrapper.find(Icons.Gear).at(0).simulate('click');+ wrapper.update();++ t.equal(wrapper.find(TimezoneSelector).length, 1, 'should render TimezoneSelector');+ t.equal(+ wrapper.find('[data-testid="time-widget-timezone"]').hostNodes().length,+ 1,+ 'should render timezone field selector'+ );++ const timezoneSelector = wrapper.find(TimezoneSelector).at(0);+ t.ok(timezoneSelector.props().timezone == null, 'should default timezone to null (UTC display)');++ timezoneSelector.props().onChange('America/Los_Angeles');++ t.deepEqual(+ setFilterAnimationTimeConfig.args[0],+ [0, {timezone: 'America/Los_Angeles'}],+ 'should call setFilterAnimationTimeConfig with selected timezone'+ );++ wrapper.setProps({+ children: (+ <TimeWidget+ {...defaultProps}+ filter={nextState.filters[0]}+ setFilterAnimationTimeConfig={setFilterAnimationTimeConfig}+ />+ )+ });+ wrapper.update();++ t.equal(+ wrapper.find(TimezoneSelector).at(0).props().timezone,+ 'America/New_York',+ 'should show the filter timezone'+ );++ t.end();+});+test('Components -> TimeWidget.mount -> test actions', t => {const onClose = sinon.spy();const toggleAnimation = sinon.spy();