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.

fix: added fix for tooltip prox on hover in uplot (#10345)

Abhi kumar9f4d9eef4681
diff --git a/frontend/src/container/DashboardContainer/visualization/panels/BarPanel/utils.ts b/frontend/src/container/DashboardContainer/visualization/panels/BarPanel/utils.ts
index 9d30259f3f..6c7ea0ae7f 100644
--- a/frontend/src/container/DashboardContainer/visualization/panels/BarPanel/utils.ts
+++ b/frontend/src/container/DashboardContainer/visualization/panels/BarPanel/utils.ts
@@ -1,3 +1,4 @@
+import { ExecStats } from 'api/v5/v5';
import { Timezone } from 'components/CustomTimePicker/timezoneUtils';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { getInitialStackedBands } from 'container/DashboardContainer/visualization/charts/utils/stackSeriesUtils';
@@ -54,6 +55,13 @@ export function prepareBarPanelConfig({
minTimeScale?: number;
maxTimeScale?: number;
}): UPlotConfigBuilder {
+ const stepIntervals: ExecStats['stepIntervals'] = get(
+ apiResponse,
+ 'data.newResult.meta.stepIntervals',
+ {},
+ );
+ const minStepInterval = Math.min(...Object.values(stepIntervals));
+
const builder = buildBaseConfig({
widget,
isDarkMode,
@@ -65,12 +73,7 @@ export function prepareBarPanelConfig({
panelType: PANEL_TYPES.BAR,
minTimeScale,
maxTimeScale,
- });
-
- builder.setCursor({
- focus: {
- prox: 1e3,
- },
+ stepInterval: minStepInterval,
});
if (widget.stackedBarChart) {
@@ -78,12 +81,6 @@ export function prepareBarPanelConfig({
builder.setBands(getInitialStackedBands(seriesCount));
}
- const stepIntervals: Record<string, number> = get(
- apiResponse,
- 'data.newResult.meta.stepIntervals',
- {},
- );
-
const seriesList: QueryData[] = apiResponse?.data?.result || [];
seriesList.forEach((series) => {
const baseLabelName = getLabelName(
diff --git a/frontend/src/container/DashboardContainer/visualization/panels/TimeSeriesPanel/utils.ts b/frontend/src/container/DashboardContainer/visualization/panels/TimeSeriesPanel/utils.ts
index 4f2e7588dd..c1edca4104 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 { ExecStats } from 'api/v5/v5';
import { Timezone } from 'components/CustomTimePicker/timezoneUtils';
import { PANEL_TYPES } from 'constants/queryBuilder';
import {
@@ -14,6 +15,7 @@ import {
VisibilityMode,
} from 'lib/uPlotV2/config/types';
import { UPlotConfigBuilder } from 'lib/uPlotV2/config/UPlotConfigBuilder';
+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';
@@ -54,6 +56,13 @@ export const prepareUPlotConfig = ({
minTimeScale?: number;
maxTimeScale?: number;
}): UPlotConfigBuilder => {
+ const stepIntervals: ExecStats['stepIntervals'] = get(
+ apiResponse,
+ 'data.newResult.meta.stepIntervals',
+ {},
+ );
+ const minStepInterval = Math.min(...Object.values(stepIntervals));
+
const builder = buildBaseConfig({
widget,
isDarkMode,
@@ -65,9 +74,12 @@ export const prepareUPlotConfig = ({
panelType: PANEL_TYPES.TIME_SERIES,
minTimeScale,
maxTimeScale,
+ stepInterval: minStepInterval,
});
- apiResponse.data?.result?.forEach((series) => {
+ const seriesList = apiResponse.data?.result || [];
+
+ seriesList.forEach((series) => {
const baseLabelName = getLabelName(
series.metric,
series.queryName || '', // query
diff --git a/frontend/src/container/DashboardContainer/visualization/panels/utils/__tests__/baseConfigBuilder.test.ts b/frontend/src/container/DashboardContainer/visualization/panels/utils/__tests__/baseConfigBuilder.test.ts
new file mode 100644
index 0000000000..e68e21bf86
--- /dev/null
+++ b/frontend/src/container/DashboardContainer/visualization/panels/utils/__tests__/baseConfigBuilder.test.ts
@@ -0,0 +1,233 @@
+import { PANEL_TYPES } from 'constants/queryBuilder';
+import { STEP_INTERVAL_MULTIPLIER } from 'lib/uPlotV2/constants';
+import { Widgets } from 'types/api/dashboard/getAll';
+import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';
+import uPlot from 'uplot';
+
+import { PanelMode } from '../../types';
+import { buildBaseConfig } from '../baseConfigBuilder';
+
+jest.mock(
+ 'container/DashboardContainer/visualization/panels/utils/legendVisibilityUtils',
+ () => ({
+ getStoredSeriesVisibility: jest.fn(),
+ }),
+);
+
+jest.mock('lib/uPlotV2/utils', () => ({
+ calculateWidthBasedOnStepInterval: jest.fn(),
+}));
+
+const calculateWidthBasedOnStepIntervalMock = jest.requireMock(
+ 'lib/uPlotV2/utils',
+).calculateWidthBasedOnStepInterval as jest.Mock;
+
+jest.mock('lib/uPlotLib/plugins/onClickPlugin', () => ({
+ __esModule: true,
+ default: jest.fn().mockReturnValue({ name: 'onClickPlugin' }),
+}));
+
+const createWidget = (overrides: Partial<Widgets> = {}): Widgets =>
+ ({
+ id: 'widget-1',
+ yAxisUnit: 'ms',
+ isLogScale: false,
+ softMin: undefined,
+ softMax: undefined,
+ thresholds: [],
+ ...overrides,
+ } as Widgets);
+
+const createApiResponse = (
+ overrides: Partial<MetricRangePayloadProps> = {},
+): MetricRangePayloadProps =>
+ ({
+ data: { result: [], resultType: 'matrix', newResult: null },
+ ...overrides,
+ } as MetricRangePayloadProps);
+
+const baseProps = {
+ widget: createWidget(),
+ apiResponse: createApiResponse(),
+ isDarkMode: true,
+ panelMode: PanelMode.DASHBOARD_VIEW,
+ panelType: PANEL_TYPES.TIME_SERIES,
+};
+
+describe('buildBaseConfig', () => {
+ it('returns a UPlotConfigBuilder instance', () => {
+ const builder = buildBaseConfig(baseProps);
+
+ expect(builder).toBeDefined();
+ expect(typeof builder.getConfig).toBe('function');
+ expect(typeof builder.getLegendItems).toBe('function');
+ });
+
+ it('configures builder with widgetId and DASHBOARD_VIEW preferences', () => {
+ const builder = buildBaseConfig({
+ ...baseProps,
+ panelMode: PanelMode.DASHBOARD_VIEW,
+ widget: createWidget({ id: 'my-widget' }),
+ });
+
+ expect(builder.getWidgetId()).toBe('my-widget');
+ expect(builder.getShouldSaveSelectionPreference()).toBe(true);
+ });
+
+ it('configures builder with IN_MEMORY selection when panelMode is DASHBOARD_EDIT', () => {
+ const builder = buildBaseConfig({
+ ...baseProps,
+ panelMode: PanelMode.DASHBOARD_EDIT,
+ });
+
+ expect(builder.getShouldSaveSelectionPreference()).toBe(false);
+ const config = builder.getConfig();
+ expect(config.series).toBeDefined();
+ });
+
+ it('passes stepInterval to builder and cursor prox uses width * multiplier', () => {
+ const stepInterval = 60;
+ const mockWidth = 100;
+ calculateWidthBasedOnStepIntervalMock.mockReturnValue(mockWidth);
+
+ const builder = buildBaseConfig({
+ ...baseProps,
+ stepInterval,
+ });
+
+ const config = builder.getConfig();
+ const prox = config.cursor?.hover?.prox;
+ expect(typeof prox).toBe('function');
+
+ const uPlotInstance = {} as uPlot;
+ const proxResult = (prox as (u: uPlot) => number)(uPlotInstance);
+
+ expect(calculateWidthBasedOnStepIntervalMock).toHaveBeenCalledWith({
+ uPlotInstance,
+ stepInterval,
+ });
+ expect(proxResult).toBe(mockWidth * STEP_INTERVAL_MULTIPLIER);
+ });
+
+ it('adds x scale with time config and min/max when provided', () => {
+ const builder = buildBaseConfig({
+ ...baseProps,
+ minTimeScale: 1000,
+ maxTimeScale: 2000,
+ });
+
+ const config = builder.getConfig();
+ expect(config.scales?.x).toBeDefined();
+ expect(config.scales?.x?.time).toBe(true);
+ const range = config.scales?.x?.range;
+ expect(Array.isArray(range)).toBe(true);
+ expect((range as [number, number])[0]).toBe(1000);
+ });
+
+ it('configures log scale on y axis when widget.isLogScale is true', () => {
+ const builder = buildBaseConfig({
+ ...baseProps,
+ widget: createWidget({ isLogScale: true }),
+ });
+
+ const config = builder.getConfig();
+ expect(config.scales?.y).toBeDefined();
+ expect(config.scales?.y?.log).toBe(10);
+ });
+
+ it('adds onClick plugin when onClick is a function', () => {
+ const onClickPlugin = jest.requireMock('lib/uPlotLib/plugins/onClickPlugin')
+ .default;
+ const onClick = jest.fn();
+
+ buildBaseConfig({
+ ...baseProps,
+ onClick,
+ apiResponse: createApiResponse(),
+ });
+
+ expect(onClickPlugin).toHaveBeenCalledWith({
+ onClick,
+ apiResponse: expect.any(Object),
+ });
+ });
+
+ it('does not add onClick plugin when onClick is not a function', () => {
+ const onClickPlugin = jest.requireMock('lib/uPlotLib/plugins/onClickPlugin')
+ .default;
+
+ const builder = buildBaseConfig({
+ ...baseProps,
+ });
+
+ const config = builder.getConfig();
+ const plugins = config.plugins ?? [];
+ expect(
+ plugins.some((p) => (p as { name?: string }).name === 'onClickPlugin'),
+ ).toBe(false);
+ expect(onClickPlugin).not.toHaveBeenCalled();
+ });
+
+ it('adds thresholds from widget', () => {
+ const builder = buildBaseConfig({
+ ...baseProps,
+ widget: createWidget({
+ thresholds: [
+ {
+ thresholdValue: 80,
+ thresholdColor: '#ff0000',
+ thresholdUnit: 'ms',
+ thresholdLabel: 'High',
+ },
+ ] as Widgets['thresholds'],
+ }),
+ });
+
+ const config = builder.getConfig();
+ const drawHooks = config.hooks?.draw ?? [];
+ expect(drawHooks.length).toBeGreaterThan(0);
+ });
+
+ it('adds x and y axes with correct scaleKeys and panelType', () => {
+ const builder = buildBaseConfig(baseProps);
+
+ const config = builder.getConfig();
+ expect(config.axes).toHaveLength(2);
+ expect(config.axes?.[0].scale).toBe('x');
+ expect(config.axes?.[1].scale).toBe('y');
+ });
+
+ it('sets tzDate when timezone is provided', () => {
+ const builder = buildBaseConfig({
+ ...baseProps,
+ timezone: {
+ name: 'America/New_York',
+ value: 'America/New_York',
+ offset: 'UTC-5',
+ searchIndex: 'America/New_York',
+ },
+ });
+
+ const config = builder.getConfig();
+ expect(config.tzDate).toBeDefined();
+ expect(typeof config.tzDate).toBe('function');
+ });
+
+ it('leaves tzDate undefined when timezone is not provided', () => {
+ const builder = buildBaseConfig(baseProps);
+
+ const config = builder.getConfig();
+ expect(config.tzDate).toBeUndefined();
+ });
+
+ it('register setSelect hook when onDragSelect is provided', () => {
+ const onDragSelect = jest.fn();
+ const builder = buildBaseConfig({
+ ...baseProps,
+ onDragSelect,
+ });
+
+ const config = builder.getConfig();
+ expect(config.hooks?.setSelect).toBeDefined();
+ });
+});
diff --git a/frontend/src/container/DashboardContainer/visualization/panels/utils/baseConfigBuilder.ts b/frontend/src/container/DashboardContainer/visualization/panels/utils/baseConfigBuilder.ts
index 0d6ed75fde..443cfcb0c1 100644
--- a/frontend/src/container/DashboardContainer/visualization/panels/utils/baseConfigBuilder.ts
+++ b/frontend/src/container/DashboardContainer/visualization/panels/utils/baseConfigBuilder.ts
@@ -26,6 +26,7 @@ export interface BaseConfigBuilderProps {
panelType: PANEL_TYPES;
minTimeScale?: number;
maxTimeScale?: number;
+ stepInterval?: number;
}
export function buildBaseConfig({
@@ -39,6 +40,7 @@ export function buildBaseConfig({
panelType,
minTimeScale,
maxTimeScale,
+ stepInterval,
}: BaseConfigBuilderProps): UPlotConfigBuilder {
const tzDate = timezone
? (timestamp: number): Date =>
@@ -56,6 +58,7 @@ export function buildBaseConfig({
].includes(panelMode)
? SelectionPreferencesSource.LOCAL_STORAGE
: SelectionPreferencesSource.IN_MEMORY,
+ stepInterval,
});
const thresholdOptions: ThresholdsDrawHookOptions = {
diff --git a/frontend/src/lib/uPlotV2/config/UPlotConfigBuilder.ts b/frontend/src/lib/uPlotV2/config/UPlotConfigBuilder.ts
index c6a642bc10..75487aa05b 100644
--- a/frontend/src/lib/uPlotV2/config/UPlotConfigBuilder.ts
+++ b/frontend/src/lib/uPlotV2/config/UPlotConfigBuilder.ts
@@ -8,10 +8,15 @@ import noop from 'lodash-es/noop';
import uPlot, { Cursor, Hooks, Options } from 'uplot';
import {
- ConfigBuilder,
- ConfigBuilderProps,
DEFAULT_CURSOR_CONFIG,
+ DEFAULT_HOVER_PROXIMITY_VALUE,
DEFAULT_PLOT_CONFIG,
+ STEP_INTERVAL_MULTIPLIER,
+} from '../constants';
+import { calculateWidthBasedOnStepInterval } from '../utils';
+import {
+ ConfigBuilder,
+ ConfigBuilderProps,
LegendItem,
SelectionPreferencesSource,
} from './types';
@@ -45,6 +50,8 @@ export class UPlotConfigBuilder extends ConfigBuilder<
private axes: Record<string, UPlotAxisBuilder> = {};
+ private stepInterval: number | undefined;
+
readonly scales: UPlotScaleBuilder[] = [];
private bands: uPlot.Band[] = [];
@@ -79,6 +86,7 @@ export class UPlotConfigBuilder extends ConfigBuilder<
tzDate,
selectionPreferencesSource,
shouldSaveSelectionPreference,
+ stepInterval,
} = args ?? {};
if (widgetId) {
this.widgetId = widgetId;
@@ -96,6 +104,10 @@ export class UPlotConfigBuilder extends ConfigBuilder<
this.shouldSaveSelectionPreference = shouldSaveSelectionPreference;
}
+ if (stepInterval) {
+ this.stepInterval = stepInterval;
+ }
+
this.onDragSelect = noop;
if (onDragSelect) {
this.onDragSelect = onDragSelect;
@@ -372,6 +384,31 @@ export class UPlotConfigBuilder extends ConfigBuilder<
return this.widgetId;
}
+ /**
+ * Get cursor configuration
+ */
+ getCursorConfig(): Cursor {
+ if (this.stepInterval) {
+ const cursorConfig = {
+ ...DEFAULT_CURSOR_CONFIG,
+ hover: {
+ ...DEFAULT_CURSOR_CONFIG.hover,
+ prox: this.stepInterval
+ ? (uPlotInstance: uPlot): number => {
+ const width = calculateWidthBasedOnStepInterval({
+ uPlotInstance,
+ stepInterval: this.stepInterval ?? 0,
+ });
+ return width * STEP_INTERVAL_MULTIPLIER;
+ }
+ : DEFAULT_HOVER_PROXIMITY_VALUE,
+ },
+ };
+ return merge({}, DEFAULT_CURSOR_CONFIG, cursorConfig, this.cursor);
+ }
+ return merge({}, DEFAULT_CURSOR_CONFIG, this.cursor);
+ }
+
/**
* Build the final uPlot.Options configuration
*/
@@ -413,7 +450,7 @@ export class UPlotConfigBuilder extends ConfigBuilder<
config.hooks = this.hooks;
config.select = this.select;
- config.cursor = merge({}, DEFAULT_CURSOR_CONFIG, this.cursor);
+ config.cursor = this.getCursorConfig();
config.tzDate = this.tzDate;
config.plugins = this.plugins.length > 0 ? this.plugins : undefined;
config.bands = this.bands.length > 0 ? this.bands : undefined;
diff --git a/frontend/src/lib/uPlotV2/config/UPlotSeriesBuilder.ts b/frontend/src/lib/uPlotV2/config/UPlotSeriesBuilder.ts
index 122266dd0c..d1506a614e 100644
--- a/frontend/src/lib/uPlotV2/config/UPlotSeriesBuilder.ts
+++ b/frontend/src/lib/uPlotV2/config/UPlotSeriesBuilder.ts
@@ -1,6 +1,7 @@
import { PANEL_TYPES } from 'constants/queryBuilder';
import { themeColors } from 'constants/theme';
import { generateColor } from 'lib/uPlotLib/utils/generateColor';
+import { calculateWidthBasedOnStepInterval } from 'lib/uPlotV2/utils';
import uPlot, { Series } from 'uplot';
import {
@@ -291,21 +292,16 @@ function getBarPathBuilder({
idx1: number,
): Series.Paths | null => {
let effectiveBarMaxWidth = barMaxWidth;
-
- const xScale = self.scales.x as uPlot.Scale | undefined;
- if (xScale && typeof xScale.min === 'number') {
- const start = xScale.min as number;
- const end = start + stepInterval;
- const startPx = self.valToPos(start, 'x');
- const endPx = self.valToPos(end, 'x');
- const intervalPx = Math.abs(endPx - startPx);
-
- if (intervalPx > 0) {
- effectiveBarMaxWidth =
- typeof barMaxWidth === 'number'
- ? Math.min(barMaxWidth, intervalPx)
- : intervalPx;
- }
+ const widthBasedOnStepInterval = calculateWidthBasedOnStepInterval({
+ uPlotInstance: self,
+ stepInterval,
+ });
+
+ if (widthBasedOnStepInterval > 0) {
+ effectiveBarMaxWidth = Math.min(
+ effectiveBarMaxWidth,
+ widthBasedOnStepInterval,
+ );
}
const barsCfgKey = `bars|${barAlignment}|${barWidthFactor}|${effectiveBarMaxWidth}`;
diff --git a/frontend/src/lib/uPlotV2/config/__tests__/UPlotConfigBuilder.test.ts b/frontend/src/lib/uPlotV2/config/__tests__/UPlotConfigBuilder.test.ts
index 593a1bf139..0d5f8795a3 100644
--- a/frontend/src/lib/uPlotV2/config/__tests__/UPlotConfigBuilder.test.ts
+++ b/frontend/src/lib/uPlotV2/config/__tests__/UPlotConfigBuilder.test.ts
@@ -1,6 +1,10 @@
import { PANEL_TYPES } from 'constants/queryBuilder';
import uPlot from 'uplot';
+import {
+ DEFAULT_HOVER_PROXIMITY_VALUE,
+ STEP_INTERVAL_MULTIPLIER,
+} from '../../constants';
import type { SeriesProps } from '../types';
import { DrawStyle, SelectionPreferencesSource } from '../types';
import { UPlotConfigBuilder } from '../UPlotConfigBuilder';
@@ -13,6 +17,14 @@ jest.mock(
}),
);
+jest.mock('lib/uPlotV2/utils', () => ({
+ calculateWidthBasedOnStepInterval: jest.fn(),
+}));
+
+const calculateWidthBasedOnStepIntervalMock = jest.requireMock(
+ 'lib/uPlotV2/utils',
+).calculateWidthBasedOnStepInterval as jest.Mock;
+
const getStoredSeriesVisibilityMock = jest.requireMock(
'container/DashboardContainer/visualization/panels/utils/legendVisibilityUtils',
) as {
@@ -384,6 +396,52 @@ describe('UPlotConfigBuilder', () => {
expect(config.cursor?.points).toBeDefined();
});
+ describe('getCursorConfig', () => {
+ it('returns default cursor merged with custom cursor when no stepInterval', () => {
+ const builder = new UPlotConfigBuilder();
+
+ builder.setCursor({
+ drag: { setScale: false },
+ });
+
+ const cursorConfig = builder.getCursorConfig();
+
+ expect(cursorConfig.drag?.setScale).toBe(false);
+ expect(cursorConfig.hover?.prox).toBe(DEFAULT_HOVER_PROXIMITY_VALUE);
+ expect(cursorConfig.points).toBeDefined();
+ });
+
+ it('returns hover prox as DEFAULT_HOVER_PROXIMITY_VALUE when stepInterval is not set', () => {
+ const builder = new UPlotConfigBuilder();
+
+ const cursorConfig = builder.getCursorConfig();
+
+ expect(cursorConfig.hover?.prox).toBe(DEFAULT_HOVER_PROXIMITY_VALUE);
+ });
+
+ it('returns hover prox as function when stepInterval is set, computing width * multiplier', () => {
+ const stepInterval = 60;
+ const mockWidth = 100;
+ calculateWidthBasedOnStepIntervalMock.mockReturnValue(mockWidth);
+
+ const builder = new UPlotConfigBuilder({ stepInterval });
+ const cursorConfig = builder.getCursorConfig();
+
+ expect(typeof cursorConfig.hover?.prox).toBe('function');
+
+ const uPlotInstance = {} as uPlot;
+ const proxResult = (cursorConfig.hover!.prox as (u: uPlot) => number)(
+ uPlotInstance,
+ );
+
+ expect(calculateWidthBasedOnStepIntervalMock).toHaveBeenCalledWith({
+ uPlotInstance,
+ stepInterval,
+ });
+ expect(proxResult).toBe(mockWidth * STEP_INTERVAL_MULTIPLIER);
+ });
+ });
+
it('adds plugins and includes them in config', () => {
const builder = new UPlotConfigBuilder();
const plugin: uPlot.Plugin = {
diff --git a/frontend/src/lib/uPlotV2/config/types.ts b/frontend/src/lib/uPlotV2/config/types.ts
index 7c0e41dd03..423f221612 100644
--- a/frontend/src/lib/uPlotV2/config/types.ts
+++ b/frontend/src/lib/uPlotV2/config/types.ts
@@ -1,6 +1,6 @@
import { PrecisionOption } from 'components/Graph/types';
import { PANEL_TYPES } from 'constants/queryBuilder';
-import uPlot, { Cursor, Options, Series } from 'uplot';
+import uPlot, { Series } from 'uplot';
import { ThresholdsDrawHookOptions } from '../hooks/types';
@@ -39,6 +39,7 @@ export interface ConfigBuilderProps {
tzDate?: uPlot.LocalDateFromUnix;
selectionPreferencesSource?: SelectionPreferencesSource;
shouldSaveSelectionPreference?: boolean;
+ stepInterval?: number;
}
/**
@@ -186,47 +187,3 @@ export interface LegendItem {
color: uPlot.Series['stroke'];
show: boolean;
}
-
-export const DEFAULT_PLOT_CONFIG: Partial<Options> = {
- focus: {
- alpha: 0.3,
- },
- cursor: {
- focus: {
- prox: 30,
- },
- },
- legend: {
- show: false,
- },
- padding: [16, 16, 8, 8],
- series: [],
- hooks: {},
-};
-
-const POINTS_FILL_COLOR = '#FFFFFF';
-
-export const DEFAULT_CURSOR_CONFIG: Cursor = {
- drag: { setScale: true },
- points: {
- one: true,
- size: (u, seriesIdx) => (u.series[seriesIdx]?.points?.size ?? 0) * 3,
- width: (_u, _seriesIdx, size) => size / 4,
- stroke: (u, seriesIdx): string => {
- const points = u.series[seriesIdx]?.points;
- const strokeFn =
- typeof points?.stroke === 'function' ? points.stroke : undefined;
- const strokeValue =
- strokeFn !== undefined
- ? strokeFn(u, seriesIdx)
- : typeof points?.stroke === 'string'
- ? points.stroke
- : '';
- return `${strokeValue}90`;
- },
- fill: (): string => POINTS_FILL_COLOR,
- },
- focus: {
- prox: 30,
- },
-};
diff --git a/frontend/src/lib/uPlotV2/constants.ts b/frontend/src/lib/uPlotV2/constants.ts
new file mode 100644
index 0000000000..9322492670
--- /dev/null
+++ b/frontend/src/lib/uPlotV2/constants.ts
@@ -0,0 +1,48 @@
+import { Cursor, Options } from 'uplot';
+
+const POINTS_FILL_COLOR = '#FFFFFF';
+
+export const DEFAULT_HOVER_PROXIMITY_VALUE = 30; // only snap if within 30px horizontally
+export const DEFAULT_FOCUS_PROXIMITY_VALUE = 1e6;
+export const STEP_INTERVAL_MULTIPLIER = 3; // multiply the width computed by STEP_INTERVAL_MULTIPLIER to get the hover prox value
+
+export const DEFAULT_PLOT_CONFIG: Partial<Options> = {
+ focus: {
+ alpha: 0.3,
+ },
+ legend: {
+ show: false,
+ },
+ padding: [16, 16, 8, 8],
+ series: [],
+ hooks: {},
+};
+
+export const DEFAULT_CURSOR_CONFIG: Cursor = {
+ drag: { setScale: true },
+ points: {
+ one: true,
+ size: (u, seriesIdx) => (u.series[seriesIdx]?.points?.size ?? 0) * 3,
+ width: (_u, _seriesIdx, size) => size / 4,
+ stroke: (u, seriesIdx): string => {
+ const points = u.series[seriesIdx]?.points;
+ const strokeFn =
+ typeof points?.stroke === 'function' ? points.stroke : undefined;
+ const strokeValue =
+ strokeFn !== undefined
+ ? strokeFn(u, seriesIdx)
+ : typeof points?.stroke === 'string'
+ ? points.stroke
+ : '';
+ return `${strokeValue}90`;
+ },
+ fill: (): string => POINTS_FILL_COLOR,
+ },
+ focus: {
+ prox: DEFAULT_FOCUS_PROXIMITY_VALUE,
+ },
+ hover: {
+ prox: DEFAULT_HOVER_PROXIMITY_VALUE,
+ bias: 0,
+ },
+};
diff --git a/frontend/src/lib/uPlotV2/plugins/TooltipPlugin/tooltipController.ts b/frontend/src/lib/uPlotV2/plugins/TooltipPlugin/tooltipController.ts
index dbeaddcb4a..1e0dbdad70 100644
--- a/frontend/src/lib/uPlotV2/plugins/TooltipPlugin/tooltipController.ts
+++ b/frontend/src/lib/uPlotV2/plugins/TooltipPlugin/tooltipController.ts
@@ -87,7 +87,7 @@ export function shouldShowTooltipForSync(
export function shouldShowTooltipForInteraction(
controller: TooltipControllerState,
): boolean {
- return controller.focusedSeriesIndex != null || controller.isAnySeriesActive;
+ return controller.focusedSeriesIndex != null;
}
export function updateHoverState(
diff --git a/frontend/src/lib/uPlotV2/utils/__tests__/index.test.ts b/frontend/src/lib/uPlotV2/utils/__tests__/index.test.ts
new file mode 100644
index 0000000000..ce7c477aee
--- /dev/null
+++ b/frontend/src/lib/uPlotV2/utils/__tests__/index.test.ts
@@ -0,0 +1,70 @@
+import uPlot from 'uplot';
+
+import { calculateWidthBasedOnStepInterval } from '../index';
+
+describe('calculateWidthBasedOnStepInterval', () => {
+ it('returns pixel width between start and start+stepInterval when xScale exists with numeric min', () => {
+ const valToPos = jest
+ .fn()
+ .mockReturnValueOnce(100) // startPx for start
+ .mockReturnValueOnce(250); // endPx for start + stepInterval
+
+ const uPlotInstance = ({
+ scales: { x: { min: 1000 } },
+ valToPos,
+ } as unknown) as uPlot;
+
+ const result = calculateWidthBasedOnStepInterval({
+ uPlotInstance,
+ stepInterval: 60,
+ });
+
+ expect(valToPos).toHaveBeenCalledWith(1000, 'x');
+ expect(valToPos).toHaveBeenCalledWith(1060, 'x');
+ expect(result).toBe(150); // Math.abs(250 - 100)
+ });
+
+ it('returns absolute pixel width when endPx is less than startPx', () => {
+ const valToPos = jest.fn().mockReturnValueOnce(250).mockReturnValueOnce(100);
+
+ const uPlotInstance = ({
+ scales: { x: { min: 0 } },
+ valToPos,
+ } as unknown) as uPlot;
+
+ const result = calculateWidthBasedOnStepInterval({
+ uPlotInstance,
+ stepInterval: 60,
+ });
+
+ expect(result).toBe(150); // Math.abs(100 - 250)
+ });
+
+ it('returns 0 when xScale is undefined', () => {
+ const uPlotInstance = ({
+ scales: { x: undefined },
+ valToPos: jest.fn(),
+ } as unknown) as uPlot;
+
+ const result = calculateWidthBasedOnStepInterval({
+ uPlotInstance,
+ stepInterval: 60,
+ });
+
+ expect(result).toBe(0);
+ });
+
+ it('returns 0 when xScale.min is not a number', () => {
+ const uPlotInstance = ({
+ scales: { x: { min: undefined } },
+ valToPos: jest.fn(),
+ } as unknown) as uPlot;
+
+ const result = calculateWidthBasedOnStepInterval({
+ uPlotInstance,
+ stepInterval: 60,
+ });
+
+ expect(result).toBe(0);
+ });
+});
diff --git a/frontend/src/lib/uPlotV2/utils/index.ts b/frontend/src/lib/uPlotV2/utils/index.ts
new file mode 100644
index 0000000000..f2e482b422
--- /dev/null
+++ b/frontend/src/lib/uPlotV2/utils/index.ts
@@ -0,0 +1,17 @@
+export function calculateWidthBasedOnStepInterval({
+ uPlotInstance,
+ stepInterval,
+}: {
+ uPlotInstance: uPlot;
+ stepInterval: number;
+}): number {
+ const xScale = uPlotInstance.scales.x;
+ if (xScale && typeof xScale.min === 'number') {
+ const start = xScale.min as number;
+ const end = start + stepInterval;
+ const startPx = uPlotInstance.valToPos(start, 'x');
+ const endPx = uPlotInstance.valToPos(end, 'x');
+ return Math.abs(endPx - startPx);
+ }
+ return 0;
+}