From 2b3a0eb8268ef129d546eeada58e0e1d29b1f72c Mon Sep 17 00:00:00 2001 From: Drew Davis Date: Fri, 2 Oct 2026 10:46:28 -0400 Subject: [PATCH] refactor: Decompose heatmap query and view builders --- packages/app/src/ClickhousePage.tsx | 34 +++-- packages/app/src/DBDashboardPage.tsx | 9 +- .../DBEditTimeChartForm/ChartPreviewPanel.tsx | 10 +- .../DBEditTimeChartForm/EditTimeChartForm.tsx | 7 +- .../__tests__/ChartPreviewPanel.test.tsx | 7 +- .../DBHeatmapChart/DBHeatmapChart.tsx | 140 +++++------------- .../DBHeatmapChart/HeatmapChartView.tsx | 107 +++++++++++++ .../components/DBHeatmapChart/HeatmapPlot.tsx | 27 +--- .../__tests__/DBHeatmapChart.render.test.tsx | 23 ++- .../components/DBHeatmapChart/heatmapAxis.ts | 32 ++++ .../components/DBHeatmapChart/heatmapPaths.ts | 4 +- .../DBHeatmapChart/heatmapQueries.ts | 16 +- .../src/components/DBHeatmapChart/index.ts | 3 +- .../DBHeatmapChart/useHeatmapData.ts | 51 ++----- .../DBHeatmapChart/useHeatmapView.ts | 58 ++++++++ .../Search/DBSearchHeatmapChart.tsx | 38 ++--- .../__tests__/DBSearchHeatmapChart.test.tsx | 6 +- 17 files changed, 342 insertions(+), 230 deletions(-) create mode 100644 packages/app/src/components/DBHeatmapChart/HeatmapChartView.tsx create mode 100644 packages/app/src/components/DBHeatmapChart/useHeatmapView.ts diff --git a/packages/app/src/ClickhousePage.tsx b/packages/app/src/ClickhousePage.tsx index cb6de4a6f0..9ba3618b88 100644 --- a/packages/app/src/ClickhousePage.tsx +++ b/packages/app/src/ClickhousePage.tsx @@ -668,23 +668,27 @@ function ClickhousePage() { { onTimeRangeSelect( diff --git a/packages/app/src/DBDashboardPage.tsx b/packages/app/src/DBDashboardPage.tsx index 7120338d20..9fa9702197 100644 --- a/packages/app/src/DBDashboardPage.tsx +++ b/packages/app/src/DBDashboardPage.tsx @@ -174,9 +174,7 @@ import ChartContainer, { } from './components/charts/ChartContainer'; import DashboardFiltersModal from './components/DashboardFiltersModal'; import { DBBarChart } from './components/DBBarChart'; -import DBHeatmapChart, { - toHeatmapChartConfig, -} from './components/DBHeatmapChart'; +import DBHeatmapChart, { toHeatmapQuery } from './components/DBHeatmapChart'; import { DBPieChart } from './components/DBPieChart'; import DBSqlRowTableWithSideBar from './components/DBSqlRowTableWithSidebar'; import OnboardingModal from './components/OnboardingModal'; @@ -249,7 +247,7 @@ function HeatmapTile({ dateRange: [Date, Date]; enabled?: boolean; }) { - const { heatmapConfig, scaleType } = toHeatmapChartConfig(queriedConfig); + const heatmapQuery = toHeatmapQuery(queriedConfig); const [clickPos, setClickPos] = useState<{ x: number; y: number } | null>( null, @@ -291,8 +289,7 @@ function HeatmapTile({ title={title} toolbarPrefix={toolbarPrefix} toolbarSuffix={toolbarSuffix} - config={heatmapConfig} - scaleType={scaleType} + query={heatmapQuery} enabled={enabled} showLegend /> diff --git a/packages/app/src/components/DBEditTimeChartForm/ChartPreviewPanel.tsx b/packages/app/src/components/DBEditTimeChartForm/ChartPreviewPanel.tsx index 25891ed0f2..8fe0e7b03b 100644 --- a/packages/app/src/components/DBEditTimeChartForm/ChartPreviewPanel.tsx +++ b/packages/app/src/components/DBEditTimeChartForm/ChartPreviewPanel.tsx @@ -26,7 +26,7 @@ import DBHeatmapChart, { buildHeatmapBoundsConfig, buildHeatmapBucketConfig, HEATMAP_N_BUCKETS, - toHeatmapChartConfig, + toHeatmapQuery, } from '@/components/DBHeatmapChart'; import DBNumberChart from '@/components/DBNumberChart'; import { DBPieChart } from '@/components/DBPieChart'; @@ -62,12 +62,10 @@ function HeatmapPreview({ }: { config: BuilderChartConfigWithDateRange; }) { - const { heatmapConfig, scaleType } = toHeatmapChartConfig(config); return (
@@ -96,8 +94,8 @@ function HeatmapSQLPreview({ ...config, timestampValueExpression, }; - const { heatmapConfig, scaleType } = - toHeatmapChartConfig(configWithTimestamp); + const { config: heatmapConfig, scaleType } = + toHeatmapQuery(configWithTimestamp); const granularity = convertDateRangeToGranularityString(dateRange, 245); const boundsConfig = buildHeatmapBoundsConfig({ diff --git a/packages/app/src/components/DBEditTimeChartForm/EditTimeChartForm.tsx b/packages/app/src/components/DBEditTimeChartForm/EditTimeChartForm.tsx index fdb798e7e5..0cf87aae5e 100644 --- a/packages/app/src/components/DBEditTimeChartForm/EditTimeChartForm.tsx +++ b/packages/app/src/components/DBEditTimeChartForm/EditTimeChartForm.tsx @@ -71,7 +71,10 @@ import { isStringSelectDisplayType, validateChartForm, } from '@/components/ChartEditor/utils'; -import type { HeatmapScaleType } from '@/components/DBHeatmapChart'; +import { + HEATMAP_DURATION_NUMBER_FORMAT, + type HeatmapScaleType, +} from '@/components/DBHeatmapChart'; import { ErrorBoundary } from '@/components/Error/ErrorBoundary'; import HeatmapSettingsDrawer, { HeatmapSettingsValues, @@ -171,7 +174,7 @@ function applyHeatmapDefaults( setValue('select', heatmapSeries); setValue('series', heatmapSeries); setValue('series.0.countExpression', 'count()'); - setValue('numberFormat', { output: 'duration', factor: 0.001 }); + setValue('numberFormat', { ...HEATMAP_DURATION_NUMBER_FORMAT }); } export default function EditTimeChartForm({ diff --git a/packages/app/src/components/DBEditTimeChartForm/__tests__/ChartPreviewPanel.test.tsx b/packages/app/src/components/DBEditTimeChartForm/__tests__/ChartPreviewPanel.test.tsx index c750a03d34..0943d8d8a0 100644 --- a/packages/app/src/components/DBEditTimeChartForm/__tests__/ChartPreviewPanel.test.tsx +++ b/packages/app/src/components/DBEditTimeChartForm/__tests__/ChartPreviewPanel.test.tsx @@ -56,9 +56,10 @@ jest.mock('@/components/DBSqlRowTableWithSidebar', () => ({ jest.mock('@/components/DBHeatmapChart', () => ({ __esModule: true, default: () =>
Heatmap Chart
, - toHeatmapChartConfig: (config: unknown) => ({ - heatmapConfig: config, - scaleType: 'log' as const, + toHeatmapQuery: (config: unknown) => ({ + mode: 'distribution', + config, + scaleType: 'log', }), buildHeatmapBoundsConfig: ({ config }: { config: unknown }) => config, buildHeatmapBucketConfig: ({ config }: { config: unknown }) => config, diff --git a/packages/app/src/components/DBHeatmapChart/DBHeatmapChart.tsx b/packages/app/src/components/DBHeatmapChart/DBHeatmapChart.tsx index 6ab4b224e4..fb7080c7e7 100644 --- a/packages/app/src/components/DBHeatmapChart/DBHeatmapChart.tsx +++ b/packages/app/src/components/DBHeatmapChart/DBHeatmapChart.tsx @@ -1,23 +1,12 @@ -import { useMemo } from 'react'; import dynamic from 'next/dynamic'; -import cx from 'classnames'; -import { Text, useMantineColorScheme } from '@mantine/core'; -import ChartContainer from '@/components/charts/ChartContainer'; -import ChartErrorState, { - ChartErrorStateVariant, -} from '@/components/charts/ChartErrorState'; - -import { ColorLegend } from './ColorLegend'; -import type { HeatmapScaleType } from './heatmapGrid'; -import { HeatmapPlot } from './HeatmapPlot'; -import type { HeatmapChartConfig } from './heatmapQueries'; -import { darkPalette, lightPalette } from './palette'; +import { HeatmapChartView, HeatmapChartViewProps } from './HeatmapChartView'; +import type { HeatmapQuery } from './heatmapQueries'; import type { SelectionBounds } from './selection'; import { useHeatmapData } from './useHeatmapData'; -type DBHeatmapChartProps = { - config: HeatmapChartConfig; +type DBHeatmapChartProps = HeatmapChartViewProps & { + query: HeatmapQuery; enabled?: boolean; onFilter?: (xMin: number, xMax: number, yMin: number, yMax: number) => void; onClearFilter?: () => void; @@ -29,108 +18,45 @@ type DBHeatmapChartProps = { * this is purely a visual mirror of that state. */ selectionBounds?: SelectionBounds | null; - title?: React.ReactNode; - toolbarPrefix?: React.ReactNode[]; - toolbarSuffix?: React.ReactNode[]; - scaleType?: HeatmapScaleType; - showLegend?: boolean; - errorVariant?: ChartErrorStateVariant; }; function DBHeatmapChart({ - config, + query, enabled = true, onFilter, - onClearFilter, - selectionBounds, - title, - toolbarPrefix, - toolbarSuffix, - scaleType = 'log', - showLegend = false, - errorVariant, + ...viewProps }: DBHeatmapChartProps) { - const { colorScheme } = useMantineColorScheme(); - const palette = colorScheme === 'light' ? lightPalette : darkPalette; - - const { view, isLoading, isRefreshing, error } = useHeatmapData({ - config, - scaleType, + const data = useHeatmapData({ + config: query.config, + scaleType: query.scaleType, enabled, }); - - const toolbarItemsMemo = useMemo(() => { - const allToolbarItems: React.ReactNode[] = []; - - if (showLegend) { - allToolbarItems.push( - , - ); - } - - if (toolbarPrefix && toolbarPrefix.length > 0) { - allToolbarItems.push(...toolbarPrefix); - } - - if (toolbarSuffix && toolbarSuffix.length > 0) { - allToolbarItems.push(...toolbarSuffix); - } - - return allToolbarItems; - }, [showLegend, palette, toolbarPrefix, toolbarSuffix]); + const { view } = data; return ( - - {isLoading ? ( - - Loading... - - ) : error ? ( - - ) : view.grid.cells.length < 2 || view.generatedTsBuckets.length < 2 ? ( - - Not enough data points to render heatmap. Try expanding your search - criteria. - - ) : ( - { - // In log mode, the bottom bucket collects all values - // clamped by greatest(value, effectiveMin). If the - // selection touches that bucket, widen yMin to 0 so - // the downstream SQL filter captures all those spans. - // The 1.1x threshold adds 10% headroom to account for - // floating-point rounding in the bucket boundary. - const adjustedYMin = - view.scaleType === 'log' && yMin <= view.effectiveMin * 1.1 - ? 0 - : yMin; - onFilter(xMin, xMax, adjustedYMin, yMax); - } - : undefined - } - onClearFilter={onClearFilter} - scaleType={view.scaleType} - palette={palette} - selectionBounds={selectionBounds} - /> - )} - + { + // In log mode, the bottom bucket collects all values + // clamped by greatest(value, effectiveMin). If the + // selection touches that bucket, widen yMin to 0 so + // the downstream SQL filter captures all those spans. + // The 1.1x threshold adds 10% headroom to account for + // floating-point rounding in the bucket boundary. + const adjustedYMin = + view.scaleType === 'log' && yMin <= view.effectiveMin * 1.1 + ? 0 + : yMin; + onFilter(xMin, xMax, adjustedYMin, yMax); + } + : undefined + } + /> ); } diff --git a/packages/app/src/components/DBHeatmapChart/HeatmapChartView.tsx b/packages/app/src/components/DBHeatmapChart/HeatmapChartView.tsx new file mode 100644 index 0000000000..75c03548a6 --- /dev/null +++ b/packages/app/src/components/DBHeatmapChart/HeatmapChartView.tsx @@ -0,0 +1,107 @@ +import { useMemo } from 'react'; +import cx from 'classnames'; +import { Text, useMantineColorScheme } from '@mantine/core'; + +import ChartContainer from '@/components/charts/ChartContainer'; +import ChartErrorState, { + ChartErrorStateVariant, +} from '@/components/charts/ChartErrorState'; +import { NumberFormat } from '@/types'; + +import { ColorLegend } from './ColorLegend'; +import { HeatmapPlot } from './HeatmapPlot'; +import { darkPalette, lightPalette } from './palette'; +import type { SelectionBounds } from './selection'; +import type { HeatmapData } from './useHeatmapView'; + +export type HeatmapChartViewProps = { + title?: React.ReactNode; + toolbarPrefix?: React.ReactNode[]; + toolbarSuffix?: React.ReactNode[]; + showLegend?: boolean; + errorVariant?: ChartErrorStateVariant; +}; + +/** Renders a heatmap's data: toolbar, loading/error/empty states and the plot. */ +export function HeatmapChartView({ + data: { view, isLoading, isRefreshing, error }, + plotKey, + numberFormat, + onFilter, + onClearFilter, + selectionBounds, + title, + toolbarPrefix, + toolbarSuffix, + showLegend = false, + errorVariant, +}: HeatmapChartViewProps & { + data: HeatmapData; + /** Remounts the plot when the query changes. */ + plotKey: string; + numberFormat?: NumberFormat; + onFilter?: (xMin: number, xMax: number, yMin: number, yMax: number) => void; + onClearFilter?: () => void; + selectionBounds?: SelectionBounds | null; +}) { + const { colorScheme } = useMantineColorScheme(); + const palette = colorScheme === 'light' ? lightPalette : darkPalette; + + const toolbarItemsMemo = useMemo(() => { + const allToolbarItems: React.ReactNode[] = []; + + if (showLegend) { + allToolbarItems.push( + , + ); + } + + if (toolbarPrefix && toolbarPrefix.length > 0) { + allToolbarItems.push(...toolbarPrefix); + } + + if (toolbarSuffix && toolbarSuffix.length > 0) { + allToolbarItems.push(...toolbarSuffix); + } + + return allToolbarItems; + }, [showLegend, palette, toolbarPrefix, toolbarSuffix]); + + return ( + + {isLoading ? ( + + Loading... + + ) : error ? ( + + ) : view.grid.cells.length < 2 || view.generatedTsBuckets.length < 2 ? ( + + Not enough data points to render heatmap. Try expanding your search + criteria. + + ) : ( + + )} + + ); +} diff --git a/packages/app/src/components/DBHeatmapChart/HeatmapPlot.tsx b/packages/app/src/components/DBHeatmapChart/HeatmapPlot.tsx index cb15aea043..d3eae05dbf 100644 --- a/packages/app/src/components/DBHeatmapChart/HeatmapPlot.tsx +++ b/packages/app/src/components/DBHeatmapChart/HeatmapPlot.tsx @@ -6,7 +6,7 @@ import { useElementSize } from '@mantine/hooks'; import { NumberFormat } from '@/types'; -import { formatHeatmapTick, logScaleSplits } from './heatmapAxis'; +import { formatHeatmapTick, heatmapYAxisOptions } from './heatmapAxis'; import { computeBucketPercentiles, gridToPlotData, @@ -14,7 +14,11 @@ import { heatmapRowCount, HeatmapScaleType, } from './heatmapGrid'; -import { baseHeatmapOptions, buildSeriesForPalette } from './heatmapPaths'; +import { + baseHeatmapOptions, + buildSeriesForPalette, + HEATMAP_AXIS_FONT, +} from './heatmapPaths'; import { HeatmapTooltip } from './HeatmapTooltip'; import { highlightDataPlugin, HighlightedPoint } from './highlightDataPlugin'; import { applySelectionToChart, SelectionBounds } from './selection'; @@ -159,19 +163,15 @@ export function HeatmapPlot({ opt.axes[0], { ...opt.axes[1], - values: (_u: uPlot, vals: number[]) => { - return vals.map(tickFormatter); - }, + ...heatmapYAxisOptions(scaleType, tickFormatter), // Override the static size fn so it measures the actual // formatted labels (from tickFormatter) rather than // whatever raw values uPlot passes in a prior cycle. size(self: uPlot, values: string[]) { if (!values || values.length === 0) return 50; - const font = - self.axes[1]?.font ?? '12px IBM Plex Mono, monospace'; const ctx = self.ctx; ctx.save(); - ctx.font = font; + ctx.font = HEATMAP_AXIS_FONT; let maxW = 0; for (const v of values) { const w = ctx.measureText(v).width; @@ -180,17 +180,6 @@ export function HeatmapPlot({ ctx.restore(); return Math.ceil(maxW) + 16; }, - ...(scaleType === 'log' - ? { - splits: (u: uPlot) => { - const [yMin, yMax] = - u.scales.y!.min != null - ? [u.scales.y!.min, u.scales.y!.max!] - : [0, 1]; - return logScaleSplits(yMin, yMax); - }, - } - : {}), }, ], } diff --git a/packages/app/src/components/DBHeatmapChart/__tests__/DBHeatmapChart.render.test.tsx b/packages/app/src/components/DBHeatmapChart/__tests__/DBHeatmapChart.render.test.tsx index 5b5d197650..fd858560c9 100644 --- a/packages/app/src/components/DBHeatmapChart/__tests__/DBHeatmapChart.render.test.tsx +++ b/packages/app/src/components/DBHeatmapChart/__tests__/DBHeatmapChart.render.test.tsx @@ -4,6 +4,10 @@ import { MantineProvider } from '@mantine/core'; import { render, screen } from '@testing-library/react'; import DBHeatmapChart from '@/components/DBHeatmapChart'; +import type { + HeatmapChartConfig, + HeatmapQuery, +} from '@/components/DBHeatmapChart/heatmapQueries'; type Props = Record; @@ -57,7 +61,7 @@ const HOUR = 60 * 60 * 1000; const T0 = new Date('2026-07-06T00:00:00Z').getTime(); function configFor(fromMs: number) { - const config: React.ComponentProps['config'] = { + const config: HeatmapChartConfig = { displayType: DisplayType.Heatmap, select: [{ aggFn: 'heatmap', valueExpression: 'Duration' }], from: { databaseName: 'default', tableName: 'otel_traces' }, @@ -70,6 +74,15 @@ function configFor(fromMs: number) { return config; } +const distribution = ( + fromMs: number, + scaleType: 'log' | 'linear' = 'log', +): HeatmapQuery => ({ + mode: 'distribution', + config: configFor(fromMs), + scaleType, +}); + // Bucket rows that line up with the time buckets of `configFor(T0)`. const bucketData = { meta: [ @@ -133,7 +146,7 @@ const lastYAxisIsLog = () => // A wrapper (rather than renderWithMantine) keeps the provider in place across // rerenders, so the chart keeps its state when the range changes. const renderChart = (fromMs: number) => - render(, { + render(, { wrapper: MantineProvider, }); @@ -168,7 +181,7 @@ describe('DBHeatmapChart refresh', () => { // A refresh moves to a later, non-overlapping range; both queries are // still showing the previous range's results. mockQueries({ boundsPlaceholder: true, bucketsPlaceholder: true }); - rerender(); + rerender(); const plot = await screen.findByTestId('heatmap-plot'); expect(lastPlottedCounts()).toEqual(settledCounts); @@ -188,7 +201,7 @@ describe('DBHeatmapChart refresh', () => { // Switching to linear refetches both queries; until they return, the // chart still shows log-scale data, so it must keep the log axis. mockQueries({ boundsPlaceholder: true, bucketsPlaceholder: true }); - rerender(); + rerender(); await screen.findByTestId('heatmap-plot'); expect(lastPlottedCounts()).toEqual(settledCounts); @@ -235,7 +248,7 @@ describe('DBHeatmapChart refresh', () => { expect(lastOptionsFor('heatmap_bucket')?.enabled).toBe(false); mockQueries({ bucketsPlaceholder: true }); - rerender(); + rerender(); expect(lastOptionsFor('heatmap_bucket')?.enabled).toBe(true); }); diff --git a/packages/app/src/components/DBHeatmapChart/heatmapAxis.ts b/packages/app/src/components/DBHeatmapChart/heatmapAxis.ts index 3aaefde64a..b9ce030eec 100644 --- a/packages/app/src/components/DBHeatmapChart/heatmapAxis.ts +++ b/packages/app/src/components/DBHeatmapChart/heatmapAxis.ts @@ -1,8 +1,16 @@ +import type uPlot from 'uplot'; + import { NumberFormat } from '@/types'; import { formatDurationMsCompact, formatNumber } from '@/utils'; import type { HeatmapScaleType } from './heatmapGrid'; +/** Number format for a heatmap of trace durations in ms. */ +export const HEATMAP_DURATION_NUMBER_FORMAT = { + output: 'duration', + factor: 0.001, +} as const satisfies NumberFormat; + /** Format a plot-space y value as a y-axis / tooltip label. */ export function formatHeatmapTick( value: number, @@ -68,3 +76,27 @@ export function logScaleSplits(yMin: number, yMax: number): number[] { } return splits; } + +/** + * uPlot y axis overrides for a heatmap's numeric y axis: formatted ticks, + * placed at powers of 10 on a log scale. + */ +export function heatmapYAxisOptions( + scaleType: HeatmapScaleType, + tickFormatter: (value: number) => string, +): Pick { + return { + values: (_u: uPlot, vals: number[]) => vals.map(tickFormatter), + ...(scaleType === 'log' + ? { + splits: (u: uPlot) => { + const [yMin, yMax] = + u.scales.y!.min != null + ? [u.scales.y!.min, u.scales.y!.max!] + : [0, 1]; + return logScaleSplits(yMin, yMax); + }, + } + : {}), + }; +} diff --git a/packages/app/src/components/DBHeatmapChart/heatmapPaths.ts b/packages/app/src/components/DBHeatmapChart/heatmapPaths.ts index 2a431531cc..82152ca9aa 100644 --- a/packages/app/src/components/DBHeatmapChart/heatmapPaths.ts +++ b/packages/app/src/components/DBHeatmapChart/heatmapPaths.ts @@ -83,9 +83,11 @@ export function heatmapPaths(opts: { }; } +export const HEATMAP_AXIS_FONT = '12px IBM Plex Mono, monospace'; + const axis: uPlot.Axis = { stroke: 'rgba(102,102,102,1)', // color of the axis line - font: '12px IBM Plex Mono, monospace', + font: HEATMAP_AXIS_FONT, grid: { show: true, // show grid lines stroke: 'rgba(52,58,64)', // grid line color diff --git a/packages/app/src/components/DBHeatmapChart/heatmapQueries.ts b/packages/app/src/components/DBHeatmapChart/heatmapQueries.ts index 2cc4ecf1eb..87ac2e3599 100644 --- a/packages/app/src/components/DBHeatmapChart/heatmapQueries.ts +++ b/packages/app/src/components/DBHeatmapChart/heatmapQueries.ts @@ -28,16 +28,22 @@ export type HeatmapChartConfig = { with?: BuilderChartConfigWithDateRange['with']; }; -/** Build a HeatmapChartConfig from a builder chart config that has heatmap extras on select[0]. */ -export function toHeatmapChartConfig(config: BuilderChartConfigWithDateRange): { - heatmapConfig: HeatmapChartConfig; +/** What a heatmap queries. */ +export type HeatmapQuery = { + mode: 'distribution'; + config: HeatmapChartConfig; scaleType: HeatmapScaleType; -} { +}; + +export function toHeatmapQuery( + config: BuilderChartConfigWithDateRange, +): HeatmapQuery { const firstSelect = Array.isArray(config.select) ? config.select[0] : undefined; return { - heatmapConfig: { + mode: 'distribution', + config: { ...config, displayType: DisplayType.Heatmap, select: [ diff --git a/packages/app/src/components/DBHeatmapChart/index.ts b/packages/app/src/components/DBHeatmapChart/index.ts index 42f313fdbd..4f2c0a8ab9 100644 --- a/packages/app/src/components/DBHeatmapChart/index.ts +++ b/packages/app/src/components/DBHeatmapChart/index.ts @@ -1,11 +1,12 @@ export { ColorLegend } from './ColorLegend'; export { default } from './DBHeatmapChart'; +export { HEATMAP_DURATION_NUMBER_FORMAT } from './heatmapAxis'; export { HEATMAP_N_BUCKETS } from './heatmapBounds'; export type { HeatmapScaleType } from './heatmapGrid'; export { buildHeatmapBoundsConfig, buildHeatmapBucketConfig, - toHeatmapChartConfig, + toHeatmapQuery, } from './heatmapQueries'; export { darkPalette, lightPalette } from './palette'; export type { SelectionBounds } from './selection'; diff --git a/packages/app/src/components/DBHeatmapChart/useHeatmapData.ts b/packages/app/src/components/DBHeatmapChart/useHeatmapData.ts index 78ebbf6800..c0f4491414 100644 --- a/packages/app/src/components/DBHeatmapChart/useHeatmapData.ts +++ b/packages/app/src/components/DBHeatmapChart/useHeatmapData.ts @@ -1,8 +1,6 @@ -import { useMemo, useState } from 'react'; +import { useMemo } from 'react'; import { inferTimestampColumn } from '@hyperdx/common-utils/dist/clickhouse'; -import { convertDateRangeToGranularityString } from '@hyperdx/common-utils/dist/core/utils'; -import { timeBucketByGranularity } from '@/ChartUtils'; import { useQueriedChartConfig } from '@/hooks/useChartConfig'; import { computeEffectiveMin, HEATMAP_N_BUCKETS } from './heatmapBounds'; @@ -17,13 +15,12 @@ import { buildHeatmapBucketConfig, HeatmapChartConfig, } from './heatmapQueries'; - -export type HeatmapView = { - grid: HeatmapGrid; - generatedTsBuckets: Date[]; - effectiveMin: number; - scaleType: HeatmapScaleType; -}; +import { + HeatmapData, + HeatmapView, + useHeatmapTimeBuckets, + useSettledView, +} from './useHeatmapView'; /** * Query a heatmap and shape it into a `HeatmapGrid`. While a refresh is in @@ -37,10 +34,10 @@ export function useHeatmapData({ config: HeatmapChartConfig; scaleType: HeatmapScaleType; enabled: boolean; -}) { - const dateRange = config.dateRange; - const granularity = convertDateRangeToGranularityString(dateRange, 245); - +}): HeatmapData { + const { granularity, generatedTsBuckets } = useHeatmapTimeBuckets( + config.dateRange, + ); const nBuckets = HEATMAP_N_BUCKETS; // Future: #1914 adds overflow-bucket indicators for smarter range @@ -54,7 +51,7 @@ export function useHeatmapData({ error: minMaxError, } = useQueriedChartConfig(minMaxConfig, { queryKey: ['heatmap', minMaxConfig], - enabled: enabled, + enabled, placeholderData: prev => prev, }); @@ -81,7 +78,7 @@ export function useHeatmapData({ queryKey: ['heatmap_bucket', bucketConfig], // Wait for fresh bounds, so a refresh doesn't also query the new range // bucketed with the previous range's min/max. - enabled: canQueryBuckets && !isMinMaxPlaceholderData, + enabled: enabled && canQueryBuckets && !isMinMaxPlaceholderData, // Only keep the previous buckets while this query can still run, so an // empty refreshed range shows "Not enough data points" instead of // pulsing on stale buckets. @@ -92,17 +89,6 @@ export function useHeatmapData({ // queries have fresh data. const isRefreshing = isMinMaxPlaceholderData || isPlaceholderData; - // Memoize so timeBucketByGranularity's fresh Date[] doesn't defeat - // the grid memoization downstream. dateRange itself may be a - // fresh array each render, so depend on primitive ms + granularity. - const fromMs = dateRange[0]?.getTime() ?? 0; - const toMs = dateRange[1]?.getTime() ?? 0; - const generatedTsBuckets = useMemo( - () => timeBucketByGranularity(dateRange[0], dateRange[1], granularity), - // eslint-disable-next-line react-hooks/exhaustive-deps - [fromMs, toMs, granularity], - ); - // A stable grid lets uplot-react skip its setData path when only // URL-state (xMin/xMax/yMin/yMax) changed. Pairs with the selectionBounds // prop on HeatmapPlot: the prop reapplies u.select on any chart @@ -123,22 +109,13 @@ export function useHeatmapData({ }); }, [data, generatedTsBuckets, scaleType, effectiveMin, max, nBuckets]); - // While refreshing, keep drawing the last settled heatmap. The previous - // bucket rows only line up with the time buckets, bounds and scale they were - // queried with, so re-plotting them on the new range would draw a blank or - // mis-scaled grid. const currentView = useMemo( () => ({ grid, generatedTsBuckets, effectiveMin, scaleType }), [grid, generatedTsBuckets, effectiveMin, scaleType], ); - const [settledView, setSettledView] = useState(currentView); - if (!isRefreshing && settledView !== currentView) { - setSettledView(currentView); - } - const view = isRefreshing ? settledView : currentView; return { - view, + view: useSettledView(currentView, isRefreshing), isLoading: isLoading || isMinMaxLoading, isRefreshing, error: error || minMaxError, diff --git a/packages/app/src/components/DBHeatmapChart/useHeatmapView.ts b/packages/app/src/components/DBHeatmapChart/useHeatmapView.ts new file mode 100644 index 0000000000..1d48346a89 --- /dev/null +++ b/packages/app/src/components/DBHeatmapChart/useHeatmapView.ts @@ -0,0 +1,58 @@ +import { useMemo, useState } from 'react'; +import { ClickHouseQueryError } from '@hyperdx/common-utils/dist/clickhouse'; +import { convertDateRangeToGranularityString } from '@hyperdx/common-utils/dist/core/utils'; + +import { timeBucketByGranularity } from '@/ChartUtils'; + +import type { HeatmapGrid, HeatmapScaleType } from './heatmapGrid'; + +export type HeatmapView = { + grid: HeatmapGrid; + generatedTsBuckets: Date[]; + /** The scale and lower bound the grid was bucketed with. */ + scaleType: HeatmapScaleType; + effectiveMin: number; +}; + +/** What a heatmap data hook returns for the chart to render. */ +export type HeatmapData = { + view: HeatmapView; + isLoading: boolean; + isRefreshing: boolean; + error: Error | ClickHouseQueryError | null | undefined; +}; + +/** The heatmap's time columns: bucket starts across the date range. */ +export function useHeatmapTimeBuckets(dateRange: [Date, Date]) { + const granularity = convertDateRangeToGranularityString(dateRange, 245); + + // Memoize so timeBucketByGranularity's fresh Date[] doesn't defeat + // the grid memoization downstream. dateRange itself may be a + // fresh array each render, so depend on primitive ms + granularity. + const fromMs = dateRange[0]?.getTime() ?? 0; + const toMs = dateRange[1]?.getTime() ?? 0; + const generatedTsBuckets = useMemo( + () => timeBucketByGranularity(dateRange[0], dateRange[1], granularity), + // eslint-disable-next-line react-hooks/exhaustive-deps + [fromMs, toMs, granularity], + ); + + return { granularity, generatedTsBuckets, fromMs, toMs }; +} + +/** + * While refreshing, keep drawing the last settled heatmap. The previous + * query results only line up with the time buckets, bounds and scale they + * were queried with, so re-plotting them on the new range would draw a blank + * or mis-scaled grid. + */ +export function useSettledView( + currentView: HeatmapView, + isRefreshing: boolean, +) { + const [settledView, setSettledView] = useState(currentView); + if (!isRefreshing && settledView !== currentView) { + setSettledView(currentView); + } + return isRefreshing ? settledView : currentView; +} diff --git a/packages/app/src/components/Search/DBSearchHeatmapChart.tsx b/packages/app/src/components/Search/DBSearchHeatmapChart.tsx index 4fd1a0424a..03a2936fb1 100644 --- a/packages/app/src/components/Search/DBSearchHeatmapChart.tsx +++ b/packages/app/src/components/Search/DBSearchHeatmapChart.tsx @@ -20,14 +20,14 @@ import DBDeltaChart from '@/components/DBDeltaChart'; import DBHeatmapChart, { ColorLegend, darkPalette, + HEATMAP_DURATION_NUMBER_FORMAT, type HeatmapScaleType, lightPalette, type SelectionBounds, - toHeatmapChartConfig, + toHeatmapQuery, } from '@/components/DBHeatmapChart'; import HeatmapSettingsDrawer from '@/components/HeatmapSettingsDrawer'; import { getDurationMsExpression } from '@/source'; -import type { NumberFormat } from '@/types'; export function DBSearchHeatmapChart({ chartConfig, @@ -139,27 +139,21 @@ export function DBSearchHeatmapChart({ }} > { setFields({ xMin, xMax, yMin, yMax }); diff --git a/packages/app/src/components/Search/__tests__/DBSearchHeatmapChart.test.tsx b/packages/app/src/components/Search/__tests__/DBSearchHeatmapChart.test.tsx index 274787f316..d1e3dcea03 100644 --- a/packages/app/src/components/Search/__tests__/DBSearchHeatmapChart.test.tsx +++ b/packages/app/src/components/Search/__tests__/DBSearchHeatmapChart.test.tsx @@ -63,7 +63,11 @@ jest.mock('../../DBHeatmapChart', () => ({ ColorLegend: jest.fn(() =>
color scale
), darkPalette: ['#000'], lightPalette: ['#fff'], - toHeatmapChartConfig: jest.fn(() => ({ heatmapConfig: {} })), + toHeatmapQuery: jest.fn(() => ({ + mode: 'distribution', + config: {}, + scaleType: 'log', + })), })); // Capture props passed to DBDeltaChart so we can assert URL coords forward.