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.

feat: added variable in url and made dashboard sync around that and sharable with user friendly format (#8874)

SagarRajput-7437d0d134502
diff --git a/frontend/src/components/NewSelect/CustomMultiSelect.tsx b/frontend/src/components/NewSelect/CustomMultiSelect.tsx
index afe2116a04..1050cc253b 100644
--- a/frontend/src/components/NewSelect/CustomMultiSelect.tsx
+++ b/frontend/src/components/NewSelect/CustomMultiSelect.tsx
@@ -32,6 +32,7 @@ import { popupContainer } from 'utils/selectPopupContainer';
import { CustomMultiSelectProps, CustomTagProps, OptionData } from './types';
import {
+ ALL_SELECTED_VALUE,
filterOptionsBySearch,
handleScrollToBottom,
prioritizeOrAddOptionForMultiSelect,
@@ -43,8 +44,6 @@ enum ToggleTagValue {
All = 'All',
}
-const ALL_SELECTED_VALUE = '__ALL__'; // Constant for the special value
-
const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
placeholder = 'Search...',
className,
diff --git a/frontend/src/components/NewSelect/utils.ts b/frontend/src/components/NewSelect/utils.ts
index c17f15d3fe..3cae1ac6ff 100644
--- a/frontend/src/components/NewSelect/utils.ts
+++ b/frontend/src/components/NewSelect/utils.ts
@@ -5,6 +5,8 @@ import { OptionData } from './types';
export const SPACEKEY = ' ';
+export const ALL_SELECTED_VALUE = '__ALL__'; // Constant for the special value
+
export const prioritizeOrAddOptionForSingleSelect = (
options: OptionData[],
value: string,
diff --git a/frontend/src/constants/query.ts b/frontend/src/constants/query.ts
index b50eb38d27..5e5237c329 100644
--- a/frontend/src/constants/query.ts
+++ b/frontend/src/constants/query.ts
@@ -50,4 +50,5 @@ export enum QueryParams {
tab = 'tab',
thresholds = 'thresholds',
selectedExplorerView = 'selectedExplorerView',
+ variables = 'variables',
}
diff --git a/frontend/src/container/NewDashboard/DashboardVariablesSelection/DashboardVariableSelection.tsx b/frontend/src/container/NewDashboard/DashboardVariablesSelection/DashboardVariableSelection.tsx
index 7e8a3e45d2..8073adaeea 100644
--- a/frontend/src/container/NewDashboard/DashboardVariablesSelection/DashboardVariableSelection.tsx
+++ b/frontend/src/container/NewDashboard/DashboardVariablesSelection/DashboardVariableSelection.tsx
@@ -1,8 +1,11 @@
import './DashboardVariableSelection.styles.scss';
import { Row } from 'antd';
+import { ALL_SELECTED_VALUE } from 'components/NewSelect/utils';
+import useVariablesFromUrl from 'hooks/dashboard/useVariablesFromUrl';
import { isEmpty } from 'lodash-es';
import { useDashboard } from 'providers/Dashboard/Dashboard';
+import { initializeDefaultVariables } from 'providers/Dashboard/initializeDefaultVariables';
import { memo, useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import { AppState } from 'store/reducers';
@@ -28,6 +31,8 @@ function DashboardVariableSelection(): JSX.Element | null {
setVariablesToGetUpdated,
} = useDashboard();
+ const { updateUrlVariable, getUrlVariables } = useVariablesFromUrl();
+
const { data } = selectedDashboard || {};
const { variables } = data || {};
@@ -61,8 +66,11 @@ function DashboardVariableSelection(): JSX.Element | null {
tableRowData.sort((a, b) => a.order - b.order);
setVariablesTableData(tableRowData);
+
+ // Initialize variables with default values if not in URL
+ initializeDefaultVariables(variables, getUrlVariables, updateUrlVariable);
}
- }, [variables]);
+ }, [getUrlVariables, updateUrlVariable, variables]);
useEffect(() => {
if (variablesTableData.length > 0) {
@@ -118,6 +126,12 @@ function DashboardVariableSelection(): JSX.Element | null {
const isDynamic = variable?.type === 'DYNAMIC';
updateLocalStorageDashboardVariables(name, value, allSelected, isDynamic);
+ if (allSelected) {
+ updateUrlVariable(name || id, ALL_SELECTED_VALUE);
+ } else {
+ updateUrlVariable(name || id, value);
+ }
+
if (selectedDashboard) {
setSelectedDashboard((prev) => {
if (prev) {
diff --git a/frontend/src/hooks/dashboard/__test__/useVariablesFromUrl.test.tsx b/frontend/src/hooks/dashboard/__test__/useVariablesFromUrl.test.tsx
new file mode 100644
index 0000000000..57b8bfb200
--- /dev/null
+++ b/frontend/src/hooks/dashboard/__test__/useVariablesFromUrl.test.tsx
@@ -0,0 +1,253 @@
+import { act, renderHook } from '@testing-library/react';
+import { QueryParams } from 'constants/query';
+import { createMemoryHistory } from 'history';
+import { Router } from 'react-router-dom';
+import { IDashboardVariable } from 'types/api/dashboard/getAll';
+
+import useVariablesFromUrl, {
+ LocalStoreDashboardVariables,
+} from '../useVariablesFromUrl';
+
+describe('useVariablesFromUrl', () => {
+ it('should initialize with empty variables when no URL params exist', () => {
+ const history = createMemoryHistory({
+ initialEntries: ['/'],
+ });
+
+ const { result } = renderHook(() => useVariablesFromUrl(), {
+ wrapper: ({ children }: { children: React.ReactNode }) => (
+ <Router history={history}>{children}</Router>
+ ),
+ });
+
+ expect(result.current.getUrlVariables()).toEqual({});
+ });
+
+ it('should correctly parse variables from URL', () => {
+ const mockVariables = {
+ var1: 'value1',
+ var2: ['value2', 'value3'],
+ var3: 123,
+ };
+
+ const encodedVariables = encodeURIComponent(JSON.stringify(mockVariables));
+ const history = createMemoryHistory({
+ initialEntries: [`/?${QueryParams.variables}=${encodedVariables}`],
+ });
+
+ const { result } = renderHook(() => useVariablesFromUrl(), {
+ wrapper: ({ children }: { children: React.ReactNode }) => (
+ <Router history={history}>{children}</Router>
+ ),
+ });
+
+ expect(result.current.getUrlVariables()).toEqual(mockVariables);
+ });
+
+ it('should handle malformed URL parameters gracefully', () => {
+ const history = createMemoryHistory({
+ initialEntries: [`/?${QueryParams.variables}=invalid-json`],
+ });
+
+ const { result } = renderHook(() => useVariablesFromUrl(), {
+ wrapper: ({ children }: { children: React.ReactNode }) => (
+ <Router history={history}>{children}</Router>
+ ),
+ });
+
+ // Should return empty object when JSON parsing fails
+ expect(result.current.getUrlVariables()).toEqual({});
+ });
+
+ it('should set variables to URL correctly', () => {
+ const history = createMemoryHistory({
+ initialEntries: ['/'],
+ });
+
+ const { result } = renderHook(() => useVariablesFromUrl(), {
+ wrapper: ({ children }: { children: React.ReactNode }) => (
+ <Router history={history}>{children}</Router>
+ ),
+ });
+
+ const mockVariables: LocalStoreDashboardVariables = {
+ var1: 'value1',
+ var2: ['value2', 'value3'],
+ };
+
+ act(() => {
+ result.current.setUrlVariables(mockVariables);
+ });
+
+ // Check if the URL was updated correctly
+ const searchParams = new URLSearchParams(history.location.search);
+ const urlVariables = searchParams.get(QueryParams.variables);
+
+ expect(urlVariables).toBeTruthy();
+ expect(JSON.parse(decodeURIComponent(urlVariables || ''))).toEqual(
+ mockVariables,
+ );
+ });
+
+ it('should remove variables param from URL when empty object is provided', () => {
+ const mockVariables = {
+ var1: 'value1',
+ var2: ['value2', 'value3'],
+ };
+
+ const encodedVariables = encodeURIComponent(JSON.stringify(mockVariables));
+ const history = createMemoryHistory({
+ initialEntries: [`/?${QueryParams.variables}=${encodedVariables}`],
+ });
+
+ const { result } = renderHook(() => useVariablesFromUrl(), {
+ wrapper: ({ children }: { children: React.ReactNode }) => (
+ <Router history={history}>{children}</Router>
+ ),
+ });
+
+ act(() => {
+ result.current.setUrlVariables({});
+ });
+
+ // Check if the URL param was removed
+ const searchParams = new URLSearchParams(history.location.search);
+ expect(searchParams.has(QueryParams.variables)).toBe(false);
+ });
+
+ it('should update a specific variable correctly', () => {
+ const initialVariables = {
+ var1: 'value1',
+ var2: ['value2', 'value3'],
+ };
+
+ const encodedVariables = encodeURIComponent(JSON.stringify(initialVariables));
+ const history = createMemoryHistory({
+ initialEntries: [`/?${QueryParams.variables}=${encodedVariables}`],
+ });
+
+ const { result } = renderHook(() => useVariablesFromUrl(), {
+ wrapper: ({ children }: { children: React.ReactNode }) => (
+ <Router history={history}>{children}</Router>
+ ),
+ });
+
+ const newValue: IDashboardVariable['selectedValue'] = 'updated-value';
+
+ act(() => {
+ result.current.updateUrlVariable('var1', newValue);
+ });
+
+ // Check if only the specified variable was updated
+ const updatedVariables = result.current.getUrlVariables();
+ expect(updatedVariables.var1).toEqual(newValue);
+ expect(updatedVariables.var2).toEqual(initialVariables.var2);
+ });
+
+ it('should preserve other URL parameters when updating variables', () => {
+ const history = createMemoryHistory({
+ initialEntries: ['/?otherParam=value'],
+ });
+
+ const { result } = renderHook(() => useVariablesFromUrl(), {
+ wrapper: ({ children }: { children: React.ReactNode }) => (
+ <Router history={history}>{children}</Router>
+ ),
+ });
+
+ const mockVariables: LocalStoreDashboardVariables = {
+ var1: 'value1',
+ };
+
+ act(() => {
+ result.current.setUrlVariables(mockVariables);
+ });
+
+ // Check if other params are preserved
+ const searchParams = new URLSearchParams(history.location.search);
+ expect(searchParams.get('otherParam')).toBe('value');
+ expect(searchParams.has(QueryParams.variables)).toBe(true);
+ });
+
+ it('should handle different variable value types correctly', () => {
+ const mockVariables: LocalStoreDashboardVariables = {
+ stringVar: 'production',
+ numberVar: 123,
+ booleanVar: true,
+ arrayVar: ['service1', 'service2'],
+ mixedArrayVar: ['string', 456, false],
+ nullVar: null,
+ };
+
+ const encodedVariables = encodeURIComponent(JSON.stringify(mockVariables));
+ const history = createMemoryHistory({
+ initialEntries: [`/?${QueryParams.variables}=${encodedVariables}`],
+ });
+
+ const { result } = renderHook(() => useVariablesFromUrl(), {
+ wrapper: ({ children }: { children: React.ReactNode }) => (
+ <Router history={history}>{children}</Router>
+ ),
+ });
+
+ const urlVariables = result.current.getUrlVariables();
+ expect(urlVariables.stringVar).toBe('production');
+ expect(urlVariables.numberVar).toBe(123);
+ expect(urlVariables.booleanVar).toBe(true);
+ expect(urlVariables.arrayVar).toEqual(['service1', 'service2']);
+ expect(urlVariables.mixedArrayVar).toEqual(['string', 456, false]);
+ expect(urlVariables.nullVar).toBeNull();
+ });
+
+ it('should handle edge cases in URL variable parsing', () => {
+ const edgeCaseVariables = {
+ emptyString: '',
+ emptyArray: [],
+ singleItemArray: ['solo'],
+ };
+
+ const encodedVariables = encodeURIComponent(
+ JSON.stringify(edgeCaseVariables),
+ );
+ const history = createMemoryHistory({
+ initialEntries: [`/?${QueryParams.variables}=${encodedVariables}`],
+ });
+
+ const { result } = renderHook(() => useVariablesFromUrl(), {
+ wrapper: ({ children }: { children: React.ReactNode }) => (
+ <Router history={history}>{children}</Router>
+ ),
+ });
+
+ const urlVariables = result.current.getUrlVariables();
+ expect(urlVariables.emptyString).toBe('');
+ expect(urlVariables.emptyArray).toEqual([]);
+ expect(urlVariables.singleItemArray).toEqual(['solo']);
+ expect(urlVariables.undefinedVar).toBeUndefined();
+ });
+
+ it('should update variables with array values correctly', () => {
+ const history = createMemoryHistory({
+ initialEntries: ['/'],
+ });
+
+ const { result } = renderHook(() => useVariablesFromUrl(), {
+ wrapper: ({ children }: { children: React.ReactNode }) => (
+ <Router history={history}>{children}</Router>
+ ),
+ });
+
+ const arrayValue: IDashboardVariable['selectedValue'] = [
+ 'value1',
+ 'value2',
+ 'value3',
+ ];
+
+ act(() => {
+ result.current.updateUrlVariable('multiSelectVar', arrayValue);
+ });
+
+ const updatedVariables = result.current.getUrlVariables();
+ expect(updatedVariables.multiSelectVar).toEqual(arrayValue);
+ });
+});
diff --git a/frontend/src/hooks/dashboard/useVariablesFromUrl.tsx b/frontend/src/hooks/dashboard/useVariablesFromUrl.tsx
new file mode 100644
index 0000000000..e38bf6a6ef
--- /dev/null
+++ b/frontend/src/hooks/dashboard/useVariablesFromUrl.tsx
@@ -0,0 +1,103 @@
+import * as Sentry from '@sentry/react';
+import { QueryParams } from 'constants/query';
+import useUrlQuery from 'hooks/useUrlQuery';
+import { useCallback } from 'react';
+import { useHistory } from 'react-router-dom';
+import { IDashboardVariable } from 'types/api/dashboard/getAll';
+
+export interface LocalStoreDashboardVariables {
+ [name: string]:
+ | IDashboardVariable['selectedValue'][]
+ | IDashboardVariable['selectedValue'];
+}
+
+interface UseVariablesFromUrlReturn {
+ getUrlVariables: () => LocalStoreDashboardVariables;
+ setUrlVariables: (variables: LocalStoreDashboardVariables) => void;
+ updateUrlVariable: (
+ name: string,
+ selectedValue: IDashboardVariable['selectedValue'],
+ ) => void;
+ clearUrlVariables: () => void;
+}
+
+const useVariablesFromUrl = (): UseVariablesFromUrlReturn => {
+ const urlQuery = useUrlQuery();
+ const history = useHistory();
+
+ const getUrlVariables = useCallback((): LocalStoreDashboardVariables => {
+ const variablesParam = urlQuery.get(QueryParams.variables);
+
+ if (!variablesParam) {
+ return {};
+ }
+
+ try {
+ return JSON.parse(decodeURIComponent(variablesParam));
+ } catch (error) {
+ Sentry.captureEvent({
+ message: `Failed to parse dashboard variables from URL: ${error}`,
+ level: 'error',
+ });
+ return {};
+ }
+ }, [urlQuery]);
+
+ const setUrlVariables = useCallback(
+ (variables: LocalStoreDashboardVariables): void => {
+ const params = new URLSearchParams(urlQuery.toString());
+
+ if (Object.keys(variables).length === 0) {
+ params.delete(QueryParams.variables);
+ } else {
+ try {
+ const encodedVariables = encodeURIComponent(JSON.stringify(variables));
+ params.set(QueryParams.variables, encodedVariables);
+ } catch (error) {
+ Sentry.captureEvent({
+ message: `Failed to serialize dashboard variables for URL: ${error}`,
+ level: 'error',
+ });
+ }
+ }
+
+ history.replace({
+ search: params.toString(),
+ });
+ },
+ [history, urlQuery],
+ );
+
+ const clearUrlVariables = useCallback((): void => {
+ const params = new URLSearchParams(urlQuery.toString());
+ params.delete(QueryParams.variables);
+ params.delete('options');
+
+ history.replace({
+ search: params.toString(),
+ });
+ }, [history, urlQuery]);
+
+ const updateUrlVariable = useCallback(
+ (name: string, selectedValue: IDashboardVariable['selectedValue']): void => {
+ const currentVariables = getUrlVariables();
+
+ const updatedVariables = {
+ ...currentVariables,
+ [name]: selectedValue,
+ };
+
+ setUrlVariables(updatedVariables as LocalStoreDashboardVariables);
+ },
+ [getUrlVariables, setUrlVariables],
+ );
+
+ return {
+ getUrlVariables,
+ setUrlVariables,
+ updateUrlVariable,
+ clearUrlVariables,
+ };
+};
+
+export default useVariablesFromUrl;
diff --git a/frontend/src/providers/Dashboard/Dashboard.tsx b/frontend/src/providers/Dashboard/Dashboard.tsx
index c8aa3c7d51..7c2db3944e 100644
--- a/frontend/src/providers/Dashboard/Dashboard.tsx
+++ b/frontend/src/providers/Dashboard/Dashboard.tsx
@@ -2,20 +2,24 @@
import { Modal } from 'antd';
import getDashboard from 'api/v1/dashboards/id/get';
import locked from 'api/v1/dashboards/id/lock';
+import { ALL_SELECTED_VALUE } from 'components/NewSelect/utils';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import ROUTES from 'constants/routes';
import { getMinMax } from 'container/TopNav/AutoRefresh/config';
import dayjs, { Dayjs } from 'dayjs';
import { useDashboardVariablesFromLocalStorage } from 'hooks/dashboard/useDashboardFromLocalStorage';
+import useVariablesFromUrl from 'hooks/dashboard/useVariablesFromUrl';
import { useSafeNavigate } from 'hooks/useSafeNavigate';
import useTabVisibility from 'hooks/useTabFocus';
import useUrlQuery from 'hooks/useUrlQuery';
import { getUpdatedLayout } from 'lib/dashboard/getUpdatedLayout';
-import { defaultTo } from 'lodash-es';
+import { defaultTo, isEmpty } from 'lodash-es';
import isEqual from 'lodash-es/isEqual';
import isUndefined from 'lodash-es/isUndefined';
import omitBy from 'lodash-es/omitBy';
import { useAppContext } from 'providers/App/App';
+import { initializeDefaultVariables } from 'providers/Dashboard/initializeDefaultVariables';
+import { normalizeUrlValueForVariable } from 'providers/Dashboard/normalizeUrlValue';
import { useErrorModal } from 'providers/ErrorModalProvider';
import {
createContext,
@@ -198,6 +202,12 @@ export function DashboardProvider({
updateLocalStorageDashboardVariables,
} = useDashboardVariablesFromLocalStorage(dashboardId);
+ const {
+ getUrlVariables,
+ updateUrlVariable,
+ clearUrlVariables,
+ } = useVariablesFromUrl();
+
const updatedTimeRef = useRef<Dayjs | null>(null); // Using ref to store the updated time
const modalRef = useRef<any>(null);
@@ -208,6 +218,14 @@ export function DashboardProvider({
const [isDashboardFetching, setIsDashboardFetching] = useState<boolean>(false);
+ // Clear variable configs when not on dashboard pages
+ useEffect(() => {
+ const isOnDashboardPage = !!isDashboardPage || !!isDashboardWidgetPage;
+ if (!isOnDashboardPage) {
+ clearUrlVariables();
+ }
+ }, [isDashboardPage, isDashboardWidgetPage, clearUrlVariables]);
+
const mergeDBWithLocalStorage = (
data: Dashboard,
localStorageVariables: any,
@@ -215,13 +233,43 @@ export function DashboardProvider({
const updatedData = data;
if (data && localStorageVariables) {
const updatedVariables = data.data.variables;
+ const variablesFromUrl = getUrlVariables();
Object.keys(data.data.variables).forEach((variable) => {
const variableData = data.data.variables[variable];
- const updatedVariable = {
+
+ // values from url
+ const urlVariable = variableData?.name
+ ? variablesFromUrl[variableData?.name] || variablesFromUrl[variableData.id]
+ : variablesFromUrl[variableData.id];
+
+ let updatedVariable = {
...data.data.variables[variable],
...localStorageVariables[variableData.name as any],
};
+ // respect the url variable if it is set, override the others
+ if (!isEmpty(urlVariable)) {
+ if (urlVariable === ALL_SELECTED_VALUE) {
+ updatedVariable = {
+ ...updatedVariable,
+ allSelected: true,
+ };
+ } else {
+ // Normalize URL value to match variable's multiSelect configuration
+ const normalizedValue = normalizeUrlValueForVariable(
+ urlVariable,
+ variableData,
+ );
+
+ updatedVariable = {
+ ...updatedVariable,
+ selectedValue: normalizedValue,
+ // Only set allSelected to false if showALLOption is available
+ ...(updatedVariable?.showALLOption && { allSelected: false }),
+ };
+ }
+ }
+
updatedVariables[variable] = updatedVariable;
});
updatedData.data.variables = updatedVariables;
@@ -289,7 +337,14 @@ export function DashboardProvider({
onError: (error) => {
showErrorModal(error as APIError);
},
+
onSuccess: (data: SuccessResponseV2<Dashboard>) => {
+ // if the url variable is not set for any variable, set it to the default value
+ const variables = data?.data?.data?.variables;
+ if (variables) {
+ initializeDefaultVariables(variables, getUrlVariables, updateUrlVariable);
+ }
+
const updatedDashboardData = transformDashboardVariables(data?.data);
const updatedDate = dayjs(updatedDashboardData?.updatedAt);
diff --git a/frontend/src/providers/Dashboard/__tests__/Dashboard.test.tsx b/frontend/src/providers/Dashboard/__tests__/Dashboard.test.tsx
index feb7905cbb..ec3983804b 100644
--- a/frontend/src/providers/Dashboard/__tests__/Dashboard.test.tsx
+++ b/frontend/src/providers/Dashboard/__tests__/Dashboard.test.tsx
@@ -6,6 +6,10 @@ import ROUTES from 'constants/routes';
import { DashboardProvider, useDashboard } from 'providers/Dashboard/Dashboard';
import { QueryClient, QueryClientProvider } from 'react-query';
import { MemoryRouter } from 'react-router-dom';
+import { IDashboardVariable } from 'types/api/dashboard/getAll';
+
+import { initializeDefaultVariables } from '../initializeDefaultVariables';
+import { normalizeUrlValueForVariable } from '../normalizeUrlValue';
// Mock the dashboard API
jest.mock('api/v1/dashboards/id/get');
@@ -50,7 +54,7 @@ jest.mock('react-redux', () => ({
jest.mock('uuid', () => ({ v4: jest.fn(() => 'mock-uuid') }));
function TestComponent(): JSX.Element {
- const { dashboardResponse, dashboardId } = useDashboard();
+ const { dashboardResponse, dashboardId, selectedDashboard } = useDashboard();
return (
<div>
@@ -60,6 +64,14 @@ function TestComponent(): JSX.Element {
<div data-testid="is-fetching">
{dashboardResponse.isFetching.toString()}
</div>
+ <div data-testid="dashboard-variables">
+ {selectedDashboard?.data?.variables
+ ? JSON.stringify(selectedDashboard.data.variables)
+ : 'null'}
+ </div>
+ <div data-testid="dashboard-data">
+ {selectedDashboard?.data?.title || 'No Title'}
+ </div>
</div>
);
}
@@ -106,6 +118,38 @@ function renderWithDashboardProvider(
);
}
+// Mock URL variables hook
+const mockGetUrlVariables = jest.fn();
+const mockUpdateUrlVariable = jest.fn();
+const mockClearUrlVariables = jest.fn();
+const mockSetUrlVariables = jest.fn();
+
+jest.mock('hooks/dashboard/useVariablesFromUrl', () => ({
+ __esModule: true,
+ default: jest.fn(() => ({
+ getUrlVariables: mockGetUrlVariables,
+ updateUrlVariable: mockUpdateUrlVariable,
+ clearUrlVariables: mockClearUrlVariables,
+ setUrlVariables: mockSetUrlVariables,
+ })),
+}));
+
+// Mock normalization function
+jest.mock('providers/Dashboard/normalizeUrlValue', () => ({
+ normalizeUrlValueForVariable: jest.fn(),
+}));
+
+// Mock initialize default variables
+jest.mock('providers/Dashboard/initializeDefaultVariables', () => ({
+ initializeDefaultVariables: jest.fn(),
+}));
+
+const mockNormalizeUrlValueForVariable = jest.mocked(
+ normalizeUrlValueForVariable,
+);
+
+const mockInitializeDefaultVariables = jest.mocked(initializeDefaultVariables);
+
describe('Dashboard Provider - Query Key with Route Params', () => {
const DASHBOARD_ID = 'test-dashboard-id';
const mockDashboardData = {
@@ -290,3 +334,244 @@ describe('Dashboard Provider - Query Key with Route Params', () => {
});
});
});
+
+describe('Dashboard Provider - URL Variables Integration', () => {
+ const DASHBOARD_ID = 'test-dashboard-id';
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ /* eslint-disable @typescript-eslint/no-explicit-any */
+ mockGetDashboard.mockResolvedValue({
+ httpStatusCode: 200,
+ data: {
+ id: DASHBOARD_ID,
+ title: 'Test Dashboard',
+ data: {
+ variables: {
+ environment: {
+ id: 'env-id',
+ name: 'environment',
+ multiSelect: false,
+ allSelected: false,
+ showALLOption: true,
+ } as any,
+ services: {
+ id: 'svc-id',
+ name: 'services',
+ multiSelect: true,
+ allSelected: false,
+ showALLOption: true,
+ } as any,
+ },
+ },
+ },
+ } as any);
+ /* eslint-enable @typescript-eslint/no-explicit-any */
+ mockGetUrlVariables.mockReturnValue({});
+ mockNormalizeUrlValueForVariable.mockImplementation((urlValue) => {
+ if (urlValue === undefined || urlValue === null) {
+ return urlValue;
+ }
+ return urlValue as IDashboardVariable['selectedValue'];
+ });
+ });
+
+ describe('URL Variable Synchronization', () => {
+ it('should initialize variables correctly when no URL variables exist', async () => {
+ // Empty URL variables - tests initialization flow
+ mockGetUrlVariables.mockReturnValue({});
+
+ const { getByTestId } = renderWithDashboardProvider(
+ `/dashboard/${DASHBOARD_ID}`,
+ {
+ dashboardId: DASHBOARD_ID,
+ },
+ );
+
+ await waitFor(() => {
+ expect(mockGetDashboard).toHaveBeenCalledWith({ id: DASHBOARD_ID });
+ });
+
+ // Verify initializeDefaultVariables was called
+ await waitFor(() => {
+ expect(mockInitializeDefaultVariables).toHaveBeenCalledWith(
+ {
+ environment: {
+ id: 'env-id',
+ name: 'environment',
+ multiSelect: false,
+ allSelected: false,
+ showALLOption: true,
+ },
+ services: {
+ id: 'svc-id',
+ name: 'services',
+ multiSelect: true,
+ allSelected: false,
+ showALLOption: true,
+ },
+ },
+ mockGetUrlVariables,
+ mockUpdateUrlVariable,
+ );
+ });
+
+ // Verify dashboard state contains the variables with default values
+ await waitFor(() => {
+ const dashboardVariables = getByTestId('dashboard-variables');
+ const parsedVariables = JSON.parse(dashboardVariables.textContent || '{}');
+
+ expect(parsedVariables).toHaveProperty('environment');
+ expect(parsedVariables).toHaveProperty('services');
+ // Default allSelected values should be preserved
+ expect(parsedVariables.environment.allSelected).toBe(false);
+ expect(parsedVariables.services.allSelected).toBe(false);
+ });
+ });
+
+ it('should merge URL variables with dashboard data and normalize values correctly', async () => {
+ const urlVariables = {
+ environment: 'development',
+ services: ['db', 'cache'],
+ };
+
+ mockGetUrlVariables.mockReturnValue(urlVariables);
+ mockNormalizeUrlValueForVariable
+ .mockReturnValueOnce('development')
+ .mockReturnValueOnce(['db', 'cache']);
+
+ const { getByTestId } = renderWithDashboardProvider(
+ `/dashboard/${DASHBOARD_ID}`,
+ {
+ dashboardId: DASHBOARD_ID,
+ },
+ );
+
+ await waitFor(() => {
+ expect(mockGetDashboard).toHaveBeenCalledWith({ id: DASHBOARD_ID });
+ });
+
+ // Verify normalization was called with correct values and variable configs
+ await waitFor(() => {
+ expect(mockNormalizeUrlValueForVariable).toHaveBeenCalledWith(
+ 'development',
+ {
+ id: 'env-id',
+ name: 'environment',
+ multiSelect: false,
+ allSelected: false,
+ showALLOption: true,
+ },
+ );
+ expect(mockNormalizeUrlValueForVariable).toHaveBeenCalledWith(
+ ['db', 'cache'],
+ {
+ id: 'svc-id',
+ name: 'services',
+ multiSelect: true,
+ allSelected: false,
+ showALLOption: true,
+ },
+ );
+ });
+
+ // Verify the dashboard state reflects the normalized URL values
+ await waitFor(() => {
+ const dashboardVariables = getByTestId('dashboard-variables');
+ const parsedVariables = JSON.parse(dashboardVariables.textContent || '{}');
+
+ // The selectedValue should be updated with normalized URL values
+ expect(parsedVariables.environment.selectedValue).toBe('development');
+ expect(parsedVariables.services.selectedValue).toEqual(['db', 'cache']);
+
+ // allSelected should be set to false when URL values override
+ expect(parsedVariables.environment.allSelected).toBe(false);
+ expect(parsedVariables.services.allSelected).toBe(false);
+ });
+ });
+
+ it('should handle ALL_SELECTED_VALUE from URL and set allSelected correctly', async () => {
+ const urlVariables = {
+ services: '__ALL__',
+ };
+
+ mockGetUrlVariables.mockReturnValue(urlVariables);
+
+ const { getByTestId } = renderWithDashboardProvider(
+ `/dashboard/${DASHBOARD_ID}`,
+ {
+ dashboardId: DASHBOARD_ID,
+ },
+ );
+
+ await waitFor(() => {
+ expect(mockGetDashboard).toHaveBeenCalledWith({ id: DASHBOARD_ID });
+ });
+
+ // Should not call normalize for __ALL__ values
+ expect(mockNormalizeUrlValueForVariable).not.toHaveBeenCalledWith(
+ '__ALL__',
+ expect.anything(),
+ );
+
+ // Verify that allSelected is set to true for the services variable
+ await waitFor(() => {
+ const dashboardVariables = getByTestId('dashboard-variables');
+ const parsedVariables = JSON.parse(dashboardVariables.textContent || '{}');
+
+ expect(parsedVariables.services.allSelected).toBe(true);
+ // Environment should remain unaffected
+ expect(parsedVariables.environment.allSelected).toBe(false);
+ });
+ });
+
+ it('should clear URL variables when not on dashboard page', async () => {
+ mockUseRouteMatch.mockReturnValue(null); // Not on dashboard page
+
+ renderWithDashboardProvider('/other-page', null);
+
+ await waitFor(() => {
+ expect(mockClearUrlVariables).toHaveBeenCalled();
+ });
+ });
+ });
+
+ describe('Variable Value Normalization', () => {
+ it('should normalize URL variables when they exist', async () => {
+ const urlVariables = {
+ environment: ['development', 'staging'], // Array for single-select
+ services: 'api', // Single value for multi-select
+ };
+
+ mockGetUrlVariables.mockReturnValue(urlVariables);
+ mockNormalizeUrlValueForVariable
+ .mockReturnValueOnce('development')
+ .mockReturnValueOnce(['api']);
+
+ renderWithDashboardProvider(`/dashboard/${DASHBOARD_ID}`, {
+ dashboardId: DASHBOARD_ID,
+ });
+
+ await waitFor(() => {
+ // Verify normalization was called with the specific values and variable configs
+ expect(mockNormalizeUrlValueForVariable).toHaveBeenCalledWith(
+ ['development', 'staging'],
+ {
+ id: 'env-id',
+ name: 'environment',
+ multiSelect: false,
+ allSelected: false,
+ showALLOption: true,
+ },
+ );
+ expect(mockNormalizeUrlValueForVariable).toHaveBeenCalledWith('api', {
+ id: 'svc-id',
+ name: 'services',
+ multiSelect: true,
+ allSelected: false,
+ showALLOption: true,
+ });
+ });
+ });
+ });
+});
diff --git a/frontend/src/providers/Dashboard/__tests__/initializeDefaultVariables.test.ts b/frontend/src/providers/Dashboard/__tests__/initializeDefaultVariables.test.ts
new file mode 100644
index 0000000000..c4402bcea4
--- /dev/null
+++ b/frontend/src/providers/Dashboard/__tests__/initializeDefaultVariables.test.ts
@@ -0,0 +1,369 @@
+import { ALL_SELECTED_VALUE } from 'components/NewSelect/utils';
+import { IDashboardVariable } from 'types/api/dashboard/getAll';
+
+import { initializeDefaultVariables } from '../initializeDefaultVariables';
+
+describe('initializeDefaultVariables', () => {
+ let mockGetUrlVariables: jest.Mock;
+ let mockUpdateUrlVariable: jest.Mock;
+
+ beforeEach(() => {
+ mockGetUrlVariables = jest.fn();
+ mockUpdateUrlVariable = jest.fn();
+ });
+
+ afterEach(() => {
+ jest.clearAllMocks();
+ });
+
+ const createMockVariable = (
+ overrides: Partial<IDashboardVariable> = {},
+ ): IDashboardVariable => ({
+ id: 'test-id',
+ name: 'test-var',
+ description: '',
+ type: 'QUERY',
+ sort: 'DISABLED',
+ showALLOption: false,
+ multiSelect: false,
+ order: 0,
+ allSelected: false,
+ customValue: '',
+ textboxValue: '',
+ selectedValue: 'default',
+ defaultValue: 'default',
+ ...overrides,
+ });
+
+ describe('Variable initialization', () => {
+ it('should initialize variables when not present in URL and verify URL state', () => {
+ const variables = {
+ environment: createMockVariable({
+ id: 'env-id',
+ name: 'environment',
+ selectedValue: 'production',
+ allSelected: false,
+ showALLOption: false,
+ }),
+ };
+
+ mockGetUrlVariables.mockReturnValue({});
+
+ initializeDefaultVariables(
+ variables,
+ mockGetUrlVariables,
+ mockUpdateUrlVariable,
+ );
+
+ // Verify the correct URL update was called
+ expect(mockUpdateUrlVariable).toHaveBeenCalledWith(
+ 'environment',
+ 'production',
+ );
+ expect(mockUpdateUrlVariable).toHaveBeenCalledTimes(1);
+
+ // Verify the correct parameters were passed
+ const callArgs = mockUpdateUrlVariable.mock.calls[0];
+ expect(callArgs[0]).toBe('environment'); // Variable name as key
+ expect(callArgs[1]).toBe('production'); // selectedValue as value
+ });
+
+ it('should not initialize variables when already present in URL by name', () => {
+ const variables = {
+ environment: createMockVariable({
+ id: 'env-id',
+ name: 'environment',
+ selectedValue: 'production',
+ }),
+ };
+
+ mockGetUrlVariables.mockReturnValue({
+ environment: 'development',
+ });
+
+ initializeDefaultVariables(
+ variables,
+ mockGetUrlVariables,
+ mockUpdateUrlVariable,
+ );
+
+ expect(mockUpdateUrlVariable).not.toHaveBeenCalled();
+ });
+
+ it('should not initialize variables when already present in URL by ID', () => {
+ const variables = {
+ environment: createMockVariable({
+ id: 'env-id',
+ name: 'environment',
+ selectedValue: 'production',
+ }),
+ };
+
+ mockGetUrlVariables.mockReturnValue({
+ 'env-id': 'development',
+ });
+
+ initializeDefaultVariables(
+ variables,
+ mockGetUrlVariables,
+ mockUpdateUrlVariable,
+ );
+
+ expect(mockUpdateUrlVariable).not.toHaveBeenCalled();
+ });
+
+ it('should handle variables with showALLOption when allSelected is true', () => {
+ const variables = {
+ services: createMockVariable({
+ id: 'svc-id',
+ name: 'services',
+ multiSelect: true,
+ selectedValue: ['api', 'web'],
+ allSelected: true,
+ showALLOption: true,
+ }),
+ };
+
+ mockGetUrlVariables.mockReturnValue({});
+
+ initializeDefaultVariables(
+ variables,
+ mockGetUrlVariables,
+ mockUpdateUrlVariable,
+ );
+
+ expect(mockUpdateUrlVariable).toHaveBeenCalledWith(
+ 'services',
+ ALL_SELECTED_VALUE,
+ );
+ });
+
+ it('should use selectedValue when allSelected is false', () => {
+ const variables = {
+ services: createMockVariable({
+ id: 'svc-id',
+ name: 'services',
+ multiSelect: true,
+ selectedValue: ['api', 'web'],
+ allSelected: false,
+ showALLOption: true,
+ }),
+ };
+
+ mockGetUrlVariables.mockReturnValue({});
+
+ initializeDefaultVariables(
+ variables,
+ mockGetUrlVariables,
+ mockUpdateUrlVariable,
+ );
+
+ expect(mockUpdateUrlVariable).toHaveBeenCalledWith('services', [
+ 'api',
+ 'web',
+ ]);
+ });
+ });
+
+ describe('CUSTOM variable type', () => {
+ it('should use parsed customValue for CUSTOM type variables', () => {
+ const variables = {
+ customVar: createMockVariable({
+ id: 'custom-id',
+ name: 'customVar',
+ type: 'CUSTOM',
+ customValue: 'value1,value2,value3',
+ selectedValue: 'ignored',
+ }),
+ };
+
+ mockGetUrlVariables.mockReturnValue({});
+
+ initializeDefaultVariables(
+ variables,
+ mockGetUrlVariables,
+ mockUpdateUrlVariable,
+ );
+
+ expect(mockUpdateUrlVariable).toHaveBeenCalledWith('customVar', [
+ 'value1',
+ 'value2',
+ 'value3',
+ ]);
+ });
+
+ it('should handle empty customValue for CUSTOM type variables', () => {
+ const variables = {
+ customVar: createMockVariable({
+ id: 'custom-id',
+ name: 'customVar',
+ type: 'CUSTOM',
+ customValue: '',
+ selectedValue: 'fallback',
+ }),
+ };
+
+ mockGetUrlVariables.mockReturnValue({});
+
+ initializeDefaultVariables(
+ variables,
+ mockGetUrlVariables,
+ mockUpdateUrlVariable,
+ );
+
+ expect(mockUpdateUrlVariable).toHaveBeenCalledWith('customVar', []);
+ });
+ });
+
+ describe('Fallback to defaultValue', () => {
+ it('should use defaultValue when selectedValue is not available', () => {
+ const variables = {
+ environment: createMockVariable({
+ id: 'env-id',
+ name: 'environment',
+ selectedValue: undefined,
+ defaultValue: 'staging',
+ }),
+ };
+
+ mockGetUrlVariables.mockReturnValue({});
+
+ initializeDefaultVariables(
+ variables,
+ mockGetUrlVariables,
+ mockUpdateUrlVariable,
+ );
+
+ expect(mockUpdateUrlVariable).toHaveBeenCalledWith('environment', 'staging');
+ });
+
+ it('should prefer selectedValue over defaultValue when available', () => {
+ const variables = {
+ environment: createMockVariable({
+ id: 'env-id',
+ name: 'environment',
+ selectedValue: 'production',
+ defaultValue: 'staging',
+ }),
+ };
+
+ mockGetUrlVariables.mockReturnValue({});
+
+ initializeDefaultVariables(
+ variables,
+ mockGetUrlVariables,
+ mockUpdateUrlVariable,
+ );
+
+ expect(mockUpdateUrlVariable).toHaveBeenCalledWith(
+ 'environment',
+ 'production',
+ );
+ });
+ });
+
+ describe('Edge cases', () => {
+ it('should handle undefined variables gracefully', () => {
+ expect(() => {
+ initializeDefaultVariables(
+ undefined as any,
+ mockGetUrlVariables,
+ mockUpdateUrlVariable,
+ );
+ }).not.toThrow();
+
+ expect(mockUpdateUrlVariable).not.toHaveBeenCalled();
+ });
+
+ it('should prefer name over id for URL variable key', () => {
+ const variables = {
+ environment: createMockVariable({
+ id: 'env-id',
+ name: 'environment',
+ selectedValue: 'production',
+ }),
+ };
+
+ mockGetUrlVariables.mockReturnValue({});
+
+ initializeDefaultVariables(
+ variables,
+ mockGetUrlVariables,
+ mockUpdateUrlVariable,
+ );
+
+ // Should use name as the key
+ expect(mockUpdateUrlVariable).toHaveBeenCalledWith(
+ 'environment',
+ 'production',
+ );
+ });
+
+ it('should use id as fallback when name is not available', () => {
+ const variables = {
+ environment: createMockVariable({
+ id: 'env-id',
+ name: undefined as any,
+ selectedValue: 'production',
+ }),
+ };
+
+ mockGetUrlVariables.mockReturnValue({});
+
+ initializeDefaultVariables(
+ variables,
+ mockGetUrlVariables,
+ mockUpdateUrlVariable,
+ );
+
+ // Should use id as the key when name is not available
+ expect(mockUpdateUrlVariable).toHaveBeenCalledWith('env-id', 'production');
+ });
+ });
+
+ describe('Multiple variables handling', () => {
+ it('should initialize multiple variables correctly', () => {
+ const variables = {
+ environment: createMockVariable({
+ id: 'env-id',
+ name: 'environment',
+ selectedValue: 'production',
+ }),
+ services: createMockVariable({
+ id: 'svc-id',
+ name: 'services',
+ multiSelect: true,
+ selectedValue: ['api', 'web'],
+ }),
+ region: createMockVariable({
+ id: 'region-id',
+ name: 'region',
+ selectedValue: 'us-east-1',
+ }),
+ };
+
+ mockGetUrlVariables.mockReturnValue({
+ environment: 'development', // This one exists in URL
+ // services and region don't exist in URL
+ });
+
+ initializeDefaultVariables(
+ variables,
+ mockGetUrlVariables,
+ mockUpdateUrlVariable,
+ );
+
+ // Should only initialize variables not in URL
+ expect(mockUpdateUrlVariable).toHaveBeenCalledTimes(2);
+ expect(mockUpdateUrlVariable).toHaveBeenCalledWith('services', [
+ 'api',
+ 'web',
+ ]);
+ expect(mockUpdateUrlVariable).toHaveBeenCalledWith('region', 'us-east-1');
+ expect(mockUpdateUrlVariable).not.toHaveBeenCalledWith(
+ 'environment',
+ expect.anything(),
+ );
+ });
+ });
+});
diff --git a/frontend/src/providers/Dashboard/__tests__/normalizeUrlValue.test.ts b/frontend/src/providers/Dashboard/__tests__/normalizeUrlValue.test.ts
new file mode 100644
index 0000000000..70bebe9aa1
--- /dev/null
+++ b/frontend/src/providers/Dashboard/__tests__/normalizeUrlValue.test.ts
@@ -0,0 +1,142 @@
+import { IDashboardVariable } from 'types/api/dashboard/getAll';
+
+import { normalizeUrlValueForVariable } from '../normalizeUrlValue';
+
+// Mock variable configurations
+const singleSelectVariable: Partial<IDashboardVariable> = {
+ id: 'env',
+ name: 'environment',
+ multiSelect: false,
+};
+
+const multiSelectVariable: Partial<IDashboardVariable> = {
+ id: 'services',
+ name: 'service_names',
+ multiSelect: true,
+};
+
+describe('normalizeUrlValueForVariable', () => {
+ describe('Single select variable', () => {
+ test('should keep single string value as is', () => {
+ const result = normalizeUrlValueForVariable(
+ 'production',
+ singleSelectVariable as IDashboardVariable,
+ );
+ expect(result).toBe('production');
+ });
+
+ test('should keep single number value as is', () => {
+ const result = normalizeUrlValueForVariable(
+ 123,
+ singleSelectVariable as IDashboardVariable,
+ );
+ expect(result).toBe(123);
+ });
+
+ test('should take first element from array', () => {
+ const result = normalizeUrlValueForVariable(
+ ['production', 'staging'],
+ singleSelectVariable as IDashboardVariable,
+ );
+ expect(result).toBe('production');
+ });
+
+ test('should return null for empty array', () => {
+ const result = normalizeUrlValueForVariable(
+ [],
+ singleSelectVariable as IDashboardVariable,
+ );
+ expect(result).toBeNull();
+ });
+
+ test('should handle null/undefined values', () => {
+ expect(
+ normalizeUrlValueForVariable(
+ null,
+ singleSelectVariable as IDashboardVariable,
+ ),
+ ).toBeNull();
+ expect(
+ normalizeUrlValueForVariable(
+ undefined,
+ singleSelectVariable as IDashboardVariable,
+ ),
+ ).toBeUndefined();
+ });
+ });
+
+ describe('Multi select variable', () => {
+ test('should convert string to array', () => {
+ const result = normalizeUrlValueForVariable(
+ 'production',
+ multiSelectVariable as IDashboardVariable,
+ );
+ expect(result).toEqual(['production']);
+ });
+
+ test('should convert number to array', () => {
+ const result = normalizeUrlValueForVariable(
+ 123,
+ multiSelectVariable as IDashboardVariable,
+ );
+ expect(result).toEqual([123]);
+ });
+
+ test('should keep array as is', () => {
+ const result = normalizeUrlValueForVariable(
+ ['production', 'staging'],
+ multiSelectVariable as IDashboardVariable,
+ );
+ expect(result).toEqual(['production', 'staging']);
+ });
+
+ test('should keep empty array as is', () => {
+ const result = normalizeUrlValueForVariable(
+ [],
+ multiSelectVariable as IDashboardVariable,
+ );
+ expect(result).toEqual([]);
+ });
+
+ test('should handle null/undefined values', () => {
+ expect(
+ normalizeUrlValueForVariable(
+ null,
+ multiSelectVariable as IDashboardVariable,
+ ),
+ ).toBeNull();
+ expect(
+ normalizeUrlValueForVariable(
+ undefined,
+ multiSelectVariable as IDashboardVariable,
+ ),
+ ).toBeUndefined();
+ });
+ });
+
+ describe('Real world scenarios', () => {
+ test('URL has array ["test", "prod"] for single select variable -> should take "test"', () => {
+ const result = normalizeUrlValueForVariable(
+ ['test', 'prod'],
+ singleSelectVariable as IDashboardVariable,
+ );
+ expect(result).toBe('test');
+ });
+
+ test('URL has string "test" for multi select variable -> should convert to ["test"]', () => {
+ const result = normalizeUrlValueForVariable(
+ 'test',
+ multiSelectVariable as IDashboardVariable,
+ );
+ expect(result).toEqual(['test']);
+ });
+
+ test('Handles mixed types in array for single select', () => {
+ const result = normalizeUrlValueForVariable(
+ ['test', 123, true],
+ singleSelectVariable as IDashboardVariable,
+ );
+ expect(result).toBe('test');
+ });
+ });
+});
diff --git a/frontend/src/providers/Dashboard/initializeDefaultVariables.ts b/frontend/src/providers/Dashboard/initializeDefaultVariables.ts
new file mode 100644
index 0000000000..299e1078ad
--- /dev/null
+++ b/frontend/src/providers/Dashboard/initializeDefaultVariables.ts
@@ -0,0 +1,48 @@
+import { ALL_SELECTED_VALUE } from 'components/NewSelect/utils';
+import { IDashboardVariable } from 'types/api/dashboard/getAll';
+
+import { commaValuesParser } from '../../lib/dashbaordVariables/customCommaValuesParser';
+
+interface UrlVariables {
+ [key: string]: any;
+}
+
+/**
+ * Initializes default values for dashboard variables if not already in URL
+ * Handles cases where variables might be keyed by either id or name
+ *
+ * @param variables Dashboard variables object
+ * @param getUrlVariables Function to get variables from URL
+ * @param updateUrlVariable Function to update URL with variable values
+ */
+export const initializeDefaultVariables = (
+ variables: Record<string, IDashboardVariable>,
+ getUrlVariables: () => UrlVariables | undefined,
+ updateUrlVariable: (
+ name: string,
+ selectedValue: IDashboardVariable['selectedValue'],
+ ) => void,
+): void => {
+ if (!variables) return;
+
+ Object.values(variables).forEach((variable) => {
+ const { id, name, allSelected, showALLOption } = variable;
+ const urlVariables = getUrlVariables();
+
+ // Check if either id or name is available in URL variables
+ const existsInUrl =
+ (id && urlVariables?.[id]) || (name && urlVariables?.[name]);
+
+ const value =
+ variable.type === 'CUSTOM'
+ ? commaValuesParser(variable?.customValue || '')
+ : variable?.selectedValue ?? variable?.defaultValue;
+
+ if (!existsInUrl) {
+ updateUrlVariable(
+ name || id,
+ allSelected && showALLOption ? ALL_SELECTED_VALUE : value,
+ );
+ }
+ });
+};
diff --git a/frontend/src/providers/Dashboard/normalizeUrlValue.ts b/frontend/src/providers/Dashboard/normalizeUrlValue.ts
new file mode 100644
index 0000000000..21b0d46204
--- /dev/null
+++ b/frontend/src/providers/Dashboard/normalizeUrlValue.ts
@@ -0,0 +1,46 @@
+import { IDashboardVariable } from 'types/api/dashboard/getAll';
+
+// Type representing a single URL variable value (from LocalStoreDashboardVariables)
+type UrlVariableValue =
+ | IDashboardVariable['selectedValue'][]
+ | IDashboardVariable['selectedValue'];
+
+/**
+ * Normalizes URL values to match the variable's multiSelect configuration
+ *
+ * Rules:
+ * - If variable is single-select and URL value is array: take first element
+ * - If variable is multi-select and URL value is string/number: convert to array
+ * - If variable is multi-select and URL value is array: keep as array
+ * - If variable is single-select and URL value is string/number: keep as is
+ *
+ * @param urlValue The raw value from URL
+ * @param variable The variable configuration
+ * @returns Normalized value that matches the variable's multiSelect setting
+ */
+export const normalizeUrlValueForVariable = (
+ urlValue: UrlVariableValue,
+ variable: IDashboardVariable,
+): IDashboardVariable['selectedValue'] => {
+ if (urlValue === undefined || urlValue === null) {
+ return urlValue;
+ }
+
+ const isMultiSelect = variable.multiSelect;
+ const isUrlValueArray = Array.isArray(urlValue);
+
+ if (isMultiSelect) {
+ // Variable expects array, ensure we return array
+ if (isUrlValueArray) {
+ return urlValue as IDashboardVariable['selectedValue'];
+ }
+ return [urlValue] as IDashboardVariable['selectedValue']; // Convert single value to array
+ }
+ // Variable expects single value
+ if (isUrlValueArray) {
+ // URL has array but variable is single-select, take first element
+ const arrayValue = urlValue;
+ return arrayValue.length > 0 ? arrayValue[0] : null;
+ }
+ return urlValue as IDashboardVariable['selectedValue']; // Already single value, keep as is
+};