SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
chore: refactored the config builder and added base config builder (#10256)
Abhi kumara171f7122fa3
diff --git a/frontend/src/container/DashboardContainer/visualization/charts/ChartWrapper/ChartWrapper.tsx b/frontend/src/container/DashboardContainer/visualization/charts/ChartWrapper/ChartWrapper.tsxnew file mode 100644index 0000000000..79f2e117a7--- /dev/null+++ b/frontend/src/container/DashboardContainer/visualization/charts/ChartWrapper/ChartWrapper.tsx@@ -0,0 +1,104 @@+import { useCallback, useRef } from 'react';+import ChartLayout from 'container/DashboardContainer/visualization/layout/ChartLayout/ChartLayout';+import Legend from 'lib/uPlotV2/components/Legend/Legend';+import {+ LegendPosition,+ TooltipRenderArgs,+} from 'lib/uPlotV2/components/types';+import UPlotChart from 'lib/uPlotV2/components/UPlotChart';+import { PlotContextProvider } from 'lib/uPlotV2/context/PlotContext';+import TooltipPlugin from 'lib/uPlotV2/plugins/TooltipPlugin/TooltipPlugin';+import noop from 'lodash-es/noop';+import uPlot from 'uplot';++import { ChartProps } from '../types';++const TOOLTIP_WIDTH_PADDING = 60;+const TOOLTIP_MIN_WIDTH = 200;++export default function ChartWrapper({+ legendConfig = { position: LegendPosition.BOTTOM },+ config,+ data,+ width: containerWidth,+ height: containerHeight,+ showTooltip = true,+ canPinTooltip = false,+ syncMode,+ syncKey,+ onDestroy = noop,+ children,+ layoutChildren,+ renderTooltip,+ 'data-testid': testId,+}: ChartProps): JSX.Element {+ const plotInstanceRef = useRef<uPlot | null>(null);++ const legendComponent = useCallback(+ (averageLegendWidth: number): React.ReactNode => {+ return (+ <Legend+ config={config}+ position={legendConfig.position}+ averageLegendWidth={averageLegendWidth}+ />+ );+ },+ [config, legendConfig.position],+ );++ const renderTooltipCallback = useCallback(+ (args: TooltipRenderArgs): React.ReactNode => {+ if (renderTooltip) {+ return renderTooltip(args);+ }+ return null;+ },+ [renderTooltip],+ );++ return (+ <PlotContextProvider>+ <ChartLayout+ config={config}+ containerWidth={containerWidth}+ containerHeight={containerHeight}+ legendConfig={legendConfig}+ legendComponent={legendComponent}+ layoutChildren={layoutChildren}+ >+ {({ chartWidth, chartHeight, averageLegendWidth }): JSX.Element => (+ <UPlotChart+ config={config}+ data={data}+ width={chartWidth}+ height={chartHeight}+ plotRef={(plot): void => {+ plotInstanceRef.current = plot;+ }}+ onDestroy={(plot: uPlot): void => {+ plotInstanceRef.current = null;+ onDestroy(plot);+ }}+ data-testid={testId}+ >+ {children}+ {showTooltip && (+ <TooltipPlugin+ config={config}+ canPinTooltip={canPinTooltip}+ syncMode={syncMode}+ maxWidth={Math.max(+ TOOLTIP_MIN_WIDTH,+ averageLegendWidth + TOOLTIP_WIDTH_PADDING,+ )}+ syncKey={syncKey}+ render={renderTooltipCallback}+ />+ )}+ </UPlotChart>+ )}+ </ChartLayout>+ </PlotContextProvider>+ );+}diff --git a/frontend/src/container/DashboardContainer/visualization/charts/TimeSeries/TimeSeries.tsx b/frontend/src/container/DashboardContainer/visualization/charts/TimeSeries/TimeSeries.tsxindex 321994890b..0db390198d 100644--- a/frontend/src/container/DashboardContainer/visualization/charts/TimeSeries/TimeSeries.tsx+++ b/frontend/src/container/DashboardContainer/visualization/charts/TimeSeries/TimeSeries.tsx@@ -1,104 +1,46 @@-import { useCallback, useRef } from 'react';-import ChartLayout from 'container/DashboardContainer/visualization/layout/ChartLayout/ChartLayout';-import Legend from 'lib/uPlotV2/components/Legend/Legend';-import Tooltip from 'lib/uPlotV2/components/Tooltip/Tooltip';+import { useCallback } from 'react';+import ChartWrapper from 'container/DashboardContainer/visualization/charts/ChartWrapper/ChartWrapper';+import TimeSeriesTooltip from 'lib/uPlotV2/components/Tooltip/TimeSeriesTooltip';+import { buildTooltipContent } from 'lib/uPlotV2/components/Tooltip/utils';import {- LegendPosition,+ TimeSeriesTooltipProps,TooltipRenderArgs,} from 'lib/uPlotV2/components/types';-import UPlotChart from 'lib/uPlotV2/components/UPlotChart';-import { PlotContextProvider } from 'lib/uPlotV2/context/PlotContext';-import TooltipPlugin from 'lib/uPlotV2/plugins/TooltipPlugin/TooltipPlugin';-import _noop from 'lodash-es/noop';-import uPlot from 'uplot';-import { ChartProps } from '../types';+import { TimeSeriesChartProps } from '../types';-const TOOLTIP_WIDTH_PADDING = 60;-const TOOLTIP_MIN_WIDTH = 200;+export default function TimeSeries(props: TimeSeriesChartProps): JSX.Element {+ const { children, renderTooltip: customRenderTooltip, ...rest } = props;-export default function TimeSeries({- legendConfig = { position: LegendPosition.BOTTOM },- config,- data,- width: containerWidth,- height: containerHeight,- disableTooltip = false,- canPinTooltip = false,- timezone,- yAxisUnit,- decimalPrecision,- syncMode,- syncKey,- onDestroy = _noop,- children,- layoutChildren,- 'data-testid': testId,-}: ChartProps): JSX.Element {- const plotInstanceRef = useRef<uPlot | null>(null);-- const legendComponent = useCallback(- (averageLegendWidth: number): React.ReactNode => {- return (- <Legend- config={config}- position={legendConfig.position}- averageLegendWidth={averageLegendWidth}- />- );+ const renderTooltip = useCallback(+ (props: TooltipRenderArgs): React.ReactNode => {+ if (customRenderTooltip) {+ return customRenderTooltip(props);+ }+ const content = buildTooltipContent({+ data: props.uPlotInstance.data,+ series: props.uPlotInstance.series,+ dataIndexes: props.dataIndexes,+ activeSeriesIndex: props.seriesIndex,+ uPlotInstance: props.uPlotInstance,+ yAxisUnit: rest.yAxisUnit ?? '',+ decimalPrecision: rest.decimalPrecision,+ });+ const tooltipProps: TimeSeriesTooltipProps = {+ ...props,+ timezone: rest.timezone,+ yAxisUnit: rest.yAxisUnit,+ decimalPrecision: rest.decimalPrecision,+ content,+ };+ return <TimeSeriesTooltip {...tooltipProps} />;},- [config, legendConfig.position],+ [customRenderTooltip, rest.timezone, rest.yAxisUnit, rest.decimalPrecision],);return (- <PlotContextProvider>- <ChartLayout- config={config}- containerWidth={containerWidth}- containerHeight={containerHeight}- legendConfig={legendConfig}- legendComponent={legendComponent}- layoutChildren={layoutChildren}- >- {({ chartWidth, chartHeight, averageLegendWidth }): JSX.Element => (- <UPlotChart- config={config}- data={data}- width={chartWidth}- height={chartHeight}- plotRef={(plot): void => {- plotInstanceRef.current = plot;- }}- onDestroy={(plot: uPlot): void => {- plotInstanceRef.current = null;- onDestroy(plot);- }}- data-testid={testId}- >- {children}- {!disableTooltip && (- <TooltipPlugin- config={config}- canPinTooltip={canPinTooltip}- syncMode={syncMode}- maxWidth={Math.max(- TOOLTIP_MIN_WIDTH,- averageLegendWidth + TOOLTIP_WIDTH_PADDING,- )}- syncKey={syncKey}- render={(props: TooltipRenderArgs): React.ReactNode => (- <Tooltip- {...props}- timezone={timezone}- yAxisUnit={yAxisUnit}- decimalPrecision={decimalPrecision}- />- )}- />- )}- </UPlotChart>- )}- </ChartLayout>- </PlotContextProvider>+ <ChartWrapper {...rest} renderTooltip={renderTooltip}>+ {children}+ </ChartWrapper>);}diff --git a/frontend/src/container/DashboardContainer/visualization/charts/types.ts b/frontend/src/container/DashboardContainer/visualization/charts/types.tsindex 5ef5d1fe43..89f5f31868 100644--- a/frontend/src/container/DashboardContainer/visualization/charts/types.ts+++ b/frontend/src/container/DashboardContainer/visualization/charts/types.ts@@ -1,29 +1,39 @@import { PrecisionOption } from 'components/Graph/types';-import { LegendConfig } from 'lib/uPlotV2/components/types';+import { LegendConfig, TooltipRenderArgs } from 'lib/uPlotV2/components/types';import { UPlotConfigBuilder } from 'lib/uPlotV2/config/UPlotConfigBuilder';import { DashboardCursorSync } from 'lib/uPlotV2/plugins/TooltipPlugin/types';interface BaseChartProps {width: number;height: number;- disableTooltip?: boolean;+ showTooltip?: boolean;timezone: string;- syncMode?: DashboardCursorSync;- syncKey?: string;canPinTooltip?: boolean;yAxisUnit?: string;decimalPrecision?: PrecisionOption;+ renderTooltip?: (props: TooltipRenderArgs) => React.ReactNode;+ 'data-testid'?: string;}--interface TimeSeriesChartProps extends BaseChartProps {+interface UPlotBasedChartProps {config: UPlotConfigBuilder;- legendConfig: LegendConfig;data: uPlot.AlignedData;+ syncMode?: DashboardCursorSync;+ syncKey?: string;plotRef?: (plot: uPlot | null) => void;onDestroy?: (plot: uPlot) => void;children?: React.ReactNode;layoutChildren?: React.ReactNode;- 'data-testid'?: string;}-export type ChartProps = TimeSeriesChartProps;+export interface TimeSeriesChartProps+ extends BaseChartProps,+ UPlotBasedChartProps {+ legendConfig: LegendConfig;+}++export interface BarChartProps extends BaseChartProps, UPlotBasedChartProps {+ legendConfig: LegendConfig;+ isStackedBarChart?: boolean;+}++export type ChartProps = TimeSeriesChartProps | BarChartProps;diff --git a/frontend/src/container/DashboardContainer/visualization/panels/TimeSeriesPanel/TimeSeriesPanel.tsx b/frontend/src/container/DashboardContainer/visualization/panels/TimeSeriesPanel/TimeSeriesPanel.tsxindex 489215ec38..cede91e5c7 100644--- a/frontend/src/container/DashboardContainer/visualization/panels/TimeSeriesPanel/TimeSeriesPanel.tsx+++ b/frontend/src/container/DashboardContainer/visualization/panels/TimeSeriesPanel/TimeSeriesPanel.tsx@@ -6,7 +6,6 @@ import { PanelWrapperProps } from 'container/PanelWrapper/panelWrapper.types';import { useIsDarkMode } from 'hooks/useDarkMode';import { useResizeObserver } from 'hooks/useDimensions';import { LegendPosition } from 'lib/uPlotV2/components/types';-import { LineInterpolation } from 'lib/uPlotV2/config/types';import { ContextMenu } from 'periscope/components/ContextMenu';import { useDashboard } from 'providers/Dashboard/Dashboard';import { useTimezone } from 'providers/Timezone';@@ -73,55 +72,28 @@ function TimeSeriesPanel(props: PanelWrapperProps): JSX.Element {}, [queryResponse?.data?.payload]);const config = useMemo(() => {- const tzDate = (timestamp: number): Date =>- uPlot.tzDate(new Date(timestamp * 1e3), timezone.value);-return prepareUPlotConfig({- widgetId: widget.id || '',- apiResponse: queryResponse?.data?.payload as MetricRangePayloadProps,- tzDate,- minTimeScale: minTimeScale,- maxTimeScale: maxTimeScale,- isLogScale: widget?.isLogScale ?? false,- thresholds: {- scaleKey: 'y',- thresholds: (widget.thresholds || []).map((threshold) => ({- thresholdValue: threshold.thresholdValue ?? 0,- thresholdColor: threshold.thresholdColor,- thresholdUnit: threshold.thresholdUnit,- thresholdLabel: threshold.thresholdLabel,- })),- yAxisUnit: widget.yAxisUnit,- },- yAxisUnit: widget.yAxisUnit || '',- softMin: widget.softMin === undefined ? null : widget.softMin,- softMax: widget.softMax === undefined ? null : widget.softMax,- spanGaps: false,- colorMapping: widget.customLegendColors ?? {},- lineInterpolation: LineInterpolation.Spline,+ widget,isDarkMode,+ currentQuery: widget.query,onClick: clickHandlerWithContextMenu,onDragSelect,- currentQuery: widget.query,+ apiResponse: queryResponse?.data?.payload as MetricRangePayloadProps,+ timezone,panelMode,+ minTimeScale: minTimeScale,+ maxTimeScale: maxTimeScale,});}, [- widget.id,- maxTimeScale,- minTimeScale,- timezone.value,- widget.customLegendColors,- widget.isLogScale,- widget.softMax,- widget.softMin,+ widget,isDarkMode,- queryResponse?.data?.payload,- widget.query,- widget.thresholds,- widget.yAxisUnit,- panelMode,clickHandlerWithContextMenu,onDragSelect,+ queryResponse?.data?.payload,+ panelMode,+ minTimeScale,+ maxTimeScale,+ timezone,]);const layoutChildren = useMemo(() => {diff --git a/frontend/src/container/DashboardContainer/visualization/panels/TimeSeriesPanel/utils.ts b/frontend/src/container/DashboardContainer/visualization/panels/TimeSeriesPanel/utils.tsindex 6772a5c153..337757aa3c 100644--- a/frontend/src/container/DashboardContainer/visualization/panels/TimeSeriesPanel/utils.ts+++ b/frontend/src/container/DashboardContainer/visualization/panels/TimeSeriesPanel/utils.ts@@ -1,3 +1,4 @@+import { Timezone } from 'components/CustomTimePicker/timezoneUtils';import { PANEL_TYPES } from 'constants/queryBuilder';import {fillMissingXAxisTimestamps,@@ -5,23 +6,20 @@ import {} from 'container/DashboardContainer/visualization/panels/utils';import { getLegend } from 'lib/dashboard/getQueryResults';import getLabelName from 'lib/getLabelName';-import onClickPlugin, {- OnClickPluginOpts,-} from 'lib/uPlotLib/plugins/onClickPlugin';+import { OnClickPluginOpts } from 'lib/uPlotLib/plugins/onClickPlugin';import {- DistributionType,DrawStyle,LineInterpolation,LineStyle,- SelectionPreferencesSource,VisibilityMode,} from 'lib/uPlotV2/config/types';import { UPlotConfigBuilder } from 'lib/uPlotV2/config/UPlotConfigBuilder';-import { ThresholdsDrawHookOptions } from 'lib/uPlotV2/hooks/types';+import { Widgets } from 'types/api/dashboard/getAll';import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';import { Query } from 'types/api/queryBuilder/queryBuilderData';import { PanelMode } from '../types';+import { buildBaseConfig } from '../utils/baseConfigBuilder';export const prepareChartData = (apiResponse: MetricRangePayloadProps,@@ -34,112 +32,39 @@ export const prepareChartData = (};export const prepareUPlotConfig = ({- widgetId,- apiResponse,- tzDate,- minTimeScale,- maxTimeScale,- isLogScale,- thresholds,- softMin,- softMax,- spanGaps,- colorMapping,- lineInterpolation,+ widget,isDarkMode,currentQuery,- onDragSelect,onClick,- yAxisUnit,+ onDragSelect,+ apiResponse,+ timezone,panelMode,+ minTimeScale,+ maxTimeScale,}: {- widgetId: string;- apiResponse: MetricRangePayloadProps;- tzDate: uPlot.LocalDateFromUnix;- minTimeScale: number | undefined;- maxTimeScale: number | undefined;- isLogScale: boolean;- softMin: number | null;- softMax: number | null;- spanGaps: boolean;- colorMapping: Record<string, string>;- lineInterpolation: LineInterpolation;+ widget: Widgets;isDarkMode: boolean;- thresholds: ThresholdsDrawHookOptions;currentQuery: Query;- yAxisUnit: string;+ onClick: OnClickPluginOpts['onClick'];onDragSelect: (startTime: number, endTime: number) => void;- onClick?: OnClickPluginOpts['onClick'];+ apiResponse: MetricRangePayloadProps;+ timezone: Timezone;panelMode: PanelMode;+ minTimeScale?: number;+ maxTimeScale?: number;}): UPlotConfigBuilder => {- const builder = new UPlotConfigBuilder({- onDragSelect,- widgetId,- tzDate,- shouldSaveSelectionPreference: panelMode === PanelMode.DASHBOARD_VIEW,- selectionPreferencesSource: [- PanelMode.DASHBOARD_VIEW,- PanelMode.STANDALONE_VIEW,- ].includes(panelMode)- ? SelectionPreferencesSource.LOCAL_STORAGE- : SelectionPreferencesSource.IN_MEMORY,- });-- // X scale – time axis- builder.addScale({- scaleKey: 'x',- time: true,- min: minTimeScale,- max: maxTimeScale,- logBase: isLogScale ? 10 : undefined,- distribution: isLogScale- ? DistributionType.Logarithmic- : DistributionType.Linear,- });-- // Y scale – value axis, driven primarily by softMin/softMax and data- builder.addScale({- scaleKey: 'y',- time: false,- min: undefined,- max: undefined,- softMin: softMin ?? undefined,- softMax: softMax ?? undefined,- thresholds,- logBase: isLogScale ? 10 : undefined,- distribution: isLogScale- ? DistributionType.Logarithmic- : DistributionType.Linear,- });-- builder.addThresholds(thresholds);-- if (typeof onClick === 'function') {- builder.addPlugin(- onClickPlugin({- onClick,- apiResponse,- }),- );- }-- builder.addAxis({- scaleKey: 'x',- show: true,- side: 2,+ const builder = buildBaseConfig({+ widget,isDarkMode,- isLogScale: false,- panelType: PANEL_TYPES.TIME_SERIES,- });-- builder.addAxis({- scaleKey: 'y',- show: true,- side: 3,- isDarkMode,- isLogScale: false,- yAxisUnit,+ onClick,+ onDragSelect,+ apiResponse,+ timezone,+ panelMode,panelType: PANEL_TYPES.TIME_SERIES,+ minTimeScale,+ maxTimeScale,});apiResponse.data?.result?.forEach((series) => {@@ -157,14 +82,16 @@ export const prepareUPlotConfig = ({scaleKey: 'y',drawStyle: DrawStyle.Line,label: label,- colorMapping,- spanGaps,+ colorMapping: widget.customLegendColors ?? {},+ spanGaps: false,lineStyle: LineStyle.Solid,- lineInterpolation,+ lineInterpolation: LineInterpolation.Spline,showPoints: VisibilityMode.Never,pointSize: 5,isDarkMode,+ panelType: PANEL_TYPES.TIME_SERIES,});});+return builder;};diff --git a/frontend/src/container/DashboardContainer/visualization/panels/utils/baseConfigBuilder.ts b/frontend/src/container/DashboardContainer/visualization/panels/utils/baseConfigBuilder.tsnew file mode 100644index 0000000000..feeaff5b10--- /dev/null+++ b/frontend/src/container/DashboardContainer/visualization/panels/utils/baseConfigBuilder.ts@@ -0,0 +1,127 @@+import { Timezone } from 'components/CustomTimePicker/timezoneUtils';+import { PANEL_TYPES } from 'constants/queryBuilder';+import onClickPlugin, {+ OnClickPluginOpts,+} from 'lib/uPlotLib/plugins/onClickPlugin';+import {+ DistributionType,+ SelectionPreferencesSource,+} from 'lib/uPlotV2/config/types';+import { UPlotConfigBuilder } from 'lib/uPlotV2/config/UPlotConfigBuilder';+import { ThresholdsDrawHookOptions } from 'lib/uPlotV2/hooks/types';+import { Widgets } from 'types/api/dashboard/getAll';+import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';+import uPlot from 'uplot';++import { PanelMode } from '../types';++export interface BaseConfigBuilderProps {+ widget: Widgets;+ apiResponse: MetricRangePayloadProps;+ isDarkMode: boolean;+ onClick: OnClickPluginOpts['onClick'];+ onDragSelect: (startTime: number, endTime: number) => void;+ timezone: Timezone;+ panelMode: PanelMode;+ panelType: PANEL_TYPES;+ minTimeScale?: number;+ maxTimeScale?: number;+}++export function buildBaseConfig({+ widget,+ isDarkMode,+ onClick,+ onDragSelect,+ apiResponse,+ timezone,+ panelMode,+ panelType,+ minTimeScale,+ maxTimeScale,+}: BaseConfigBuilderProps): UPlotConfigBuilder {+ const tzDate = (timestamp: number): Date =>+ uPlot.tzDate(new Date(timestamp * 1e3), timezone.value);++ const builder = new UPlotConfigBuilder({+ onDragSelect,+ widgetId: widget.id,+ tzDate,+ shouldSaveSelectionPreference: panelMode === PanelMode.DASHBOARD_VIEW,+ selectionPreferencesSource: [+ PanelMode.DASHBOARD_VIEW,+ PanelMode.STANDALONE_VIEW,+ ].includes(panelMode)+ ? SelectionPreferencesSource.LOCAL_STORAGE+ : SelectionPreferencesSource.IN_MEMORY,+ });++ const thresholdOptions: ThresholdsDrawHookOptions = {+ scaleKey: 'y',+ thresholds: (widget.thresholds || []).map((threshold) => ({+ thresholdValue: threshold.thresholdValue ?? 0,+ thresholdColor: threshold.thresholdColor,+ thresholdUnit: threshold.thresholdUnit,+ thresholdLabel: threshold.thresholdLabel,+ })),+ yAxisUnit: widget.yAxisUnit,+ };++ builder.addThresholds(thresholdOptions);++ builder.addScale({+ scaleKey: 'x',+ time: true,+ min: minTimeScale,+ max: maxTimeScale,+ logBase: widget.isLogScale ? 10 : undefined,+ distribution: widget.isLogScale+ ? DistributionType.Logarithmic+ : DistributionType.Linear,+ });++ // Y scale – value axis, driven primarily by softMin/softMax and data+ builder.addScale({+ scaleKey: 'y',+ time: false,+ min: undefined,+ max: undefined,+ softMin: widget.softMin ?? undefined,+ softMax: widget.softMax ?? undefined,+ // thresholds,+ logBase: widget.isLogScale ? 10 : undefined,+ distribution: widget.isLogScale+ ? DistributionType.Logarithmic+ : DistributionType.Linear,+ });++ if (typeof onClick === 'function') {+ builder.addPlugin(+ onClickPlugin({+ onClick,+ apiResponse,+ }),+ );+ }++ builder.addAxis({+ scaleKey: 'x',+ show: true,+ side: 2,+ isDarkMode,+ isLogScale: widget.isLogScale,+ panelType,+ });++ builder.addAxis({+ scaleKey: 'y',+ show: true,+ side: 3,+ isDarkMode,+ isLogScale: widget.isLogScale,+ yAxisUnit: widget.yAxisUnit,+ panelType,+ });++ return builder;+}diff --git a/frontend/src/lib/uPlotV2/components/Tooltip/TimeSeriesTooltip.tsx b/frontend/src/lib/uPlotV2/components/Tooltip/TimeSeriesTooltip.tsxnew file mode 100644index 0000000000..cf83e61dec--- /dev/null+++ b/frontend/src/lib/uPlotV2/components/Tooltip/TimeSeriesTooltip.tsx@@ -0,0 +1,8 @@+import { TimeSeriesTooltipProps } from '../types';+import Tooltip from './Tooltip';++export default function TimeSeriesTooltip(+ props: TimeSeriesTooltipProps,+): JSX.Element {+ return <Tooltip {...props} />;+}diff --git a/frontend/src/lib/uPlotV2/components/Tooltip/Tooltip.tsx b/frontend/src/lib/uPlotV2/components/Tooltip/Tooltip.tsxindex 787625cd1c..b9693df1a9 100644--- a/frontend/src/lib/uPlotV2/components/Tooltip/Tooltip.tsx+++ b/frontend/src/lib/uPlotV2/components/Tooltip/Tooltip.tsx@@ -5,8 +5,7 @@ import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';import dayjs from 'dayjs';import { useIsDarkMode } from 'hooks/useDarkMode';-import { TooltipContentItem, TooltipProps } from '../types';-import { buildTooltipContent } from './utils';+import { TooltipProps } from '../types';import './Tooltip.styles.scss';@@ -14,14 +13,14 @@ const TOOLTIP_LIST_MAX_HEIGHT = 330;const TOOLTIP_ITEM_HEIGHT = 38;export default function Tooltip({- seriesIndex,- dataIndexes,uPlotInstance,timezone,- yAxisUnit = '',- decimalPrecision,+ content,}: TooltipProps): JSX.Element {const isDarkMode = useIsDarkMode();++ const tooltipContent = content ?? [];+const headerTitle = useMemo(() => {const data = uPlotInstance.data;const cursorIdx = uPlotInstance.cursor.idx;@@ -33,20 +32,6 @@ export default function Tooltip({.format(DATE_TIME_FORMATS.MONTH_DATETIME_SECONDS);}, [timezone, uPlotInstance.data, uPlotInstance.cursor.idx]);- const content = useMemo(- (): TooltipContentItem[] =>- buildTooltipContent({- data: uPlotInstance.data,- series: uPlotInstance.series,- dataIndexes,- activeSeriesIndex: seriesIndex,- uPlotInstance,- yAxisUnit,- decimalPrecision,- }),- [uPlotInstance, seriesIndex, dataIndexes, yAxisUnit, decimalPrecision],- );-return (<divclassName={cx(@@ -60,16 +45,16 @@ export default function Tooltip({<divstyle={{height: Math.min(- content.length * TOOLTIP_ITEM_HEIGHT,+ tooltipContent.length * TOOLTIP_ITEM_HEIGHT,TOOLTIP_LIST_MAX_HEIGHT,),minHeight: 0,}}>- {content.length > 0 ? (+ {tooltipContent.length > 0 ? (<VirtuosoclassName="uplot-tooltip-list"- data={content}+ data={tooltipContent}defaultItemHeight={TOOLTIP_ITEM_HEIGHT}itemContent={(_, item): JSX.Element => (<div className="uplot-tooltip-item">diff --git a/frontend/src/lib/uPlotV2/components/Tooltip/utils.ts b/frontend/src/lib/uPlotV2/components/Tooltip/utils.tsindex 305b6c0102..394e9e1b75 100644--- a/frontend/src/lib/uPlotV2/components/Tooltip/utils.ts+++ b/frontend/src/lib/uPlotV2/components/Tooltip/utils.ts@@ -20,6 +20,27 @@ export function resolveSeriesColor(return FALLBACK_SERIES_COLOR;}+export function getTooltipBaseValue({+ data,+ index,+ dataIndex,+ isStackedBarChart,+}: {+ data: AlignedData;+ index: number;+ dataIndex: number;+ isStackedBarChart?: boolean;+}): number | null {+ let baseValue = data[index][dataIndex] ?? null;+ if (isStackedBarChart && index + 1 < data.length && baseValue !== null) {+ const nextValue = data[index + 1][dataIndex] ?? null;+ if (nextValue !== null) {+ baseValue = baseValue - nextValue;+ }+ }+ return baseValue;+}+export function buildTooltipContent({data,series,@@ -28,6 +49,7 @@ export function buildTooltipContent({uPlotInstance,yAxisUnit,decimalPrecision,+ isStackedBarChart,}: {data: AlignedData;series: Series[];@@ -36,6 +58,7 @@ export function buildTooltipContent({uPlotInstance: uPlot;yAxisUnit: string;decimalPrecision?: PrecisionOption;+ isStackedBarChart?: boolean;}): TooltipContentItem[] {const active: TooltipContentItem[] = [];const rest: TooltipContentItem[] = [];@@ -52,23 +75,29 @@ export function buildTooltipContent({continue;}- const raw = data[index]?.[dataIndex];- const value = Number(raw);- const displayValue = Number.isNaN(value) ? 0 : value;+ const baseValue = getTooltipBaseValue({+ data,+ index,+ dataIndex,+ isStackedBarChart,+ });+const isActive = index === activeSeriesIndex;- const item: TooltipContentItem = {- label: String(s.label ?? ''),- value: displayValue,- tooltipValue: getToolTipValue(displayValue, yAxisUnit, decimalPrecision),- color: resolveSeriesColor(s.stroke, uPlotInstance, index),- isActive,- };+ if (Number.isFinite(baseValue) && baseValue !== null) {+ const item: TooltipContentItem = {+ label: String(s.label ?? ''),+ value: baseValue,+ tooltipValue: getToolTipValue(baseValue, yAxisUnit, decimalPrecision),+ color: resolveSeriesColor(s.stroke, uPlotInstance, index),+ isActive,+ };- if (isActive) {- active.push(item);- } else {- rest.push(item);+ if (isActive) {+ active.push(item);+ } else {+ rest.push(item);+ }}}diff --git a/frontend/src/lib/uPlotV2/components/types.ts b/frontend/src/lib/uPlotV2/components/types.tsindex e1a016df17..4655922720 100644--- a/frontend/src/lib/uPlotV2/components/types.ts+++ b/frontend/src/lib/uPlotV2/components/types.ts@@ -59,11 +59,22 @@ export interface TooltipRenderArgs {viaSync: boolean;}-export type TooltipProps = TooltipRenderArgs & {+export interface BaseTooltipProps {timezone: string;yAxisUnit?: string;decimalPrecision?: PrecisionOption;-};+ content?: TooltipContentItem[];+}++export interface TimeSeriesTooltipProps+ extends BaseTooltipProps,+ TooltipRenderArgs {}++export interface BarTooltipProps extends BaseTooltipProps, TooltipRenderArgs {+ isStackedBarChart?: boolean;+}++export type TooltipProps = TimeSeriesTooltipProps | BarTooltipProps;export enum LegendPosition {BOTTOM = 'bottom',diff --git a/frontend/src/lib/uPlotV2/config/types.ts b/frontend/src/lib/uPlotV2/config/types.tsindex 099c11c98d..7eef681a02 100644--- a/frontend/src/lib/uPlotV2/config/types.ts+++ b/frontend/src/lib/uPlotV2/config/types.ts@@ -110,6 +110,7 @@ export enum LineStyle {export enum DrawStyle {Line = 'line',Points = 'points',+ Bar = 'bar',}export enum LineInterpolation {@@ -128,7 +129,7 @@ export enum VisibilityMode {export interface SeriesProps {scaleKey: string;label?: string;-+ panelType: PANEL_TYPES;colorMapping: Record<string, string>;drawStyle: DrawStyle;pathBuilder?: Series.PathBuilder;diff --git a/frontend/src/lib/uPlotV2/plugins/TooltipPlugin/types.ts b/frontend/src/lib/uPlotV2/plugins/TooltipPlugin/types.tsindex 0a0ccc83b8..c8aed00c39 100644--- a/frontend/src/lib/uPlotV2/plugins/TooltipPlugin/types.ts+++ b/frontend/src/lib/uPlotV2/plugins/TooltipPlugin/types.ts@@ -1,7 +1,13 @@-import { CSSProperties } from 'react';+import type {+ CSSProperties,+ MutableRefObject,+ ReactNode,+ RefObject,+} from 'react';+import type uPlot from 'uplot';-import { TooltipRenderArgs } from '../../components/types';-import { UPlotConfigBuilder } from '../../config/UPlotConfigBuilder';+import type { TooltipRenderArgs } from '../../components/types';+import type { UPlotConfigBuilder } from '../../config/UPlotConfigBuilder';export const TOOLTIP_OFFSET = 10;@@ -17,7 +23,7 @@ export interface TooltipViewState {isHovering: boolean;isPinned: boolean;dismiss: () => void;- contents?: React.ReactNode;+ contents?: ReactNode;}export interface TooltipLayoutInfo {@@ -31,7 +37,7 @@ export interface TooltipPluginProps {canPinTooltip?: boolean;syncMode?: DashboardCursorSync;syncKey?: string;- render: (args: TooltipRenderArgs) => React.ReactNode;+ render: (args: TooltipRenderArgs) => ReactNode;maxWidth?: number;maxHeight?: number;}@@ -75,13 +81,11 @@ export interface TooltipControllerState {*/export interface TooltipControllerContext {controller: TooltipControllerState;- layoutRef: React.MutableRefObject<TooltipLayoutInfo | undefined>;- containerRef: React.RefObject<HTMLDivElement | null>;- rafId: React.MutableRefObject<number | null>;+ layoutRef: MutableRefObject<TooltipLayoutInfo | undefined>;+ containerRef: RefObject<HTMLDivElement | null>;+ rafId: MutableRefObject<number | null>;updateState: (updates: Partial<TooltipViewState>) => void;- renderRef: React.MutableRefObject<- (args: TooltipRenderArgs) => React.ReactNode- >;+ renderRef: MutableRefObject<(args: TooltipRenderArgs) => ReactNode>;syncMode: DashboardCursorSync;syncKey: string;canPinTooltip: boolean;