Skip to content

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.

test: added tests for barpanel hooks + utils (#10295)

Abhi kumar8f3839886315
diff --git a/frontend/src/container/DashboardContainer/visualization/charts/utils/__tests__/stackUtils.test.ts b/frontend/src/container/DashboardContainer/visualization/charts/utils/__tests__/stackUtils.test.ts
new file mode 100644
index 0000000000..d9e049652a
--- /dev/null
+++ b/frontend/src/container/DashboardContainer/visualization/charts/utils/__tests__/stackUtils.test.ts
@@ -0,0 +1,117 @@
+import { AlignedData } from 'uplot';
+
+import { getInitialStackedBands, stack } from '../stackUtils';
+
+describe('stackUtils', () => {
+ describe('stack', () => {
+ const neverOmit = (): boolean => false;
+
+ it('preserves time axis as first row', () => {
+ const data: AlignedData = [
+ [100, 200, 300],
+ [1, 2, 3],
+ [4, 5, 6],
+ ];
+ const { data: result } = stack(data, neverOmit);
+ expect(result[0]).toEqual([100, 200, 300]);
+ });
+
+ it('stacks value series cumulatively (last = raw, first = total)', () => {
+ // Time, then 3 value series. Stack order: last series stays raw, then we add upward.
+ const data: AlignedData = [
+ [0, 1, 2],
+ [1, 2, 3], // series 1
+ [4, 5, 6], // series 2
+ [7, 8, 9], // series 3
+ ];
+ const { data: result } = stack(data, neverOmit);
+ // result[1] = s1+s2+s3, result[2] = s2+s3, result[3] = s3
+ expect(result[1]).toEqual([12, 15, 18]); // 1+4+7, 2+5+8, 3+6+9
+ expect(result[2]).toEqual([11, 13, 15]); // 4+7, 5+8, 6+9
+ expect(result[3]).toEqual([7, 8, 9]);
+ });
+
+ it('treats null values as 0 when stacking', () => {
+ const data: AlignedData = [
+ [0, 1],
+ [1, null],
+ [null, 10],
+ ];
+ const { data: result } = stack(data, neverOmit);
+ expect(result[1]).toEqual([1, 10]); // total
+ expect(result[2]).toEqual([0, 10]); // last series with null→0
+ });
+
+ it('copies omitted series as-is without accumulating', () => {
+ // Omit series 2 (index 2); series 1 and 3 are stacked.
+ const data: AlignedData = [
+ [0, 1],
+ [10, 20], // series 1
+ [100, 200], // series 2 - omitted
+ [1, 2], // series 3
+ ];
+ const omitSeries2 = (i: number): boolean => i === 2;
+ const { data: result } = stack(data, omitSeries2);
+ // series 3 raw: [1, 2]; series 2 omitted: [100, 200] as-is; series 1 stacked with s3: [11, 22]
+ expect(result[1]).toEqual([11, 22]); // 10+1, 20+2
+ expect(result[2]).toEqual([100, 200]); // copied, not stacked
+ expect(result[3]).toEqual([1, 2]);
+ });
+
+ it('returns bands between consecutive visible series when none omitted', () => {
+ const data: AlignedData = [
+ [0, 1],
+ [1, 2],
+ [3, 4],
+ [5, 6],
+ ];
+ const { bands } = stack(data, neverOmit);
+ expect(bands).toEqual([{ series: [1, 2] }, { series: [2, 3] }]);
+ });
+
+ it('returns bands only between visible series when some are omitted', () => {
+ // 4 value series; omit index 2. Visible: 1, 3, 4. Bands: [1,3], [3,4]
+ const data: AlignedData = [[0], [1], [2], [3], [4]];
+ const omitSeries2 = (i: number): boolean => i === 2;
+ const { bands } = stack(data, omitSeries2);
+ expect(bands).toEqual([{ series: [1, 3] }, { series: [3, 4] }]);
+ });
+
+ it('returns empty bands when only one value series', () => {
+ const data: AlignedData = [
+ [0, 1],
+ [1, 2],
+ ];
+ const { bands } = stack(data, neverOmit);
+ expect(bands).toEqual([]);
+ });
+ });
+
+ describe('getInitialStackedBands', () => {
+ it('returns one band between each consecutive pair for seriesCount 3', () => {
+ expect(getInitialStackedBands(3)).toEqual([
+ { series: [1, 2] },
+ { series: [2, 3] },
+ ]);
+ });
+
+ it('returns empty array for seriesCount 0 or 1', () => {
+ expect(getInitialStackedBands(0)).toEqual([]);
+ expect(getInitialStackedBands(1)).toEqual([]);
+ });
+
+ it('returns single band for seriesCount 2', () => {
+ expect(getInitialStackedBands(2)).toEqual([{ series: [1, 2] }]);
+ });
+
+ it('returns bands [1,2], [2,3], ..., [n-1, n] for seriesCount n', () => {
+ const bands = getInitialStackedBands(5);
+ expect(bands).toEqual([
+ { series: [1, 2] },
+ { series: [2, 3] },
+ { series: [3, 4] },
+ { series: [4, 5] },
+ ]);
+ });
+ });
+});
diff --git a/frontend/src/container/DashboardContainer/visualization/charts/utils/stackUtils.ts b/frontend/src/container/DashboardContainer/visualization/charts/utils/stackUtils.ts
new file mode 100644
index 0000000000..1119d5faa9
--- /dev/null
+++ b/frontend/src/container/DashboardContainer/visualization/charts/utils/stackUtils.ts
@@ -0,0 +1,116 @@
+import uPlot, { AlignedData } from 'uplot';
+
+/**
+ * Stack data cumulatively (top-down: first series = top, last = bottom).
+ * When `omit(seriesIndex)` returns true, that series is excluded from stacking.
+ */
+export function stack(
+ data: AlignedData,
+ omit: (seriesIndex: number) => boolean,
+): { data: AlignedData; bands: uPlot.Band[] } {
+ const timeAxis = data[0];
+ const pointCount = timeAxis.length;
+ const valueSeriesCount = data.length - 1; // exclude time axis
+
+ const stackedSeries = buildStackedSeries({
+ data,
+ valueSeriesCount,
+ pointCount,
+ omit,
+ });
+ const bands = buildFillBands(valueSeriesCount + 1, omit); // +1 for 1-based series indices
+
+ return {
+ data: [timeAxis, ...stackedSeries] as AlignedData,
+ bands,
+ };
+}
+
+interface BuildStackedSeriesParams {
+ data: AlignedData;
+ valueSeriesCount: number;
+ pointCount: number;
+ omit: (seriesIndex: number) => boolean;
+}
+
+/**
+ * Accumulate from last series upward: last series = raw values, first = total.
+ * Omitted series are copied as-is (no accumulation).
+ */
+function buildStackedSeries({
+ data,
+ valueSeriesCount,
+ pointCount,
+ omit,
+}: BuildStackedSeriesParams): (number | null)[][] {
+ const stackedSeries: (number | null)[][] = Array(valueSeriesCount);
+ const cumulativeSums = Array(pointCount).fill(0) as number[];
+
+ for (let seriesIndex = valueSeriesCount; seriesIndex >= 1; seriesIndex--) {
+ const rawValues = data[seriesIndex] as (number | null)[];
+
+ if (omit(seriesIndex)) {
+ stackedSeries[seriesIndex - 1] = rawValues;
+ } else {
+ stackedSeries[seriesIndex - 1] = rawValues.map((rawValue, pointIndex) => {
+ const numericValue = rawValue == null ? 0 : Number(rawValue);
+ return (cumulativeSums[pointIndex] += numericValue);
+ });
+ }
+ }
+
+ return stackedSeries;
+}
+
+/**
+ * Bands define fill between consecutive visible series for stacked appearance.
+ * uPlot format: [upperSeriesIdx, lowerSeriesIdx].
+ */
+function buildFillBands(
+ seriesLength: number,
+ omit: (seriesIndex: number) => boolean,
+): uPlot.Band[] {
+ const bands: uPlot.Band[] = [];
+
+ for (let seriesIndex = 1; seriesIndex < seriesLength; seriesIndex++) {
+ if (omit(seriesIndex)) {
+ continue;
+ }
+ const nextVisibleSeriesIndex = findNextVisibleSeriesIndex(
+ seriesLength,
+ seriesIndex,
+ omit,
+ );
+ if (nextVisibleSeriesIndex !== -1) {
+ bands.push({ series: [seriesIndex, nextVisibleSeriesIndex] });
+ }
+ }
+
+ return bands;
+}
+
+function findNextVisibleSeriesIndex(
+ seriesLength: number,
+ afterIndex: number,
+ omit: (seriesIndex: number) => boolean,
+): number {
+ for (let i = afterIndex + 1; i < seriesLength; i++) {
+ if (!omit(i)) {
+ return i;
+ }
+ }
+ return -1;
+}
+
+/**
+ * Returns band indices for initial stacked state (no series omitted).
+ * Top-down: first series at top, band fills between consecutive series.
+ * uPlot band format: [upperSeriesIdx, lowerSeriesIdx].
+ */
+export function getInitialStackedBands(seriesCount: number): uPlot.Band[] {
+ const bands: uPlot.Band[] = [];
+ for (let seriesIndex = 1; seriesIndex < seriesCount; seriesIndex++) {
+ bands.push({ series: [seriesIndex, seriesIndex + 1] });
+ }
+ return bands;
+}
diff --git a/frontend/src/container/DashboardContainer/visualization/hooks/__tests__/useBarChartStacking.test.ts b/frontend/src/container/DashboardContainer/visualization/hooks/__tests__/useBarChartStacking.test.ts
new file mode 100644
index 0000000000..5e6809aeb5
--- /dev/null
+++ b/frontend/src/container/DashboardContainer/visualization/hooks/__tests__/useBarChartStacking.test.ts
@@ -0,0 +1,313 @@
+import { renderHook } from '@testing-library/react';
+import uPlot from 'uplot';
+
+import type { UseBarChartStackingParams } from '../useBarChartStacking';
+import { useBarChartStacking } from '../useBarChartStacking';
+
+type MockConfig = { addHook: jest.Mock };
+
+function asConfig(c: MockConfig): UseBarChartStackingParams['config'] {
+ return (c as unknown) as UseBarChartStackingParams['config'];
+}
+
+function createMockConfig(): {
+ config: MockConfig;
+ invokeSetData: (plot: uPlot) => void;
+ invokeSetSeries: (
+ plot: uPlot,
+ seriesIndex: number | null,
+ opts: Partial<uPlot.Series> & { focus?: boolean },
+ ) => void;
+ removeSetData: jest.Mock;
+ removeSetSeries: jest.Mock;
+} {
+ let setDataHandler: ((plot: uPlot) => void) | null = null;
+ let setSeriesHandler:
+ | ((plot: uPlot, seriesIndex: number | null, opts: uPlot.Series) => void)
+ | null = null;
+
+ const removeSetData = jest.fn();
+ const removeSetSeries = jest.fn();
+
+ const addHook = jest.fn(
+ (
+ hookName: string,
+ handler: (plot: uPlot, ...args: unknown[]) => void,
+ ): (() => void) => {
+ if (hookName === 'setData') {
+ setDataHandler = handler as (plot: uPlot) => void;
+ return removeSetData;
+ }
+ if (hookName === 'setSeries') {
+ setSeriesHandler = handler as (
+ plot: uPlot,
+ seriesIndex: number | null,
+ opts: uPlot.Series,
+ ) => void;
+ return removeSetSeries;
+ }
+ return jest.fn();
+ },
+ );
+
+ const config: MockConfig = { addHook };
+
+ const invokeSetData = (plot: uPlot): void => {
+ setDataHandler?.(plot);
+ };
+
+ const invokeSetSeries = (
+ plot: uPlot,
+ seriesIndex: number | null,
+ opts: Partial<uPlot.Series> & { focus?: boolean },
+ ): void => {
+ setSeriesHandler?.(plot, seriesIndex, opts as uPlot.Series);
+ };
+
+ return {
+ config,
+ invokeSetData,
+ invokeSetSeries,
+ removeSetData,
+ removeSetSeries,
+ };
+}
+
+function createMockPlot(overrides: Partial<uPlot> = {}): uPlot {
+ return ({
+ data: [
+ [0, 1, 2],
+ [1, 2, 3],
+ [4, 5, 6],
+ ],
+ series: [{ show: true }, { show: true }, { show: true }],
+ delBand: jest.fn(),
+ addBand: jest.fn(),
+ setData: jest.fn(),
+ ...overrides,
+ } as unknown) as uPlot;
+}
+
+describe('useBarChartStacking', () => {
+ it('returns data as-is when isStackedBarChart is false', () => {
+ const data: uPlot.AlignedData = [
+ [100, 200],
+ [1, 2],
+ [3, 4],
+ ];
+ const { result } = renderHook(() =>
+ useBarChartStacking({
+ data,
+ isStackedBarChart: false,
+ config: null,
+ }),
+ );
+ expect(result.current).toBe(data);
+ });
+
+ it('returns data as-is when config is null and isStackedBarChart is true', () => {
+ const data: uPlot.AlignedData = [
+ [0, 1],
+ [1, 2],
+ [4, 5],
+ ];
+ const { result } = renderHook(() =>
+ useBarChartStacking({
+ data,
+ isStackedBarChart: true,
+ config: null,
+ }),
+ );
+ // Still returns stacked data (computed in useMemo); no hooks registered
+ expect(result.current[0]).toEqual([0, 1]);
+ expect(result.current[1]).toEqual([5, 7]); // stacked
+ expect(result.current[2]).toEqual([4, 5]);
+ });
+
+ it('returns stacked data when isStackedBarChart is true and multiple value series', () => {
+ const data: uPlot.AlignedData = [
+ [0, 1, 2],
+ [1, 2, 3],
+ [4, 5, 6],
+ [7, 8, 9],
+ ];
+ const { result } = renderHook(() =>
+ useBarChartStacking({
+ data,
+ isStackedBarChart: true,
+ config: null,
+ }),
+ );
+ expect(result.current[0]).toEqual([0, 1, 2]);
+ expect(result.current[1]).toEqual([12, 15, 18]); // s1+s2+s3
+ expect(result.current[2]).toEqual([11, 13, 15]); // s2+s3
+ expect(result.current[3]).toEqual([7, 8, 9]);
+ });
+
+ it('returns data as-is when only one value series (no stacking needed)', () => {
+ const data: uPlot.AlignedData = [
+ [0, 1],
+ [1, 2],
+ ];
+ const { result } = renderHook(() =>
+ useBarChartStacking({
+ data,
+ isStackedBarChart: true,
+ config: null,
+ }),
+ );
+ expect(result.current).toEqual(data);
+ });
+
+ it('registers setData and setSeries hooks when isStackedBarChart and config provided', () => {
+ const { config } = createMockConfig();
+ const data: uPlot.AlignedData = [
+ [0, 1],
+ [1, 2],
+ [3, 4],
+ ];
+
+ renderHook(() =>
+ useBarChartStacking({
+ data,
+ isStackedBarChart: true,
+ config: asConfig(config),
+ }),
+ );
+
+ expect(config.addHook).toHaveBeenCalledWith('setData', expect.any(Function));
+ expect(config.addHook).toHaveBeenCalledWith(
+ 'setSeries',
+ expect.any(Function),
+ );
+ });
+
+ it('does not register hooks when isStackedBarChart is false', () => {
+ const { config } = createMockConfig();
+ const data: uPlot.AlignedData = [
+ [0, 1],
+ [1, 2],
+ [3, 4],
+ ];
+
+ renderHook(() =>
+ useBarChartStacking({
+ data,
+ isStackedBarChart: false,
+ config: asConfig(config),
+ }),
+ );
+
+ expect(config.addHook).not.toHaveBeenCalled();
+ });
+
+ it('calls cleanup when unmounted', () => {
+ const { config, removeSetData, removeSetSeries } = createMockConfig();
+ const data: uPlot.AlignedData = [
+ [0, 1],
+ [1, 2],
+ [3, 4],
+ ];
+
+ const { unmount } = renderHook(() =>
+ useBarChartStacking({
+ data,
+ isStackedBarChart: true,
+ config: asConfig(config),
+ }),
+ );
+
+ unmount();
+
+ expect(removeSetData).toHaveBeenCalled();
+ expect(removeSetSeries).toHaveBeenCalled();
+ });
+
+ it('re-stacks and updates plot when setData hook is invoked', () => {
+ const { config, invokeSetData } = createMockConfig();
+ const data: uPlot.AlignedData = [
+ [0, 1, 2],
+ [1, 2, 3],
+ [4, 5, 6],
+ ];
+ const plot = createMockPlot({
+ data: [
+ [0, 1, 2],
+ [5, 7, 9],
+ [4, 5, 6],
+ ],
+ });
+
+ renderHook(() =>
+ useBarChartStacking({
+ data,
+ isStackedBarChart: true,
+ config: asConfig(config),
+ }),
+ );
+
+ invokeSetData(plot);
+
+ expect(plot.delBand).toHaveBeenCalledWith(null);
+ expect(plot.addBand).toHaveBeenCalled();
+ expect(plot.setData).toHaveBeenCalledWith(
+ expect.arrayContaining([
+ [0, 1, 2],
+ expect.any(Array), // stacked row 1
+ expect.any(Array), // stacked row 2
+ ]),
+ );
+ });
+
+ it('re-stacks when setSeries hook is invoked (e.g. legend toggle)', () => {
+ const { config, invokeSetSeries } = createMockConfig();
+ const data: uPlot.AlignedData = [
+ [0, 1],
+ [10, 20],
+ [5, 10],
+ ];
+ // Plot data must match unstacked length so canApplyStacking passes
+ const plot = createMockPlot({
+ data: [
+ [0, 1],
+ [15, 30],
+ [5, 10],
+ ],
+ });
+
+ renderHook(() =>
+ useBarChartStacking({
+ data,
+ isStackedBarChart: true,
+ config: asConfig(config),
+ }),
+ );
+
+ invokeSetSeries(plot, 1, { show: false });
+
+ expect(plot.setData).toHaveBeenCalled();
+ });
+
+ it('does not re-stack when setSeries is called with focus option', () => {
+ const { config, invokeSetSeries } = createMockConfig();
+ const data: uPlot.AlignedData = [
+ [0, 1],
+ [1, 2],
+ [3, 4],
+ ];
+ const plot = createMockPlot();
+
+ renderHook(() =>
+ useBarChartStacking({
+ data,
+ isStackedBarChart: true,
+ config: asConfig(config),
+ }),
+ );
+
+ (plot.setData as jest.Mock).mockClear();
+ invokeSetSeries(plot, 1, { focus: true } as uPlot.Series);
+
+ expect(plot.setData).not.toHaveBeenCalled();
+ });
+});