From 38b1e6a9b119a4e443d65b9a73c880f588a85a6c Mon Sep 17 00:00:00 2001 From: Karl Power Date: Fri, 23 Oct 2026 14:13:21 +0200 Subject: [PATCH 1/4] feat: override the time zone on the search and dashboard pages Add a time zone selector to the time picker on the search and dashboard pages. It overrides the user's time zone setting for that page and is kept in the tz URL param, so links and reloads keep it. - TimeZoneOverrideProvider reads tz; useDisplayTimeZone prefers it over the user setting, and ignores zones the browser doesn't know - The picker input shows the zone it uses, highlighted when it isn't the browser's, and its popover ends with the selector - TimeZoneSelect gains a default option that clears the override, and shows each zone's offset, including on the selected value - Default, UTC and Local shortcut buttons under the selector; User Preferences gets UTC and Local - Show short zone labels as UTC offsets rather than abbreviations - Links from charts and table rows to Search and dashboards carry tz - The sidebar badge stays on the user setting --- .changeset/time-zone-override.md | 5 + packages/app/src/DBDashboardPage.tsx | 40 +++- packages/app/src/DBSearchPage.tsx | 5 +- packages/app/src/UserPreferencesModal.tsx | 18 +- .../__tests__/UserPreferencesModal.test.tsx | 19 ++ packages/app/src/__tests__/timeZone.test.ts | 35 ++-- .../src/__tests__/useDisplayTimeZone.test.tsx | 136 +++++++++++++ packages/app/src/components/DBTimeChart.tsx | 6 +- .../src/components/TimePicker/TimePicker.tsx | 23 ++- .../TimePicker/TimePickerTimeZone.tsx | 72 +++++++ .../__tests__/TimePickerTimeZone.test.tsx | 116 +++++++++++ .../app/src/components/TimeZoneSelect.tsx | 189 +++++++++++++----- .../__tests__/TimeZoneSelect.test.tsx | 58 +++++- .../__tests__/useOnClickLinkBuilder.test.tsx | 38 ++++ .../app/src/hooks/useOnClickLinkBuilder.ts | 6 +- packages/app/src/timeZone.ts | 44 ++-- packages/app/src/timeZoneOverride.tsx | 73 +++++++ packages/app/src/useDisplayTimeZone.ts | 11 +- 18 files changed, 772 insertions(+), 122 deletions(-) create mode 100644 .changeset/time-zone-override.md create mode 100644 packages/app/src/__tests__/useDisplayTimeZone.test.tsx create mode 100644 packages/app/src/components/TimePicker/TimePickerTimeZone.tsx create mode 100644 packages/app/src/components/TimePicker/__tests__/TimePickerTimeZone.test.tsx create mode 100644 packages/app/src/timeZoneOverride.tsx diff --git a/.changeset/time-zone-override.md b/.changeset/time-zone-override.md new file mode 100644 index 0000000000..000c7dc14c --- /dev/null +++ b/.changeset/time-zone-override.md @@ -0,0 +1,5 @@ +--- +'@hyperdx/app': minor +--- + +feat: Pick a time zone for the search and dashboard pages from the time picker, overriding the time zone in User Preferences. The picker shows the zone it uses, and the choice is kept in the URL and in links from charts and tables diff --git a/packages/app/src/DBDashboardPage.tsx b/packages/app/src/DBDashboardPage.tsx index 2a691b1703..3126695466 100644 --- a/packages/app/src/DBDashboardPage.tsx +++ b/packages/app/src/DBDashboardPage.tsx @@ -237,6 +237,10 @@ import { useDefaultTimeRange, useNewTimeQuery, } from './timeQuery'; +import { + TimeZoneOverrideProvider, + useTimeZoneLinkParam, +} from './timeZoneOverride'; import { useConfirm } from './useConfirm'; import { useDisplayTimeZone } from './useDisplayTimeZone'; import { FormatTime } from './useFormatTime'; @@ -278,6 +282,7 @@ function HeatmapTile({ ); const containerRef = useRef(null); + const addTimeZone = useTimeZoneLinkParam(); const eventDeltasUrl = useMemo(() => { // Search page event deltas only supports trace sources and distribution mode if ( @@ -294,8 +299,8 @@ function HeatmapTile({ }); if (!url) return null; const separator = url.includes('?') ? '&' : '?'; - return `${url}${separator}mode=delta`; - }, [source, mode, queriedConfig, dateRange]); + return addTimeZone(`${url}${separator}mode=delta`); + }, [source, mode, queriedConfig, dateRange, addTimeZone]); const handleClick = useCallback( (e: React.MouseEvent) => { @@ -914,13 +919,15 @@ const Tile = ({ ); }, [sqlFilters, queriedConfig, source]); + const addTimeZone = useTimeZoneLinkParam(); const replaySearchUrl = useMemo(() => { - return buildDashboardReplaySearchUrl({ + const url = buildDashboardReplaySearchUrl({ source, config: queriedConfig, dateRange, }); - }, [dateRange, queriedConfig, source]); + return url && addTimeZone(url); + }, [dateRange, queriedConfig, source, addTimeZone]); const hoverToolbar = useMemo(() => { if (readOnly) return null; @@ -1311,13 +1318,15 @@ const Tile = ({ variant="default" getRowSearchLink={ isBuilderChartConfig(effectiveQueriedConfig) - ? row => - buildTableRowSearchUrl({ + ? row => { + const url = buildTableRowSearchUrl({ row, source, config: effectiveQueriedConfig, dateRange: effectiveDateRange, - }) + }); + return url && addTimeZone(url); + } : undefined } onFilter={onFilter} @@ -1478,6 +1487,7 @@ const Tile = ({ ); }, [ + addTimeZone, hoverToolbar, queriedConfig, title, @@ -3568,9 +3578,19 @@ function DBDashboardPageGuarded({ ); } -const DBDashboardPageDynamic = dynamic(async () => DBDashboardPageGuarded, { - ssr: false, -}); +// Outside DBDashboardPageGuarded, which formats the saved range in the zone. +function DBDashboardPageWithTimeZone(props: { presetConfig?: Dashboard }) { + return ( + + + + ); +} + +const DBDashboardPageDynamic = dynamic( + async () => DBDashboardPageWithTimeZone, + { ssr: false }, +); // @ts-expect-error for getLayout DBDashboardPageDynamic.getLayout = withAppNavForSurface('dashboard'); diff --git a/packages/app/src/DBSearchPage.tsx b/packages/app/src/DBSearchPage.tsx index 9f5f62522c..9ad1c32892 100644 --- a/packages/app/src/DBSearchPage.tsx +++ b/packages/app/src/DBSearchPage.tsx @@ -139,6 +139,7 @@ import { useDefaultTimeRange, useNewTimeQuery, } from '@/timeQuery'; +import { TimeZoneOverrideProvider } from '@/timeZoneOverride'; import { formatDurationMs, orderByAfterRemovingSelectItem, @@ -1048,7 +1049,9 @@ export function DBSearchPage() { search: getSavedSearchIdFromPath() ?? undefined, }} > - + + + ); } diff --git a/packages/app/src/UserPreferencesModal.tsx b/packages/app/src/UserPreferencesModal.tsx index c5c56cac5e..8613565a4a 100644 --- a/packages/app/src/UserPreferencesModal.tsx +++ b/packages/app/src/UserPreferencesModal.tsx @@ -11,7 +11,7 @@ import { Tooltip, } from '@mantine/core'; -import { TimeZoneSelect } from './components/TimeZoneSelect'; +import { TimeZoneSelect, TimeZoneShortcuts } from './components/TimeZoneSelect'; import { isContentFontSize, OPTIONS_CONTENT_FONT_SIZE, @@ -114,11 +114,17 @@ export const UserPreferencesModal = ({ label="Time zone" description="Times are displayed and input in this zone." > - setUserPreference({ timeZone })} - /> + + timeZone && setUserPreference({ timeZone })} + /> + setUserPreference({ timeZone })} + /> + diff --git a/packages/app/src/__tests__/UserPreferencesModal.test.tsx b/packages/app/src/__tests__/UserPreferencesModal.test.tsx index ef1b72a446..ddd9213b7c 100644 --- a/packages/app/src/__tests__/UserPreferencesModal.test.tsx +++ b/packages/app/src/__tests__/UserPreferencesModal.test.tsx @@ -44,6 +44,25 @@ describe('UserPreferencesModal', () => { expect(readStoredPreferences().timeZone).toBe('Etc/UTC'); }); + + it.each([ + ['time-zone-utc', 'Asia/Tokyo', 'Etc/UTC'], + ['time-zone-local', 'Etc/UTC', 'local'], + ])( + 'stores the zone from the %s shortcut', + async (testId, stored, expected) => { + renderModal({ timeZone: stored }); + + await userEvent.click(screen.getByTestId(testId)); + + expect(readStoredPreferences().timeZone).toBe(expected); + }, + ); + + it('has no Default shortcut, since this is the default', () => { + renderModal(); + expect(screen.queryByTestId('time-zone-default')).toBeNull(); + }); }); describe('Row click', () => { diff --git a/packages/app/src/__tests__/timeZone.test.ts b/packages/app/src/__tests__/timeZone.test.ts index b2022b77bf..b6d4872216 100644 --- a/packages/app/src/__tests__/timeZone.test.ts +++ b/packages/app/src/__tests__/timeZone.test.ts @@ -1,8 +1,9 @@ import { formatTimeZoneName, getSupportedTimeZones, - getTimeZoneOffsetLabel, + getTimeZonePreferenceLabel, getTimeZoneShortName, + isTimeZonePreference, isValidTimeZone, LOCAL_TIME_ZONE, resolveTimeZonePreference, @@ -24,19 +25,21 @@ describe('resolveTimeZonePreference', () => { }); }); -describe('getTimeZoneOffsetLabel', () => { - it('uses the offset in effect on the date', () => { - expect( - getTimeZoneOffsetLabel('America/Los_Angeles', new Date('2026-07-01Z')), - ).toBe('UTC-07:00'); - expect( - getTimeZoneOffsetLabel('America/Los_Angeles', new Date('2026-12-01Z')), - ).toBe('UTC-08:00'); - expect(getTimeZoneOffsetLabel('Asia/Kolkata')).toBe('UTC+05:30'); +describe('isTimeZonePreference', () => { + it('accepts local and zones the browser knows', () => { + expect(isTimeZonePreference(LOCAL_TIME_ZONE)).toBe(true); + expect(isTimeZonePreference('Asia/Tokyo')).toBe(true); + expect(isTimeZonePreference('Mars/Olympus_Mons')).toBe(false); }); +}); - it('labels UTC with a zero offset', () => { - expect(getTimeZoneOffsetLabel('Etc/UTC')).toBe('UTC+00:00'); +describe('getTimeZonePreferenceLabel', () => { + it('names local, UTC and other zones', () => { + expect(getTimeZonePreferenceLabel(LOCAL_TIME_ZONE)).toBe('Local'); + expect(getTimeZonePreferenceLabel('Etc/UTC')).toBe('UTC'); + expect(getTimeZonePreferenceLabel('America/Los_Angeles')).toBe( + 'America/Los Angeles', + ); }); }); @@ -58,16 +61,16 @@ describe('formatTimeZoneName', () => { }); describe('getTimeZoneShortName', () => { - it('uses the abbreviation in effect on the date', () => { + it('uses the offset in effect on the date, not an abbreviation', () => { expect( getTimeZoneShortName('America/Los_Angeles', new Date('2026-07-01Z')), - ).toBe('PDT'); + ).toBe('UTC-7'); expect( getTimeZoneShortName('America/Los_Angeles', new Date('2026-12-01Z')), - ).toBe('PST'); + ).toBe('UTC-8'); }); - it('names UTC and labels zones without an abbreviation from UTC', () => { + it('names a zero offset UTC and keeps partial-hour offsets', () => { expect(getTimeZoneShortName('Etc/UTC')).toBe('UTC'); expect(getTimeZoneShortName('Asia/Tokyo')).toBe('UTC+9'); expect(getTimeZoneShortName('Asia/Kolkata')).toBe('UTC+5:30'); diff --git a/packages/app/src/__tests__/useDisplayTimeZone.test.tsx b/packages/app/src/__tests__/useDisplayTimeZone.test.tsx new file mode 100644 index 0000000000..7a67910bc3 --- /dev/null +++ b/packages/app/src/__tests__/useDisplayTimeZone.test.tsx @@ -0,0 +1,136 @@ +import { renderHook } from '@testing-library/react'; + +import { + TimeZoneOverrideProvider, + useTimeZoneLinkParam, + useTimeZoneOverride, + withTimeZoneParam, +} from '@/timeZoneOverride'; +import { useDisplayTimeZone } from '@/useDisplayTimeZone'; + +let mockTz: string | null = null; +const mockSetTz = jest.fn(); +jest.mock('nuqs', () => ({ + parseAsString: {}, + useQueryState: () => [mockTz, mockSetTz], +})); + +let mockUserTimeZone = 'Etc/UTC'; +jest.mock('@/useUserPreferences', () => ({ + useUserPreferences: () => ({ + userPreferences: { timeZone: mockUserTimeZone }, + }), +})); + +const withProvider = ({ children }: { children: React.ReactNode }) => ( + {children} +); + +describe('useDisplayTimeZone', () => { + beforeEach(() => { + mockTz = null; + mockUserTimeZone = 'Etc/UTC'; + mockSetTz.mockClear(); + }); + + it('uses the user setting outside a page override', () => { + mockTz = 'Asia/Tokyo'; + const { result } = renderHook(() => useDisplayTimeZone()); + expect(result.current).toBe('Etc/UTC'); + }); + + it('uses the user setting when the page has no override', () => { + const { result } = renderHook(() => useDisplayTimeZone(), { + wrapper: withProvider, + }); + expect(result.current).toBe('Etc/UTC'); + }); + + it('prefers the page override', () => { + mockTz = 'Asia/Tokyo'; + const { result } = renderHook(() => useDisplayTimeZone(), { + wrapper: withProvider, + }); + expect(result.current).toBe('Asia/Tokyo'); + }); + + it('lets the page override to local time', () => { + mockTz = 'local'; + const { result } = renderHook(() => useDisplayTimeZone(), { + wrapper: withProvider, + }); + expect(result.current).toBeUndefined(); + }); + + it('ignores an override the browser does not recognise', () => { + mockTz = 'Mars/Olympus_Mons'; + const { result } = renderHook( + () => ({ + displayTimeZone: useDisplayTimeZone(), + override: useTimeZoneOverride(), + }), + { wrapper: withProvider }, + ); + expect(result.current.displayTimeZone).toBe('Etc/UTC'); + expect(result.current.override?.timeZone).toBeNull(); + }); + + it('writes the override to the URL', () => { + const { result } = renderHook(() => useTimeZoneOverride(), { + wrapper: withProvider, + }); + result.current?.setTimeZone('Asia/Tokyo'); + expect(mockSetTz).toHaveBeenCalledWith('Asia/Tokyo'); + result.current?.setTimeZone(null); + expect(mockSetTz).toHaveBeenCalledWith(null); + }); +}); + +describe('withTimeZoneParam', () => { + it('appends tz to a URL with or without a query', () => { + expect(withTimeZoneParam('/search', 'Asia/Tokyo')).toBe( + '/search?tz=Asia%2FTokyo', + ); + expect(withTimeZoneParam('/search?from=1&to=2', 'Etc/UTC')).toBe( + '/search?from=1&to=2&tz=Etc%2FUTC', + ); + }); + + it('keeps the hash after the query', () => { + expect(withTimeZoneParam('/dashboards/1?a=b#tile', 'local')).toBe( + '/dashboards/1?a=b&tz=local#tile', + ); + }); + + it('leaves the URL unchanged without an override', () => { + expect(withTimeZoneParam('/search?a=b', null)).toBe('/search?a=b'); + }); + + it('keeps existing param encoding intact', () => { + const where = encodeURIComponent(encodeURIComponent('a = 1\nb = 2')); + expect(withTimeZoneParam(`/search?where=${where}`, 'Etc/UTC')).toBe( + `/search?where=${where}&tz=Etc%2FUTC`, + ); + }); +}); + +describe('useTimeZoneLinkParam', () => { + beforeEach(() => { + mockTz = null; + }); + + it("adds the page's override to links", () => { + mockTz = 'Asia/Tokyo'; + const { result } = renderHook(() => useTimeZoneLinkParam(), { + wrapper: withProvider, + }); + expect(result.current('/search')).toBe('/search?tz=Asia%2FTokyo'); + }); + + it('leaves links unchanged without an override', () => { + const { result } = renderHook(() => useTimeZoneLinkParam(), { + wrapper: withProvider, + }); + expect(result.current('/search')).toBe('/search'); + }); +}); diff --git a/packages/app/src/components/DBTimeChart.tsx b/packages/app/src/components/DBTimeChart.tsx index 99e2ff79d6..058ffcad7e 100644 --- a/packages/app/src/components/DBTimeChart.tsx +++ b/packages/app/src/components/DBTimeChart.tsx @@ -61,6 +61,7 @@ import { import { useMVOptimizationExplanation } from '@/hooks/useMVOptimizationExplanation'; import { useResultColumnFilterKeys } from '@/hooks/useResultColumnFilterKeys'; import { useChartNumberFormats, useSource } from '@/source'; +import { useTimeZoneLinkParam } from '@/timeZoneOverride'; import type { NumberFormat, TileFilterHandler } from '@/types'; import ChartContainer from './charts/ChartContainer'; @@ -786,6 +787,7 @@ function DBTimeChartComponent({ : undefined; }, [activeClickPayload]); + const addTimeZone = useTimeZoneLinkParam(); const buildSearchUrl = useCallback( (seriesKey?: string, seriesValue?: number) => { // Raw SQL charts are not supported for drill-down as we don't know the source which is being used. @@ -901,15 +903,17 @@ function DBTimeChartComponent({ seconds: convertGranularityToSeconds(granularity), }); - return buildEventsSearchUrl({ + const url = buildEventsSearchUrl({ source, config: expandedConfig, dateRange: [from, to], groupFilters, valueRangeFilter, }); + return url && addTimeZone(url); }, [ + addTimeZone, clickedActiveLabelDate, config, granularity, diff --git a/packages/app/src/components/TimePicker/TimePicker.tsx b/packages/app/src/components/TimePicker/TimePicker.tsx index 153963edff..141fa09e6f 100644 --- a/packages/app/src/components/TimePicker/TimePicker.tsx +++ b/packages/app/src/components/TimePicker/TimePicker.tsx @@ -25,9 +25,14 @@ import { DateInput, DateInputProps } from '@mantine/dates'; import { useDisclosure } from '@mantine/hooks'; import { IconBolt, IconCalendarFilled } from '@tabler/icons-react'; +import { useTimeZoneOverride } from '@/timeZoneOverride'; import { useDisplayTimeZone } from '@/useDisplayTimeZone'; import { useUserPreferences } from '@/useUserPreferences'; +import { + TimePickerTimeZoneBadge, + TimePickerTimeZoneSelect, +} from './TimePickerTimeZone'; import { TimePickerMode } from './types'; import { useTimePickerForm } from './useTimePickerForm'; import { @@ -143,6 +148,8 @@ const TimePickerComponent = ({ userPreferences: { timeFormat }, } = useUserPreferences(); const timeZone = useDisplayTimeZone(); + // Pages that can override the time zone show it in the picker. + const showTimeZone = useTimeZoneOverride() != null; const [opened, { close, toggle }] = useDisclosure(false); @@ -307,12 +314,17 @@ const TimePickerComponent = ({ : 'var(--color-text)', }, }} + rightSectionWidth={showTimeZone ? 84 : undefined} + rightSectionPointerEvents="none" rightSection={ - opened && ( - - d - - ) + + {showTimeZone && } + {opened && ( + + d + + )} + } value={value} onChange={event => onChange(event.currentTarget.value)} @@ -555,6 +567,7 @@ const TimePickerComponent = ({ + ); diff --git a/packages/app/src/components/TimePicker/TimePickerTimeZone.tsx b/packages/app/src/components/TimePicker/TimePickerTimeZone.tsx new file mode 100644 index 0000000000..ddcc31aa98 --- /dev/null +++ b/packages/app/src/components/TimePicker/TimePickerTimeZone.tsx @@ -0,0 +1,72 @@ +import { ComboboxProps, Group, Stack, Text } from '@mantine/core'; + +import { TimeZoneSelect, TimeZoneShortcuts } from '@/components/TimeZoneSelect'; +import { getLocalTimeZone, getTimeZoneShortName } from '@/timeZone'; +import { useTimeZoneOverride } from '@/timeZoneOverride'; +import { useDisplayTimeZone } from '@/useDisplayTimeZone'; +import { useUserPreferences } from '@/useUserPreferences'; + +/** + * Short name of the zone the picker reads and shows times in, highlighted + * when it isn't the browser's. + */ +export function TimePickerTimeZoneBadge() { + const timeZone = useDisplayTimeZone(); + return ( + + {getTimeZoneShortName(timeZone ?? getLocalTimeZone())} + + ); +} + +/** Sets the page's time zone override. Renders nothing without one. */ +export function TimePickerTimeZoneSelect({ + comboboxProps, +}: { + comboboxProps: ComboboxProps; +}) { + const override = useTimeZoneOverride(); + const { + userPreferences: { timeZone: userTimeZone }, + } = useUserPreferences(); + + if (override == null) { + return null; + } + + return ( + + + Time zone + + + + override.setTimeZone(null)} + /> + + + ); +} diff --git a/packages/app/src/components/TimePicker/__tests__/TimePickerTimeZone.test.tsx b/packages/app/src/components/TimePicker/__tests__/TimePickerTimeZone.test.tsx new file mode 100644 index 0000000000..59a912dcfa --- /dev/null +++ b/packages/app/src/components/TimePicker/__tests__/TimePickerTimeZone.test.tsx @@ -0,0 +1,116 @@ +import { fireEvent, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; + +import { TimePicker } from '@/components/TimePicker'; + +let mockOverride: { + timeZone: string | null; + setTimeZone: jest.Mock; +} | null = null; +jest.mock('@/timeZoneOverride', () => ({ + useTimeZoneOverride: () => mockOverride, +})); + +let mockDisplayTimeZone: string | undefined; +jest.mock('@/useDisplayTimeZone', () => ({ + useDisplayTimeZone: () => mockDisplayTimeZone, +})); + +const renderPicker = () => { + renderWithMantine( + , + ); +}; + +describe('TimePicker time zone override', () => { + beforeEach(() => { + mockOverride = null; + mockDisplayTimeZone = undefined; + }); + + it('shows no time zone without a page override', () => { + renderPicker(); + fireEvent.click(screen.getByTestId('time-picker-input')); + + expect(screen.queryByTestId('time-picker-time-zone')).toBeNull(); + expect(screen.queryByTestId('time-picker-time-zone-select')).toBeNull(); + }); + + it('shows the display zone in the input', () => { + mockOverride = { timeZone: 'Asia/Tokyo', setTimeZone: jest.fn() }; + mockDisplayTimeZone = 'Asia/Tokyo'; + renderPicker(); + + expect(screen.getByTestId('time-picker-time-zone')).toHaveTextContent( + 'UTC+9', + ); + }); + + async function pickTimeZone(option: RegExp) { + fireEvent.click(screen.getByTestId('time-picker-input')); + await userEvent.click( + await screen.findByTestId('time-picker-time-zone-select'), + ); + await userEvent.click( + await screen.findByRole('option', { name: option, hidden: true }), + ); + } + + it('sets the page override', async () => { + const setTimeZone = jest.fn(); + mockOverride = { timeZone: null, setTimeZone }; + renderPicker(); + + await pickTimeZone(/^UTC/); + + expect(setTimeZone).toHaveBeenCalledWith('Etc/UTC'); + }); + + it.each([ + ['time-picker-time-zone-utc', 'Etc/UTC'], + ['time-picker-time-zone-local', 'local'], + ])('sets the override from the %s shortcut', async (testId, timeZone) => { + const setTimeZone = jest.fn(); + mockOverride = { timeZone: 'Asia/Tokyo', setTimeZone }; + renderPicker(); + fireEvent.click(screen.getByTestId('time-picker-input')); + + await userEvent.click(await screen.findByTestId(testId)); + + expect(setTimeZone).toHaveBeenCalledWith(timeZone); + }); + + it('clears the page override with the Default shortcut', async () => { + const setTimeZone = jest.fn(); + mockOverride = { timeZone: 'Asia/Tokyo', setTimeZone }; + renderPicker(); + fireEvent.click(screen.getByTestId('time-picker-input')); + + const shortcuts = ( + await screen.findByTestId('time-picker-time-zone-default') + ).parentElement; + expect( + Array.from(shortcuts?.children ?? []).map(button => button.textContent), + ).toEqual(['Default', 'UTC', 'Local']); + + await userEvent.click(screen.getByTestId('time-picker-time-zone-default')); + + expect(setTimeZone).toHaveBeenCalledWith(null); + }); + + it('clears the page override with the default option', async () => { + const setTimeZone = jest.fn(); + mockOverride = { timeZone: 'Etc/UTC', setTimeZone }; + mockDisplayTimeZone = 'Etc/UTC'; + renderPicker(); + + // The default names the user setting, which is unset here. + await pickTimeZone(/^Default \(Local\)/); + + expect(setTimeZone).toHaveBeenCalledWith(null); + }); +}); diff --git a/packages/app/src/components/TimeZoneSelect.tsx b/packages/app/src/components/TimeZoneSelect.tsx index 4de300eb1c..a652b0dbc1 100644 --- a/packages/app/src/components/TimeZoneSelect.tsx +++ b/packages/app/src/components/TimeZoneSelect.tsx @@ -2,6 +2,7 @@ import { useCallback, useMemo } from 'react'; import { UTC_TIME_ZONE } from '@hyperdx/common-utils/dist/core/utils'; import { Box, + Button, ComboboxData, ComboboxItem, Group, @@ -15,7 +16,7 @@ import { formatTimeZoneName, getLocalTimeZone, getSupportedTimeZones, - getTimeZoneOffsetLabel, + getTimeZonePreferenceLabel, getTimeZoneShortName, LOCAL_TIME_ZONE, resolveTimeZonePreference, @@ -25,23 +26,38 @@ type TimeZoneSelectProps = Omit< SelectProps, 'value' | 'onChange' | 'data' | 'renderOption' > & { - /** A time zone setting: `LOCAL_TIME_ZONE` or an IANA name. */ - value: string; - onChange: (value: string) => void; + /** + * A time zone setting: `LOCAL_TIME_ZONE` or an IANA name, or null for the + * default option. + */ + value: string | null; + onChange: (value: string | null) => void; + /** + * The setting the default option stands for, such as the user's. Adds a + * "Default (…)" option, pinned first, that selects null. + */ + defaultTimeZone?: string; }; -/** Offsets shown next to each option, keyed by option value. */ -function getOffsetLabels(zones: string[]): Map { - const localZone = getLocalTimeZone(); - - return new Map([ - [ - LOCAL_TIME_ZONE, - `${getTimeZoneShortName(localZone)} · ${getTimeZoneOffsetLabel(localZone)}`, - ], - [UTC_TIME_ZONE, getTimeZoneOffsetLabel(UTC_TIME_ZONE)], - ...zones.map(zone => [zone, getTimeZoneOffsetLabel(zone)] as const), - ]); +const DEFAULT_OPTION = '__default'; + +type ZoneOption = { value: string; name: string; offset?: string }; + +function getDefaultOption(preference: string): ZoneOption { + const timeZone = resolveTimeZonePreference(preference); + return { + value: DEFAULT_OPTION, + name: `Default (${getTimeZonePreferenceLabel(preference)})`, + offset: + timeZone === UTC_TIME_ZONE + ? undefined + : getTimeZoneShortName(timeZone ?? getLocalTimeZone()), + }; +} + +// The label is what the input shows and what search matches. +function toComboboxItem({ value, name, offset }: ZoneOption): ComboboxItem { + return { value, label: offset ? `${name} ${offset}` : name }; } /** @@ -51,14 +67,22 @@ function getOffsetLabels(zones: string[]): Map { export function TimeZoneSelect({ value, onChange, + defaultTimeZone, ...props }: TimeZoneSelectProps) { - const selected = resolveTimeZonePreference(value) ?? LOCAL_TIME_ZONE; + const selected = + value == null && defaultTimeZone != null + ? DEFAULT_OPTION + : (resolveTimeZonePreference(value ?? LOCAL_TIME_ZONE) ?? + LOCAL_TIME_ZONE); const zones = useMemo(() => { const supported = getSupportedTimeZones(); - const isPinned = selected === LOCAL_TIME_ZONE || selected === UTC_TIME_ZONE; + const isPinned = + selected === DEFAULT_OPTION || + selected === LOCAL_TIME_ZONE || + selected === UTC_TIME_ZONE; const isListed = supported.includes(selected); @@ -69,43 +93,57 @@ export function TimeZoneSelect({ return [...supported, selected]; }, [selected]); - const data = useMemo( - () => [ + const { data, optionsByValue } = useMemo(() => { + const localZone = getLocalTimeZone(); + const pinned: ZoneOption[] = [ + ...(defaultTimeZone != null ? [getDefaultOption(defaultTimeZone)] : []), { value: LOCAL_TIME_ZONE, - label: `Local (${formatTimeZoneName(getLocalTimeZone())})`, + name: `Local (${formatTimeZoneName(localZone)})`, + offset: getTimeZoneShortName(localZone), }, - { value: UTC_TIME_ZONE, label: 'UTC' }, - { - group: 'All time zones', - items: zones.map(zone => ({ - value: zone, - label: formatTimeZoneName(zone), - })), - }, - ], - [zones], - ); - - const offsetLabels = useMemo(() => getOffsetLabels(zones), [zones]); + // UTC's name is already its offset. + { value: UTC_TIME_ZONE, name: 'UTC' }, + ]; + const listed: ZoneOption[] = zones.map(zone => ({ + value: zone, + name: formatTimeZoneName(zone), + offset: getTimeZoneShortName(zone), + })); + + return { + data: [ + ...pinned.map(toComboboxItem), + { group: 'All time zones', items: listed.map(toComboboxItem) }, + ] satisfies ComboboxData, + optionsByValue: new Map( + [...pinned, ...listed].map(option => [option.value, option]), + ), + }; + }, [zones, defaultTimeZone]); const renderOption = useCallback( - ({ option, checked }: { option: ComboboxItem; checked?: boolean }) => ( - - - {option.label} - - - {offsetLabels.get(option.value)} - - - - {checked && ( - - )} - - ), - [offsetLabels], + ({ option, checked }: { option: ComboboxItem; checked?: boolean }) => { + const zone = optionsByValue.get(option.value); + return ( + + + {zone?.name ?? option.label} + + {zone?.offset && ( + + {zone.offset} + + )} + + + {checked && ( + + )} + + ); + }, + [optionsByValue], ); return ( @@ -117,8 +155,57 @@ export function TimeZoneSelect({ {...props} data={data} value={selected} - onChange={next => next && onChange(next)} + onChange={next => { + if (next != null) { + onChange(next === DEFAULT_OPTION ? null : next); + } + }} renderOption={renderOption} /> ); } + +/** + * One-click "UTC" and "Local" buttons, for under a `TimeZoneSelect`. With + * `onSelectDefault`, a "Default" button comes first. + */ +export function TimeZoneShortcuts({ + onSelect, + onSelectDefault, + testIdPrefix, +}: { + onSelect: (timeZone: string) => void; + onSelectDefault?: () => void; + testIdPrefix: string; +}) { + return ( + + {onSelectDefault && ( + + )} + + + + ); +} diff --git a/packages/app/src/components/__tests__/TimeZoneSelect.test.tsx b/packages/app/src/components/__tests__/TimeZoneSelect.test.tsx index d7b71e5c73..d7afd95473 100644 --- a/packages/app/src/components/__tests__/TimeZoneSelect.test.tsx +++ b/packages/app/src/components/__tests__/TimeZoneSelect.test.tsx @@ -20,11 +20,23 @@ const optionNames = () => .getAllByRole('option', { hidden: true }) .map(option => option.textContent); +const LOCAL_LABEL = /^Local \(America\/New York\) UTC-[45]$/; + +const LOCAL_DEFAULT_LABEL = /^Default \(Local\) UTC-[45]$/; + +const inputValue = () => + screen.getByTestId('time-zone-select').value; + describe('TimeZoneSelect', () => { - it('shows the local zone for the local setting', () => { + it('shows the local zone and its offset for the local setting', () => { renderSelect('local'); + expect(inputValue()).toMatch(LOCAL_LABEL); + }); + + it('shows a selected zone with its offset', () => { + renderSelect('Asia/Tokyo'); expect(screen.getByTestId('time-zone-select')).toHaveValue( - 'Local (America/New York)', + 'Asia/Tokyo UTC+9', ); }); @@ -33,11 +45,9 @@ describe('TimeZoneSelect', () => { await userEvent.click(screen.getByTestId('time-zone-select')); const names = optionNames(); - expect(names[0]).toMatch( - /^Local \(America\/New York\)E[SD]T · UTC-0[45]:00$/, - ); - expect(names[1]).toBe('UTCUTC+00:00'); - expect(names.slice(2)).toContain('Asia/TokyoUTC+09:00'); + expect(names[0]).toMatch(/^Local \(America\/New York\)UTC-[45]$/); + expect(names[1]).toBe('UTC'); + expect(names.slice(2)).toContain('Asia/TokyoUTC+9'); expect(names.filter(name => name?.startsWith('UTC'))).toHaveLength(1); }); @@ -57,10 +67,38 @@ describe('TimeZoneSelect', () => { expect(onChange).toHaveBeenCalledWith('America/Los_Angeles'); }); + it('finds zones by offset', async () => { + renderSelect('local'); + + const input = screen.getByTestId('time-zone-select'); + await userEvent.clear(input); + await userEvent.type(input, 'utc+9'); + + expect(optionNames()).toContain('Asia/TokyoUTC+9'); + expect(optionNames()).not.toContain('Europe/BerlinUTC+1'); + }); + + it.each([ + ['local', LOCAL_DEFAULT_LABEL], + ['Asia/Tokyo', /^Default \(Asia\/Tokyo\) UTC\+9$/], + ['Etc/UTC', /^Default \(UTC\)$/], + ])( + 'names the default option after %s with its offset', + (defaultTimeZone, label) => { + renderWithMantine( + , + ); + expect(inputValue()).toMatch(label); + }, + ); + it('shows local for a zone the browser does not recognise', () => { renderSelect('Mars/Olympus_Mons'); - expect(screen.getByTestId('time-zone-select')).toHaveValue( - 'Local (America/New York)', - ); + expect(inputValue()).toMatch(LOCAL_LABEL); }); }); diff --git a/packages/app/src/hooks/__tests__/useOnClickLinkBuilder.test.tsx b/packages/app/src/hooks/__tests__/useOnClickLinkBuilder.test.tsx index 9ab42e0d18..fa78feda9e 100644 --- a/packages/app/src/hooks/__tests__/useOnClickLinkBuilder.test.tsx +++ b/packages/app/src/hooks/__tests__/useOnClickLinkBuilder.test.tsx @@ -9,6 +9,13 @@ import { renderHook } from '@testing-library/react'; import { useDashboards } from '@/dashboard'; import { useOnClickLinkBuilder } from '@/hooks/useOnClickLinkBuilder'; import { useSources } from '@/source'; +import { TimeZoneOverrideProvider } from '@/timeZoneOverride'; + +let mockTz: string | null = null; +jest.mock('nuqs', () => ({ + parseAsString: {}, + useQueryState: () => [mockTz, jest.fn()], +})); jest.mock('@/source', () => ({ useSources: jest.fn(), @@ -86,6 +93,37 @@ describe('useOnClickLinkBuilder', () => { expect(action.url!.startsWith('/dashboards/dash_1?')).toBe(true); }); + it("adds the page's time zone override to search and dashboard links", () => { + mockTz = 'Asia/Tokyo'; + const wrapper = ({ children }: { children: React.ReactNode }) => ( + {children} + ); + const tzOf = (onClick: OnClickSearch | OnClickDashboard) => { + const { result } = renderHook( + () => useOnClickLinkBuilder({ onClick, dateRange }), + { wrapper }, + ); + const url = result.current!({}).url!; + return new URLSearchParams(url.split('?')[1]).get('tz'); + }; + + expect( + tzOf({ + type: 'search', + target: { mode: 'id', id: 'src_1' }, + whereLanguage: 'sql', + }), + ).toBe('Asia/Tokyo'); + expect( + tzOf({ + type: 'dashboard', + target: { mode: 'id', id: 'dash_1' }, + whereLanguage: 'sql', + }), + ).toBe('Asia/Tokyo'); + mockTz = null; + }); + it('resolves an external link to an absolute URL marked external', () => { const onClick: OnClickExternal = { type: 'external', diff --git a/packages/app/src/hooks/useOnClickLinkBuilder.ts b/packages/app/src/hooks/useOnClickLinkBuilder.ts index dd3dbe13a6..5b58d8a5bd 100644 --- a/packages/app/src/hooks/useOnClickLinkBuilder.ts +++ b/packages/app/src/hooks/useOnClickLinkBuilder.ts @@ -10,6 +10,7 @@ import { notifications } from '@mantine/notifications'; import { useDashboards } from '@/dashboard'; import { useSources } from '@/source'; +import { useTimeZoneLinkParam } from '@/timeZoneOverride'; /** * The action a row click should take. `url` is set when the row's @@ -54,6 +55,7 @@ export function useOnClickLinkBuilder({ }): ((row: Record) => RowAction) | null { const { data: sources } = useSources(); const { data: dashboards } = useDashboards(); + const addTimeZone = useTimeZoneLinkParam(); const [sourceIdsByName, sourceIds, sourceNamesById] = useMemo(() => { const idsByName = new Map(); @@ -124,7 +126,8 @@ export function useOnClickLinkBuilder({ if (renderResult.ok) { return { - url: renderResult.url, + // Search and dashboards take the same override; other sites don't. + url: isExternal ? renderResult.url : addTimeZone(renderResult.url), description: isExternal ? renderResult.url : description, external: isExternal, }; @@ -154,6 +157,7 @@ export function useOnClickLinkBuilder({ return result; }; }, [ + addTimeZone, onClick, sourceIds, sourceIdsByName, diff --git a/packages/app/src/timeZone.ts b/packages/app/src/timeZone.ts index f4ce61a3cf..71f13a14e2 100644 --- a/packages/app/src/timeZone.ts +++ b/packages/app/src/timeZone.ts @@ -12,6 +12,20 @@ export function isValidTimeZone(timeZone: string): boolean { } } +/** Whether `value` is a time zone setting this browser can use. */ +export function isTimeZonePreference(value: string): boolean { + return value === LOCAL_TIME_ZONE || isValidTimeZone(value); +} + +/** "Local", "UTC", or the zone's name, e.g. "Asia/Tokyo". */ +export function getTimeZonePreferenceLabel(preference: string): string { + const timeZone = resolveTimeZonePreference(preference); + if (timeZone == null) { + return 'Local'; + } + return timeZone === UTC_TIME_ZONE ? 'UTC' : formatTimeZoneName(timeZone); +} + /** * The IANA zone a setting refers to, or undefined for the local zone. Zones * the browser doesn't recognise fall back to local. @@ -45,39 +59,31 @@ function gmtToUtc(label: string): string { return label.replace(/^GMT/, 'UTC'); } -/** Offset of `timeZone` at `date`, e.g. "UTC-07:00". */ -export function getTimeZoneOffsetLabel( - timeZone: string, - // eslint-disable-next-line no-restricted-syntax - date: Date = new Date(), -): string { - const offset = - new Intl.DateTimeFormat('en-US', { timeZone, timeZoneName: 'longOffset' }) - .formatToParts(date) - .find(part => part.type === 'timeZoneName')?.value ?? 'GMT'; - // Zero offsets come back as plain "GMT" in some runtimes. - return offset === 'GMT' ? 'UTC+00:00' : gmtToUtc(offset); -} - /** "America/Los_Angeles" as "America/Los Angeles". */ export function formatTimeZoneName(timeZone: string): string { return timeZone.replaceAll('_', ' '); } /** - * Short name of `timeZone` at `date`, e.g. "UTC", "PDT" or "UTC+9". en-US is - * used because it has abbreviations for the most zones. + * Short offset of `timeZone` at `date`, e.g. "UTC-7" or "UTC+5:30", or "UTC" + * for a zero offset. Offsets rather than abbreviations like "PDT", which only + * exist for some zones and are ambiguous. */ export function getTimeZoneShortName( timeZone: string, // eslint-disable-next-line no-restricted-syntax date: Date = new Date(), ): string { - const name = new Intl.DateTimeFormat('en-US', { + const offset = new Intl.DateTimeFormat('en-US', { timeZone, - timeZoneName: 'short', + timeZoneName: 'shortOffset', }) .formatToParts(date) .find(part => part.type === 'timeZoneName')?.value; - return name ? gmtToUtc(name) : timeZone; + if (offset == null) { + return timeZone; + } + // Zero offsets come back as "GMT+0", or plain "GMT" in some runtimes. + const label = gmtToUtc(offset); + return label === 'UTC+0' ? 'UTC' : label; } diff --git a/packages/app/src/timeZoneOverride.tsx b/packages/app/src/timeZoneOverride.tsx new file mode 100644 index 0000000000..ddab4adeac --- /dev/null +++ b/packages/app/src/timeZoneOverride.tsx @@ -0,0 +1,73 @@ +import { + createContext, + type ReactNode, + use, + useCallback, + useMemo, +} from 'react'; +import { parseAsString, useQueryState } from 'nuqs'; + +import { isTimeZonePreference } from './timeZone'; + +type TimeZoneOverride = { + /** The page's time zone setting, or null to use the user's. */ + timeZone: string | null; + setTimeZone: (timeZone: string | null) => void; +}; + +const TimeZoneOverrideContext = createContext(null); + +/** + * Lets a page show times in its own zone, kept in the `tz` URL param so links + * keep it. Wrap the page's content, not the app: the sidebar keeps showing + * the user's setting. + */ +export function TimeZoneOverrideProvider({ + children, +}: { + children: ReactNode; +}) { + const [tz, setTz] = useQueryState('tz', parseAsString); + + const timeZone = tz != null && isTimeZonePreference(tz) ? tz : null; + + const value = useMemo( + () => ({ timeZone, setTimeZone: setTz }), + [timeZone, setTz], + ); + + return ( + {children} + ); +} + +/** The page's time zone override, or null outside `TimeZoneOverrideProvider`. */ +export function useTimeZoneOverride(): TimeZoneOverride | null { + return use(TimeZoneOverrideContext); +} + +/** + * Adds `tz` to an in-app URL. Appends rather than re-encoding the query, whose + * params can carry their own encoding (see buildEventsSearchUrl). + */ +export function withTimeZoneParam( + url: string, + timeZone: string | null | undefined, +): string { + if (timeZone == null) { + return url; + } + const [path, hash] = url.split('#', 2); + const separator = path.includes('?') ? '&' : '?'; + const withParam = `${path}${separator}tz=${encodeURIComponent(timeZone)}`; + return hash == null ? withParam : `${withParam}#${hash}`; +} + +/** + * Adds the page's time zone override to links to pages that support one, so + * they open in the same zone. + */ +export function useTimeZoneLinkParam(): (url: string) => string { + const timeZone = useTimeZoneOverride()?.timeZone; + return useCallback(url => withTimeZoneParam(url, timeZone), [timeZone]); +} diff --git a/packages/app/src/useDisplayTimeZone.ts b/packages/app/src/useDisplayTimeZone.ts index ce39ceea24..162552db1d 100644 --- a/packages/app/src/useDisplayTimeZone.ts +++ b/packages/app/src/useDisplayTimeZone.ts @@ -1,15 +1,22 @@ import { useMemo } from 'react'; import { resolveTimeZonePreference } from './timeZone'; +import { useTimeZoneOverride } from './timeZoneOverride'; import { useUserPreferences } from './useUserPreferences'; /** * IANA time zone that times are shown and typed in, or undefined for the - * local zone. + * local zone. The page's override wins over the user's setting. */ export function useDisplayTimeZone(): string | undefined { const { userPreferences: { timeZone }, } = useUserPreferences(); - return useMemo(() => resolveTimeZonePreference(timeZone), [timeZone]); + + const override = useTimeZoneOverride()?.timeZone; + + return useMemo( + () => resolveTimeZonePreference(override ?? timeZone), + [override, timeZone], + ); } From a472fc6f0ff47c0f243b174a2be65ecc3391674e Mon Sep 17 00:00:00 2001 From: Karl Power Date: Fri, 30 Oct 2026 10:51:48 +0100 Subject: [PATCH 2/4] fix: don't highlight the time zone badge for the browser's own zone --- .../TimePicker/TimePickerTimeZone.tsx | 11 +++++++---- .../__tests__/TimePickerTimeZone.test.tsx | 17 +++++++++++++++++ 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/packages/app/src/components/TimePicker/TimePickerTimeZone.tsx b/packages/app/src/components/TimePicker/TimePickerTimeZone.tsx index ddcc31aa98..34ac58d575 100644 --- a/packages/app/src/components/TimePicker/TimePickerTimeZone.tsx +++ b/packages/app/src/components/TimePicker/TimePickerTimeZone.tsx @@ -11,16 +11,19 @@ import { useUserPreferences } from '@/useUserPreferences'; * when it isn't the browser's. */ export function TimePickerTimeZoneBadge() { - const timeZone = useDisplayTimeZone(); + const localTimeZone = getLocalTimeZone(); + const timeZone = useDisplayTimeZone() ?? localTimeZone; + const isLocal = timeZone === localTimeZone; return ( - {getTimeZoneShortName(timeZone ?? getLocalTimeZone())} + {getTimeZoneShortName(timeZone)} ); } diff --git a/packages/app/src/components/TimePicker/__tests__/TimePickerTimeZone.test.tsx b/packages/app/src/components/TimePicker/__tests__/TimePickerTimeZone.test.tsx index 59a912dcfa..8dc92504c5 100644 --- a/packages/app/src/components/TimePicker/__tests__/TimePickerTimeZone.test.tsx +++ b/packages/app/src/components/TimePicker/__tests__/TimePickerTimeZone.test.tsx @@ -50,6 +50,23 @@ describe('TimePicker time zone override', () => { ); }); + // Tests run with TZ=America/New_York. + it.each([ + [undefined, true], + ['America/New_York', true], + ['Asia/Tokyo', false], + ])( + 'highlights the zone %s only when it is not local', + (timeZone, isLocal) => { + mockOverride = { timeZone: timeZone ?? null, setTimeZone: jest.fn() }; + mockDisplayTimeZone = timeZone; + renderPicker(); + + const badge = screen.getByTestId('time-picker-time-zone'); + expect(badge).toHaveAttribute('data-local', String(isLocal)); + }, + ); + async function pickTimeZone(option: RegExp) { fireEvent.click(screen.getByTestId('time-picker-input')); await userEvent.click( From 7a1eccb9122131500e7731d511259d23aa54062d Mon Sep 17 00:00:00 2001 From: Karl Power Date: Fri, 30 Oct 2026 10:59:31 +0100 Subject: [PATCH 3/4] fix: show the time zone offset in effect during the selected range --- packages/app/src/__tests__/timeZone.test.ts | 36 ++++++++++++++++ .../src/components/TimePicker/TimePicker.tsx | 11 ++++- .../TimePicker/TimePickerTimeZone.tsx | 43 ++++++++++++++++--- .../__tests__/TimePickerTimeZone.test.tsx | 20 ++++++++- packages/app/src/timeZone.ts | 18 ++++++++ 5 files changed, 118 insertions(+), 10 deletions(-) diff --git a/packages/app/src/__tests__/timeZone.test.ts b/packages/app/src/__tests__/timeZone.test.ts index b6d4872216..6d2a81110f 100644 --- a/packages/app/src/__tests__/timeZone.test.ts +++ b/packages/app/src/__tests__/timeZone.test.ts @@ -2,6 +2,7 @@ import { formatTimeZoneName, getSupportedTimeZones, getTimeZonePreferenceLabel, + getTimeZoneRangeShortName, getTimeZoneShortName, isTimeZonePreference, isValidTimeZone, @@ -82,3 +83,38 @@ describe('getTimeZoneShortName', () => { ); }); }); + +describe('getTimeZoneRangeShortName', () => { + it('uses the offset during the range, not today', () => { + expect( + getTimeZoneRangeShortName('America/Los_Angeles', [ + new Date('2026-01-15T10:00:00Z'), + new Date('2026-01-15T11:00:00Z'), + ]), + ).toBe('UTC-8'); + }); + + it('shows both offsets for a range across a DST change', () => { + expect( + getTimeZoneRangeShortName('America/Los_Angeles', [ + new Date('2026-10-31T12:00:00Z'), + new Date('2026-11-02T12:00:00Z'), + ]), + ).toBe('UTC-7/-8'); + expect( + getTimeZoneRangeShortName('Europe/London', [ + new Date('2026-03-28T12:00:00Z'), + new Date('2026-03-30T12:00:00Z'), + ]), + ).toBe('UTC+0/+1'); + }); + + it('shows one offset for a zone without DST', () => { + expect( + getTimeZoneRangeShortName('Etc/UTC', [ + new Date('2026-01-15Z'), + new Date('2026-07-15Z'), + ]), + ).toBe('UTC'); + }); +}); diff --git a/packages/app/src/components/TimePicker/TimePicker.tsx b/packages/app/src/components/TimePicker/TimePicker.tsx index 141fa09e6f..4f725e2af5 100644 --- a/packages/app/src/components/TimePicker/TimePicker.tsx +++ b/packages/app/src/components/TimePicker/TimePicker.tsx @@ -32,6 +32,7 @@ import { useUserPreferences } from '@/useUserPreferences'; import { TimePickerTimeZoneBadge, TimePickerTimeZoneSelect, + useTimePickerTimeZoneLabel, } from './TimePickerTimeZone'; import { TimePickerMode } from './types'; import { useTimePickerForm } from './useTimePickerForm'; @@ -173,6 +174,7 @@ const TimePickerComponent = ({ const dateRange = React.useMemo(() => { return parseTimeRangeInput(value, timeZone); }, [value, timeZone]); + const timeZoneLabel = useTimePickerTimeZoneLabel(dateRange); React.useEffect(() => { // Only update form values from external dateRange when popover is closed @@ -314,11 +316,16 @@ const TimePickerComponent = ({ : 'var(--color-text)', }, }} - rightSectionWidth={showTimeZone ? 84 : undefined} + // Sized to the label: offsets like "UTC-3:30/-2:30" run long. + rightSectionWidth={ + showTimeZone + ? `calc(${timeZoneLabel.label.length}ch + ${opened ? 40 : 16}px)` + : undefined + } rightSectionPointerEvents="none" rightSection={ - {showTimeZone && } + {showTimeZone && } {opened && ( d diff --git a/packages/app/src/components/TimePicker/TimePickerTimeZone.tsx b/packages/app/src/components/TimePicker/TimePickerTimeZone.tsx index 34ac58d575..280133bbd3 100644 --- a/packages/app/src/components/TimePicker/TimePickerTimeZone.tsx +++ b/packages/app/src/components/TimePicker/TimePickerTimeZone.tsx @@ -1,19 +1,50 @@ +import { useMemo } from 'react'; import { ComboboxProps, Group, Stack, Text } from '@mantine/core'; import { TimeZoneSelect, TimeZoneShortcuts } from '@/components/TimeZoneSelect'; -import { getLocalTimeZone, getTimeZoneShortName } from '@/timeZone'; +import { + getLocalTimeZone, + getTimeZoneRangeShortName, + getTimeZoneShortName, +} from '@/timeZone'; import { useTimeZoneOverride } from '@/timeZoneOverride'; import { useDisplayTimeZone } from '@/useDisplayTimeZone'; import { useUserPreferences } from '@/useUserPreferences'; /** - * Short name of the zone the picker reads and shows times in, highlighted - * when it isn't the browser's. + * Offset of the zone the picker reads and shows times in, during `range` + * (now if it didn't parse), and whether it is the browser's zone. */ -export function TimePickerTimeZoneBadge() { +export function useTimePickerTimeZoneLabel( + range: readonly [Date | null, Date | null], +): { label: string; isLocal: boolean } { const localTimeZone = getLocalTimeZone(); const timeZone = useDisplayTimeZone() ?? localTimeZone; - const isLocal = timeZone === localTimeZone; + const startMs = range[0]?.getTime(); + const endMs = range[1]?.getTime(); + return useMemo( + () => ({ + label: + startMs != null && endMs != null + ? getTimeZoneRangeShortName(timeZone, [ + new Date(startMs), + new Date(endMs), + ]) + : getTimeZoneShortName(timeZone), + isLocal: timeZone === localTimeZone, + }), + [timeZone, localTimeZone, startMs, endMs], + ); +} + +/** The zone's offset, highlighted when it isn't the browser's zone. */ +export function TimePickerTimeZoneBadge({ + label, + isLocal, +}: { + label: string; + isLocal: boolean; +}) { return ( - {getTimeZoneShortName(timeZone)} + {label} ); } diff --git a/packages/app/src/components/TimePicker/__tests__/TimePickerTimeZone.test.tsx b/packages/app/src/components/TimePicker/__tests__/TimePickerTimeZone.test.tsx index 8dc92504c5..65dd68176c 100644 --- a/packages/app/src/components/TimePicker/__tests__/TimePickerTimeZone.test.tsx +++ b/packages/app/src/components/TimePicker/__tests__/TimePickerTimeZone.test.tsx @@ -16,10 +16,10 @@ jest.mock('@/useDisplayTimeZone', () => ({ useDisplayTimeZone: () => mockDisplayTimeZone, })); -const renderPicker = () => { +const renderPicker = (inputValue = 'Oct 22 14:00:00 - Oct 22 15:00:00') => { renderWithMantine( , @@ -50,6 +50,22 @@ describe('TimePicker time zone override', () => { ); }); + it.each([ + ['Jan 15 2026 10:00:00 - Jan 15 2026 11:00:00', 'UTC-8'], + ['Oct 31 2026 10:00:00 - Nov 2 2026 10:00:00', 'UTC-7/-8'], + ])('shows the offset during the range %s', (inputValue, label) => { + mockOverride = { + timeZone: 'America/Los_Angeles', + setTimeZone: jest.fn(), + }; + mockDisplayTimeZone = 'America/Los_Angeles'; + renderPicker(inputValue); + + expect(screen.getByTestId('time-picker-time-zone')).toHaveTextContent( + label, + ); + }); + // Tests run with TZ=America/New_York. it.each([ [undefined, true], diff --git a/packages/app/src/timeZone.ts b/packages/app/src/timeZone.ts index 71f13a14e2..af44cd002a 100644 --- a/packages/app/src/timeZone.ts +++ b/packages/app/src/timeZone.ts @@ -87,3 +87,21 @@ export function getTimeZoneShortName( const label = gmtToUtc(offset); return label === 'UTC+0' ? 'UTC' : label; } + +/** + * Short offset of `timeZone` over `range`. A range across a DST change shows + * both offsets, e.g. "UTC-8/-7"; London's "UTC+0/+1". + */ +export function getTimeZoneRangeShortName( + timeZone: string, + [start, end]: readonly [Date, Date], +): string { + const startName = getTimeZoneShortName(timeZone, start); + const endName = getTimeZoneShortName(timeZone, end); + if (startName === endName) { + return startName; + } + const offsetOf = (name: string) => + name === 'UTC' ? '+0' : name.replace(/^UTC/, ''); + return `UTC${offsetOf(startName)}/${offsetOf(endName)}`; +} From 53dd9a15aad989902df8bbfed5fc8defa98ec865 Mon Sep 17 00:00:00 2001 From: Karl Power Date: Fri, 30 Oct 2026 12:05:29 +0100 Subject: [PATCH 4/4] fix: re-format the fullscreen tile's time range when the time zone changes --- packages/app/src/DBDashboardPage.tsx | 8 ++-- .../__tests__/useTimeRangeInputText.test.tsx | 46 +++++++++++++++++++ packages/app/src/timeQuery.ts | 27 +++++++++++ 3 files changed, 77 insertions(+), 4 deletions(-) create mode 100644 packages/app/src/__tests__/useTimeRangeInputText.test.tsx diff --git a/packages/app/src/DBDashboardPage.tsx b/packages/app/src/DBDashboardPage.tsx index 3126695466..dcb54893d9 100644 --- a/packages/app/src/DBDashboardPage.tsx +++ b/packages/app/src/DBDashboardPage.tsx @@ -236,6 +236,7 @@ import { parseRelativeTimeQuery, useDefaultTimeRange, useNewTimeQuery, + useTimeRangeInputText, } from './timeQuery'; import { TimeZoneOverrideProvider, @@ -545,9 +546,8 @@ const Tile = ({ // changing them does not propagate up to the dashboard. const [fullscreenDateRange, setFullscreenDateRange] = useState<[Date, Date]>(dateRange); - const [fullscreenInputValue, setFullscreenInputValue] = useState(() => - dateRangeToString(dateRange, timeZone), - ); + const [fullscreenInputValue, setFullscreenInputValue] = + useTimeRangeInputText(fullscreenDateRange); const [fullscreenGranularity, setFullscreenGranularity] = useState< Granularity | 'auto' | undefined >(() => (granularity as Granularity | undefined) ?? 'auto'); @@ -561,7 +561,7 @@ const Tile = ({ (granularity as Granularity | undefined) ?? 'auto', ); setIsFullscreen(true); - }, [dateRange, granularity, timeZone]); + }, [dateRange, granularity, timeZone, setFullscreenInputValue]); const handleFullscreenSearch = useCallback( (value: string) => { diff --git a/packages/app/src/__tests__/useTimeRangeInputText.test.tsx b/packages/app/src/__tests__/useTimeRangeInputText.test.tsx new file mode 100644 index 0000000000..2667c830e3 --- /dev/null +++ b/packages/app/src/__tests__/useTimeRangeInputText.test.tsx @@ -0,0 +1,46 @@ +import { act, renderHook } from '@testing-library/react'; + +import { useTimeRangeInputText } from '@/timeQuery'; + +let mockTimeZone: string | undefined = 'Etc/UTC'; +jest.mock('@/useDisplayTimeZone', () => ({ + useDisplayTimeZone: () => mockTimeZone, +})); + +const range: [Date, Date] = [ + new Date('2026-10-22T14:00:00Z'), + new Date('2026-10-22T15:00:00Z'), +]; + +describe('useTimeRangeInputText', () => { + beforeEach(() => { + jest.useFakeTimers().setSystemTime(new Date('2026-10-23T00:00:00Z')); + mockTimeZone = 'Etc/UTC'; + }); + + afterEach(() => { + jest.useRealTimers(); + }); + + it('formats the range in the display time zone', () => { + const { result } = renderHook(() => useTimeRangeInputText(range)); + expect(result.current[0]).toBe('Oct 22 14:00:00 - Oct 22 15:00:00'); + }); + + it('keeps edited text while the zone is unchanged', () => { + const { result, rerender } = renderHook(() => useTimeRangeInputText(range)); + act(() => result.current[1]('last monday')); + rerender(); + expect(result.current[0]).toBe('last monday'); + }); + + it('re-formats the range when the zone changes', () => { + const { result, rerender } = renderHook(() => useTimeRangeInputText(range)); + act(() => result.current[1]('last monday')); + + mockTimeZone = 'Asia/Tokyo'; + rerender(); + + expect(result.current[0]).toBe('Oct 22 23:00:00 - Oct 23 00:00:00'); + }); +}); diff --git a/packages/app/src/timeQuery.ts b/packages/app/src/timeQuery.ts index d13f525768..96a7fa9336 100644 --- a/packages/app/src/timeQuery.ts +++ b/packages/app/src/timeQuery.ts @@ -555,3 +555,30 @@ export function useDefaultTimeRange(query: string): [Date, Date] { return state.range; } + +/** + * Text for an editable time range input. It is re-formatted from `range` when + * the display time zone changes, so it never holds clock times from another + * zone that the picker would then read in the new one. + */ +export function useTimeRangeInputText( + range: [Date, Date], +): [string, (text: string) => void] { + const timeZone = useDisplayTimeZone(); + const [state, setState] = useState(() => ({ + text: dateRangeToString(range, timeZone), + timeZone, + })); + const setText = useCallback( + (text: string) => setState(prev => ({ ...prev, text })), + [], + ); + + if (state.timeZone !== timeZone) { + const next = { text: dateRangeToString(range, timeZone), timeZone }; + setState(next); + return [next.text, setText]; + } + + return [state.text, setText]; +}