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
fix: adapt the scroll reset fix in alert and histogram panels (#9322)
SagarRajput-7adfd16ce1b39
diff --git a/frontend/src/components/HostMetricsDetail/Metrics/Metrics.tsx b/frontend/src/components/HostMetricsDetail/Metrics/Metrics.tsxindex 179dacb4a5..3550b0c56f 100644--- a/frontend/src/components/HostMetricsDetail/Metrics/Metrics.tsx+++ b/frontend/src/components/HostMetricsDetail/Metrics/Metrics.tsx@@ -60,6 +60,14 @@ function Metrics({setElement,} = useMultiIntersectionObserver(hostWidgetInfo.length, { threshold: 0.1 });+ const legendScrollPositionRef = useRef<{+ scrollTop: number;+ scrollLeft: number;+ }>({+ scrollTop: 0,+ scrollLeft: 0,+ });+const queryPayloads = useMemo(() =>getHostQueryPayload(@@ -147,6 +155,13 @@ function Metrics({maxTimeScale: graphTimeIntervals[idx].end,onDragSelect: (start, end) => onDragSelect(start, end, idx),query: currentQuery,+ legendScrollPosition: legendScrollPositionRef.current,+ setLegendScrollPosition: (position: {+ scrollTop: number;+ scrollLeft: number;+ }) => {+ legendScrollPositionRef.current = position;+ },}),),[diff --git a/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/StatusCodeBarCharts.tsx b/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/StatusCodeBarCharts.tsxindex 6b665ac297..cf734de377 100644--- a/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/StatusCodeBarCharts.tsx+++ b/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/StatusCodeBarCharts.tsx@@ -69,6 +69,13 @@ function StatusCodeBarCharts({} = endPointStatusCodeLatencyBarChartsDataQuery;const { startTime: minTime, endTime: maxTime } = timeRange;+ const legendScrollPositionRef = useRef<{+ scrollTop: number;+ scrollLeft: number;+ }>({+ scrollTop: 0,+ scrollLeft: 0,+ });const graphRef = useRef<HTMLDivElement>(null);const dimensions = useResizeObserver(graphRef);@@ -207,6 +214,13 @@ function StatusCodeBarCharts({onDragSelect,colorMapping,query: currentQuery,+ legendScrollPosition: legendScrollPositionRef.current,+ setLegendScrollPosition: (position: {+ scrollTop: number;+ scrollLeft: number;+ }) => {+ legendScrollPositionRef.current = position;+ },}),[minTime,diff --git a/frontend/src/container/FormAlertRules/ChartPreview/index.tsx b/frontend/src/container/FormAlertRules/ChartPreview/index.tsxindex 068103de1d..8645a6a255 100644--- a/frontend/src/container/FormAlertRules/ChartPreview/index.tsx+++ b/frontend/src/container/FormAlertRules/ChartPreview/index.tsx@@ -108,6 +108,13 @@ 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 { minTime, maxTime, selectedTime: globalSelectedInterval } = useSelector<@@ -296,6 +303,13 @@ function ChartPreview({setGraphsVisibilityStates: setGraphVisibility,enhancedLegend: true,legendPosition,+ legendScrollPosition: legendScrollPositionRef.current,+ setLegendScrollPosition: (position: {+ scrollTop: number;+ scrollLeft: number;+ }) => {+ legendScrollPositionRef.current = position;+ },}),[yAxisUnit,diff --git a/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityMetrics/EntityMetrics.tsx b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityMetrics/EntityMetrics.tsxindex c9cd831a19..9ee3196d94 100644--- a/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityMetrics/EntityMetrics.tsx+++ b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityMetrics/EntityMetrics.tsx@@ -115,6 +115,13 @@ function EntityMetrics<T>({const graphRef = useRef<HTMLDivElement>(null);const dimensions = useResizeObserver(graphRef);const { currentQuery } = useQueryBuilder();+ const legendScrollPositionRef = useRef<{+ scrollTop: number;+ scrollLeft: number;+ }>({+ scrollTop: 0,+ scrollLeft: 0,+ });const chartData = useMemo(() =>@@ -184,6 +191,13 @@ function EntityMetrics<T>({maxTimeScale: graphTimeIntervals[idx].end,onDragSelect: (start, end) => onDragSelect(start, end, idx),query: currentQuery,+ legendScrollPosition: legendScrollPositionRef.current,+ setLegendScrollPosition: (position: {+ scrollTop: number;+ scrollLeft: number;+ }) => {+ legendScrollPositionRef.current = position;+ },});}),[diff --git a/frontend/src/container/LogDetailedView/InfraMetrics/NodeMetrics.tsx b/frontend/src/container/LogDetailedView/InfraMetrics/NodeMetrics.tsxindex 250a8065d4..9f20ca996d 100644--- a/frontend/src/container/LogDetailedView/InfraMetrics/NodeMetrics.tsx+++ b/frontend/src/container/LogDetailedView/InfraMetrics/NodeMetrics.tsx@@ -83,6 +83,13 @@ function NodeMetrics({const isDarkMode = useIsDarkMode();const graphRef = useRef<HTMLDivElement>(null);const dimensions = useResizeObserver(graphRef);+ const legendScrollPositionRef = useRef<{+ scrollTop: number;+ scrollLeft: number;+ }>({+ scrollTop: 0,+ scrollLeft: 0,+ });const chartData = useMemo(() => queries.map(({ data }) => getUPlotChartData(data?.payload)),@@ -109,6 +116,13 @@ function NodeMetrics({uPlot.tzDate(new Date(timestamp * 1e3), timezone.value),timezone: timezone.value,query: currentQuery,+ legendScrollPosition: legendScrollPositionRef.current,+ setLegendScrollPosition: (position: {+ scrollTop: number;+ scrollLeft: number;+ }) => {+ legendScrollPositionRef.current = position;+ },}),),[diff --git a/frontend/src/container/LogDetailedView/InfraMetrics/PodMetrics.tsx b/frontend/src/container/LogDetailedView/InfraMetrics/PodMetrics.tsxindex d48fcb4c06..426be24057 100644--- a/frontend/src/container/LogDetailedView/InfraMetrics/PodMetrics.tsx+++ b/frontend/src/container/LogDetailedView/InfraMetrics/PodMetrics.tsx@@ -45,6 +45,14 @@ function PodMetrics({};}, [logLineTimestamp]);+ const legendScrollPositionRef = useRef<{+ scrollTop: number;+ scrollLeft: number;+ }>({+ scrollTop: 0,+ scrollLeft: 0,+ });+const { featureFlags } = useAppContext();const dotMetricsEnabled =featureFlags?.find((flag) => flag.name === FeatureKeys.DOT_METRICS_ENABLED)@@ -91,6 +99,13 @@ function PodMetrics({uPlot.tzDate(new Date(timestamp * 1e3), timezone.value),timezone: timezone.value,query: currentQuery,+ legendScrollPosition: legendScrollPositionRef.current,+ setLegendScrollPosition: (position: {+ scrollTop: number;+ scrollLeft: number;+ }) => {+ legendScrollPositionRef.current = position;+ },}),),[diff --git a/frontend/src/container/PanelWrapper/HistogramPanelWrapper.tsx b/frontend/src/container/PanelWrapper/HistogramPanelWrapper.tsxindex 4e05c02b28..ab697aa967 100644--- a/frontend/src/container/PanelWrapper/HistogramPanelWrapper.tsx+++ b/frontend/src/container/PanelWrapper/HistogramPanelWrapper.tsx@@ -26,6 +26,7 @@ function HistogramPanelWrapper({enableDrillDown = false,}: PanelWrapperProps): JSX.Element {const graphRef = useRef<HTMLDivElement>(null);+ const legendScrollPositionRef = useRef<number>(0);const { toScrollWidgetId, setToScrollWidgetId } = useDashboard();const isDarkMode = useIsDarkMode();const containerDimensions = useResizeObserver(graphRef);@@ -129,6 +130,10 @@ function HistogramPanelWrapper({onClickHandler: enableDrillDown? clickHandlerWithContextMenu: onClickHandler ?? _noop,+ legendScrollPosition: legendScrollPositionRef.current,+ setLegendScrollPosition: (position: number) => {+ legendScrollPositionRef.current = position;+ },}),[containerDimensions,diff --git a/frontend/src/container/PanelWrapper/__tests__/histogramLegendScroll.test.tsx b/frontend/src/container/PanelWrapper/__tests__/histogramLegendScroll.test.tsxnew file mode 100644index 0000000000..03a7c27aef--- /dev/null+++ b/frontend/src/container/PanelWrapper/__tests__/histogramLegendScroll.test.tsx@@ -0,0 +1,118 @@+import { getUplotHistogramChartOptions } from 'lib/uPlotLib/getUplotHistogramChartOptions';+import uPlot from 'uplot';++// Mock dependencies+jest.mock('lib/uPlotLib/plugins/tooltipPlugin', () => jest.fn(() => ({})));+jest.mock('lib/uPlotLib/plugins/onClickPlugin', () => jest.fn(() => ({})));++const mockApiResponse = {+ data: {+ result: [+ {+ metric: { __name__: 'test_metric' },+ queryName: 'test_query',+ values: [[1640995200, '10'] as [number, string]],+ },+ ],+ resultType: 'time_series',+ newResult: {+ data: {+ result: [],+ resultType: 'time_series',+ },+ },+ },+};++const mockDimensions = { width: 800, height: 400 };+const mockHistogramData: uPlot.AlignedData = [[1640995200], [10]];+const TEST_HISTOGRAM_ID = 'test-histogram';++describe('Histogram Chart Options Legend Scroll Position', () => {+ let originalRequestAnimationFrame: typeof global.requestAnimationFrame;++ beforeEach(() => {+ jest.clearAllMocks();+ originalRequestAnimationFrame = global.requestAnimationFrame;+ });++ afterEach(() => {+ global.requestAnimationFrame = originalRequestAnimationFrame;+ });++ it('should set up scroll position tracking in histogram chart ready hook', () => {+ const mockSetScrollPosition = jest.fn();+ const options = getUplotHistogramChartOptions({+ id: TEST_HISTOGRAM_ID,+ dimensions: mockDimensions,+ isDarkMode: false,+ apiResponse: mockApiResponse,+ histogramData: mockHistogramData,+ legendScrollPosition: 0,+ setLegendScrollPosition: mockSetScrollPosition,+ });++ // Create mock chart with legend element+ const mockChart = ({+ root: document.createElement('div'),+ } as unknown) as uPlot;++ const legend = document.createElement('div');+ legend.className = 'u-legend';+ mockChart.root.appendChild(legend);++ const addEventListenerSpy = jest.spyOn(legend, 'addEventListener');++ // Execute ready hook+ if (options.hooks?.ready) {+ options.hooks.ready.forEach((hook) => hook?.(mockChart));+ }++ // Verify that scroll event listener was added and cleanup function was stored+ expect(addEventListenerSpy).toHaveBeenCalledWith(+ 'scroll',+ expect.any(Function),+ );+ expect(+ (mockChart as uPlot & { _legendScrollCleanup?: () => void })+ ._legendScrollCleanup,+ ).toBeDefined();+ });++ it('should restore histogram chart scroll position when provided', () => {+ const mockScrollPosition = 50;+ const mockSetScrollPosition = jest.fn();+ const options = getUplotHistogramChartOptions({+ id: TEST_HISTOGRAM_ID,+ dimensions: mockDimensions,+ isDarkMode: false,+ apiResponse: mockApiResponse,+ histogramData: mockHistogramData,+ legendScrollPosition: mockScrollPosition,+ setLegendScrollPosition: mockSetScrollPosition,+ });++ // Create mock chart with legend element+ const mockChart = ({+ root: document.createElement('div'),+ } as unknown) as uPlot;++ const legend = document.createElement('div');+ legend.className = 'u-legend';+ legend.scrollTop = 0;+ mockChart.root.appendChild(legend);++ // Mock requestAnimationFrame+ const mockRequestAnimationFrame = jest.fn((callback) => callback());+ global.requestAnimationFrame = mockRequestAnimationFrame;++ // Execute ready hook+ if (options.hooks?.ready) {+ options.hooks.ready.forEach((hook) => hook?.(mockChart));+ }++ // Verify that requestAnimationFrame was called and scroll position was restored+ expect(mockRequestAnimationFrame).toHaveBeenCalledWith(expect.any(Function));+ expect(legend.scrollTop).toBe(mockScrollPosition);+ });+});diff --git a/frontend/src/container/TimeSeriesView/TimeSeriesView.tsx b/frontend/src/container/TimeSeriesView/TimeSeriesView.tsxindex 9f74aa5770..cb97ab5b01 100644--- a/frontend/src/container/TimeSeriesView/TimeSeriesView.tsx+++ b/frontend/src/container/TimeSeriesView/TimeSeriesView.tsx@@ -81,6 +81,13 @@ function TimeSeriesView({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 { minTime, maxTime, selectedTime: globalSelectedInterval } = useSelector<AppState,@@ -203,6 +210,13 @@ function TimeSeriesView({setGraphsVisibilityStates: setGraphVisibility,enhancedLegend: true,legendPosition: LegendPosition.BOTTOM,+ legendScrollPosition: legendScrollPositionRef.current,+ setLegendScrollPosition: (position: {+ scrollTop: number;+ scrollLeft: number;+ }) => {+ legendScrollPositionRef.current = position;+ },});return (diff --git a/frontend/src/lib/uPlotLib/getUplotHistogramChartOptions.ts b/frontend/src/lib/uPlotLib/getUplotHistogramChartOptions.tsindex bee488f891..12fd1fd8e5 100644--- a/frontend/src/lib/uPlotLib/getUplotHistogramChartOptions.ts+++ b/frontend/src/lib/uPlotLib/getUplotHistogramChartOptions.ts@@ -17,6 +17,11 @@ import { drawStyles } from './utils/constants';import { generateColor } from './utils/generateColor';import getAxes from './utils/getAxes';+// Extended uPlot interface with custom properties+interface ExtendedUPlot extends uPlot {+ _legendScrollCleanup?: () => void;+}+type GetUplotHistogramChartOptionsProps = {id?: string;apiResponse?: MetricRangePayloadProps;@@ -30,6 +35,8 @@ type GetUplotHistogramChartOptionsProps = {setGraphsVisibilityStates?: Dispatch<SetStateAction<boolean[]>>;mergeAllQueries?: boolean;onClickHandler?: OnClickPluginOpts['onClick'];+ legendScrollPosition?: number;+ setLegendScrollPosition?: (position: number) => void;};type GetHistogramSeriesProps = {@@ -124,6 +131,8 @@ export const getUplotHistogramChartOptions = ({mergeAllQueries,onClickHandler = _noop,panelType,+ legendScrollPosition,+ setLegendScrollPosition,}: GetUplotHistogramChartOptionsProps): uPlot.Options =>({id,@@ -179,33 +188,94 @@ export const getUplotHistogramChartOptions = ({(self): void => {const legend = self.root.querySelector('.u-legend');if (legend) {+ const legendElement = legend as HTMLElement;++ // Enhanced legend scroll position preservation+ if (setLegendScrollPosition && typeof legendScrollPosition === 'number') {+ const handleScroll = (): void => {+ setLegendScrollPosition(legendElement.scrollTop);+ };++ // Add scroll event listener to save position+ legendElement.addEventListener('scroll', handleScroll);++ // Restore scroll position+ requestAnimationFrame(() => {+ legendElement.scrollTop = legendScrollPosition;+ });++ // Store cleanup function+ const extSelf = self as ExtendedUPlot;+ extSelf._legendScrollCleanup = (): void => {+ legendElement.removeEventListener('scroll', handleScroll);+ };+ }+const seriesEls = legend.querySelectorAll('.u-series');const seriesArray = Array.from(seriesEls);seriesArray.forEach((seriesEl, index) => {- seriesEl.addEventListener('click', () => {- if (graphsVisibilityStates) {- setGraphsVisibilityStates?.((prev) => {- const newGraphVisibilityStates = [...prev];- if (- newGraphVisibilityStates[index + 1] &&- newGraphVisibilityStates.every((value, i) =>- i === index + 1 ? value : !value,- )- ) {- newGraphVisibilityStates.fill(true);- } else {- newGraphVisibilityStates.fill(false);- newGraphVisibilityStates[index + 1] = true;+ // Add click handlers for marker and text separately+ const thElement = seriesEl.querySelector('th');+ if (thElement) {+ const currentMarker = thElement.querySelector('.u-marker');+ const textElement =+ thElement.querySelector('.legend-text') || thElement;++ // Marker click handler - checkbox behavior (toggle individual series)+ if (currentMarker) {+ currentMarker.addEventListener('click', (e) => {+ e.stopPropagation?.(); // Prevent event bubbling to text handler++ if (graphsVisibilityStates) {+ setGraphsVisibilityStates?.((prev) => {+ const newGraphVisibilityStates = [...prev];+ // Toggle the specific series visibility (checkbox behavior)+ newGraphVisibilityStates[index + 1] = !newGraphVisibilityStates[+ index + 1+ ];++ saveLegendEntriesToLocalStorage({+ options: self,+ graphVisibilityState: newGraphVisibilityStates,+ name: id || '',+ });+ return newGraphVisibilityStates;+ });}- saveLegendEntriesToLocalStorage({- options: self,- graphVisibilityState: newGraphVisibilityStates,- name: id || '',- });- return newGraphVisibilityStates;});}- });++ // Text click handler - show only/show all behavior (existing behavior)+ textElement.addEventListener('click', (e) => {+ e.stopPropagation?.(); // Prevent event bubbling++ if (graphsVisibilityStates) {+ setGraphsVisibilityStates?.((prev) => {+ const newGraphVisibilityStates = [...prev];+ // Show only this series / show all behavior+ if (+ newGraphVisibilityStates[index + 1] &&+ newGraphVisibilityStates.every((value, i) =>+ i === index + 1 ? value : !value,+ )+ ) {+ // If only this series is visible, show all+ newGraphVisibilityStates.fill(true);+ } else {+ // Otherwise, show only this series+ newGraphVisibilityStates.fill(false);+ newGraphVisibilityStates[index + 1] = true;+ }+ saveLegendEntriesToLocalStorage({+ options: self,+ graphVisibilityState: newGraphVisibilityStates,+ name: id || '',+ });+ return newGraphVisibilityStates;+ });+ }+ });+ }});}},