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: fix drag select not working in panel edit mode (#9130)

SagarRajput-795f8fa156655
diff --git a/frontend/src/container/GridCardLayout/GridCard/FullView/__tests__/PanelWrapperDragSelect.test.tsx b/frontend/src/container/GridCardLayout/GridCard/FullView/__tests__/PanelWrapperDragSelect.test.tsx
new file mode 100644
index 0000000000..5e662cf9fc
--- /dev/null
+++ b/frontend/src/container/GridCardLayout/GridCard/FullView/__tests__/PanelWrapperDragSelect.test.tsx
@@ -0,0 +1,207 @@
+/* eslint-disable sonarjs/no-duplicate-string */
+
+import { PANEL_TYPES } from 'constants/queryBuilder';
+import PanelWrapper from 'container/PanelWrapper/PanelWrapper';
+import { RowData } from 'lib/query/createTableColumnsFromQuery';
+import { MutableRefObject } from 'react';
+import { render, screen, waitFor } from 'tests/test-utils';
+import { Widgets } from 'types/api/dashboard/getAll';
+import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
+import { EQueryType } from 'types/common/dashboard';
+import { DataSource } from 'types/common/queryBuilder';
+
+// Mock dependencies
+jest.mock('container/PanelWrapper/constants', () => ({
+ PanelTypeVsPanelWrapper: {
+ [PANEL_TYPES.TIME_SERIES]: ({
+ onDragSelect,
+ }: {
+ onDragSelect: (start: number, end: number) => void;
+ }): JSX.Element => {
+ const handleCanvasMouseDown = (): void => {
+ // Simulate drag start
+ const handleMouseMove = (): void => {
+ // Simulate drag progress
+ };
+
+ const handleMouseUp = (): void => {
+ // Simulate drag end and call onDragSelect
+ onDragSelect(1634325650, 1634325750);
+ document.removeEventListener('mousemove', handleMouseMove);
+ document.removeEventListener('mouseup', handleMouseUp);
+ };
+
+ document.addEventListener('mousemove', handleMouseMove);
+ document.addEventListener('mouseup', handleMouseUp);
+ };
+
+ return (
+ <div data-testid="mock-time-series-panel">
+ <canvas
+ data-testid="uplot-canvas"
+ width={400}
+ height={300}
+ onMouseDown={handleCanvasMouseDown}
+ />
+ <button
+ type="button"
+ data-testid="drag-select-trigger"
+ onClick={(): void => onDragSelect(1634325650, 1634325750)}
+ >
+ Trigger Drag Select
+ </button>
+ </div>
+ );
+ },
+ },
+}));
+
+// Mock data
+const mockWidget: Widgets = {
+ id: 'test-widget-id',
+ query: {
+ builder: {
+ queryData: [
+ {
+ dataSource: DataSource.METRICS,
+ queryName: 'A',
+ aggregateOperator: 'sum',
+ aggregateAttribute: {
+ key: 'test',
+ dataType: DataTypes.Float64,
+ type: '',
+ },
+ functions: [],
+ groupBy: [],
+ expression: 'A',
+ disabled: false,
+ having: [],
+ limit: null,
+ orderBy: [],
+ stepInterval: 60,
+ legend: '',
+ spaceAggregation: 'sum',
+ timeAggregation: 'sum',
+ },
+ ],
+ queryFormulas: [],
+ queryTraceOperator: [],
+ },
+ promql: [],
+ clickhouse_sql: [],
+ id: 'test-query-id',
+ queryType: EQueryType.QUERY_BUILDER,
+ },
+ panelTypes: PANEL_TYPES.TIME_SERIES,
+ title: 'Test Widget',
+ description: '',
+ opacity: '',
+ timePreferance: 'GLOBAL_TIME',
+ nullZeroValues: '',
+ yAxisUnit: '',
+ fillSpans: false,
+ softMin: null,
+ softMax: null,
+ selectedLogFields: [],
+ selectedTracesFields: [],
+};
+
+// Mock response data
+const mockQueryResponse: any = {
+ data: {
+ payload: {
+ data: {
+ result: [
+ {
+ metric: { __name__: 'test_metric' },
+ values: [[1634325600, '42']],
+ queryName: 'A',
+ },
+ ],
+ resultType: '',
+ newResult: {
+ data: {
+ resultType: '',
+ result: [
+ {
+ queryName: 'A',
+ series: null,
+ list: null,
+ },
+ ],
+ },
+ },
+ },
+ },
+ statusCode: 200,
+ message: 'success',
+ error: null,
+ },
+ isLoading: false,
+ isError: false,
+ error: null,
+ isFetching: false,
+ refetch: jest.fn(),
+};
+
+describe('PanelWrapper with DragSelect', () => {
+ const tableProcessedDataRef = { current: [] } as MutableRefObject<RowData[]>;
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('simulates drag select on uPlot canvas', async () => {
+ const mockOnDragSelect = jest.fn();
+
+ render(
+ <PanelWrapper
+ widget={mockWidget}
+ queryResponse={mockQueryResponse}
+ onDragSelect={mockOnDragSelect}
+ selectedGraph={PANEL_TYPES.TIME_SERIES}
+ tableProcessedDataRef={tableProcessedDataRef}
+ />,
+ );
+
+ // Verify the panel renders
+ expect(screen.getByTestId('mock-time-series-panel')).toBeInTheDocument();
+
+ // Find the canvas element
+ const canvas = screen.getByTestId('uplot-canvas');
+ expect(canvas).toBeInTheDocument();
+
+ // Simulate drag events on the canvas
+ // Start drag by dispatching mousedown
+ canvas.dispatchEvent(
+ new MouseEvent('mousedown', {
+ clientX: 10,
+ clientY: 10,
+ bubbles: true,
+ }),
+ );
+
+ // Simulate mouse move during drag
+ canvas.dispatchEvent(
+ new MouseEvent('mousemove', {
+ clientX: 60,
+ clientY: 60,
+ bubbles: true,
+ }),
+ );
+
+ // End drag by dispatching mouseup
+ canvas.dispatchEvent(
+ new MouseEvent('mouseup', {
+ clientX: 80,
+ clientY: 80,
+ bubbles: true,
+ }),
+ );
+
+ // Wait for the onDragSelect to be called
+ await waitFor(() => {
+ expect(mockOnDragSelect).toHaveBeenCalledWith(1634325650, 1634325750);
+ });
+ });
+});
diff --git a/frontend/src/container/GridCardLayout/GridCard/FullView/index.tsx b/frontend/src/container/GridCardLayout/GridCard/FullView/index.tsx
index f27089041c..e0b6c4dd3c 100644
--- a/frontend/src/container/GridCardLayout/GridCard/FullView/index.tsx
+++ b/frontend/src/container/GridCardLayout/GridCard/FullView/index.tsx
@@ -38,9 +38,7 @@ import { isEmpty } from 'lodash-es';
import { useAppContext } from 'providers/App/App';
import { useDashboard } from 'providers/Dashboard/Dashboard';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { useDispatch, useSelector } from 'react-redux';
-import { useLocation } from 'react-router-dom';
-import { UpdateTimeInterval } from 'store/actions';
+import { useSelector } from 'react-redux';
import { AppState } from 'store/reducers';
import { Warning } from 'types/api';
import { GlobalReducer } from 'types/reducer/globalTime';
@@ -67,13 +65,11 @@ function FullView({
enableDrillDown = false,
}: FullViewProps): JSX.Element {
const { safeNavigate } = useSafeNavigate();
- const { selectedTime: globalSelectedTime } = useSelector<
+ const { selectedTime: globalSelectedTime, minTime, maxTime } = useSelector<
AppState,
GlobalReducer
>((state) => state.globalTime);
- const dispatch = useDispatch();
const urlQuery = useUrlQuery();
- const location = useLocation();
const fullViewRef = useRef<HTMLDivElement>(null);
const { handleRunQuery } = useQueryBuilder();
@@ -154,11 +150,16 @@ function FullView({
});
useEffect(() => {
+ const timeRange =
+ selectedTime.enum !== 'GLOBAL_TIME'
+ ? { start: undefined, end: undefined }
+ : { start: Math.floor(minTime / 1e9), end: Math.floor(maxTime / 1e9) };
setRequestData((prev) => ({
...prev,
selectedTime: selectedTime.enum,
+ ...timeRange,
}));
- }, [selectedTime]);
+ }, [selectedTime, minTime, maxTime]);
// Update requestData when panel type changes
useEffect(() => {
@@ -181,38 +182,34 @@ function FullView({
});
}, [selectedPanelType]);
- const response = useGetQueryRange(
- requestData,
- // selectedDashboard?.data?.version || version || DEFAULT_ENTITY_VERSION,
- ENTITY_VERSION_V5,
- {
- queryKey: [widget?.query, selectedPanelType, requestData, version],
- enabled: !isDependedDataLoaded,
- keepPreviousData: true,
- },
- );
+ const response = useGetQueryRange(requestData, ENTITY_VERSION_V5, {
+ queryKey: [
+ widget?.query,
+ selectedPanelType,
+ requestData,
+ version,
+ minTime,
+ maxTime,
+ ],
+ enabled: !isDependedDataLoaded,
+ keepPreviousData: true,
+ });
- const onDragSelect = useCallback(
- (start: number, end: number): void => {
- const startTimestamp = Math.trunc(start);
- const endTimestamp = Math.trunc(end);
+ const onDragSelect = useCallback((start: number, end: number): void => {
+ const startTimestamp = Math.trunc(start);
+ const endTimestamp = Math.trunc(end);
- if (startTimestamp !== endTimestamp) {
- dispatch(UpdateTimeInterval('custom', [startTimestamp, endTimestamp]));
- }
+ const { maxTime, minTime } = GetMinMax('custom', [
+ startTimestamp,
+ endTimestamp,
+ ]);
- const { maxTime, minTime } = GetMinMax('custom', [
- startTimestamp,
- endTimestamp,
- ]);
-
- urlQuery.set(QueryParams.startTime, minTime.toString());
- urlQuery.set(QueryParams.endTime, maxTime.toString());
- const generatedUrl = `${location.pathname}?${urlQuery.toString()}`;
- safeNavigate(generatedUrl);
- },
- [dispatch, location.pathname, safeNavigate, urlQuery],
- );
+ setRequestData((prev) => ({
+ ...prev,
+ start: Math.floor(minTime / 1e9),
+ end: Math.floor(maxTime / 1e9),
+ }));
+ }, []);
const [graphsVisibilityStates, setGraphsVisibilityStates] = useState<
boolean[]
diff --git a/frontend/src/container/NewWidget/LeftContainer/index.tsx b/frontend/src/container/NewWidget/LeftContainer/index.tsx
index fe5406620f..0e9f024679 100644
--- a/frontend/src/container/NewWidget/LeftContainer/index.tsx
+++ b/frontend/src/container/NewWidget/LeftContainer/index.tsx
@@ -30,25 +30,21 @@ function LeftContainer({
enableDrillDown = false,
}: WidgetGraphProps): JSX.Element {
const { stagedQuery } = useQueryBuilder();
- // const { selectedDashboard } = useDashboard();
- const { selectedTime: globalSelectedInterval } = useSelector<
+ const { selectedTime: globalSelectedInterval, minTime, maxTime } = useSelector<
AppState,
GlobalReducer
>((state) => state.globalTime);
- const queryResponse = useGetQueryRange(
- requestData,
- // selectedDashboard?.data?.version || DEFAULT_ENTITY_VERSION,
- ENTITY_VERSION_V5,
- {
- enabled: !!stagedQuery,
- queryKey: [
- REACT_QUERY_KEY.GET_QUERY_RANGE,
- globalSelectedInterval,
- requestData,
- ],
- },
- );
+ const queryResponse = useGetQueryRange(requestData, ENTITY_VERSION_V5, {
+ enabled: !!stagedQuery,
+ queryKey: [
+ REACT_QUERY_KEY.GET_QUERY_RANGE,
+ globalSelectedInterval,
+ requestData,
+ minTime,
+ maxTime,
+ ],
+ });
// Update parent component with query response for legend colors
useEffect(() => {