diff --git a/.changeset/year-scale-chart-dates.md b/.changeset/year-scale-chart-dates.md new file mode 100644 index 000000000..41b86b74e --- /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 ad844cff0..199316f83 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; + getDateFormat?: (labelSeconds: number) => 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, + getDateFormat, 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 dd80d030a..17f96e1e4 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,14 +474,28 @@ 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 - // so neither is clipped on a narrow chart. Renders every tick through one + // 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. const renderCompactXTick = useCallback( @@ -488,7 +507,13 @@ export const MemoChart = memo(function MemoChart({ visibleTicksCount, fill, }: XAxisTickContentProps) => { - const textAnchor = compactTickAnchor(index, visibleTicksCount); + const tickSeconds = Number(payload.value); + const textAnchor = + xAxisTicks && + tickSeconds !== xAxisDomain[0] && + tickSeconds !== xAxisDomain[1] + ? 'middle' + : compactTickAnchor(index, visibleTicksCount); return ( ); }, - [xTickFormatter, axisTickFontSize], + [xTickFormatter, axisTickFontSize, xAxisTicks, xAxisDomain], ); const tickFormatter = useCallback( @@ -579,6 +604,16 @@ export const MemoChart = memo(function MemoChart({ return map; }, [lineData]); + const getTooltipLabelDateFormat = useCallback( + (labelSeconds: number) => + getTooltipDateFormat({ + labelSeconds, + yearScale, + granularity, + timeZone: 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. // Refs are stable, so only the listed values are deps. @@ -589,6 +624,7 @@ export const MemoChart = memo(function MemoChart({ numberFormatByKey={tooltipNumberFormatsByKey} lineDataMap={lineDataMap} previousPeriodOffsetSeconds={previousPeriodOffsetSeconds} + getDateFormat={getTooltipLabelDateFormat} activePointYByKeyRef={activePointYByKeyRef} containerRef={containerRef} /> @@ -598,6 +634,7 @@ export const MemoChart = memo(function MemoChart({ tooltipNumberFormatsByKey, lineDataMap, previousPeriodOffsetSeconds, + getTooltipLabelDateFormat, ], ); @@ -901,8 +938,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 23fe5c85c..ebb9bc67b 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,194 @@ 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 seconds = (iso: string) => new Date(iso).getTime() / 1000; + const utcMidnight = seconds('2025-11-08T00:00:00Z'); + + it('keeps the default format below a year', () => { + expect( + getTooltipDateFormat({ + labelSeconds: utcMidnight, + yearScale: false, + granularity: '1 day', + timeZone: 'Etc/UTC', + }), + ).toBe('normal'); + }); + + it.each(['1 day', '30 day'])( + 'shows only the date with the year for a midnight %s bucket', + granularity => { + expect( + getTooltipDateFormat({ + labelSeconds: utcMidnight, + yearScale: true, + 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({ + labelSeconds: utcMidnight, + yearScale: true, + granularity: '1 day', + timeZone: 'America/New_York', + }), + ).toBe('withYear'); + expect( + getTooltipDateFormat({ + labelSeconds: seconds('2025-11-08T05:00:00Z'), + yearScale: true, + granularity: '1 day', + timeZone: 'America/New_York', + }), + ).toBe('isoDate'); + }); + + it('keeps the time, with the year, for sub-day buckets', () => { + expect( + getTooltipDateFormat({ + labelSeconds: utcMidnight, + yearScale: true, + granularity: '1 hour', + timeZone: 'Etc/UTC', + }), + ).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 16e9ea370..ec7cdcc72 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,35 +368,161 @@ 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; +} + +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 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, + yearScale, + granularity, + timeZone, +}: { + labelSeconds: number; + /** See isYearScaleRange. */ + yearScale: boolean; + granularity: string; + timeZone: string | undefined; +}): DateFormat { + if (!yearScale) { + return 'normal'; + } + return convertGranularityToSeconds(granularity) >= SECONDS_PER_DAY && + isMidnightIn(labelSeconds, timeZone) + ? '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'; } - 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/HDXMultiSeriesTimeChart/index.ts b/packages/app/src/HDXMultiSeriesTimeChart/index.ts index df1806ec3..ca8084a15 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 4fd5aca15..62ba867ff 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 8c28b9989..6d56cbbad 100644 --- a/packages/app/src/components/DBTimeChart/DBTimeChart.tsx +++ b/packages/app/src/components/DBTimeChart/DBTimeChart.tsx @@ -27,7 +27,12 @@ import { MAX_LOADABLE_TIME_CHART_SERIES, resolveRenderedSeriesCap, } from '@/defaults'; -import { type ActiveClickPayload, MemoChart } from '@/HDXMultiSeriesTimeChart'; +import { + type ActiveClickPayload, + getTooltipDateFormat, + isYearScaleRange, + MemoChart, +} from '@/HDXMultiSeriesTimeChart'; import { getMinGranularitySeconds, useQueriedChartConfig, @@ -37,6 +42,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'; @@ -471,6 +477,7 @@ function DBTimeChartComponent({ [setDisplayType], ); + const displayTimeZone = useDisplayTimeZone(); const [activeClickPayload, setActiveClickPayload] = useState< ActiveClickPayload | undefined >(undefined); @@ -655,6 +662,16 @@ function DBTimeChartComponent({ fallbackNumberFormat={queriedConfig.numberFormat} numberFormatByKey={formatByColumn} previousPeriodOffsetSeconds={previousPeriodOffsetSeconds} + dateFormat={ + activeClickPayload?.activeLabel != null + ? getTooltipDateFormat({ + labelSeconds: Number(activeClickPayload.activeLabel), + yearScale: isYearScaleRange(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} diff --git a/packages/app/src/components/charts/ChartSeriesTooltip.tsx b/packages/app/src/components/charts/ChartSeriesTooltip.tsx index 632063b80..157556b64 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 732505d28..52ec3b6e7 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 3d3bb6af6..d3b56a0c6 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 d9b985546..48914c610 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'; }, ) => {