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: added fix for storing legend preferences (#10184)
Abhi kumarb660dc85734c
diff --git a/frontend/src/container/DashboardContainer/visualization/layout/ChartLayout/ChartLayout.styles.scss b/frontend/src/container/DashboardContainer/visualization/layout/ChartLayout/ChartLayout.styles.scssindex 96064b1544..ab37aa7af4 100644--- a/frontend/src/container/DashboardContainer/visualization/layout/ChartLayout/ChartLayout.styles.scss+++ b/frontend/src/container/DashboardContainer/visualization/layout/ChartLayout/ChartLayout.styles.scss@@ -10,7 +10,6 @@.chart-layout__legend-wrapper {padding-left: 0 !important;- padding-right: 12px !important;}}diff --git a/frontend/src/container/DashboardContainer/visualization/panels/types.ts b/frontend/src/container/DashboardContainer/visualization/panels/types.tsindex f85714cdae..e081c72035 100644--- a/frontend/src/container/DashboardContainer/visualization/panels/types.ts+++ b/frontend/src/container/DashboardContainer/visualization/panels/types.ts@@ -13,3 +13,16 @@ export interface GraphVisibilityState {name: string;dataIndex: SeriesVisibilityItem[];}++/**+ * Context in which a panel is rendered. Used to vary behavior (e.g. persistence,+ * interactions) per context.+ */+export enum PanelMode {+ /** Panel opened in full-screen / standalone view (e.g. from a dashboard widget). */+ STANDALONE_VIEW = 'STANDALONE_VIEW',+ /** Panel in the widget builder while editing a dashboard. */+ DASHBOARD_EDIT = 'DASHBOARD_EDIT',+ /** Panel rendered as a widget on a dashboard (read-only view). */+ DASHBOARD_VIEW = 'DASHBOARD_VIEW',+}diff --git a/frontend/src/container/GridCardLayout/GridCard/FullView/__tests__/PanelWrapperDragSelect.test.tsx b/frontend/src/container/GridCardLayout/GridCard/FullView/__tests__/PanelWrapperDragSelect.test.tsxindex ec7dc23a9e..83a989d6c1 100644--- a/frontend/src/container/GridCardLayout/GridCard/FullView/__tests__/PanelWrapperDragSelect.test.tsx+++ b/frontend/src/container/GridCardLayout/GridCard/FullView/__tests__/PanelWrapperDragSelect.test.tsx@@ -2,6 +2,7 @@import { MutableRefObject } from 'react';import { PANEL_TYPES } from 'constants/queryBuilder';+import { PanelMode } from 'container/DashboardContainer/visualization/panels/types';import PanelWrapper from 'container/PanelWrapper/PanelWrapper';import { RowData } from 'lib/query/createTableColumnsFromQuery';import { render, screen, waitFor } from 'tests/test-utils';@@ -156,6 +157,7 @@ describe('PanelWrapper with DragSelect', () => {render(<PanelWrapper+ panelMode={PanelMode.STANDALONE_VIEW}widget={mockWidget}queryResponse={mockQueryResponse}onDragSelect={mockOnDragSelect}diff --git a/frontend/src/container/GridCardLayout/GridCard/FullView/index.tsx b/frontend/src/container/GridCardLayout/GridCard/FullView/index.tsxindex 0c414ac298..401d77085b 100644--- a/frontend/src/container/GridCardLayout/GridCard/FullView/index.tsx+++ b/frontend/src/container/GridCardLayout/GridCard/FullView/index.tsx@@ -17,6 +17,7 @@ import WarningPopover from 'components/WarningPopover/WarningPopover';import { ENTITY_VERSION_V5 } from 'constants/app';import { QueryParams } from 'constants/query';import { PANEL_TYPES } from 'constants/queryBuilder';+import { PanelMode } from 'container/DashboardContainer/visualization/panels/types';import useDrilldown from 'container/GridCardLayout/GridCard/FullView/useDrilldown';import { populateMultipleResults } from 'container/NewWidget/LeftContainer/WidgetGraph/util';import {@@ -366,6 +367,7 @@ function FullView({/>)}<PanelWrapper+ panelMode={PanelMode.STANDALONE_VIEW}queryResponse={response}widget={widget}setRequestData={setRequestData}diff --git a/frontend/src/container/GridCardLayout/GridCard/WidgetGraphComponent.tsx b/frontend/src/container/GridCardLayout/GridCard/WidgetGraphComponent.tsxindex 63b9c23e8d..6388355986 100644--- a/frontend/src/container/GridCardLayout/GridCard/WidgetGraphComponent.tsx+++ b/frontend/src/container/GridCardLayout/GridCard/WidgetGraphComponent.tsx@@ -14,6 +14,7 @@ import { useNavigateToExplorer } from 'components/CeleryTask/useNavigateToExplorimport { ToggleGraphProps } from 'components/Graph/types';import { QueryParams } from 'constants/query';import { PANEL_TYPES } from 'constants/queryBuilder';+import { PanelMode } from 'container/DashboardContainer/visualization/panels/types';import { placeWidgetAtBottom } from 'container/NewWidget/utils';import PanelWrapper from 'container/PanelWrapper/PanelWrapper';import useGetResolvedText from 'hooks/dashboard/useGetResolvedText';@@ -407,6 +408,7 @@ function WidgetGraphComponent({ref={graphRef}><PanelWrapper+ panelMode={PanelMode.DASHBOARD_VIEW}widget={widget}queryResponse={queryResponse}setRequestData={setRequestData}diff --git a/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/WidgetGraphs.tsx b/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/WidgetGraphs.tsxindex 847ac9c8ed..4cb48aa756 100644--- a/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/WidgetGraphs.tsx+++ b/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/WidgetGraphs.tsx@@ -13,6 +13,7 @@ import { useNavigateToExplorer } from 'components/CeleryTask/useNavigateToExplorimport { ToggleGraphProps } from 'components/Graph/types';import { QueryParams } from 'constants/query';import { PANEL_TYPES } from 'constants/queryBuilder';+import { PanelMode } from 'container/DashboardContainer/visualization/panels/types';import { handleGraphClick } from 'container/GridCardLayout/GridCard/utils';import { useGraphClickToShowButton } from 'container/GridCardLayout/useGraphClickToShowButton';import useNavigateToExplorerPages from 'container/GridCardLayout/useNavigateToExplorerPages';@@ -183,6 +184,7 @@ function WidgetGraph({}}><PanelWrapper+ panelMode={PanelMode.DASHBOARD_EDIT}widget={selectedWidget}queryResponse={queryResponse}setRequestData={setRequestData}diff --git a/frontend/src/container/PanelWrapper/PanelWrapper.tsx b/frontend/src/container/PanelWrapper/PanelWrapper.tsxindex c91f5803fb..81e8784414 100644--- a/frontend/src/container/PanelWrapper/PanelWrapper.tsx+++ b/frontend/src/container/PanelWrapper/PanelWrapper.tsx@@ -21,6 +21,7 @@ function PanelWrapper({onOpenTraceBtnClick,customSeries,customOnRowClick,+ panelMode,enableDrillDown = false,}: PanelWrapperProps): JSX.Element {const Component = PanelTypeVsPanelWrapper[@@ -33,6 +34,7 @@ function PanelWrapper({}return (<Component+ panelMode={panelMode}widget={widget}queryResponse={queryResponse}setRequestData={setRequestData}diff --git a/frontend/src/container/PanelWrapper/__tests__/TablePanelWrapper.test.tsx b/frontend/src/container/PanelWrapper/__tests__/TablePanelWrapper.test.tsxindex 0c2389dead..d74acd08d6 100644--- a/frontend/src/container/PanelWrapper/__tests__/TablePanelWrapper.test.tsx+++ b/frontend/src/container/PanelWrapper/__tests__/TablePanelWrapper.test.tsx@@ -1,3 +1,4 @@+import { PanelMode } from 'container/DashboardContainer/visualization/panels/types';import { render } from 'tests/test-utils';import { Widgets } from 'types/api/dashboard/getAll';@@ -11,6 +12,7 @@ describe('Table panel wrappper tests', () => {it('table should render fine with the query response and column units', () => {const { container, getByText } = render(<TablePanelWrapper+ panelMode={PanelMode.DASHBOARD_VIEW}widget={(tablePanelWidgetQuery as unknown) as Widgets}queryResponse={(tablePanelQueryResponse as unknown) as any}onDragSelect={(): void => {}}diff --git a/frontend/src/container/PanelWrapper/__tests__/ValuePanelWrapper.test.tsx b/frontend/src/container/PanelWrapper/__tests__/ValuePanelWrapper.test.tsxindex 362b31c4b9..8ba218dccd 100644--- a/frontend/src/container/PanelWrapper/__tests__/ValuePanelWrapper.test.tsx+++ b/frontend/src/container/PanelWrapper/__tests__/ValuePanelWrapper.test.tsx@@ -1,3 +1,4 @@+import { PanelMode } from 'container/DashboardContainer/visualization/panels/types';import { render } from 'tests/test-utils';import { Widgets } from 'types/api/dashboard/getAll';@@ -20,6 +21,7 @@ describe('Value panel wrappper tests', () => {it('should render value panel correctly with yaxis unit', () => {const { getByText } = render(<ValuePanelWrapper+ panelMode={PanelMode.DASHBOARD_VIEW}widget={(valuePanelWidget as unknown) as Widgets}queryResponse={(valuePanelQueryResponse as unknown) as any}onDragSelect={(): void => {}}@@ -34,6 +36,7 @@ describe('Value panel wrappper tests', () => {it('should render tooltip when there are conflicting thresholds', () => {const { getByTestId, container } = render(<ValuePanelWrapper+ panelMode={PanelMode.DASHBOARD_VIEW}widget={({ ...valuePanelWidget, thresholds } as unknown) as Widgets}queryResponse={(valuePanelQueryResponse as unknown) as any}onDragSelect={(): void => {}}diff --git a/frontend/src/container/PanelWrapper/panelWrapper.types.ts b/frontend/src/container/PanelWrapper/panelWrapper.types.tsindex 53e1ec078b..0480ef0783 100644--- a/frontend/src/container/PanelWrapper/panelWrapper.types.ts+++ b/frontend/src/container/PanelWrapper/panelWrapper.types.ts@@ -1,6 +1,7 @@import { Dispatch, SetStateAction } from 'react';import { UseQueryResult } from 'react-query';import { PANEL_TYPES } from 'constants/queryBuilder';+import { PanelMode } from 'container/DashboardContainer/visualization/panels/types';import { WidgetGraphComponentProps } from 'container/GridCardLayout/GridCard/types';import { RowData } from 'lib/query/createTableColumnsFromQuery';import { OnClickPluginOpts } from 'lib/uPlotLib/plugins/onClickPlugin';@@ -31,6 +32,7 @@ export type PanelWrapperProps = {customOnRowClick?: (record: RowData) => void;customSeries?: (data: QueryData[]) => uPlot.Series[];enableDrillDown?: boolean;+ panelMode: PanelMode;};export type TooltipData = {diff --git a/frontend/src/lib/uPlotV2/components/UPlotChart.tsx b/frontend/src/lib/uPlotV2/components/UPlotChart.tsxindex 8858d7fb29..77b3d9437a 100644--- a/frontend/src/lib/uPlotV2/components/UPlotChart.tsx+++ b/frontend/src/lib/uPlotV2/components/UPlotChart.tsx@@ -6,7 +6,6 @@ import { LineChart } from 'lucide-react';import ErrorBoundaryFallback from 'pages/ErrorBoundaryFallback/ErrorBoundaryFallback';import uPlot, { AlignedData, Options } from 'uplot';-import { UPlotConfigBuilder } from '../config/UPlotConfigBuilder';import { usePlotContext } from '../context/PlotContext';import { UPlotChartProps } from './types';@@ -49,7 +48,6 @@ export default function UPlotChart({const containerRef = useRef<HTMLDivElement>(null);const plotInstanceRef = useRef<uPlot | null>(null);const prevPropsRef = useRef<UPlotChartProps | null>(null);- const configUsedForPlotRef = useRef<UPlotConfigBuilder | null>(null);/*** Destroy the existing plot instance if present.@@ -57,12 +55,6 @@ export default function UPlotChart({const destroyPlot = useCallback((): void => {if (plotInstanceRef.current) {onDestroy?.(plotInstanceRef.current);- // Clean up the config builder that was used to create this plot (not the current prop)- if (configUsedForPlotRef.current) {- configUsedForPlotRef.current.destroy();- }- configUsedForPlotRef.current = null;-plotInstanceRef.current.destroy();plotInstanceRef.current = null;setPlotContextInitialState({ uPlotInstance: null });@@ -97,13 +89,14 @@ export default function UPlotChart({if (plotRef) {plotRef(plot);}+setPlotContextInitialState({uPlotInstance: plot,widgetId: config.getWidgetId(),+ shouldSaveSelectionPreference: config.getShouldSaveSelectionPreference(),});plotInstanceRef.current = plot;- configUsedForPlotRef.current = config;}, [config,data,@@ -143,11 +136,13 @@ export default function UPlotChart({return;}- // Check if the plot instance's container has been unmounted (e.g., after "No Data" state)- // If so, we need to recreate the plot with the new container+ // Check if the plot instance's root is no longer attached to our container+ // (e.g., after React has re‑mounted the container div). In uPlot, `root`+ // is a child of the container, so we must compare against its parent node.const isPlotOrphaned =- plotInstanceRef.current &&- plotInstanceRef.current.root !== containerRef.current;+ !!plotInstanceRef.current &&+ (!containerRef.current ||+ plotInstanceRef.current.root.parentElement !== containerRef.current);// Update dimensions without reinitializing if only size changedif (diff --git a/frontend/src/lib/uPlotV2/config/UPlotConfigBuilder.ts b/frontend/src/lib/uPlotV2/config/UPlotConfigBuilder.tsindex a029edc8a1..561ec6a3c3 100644--- a/frontend/src/lib/uPlotV2/config/UPlotConfigBuilder.ts+++ b/frontend/src/lib/uPlotV2/config/UPlotConfigBuilder.ts@@ -1,6 +1,7 @@import { getStoredSeriesVisibility } from 'container/DashboardContainer/visualization/panels/utils/legendVisibilityUtils';import { ThresholdsDrawHookOptions } from 'lib/uPlotV2/hooks/types';import { thresholdsDrawHook } from 'lib/uPlotV2/hooks/useThresholdsDrawHook';+import { resolveSeriesVisibility } from 'lib/uPlotV2/utils/seriesVisibility';import { merge } from 'lodash-es';import noop from 'lodash-es/noop';import uPlot, { Cursor, Hooks, Options } from 'uplot';@@ -11,6 +12,7 @@ import {DEFAULT_CURSOR_CONFIG,DEFAULT_PLOT_CONFIG,LegendItem,+ SelectionPreferencesSource,} from './types';import { AxisProps, UPlotAxisBuilder } from './UPlotAxisBuilder';import { ScaleProps, UPlotScaleBuilder } from './UPlotScaleBuilder';@@ -36,6 +38,10 @@ export class UPlotConfigBuilder extends ConfigBuilder<> {series: UPlotSeriesBuilder[] = [];+ private selectionPreferencesSource: SelectionPreferencesSource =+ SelectionPreferencesSource.IN_MEMORY;+ private shouldSaveSelectionPreference = false;+private axes: Record<string, UPlotAxisBuilder> = {};readonly scales: UPlotScaleBuilder[] = [];@@ -64,11 +70,15 @@ export class UPlotConfigBuilder extends ConfigBuilder<private onDragSelect: (startTime: number, endTime: number) => void;- private cleanups: Array<() => void> = [];-constructor(args?: ConfigBuilderProps) {super(args ?? {});- const { widgetId, onDragSelect, tzDate } = args ?? {};+ const {+ widgetId,+ onDragSelect,+ tzDate,+ selectionPreferencesSource,+ shouldSaveSelectionPreference,+ } = args ?? {};if (widgetId) {this.widgetId = widgetId;}@@ -77,25 +87,38 @@ export class UPlotConfigBuilder extends ConfigBuilder<this.tzDate = tzDate;}- this.onDragSelect = noop;+ if (selectionPreferencesSource) {+ this.selectionPreferencesSource = selectionPreferencesSource;+ }+ if (shouldSaveSelectionPreference) {+ this.shouldSaveSelectionPreference = shouldSaveSelectionPreference;+ }++ this.onDragSelect = noop;if (onDragSelect) {this.onDragSelect = onDragSelect;- // Add a hook to handle the select event- const cleanup = this.addHook('setSelect', (self: uPlot): void => {+ this.addHook('setSelect', (self: uPlot): void => {const selection = self.select;// Only trigger onDragSelect when there's an actual drag range (width > 0)// A click without dragging produces width === 0, which should be ignoredif (selection && selection.width > 0) {const startTime = self.posToVal(selection.left, 'x');const endTime = self.posToVal(selection.left + selection.width, 'x');+this.onDragSelect(startTime * 1000, endTime * 1000);}});- this.cleanups.push(cleanup);}}+ /**+ * Get the save selection preferences+ */+ getShouldSaveSelectionPreference(): boolean {+ return this.shouldSaveSelectionPreference;+ }+/*** Add or merge an axis configuration*/@@ -158,8 +181,7 @@ export class UPlotConfigBuilder extends ConfigBuilder<addThresholds(options: ThresholdsDrawHookOptions): void {if (!this.thresholds[options.scaleKey]) {this.thresholds[options.scaleKey] = options;- const cleanup = this.addHook('draw', thresholdsDrawHook(options));- this.cleanups.push(cleanup);+ this.addHook('draw', thresholdsDrawHook(options));}}@@ -212,20 +234,39 @@ export class UPlotConfigBuilder extends ConfigBuilder<this.tzDate = tzDate;}+ /**+ * Returns stored series visibility map from localStorage when preferences source is LOCAL_STORAGE, otherwise null.+ */+ private getStoredVisibilityMap(): Map<string, boolean> | null {+ if (+ this.widgetId &&+ this.selectionPreferencesSource === SelectionPreferencesSource.LOCAL_STORAGE+ ) {+ return getStoredSeriesVisibility(this.widgetId);+ }+ return null;+ }+/*** Get legend items with visibility state restored from localStorage if available*/getLegendItems(): Record<number, LegendItem> {- const visibilityMap = this.widgetId- ? getStoredSeriesVisibility(this.widgetId)- : null;+ const visibilityMap = this.getStoredVisibilityMap();+ const isAnySeriesHidden = !!(+ visibilityMap && Array.from(visibilityMap.values()).some((show) => !show)+ );+return this.series.reduce((acc, s: UPlotSeriesBuilder, index: number) => {const seriesConfig = s.getConfig();const label = seriesConfig.label ?? '';const seriesIndex = index + 1; // +1 because the first series is the timestamp- // Priority: stored visibility > series config > default (true)- const show = visibilityMap?.get(label) ?? seriesConfig.show ?? true;+ const show = resolveSeriesVisibility(+ label,+ seriesConfig.show,+ visibilityMap,+ isAnySeriesHidden,+ );acc[seriesIndex] = {seriesIndex,@@ -238,13 +279,6 @@ export class UPlotConfigBuilder extends ConfigBuilder<}, {} as Record<number, LegendItem>);}- /**- * Remove all hooks and cleanup functions- */- destroy(): void {- this.cleanups.forEach((cleanup) => cleanup());- }-/*** Get the widget id*/@@ -260,9 +294,27 @@ export class UPlotConfigBuilder extends ConfigBuilder<...DEFAULT_PLOT_CONFIG,};+ const visibilityMap = this.getStoredVisibilityMap();+ const isAnySeriesHidden = !!(+ visibilityMap && Array.from(visibilityMap.values()).some((show) => !show)+ );+config.series = [{ value: (): string => '' }, // Base series for timestamp- ...this.series.map((s) => s.getConfig()),+ ...this.series.map((s) => {+ const series = s.getConfig();+ const label = series.label ?? '';+ const visible = resolveSeriesVisibility(+ label,+ series.show,+ visibilityMap,+ isAnySeriesHidden,+ );+ return {+ ...series,+ show: visible,+ };+ }),];config.axes = Object.values(this.axes).map((a) => a.getConfig());config.scales = this.scales.reduce(diff --git a/frontend/src/lib/uPlotV2/config/types.ts b/frontend/src/lib/uPlotV2/config/types.tsindex cf7a508b59..099c11c98d 100644--- a/frontend/src/lib/uPlotV2/config/types.ts+++ b/frontend/src/lib/uPlotV2/config/types.ts@@ -22,6 +22,14 @@ export abstract class ConfigBuilder<P, T> {merge?(props: Partial<P>): void;}+/**+ * Preferences source for the uPlot config builder+ */+export enum SelectionPreferencesSource {+ LOCAL_STORAGE = 'LOCAL_STORAGE',+ IN_MEMORY = 'IN_MEMORY',+}+/*** Props for configuring the uPlot config builder*/@@ -29,6 +37,8 @@ export interface ConfigBuilderProps {widgetId?: string;onDragSelect?: (startTime: number, endTime: number) => void;tzDate?: uPlot.LocalDateFromUnix;+ selectionPreferencesSource?: SelectionPreferencesSource;+ shouldSaveSelectionPreference?: boolean;}/**diff --git a/frontend/src/lib/uPlotV2/context/PlotContext.tsx b/frontend/src/lib/uPlotV2/context/PlotContext.tsxindex 2a522b61cb..95ec7eed69 100644--- a/frontend/src/lib/uPlotV2/context/PlotContext.tsx+++ b/frontend/src/lib/uPlotV2/context/PlotContext.tsx@@ -9,16 +9,17 @@ import {import type { SeriesVisibilityItem } from 'container/DashboardContainer/visualization/panels/types';import { updateSeriesVisibilityToLocalStorage } from 'container/DashboardContainer/visualization/panels/utils/legendVisibilityUtils';import type uPlot from 'uplot';-export interface PlotContextInitialState {uPlotInstance: uPlot | null;widgetId?: string;+ shouldSaveSelectionPreference?: boolean;}export interface IPlotContext {setPlotContextInitialState: (state: PlotContextInitialState) => void;onToggleSeriesVisibility: (seriesIndex: number) => void;onToggleSeriesOnOff: (seriesIndex: number) => void;onFocusSeries: (seriesIndex: number | null) => void;+ syncSeriesVisibilityToLocalStorage: () => void;}export const PlotContext = createContext<IPlotContext | null>(null);@@ -29,68 +30,84 @@ export const PlotContextProvider = ({const uPlotInstanceRef = useRef<uPlot | null>(null);const activeSeriesIndex = useRef<number | undefined>(undefined);const widgetIdRef = useRef<string | undefined>(undefined);+ const shouldSavePreferencesRef = useRef<boolean>(false);const setPlotContextInitialState = useCallback(- ({ uPlotInstance, widgetId }: PlotContextInitialState): void => {+ ({+ uPlotInstance,+ widgetId,+ shouldSaveSelectionPreference,+ }: PlotContextInitialState): void => {uPlotInstanceRef.current = uPlotInstance;widgetIdRef.current = widgetId;activeSeriesIndex.current = undefined;+ shouldSavePreferencesRef.current = !!shouldSaveSelectionPreference;},[],);- const onToggleSeriesVisibility = useCallback((seriesIndex: number): void => {+ const syncSeriesVisibilityToLocalStorage = useCallback((): void => {const plot = uPlotInstanceRef.current;- if (!plot) {+ if (!plot || !widgetIdRef.current) {return;}- const isReset = activeSeriesIndex.current === seriesIndex;- activeSeriesIndex.current = isReset ? undefined : seriesIndex;+ const seriesVisibility: SeriesVisibilityItem[] = plot.series.map(+ (series) => ({+ label: series.label ?? '',+ show: series.show ?? true,+ }),+ );- plot.batch(() => {- plot.series.forEach((_, index) => {- if (index === 0) {- return;- }- const currentSeriesIndex = index;- plot.setSeries(currentSeriesIndex, {- show: isReset || currentSeriesIndex === seriesIndex,+ updateSeriesVisibilityToLocalStorage(widgetIdRef.current, seriesVisibility);+ }, []);++ const onToggleSeriesVisibility = useCallback(+ (seriesIndex: number): void => {+ const plot = uPlotInstanceRef.current;+ if (!plot) {+ return;+ }++ const isReset = activeSeriesIndex.current === seriesIndex;+ activeSeriesIndex.current = isReset ? undefined : seriesIndex;++ plot.batch(() => {+ plot.series.forEach((_, index) => {+ if (index === 0) {+ return;+ }+ const currentSeriesIndex = index;+ plot.setSeries(currentSeriesIndex, {+ show: isReset || currentSeriesIndex === seriesIndex,+ });});+ if (widgetIdRef.current && shouldSavePreferencesRef.current) {+ syncSeriesVisibilityToLocalStorage();+ }});- if (widgetIdRef.current) {- const seriesVisibility: SeriesVisibilityItem[] = plot.series.map(- (series) => ({- label: series.label ?? '',- show: series.show ?? true,- }),- );- updateSeriesVisibilityToLocalStorage(widgetIdRef.current, seriesVisibility);- }- });- }, []);+ },+ [syncSeriesVisibilityToLocalStorage],+ );- const onToggleSeriesOnOff = useCallback((seriesIndex: number): void => {- const plot = uPlotInstanceRef.current;- if (!plot) {- return;- }+ const onToggleSeriesOnOff = useCallback(+ (seriesIndex: number): void => {+ const plot = uPlotInstanceRef.current;+ if (!plot) {+ return;+ }- const series = plot.series[seriesIndex];- if (!series) {- return;- }- plot.setSeries(seriesIndex, { show: !series.show });- if (widgetIdRef.current) {- const seriesVisibility: SeriesVisibilityItem[] = plot.series.map(- (series) => ({- label: series.label ?? '',- show: series.show ?? true,- }),- );- updateSeriesVisibilityToLocalStorage(widgetIdRef.current, seriesVisibility);- }- }, []);+ const series = plot.series[seriesIndex];+ if (!series) {+ return;+ }+ plot.setSeries(seriesIndex, { show: !series.show });+ if (widgetIdRef.current && shouldSavePreferencesRef.current) {+ syncSeriesVisibilityToLocalStorage();+ }+ },+ [syncSeriesVisibilityToLocalStorage],+ );const onFocusSeries = useCallback((seriesIndex: number | null): void => {const plot = uPlotInstanceRef.current;@@ -113,12 +130,14 @@ export const PlotContextProvider = ({setPlotContextInitialState,onToggleSeriesOnOff,onFocusSeries,+ syncSeriesVisibilityToLocalStorage,}),[onToggleSeriesVisibility,setPlotContextInitialState,onToggleSeriesOnOff,onFocusSeries,+ syncSeriesVisibilityToLocalStorage,],);diff --git a/frontend/src/lib/uPlotV2/utils/seriesVisibility.ts b/frontend/src/lib/uPlotV2/utils/seriesVisibility.tsnew file mode 100644index 0000000000..612362560e--- /dev/null+++ b/frontend/src/lib/uPlotV2/utils/seriesVisibility.ts@@ -0,0 +1,11 @@+export function resolveSeriesVisibility(+ label: string,+ seriesShow: boolean | undefined | null,+ visibilityMap: Map<string, boolean> | null,+ isAnySeriesHidden: boolean,+): boolean {+ if (isAnySeriesHidden) {+ return visibilityMap?.get(label) ?? false;+ }+ return seriesShow ?? true;+}