diff --git a/.changeset/time-zone-preference.md b/.changeset/time-zone-preference.md new file mode 100644 index 0000000000..2bfe3a8342 --- /dev/null +++ b/.changeset/time-zone-preference.md @@ -0,0 +1,7 @@ +--- +'@hyperdx/common-utils': patch +'@hyperdx/app': patch +'@hyperdx/api': patch +--- + +refactor: Store the time display setting as a time zone instead of a UTC switch, converting existing settings, and remove the `isUTC` option from `formatDate` diff --git a/packages/api/src/tasks/checkAlerts/template.ts b/packages/api/src/tasks/checkAlerts/template.ts index 9b31304d4d..5cb3b148b3 100644 --- a/packages/api/src/tasks/checkAlerts/template.ts +++ b/packages/api/src/tasks/checkAlerts/template.ts @@ -3,7 +3,11 @@ import { Metadata } from '@hyperdx/common-utils/dist/core/metadata'; import { getPromqlSeries } from '@hyperdx/common-utils/dist/core/promql'; import { renderChartConfig } from '@hyperdx/common-utils/dist/core/renderChartConfig'; import { buildSearchChartConfig } from '@hyperdx/common-utils/dist/core/searchChartConfig'; -import { formatDate, objectHash } from '@hyperdx/common-utils/dist/core/utils'; +import { + formatDate, + objectHash, + UTC_TIME_ZONE, +} from '@hyperdx/common-utils/dist/core/utils'; import { isPromqlSavedChartConfig, isRawSqlSavedChartConfig, @@ -881,9 +885,9 @@ export const renderAlertTemplate = async ({ }; const timeRangeMessage = `Time Range (UTC): [${formatDate(view.startTime, { - isUTC: true, + timeZone: UTC_TIME_ZONE, })} - ${formatDate(view.endTime, { - isUTC: true, + timeZone: UTC_TIME_ZONE, })})`; let rawTemplateBody; diff --git a/packages/app/src/UserPreferencesModal.tsx b/packages/app/src/UserPreferencesModal.tsx index 5683706dd7..3c46ad17c2 100644 --- a/packages/app/src/UserPreferencesModal.tsx +++ b/packages/app/src/UserPreferencesModal.tsx @@ -1,5 +1,6 @@ import * as React from 'react'; import { Badge } from '@clickhouse/click-ui'; +import { UTC_TIME_ZONE } from '@hyperdx/common-utils/dist/core/utils'; import { Autocomplete, Divider, @@ -19,6 +20,7 @@ import { } from './config/fonts'; import { useAppTheme } from './theme/ThemeProvider'; import { isValidThemeName, themes } from './theme'; +import { LOCAL_TIME_ZONE } from './timeZone'; import { DEFAULT_ROW_CLICK_ACTION, RowClickAction, @@ -114,10 +116,12 @@ export const UserPreferencesModal = ({ setUserPreference({ - isUTC: e.currentTarget.checked, + timeZone: e.currentTarget.checked + ? UTC_TIME_ZONE + : LOCAL_TIME_ZONE, }) } /> diff --git a/packages/app/src/__tests__/timeZone.test.ts b/packages/app/src/__tests__/timeZone.test.ts new file mode 100644 index 0000000000..4c039440cf --- /dev/null +++ b/packages/app/src/__tests__/timeZone.test.ts @@ -0,0 +1,38 @@ +import { + getTimeZoneShortName, + isValidTimeZone, + LOCAL_TIME_ZONE, + resolveTimeZonePreference, +} from '@/timeZone'; + +describe('resolveTimeZonePreference', () => { + it('returns undefined for the local setting', () => { + expect(resolveTimeZonePreference(LOCAL_TIME_ZONE)).toBeUndefined(); + }); + + it('returns a valid IANA name', () => { + expect(resolveTimeZonePreference('Etc/UTC')).toBe('Etc/UTC'); + expect(resolveTimeZonePreference('Asia/Tokyo')).toBe('Asia/Tokyo'); + }); + + it('falls back to local for a zone the browser does not recognise', () => { + expect(isValidTimeZone('Mars/Olympus_Mons')).toBe(false); + expect(resolveTimeZonePreference('Mars/Olympus_Mons')).toBeUndefined(); + }); +}); + +describe('getTimeZoneShortName', () => { + it('uses the abbreviation in effect on the date', () => { + expect( + getTimeZoneShortName('America/Los_Angeles', new Date('2026-07-01Z')), + ).toBe('PDT'); + expect( + getTimeZoneShortName('America/Los_Angeles', new Date('2026-12-01Z')), + ).toBe('PST'); + }); + + it('names UTC and zones without an abbreviation', () => { + expect(getTimeZoneShortName('Etc/UTC')).toBe('UTC'); + expect(getTimeZoneShortName('Asia/Tokyo')).toBe('GMT+9'); + }); +}); diff --git a/packages/app/src/__tests__/useUserPreferences.test.tsx b/packages/app/src/__tests__/useUserPreferences.test.tsx index 10720d79f0..86b89955db 100644 --- a/packages/app/src/__tests__/useUserPreferences.test.tsx +++ b/packages/app/src/__tests__/useUserPreferences.test.tsx @@ -60,7 +60,7 @@ describe('migrateUserPreferences', () => { const result = migrateUserPreferences(legacyData); expect(result).toEqual({ - isUTC: false, + timeZone: 'local', timeFormat: '12h', colorMode: 'dark', font: 'IBM Plex Mono', @@ -84,7 +84,7 @@ describe('migrateUserPreferences', () => { const result = migrateUserPreferences(legacyData); expect(result).toEqual({ - isUTC: true, + timeZone: 'Etc/UTC', timeFormat: '24h', colorMode: 'light', font: 'Inter', @@ -137,7 +137,7 @@ describe('migrateUserPreferences', () => { const result = migrateUserPreferences(legacyData); expect(result).toEqual({ - isUTC: true, + timeZone: 'Etc/UTC', timeFormat: '24h', colorMode: 'light', font: 'Roboto Mono', @@ -154,7 +154,7 @@ describe('migrateUserPreferences', () => { const result = migrateUserPreferences(legacyData); expect(result).toEqual({ - isUTC: false, // From DEFAULT_PREFERENCES + timeZone: 'local', // From DEFAULT_PREFERENCES timeFormat: '12h', // From DEFAULT_PREFERENCES colorMode: 'dark', // Migrated from theme font: 'IBM Plex Mono', // From DEFAULT_PREFERENCES @@ -221,7 +221,7 @@ describe('migrateUserPreferences', () => { const result = migrateUserPreferences(partialData); expect(result).toEqual({ - isUTC: false, // From DEFAULT_PREFERENCES + timeZone: 'local', // From DEFAULT_PREFERENCES timeFormat: '12h', // From DEFAULT_PREFERENCES colorMode: 'light', // Migrated from theme font: 'IBM Plex Mono', // From DEFAULT_PREFERENCES @@ -241,7 +241,7 @@ describe('migrateUserPreferences', () => { const result = migrateUserPreferences(legacyData); expect(result).toEqual({ - isUTC: false, + timeZone: 'local', timeFormat: '12h', colorMode: 'dark', font: 'IBM Plex Mono', @@ -254,7 +254,7 @@ describe('migrateUserPreferences', () => { describe('Migration idempotency', () => { it('should return already migrated data unchanged', () => { const migratedData: UserPreferences = { - isUTC: false, + timeZone: 'local', timeFormat: '12h', colorMode: 'dark', font: 'IBM Plex Mono', @@ -269,7 +269,7 @@ describe('migrateUserPreferences', () => { it('should accept colorMode "system" as valid', () => { const dataWithSystem: UserPreferences = { - isUTC: false, + timeZone: 'local', timeFormat: '12h', colorMode: 'system', font: 'IBM Plex Mono', @@ -286,7 +286,7 @@ describe('migrateUserPreferences', () => { const mixedData = JSON.stringify({ theme: 'light', colorMode: 'dark', - isUTC: false, + timeZone: 'local', timeFormat: '12h', font: 'IBM Plex Mono', }); @@ -323,6 +323,53 @@ describe('migrateUserPreferences', () => { }); }); + describe('isUTC migration (isUTC → timeZone)', () => { + it.each([ + [true, 'Etc/UTC'], + [false, 'local'], + ])('replaces isUTC=%s with timeZone=%s and saves it', (isUTC, timeZone) => { + const stored = JSON.stringify({ + isUTC, + timeFormat: '24h', + colorMode: 'dark', + font: 'Inter', + }); + + const result = migrateUserPreferences(stored); + + expect(result).toEqual({ + timeZone, + timeFormat: '24h', + colorMode: 'dark', + font: 'Inter', + }); + expect(localStorageMock.setItem).toHaveBeenCalledWith( + STORAGE_KEY, + JSON.stringify(result), + ); + }); + + it('defaults to local when neither isUTC nor timeZone is stored', () => { + const result = migrateUserPreferences( + JSON.stringify({ colorMode: 'dark', timeFormat: '12h' }), + ); + expect(result?.timeZone).toBe('local'); + }); + + it('keeps a stored timeZone over isUTC', () => { + const result = migrateUserPreferences( + JSON.stringify({ + isUTC: true, + timeZone: 'Asia/Tokyo', + colorMode: 'dark', + timeFormat: '12h', + }), + ); + expect(result?.timeZone).toBe('Asia/Tokyo'); + expect(result).not.toHaveProperty('isUTC'); + }); + }); + describe('localStorage error handling', () => { it('should handle localStorage.setItem errors gracefully', () => { localStorageMock.setItem.mockImplementation(() => { @@ -339,7 +386,7 @@ describe('migrateUserPreferences', () => { // Should not throw, should return migrated data even if save fails const result = migrateUserPreferences(legacyData); expect(result).toEqual({ - isUTC: false, + timeZone: 'local', timeFormat: '12h', colorMode: 'dark', font: 'IBM Plex Mono', @@ -365,7 +412,7 @@ describe('migrateUserPreferences', () => { // Should not throw - should return migrated data const result = migrateUserPreferences(legacyData); expect(result).toEqual({ - isUTC: false, + timeZone: 'local', timeFormat: '12h', colorMode: 'dark', font: 'IBM Plex Mono', diff --git a/packages/app/src/components/AppNav/AppNav.tsx b/packages/app/src/components/AppNav/AppNav.tsx index 3f5b1f12c9..9db1e68f31 100644 --- a/packages/app/src/components/AppNav/AppNav.tsx +++ b/packages/app/src/components/AppNav/AppNav.tsx @@ -40,8 +40,9 @@ import InstallInstructionModal from '@/InstallInstructionsModal'; import OnboardingChecklist from '@/OnboardingChecklist'; import { useSavedSearches } from '@/savedSearch'; import { useLogomark, useWordmark } from '@/theme/ThemeProvider'; +import { getTimeZoneShortName } from '@/timeZone'; +import { useDisplayTimeZone } from '@/useDisplayTimeZone'; import { UserPreferencesModal } from '@/UserPreferencesModal'; -import { useUserPreferences } from '@/useUserPreferences'; import { AppNavCloudBanner, @@ -276,9 +277,8 @@ export default function AppNav({ fixed = false }: { fixed?: boolean }) { { close: closeUserPreferences, open: openUserPreferences }, ] = useDisclosure(false); - const { - userPreferences: { isUTC }, - } = useUserPreferences(); + const timeZone = useDisplayTimeZone(); + const timeZoneShortName = timeZone && getTimeZoneShortName(timeZone); const [ showInstallInstructions, @@ -373,12 +373,12 @@ export default function AppNav({ fixed = false }: { fixed?: boolean }) { would be redundant and crowd this already-tight row. */} ) } diff --git a/packages/app/src/components/DBRowTable.tsx b/packages/app/src/components/DBRowTable.tsx index 6e5885b4a8..69e9a15d80 100644 --- a/packages/app/src/components/DBRowTable.tsx +++ b/packages/app/src/components/DBRowTable.tsx @@ -95,6 +95,8 @@ import { MIN_LAST_COLUMN_WIDTH, UNDEFINED_WIDTH, } from '@/tableUtils'; +import { getTimeZoneShortName } from '@/timeZone'; +import { useDisplayTimeZone } from '@/useDisplayTimeZone'; import { FormatTime } from '@/useFormatTime'; import { DEFAULT_ROW_CLICK_ACTION, @@ -464,8 +466,9 @@ export const RawLogTable = memo( ); const { - userPreferences: { isUTC, rowClickAction }, + userPreferences: { rowClickAction }, } = useUserPreferences(); + const timeZone = useDisplayTimeZone(); const { scale: contentFontScale } = useContentFontSize(); // The ClickHouse dashboard's slow-query list has no side panel to open, so @@ -672,7 +675,7 @@ export const RawLogTable = memo( // TODO: add support for sorting on Dynamic JSON fields enableSorting: jsColumnType !== JSDataType.Dynamic, accessorFn: curry(retrieveColumnValue)(column), // Columns can contain '.' and will not work with accessorKey - header: `${columnNameMap?.[column] ?? column}${isDate ? (isUTC ? ' (UTC)' : ' (Local)') : ''}`, + header: `${columnNameMap?.[column] ?? column}${isDate ? ` (${timeZone ? getTimeZoneShortName(timeZone) : 'Local'})` : ''}`, cell: info => { const value = info.getValue(); // This can be any type realistically (numbers, strings, etc.) @@ -743,7 +746,7 @@ export const RawLogTable = memo( }) as ColumnDef[]), ], [ - isUTC, + timeZone, highlightedLineId, displayedColumns, columnSizeOpts, diff --git a/packages/app/src/timeZone.ts b/packages/app/src/timeZone.ts new file mode 100644 index 0000000000..cb904975b8 --- /dev/null +++ b/packages/app/src/timeZone.ts @@ -0,0 +1,46 @@ +import { UTC_TIME_ZONE } from '@hyperdx/common-utils/dist/core/utils'; + +/** Time zone setting value that follows the browser's zone. */ +export const LOCAL_TIME_ZONE = 'local'; + +export function isValidTimeZone(timeZone: string): boolean { + try { + new Intl.DateTimeFormat('en-US', { timeZone }); + return true; + } catch { + return false; + } +} + +/** + * The IANA zone a setting refers to, or undefined for the local zone. Zones + * the browser doesn't recognise fall back to local. + */ +export function resolveTimeZonePreference( + preference: string, +): string | undefined { + return preference !== LOCAL_TIME_ZONE && isValidTimeZone(preference) + ? preference + : undefined; +} + +/** The setting that `isUTC`, the switch that predates it, maps to. */ +export function timeZonePreferenceFromIsUTC(isUTC: unknown) { + return isUTC === true ? UTC_TIME_ZONE : LOCAL_TIME_ZONE; +} + +/** + * Short name of `timeZone` at `date`, e.g. "UTC", "PDT" or "GMT+9". en-US is + * used because it has abbreviations for the most zones. + */ +export function getTimeZoneShortName( + timeZone: string, + // eslint-disable-next-line no-restricted-syntax + date: Date = new Date(), +): string { + return ( + new Intl.DateTimeFormat('en-US', { timeZone, timeZoneName: 'short' }) + .formatToParts(date) + .find(part => part.type === 'timeZoneName')?.value ?? timeZone + ); +} diff --git a/packages/app/src/useDisplayTimeZone.ts b/packages/app/src/useDisplayTimeZone.ts index fd830a811c..ce39ceea24 100644 --- a/packages/app/src/useDisplayTimeZone.ts +++ b/packages/app/src/useDisplayTimeZone.ts @@ -1,5 +1,6 @@ -import { UTC_TIME_ZONE } from '@hyperdx/common-utils/dist/core/utils'; +import { useMemo } from 'react'; +import { resolveTimeZonePreference } from './timeZone'; import { useUserPreferences } from './useUserPreferences'; /** @@ -8,7 +9,7 @@ import { useUserPreferences } from './useUserPreferences'; */ export function useDisplayTimeZone(): string | undefined { const { - userPreferences: { isUTC }, + userPreferences: { timeZone }, } = useUserPreferences(); - return isUTC ? UTC_TIME_ZONE : undefined; + return useMemo(() => resolveTimeZonePreference(timeZone), [timeZone]); } diff --git a/packages/app/src/useFormatTime.tsx b/packages/app/src/useFormatTime.tsx index 3d76e7c0bf..59019a0651 100644 --- a/packages/app/src/useFormatTime.tsx +++ b/packages/app/src/useFormatTime.tsx @@ -1,6 +1,7 @@ import React from 'react'; import { formatDate } from '@hyperdx/common-utils/dist/core/utils'; +import { useDisplayTimeZone } from './useDisplayTimeZone'; import { useUserPreferences } from './useUserPreferences'; type DateLike = number | string | Date; @@ -16,8 +17,9 @@ const parse = (time: DateLike) => { export const useFormatTime = () => { const { - userPreferences: { isUTC, timeFormat }, + userPreferences: { timeFormat }, } = useUserPreferences(); + const timeZone = useDisplayTimeZone(); return React.useCallback( (time: DateLike, { format }: { format?: DateFormat } | undefined = {}) => { @@ -25,7 +27,7 @@ export const useFormatTime = () => { const date = parse(time); return formatDate(date, { clock: timeFormat, - isUTC, + timeZone, format, }); } catch (err) { @@ -33,7 +35,7 @@ export const useFormatTime = () => { return 'Unknown date'; } }, - [isUTC, timeFormat], + [timeZone, timeFormat], ); }; diff --git a/packages/app/src/useUserPreferences.tsx b/packages/app/src/useUserPreferences.tsx index e91510ad6e..88c5ac297b 100644 --- a/packages/app/src/useUserPreferences.tsx +++ b/packages/app/src/useUserPreferences.tsx @@ -9,6 +9,7 @@ import { DEFAULT_CONTENT_FONT_SIZE, isContentFontSize, } from '@/config/fonts'; +import { LOCAL_TIME_ZONE, timeZonePreferenceFromIsUTC } from '@/timeZone'; type ColorModePreference = 'light' | 'dark' | 'system'; @@ -18,7 +19,11 @@ export type RowClickAction = 'expand' | 'sidePanel'; export const DEFAULT_ROW_CLICK_ACTION: RowClickAction = 'sidePanel'; export type UserPreferences = { - isUTC: boolean; + /** + * Zone that times are shown and typed in: `LOCAL_TIME_ZONE`, or an IANA + * name such as `Etc/UTC`. Read it via `useDisplayTimeZone`. + */ + timeZone: string; timeFormat: '12h' | '24h'; /** Color mode preference (light/dark/system). Separate from brand theme (hyperdx/clickstack). */ colorMode: ColorModePreference; @@ -44,7 +49,7 @@ type LegacyUserPreferences = Omit & { const STORAGE_KEY = 'hdx-user-preferences'; const DEFAULT_PREFERENCES: UserPreferences = { - isUTC: false, + timeZone: LOCAL_TIME_ZONE, timeFormat: '12h', colorMode: 'system', font: 'IBM Plex Mono', @@ -97,8 +102,44 @@ function isLegacyUserPreferences(obj: unknown): obj is LegacyUserPreferences { ); } +/** Replaces `isUTC`, the switch that predates `timeZone`, with `timeZone`. */ +function withTimeZone( + prefs: T, +): Omit & { timeZone: string } { + const { isUTC, timeZone, ...rest } = prefs; + return { + ...rest, + timeZone: + typeof timeZone === 'string' + ? timeZone + : timeZonePreferenceFromIsUTC(isUTC), + }; +} + +function needsTimeZoneMigration(prefs: { + isUTC?: unknown; + timeZone?: unknown; +}): boolean { + return 'isUTC' in prefs || typeof prefs.timeZone !== 'string'; +} + +// Only writes when the value differs, to avoid a write on every read. +function saveMigrated(migrated: UserPreferences) { + try { + if (typeof window !== 'undefined') { + const migratedJson = JSON.stringify(migrated); + if (localStorage.getItem(STORAGE_KEY) !== migratedJson) { + localStorage.setItem(STORAGE_KEY, migratedJson); + } + } + } catch { + // Ignore localStorage errors (private browsing, etc.) + } +} + /** - * Migrates old localStorage data from `theme` to `colorMode`. + * Migrates old localStorage data from `theme` to `colorMode`, and from + * `isUTC` to `timeZone`. * This ensures existing users don't lose their light/dark mode preference. * * Uses an in-memory cache to avoid repeated localStorage writes on every read. @@ -131,24 +172,10 @@ export function migrateUserPreferences( theme === 'light' || theme === 'dark' ? theme : 'dark'; const migrated: UserPreferences = { ...DEFAULT_PREFERENCES, - ...rest, + ...withTimeZone(rest), colorMode: validTheme, }; - - // Only write to localStorage if the migrated data differs from what's stored - // This prevents unnecessary writes on every render and avoids race conditions - try { - if (typeof window !== 'undefined') { - const migratedJson = JSON.stringify(migrated); - // Compare with current stored value to avoid unnecessary write - const currentStored = localStorage.getItem(STORAGE_KEY); - if (currentStored !== migratedJson) { - localStorage.setItem(STORAGE_KEY, migratedJson); - } - } - } catch { - // Ignore localStorage errors (private browsing, etc.) - } + saveMigrated(migrated); // Cache the result to avoid re-processing on subsequent calls migrationCache = { @@ -161,12 +188,18 @@ export function migrateUserPreferences( // Already migrated or new format - validate it's a proper UserPreferences if (isUserPreferences(parsed)) { + const result = needsTimeZoneMigration(parsed) + ? withTimeZone(parsed) + : parsed; + if (result !== parsed) { + saveMigrated(result); + } // Cache the result to avoid re-processing on subsequent calls migrationCache = { storedValue: stored, - result: parsed, + result, }; - return parsed; + return result; } // Invalid format, return null to use defaults diff --git a/packages/common-utils/src/__tests__/utils.test.ts b/packages/common-utils/src/__tests__/utils.test.ts index 05842a0e10..ee0ae6eae0 100644 --- a/packages/common-utils/src/__tests__/utils.test.ts +++ b/packages/common-utils/src/__tests__/utils.test.ts @@ -31,6 +31,7 @@ import { splitAndTrimCSV, splitAndTrimWithBracket, toWallClock, + UTC_TIME_ZONE, } from '@/core/utils'; import { isBuilderSavedChartConfig } from '@/guards'; import { @@ -60,7 +61,7 @@ describe('utils', () => { expect( formatDate(date, { clock: '12h', - isUTC: true, + timeZone: UTC_TIME_ZONE, }), ).toEqual('Jan 1 12:00:00 PM'); }); @@ -70,7 +71,7 @@ describe('utils', () => { expect( formatDate(date, { clock: '24h', - isUTC: true, + timeZone: UTC_TIME_ZONE, format: 'withMs', }), ).toEqual('Jan 1 12:00:00.000'); @@ -81,7 +82,6 @@ describe('utils', () => { expect( formatDate(date, { clock: '12h', - isUTC: false, }), ).toEqual('Jan 1 12:00:00 PM'); }); @@ -91,7 +91,6 @@ describe('utils', () => { expect( formatDate(date, { clock: '24h', - isUTC: false, format: 'withMs', }), ).toEqual('Jan 1 12:00:00.000'); @@ -103,17 +102,6 @@ describe('utils', () => { formatDate(date, { clock: '24h', timeZone: 'Asia/Tokyo' }), ).toEqual('Jan 1 21:00:00'); }); - - it('prefers timeZone over isUTC', () => { - const date = new Date('2021-01-01T12:00:00Z'); - expect( - formatDate(date, { - clock: '24h', - isUTC: true, - timeZone: 'America/Los_Angeles', - }), - ).toEqual('Jan 1 04:00:00'); - }); }); describe('toWallClock / fromWallClock', () => { diff --git a/packages/common-utils/src/core/utils.ts b/packages/common-utils/src/core/utils.ts index 3fba09931b..0042b9da81 100644 --- a/packages/common-utils/src/core/utils.ts +++ b/packages/common-utils/src/core/utils.ts @@ -762,29 +762,23 @@ const TIME_TOKENS = { export const UTC_TIME_ZONE = 'Etc/UTC'; -/** - * Formats `date` in `timeZone` (an IANA name). `isUTC` is shorthand for - * `timeZone: UTC_TIME_ZONE`; with neither set, the local zone is used. - */ +/** Formats `date` in `timeZone` (an IANA name), or the local zone if unset. */ export const formatDate = ( date: Date, { - isUTC = false, timeZone, format = 'normal', clock = '12h', }: { - isUTC?: boolean; timeZone?: string; format?: 'normal' | 'short' | 'withMs' | 'time' | 'withYear'; clock?: '12h' | '24h'; }, ) => { const formatStr = TIME_TOKENS[format][clock]; - const zone = timeZone ?? (isUTC ? UTC_TIME_ZONE : undefined); - return zone - ? formatInTimeZone(date, zone, formatStr) + return timeZone + ? formatInTimeZone(date, timeZone, formatStr) : fnsFormat(date, formatStr); };