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: added changes to migerate alert chart component to new charts (#11308)
Abhi kumarfdbdbf27a8d1
diff --git a/frontend/src/container/CreateAlertV2/QuerySection/ChartPreview/ChartPreview.tsx b/frontend/src/container/CreateAlertV2/QuerySection/ChartPreview/ChartPreview.tsxindex 79dde33370..a9766fde74 100644--- a/frontend/src/container/CreateAlertV2/QuerySection/ChartPreview/ChartPreview.tsx+++ b/frontend/src/container/CreateAlertV2/QuerySection/ChartPreview/ChartPreview.tsx@@ -91,7 +91,6 @@ function ChartPreview({const renderQBChartPreview = (): JSX.Element => (<ChartPreviewComponentheadline={headline}- name=""query={stagedQuery}selectedInterval={globalSelectedInterval}alertDef={alertDef}@@ -107,7 +106,6 @@ function ChartPreview({const renderPromAndChQueryChartPreview = (): JSX.Element => (<ChartPreviewComponentheadline={headline}- name="Chart Preview"query={stagedQuery}alertDef={alertDef}selectedInterval={globalSelectedInterval}diff --git a/frontend/src/container/CreateAlertV2/QuerySection/__tests__/ChartPreview.test.tsx b/frontend/src/container/CreateAlertV2/QuerySection/__tests__/ChartPreview.test.tsxindex 5d20569dd4..edf4b09daa 100644--- a/frontend/src/container/CreateAlertV2/QuerySection/__tests__/ChartPreview.test.tsx+++ b/frontend/src/container/CreateAlertV2/QuerySection/__tests__/ChartPreview.test.tsx@@ -17,7 +17,6 @@ import { CreateAlertProvider } from '../../context';import ChartPreview from '../ChartPreview/ChartPreview';const REQUESTS_PER_SEC = 'requests/sec';-const CHART_PREVIEW_NAME = 'Chart Preview';const QUERY_TYPE_TEST_ID = 'query-type';const GRAPH_TYPE_TEST_ID = 'graph-type';const CHART_PREVIEW_COMPONENT_TEST_ID = 'chart-preview-component';@@ -34,7 +33,6 @@ jest.mock(return (<div data-testid={CHART_PREVIEW_COMPONENT_TEST_ID}><div data-testid="headline">{props.headline}</div>- <div data-testid="name">{props.name}</div><div data-testid={QUERY_TYPE_TEST_ID}>{props.query?.queryType}</div><div data-testid="selected-interval">{props.selectedInterval?.startTime}@@ -175,12 +173,6 @@ describe('ChartPreview', () => {);});- it('renders QueryBuilder chart preview with empty name when query type is QUERY_BUILDER', () => {- renderChartPreview();-- expect(screen.getByTestId('name')).toHaveTextContent('');- });-it('renders QueryBuilder chart preview with correct props', () => {renderChartPreview();@@ -191,7 +183,6 @@ describe('ChartPreview', () => {expect(screen.getByTestId(GRAPH_TYPE_TEST_ID)).toHaveTextContent(PANEL_TYPES.TIME_SERIES,);- expect(screen.getByTestId('name')).toHaveTextContent('');expect(screen.getByTestId('headline')).toBeInTheDocument();expect(screen.getByTestId('selected-interval')).toBeInTheDocument();});@@ -214,7 +205,6 @@ describe('ChartPreview', () => {expect(screen.getByTestId(CHART_PREVIEW_COMPONENT_TEST_ID),).toBeInTheDocument();- expect(screen.getByTestId('name')).toHaveTextContent(CHART_PREVIEW_NAME);expect(screen.getByTestId(QUERY_TYPE_TEST_ID)).toHaveTextContent(EQueryType.PROM,);@@ -238,7 +228,6 @@ describe('ChartPreview', () => {expect(screen.getByTestId(CHART_PREVIEW_COMPONENT_TEST_ID),).toBeInTheDocument();- expect(screen.getByTestId('name')).toHaveTextContent(CHART_PREVIEW_NAME);expect(screen.getByTestId(QUERY_TYPE_TEST_ID)).toHaveTextContent(EQueryType.CLICKHOUSE,);diff --git a/frontend/src/container/DashboardContainer/visualization/panels/BarPanel/BarPanel.tsx b/frontend/src/container/DashboardContainer/visualization/panels/BarPanel/BarPanel.tsxindex cc2d106771..31bc6d6988 100644--- a/frontend/src/container/DashboardContainer/visualization/panels/BarPanel/BarPanel.tsx+++ b/frontend/src/container/DashboardContainer/visualization/panels/BarPanel/BarPanel.tsx@@ -17,10 +17,11 @@ import { getTimeRange } from 'utils/getTimeRange';import BarChart from '../../charts/BarChart/BarChart';import ChartManager from '../../components/ChartManager/ChartManager';import { usePanelContextMenu } from '../../hooks/usePanelContextMenu';-import { prepareBarPanelConfig, prepareBarPanelData } from './utils';+import { prepareBarPanelConfig } from './utils';import '../Panel.styles.scss';import TooltipFooter from '../components/TooltipFooter';+import { prepareChartData } from 'lib/uPlotV2/utils/dataUtils';function BarPanel(props: PanelWrapperProps): JSX.Element {const {@@ -99,7 +100,7 @@ function BarPanel(props: PanelWrapperProps): JSX.Element {if (!queryResponse?.data?.payload) {return [];}- return prepareBarPanelData(queryResponse?.data?.payload);+ return prepareChartData(queryResponse?.data?.payload);}, [queryResponse?.data?.payload]);const layoutChildren = useMemo(() => {diff --git a/frontend/src/container/DashboardContainer/visualization/panels/BarPanel/utils.ts b/frontend/src/container/DashboardContainer/visualization/panels/BarPanel/utils.tsindex c28811f9ee..94c0ccfc66 100644--- a/frontend/src/container/DashboardContainer/visualization/panels/BarPanel/utils.ts+++ b/frontend/src/container/DashboardContainer/visualization/panels/BarPanel/utils.ts@@ -11,21 +11,10 @@ import { get } from 'lodash-es';import { Widgets } from 'types/api/dashboard/getAll';import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';import { Query } from 'types/api/queryBuilder/queryBuilderData';-import { AlignedData } from 'uplot';import { PanelMode } from '../types';-import { fillMissingXAxisTimestamps, getXAxisTimestamps } from '../utils';import { buildBaseConfig } from '../utils/baseConfigBuilder';-export function prepareBarPanelData(- apiResponse: MetricRangePayloadProps,-): AlignedData {- const seriesList = apiResponse?.data?.result || [];- const timestampArr = getXAxisTimestamps(seriesList);- const yAxisValuesArr = fillMissingXAxisTimestamps(timestampArr, seriesList);- return [timestampArr, ...yAxisValuesArr];-}-export function prepareBarPanelConfig({widget,isDarkMode,diff --git a/frontend/src/container/DashboardContainer/visualization/panels/TimeSeriesPanel/TimeSeriesPanel.tsx b/frontend/src/container/DashboardContainer/visualization/panels/TimeSeriesPanel/TimeSeriesPanel.tsxindex 337f5ca139..39efbb86f5 100644--- a/frontend/src/container/DashboardContainer/visualization/panels/TimeSeriesPanel/TimeSeriesPanel.tsx+++ b/frontend/src/container/DashboardContainer/visualization/panels/TimeSeriesPanel/TimeSeriesPanel.tsx@@ -17,10 +17,11 @@ import { useTimezone } from 'providers/Timezone';import uPlot from 'uplot';import { getTimeRange } from 'utils/getTimeRange';-import { prepareChartData, prepareUPlotConfig } from '../TimeSeriesPanel/utils';+import { prepareUPlotConfig } from '../TimeSeriesPanel/utils';import '../Panel.styles.scss';import TooltipFooter from '../components/TooltipFooter';+import { prepareChartData } from 'lib/uPlotV2/utils/dataUtils';function TimeSeriesPanel(props: PanelWrapperProps): JSX.Element {const {diff --git a/frontend/src/container/DashboardContainer/visualization/panels/TimeSeriesPanel/__tests__/utils.test.ts b/frontend/src/container/DashboardContainer/visualization/panels/TimeSeriesPanel/__tests__/utils.test.tsindex 66ae5533f6..7594a5b49c 100644--- a/frontend/src/container/DashboardContainer/visualization/panels/TimeSeriesPanel/__tests__/utils.test.ts+++ b/frontend/src/container/DashboardContainer/visualization/panels/TimeSeriesPanel/__tests__/utils.test.ts@@ -6,7 +6,8 @@ import {import { Query } from 'types/api/queryBuilder/queryBuilderData';import { PanelMode } from '../../types';-import { prepareChartData, prepareUPlotConfig } from '../utils';+import { prepareUPlotConfig } from '../utils';+import { prepareChartData } from 'lib/uPlotV2/utils/dataUtils';jest.mock('container/DashboardContainer/visualization/panels/utils/legendVisibilityUtils',diff --git a/frontend/src/container/DashboardContainer/visualization/panels/TimeSeriesPanel/utils.ts b/frontend/src/container/DashboardContainer/visualization/panels/TimeSeriesPanel/utils.tsindex aa0816eeed..bbf7b74c3f 100644--- a/frontend/src/container/DashboardContainer/visualization/panels/TimeSeriesPanel/utils.ts+++ b/frontend/src/container/DashboardContainer/visualization/panels/TimeSeriesPanel/utils.ts@@ -1,10 +1,6 @@import { ExecStats } from 'api/v5/v5';import { Timezone } from 'components/CustomTimePicker/timezoneUtils';import { PANEL_TYPES } from 'constants/queryBuilder';-import {- fillMissingXAxisTimestamps,- getXAxisTimestamps,-} from 'container/DashboardContainer/visualization/panels/utils';import { getLegend } from 'lib/dashboard/getQueryResults';import getLabelName from 'lib/getLabelName';import { OnClickPluginOpts } from 'lib/uPlotLib/plugins/onClickPlugin';@@ -15,42 +11,15 @@ import {LineStyle,} from 'lib/uPlotV2/config/types';import { UPlotConfigBuilder } from 'lib/uPlotV2/config/UPlotConfigBuilder';-import { isInvalidPlotValue } from 'lib/uPlotV2/utils/dataUtils';+import { hasSingleVisiblePoint } from 'lib/uPlotV2/utils/dataUtils';import get from 'lodash-es/get';import { Widgets } from 'types/api/dashboard/getAll';import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';import { Query } from 'types/api/queryBuilder/queryBuilderData';-import { QueryData } from 'types/api/widgets/getQuery';import { PanelMode } from '../types';import { buildBaseConfig } from '../utils/baseConfigBuilder';-export const prepareChartData = (- apiResponse: MetricRangePayloadProps,-): uPlot.AlignedData => {- const seriesList = apiResponse?.data?.result || [];- const timestampArr = getXAxisTimestamps(seriesList);- const yAxisValuesArr = fillMissingXAxisTimestamps(timestampArr, seriesList);-- return [timestampArr, ...yAxisValuesArr];-};--function hasSingleVisiblePointForSeries(series: QueryData): boolean {- const rawValues = series.values ?? [];- let validPointCount = 0;-- for (const [, rawValue] of rawValues) {- if (!isInvalidPlotValue(rawValue)) {- validPointCount += 1;- if (validPointCount > 1) {- return false;- }- }- }-- return true;-}-export const prepareUPlotConfig = ({widget,isDarkMode,@@ -107,7 +76,7 @@ export const prepareUPlotConfig = ({}apiResponse.data.result.forEach((series) => {- const hasSingleValidPoint = hasSingleVisiblePointForSeries(series);+ const hasSingleValidPoint = hasSingleVisiblePoint(series.values);const baseLabelName = getLabelName(series.metric,series.queryName || '', // querydiff --git a/frontend/src/container/FormAlertRules/ChartPreview/ChartContent.tsx b/frontend/src/container/FormAlertRules/ChartPreview/ChartContent.tsxnew file mode 100644index 0000000000..2bad02ab2f--- /dev/null+++ b/frontend/src/container/FormAlertRules/ChartPreview/ChartContent.tsx@@ -0,0 +1,118 @@+import { useMemo } from 'react';+import { Timezone } from 'components/CustomTimePicker/timezoneUtils';+import { PANEL_TYPES } from 'constants/queryBuilder';+import BarChart from 'container/DashboardContainer/visualization/charts/BarChart/BarChart';+import TimeSeries from 'container/DashboardContainer/visualization/charts/TimeSeries/TimeSeries';+import { ThresholdProps } from 'container/NewWidget/RightContainer/Threshold/types';+import { LegendPosition } from 'lib/uPlotV2/components/types';+import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';+import { Query } from 'types/api/queryBuilder/queryBuilderData';+import uPlot from 'uplot';++import {+ AlertChartPanelType,+ buildAlertChartConfig,+ buildChartId,+} from './utils';++// Panel types that render through the UPlotConfigBuilder pipeline.+// To support a new modern-chart panel type, add an entry here and extend+// `AlertChartPanelType` / `buildAlertChartConfig` to handle its series setup.+const SUPPORTED_CHARTS: Record<+ AlertChartPanelType,+ typeof TimeSeries | typeof BarChart+> = {+ [PANEL_TYPES.TIME_SERIES]: TimeSeries,+ [PANEL_TYPES.BAR]: BarChart,+};++const isSupportedPanelType = (+ panelType: PANEL_TYPES,+): panelType is AlertChartPanelType => panelType in SUPPORTED_CHARTS;++export interface ChartContentProps {+ panelType: PANEL_TYPES;+ alertId?: string;+ query: Query;+ apiResponse?: MetricRangePayloadProps;+ data: uPlot.AlignedData;+ thresholds: ThresholdProps[];+ yAxisUnit: string;+ legendPosition: LegendPosition;+ isDarkMode: boolean;+ timezone: Timezone;+ width: number;+ height: number;+ minTimeScale?: number;+ maxTimeScale?: number;+ onDragSelect: (start: number, end: number) => void;+}++export default function ChartContent({+ panelType,+ alertId,+ query,+ thresholds,+ apiResponse,+ data,+ yAxisUnit,+ isDarkMode,+ timezone,+ minTimeScale,+ maxTimeScale,+ onDragSelect,+ width,+ height,+ legendPosition,+}: ChartContentProps): JSX.Element | null {+ const supported = isSupportedPanelType(panelType);++ const config = useMemo(+ () =>+ buildAlertChartConfig({+ id: buildChartId(alertId),+ panelType: panelType as AlertChartPanelType,+ query,+ thresholds,+ apiResponse,+ yAxisUnit,+ isDarkMode,+ timezone,+ minTimeScale,+ maxTimeScale,+ onDragSelect,+ }),+ [+ alertId,+ panelType,+ query,+ thresholds,+ apiResponse,+ yAxisUnit,+ isDarkMode,+ timezone,+ minTimeScale,+ maxTimeScale,+ onDragSelect,+ ],+ );++ if (!supported) {+ return null;+ }++ const Component = SUPPORTED_CHARTS[panelType];++ return (+ <Component+ config={config}+ data={data}+ width={width}+ height={height}+ legendConfig={{ position: legendPosition }}+ canPinTooltip+ yAxisUnit={yAxisUnit}+ timezone={timezone}+ />+ );+}diff --git a/frontend/src/container/FormAlertRules/ChartPreview/index.tsx b/frontend/src/container/FormAlertRules/ChartPreview/index.tsxindex 6b0581232f..8725096ca4 100644--- a/frontend/src/container/FormAlertRules/ChartPreview/index.tsx+++ b/frontend/src/container/FormAlertRules/ChartPreview/index.tsx@@ -15,8 +15,6 @@ import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';import AnomalyAlertEvaluationView from 'container/AnomalyAlertEvaluationView';import { INITIAL_CRITICAL_THRESHOLD } from 'container/CreateAlertV2/context/constants';import { Threshold } from 'container/CreateAlertV2/context/types';-import { getLocalStorageGraphVisibilityState } from 'container/GridCardLayout/GridCard/utils';-import GridPanelSwitch from 'container/GridPanelSwitch';import { populateMultipleResults } from 'container/NewWidget/LeftContainer/WidgetGraph/util';import { getFormatNameByOptionId } from 'container/NewWidget/RightContainer/alertFomatCategories';import { timePreferenceType } from 'container/NewWidget/RightContainer/timeItems';@@ -32,8 +30,7 @@ import useUrlQuery from 'hooks/useUrlQuery';import GetMinMax from 'lib/getMinMax';import getTimeString from 'lib/getTimeString';import history from 'lib/history';-import { getUPlotChartOptions } from 'lib/uPlotLib/getUplotChartOptions';-import { getUPlotChartData } from 'lib/uPlotLib/utils/getUplotChartData';+import { LegendPosition } from 'lib/uPlotV2/components/types';import { isEmpty } from 'lodash-es';import { useAppContext } from 'providers/App/App';import { useTimezone } from 'providers/Timezone';@@ -41,24 +38,27 @@ import { UpdateTimeInterval } from 'store/actions';import { AppState } from 'store/reducers';import { Warning } from 'types/api';import { AlertDef } from 'types/api/alerts/def';-import { LegendPosition } from 'types/api/dashboard/getAll';import APIError from 'types/api/error';import { Query } from 'types/api/queryBuilder/queryBuilderData';import { EQueryType } from 'types/common/dashboard';import { GlobalReducer } from 'types/reducer/globalTime';-import uPlot from 'uplot';import { getGraphType } from 'utils/getGraphType';import { getSortedSeriesData } from 'utils/getSortedSeriesData';import { getTimeRange } from 'utils/getTimeRange';import { AlertDetectionTypes } from '..';+import ChartContent from './ChartContent';import { ChartContainer } from './styles';import { getThresholds } from './utils';import './ChartPreview.styles.scss';+import { prepareChartData } from 'lib/uPlotV2/utils/dataUtils';++// Height reserved for the `.chart-preview-header` strip rendered above the chart.+const CHART_PREVIEW_HEADER_HEIGHT = 48;+const CHART_PREVIEW_CONTAINER_PADDING = 16;export interface ChartPreviewProps {- name: string;query: Query | null;graphType?: PANEL_TYPES;selectedTime?: timePreferenceType;@@ -77,7 +77,6 @@ export interface ChartPreviewProps {// eslint-disable-next-line sonarjs/cognitive-complexityfunction ChartPreview({- name,query,graphType = PANEL_TYPES.TIME_SERIES,selectedTime = 'GLOBAL_TIME',@@ -113,14 +112,6 @@ function ChartPreview({const [minTimeScale, setMinTimeScale] = useState<number>();const [maxTimeScale, setMaxTimeScale] = useState<number>();- const [graphVisibility, setGraphVisibility] = useState<boolean[]>([]);- const legendScrollPositionRef = useRef<{- scrollTop: number;- scrollLeft: number;- }>({- scrollTop: 0,- scrollLeft: 0,- });const { currentQuery } = useQueryBuilder();const {@@ -219,18 +210,6 @@ function ChartPreview({setMaxTimeScale(endTime);}, [maxTime, minTime, globalSelectedInterval, queryResponse, setQueryStatus]);- // Initialize graph visibility from localStorage- useEffect(() => {- if (queryResponse?.data?.payload?.data?.result) {- const { graphVisibilityStates: localStoredVisibilityState } =- getLocalStorageGraphVisibilityState({- apiResponse: queryResponse.data.payload.data.result,- name: 'alert-chart-preview',- });- setGraphVisibility(localStoredVisibilityState);- }- }, [queryResponse?.data?.payload?.data?.result]);-if (queryResponse.data && graphType === PANEL_TYPES.BAR) {const sortedSeriesData = getSortedSeriesData(queryResponse.data?.payload.data.result,@@ -288,62 +267,17 @@ function ChartPreview({return LegendPosition.RIGHT;}, [queryResponse?.data?.payload?.data?.result?.length, showSideLegend]);- const options = useMemo(- () =>- getUPlotChartOptions({- id: 'alert_legend_widget',- yAxisUnit,- apiResponse: queryResponse?.data?.payload,- dimensions: {- height: containerDimensions?.height ? containerDimensions.height - 48 : 0,- width: containerDimensions?.width,- },- minTimeScale,- maxTimeScale,- isDarkMode,- onDragSelect,- thresholds: getThresholds(thresholds, t, optionName, yAxisUnit),- softMax: null,- softMin: null,- panelType: graphType,- tzDate: (timestamp: number) =>- uPlot.tzDate(new Date(timestamp * 1e3), timezone.value),- timezone: timezone.value,- currentQuery,- query: query || currentQuery,- graphsVisibilityStates: graphVisibility,- setGraphsVisibilityStates: setGraphVisibility,- enhancedLegend: true,- legendPosition,- legendScrollPosition: legendScrollPositionRef.current,- setLegendScrollPosition: (position: {- scrollTop: number;- scrollLeft: number;- }) => {- legendScrollPositionRef.current = position;- },- }),- [- yAxisUnit,- queryResponse?.data?.payload,- containerDimensions,- minTimeScale,- maxTimeScale,- isDarkMode,- onDragSelect,- thresholds,- t,- optionName,- graphType,- timezone.value,- currentQuery,- query,- graphVisibility,- legendPosition,- ],+ const resolvedThresholds = useMemo(+ () => getThresholds(thresholds, t, optionName, yAxisUnit),+ [thresholds, t, optionName, yAxisUnit],);- const chartData = getUPlotChartData(queryResponse?.data?.payload);+ const chartData = useMemo(() => {+ if (!queryResponse?.data?.payload) {+ return [];+ }+ return prepareChartData(queryResponse?.data?.payload);+ }, [queryResponse?.data?.payload]);const hasResultData = !!queryResponse?.data?.payload?.data?.result?.length;@@ -361,6 +295,14 @@ function ChartPreview({?.active || false;const isWarning = !isEmpty(queryResponse.data?.warning);++ const chartWidth = containerDimensions?.width+ ? containerDimensions.width - CHART_PREVIEW_CONTAINER_PADDING+ : 0;+ const chartHeight = containerDimensions?.height+ ? containerDimensions.height - CHART_PREVIEW_HEADER_HEIGHT+ : 0;+return (<div className="alert-chart-container" ref={graphRef}><ChartContainer>@@ -384,16 +326,22 @@ function ChartPreview({)}{chartDataAvailable && !isAnomalyDetectionAlert && (- <GridPanelSwitch- options={options}+ <ChartContentpanelType={graphType}+ alertId={alertDef?.id}+ query={query || currentQuery}+ apiResponse={queryResponse.data?.payload}data={chartData}- name={name || 'Chart Preview'}- panelData={- queryResponse.data?.payload?.data?.newResult?.data?.result || []- }- query={query || initialQueriesMap.metrics}+ thresholds={resolvedThresholds}yAxisUnit={yAxisUnit}+ legendPosition={legendPosition}+ isDarkMode={isDarkMode}+ timezone={timezone}+ width={chartWidth}+ height={chartHeight}+ minTimeScale={minTimeScale}+ maxTimeScale={maxTimeScale}+ onDragSelect={onDragSelect}/>)}diff --git a/frontend/src/container/FormAlertRules/ChartPreview/utils.ts b/frontend/src/container/FormAlertRules/ChartPreview/utils.tsindex 69707c0f59..9eec933b3c 100644--- a/frontend/src/container/FormAlertRules/ChartPreview/utils.ts+++ b/frontend/src/container/FormAlertRules/ChartPreview/utils.ts@@ -1,6 +1,10 @@import { Color } from '@signozhq/design-tokens';+import { ExecStats } from 'api/v5/v5';+import { Timezone } from 'components/CustomTimePicker/timezoneUtils';import { PANEL_TYPES } from 'constants/queryBuilder';import { Threshold } from 'container/CreateAlertV2/context/types';+import { PanelMode } from 'container/DashboardContainer/visualization/panels/types';+import { buildBaseConfig } from 'container/DashboardContainer/visualization/panels/utils/baseConfigBuilder';import { ThresholdProps } from 'container/NewWidget/RightContainer/Threshold/types';import {BooleanFormats,@@ -11,6 +15,20 @@ import {TimeFormats,} from 'container/NewWidget/RightContainer/types';import { TFunction } from 'i18next';+import { getLegend } from 'lib/dashboard/getQueryResults';+import getLabelName from 'lib/getLabelName';+import { OnClickPluginOpts } from 'lib/uPlotLib/plugins/onClickPlugin';+import {+ DrawStyle,+ FillMode,+ LineInterpolation,+ LineStyle,+} from 'lib/uPlotV2/config/types';+import { UPlotConfigBuilder } from 'lib/uPlotV2/config/UPlotConfigBuilder';+import { hasSingleVisiblePoint } from 'lib/uPlotV2/utils/dataUtils';+import { get } from 'lodash-es';+import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';+import { Query } from 'types/api/queryBuilder/queryBuilderData';import {dataFormatConfig,@@ -20,6 +38,8 @@ import {timeUnitsConfig,} from './config';+const CHART_ID_PREFIX = 'alert_legend_widget';+export function covertIntoDataFormats({value,sourceUnit,@@ -142,3 +162,110 @@ export const getThresholds = (});return thresholdsToReturn;};++export type AlertChartPanelType = PANEL_TYPES.TIME_SERIES | PANEL_TYPES.BAR;++export interface BuildAlertChartConfigParams {+ id: string;+ panelType: AlertChartPanelType;+ query: Query;+ thresholds: ThresholdProps[];+ apiResponse?: MetricRangePayloadProps;+ yAxisUnit?: string;+ isDarkMode: boolean;+ timezone: Timezone;+ minTimeScale?: number;+ maxTimeScale?: number;+ onDragSelect: (startTime: number, endTime: number) => void;+ onClick?: OnClickPluginOpts['onClick'];+}++export const buildAlertChartConfig = ({+ id,+ panelType,+ query,+ thresholds,+ apiResponse,+ yAxisUnit,+ isDarkMode,+ timezone,+ minTimeScale,+ maxTimeScale,+ onDragSelect,+ onClick,+}: BuildAlertChartConfigParams): UPlotConfigBuilder => {+ const stepIntervals: ExecStats['stepIntervals'] = get(+ apiResponse,+ 'data.newResult.meta.stepIntervals',+ {},+ );+ const stepIntervalValues = Object.values(stepIntervals);+ const minStepInterval = stepIntervalValues.length+ ? Math.min(...stepIntervalValues)+ : undefined;++ const builder = buildBaseConfig({+ id,+ panelType,+ panelMode: PanelMode.DASHBOARD_VIEW,+ thresholds,+ apiResponse,+ yAxisUnit,+ isDarkMode,+ timezone,+ minTimeScale,+ maxTimeScale,+ stepInterval: minStepInterval,+ onDragSelect,+ onClick,+ });++ const seriesList = apiResponse?.data?.result;+ if (!seriesList?.length) {+ return builder;+ }++ const isBar = panelType === PANEL_TYPES.BAR;++ seriesList.forEach((series) => {+ const baseLabelName = getLabelName(+ series.metric,+ series.queryName || '',+ series.legend || '',+ );+ const label = query ? getLegend(series, query, baseLabelName) : baseLabelName;++ if (isBar) {+ builder.addSeries({+ scaleKey: 'y',+ drawStyle: DrawStyle.Bar,+ label,+ colorMapping: {},+ isDarkMode,+ stepInterval: get(stepIntervals, series.queryName, undefined),+ });+ return;+ }++ const hasSingleValidPoint = hasSingleVisiblePoint(series.values);+ builder.addSeries({+ scaleKey: 'y',+ drawStyle: hasSingleValidPoint ? DrawStyle.Points : DrawStyle.Line,+ label,+ colorMapping: {},+ spanGaps: true,+ lineStyle: LineStyle.Solid,+ lineInterpolation: LineInterpolation.Spline,+ showPoints: hasSingleValidPoint,+ pointSize: 5,+ fillMode: FillMode.None,+ isDarkMode,+ metric: series.metric,+ });+ });++ return builder;+};++export const buildChartId = (id?: string): string =>+ id ? `${CHART_ID_PREFIX}_${id}` : CHART_ID_PREFIX;diff --git a/frontend/src/container/FormAlertRules/index.tsx b/frontend/src/container/FormAlertRules/index.tsxindex 7c218f6119..e447164112 100644--- a/frontend/src/container/FormAlertRules/index.tsx+++ b/frontend/src/container/FormAlertRules/index.tsx@@ -719,7 +719,6 @@ function FormAlertRules({panelType={panelType || PANEL_TYPES.TIME_SERIES}/>}- name=""query={stagedQuery}selectedInterval={globalSelectedInterval}alertDef={alertDef}@@ -739,7 +738,6 @@ function FormAlertRules({panelType={panelType || PANEL_TYPES.TIME_SERIES}/>}- name="Chart Preview"query={stagedQuery}alertDef={alertDef}selectedInterval={globalSelectedInterval}diff --git a/frontend/src/lib/uPlotV2/utils/dataUtils.ts b/frontend/src/lib/uPlotV2/utils/dataUtils.tsindex f56c155a47..2447524727 100644--- a/frontend/src/lib/uPlotV2/utils/dataUtils.ts+++ b/frontend/src/lib/uPlotV2/utils/dataUtils.ts@@ -1,3 +1,9 @@+import {+ fillMissingXAxisTimestamps,+ getXAxisTimestamps,+} from 'container/DashboardContainer/visualization/panels/utils';+import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';+/*** Checks if a value is invalid for plotting*@@ -52,6 +58,28 @@ export function normalizePlotValue(return value as number;}+/**+ * Returns true if at most one entry in `values` is a valid plot value.+ *+ * Used to decide whether a series should render as a single point (drawStyle:+ * Points) vs a line — a continuous line with only one visible sample is+ * invisible to the user.+ */+export function hasSingleVisiblePoint(+ values: ReadonlyArray<readonly [unknown, unknown]> | undefined,+): boolean {+ let validPointCount = 0;+ for (const [, rawValue] of values ?? []) {+ if (!isInvalidPlotValue(rawValue)) {+ validPointCount += 1;+ if (validPointCount > 1) {+ return false;+ }+ }+ }+ return true;+}+export interface SeriesSpanGapsOption {spanGaps?: boolean | number;}@@ -226,3 +254,21 @@ export function applySpanGapsToAlignedData(return [newX, ...transformedSeries] as uPlot.AlignedData;}++/** * Transforms raw API response into aligned data format expected by uPlot.+ *+ * The API response contains multiple series of time-value pairs, each with its+ * own set of timestamps. uPlot requires a single shared x-axis (timestamps)+ * and separate y-value arrays for each series, aligned by index. This function+ * extracts the unique sorted timestamps across all series and fills in missing+ * values with null to maintain alignment.+ */+export const prepareChartData = (+ apiResponse: MetricRangePayloadProps,+): uPlot.AlignedData => {+ const seriesList = apiResponse?.data?.result || [];+ const timestampArr = getXAxisTimestamps(seriesList);+ const yAxisValuesArr = fillMissingXAxisTimestamps(timestampArr, seriesList);++ return [timestampArr, ...yAxisValuesArr];+};