Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
feat(filters): add 12/24-hour time format selector (#3826)
Igor Dykhta5dfe59dbe5d8
diff --git a/src/components/src/filters/time-widget-settings.tsx b/src/components/src/filters/time-widget-settings.tsxindex 31731fd3d..b6ce5ec48 100644--- a/src/components/src/filters/time-widget-settings.tsx+++ b/src/components/src/filters/time-widget-settings.tsx@@ -3,6 +3,7 @@import React, {useCallback, useEffect, useMemo, useState} from 'react';import styled from 'styled-components';+import moment from 'moment';import ItemSelector from '../common/item-selector/item-selector';import FieldSelectorFactory from '../common/field-selector';import Switch from '../common/switch';@@ -12,6 +13,7 @@ import {AGGREGATION_TYPES,ALL_FIELD_TYPES,DEFAULT_COLOR_UI,+ DEFAULT_TIME_FORMAT,durationMillisecond,durationSecond,durationMinute,@@ -50,6 +52,102 @@ const INTERVAL_UNITS = [{id: 'year', label: 'Year', duration: durationYear}];+const TIME_FORMAT_OPTIONS = ['12-hour', '24-hour'] as const;++type HourCycle = (typeof TIME_FORMAT_OPTIONS)[number];++const FORMAT_TOKENS =+ /(\[[^[]*\])|(\\.)|(LTS|LT|[Hh]mm(ss)?|[Hh]{1,2}|k{1,2}|mm?|ss?|S{1,9}|[Aa]|.)/g;++function tokenizeTimeFormat(format: string): string[] {+ const tokens = format.match(FORMAT_TOKENS) || [];+ return tokens.flatMap(token => {+ if (token !== 'LT' && token !== 'LTS') {+ return token;+ }+ const localizedFormat = moment.localeData().longDateFormat(token);+ return localizedFormat?.match(FORMAT_TOKENS) || token;+ });+}++function getHourTokenCycle(token: string): HourCycle | null {+ if (/^(H{1,2}|k{1,2}|Hmm(ss)?)$/.test(token)) {+ return '24-hour';+ }+ if (/^(h{1,2}|hmm(ss)?)$/.test(token)) {+ return '12-hour';+ }+ return null;+}++function getHourCycle(format: string): HourCycle | null {+ for (const token of tokenizeTimeFormat(format)) {+ const hourCycle = getHourTokenCycle(token);+ if (hourCycle) {+ return hourCycle;+ }+ }+ return null;+}++function getLocaleHourCycle(): HourCycle {+ return getHourCycle(moment.localeData().longDateFormat('LT')) || '24-hour';+}++function updateHourCycle(format: string, hourCycle: HourCycle): string {+ const tokens = tokenizeTimeFormat(format);+ const hourIndexes: number[] = [];+ const meridiemIndexes: number[] = [];++ tokens.forEach((token, index) => {+ if (getHourTokenCycle(token)) {+ hourIndexes.push(index);+ if (/^[Hh]mm(ss)?$/.test(token)) {+ tokens[index] = `${hourCycle === '24-hour' ? 'H' : 'h'}${token.slice(1)}`;+ } else {+ tokens[index] = hourCycle === '24-hour' ? 'HH' : token.length === 2 ? 'hh' : 'h';+ }+ } else if (/^[Aa]$/.test(token)) {+ meridiemIndexes.push(index);+ }+ });++ if (!hourIndexes.length) {+ return `${format} ${hourCycle === '24-hour' ? 'HH:mm' : 'hh:mm A'}`;+ }++ if (hourCycle === '24-hour') {+ meridiemIndexes.forEach(index => {+ tokens[index] = '';+ const adjacentIndex = index < hourIndexes[0] ? index + 1 : index - 1;+ if (/^\s$/.test(tokens[adjacentIndex] || '')) {+ tokens[adjacentIndex] = '';+ }+ });+ return tokens.join('');+ }++ if (!meridiemIndexes.length) {+ const localeTokens = tokenizeTimeFormat(moment.localeData().longDateFormat('LT'));+ const localeHourIndex = localeTokens.findIndex(token => Boolean(getHourTokenCycle(token)));+ const localeMeridiemIndex = localeTokens.findIndex(token => /^[Aa]$/.test(token));+ const meridiemToken = localeMeridiemIndex >= 0 ? localeTokens[localeMeridiemIndex] : 'A';++ if (localeMeridiemIndex >= 0 && localeMeridiemIndex < localeHourIndex) {+ tokens.splice(hourIndexes[0], 0, meridiemToken, ' ');+ } else {+ const lastTimeTokenIndex = tokens.reduce(+ (lastIndex, token, index) =>+ index >= hourIndexes[0] && /^(m{1,2}|s{1,2}|S{1,9})$/.test(token) ? index : lastIndex,+ hourIndexes[hourIndexes.length - 1]+ );+ tokens.splice(lastTimeTokenIndex + 1, 0, ' ', meridiemToken);+ }+ }++ return tokens.join('');+}+const SettingsPanel = styled.div`display: flex;flex-direction: column;@@ -277,6 +375,7 @@ export type TimeWidgetSettingsProps = {datasets: Datasets;setFilterPlot: (newProp: any, valueIndex?: number) => void;onTimezoneChange: (timezone: string) => void;+ onTimeFormatChange: (timeFormat: string) => void;};function parseInterval(intervalId: string | undefined): {step: number; unit: string} {@@ -298,7 +397,8 @@ function TimeWidgetSettingsFactory(filter,datasets,setFilterPlot,- onTimezoneChange+ onTimezoneChange,+ onTimeFormatChange}) => {const {plotType} = filter;const currentInterval = plotType?.interval;@@ -493,6 +593,20 @@ function TimeWidgetSettingsFactory([aggregationOptions]);+ const effectiveTimeFormat =+ (typeof filter.timeFormat === 'string' ? filter.timeFormat : filter.defaultTimeFormat) ||+ DEFAULT_TIME_FORMAT;+ const selectedTimeFormat = getHourCycle(effectiveTimeFormat) || getLocaleHourCycle();++ const handleTimeFormatChange = useCallback(+ (value: unknown) => {+ if (value === '12-hour' || value === '24-hour') {+ onTimeFormatChange(updateHourCycle(effectiveTimeFormat, value));+ }+ },+ [effectiveTimeFormat, onTimeFormatChange]+ );+return (<SettingsPanel className="time-widget--settings"><AxisSection>@@ -539,6 +653,25 @@ function TimeWidgetSettingsFactory(</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></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 af3bef9ba..6f80e8f97 100644--- a/src/components/src/filters/time-widget.tsx+++ b/src/components/src/filters/time-widget.tsx@@ -155,6 +155,11 @@ function TimeWidgetFactory([index, setFilterAnimationTimeConfig]);+ const _onTimeFormatChange = useCallback(+ (timeFormat: string) => setFilterAnimationTimeConfig(index, {timeFormat}),+ [index, setFilterAnimationTimeConfig]+ );+const _onToggleSettings = useCallback(() => {setShowSettings(prev => !prev);}, []);@@ -485,6 +490,7 @@ function TimeWidgetFactory(datasets={datasets}setFilterPlot={_setFilterPlot}onTimezoneChange={_onTimezoneChange}+ onTimeFormatChange={_onTimeFormatChange}/>) : null}<TimelineSection>diff --git a/src/localization/src/translations/en.ts b/src/localization/src/translations/en.tsindex 7e7ed1573..3f67f633f 100644--- a/src/localization/src/translations/en.ts+++ b/src/localization/src/translations/en.ts@@ -416,6 +416,7 @@ export default {filterOutHint: 'Hide rows that match this filter and keep the rest.',timezone: 'Time Zone',selectTimezone: 'Select display timezone',+ timeFormat: 'Time Format',groupBy: 'Group By',groupByField: 'Group by field',maxGroups: 'Max number of groups',diff --git a/test/browser/components/filters/time-widget-test.js b/test/browser/components/filters/time-widget-test.jsindex 155e9f8be..880d87b08 100644--- a/test/browser/components/filters/time-widget-test.js+++ b/test/browser/components/filters/time-widget-test.js@@ -6,6 +6,7 @@ import React 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';@@ -25,10 +26,13 @@ import {IconButton,SliderHandle,Typeahead,+ ItemSelector,TimezoneSelector,appInjector} from '@kepler.gl/components';+moment.locale('en');+const TimeWidget = appInjector.get(TimeWidgetFactory);const TimeRangeSlider = appInjector.get(TimeRangeSliderFactory);const RangeSlider = appInjector.get(RangeSliderFactory);@@ -158,6 +162,174 @@ test('Components -> TimeWidget.mount -> timezone selector', t => {t.end();});+test('Components -> TimeWidget.mount -> time format selector', t => {+ const setFilterAnimationTimeConfig = sinon.spy();+ const mountTimeWidget = filter => {+ const mounted = mountWithTheme(+ <IntlWrapper>+ <TimeWidget+ {...defaultProps}+ filter={filter}+ setFilterAnimationTimeConfig={setFilterAnimationTimeConfig}+ />+ </IntlWrapper>+ );+ mounted.find(Icons.Gear).at(0).simulate('click');+ mounted.update();+ return mounted;+ };++ let wrapper;+ t.doesNotThrow(() => {+ wrapper = mountTimeWidget(defaultProps.filter);+ }, 'TimeWidget should not fail without props');++ t.equal(+ wrapper.find('[data-testid="time-widget-time-format"]').hostNodes().length,+ 1,+ 'should render time format selector'+ );++ const getTimeFormatSelector = () =>+ wrapper.find('[data-testid="time-widget-time-format"]').find(ItemSelector).at(0);++ t.equal(getTimeFormatSelector().length, 1, 'should expose the time format options');+ t.equal(+ wrapper.find('[data-testid="time-widget-time-format"]').hostNodes().prop('aria-labelledby'),+ 'time-widget-time-format-label',+ 'should associate the selector with its label'+ );+ t.equal(+ getTimeFormatSelector().prop('searchable'),+ false,+ 'should use a non-searchable kepler item selector'+ );++ t.equal(+ getTimeFormatSelector().prop('selectedItems'),+ '12-hour',+ 'should default to 12-hour format'+ );++ getTimeFormatSelector().prop('onChange')('24-hour');++ t.deepEqual(+ setFilterAnimationTimeConfig.args[0],+ [0, {timeFormat: 'L HH:mm:ss'}],+ 'should call setFilterAnimationTimeConfig with 24-hour format'+ );++ wrapper.unmount();+ wrapper = mountTimeWidget({...defaultProps.filter, timeFormat: 'L HH:mm:ss'});++ t.equal(+ getTimeFormatSelector().prop('selectedItems'),+ '24-hour',+ 'should show the filter time format'+ );+ t.equal(+ wrapper+ .find(FloatingTimeDisplay)+ .find('.animation-control__time-display__bottom')+ .at(0)+ .find('.time-value')+ .at(0)+ .text(),+ '09/23/2016 05:00:00',+ 'should render time without an AM/PM suffix'+ );++ getTimeFormatSelector().prop('onChange')('12-hour');++ t.deepEqual(+ setFilterAnimationTimeConfig.lastCall.args,+ [0, {timeFormat: 'L hh:mm:ss A'}],+ 'should call setFilterAnimationTimeConfig with 12-hour format'+ );++ wrapper.unmount();+ wrapper = mountTimeWidget({...defaultProps.filter, timeFormat: 'L hh:mm:ss A'});++ t.equal(+ wrapper+ .find(FloatingTimeDisplay)+ .find('.animation-control__time-display__bottom')+ .at(0)+ .find('.time-value')+ .at(0)+ .text(),+ '09/23/2016 05:00:00 AM',+ 'should render time with an AM/PM suffix'+ );++ wrapper.unmount();+ wrapper = mountTimeWidget({+ ...defaultProps.filter,+ timeFormat: null,+ defaultTimeFormat: 'L LTS.SSS'+ });+ getTimeFormatSelector().prop('onChange')('24-hour');++ t.deepEqual(+ setFilterAnimationTimeConfig.lastCall.args,+ [0, {timeFormat: 'L HH:mm:ss.SSS'}],+ 'should preserve millisecond precision when changing the hour cycle'+ );++ wrapper.unmount();+ wrapper = mountTimeWidget({+ ...defaultProps.filter,+ timeFormat: 'L hmmss A'+ });+ getTimeFormatSelector().prop('onChange')('24-hour');++ t.deepEqual(+ setFilterAnimationTimeConfig.lastCall.args,+ [0, {timeFormat: 'L Hmmss'}],+ 'should convert a compact time without appending a second time format'+ );++ wrapper.unmount();+ const previousLocale = moment.locale();+ moment.locale('en-gb');+ wrapper = mountTimeWidget({+ ...defaultProps.filter,+ timeFormat: null,+ defaultTimeFormat: 'L LT'+ });++ t.equal(+ getTimeFormatSelector().prop('selectedItems'),+ '24-hour',+ 'should derive the hour cycle from a localized default format'+ );+ wrapper.unmount();+ moment.locale(previousLocale);++ wrapper = mountTimeWidget({+ ...defaultProps.filter,+ timeFormat: null,+ defaultTimeFormat: 'L'+ });++ t.equal(+ getTimeFormatSelector().prop('disabled'),+ undefined,+ 'should keep hour-cycle selection enabled when the effective format has no hour'+ );++ getTimeFormatSelector().prop('onChange')('24-hour');++ t.deepEqual(+ setFilterAnimationTimeConfig.lastCall.args,+ [0, {timeFormat: 'L HH:mm'}],+ 'should add a zero-padded 24-hour time to a date-only format'+ );++ wrapper.unmount();+ t.end();+});+test('Components -> TimeWidget.mount -> test actions', t => {const onClose = sinon.spy();const toggleAnimation = sinon.spy();