From b4e079759662ed33f60e09afda95b793944f2f2c Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 25 Nov 2026 20:59:02 +0000 Subject: [PATCH 1/3] fix(app): label year-scale time charts by month and year Time charts spanning a year or more now place x-axis ticks on month starts labelled like 'Mar 2024', and tooltips include the year ('2024-03-18' for daily or coarser buckets). Shorter ranges keep their existing formats. Co-authored-by: Mike Shi --- .changeset/year-scale-chart-dates.md | 9 + .../ChartTooltipContent.tsx | 4 + .../src/HDXMultiSeriesTimeChart/MemoChart.tsx | 25 ++- .../__tests__/HDXMultiSeriesTimeChart.test.ts | 163 ++++++++++++++++++ .../src/HDXMultiSeriesTimeChart/axisTicks.ts | 125 +++++++++++++- .../app/src/HDXMultiSeriesTimeChart/index.ts | 3 + .../DBTimeChart/ChartTooltipOverlay.tsx | 7 +- .../components/DBTimeChart/DBTimeChart.tsx | 7 +- .../components/charts/ChartSeriesTooltip.tsx | 5 + .../src/components/charts/ChartTooltip.tsx | 15 +- packages/app/src/useFormatTime.tsx | 13 +- .../common-utils/src/__tests__/utils.test.ts | 14 ++ packages/common-utils/src/core/utils.ts | 12 +- 13 files changed, 381 insertions(+), 21 deletions(-) create mode 100644 .changeset/year-scale-chart-dates.md diff --git a/.changeset/year-scale-chart-dates.md b/.changeset/year-scale-chart-dates.md new file mode 100644 index 0000000000..41b86b74ee --- /dev/null +++ b/.changeset/year-scale-chart-dates.md @@ -0,0 +1,9 @@ +--- +'@hyperdx/common-utils': patch +'@hyperdx/app': patch +--- + +fix: label time charts spanning a year or more by month and year. X-axis ticks +sit on month starts and read like `Mar 2024`, and tooltips show the year +(`2024-03-18`, without a time of day for daily or coarser buckets). Shorter +ranges keep their existing formats. diff --git a/packages/app/src/HDXMultiSeriesTimeChart/ChartTooltipContent.tsx b/packages/app/src/HDXMultiSeriesTimeChart/ChartTooltipContent.tsx index ad844cff0b..4547bc022d 100644 --- a/packages/app/src/HDXMultiSeriesTimeChart/ChartTooltipContent.tsx +++ b/packages/app/src/HDXMultiSeriesTimeChart/ChartTooltipContent.tsx @@ -9,6 +9,7 @@ import { useChartTooltipZIndex, } from '@/components/charts/ChartTooltip'; import type { NumberFormat } from '@/types'; +import type { DateFormat } from '@/useFormatTime'; import { getVisibleTooltipRows } from './chartData'; import { @@ -23,6 +24,7 @@ import styles from '@styles/HDXLineChart.module.scss'; type HDXLineChartTooltipProps = { lineDataMap: { [keyName: string]: LineData }; previousPeriodOffsetSeconds?: number; + dateFormat?: DateFormat; numberFormat?: NumberFormat; numberFormatByKey: Map; /** Per-series active-point pixel Y, captured by the Area active dots. */ @@ -53,6 +55,7 @@ export const HDXLineChartTooltip = withErrorBoundary( numberFormatByKey, lineDataMap, previousPeriodOffsetSeconds, + dateFormat, activePointYByKeyRef, containerRef, } = props; @@ -76,6 +79,7 @@ export const HDXLineChartTooltip = withErrorBoundary( ); diff --git a/packages/app/src/HDXMultiSeriesTimeChart/MemoChart.tsx b/packages/app/src/HDXMultiSeriesTimeChart/MemoChart.tsx index dd80d030ab..0ac4e40d9a 100644 --- a/packages/app/src/HDXMultiSeriesTimeChart/MemoChart.tsx +++ b/packages/app/src/HDXMultiSeriesTimeChart/MemoChart.tsx @@ -49,7 +49,11 @@ import { COLORS } from '@/utils'; import { compactTickAnchor, formatAxisTick, + getMonthStartTicks, + getTooltipDateFormat, getXAxisTickDateFormat, + isYearScaleRange, + MONTH_TICK_MIN_GAP_PX, } from './axisTicks'; import { type ActiveClickPayload, @@ -461,6 +465,7 @@ export const MemoChart = memo(function MemoChart({ const formatTime = useFormatTime(); const displayTimeZone = useDisplayTimeZone(); + const yearScale = isYearScaleRange(dateRange); const xTickFormatter = useCallback( (value: number, index: number) => { return formatTime(value * 1000, { @@ -469,10 +474,22 @@ export const MemoChart = memo(function MemoChart({ index, granularity, timeZone: displayTimeZone, + yearScale, }), }); }, - [formatTime, granularity, displayTimeZone], + [formatTime, granularity, displayTimeZone, yearScale], + ); + const xAxisTicks = useMemo( + () => + yearScale + ? getMonthStartTicks({ + domain: xAxisDomain, + timeZone: displayTimeZone, + plotWidth: containerWidth - yAxisWidth, + }) + : undefined, + [yearScale, xAxisDomain, displayTimeZone, containerWidth, yAxisWidth], ); // Compact mode: anchor the first label to the start and the last to the end @@ -579,6 +596,7 @@ export const MemoChart = memo(function MemoChart({ return map; }, [lineData]); + const tooltipDateFormat = getTooltipDateFormat({ dateRange, granularity }); // Memoize the tooltip `content` element: recharts re-evaluates it every hover // frame, so a fresh element each render defeats HDXLineChartTooltip's memo. // Refs are stable, so only the listed values are deps. @@ -589,6 +607,7 @@ export const MemoChart = memo(function MemoChart({ numberFormatByKey={tooltipNumberFormatsByKey} lineDataMap={lineDataMap} previousPeriodOffsetSeconds={previousPeriodOffsetSeconds} + dateFormat={tooltipDateFormat} activePointYByKeyRef={activePointYByKeyRef} containerRef={containerRef} /> @@ -598,6 +617,7 @@ export const MemoChart = memo(function MemoChart({ tooltipNumberFormatsByKey, lineDataMap, previousPeriodOffsetSeconds, + tooltipDateFormat, ], ); @@ -901,8 +921,9 @@ export const MemoChart = memo(function MemoChart({ interval="preserveStartEnd" scale="time" type="number" + ticks={xAxisTicks} tickFormatter={xTickFormatter} - minTickGap={100} + minTickGap={xAxisTicks ? MONTH_TICK_MIN_GAP_PX : 100} tick={ compactXAxisLabels ? renderCompactXTick diff --git a/packages/app/src/HDXMultiSeriesTimeChart/__tests__/HDXMultiSeriesTimeChart.test.ts b/packages/app/src/HDXMultiSeriesTimeChart/__tests__/HDXMultiSeriesTimeChart.test.ts index 23fe5c85c9..c9da97ae47 100644 --- a/packages/app/src/HDXMultiSeriesTimeChart/__tests__/HDXMultiSeriesTimeChart.test.ts +++ b/packages/app/src/HDXMultiSeriesTimeChart/__tests__/HDXMultiSeriesTimeChart.test.ts @@ -19,13 +19,16 @@ import { formatAxisTick, getExpandableYAxisTicks, getLineCurveType, + getMonthStartTicks, getNiceYAxisTicks, getSelectedLineData, + getTooltipDateFormat, getVisibleLineData, getVisibleTooltipRows, getXAxisTickDateFormat, getYAxisTicks, HARD_LINES_LIMIT, + isYearScaleRange, sameActiveClickSeries, scanStackedYAxisValueRange, scanYAxisValueRange, @@ -1437,4 +1440,164 @@ describe('getXAxisTickDateFormat', () => { }), ).toBe('time'); }); + + it.each(['1 hour', '1 day', '30 day'])( + 'shows the month and year on every tick of a year-scale range at %s granularity', + granularity => { + for (const index of [0, 1]) { + expect( + getXAxisTickDateFormat({ + tickSeconds: seconds('2026-10-27T04:00:00Z'), + index, + granularity, + timeZone: 'America/New_York', + yearScale: true, + }), + ).toBe('monthYear'); + } + }, + ); +}); + +describe('isYearScaleRange', () => { + it('starts at a year', () => { + expect( + isYearScaleRange([ + new Date('2025-03-01T00:00:00Z'), + new Date('2026-03-01T00:00:00Z'), + ]), + ).toBe(true); + expect( + isYearScaleRange([ + new Date('2025-03-02T00:00:00Z'), + new Date('2026-03-01T00:00:00Z'), + ]), + ).toBe(false); + }); +}); + +describe('getTooltipDateFormat', () => { + const twoYears: [Date, Date] = [ + new Date('2024-11-25T00:00:00Z'), + new Date('2026-11-25T00:00:00Z'), + ]; + + it('keeps the default format below a year', () => { + expect( + getTooltipDateFormat({ + dateRange: [new Date('2026-10-01'), new Date('2026-11-01')], + granularity: '1 day', + }), + ).toBe('normal'); + }); + + it('shows only the date with the year for daily or coarser buckets', () => { + expect( + getTooltipDateFormat({ dateRange: twoYears, granularity: '30 day' }), + ).toBe('isoDate'); + expect( + getTooltipDateFormat({ dateRange: twoYears, granularity: '1 day' }), + ).toBe('isoDate'); + }); + + it('keeps the time, with the year, for sub-day buckets', () => { + expect( + getTooltipDateFormat({ dateRange: twoYears, granularity: '1 hour' }), + ).toBe('withYear'); + }); +}); + +describe('getMonthStartTicks', () => { + const seconds = (iso: string) => new Date(iso).getTime() / 1000; + const iso = (ticks: number[] | undefined) => + ticks?.map(t => new Date(t * 1000).toISOString()); + const twoYears: [number, number] = [ + seconds('2024-11-25T00:00:00Z'), + seconds('2026-11-25T00:00:00Z'), + ]; + + it('returns undefined before the chart is measured', () => { + expect( + getMonthStartTicks({ + domain: twoYears, + timeZone: 'Etc/UTC', + plotWidth: 0, + }), + ).toBeUndefined(); + }); + + it('places ticks on month starts at the smallest step that fits', () => { + // 500px fits 5 ticks, so 25 months need a 6-month step. + expect( + iso( + getMonthStartTicks({ + domain: twoYears, + timeZone: 'Etc/UTC', + plotWidth: 500, + }), + ), + ).toEqual([ + '2025-01-01T00:00:00.000Z', + '2025-07-01T00:00:00.000Z', + '2026-01-01T00:00:00.000Z', + '2026-07-01T00:00:00.000Z', + ]); + }); + + it('keeps two ticks on a narrow chart', () => { + expect( + iso( + getMonthStartTicks({ + domain: twoYears, + timeZone: 'Etc/UTC', + plotWidth: 280, + }), + ), + ).toEqual(['2025-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z']); + }); + + it('uses every month when there is room', () => { + const ticks = getMonthStartTicks({ + domain: twoYears, + timeZone: 'Etc/UTC', + plotWidth: 4000, + }); + expect(ticks).toHaveLength(24); + expect(iso(ticks)?.[0]).toBe('2024-12-01T00:00:00.000Z'); + }); + + it('uses midnight in the display time zone, across DST changes', () => { + expect( + iso( + getMonthStartTicks({ + domain: twoYears, + timeZone: 'America/New_York', + plotWidth: 500, + }), + ), + ).toEqual([ + '2025-01-01T05:00:00.000Z', + '2025-07-01T04:00:00.000Z', + '2026-01-01T05:00:00.000Z', + '2026-07-01T04:00:00.000Z', + ]); + }); + + it('steps by whole years on very long ranges', () => { + const ticks = getMonthStartTicks({ + domain: [ + seconds('2016-06-01T00:00:00Z'), + seconds('2026-06-01T00:00:00Z'), + ], + timeZone: 'Etc/UTC', + plotWidth: 500, + }); + expect(iso(ticks)).toEqual([ + '2018-01-01T00:00:00.000Z', + '2020-01-01T00:00:00.000Z', + '2022-01-01T00:00:00.000Z', + '2024-01-01T00:00:00.000Z', + '2026-01-01T00:00:00.000Z', + ]); + }); }); diff --git a/packages/app/src/HDXMultiSeriesTimeChart/axisTicks.ts b/packages/app/src/HDXMultiSeriesTimeChart/axisTicks.ts index 16e9ea3700..cb919b2bcf 100644 --- a/packages/app/src/HDXMultiSeriesTimeChart/axisTicks.ts +++ b/packages/app/src/HDXMultiSeriesTimeChart/axisTicks.ts @@ -1,6 +1,7 @@ import { getTickValuesFixedDomain } from 'recharts/lib/util/scale/getNiceTickValues'; import { convertGranularityToSeconds, + fromWallClock, toWallClock, } from '@hyperdx/common-utils/dist/core/utils'; @@ -367,25 +368,139 @@ export function compactTickAnchor( } const SECONDS_PER_DAY = 24 * 60 * 60; +const SECONDS_PER_YEAR = 365 * SECONDS_PER_DAY; /** - * Format for an x-axis tick label. Below daily granularity the first tick - * carries the date and the rest only the time. At daily granularity or coarser - * every tick carries the date, plus the time when the bucket does not start at - * midnight in `timeZone` (buckets are UTC-aligned, so this happens in most - * zones). An undefined `timeZone` means the browser's zone. + * Whether a chart's date range is long enough to label by month and year: + * at a year or more, day-level tick labels repeat across years and a time of + * day is noise. + */ +export function isYearScaleRange( + dateRange: readonly [Date, Date] | Readonly<[Date, Date]>, +): boolean { + return ( + (dateRange[1].getTime() - dateRange[0].getTime()) / 1000 >= SECONDS_PER_YEAR + ); +} + +// Month steps for year-scale ticks; each divides 12 or is a whole number of +// years, so ticks land on the same months every year. +const MONTH_TICK_STEPS = [1, 2, 3, 6, 12, 24, 60, 120]; + +const MIN_MONTH_TICK_SPACING_PX = 100; + +/** + * XAxis minTickGap to use with getMonthStartTicks. Those ticks are already + * spaced for their labels; the default gap (label width + 100px) would make + * Recharts drop some of them and leave the rest unevenly spaced. + */ +export const MONTH_TICK_MIN_GAP_PX = 16; + +/** + * X-axis ticks for a year-scale chart: the first instant of a month in + * `timeZone`, every `step` months, choosing the smallest step that fits + * `plotWidth`. Recharts' own time ticks land at arbitrary instants on a + * seconds-valued axis, which would label "Mar 2024" partway through March. + * Returns undefined (let Recharts choose) before the chart is measured. + */ +export function getMonthStartTicks({ + domain, + timeZone, + plotWidth, +}: { + domain: readonly [number, number]; + timeZone: string | undefined; + plotWidth: number; +}): number[] | undefined { + const [startSeconds, endSeconds] = domain; + if (plotWidth <= 0 || !(endSeconds > startSeconds)) { + return undefined; + } + const zone = timeZone ?? getLocalTimeZone(); + const toMonthIndex = (seconds: number) => { + const wallClock = toWallClock(new Date(seconds * 1000), zone); + return wallClock.getUTCFullYear() * 12 + wallClock.getUTCMonth(); + }; + const firstMonth = toMonthIndex(startSeconds); + const lastMonth = toMonthIndex(endSeconds); + const monthStartSeconds = (monthIndex: number) => + fromWallClock( + new Date(Date.UTC(Math.floor(monthIndex / 12), monthIndex % 12, 1)), + zone, + ).getTime() / 1000; + + const ticksForStep = (step: number) => { + const ticks: number[] = []; + for ( + let month = Math.ceil(firstMonth / step) * step; + month <= lastMonth; + month += step + ) { + const tick = monthStartSeconds(month); + if (tick >= startSeconds && tick <= endSeconds) { + ticks.push(tick); + } + } + return ticks; + }; + + const maxTicks = Math.max( + 2, + Math.floor(plotWidth / MIN_MONTH_TICK_SPACING_PX), + ); + let ticks: number[] = []; + for (const step of MONTH_TICK_STEPS) { + ticks = ticksForStep(step); + if (ticks.length <= maxTicks) { + break; + } + } + return ticks.length > 0 ? ticks : undefined; +} + +/** + * Format for the tooltip header timestamp. Year-scale ranges carry the year, + * and drop the time of day when buckets are a day or longer. + */ +export function getTooltipDateFormat({ + dateRange, + granularity, +}: { + dateRange: readonly [Date, Date] | Readonly<[Date, Date]>; + granularity: string; +}): DateFormat { + if (!isYearScaleRange(dateRange)) { + return 'normal'; + } + return convertGranularityToSeconds(granularity) >= SECONDS_PER_DAY + ? 'isoDate' + : 'withYear'; +} + +/** + * Format for an x-axis tick label. Year-scale ranges show the month and year + * on every tick. Otherwise, below daily granularity the first tick carries the + * date and the rest only the time. At daily granularity or coarser every tick + * carries the date, plus the time when the bucket does not start at midnight + * in `timeZone` (buckets are UTC-aligned, so this happens in most zones). An + * undefined `timeZone` means the browser's zone. */ export function getXAxisTickDateFormat({ tickSeconds, index, granularity, timeZone, + yearScale = false, }: { tickSeconds: number; index: number; granularity: string; timeZone: string | undefined; + yearScale?: boolean; }): DateFormat { + if (yearScale) { + return 'monthYear'; + } if (convertGranularityToSeconds(granularity) < SECONDS_PER_DAY) { return index === 0 ? 'normal' : 'time'; } diff --git a/packages/app/src/HDXMultiSeriesTimeChart/index.ts b/packages/app/src/HDXMultiSeriesTimeChart/index.ts index df1806ec33..ca8084a150 100644 --- a/packages/app/src/HDXMultiSeriesTimeChart/index.ts +++ b/packages/app/src/HDXMultiSeriesTimeChart/index.ts @@ -8,9 +8,12 @@ export { compactTickAnchor, formatAxisTick, getExpandableYAxisTicks, + getMonthStartTicks, getNiceYAxisTicks, + getTooltipDateFormat, getXAxisTickDateFormat, getYAxisTicks, + isYearScaleRange, } from './axisTicks'; export { type ActiveClickPayload, diff --git a/packages/app/src/components/DBTimeChart/ChartTooltipOverlay.tsx b/packages/app/src/components/DBTimeChart/ChartTooltipOverlay.tsx index 4fd5aca15a..62ba867ff1 100644 --- a/packages/app/src/components/DBTimeChart/ChartTooltipOverlay.tsx +++ b/packages/app/src/components/DBTimeChart/ChartTooltipOverlay.tsx @@ -26,10 +26,14 @@ export function ChartTooltipOverlay({ fallbackNumberFormat, numberFormatByKey, previousPeriodOffsetSeconds, + dateFormat, hiddenSeriesCount, onLoadAllSeries, expanded, -}: Pick & { +}: Pick< + ChartSeriesTooltipProps, + 'getSeriesFilters' | 'onFilterSeries' | 'dateFormat' +> & { payload: ActiveClickPayload | undefined; buildSearchUrl: (key?: string, value?: number) => string | null; onDismiss: () => void; @@ -159,6 +163,7 @@ export function ChartTooltipOverlay({ fallbackNumberFormat={fallbackNumberFormat} numberFormatByKey={numberFormatByKey} previousPeriodOffsetSeconds={previousPeriodOffsetSeconds} + dateFormat={dateFormat} buildSearchUrl={buildSearchUrl} onDismiss={onDismiss} onFocusSeries={onFocusSeries} diff --git a/packages/app/src/components/DBTimeChart/DBTimeChart.tsx b/packages/app/src/components/DBTimeChart/DBTimeChart.tsx index 8c28b99892..ed0be0efff 100644 --- a/packages/app/src/components/DBTimeChart/DBTimeChart.tsx +++ b/packages/app/src/components/DBTimeChart/DBTimeChart.tsx @@ -27,7 +27,11 @@ import { MAX_LOADABLE_TIME_CHART_SERIES, resolveRenderedSeriesCap, } from '@/defaults'; -import { type ActiveClickPayload, MemoChart } from '@/HDXMultiSeriesTimeChart'; +import { + type ActiveClickPayload, + getTooltipDateFormat, + MemoChart, +} from '@/HDXMultiSeriesTimeChart'; import { getMinGranularitySeconds, useQueriedChartConfig, @@ -655,6 +659,7 @@ function DBTimeChartComponent({ fallbackNumberFormat={queriedConfig.numberFormat} numberFormatByKey={formatByColumn} previousPeriodOffsetSeconds={previousPeriodOffsetSeconds} + dateFormat={getTooltipDateFormat({ dateRange, granularity })} // "+N more" in the pinned tooltip loads every series (same escape // hatch as the hidden-series warning). Only offered while capped. hiddenSeriesCount={hiddenSeriesCount} diff --git a/packages/app/src/components/charts/ChartSeriesTooltip.tsx b/packages/app/src/components/charts/ChartSeriesTooltip.tsx index 632063b80d..157556b64e 100644 --- a/packages/app/src/components/charts/ChartSeriesTooltip.tsx +++ b/packages/app/src/components/charts/ChartSeriesTooltip.tsx @@ -26,6 +26,7 @@ import { MAX_TOOLTIP_ROWS, } from '@/HDXMultiSeriesTimeChart'; import type { NumberFormat } from '@/types'; +import type { DateFormat } from '@/useFormatTime'; import { ChartTooltipContainer, @@ -215,6 +216,8 @@ export type ChartSeriesTooltipProps = { /** Per-value-column number formats, keyed by result column name. */ numberFormatByKey: Map; previousPeriodOffsetSeconds?: number; + /** Format for the header timestamp; see getTooltipDateFormat. */ + dateFormat?: DateFormat; /** Drill-down URL for the whole bucket (no args) or one series (key + value). */ buildSearchUrl?: (key?: string, value?: number) => string | null; /** Dismiss the tooltip (used by links + focus). */ @@ -279,6 +282,7 @@ export function ChartSeriesTooltip({ fallbackNumberFormat, numberFormatByKey, previousPeriodOffsetSeconds, + dateFormat, buildSearchUrl, onDismiss, onFocusSeries, @@ -334,6 +338,7 @@ export function ChartSeriesTooltip({ onDismiss?.()} /> ); diff --git a/packages/app/src/components/charts/ChartTooltip.tsx b/packages/app/src/components/charts/ChartTooltip.tsx index 732505d28c..52ec3b6e7c 100644 --- a/packages/app/src/components/charts/ChartTooltip.tsx +++ b/packages/app/src/components/charts/ChartTooltip.tsx @@ -8,7 +8,7 @@ import { } from '@tabler/icons-react'; import type { NumberFormat } from '@/types'; -import { FormatTime } from '@/useFormatTime'; +import { type DateFormat, FormatTime } from '@/useFormatTime'; import { formatNumber, truncateMiddle } from '@/utils'; import { useZIndex } from '@/zIndex'; @@ -160,18 +160,23 @@ export const ChartTooltipItem = memo( const ChartTooltipTimestamp = ({ labelSeconds, previousPeriodOffsetSeconds, + dateFormat, }: { labelSeconds: number | string; previousPeriodOffsetSeconds?: number; + dateFormat?: DateFormat; }) => { const sec = Number(labelSeconds); return ( <> - + {previousPeriodOffsetSeconds != null && ( <> {' (vs '} - + {')'} )} @@ -187,10 +192,13 @@ const ChartTooltipTimestamp = ({ export const ChartTooltipHeader = ({ labelSeconds, previousPeriodOffsetSeconds, + dateFormat, onClose, }: { labelSeconds: number | string; previousPeriodOffsetSeconds?: number; + /** Defaults to the full date and time without the year. */ + dateFormat?: DateFormat; /** Pinned only; when omitted the X is rendered but hidden. */ onClose?: () => void; }) => ( @@ -199,6 +207,7 @@ export const ChartTooltipHeader = ({ { if (time instanceof Date) { diff --git a/packages/common-utils/src/__tests__/utils.test.ts b/packages/common-utils/src/__tests__/utils.test.ts index 3d3bb6af68..d3b56a0c6c 100644 --- a/packages/common-utils/src/__tests__/utils.test.ts +++ b/packages/common-utils/src/__tests__/utils.test.ts @@ -115,6 +115,20 @@ describe('utils', () => { }), ).toEqual('Jan 2'); }); + + it('formats the month and year, in the given time zone', () => { + const date = new Date('2024-02-29T20:00:00Z'); + expect( + formatDate(date, { timeZone: 'Asia/Tokyo', format: 'monthYear' }), + ).toEqual('Mar 2024'); + }); + + it('formats an ISO date, in the given time zone', () => { + const date = new Date('2024-03-17T20:00:00Z'); + expect( + formatDate(date, { timeZone: 'Asia/Tokyo', format: 'isoDate' }), + ).toEqual('2024-03-18'); + }); }); describe('toWallClock / fromWallClock', () => { diff --git a/packages/common-utils/src/core/utils.ts b/packages/common-utils/src/core/utils.ts index d9b9855468..48914c6101 100644 --- a/packages/common-utils/src/core/utils.ts +++ b/packages/common-utils/src/core/utils.ts @@ -849,8 +849,18 @@ const TIME_TOKENS = { '12h': 'MMM d', '24h': 'MMM d', }, + monthYear: { + '12h': 'MMM yyyy', + '24h': 'MMM yyyy', + }, + isoDate: { + '12h': 'yyyy-MM-dd', + '24h': 'yyyy-MM-dd', + }, }; +export type DateFormat = keyof typeof TIME_TOKENS; + export const UTC_TIME_ZONE = 'Etc/UTC'; /** Formats `date` in `timeZone` (an IANA name), or the local zone if unset. */ @@ -862,7 +872,7 @@ export const formatDate = ( clock = '12h', }: { timeZone?: string; - format?: 'normal' | 'short' | 'withMs' | 'time' | 'withYear' | 'date'; + format?: DateFormat; clock?: '12h' | '24h'; }, ) => { From a250f8ba0a8c63bb8d3f47d9bdbcf337814304ea Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 25 Nov 2026 21:14:23 +0000 Subject: [PATCH 2/3] fix(app): keep the tooltip time when a year-scale bucket is not at local midnight UTC-aligned daily buckets start before midnight in zones west of UTC, so a date-only tooltip named the previous day. Show the date only when the bucket starts at midnight in the display zone, and center compact x-axis labels on month-start ticks. Co-authored-by: Mike Shi --- .../ChartTooltipContent.tsx | 6 +-- .../src/HDXMultiSeriesTimeChart/MemoChart.tsx | 25 ++++++++--- .../__tests__/HDXMultiSeriesTimeChart.test.ts | 44 ++++++++++++++++--- .../src/HDXMultiSeriesTimeChart/axisTicks.ts | 35 ++++++++++----- .../components/DBTimeChart/DBTimeChart.tsx | 13 +++++- 5 files changed, 96 insertions(+), 27 deletions(-) diff --git a/packages/app/src/HDXMultiSeriesTimeChart/ChartTooltipContent.tsx b/packages/app/src/HDXMultiSeriesTimeChart/ChartTooltipContent.tsx index 4547bc022d..199316f83b 100644 --- a/packages/app/src/HDXMultiSeriesTimeChart/ChartTooltipContent.tsx +++ b/packages/app/src/HDXMultiSeriesTimeChart/ChartTooltipContent.tsx @@ -24,7 +24,7 @@ import styles from '@styles/HDXLineChart.module.scss'; type HDXLineChartTooltipProps = { lineDataMap: { [keyName: string]: LineData }; previousPeriodOffsetSeconds?: number; - dateFormat?: DateFormat; + getDateFormat?: (labelSeconds: number) => DateFormat; numberFormat?: NumberFormat; numberFormatByKey: Map; /** Per-series active-point pixel Y, captured by the Area active dots. */ @@ -55,7 +55,7 @@ export const HDXLineChartTooltip = withErrorBoundary( numberFormatByKey, lineDataMap, previousPeriodOffsetSeconds, - dateFormat, + getDateFormat, activePointYByKeyRef, containerRef, } = props; @@ -79,7 +79,7 @@ export const HDXLineChartTooltip = withErrorBoundary( ); diff --git a/packages/app/src/HDXMultiSeriesTimeChart/MemoChart.tsx b/packages/app/src/HDXMultiSeriesTimeChart/MemoChart.tsx index 0ac4e40d9a..e3317b8d4d 100644 --- a/packages/app/src/HDXMultiSeriesTimeChart/MemoChart.tsx +++ b/packages/app/src/HDXMultiSeriesTimeChart/MemoChart.tsx @@ -493,7 +493,9 @@ export const MemoChart = memo(function MemoChart({ ); // Compact mode: anchor the first label to the start and the last to the end - // so neither is clipped on a narrow chart. Renders every tick through one + // so neither is clipped on a narrow chart. Month-start ticks sit inside the + // plot rather than on its edges, so those stay centered on their marks. + // Renders every tick through one // path (axis color, mono) so the axis stays visually consistent. `fill` is // the color Recharts gives every tick, so these match the y-axis labels. const renderCompactXTick = useCallback( @@ -505,7 +507,9 @@ export const MemoChart = memo(function MemoChart({ visibleTicksCount, fill, }: XAxisTickContentProps) => { - const textAnchor = compactTickAnchor(index, visibleTicksCount); + const textAnchor = xAxisTicks + ? 'middle' + : compactTickAnchor(index, visibleTicksCount); return ( ); }, - [xTickFormatter, axisTickFontSize], + [xTickFormatter, axisTickFontSize, xAxisTicks], ); const tickFormatter = useCallback( @@ -596,7 +600,16 @@ export const MemoChart = memo(function MemoChart({ return map; }, [lineData]); - const tooltipDateFormat = getTooltipDateFormat({ dateRange, granularity }); + const getTooltipLabelDateFormat = useCallback( + (labelSeconds: number) => + getTooltipDateFormat({ + labelSeconds, + dateRange, + granularity, + timeZone: displayTimeZone, + }), + [dateRange, granularity, displayTimeZone], + ); // Memoize the tooltip `content` element: recharts re-evaluates it every hover // frame, so a fresh element each render defeats HDXLineChartTooltip's memo. // Refs are stable, so only the listed values are deps. @@ -607,7 +620,7 @@ export const MemoChart = memo(function MemoChart({ numberFormatByKey={tooltipNumberFormatsByKey} lineDataMap={lineDataMap} previousPeriodOffsetSeconds={previousPeriodOffsetSeconds} - dateFormat={tooltipDateFormat} + getDateFormat={getTooltipLabelDateFormat} activePointYByKeyRef={activePointYByKeyRef} containerRef={containerRef} /> @@ -617,7 +630,7 @@ export const MemoChart = memo(function MemoChart({ tooltipNumberFormatsByKey, lineDataMap, previousPeriodOffsetSeconds, - tooltipDateFormat, + getTooltipLabelDateFormat, ], ); diff --git a/packages/app/src/HDXMultiSeriesTimeChart/__tests__/HDXMultiSeriesTimeChart.test.ts b/packages/app/src/HDXMultiSeriesTimeChart/__tests__/HDXMultiSeriesTimeChart.test.ts index c9da97ae47..30df81c08d 100644 --- a/packages/app/src/HDXMultiSeriesTimeChart/__tests__/HDXMultiSeriesTimeChart.test.ts +++ b/packages/app/src/HDXMultiSeriesTimeChart/__tests__/HDXMultiSeriesTimeChart.test.ts @@ -1477,32 +1477,66 @@ describe('isYearScaleRange', () => { }); describe('getTooltipDateFormat', () => { + const seconds = (iso: string) => new Date(iso).getTime() / 1000; const twoYears: [Date, Date] = [ new Date('2024-11-25T00:00:00Z'), new Date('2026-11-25T00:00:00Z'), ]; + const utcMidnight = seconds('2025-11-08T00:00:00Z'); it('keeps the default format below a year', () => { expect( getTooltipDateFormat({ + labelSeconds: utcMidnight, dateRange: [new Date('2026-10-01'), new Date('2026-11-01')], granularity: '1 day', + timeZone: 'Etc/UTC', }), ).toBe('normal'); }); - it('shows only the date with the year for daily or coarser buckets', () => { + it.each(['1 day', '30 day'])( + 'shows only the date with the year for a midnight %s bucket', + granularity => { + expect( + getTooltipDateFormat({ + labelSeconds: utcMidnight, + dateRange: twoYears, + granularity, + timeZone: 'Etc/UTC', + }), + ).toBe('isoDate'); + }, + ); + + it('keeps the time when a daily bucket does not start at local midnight', () => { + // A UTC-aligned bucket starts at 7 PM the previous day in New York. expect( - getTooltipDateFormat({ dateRange: twoYears, granularity: '30 day' }), - ).toBe('isoDate'); + getTooltipDateFormat({ + labelSeconds: utcMidnight, + dateRange: twoYears, + granularity: '1 day', + timeZone: 'America/New_York', + }), + ).toBe('withYear'); expect( - getTooltipDateFormat({ dateRange: twoYears, granularity: '1 day' }), + getTooltipDateFormat({ + labelSeconds: seconds('2025-11-08T05:00:00Z'), + dateRange: twoYears, + granularity: '1 day', + timeZone: 'America/New_York', + }), ).toBe('isoDate'); }); it('keeps the time, with the year, for sub-day buckets', () => { expect( - getTooltipDateFormat({ dateRange: twoYears, granularity: '1 hour' }), + getTooltipDateFormat({ + labelSeconds: utcMidnight, + dateRange: twoYears, + granularity: '1 hour', + timeZone: 'Etc/UTC', + }), ).toBe('withYear'); }); }); diff --git a/packages/app/src/HDXMultiSeriesTimeChart/axisTicks.ts b/packages/app/src/HDXMultiSeriesTimeChart/axisTicks.ts index cb919b2bcf..9fcca9834b 100644 --- a/packages/app/src/HDXMultiSeriesTimeChart/axisTicks.ts +++ b/packages/app/src/HDXMultiSeriesTimeChart/axisTicks.ts @@ -458,21 +458,40 @@ export function getMonthStartTicks({ return ticks.length > 0 ? ticks : undefined; } +function isMidnightIn(seconds: number, timeZone: string | undefined) { + const wallClock = toWallClock( + new Date(seconds * 1000), + timeZone ?? getLocalTimeZone(), + ); + return ( + wallClock.getUTCHours() === 0 && + wallClock.getUTCMinutes() === 0 && + wallClock.getUTCSeconds() === 0 + ); +} + /** - * Format for the tooltip header timestamp. Year-scale ranges carry the year, - * and drop the time of day when buckets are a day or longer. + * Format for the tooltip header timestamp at `labelSeconds`. Year-scale ranges + * carry the year, and drop the time of day when buckets are a day or longer + * and the bucket starts at midnight in `timeZone`. Buckets are UTC-aligned, so + * elsewhere a date alone would name the previous or next day without saying so. */ export function getTooltipDateFormat({ + labelSeconds, dateRange, granularity, + timeZone, }: { + labelSeconds: number; dateRange: readonly [Date, Date] | Readonly<[Date, Date]>; granularity: string; + timeZone: string | undefined; }): DateFormat { if (!isYearScaleRange(dateRange)) { return 'normal'; } - return convertGranularityToSeconds(granularity) >= SECONDS_PER_DAY + return convertGranularityToSeconds(granularity) >= SECONDS_PER_DAY && + isMidnightIn(labelSeconds, timeZone) ? 'isoDate' : 'withYear'; } @@ -504,13 +523,5 @@ export function getXAxisTickDateFormat({ if (convertGranularityToSeconds(granularity) < SECONDS_PER_DAY) { return index === 0 ? 'normal' : 'time'; } - const wallClock = toWallClock( - new Date(tickSeconds * 1000), - timeZone ?? getLocalTimeZone(), - ); - const isMidnight = - wallClock.getUTCHours() === 0 && - wallClock.getUTCMinutes() === 0 && - wallClock.getUTCSeconds() === 0; - return isMidnight ? 'date' : 'short'; + return isMidnightIn(tickSeconds, timeZone) ? 'date' : 'short'; } diff --git a/packages/app/src/components/DBTimeChart/DBTimeChart.tsx b/packages/app/src/components/DBTimeChart/DBTimeChart.tsx index ed0be0efff..dafec8e750 100644 --- a/packages/app/src/components/DBTimeChart/DBTimeChart.tsx +++ b/packages/app/src/components/DBTimeChart/DBTimeChart.tsx @@ -41,6 +41,7 @@ import { useResultColumnFilterKeys } from '@/hooks/useResultColumnFilterKeys'; import { useChartNumberFormats, useSource } from '@/source'; import { useTimeZoneLinkParam } from '@/timeZoneOverride'; import type { TileFilterHandler } from '@/types'; +import { useDisplayTimeZone } from '@/useDisplayTimeZone'; import { ChartTooltipOverlay } from './ChartTooltipOverlay'; import { useCrossChartPinDismiss } from './crossChartPin'; @@ -475,6 +476,7 @@ function DBTimeChartComponent({ [setDisplayType], ); + const displayTimeZone = useDisplayTimeZone(); const [activeClickPayload, setActiveClickPayload] = useState< ActiveClickPayload | undefined >(undefined); @@ -659,7 +661,16 @@ function DBTimeChartComponent({ fallbackNumberFormat={queriedConfig.numberFormat} numberFormatByKey={formatByColumn} previousPeriodOffsetSeconds={previousPeriodOffsetSeconds} - dateFormat={getTooltipDateFormat({ dateRange, granularity })} + dateFormat={ + activeClickPayload?.activeLabel != null + ? getTooltipDateFormat({ + labelSeconds: Number(activeClickPayload.activeLabel), + dateRange, + granularity, + timeZone: displayTimeZone, + }) + : undefined + } // "+N more" in the pinned tooltip loads every series (same escape // hatch as the hidden-series warning). Only offered while capped. hiddenSeriesCount={hiddenSeriesCount} From fa6af2fedbf18b1acf0f8e29f05c390675d42614 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 25 Nov 2026 21:21:41 +0000 Subject: [PATCH 3/3] fix(app): anchor compact month ticks on domain bounds; keep tooltip memo stable Compact month-start labels that land on a domain bound are anchored to it again so they don't clip. The tooltip format resolver now depends on the year-scale flag rather than the dateRange array, which is a new array on each parent render. Co-authored-by: Mike Shi --- .../src/HDXMultiSeriesTimeChart/MemoChart.tsx | 20 +++++++++++-------- .../__tests__/HDXMultiSeriesTimeChart.test.ts | 14 +++++-------- .../src/HDXMultiSeriesTimeChart/axisTicks.ts | 7 ++++--- .../components/DBTimeChart/DBTimeChart.tsx | 3 ++- 4 files changed, 23 insertions(+), 21 deletions(-) diff --git a/packages/app/src/HDXMultiSeriesTimeChart/MemoChart.tsx b/packages/app/src/HDXMultiSeriesTimeChart/MemoChart.tsx index e3317b8d4d..17f96e1e44 100644 --- a/packages/app/src/HDXMultiSeriesTimeChart/MemoChart.tsx +++ b/packages/app/src/HDXMultiSeriesTimeChart/MemoChart.tsx @@ -493,8 +493,8 @@ export const MemoChart = memo(function MemoChart({ ); // Compact mode: anchor the first label to the start and the last to the end - // so neither is clipped on a narrow chart. Month-start ticks sit inside the - // plot rather than on its edges, so those stay centered on their marks. + // so neither is clipped on a narrow chart. Month-start ticks usually sit + // inside the plot, so only those on a domain bound are anchored to it. // Renders every tick through one // path (axis color, mono) so the axis stays visually consistent. `fill` is // the color Recharts gives every tick, so these match the y-axis labels. @@ -507,9 +507,13 @@ export const MemoChart = memo(function MemoChart({ visibleTicksCount, fill, }: XAxisTickContentProps) => { - const textAnchor = xAxisTicks - ? 'middle' - : compactTickAnchor(index, visibleTicksCount); + const tickSeconds = Number(payload.value); + const textAnchor = + xAxisTicks && + tickSeconds !== xAxisDomain[0] && + tickSeconds !== xAxisDomain[1] + ? 'middle' + : compactTickAnchor(index, visibleTicksCount); return ( ); }, - [xTickFormatter, axisTickFontSize, xAxisTicks], + [xTickFormatter, axisTickFontSize, xAxisTicks, xAxisDomain], ); const tickFormatter = useCallback( @@ -604,11 +608,11 @@ export const MemoChart = memo(function MemoChart({ (labelSeconds: number) => getTooltipDateFormat({ labelSeconds, - dateRange, + yearScale, granularity, timeZone: displayTimeZone, }), - [dateRange, granularity, displayTimeZone], + [yearScale, granularity, displayTimeZone], ); // Memoize the tooltip `content` element: recharts re-evaluates it every hover // frame, so a fresh element each render defeats HDXLineChartTooltip's memo. diff --git a/packages/app/src/HDXMultiSeriesTimeChart/__tests__/HDXMultiSeriesTimeChart.test.ts b/packages/app/src/HDXMultiSeriesTimeChart/__tests__/HDXMultiSeriesTimeChart.test.ts index 30df81c08d..ebb9bc67b6 100644 --- a/packages/app/src/HDXMultiSeriesTimeChart/__tests__/HDXMultiSeriesTimeChart.test.ts +++ b/packages/app/src/HDXMultiSeriesTimeChart/__tests__/HDXMultiSeriesTimeChart.test.ts @@ -1478,17 +1478,13 @@ describe('isYearScaleRange', () => { describe('getTooltipDateFormat', () => { const seconds = (iso: string) => new Date(iso).getTime() / 1000; - const twoYears: [Date, Date] = [ - new Date('2024-11-25T00:00:00Z'), - new Date('2026-11-25T00:00:00Z'), - ]; const utcMidnight = seconds('2025-11-08T00:00:00Z'); it('keeps the default format below a year', () => { expect( getTooltipDateFormat({ labelSeconds: utcMidnight, - dateRange: [new Date('2026-10-01'), new Date('2026-11-01')], + yearScale: false, granularity: '1 day', timeZone: 'Etc/UTC', }), @@ -1501,7 +1497,7 @@ describe('getTooltipDateFormat', () => { expect( getTooltipDateFormat({ labelSeconds: utcMidnight, - dateRange: twoYears, + yearScale: true, granularity, timeZone: 'Etc/UTC', }), @@ -1514,7 +1510,7 @@ describe('getTooltipDateFormat', () => { expect( getTooltipDateFormat({ labelSeconds: utcMidnight, - dateRange: twoYears, + yearScale: true, granularity: '1 day', timeZone: 'America/New_York', }), @@ -1522,7 +1518,7 @@ describe('getTooltipDateFormat', () => { expect( getTooltipDateFormat({ labelSeconds: seconds('2025-11-08T05:00:00Z'), - dateRange: twoYears, + yearScale: true, granularity: '1 day', timeZone: 'America/New_York', }), @@ -1533,7 +1529,7 @@ describe('getTooltipDateFormat', () => { expect( getTooltipDateFormat({ labelSeconds: utcMidnight, - dateRange: twoYears, + yearScale: true, granularity: '1 hour', timeZone: 'Etc/UTC', }), diff --git a/packages/app/src/HDXMultiSeriesTimeChart/axisTicks.ts b/packages/app/src/HDXMultiSeriesTimeChart/axisTicks.ts index 9fcca9834b..ec7cdcc727 100644 --- a/packages/app/src/HDXMultiSeriesTimeChart/axisTicks.ts +++ b/packages/app/src/HDXMultiSeriesTimeChart/axisTicks.ts @@ -478,16 +478,17 @@ function isMidnightIn(seconds: number, timeZone: string | undefined) { */ export function getTooltipDateFormat({ labelSeconds, - dateRange, + yearScale, granularity, timeZone, }: { labelSeconds: number; - dateRange: readonly [Date, Date] | Readonly<[Date, Date]>; + /** See isYearScaleRange. */ + yearScale: boolean; granularity: string; timeZone: string | undefined; }): DateFormat { - if (!isYearScaleRange(dateRange)) { + if (!yearScale) { return 'normal'; } return convertGranularityToSeconds(granularity) >= SECONDS_PER_DAY && diff --git a/packages/app/src/components/DBTimeChart/DBTimeChart.tsx b/packages/app/src/components/DBTimeChart/DBTimeChart.tsx index dafec8e750..6d56cbbad8 100644 --- a/packages/app/src/components/DBTimeChart/DBTimeChart.tsx +++ b/packages/app/src/components/DBTimeChart/DBTimeChart.tsx @@ -30,6 +30,7 @@ import { import { type ActiveClickPayload, getTooltipDateFormat, + isYearScaleRange, MemoChart, } from '@/HDXMultiSeriesTimeChart'; import { @@ -665,7 +666,7 @@ function DBTimeChartComponent({ activeClickPayload?.activeLabel != null ? getTooltipDateFormat({ labelSeconds: Number(activeClickPayload.activeLabel), - dateRange, + yearScale: isYearScaleRange(dateRange), granularity, timeZone: displayTimeZone, })