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.

chore: use variable select strategy + (#10245)

Ashwin Bhatkal72b0f2749458
diff --git a/frontend/src/components/NewSelect/CustomMultiSelect.tsx b/frontend/src/components/NewSelect/CustomMultiSelect.tsx
index 8e19a2c5c1..877cccc9e3 100644
--- a/frontend/src/components/NewSelect/CustomMultiSelect.tsx
+++ b/frontend/src/components/NewSelect/CustomMultiSelect.tsx
@@ -140,10 +140,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
}, [selectedValues, allAvailableValues, enableAllSelection]);
// Define allOptionShown earlier in the code
- const allOptionShown = useMemo(
- () => value === ALL_SELECTED_VALUE || value === 'ALL',
- [value],
- );
+ const allOptionShown = value === ALL_SELECTED_VALUE;
// Value passed to the underlying Ant Select component
const displayValue = useMemo(
diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/CustomVariableInput.tsx b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/CustomVariableInput.tsx
index 4ae5bb0b81..4233d8fe6b 100644
--- a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/CustomVariableInput.tsx
+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/CustomVariableInput.tsx
@@ -1,10 +1,11 @@
-import { memo, useMemo } from 'react';
+import { memo, useEffect, useMemo } from 'react';
import { commaValuesParser } from 'lib/dashboardVariables/customCommaValuesParser';
import sortValues from 'lib/dashboardVariables/sortVariableValues';
import SelectVariableInput from './SelectVariableInput';
import { useDashboardVariableSelectHelper } from './useDashboardVariableSelectHelper';
import { VariableItemProps } from './VariableItem';
+import { customVariableSelectStrategy } from './variableSelectStrategy/customVariableSelectStrategy';
type CustomVariableInputProps = Pick<
VariableItemProps,
@@ -29,16 +30,31 @@ function CustomVariableInput({
onChange,
onDropdownVisibleChange,
handleClear,
+ applyDefaultIfNeeded,
} = useDashboardVariableSelectHelper({
variableData,
optionsData,
onValueUpdate,
+ strategy: customVariableSelectStrategy,
});
+ // Apply default on mount — options are available synchronously for custom variables
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ useEffect(applyDefaultIfNeeded, []);
+
+ const selectOptions = useMemo(
+ () =>
+ optionsData.map((option) => ({
+ label: option.toString(),
+ value: option.toString(),
+ })),
+ [optionsData],
+ );
+
return (
<SelectVariableInput
variableId={variableData.id}
- options={optionsData}
+ options={selectOptions}
value={value}
onChange={onChange}
onDropdownVisibleChange={onDropdownVisibleChange}
diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/DashboardVariableSelection.tsx b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/DashboardVariableSelection.tsx
index 301568a471..5fe1868eeb 100644
--- a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/DashboardVariableSelection.tsx
+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/DashboardVariableSelection.tsx
@@ -13,7 +13,6 @@ import { AppState } from 'store/reducers';
import { IDashboardVariable } from 'types/api/dashboard/getAll';
import { GlobalReducer } from 'types/reducer/globalTime';
-import DynamicVariableSelection from './DynamicVariableSelection';
import { onUpdateVariableNode } from './util';
import VariableItem from './VariableItem';
@@ -153,14 +152,7 @@ function DashboardVariableSelection(): JSX.Element | null {
{sortedVariablesArray.map((variable) => {
const key = `${variable.name}${variable.id}${variable.order}`;
- return variable.type === 'DYNAMIC' ? (
- <DynamicVariableSelection
- key={key}
- existingVariables={dashboardVariables}
- variableData={variable}
- onValueUpdate={onValueUpdate}
- />
- ) : (
+ return (
<VariableItem
key={key}
existingVariables={dashboardVariables}
diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/DynamicVariableInput.tsx b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/DynamicVariableInput.tsx
new file mode 100644
index 0000000000..68a465a2be
--- /dev/null
+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/DynamicVariableInput.tsx
@@ -0,0 +1,343 @@
+import { memo, useCallback, useMemo, useState } from 'react';
+import { useQuery } from 'react-query';
+import { useSelector } from 'react-redux';
+import { getFieldValues } from 'api/dynamicVariables/getFieldValues';
+import { SOMETHING_WENT_WRONG } from 'constants/api';
+import { DEBOUNCE_DELAY } from 'constants/queryBuilderFilterConfig';
+import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
+import useDebounce from 'hooks/useDebounce';
+import { isEmpty } from 'lodash-es';
+import { AppState } from 'store/reducers';
+import { GlobalReducer } from 'types/reducer/globalTime';
+import { isRetryableError as checkIfRetryableError } from 'utils/errorUtils';
+
+import SelectVariableInput from './SelectVariableInput';
+import { useDashboardVariableSelectHelper } from './useDashboardVariableSelectHelper';
+import { getOptionsForDynamicVariable } from './util';
+import { VariableItemProps } from './VariableItem';
+import { dynamicVariableSelectStrategy } from './variableSelectStrategy/dynamicVariableSelectStrategy';
+
+import './DashboardVariableSelection.styles.scss';
+
+type DynamicVariableInputProps = Pick<
+ VariableItemProps,
+ 'variableData' | 'onValueUpdate' | 'existingVariables'
+>;
+
+// eslint-disable-next-line sonarjs/cognitive-complexity
+function DynamicVariableInput({
+ variableData,
+ onValueUpdate,
+ existingVariables,
+}: DynamicVariableInputProps): JSX.Element {
+ const [optionsData, setOptionsData] = useState<(string | number | boolean)[]>(
+ [],
+ );
+
+ const [errorMessage, setErrorMessage] = useState<null | string>(null);
+ const [isRetryableError, setIsRetryableError] = useState<boolean>(true);
+
+ const [isComplete, setIsComplete] = useState<boolean>(false);
+
+ const [filteredOptionsData, setFilteredOptionsData] = useState<
+ (string | number | boolean)[]
+ >([]);
+
+ const [relatedValues, setRelatedValues] = useState<string[]>([]);
+ const [originalRelatedValues, setOriginalRelatedValues] = useState<string[]>(
+ [],
+ );
+
+ // Track dropdown open state for auto-checking new values
+ const [isDropdownOpen, setIsDropdownOpen] = useState<boolean>(false);
+
+ const [apiSearchText, setApiSearchText] = useState<string>('');
+
+ const debouncedApiSearchText = useDebounce(apiSearchText, DEBOUNCE_DELAY);
+
+ // Build a memoized list of all currently available option strings (normalized + related)
+ const allAvailableOptionStrings = useMemo(
+ () => [
+ ...new Set([
+ ...optionsData.map((v) => v.toString()),
+ ...relatedValues.map((v) => v.toString()),
+ ]),
+ ],
+ [optionsData, relatedValues],
+ );
+
+ const {
+ value,
+ tempSelection,
+ setTempSelection,
+ handleClear,
+ enableSelectAll,
+ defaultValue,
+ applyDefaultIfNeeded,
+ onChange,
+ onDropdownVisibleChange,
+ } = useDashboardVariableSelectHelper({
+ variableData,
+ optionsData,
+ onValueUpdate,
+ strategy: dynamicVariableSelectStrategy,
+ allAvailableOptionStrings,
+ });
+
+ // Create a dependency key from all dynamic variables
+ const dynamicVariablesKey = useMemo(() => {
+ if (!existingVariables) {
+ return 'no_variables';
+ }
+
+ const dynamicVars = Object.values(existingVariables)
+ .filter((v) => v.type === 'DYNAMIC')
+ .map(
+ (v) => `${v.name || 'unnamed'}:${JSON.stringify(v.selectedValue || null)}`,
+ )
+ .join('|');
+
+ return dynamicVars || 'no_dynamic_variables';
+ }, [existingVariables]);
+
+ const { maxTime, minTime } = useSelector<AppState, GlobalReducer>(
+ (state) => state.globalTime,
+ );
+
+ // existing query is the query made from the other dynamic variables around this one with there current values
+ // for e.g. k8s.namespace.name IN ["zeus", "gene"] AND doc_op_type IN ["test"]
+ // eslint-disable-next-line sonarjs/cognitive-complexity
+ const existingQuery = useMemo(() => {
+ if (!existingVariables || !variableData.dynamicVariablesAttribute) {
+ return '';
+ }
+
+ const queryParts: string[] = [];
+
+ Object.entries(existingVariables).forEach(([, variable]) => {
+ // Skip the current variable being processed
+ if (variable.id === variableData.id) {
+ return;
+ }
+
+ // Only include dynamic variables that have selected values and are not selected as ALL
+ if (
+ variable.type === 'DYNAMIC' &&
+ variable.dynamicVariablesAttribute &&
+ variable.selectedValue &&
+ !isEmpty(variable.selectedValue) &&
+ (variable.showALLOption ? !variable.allSelected : true)
+ ) {
+ const attribute = variable.dynamicVariablesAttribute;
+ const values = Array.isArray(variable.selectedValue)
+ ? variable.selectedValue
+ : [variable.selectedValue];
+
+ // Filter out empty values and convert to strings
+ const validValues = values
+ .filter((val) => val !== null && val !== undefined && val !== '')
+ .map((val) => val.toString());
+
+ if (validValues.length > 0) {
+ // Format values for query - wrap strings in quotes, keep numbers as is
+ const formattedValues = validValues.map((val) => {
+ // Check if value is a number
+ const numValue = Number(val);
+ if (!Number.isNaN(numValue) && Number.isFinite(numValue)) {
+ return val; // Keep as number
+ }
+ // Escape single quotes and wrap in quotes
+ return `'${val.replace(/'/g, "\\'")}'`;
+ });
+
+ if (formattedValues.length === 1) {
+ queryParts.push(`${attribute} = ${formattedValues[0]}`);
+ } else {
+ queryParts.push(`${attribute} IN [${formattedValues.join(', ')}]`);
+ }
+ }
+ }
+ });
+
+ return queryParts.join(' AND ');
+ }, [
+ existingVariables,
+ variableData.id,
+ variableData.dynamicVariablesAttribute,
+ ]);
+
+ // Wrap the hook's onDropdownVisibleChange to also track isDropdownOpen and handle cleanup
+ const handleSelectDropdownVisibilityChange = useCallback(
+ (visible: boolean): void => {
+ setIsDropdownOpen(visible);
+
+ onDropdownVisibleChange(visible);
+
+ if (!visible) {
+ setFilteredOptionsData(optionsData);
+ setRelatedValues(originalRelatedValues);
+ setApiSearchText('');
+ }
+ },
+ [onDropdownVisibleChange, optionsData, originalRelatedValues],
+ );
+
+ const { isLoading, refetch } = useQuery(
+ [
+ REACT_QUERY_KEY.DASHBOARD_BY_ID,
+ variableData.name || `variable_${variableData.id}`,
+ dynamicVariablesKey,
+ minTime,
+ maxTime,
+ debouncedApiSearchText,
+ variableData.dynamicVariablesSource,
+ variableData.dynamicVariablesAttribute,
+ ],
+ {
+ enabled:
+ variableData.type === 'DYNAMIC' &&
+ !!variableData.dynamicVariablesSource &&
+ !!variableData.dynamicVariablesAttribute,
+ queryFn: () =>
+ getFieldValues(
+ variableData.dynamicVariablesSource?.toLowerCase() === 'all telemetry'
+ ? undefined
+ : (variableData.dynamicVariablesSource?.toLowerCase() as
+ | 'traces'
+ | 'logs'
+ | 'metrics'),
+ variableData.dynamicVariablesAttribute,
+ debouncedApiSearchText,
+ minTime,
+ maxTime,
+ existingQuery,
+ ),
+ onSuccess: (data) => {
+ const newNormalizedValues = data.data?.normalizedValues || [];
+ const newRelatedValues = data.data?.relatedValues || [];
+
+ if (!debouncedApiSearchText) {
+ setOptionsData(newNormalizedValues);
+ setIsComplete(data.data?.complete || false);
+ }
+ setFilteredOptionsData(newNormalizedValues);
+ setRelatedValues(newRelatedValues);
+ setOriginalRelatedValues(newRelatedValues);
+
+ // Only run auto-check logic when necessary to avoid performance issues
+ if (variableData.allSelected && isDropdownOpen) {
+ // Build the latest full list from API (normalized + related)
+ const latestValues = [
+ ...new Set([
+ ...newNormalizedValues.map((v) => v.toString()),
+ ...newRelatedValues.map((v) => v.toString()),
+ ]),
+ ];
+
+ // Update temp selection to exactly reflect latest API values when ALL is active
+ const currentStrings = Array.isArray(tempSelection)
+ ? tempSelection.map((v) => v.toString())
+ : tempSelection
+ ? [tempSelection.toString()]
+ : [];
+ const areSame =
+ currentStrings.length === latestValues.length &&
+ latestValues.every((v) => currentStrings.includes(v));
+ if (!areSame) {
+ setTempSelection(latestValues);
+ }
+ }
+
+ // Apply default if no value is selected (e.g., new variable, first load)
+ if (!debouncedApiSearchText) {
+ const allNewOptions = [
+ ...new Set([
+ ...newNormalizedValues.map((v) => v.toString()),
+ ...newRelatedValues.map((v) => v.toString()),
+ ]),
+ ];
+ applyDefaultIfNeeded(allNewOptions);
+ }
+ },
+ onError: (error: any) => {
+ if (error) {
+ let message = SOMETHING_WENT_WRONG;
+ if (error?.message) {
+ message = error?.message;
+ } else {
+ message =
+ 'Please make sure configuration is valid and you have required setup and permissions';
+ }
+ setErrorMessage(message);
+
+ // Check if error is retryable (5xx) or not (4xx)
+ const isRetryable = checkIfRetryableError(error);
+ setIsRetryableError(isRetryable);
+ }
+ },
+ },
+ );
+
+ const handleRetry = useCallback((): void => {
+ setErrorMessage(null);
+ setIsRetryableError(true);
+ refetch();
+ }, [refetch]);
+
+ const handleSearch = useCallback(
+ (text: string) => {
+ if (isComplete) {
+ if (!text) {
+ setFilteredOptionsData(optionsData);
+ setRelatedValues(originalRelatedValues);
+ return;
+ }
+
+ const lowerText = text.toLowerCase();
+ setFilteredOptionsData(
+ optionsData.filter((option) =>
+ option.toString().toLowerCase().includes(lowerText),
+ ),
+ );
+ setRelatedValues(
+ originalRelatedValues.filter((val) =>
+ val.toLowerCase().includes(lowerText),
+ ),
+ );
+ } else {
+ setApiSearchText(text);
+ }
+ },
+ [isComplete, optionsData, originalRelatedValues],
+ );
+
+ const selectOptions = useMemo(
+ () =>
+ getOptionsForDynamicVariable(filteredOptionsData || [], relatedValues || []),
+ [filteredOptionsData, relatedValues],
+ );
+
+ return (
+ <SelectVariableInput
+ variableId={variableData.id}
+ options={selectOptions}
+ value={value}
+ onChange={onChange}
+ onDropdownVisibleChange={handleSelectDropdownVisibilityChange}
+ onClear={handleClear}
+ enableSelectAll={enableSelectAll}
+ defaultValue={defaultValue}
+ isMultiSelect={variableData.multiSelect}
+ // dynamic variable specific + API related props
+ loading={isLoading}
+ errorMessage={errorMessage}
+ onRetry={handleRetry}
+ isDynamicVariable
+ showRetryButton={isRetryableError}
+ showIncompleteDataMessage={!isComplete && filteredOptionsData.length > 0}
+ onSearch={handleSearch}
+ />
+ );
+}
+
+export default memo(DynamicVariableInput);
diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/DynamicVariableSelection.tsx b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/DynamicVariableSelection.tsx
deleted file mode 100644
index 1b67d18852..0000000000
--- a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/DynamicVariableSelection.tsx
+++ /dev/null
@@ -1,602 +0,0 @@
-/* eslint-disable sonarjs/cognitive-complexity */
-/* eslint-disable no-nested-ternary */
-import { useCallback, useEffect, useMemo, useState } from 'react';
-import { useQuery } from 'react-query';
-import { useSelector } from 'react-redux';
-import { InfoCircleOutlined } from '@ant-design/icons';
-import { Tooltip, Typography } from 'antd';
-import { getFieldValues } from 'api/dynamicVariables/getFieldValues';
-import { CustomMultiSelect, CustomSelect } from 'components/NewSelect';
-import { SOMETHING_WENT_WRONG } from 'constants/api';
-import { DEBOUNCE_DELAY } from 'constants/queryBuilderFilterConfig';
-import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
-import useDebounce from 'hooks/useDebounce';
-import { isEmpty, isUndefined } from 'lodash-es';
-import { AppState } from 'store/reducers';
-import { IDashboardVariable } from 'types/api/dashboard/getAll';
-import { GlobalReducer } from 'types/reducer/globalTime';
-import { isRetryableError as checkIfRetryableError } from 'utils/errorUtils';
-import { popupContainer } from 'utils/selectPopupContainer';
-
-import { ALL_SELECT_VALUE } from '../utils';
-import { SelectItemStyle } from './styles';
-import {
- areArraysEqual,
- getOptionsForDynamicVariable,
- getSelectValue,
- uniqueValues,
-} from './util';
-
-import './DashboardVariableSelection.styles.scss';
-
-interface DynamicVariableSelectionProps {
- variableData: IDashboardVariable;
- existingVariables: Record<string, IDashboardVariable>;
- onValueUpdate: (
- name: string,
- id: string,
- arg1: IDashboardVariable['selectedValue'],
- allSelected: boolean,
- haveCustomValuesSelected?: boolean,
- ) => void;
-}
-
-function DynamicVariableSelection({
- variableData,
- onValueUpdate,
- existingVariables,
-}: DynamicVariableSelectionProps): JSX.Element {
- const [optionsData, setOptionsData] = useState<(string | number | boolean)[]>(
- [],
- );
-
- const [errorMessage, setErrorMessage] = useState<null | string>(null);
- const [isRetryableError, setIsRetryableError] = useState<boolean>(true);
-
- const [isComplete, setIsComplete] = useState<boolean>(false);
-
- const [filteredOptionsData, setFilteredOptionsData] = useState<
- (string | number | boolean)[]
- >([]);
-
- const [relatedValues, setRelatedValues] = useState<string[]>([]);
- const [originalRelatedValues, setOriginalRelatedValues] = useState<string[]>(
- [],
- );
-
- const [tempSelection, setTempSelection] = useState<
- string | string[] | undefined
- >(undefined);
-
- // Track dropdown open state for auto-checking new values
- const [isDropdownOpen, setIsDropdownOpen] = useState<boolean>(false);
-
- // Create a dependency key from all dynamic variables
- const dynamicVariablesKey = useMemo(() => {
- if (!existingVariables) {
- return 'no_variables';
- }
-
- const dynamicVars = Object.values(existingVariables)
- .filter((v) => v.type === 'DYNAMIC')
- .map(
- (v) => `${v.name || 'unnamed'}:${JSON.stringify(v.selectedValue || null)}`,
- )
- .join('|');
-
- return dynamicVars || 'no_dynamic_variables';
- }, [existingVariables]);
-
- const [apiSearchText, setApiSearchText] = useState<string>('');
-
- const debouncedApiSearchText = useDebounce(apiSearchText, DEBOUNCE_DELAY);
-
- const { maxTime, minTime } = useSelector<AppState, GlobalReducer>(
- (state) => state.globalTime,
- );
-
- // existing query is the query made from the other dynamic variables around this one with there current values
- // for e.g. k8s.namespace.name IN ["zeus", "gene"] AND doc_op_type IN ["test"]
- const existingQuery = useMemo(() => {
- if (!existingVariables || !variableData.dynamicVariablesAttribute) {
- return '';
- }
-
- const queryParts: string[] = [];
-
- Object.entries(existingVariables).forEach(([, variable]) => {
- // Skip the current variable being processed
- if (variable.id === variableData.id) {
- return;
- }
-
- // Only include dynamic variables that have selected values and are not selected as ALL
- if (
- variable.type === 'DYNAMIC' &&
- variable.dynamicVariablesAttribute &&
- variable.selectedValue &&
- !isEmpty(variable.selectedValue) &&
- (variable.showALLOption ? !variable.allSelected : true)
- ) {
- const attribute = variable.dynamicVariablesAttribute;
- const values = Array.isArray(variable.selectedValue)
- ? variable.selectedValue
- : [variable.selectedValue];
-
- // Filter out empty values and convert to strings
- const validValues = values
- .filter((value) => value !== null && value !== undefined && value !== '')
- .map((value) => value.toString());
-
- if (validValues.length > 0) {
- // Format values for query - wrap strings in quotes, keep numbers as is
- const formattedValues = validValues.map((value) => {
- // Check if value is a number
- const numValue = Number(value);
- if (!Number.isNaN(numValue) && Number.isFinite(numValue)) {
- return value; // Keep as number
- }
- // Escape single quotes and wrap in quotes
- return `'${value.replace(/'/g, "\\'")}'`;
- });
-
- if (formattedValues.length === 1) {
- queryParts.push(`${attribute} = ${formattedValues[0]}`);
- } else {
- queryParts.push(`${attribute} IN [${formattedValues.join(', ')}]`);
- }
- }
- }
- });
-
- return queryParts.join(' AND ');
- }, [
- existingVariables,
- variableData.id,
- variableData.dynamicVariablesAttribute,
- ]);
-
- const { isLoading, refetch } = useQuery(
- [
- REACT_QUERY_KEY.DASHBOARD_BY_ID,
- variableData.name || `variable_${variableData.id}`,
- dynamicVariablesKey,
- minTime,
- maxTime,
- debouncedApiSearchText,
- ],
- {
- enabled: variableData.type === 'DYNAMIC',
- queryFn: () =>
- getFieldValues(
- variableData.dynamicVariablesSource?.toLowerCase() === 'all telemetry'
- ? undefined
- : (variableData.dynamicVariablesSource?.toLowerCase() as
- | 'traces'
- | 'logs'
- | 'metrics'),
- variableData.dynamicVariablesAttribute,
- debouncedApiSearchText,
- minTime,
- maxTime,
- existingQuery,
- ),
- onSuccess: (data) => {
- const newNormalizedValues = data.data?.normalizedValues || [];
- const newRelatedValues = data.data?.relatedValues || [];
-
- if (!debouncedApiSearchText) {
- setOptionsData(newNormalizedValues);
- setIsComplete(data.data?.complete || false);
- }
- setFilteredOptionsData(newNormalizedValues);
- setRelatedValues(newRelatedValues);
- setOriginalRelatedValues(newRelatedValues);
-
- // Only run auto-check logic when necessary to avoid performance issues
- if (variableData.allSelected && isDropdownOpen) {
- // Build the latest full list from API (normalized + related)
- const latestValues = [
- ...new Set([
- ...newNormalizedValues.map((v) => v.toString()),
- ...newRelatedValues.map((v) => v.toString()),
- ]),
- ];
-
- // Update temp selection to exactly reflect latest API values when ALL is active
- const currentStrings = Array.isArray(tempSelection)
- ? tempSelection.map((v) => v.toString())
- : tempSelection
- ? [tempSelection.toString()]
- : [];
- const areSame =
- currentStrings.length === latestValues.length &&
- latestValues.every((v) => currentStrings.includes(v));
- if (!areSame) {
- setTempSelection(latestValues);
- }
- }
- },
- onError: (error: any) => {
- if (error) {
- let message = SOMETHING_WENT_WRONG;
- if (error?.message) {
- message = error?.message;
- } else {
- message =
- 'Please make sure configuration is valid and you have required setup and permissions';
- }
- setErrorMessage(message);
-
- // Check if error is retryable (5xx) or not (4xx)
- const isRetryable = checkIfRetryableError(error);
- setIsRetryableError(isRetryable);
- }
- },
- },
- );
-
- const handleChange = useCallback(
- (inputValue: string | string[]): void => {
- const value = variableData.multiSelect && !inputValue ? [] : inputValue;
-
- if (
- value === variableData.selectedValue ||
- (Array.isArray(value) &&
- Array.isArray(variableData.selectedValue) &&
- areArraysEqual(value, variableData.selectedValue))
- ) {
- return;
- }
-
- if (variableData.name) {
- if (
- value === ALL_SELECT_VALUE ||
- (Array.isArray(value) && value.includes(ALL_SELECT_VALUE))
- ) {
- // For ALL selection in dynamic variables, pass null to avoid storing values
- // The parent component will handle this appropriately
- onValueUpdate(variableData.name, variableData.id, null, true);
- } else {
- // Build union of available options shown in dropdown (normalized + related)
- const allAvailableOptionStrings = [
- ...new Set([
- ...optionsData.map((v) => v.toString()),
- ...relatedValues.map((v) => v.toString()),
- ]),
- ];
-
- const haveCustomValuesSelected =
- Array.isArray(value) &&
- !value.every((v) => allAvailableOptionStrings.includes(v.toString()));
-
- onValueUpdate(
- variableData.name,
- variableData.id,
- value,
- allAvailableOptionStrings.every((v) => value.includes(v.toString())),
- haveCustomValuesSelected,
- );
- }
- }
- },
- [variableData, onValueUpdate, optionsData, relatedValues],
- );
-
- useEffect(() => {
- if (
- variableData.dynamicVariablesSource &&
- variableData.dynamicVariablesAttribute
- ) {
- refetch();
- }
- }, [
- refetch,
- variableData.dynamicVariablesSource,
- variableData.dynamicVariablesAttribute,
- debouncedApiSearchText,
- ]);
-
- // Build a memoized list of all currently available option strings (normalized + related)
- const allAvailableOptionStrings = useMemo(
- () => [
- ...new Set([
- ...optionsData.map((v) => v.toString()),
- ...relatedValues.map((v) => v.toString()),
- ]),
- ],
- [optionsData, relatedValues],
- );
-
- const handleSearch = useCallback(
- (text: string) => {
- if (isComplete) {
- if (!text) {
- setFilteredOptionsData(optionsData);
- setRelatedValues(originalRelatedValues);
- return;
- }
-
- const localFilteredOptionsData: (string | number | boolean)[] = [];
- optionsData.forEach((option) => {
- if (option.toString().toLowerCase().includes(text.toLowerCase())) {
- localFilteredOptionsData.push(option);
- }
- });
- setFilteredOptionsData(localFilteredOptionsData);
- setRelatedValues(
- originalRelatedValues.filter((value) =>
- value.toLowerCase().includes(text.toLowerCase()),
- ),
- );
- } else {
- setApiSearchText(text);
- }
- },
- [isComplete, optionsData, originalRelatedValues],
- );
-
- const { selectedValue } = variableData;
- const selectedValueStringified = useMemo(
- () => getSelectValue(selectedValue, variableData),
- [selectedValue, variableData],
- );
-
- const enableSelectAll = variableData.multiSelect && variableData.showALLOption;
-
- const selectValue =
- variableData.allSelected && enableSelectAll
- ? ALL_SELECT_VALUE
- : selectedValueStringified;
-
- // Add a handler for tracking temporary selection changes
- const handleTempChange = useCallback(
- (inputValue: string | string[]): void => {
- // Store the selection in temporary state while dropdown is open
- const value = variableData.multiSelect && !inputValue ? [] : inputValue;
- const sanitizedValue = uniqueValues(value);
- setTempSelection(sanitizedValue);
- },
- [variableData.multiSelect],
- );
-
- // Handle dropdown visibility changes
- const handleDropdownVisibleChange = (visible: boolean): void => {
- // Update dropdown open state for auto-checking
- setIsDropdownOpen(visible);
-
- // Initialize temp selection when opening dropdown
- if (visible) {
- if (isUndefined(tempSelection) && selectValue === ALL_SELECT_VALUE) {
- // When ALL is selected, set selection to exactly the latest available values
- const latestAll = [...allAvailableOptionStrings];
- setTempSelection(latestAll);
- } else {
- setTempSelection(getSelectValue(variableData.selectedValue, variableData));
- }
- }
- // Apply changes when closing dropdown
- else if (!visible && tempSelection !== undefined) {
- // Only call handleChange if there's actually a change in the selection
- const currentValue = variableData.selectedValue;
-
- // Helper function to check if arrays have the same elements regardless of order
- const areArraysEqualIgnoreOrder = (a: any[], b: any[]): boolean => {
- if (a.length !== b.length) {
- return false;
- }
- const sortedA = [...a].sort();
- const sortedB = [...b].sort();
- return areArraysEqual(sortedA, sortedB);
- };
-
- // If ALL was selected before and remains ALL after, skip updating
- const wasAllSelected = enableSelectAll && variableData.allSelected;
- const isAllSelectedAfter =
- enableSelectAll &&
- Array.isArray(tempSelection) &&
- tempSelection.length === allAvailableOptionStrings.length &&
- allAvailableOptionStrings.every((v) => tempSelection.includes(v));
-
- if (wasAllSelected && isAllSelectedAfter) {
- setTempSelection(undefined);
- return;
- }
-
- const hasChanged =
- tempSelection !== currentValue &&
- !(
- Array.isArray(tempSelection) &&
- Array.isArray(currentValue) &&
- areArraysEqualIgnoreOrder(tempSelection, currentValue)
- );
-
- if (hasChanged) {
- handleChange(tempSelection);
- }
- setTempSelection(undefined);
- }
-
- // Always reset filtered data when dropdown closes, regardless of tempSelection state
- if (!visible) {
- setFilteredOptionsData(optionsData);
- setRelatedValues(originalRelatedValues);
- setApiSearchText('');
- }
- };
-
- useEffect(
- () => (): void => {
- // Cleanup on unmount
- setTempSelection(undefined);
- setFilteredOptionsData([]);
- setRelatedValues([]);
- setApiSearchText('');
- },
- [],
- );
-
- // eslint-disable-next-line sonarjs/cognitive-complexity
- const finalSelectedValues = useMemo(() => {
- if (variableData.multiSelect) {
- let value = tempSelection || selectedValue;
- if (isEmpty(value)) {
- if (variableData.showALLOption) {
- if (variableData.defaultValue) {
- value = variableData.defaultValue;
- } else if (variableData.allSelected) {
- // If ALL is selected but no stored values, derive from available options
- // This handles the case where we don't store values in localStorage for ALL
- value = allAvailableOptionStrings;
- } else {
- value = optionsData;
- }
- } else if (variableData.defaultValue) {
- value = variableData.defaultValue;
- } else {
- value = optionsData?.[0];
- }
- }
-
- return value;
- }
- if (isEmpty(selectedValue)) {
- if (variableData.defaultValue) {
- return variableData.defaultValue;
- }
- return optionsData[0]?.toString();
- }
-
- return selectedValue;
- }, [
- variableData.multiSelect,
- variableData.showALLOption,
- variableData.defaultValue,
- variableData.allSelected,
- selectedValue,
- tempSelection,
- optionsData,
- allAvailableOptionStrings,
- ]);
-
- useEffect(() => {
- if (
- (variableData.multiSelect && !(tempSelection || selectValue)) ||
- isEmpty(selectValue)
- ) {
- handleChange(finalSelectedValues as string[] | string);
- }
- }, [
- finalSelectedValues,
- handleChange,
- selectValue,
- tempSelection,
- variableData.multiSelect,
- ]);
-
- return (
- <div className="variable-item">
- <Typography.Text className="variable-name" ellipsis>
- ${variableData.name}
- {variableData.description && (
- <Tooltip title={variableData.description}>
- <InfoCircleOutlined className="info-icon" />
- </Tooltip>
- )}
- </Typography.Text>
- <div className="variable-value">
- {variableData.multiSelect ? (
- <CustomMultiSelect
- key={variableData.id}
- options={getOptionsForDynamicVariable(
- filteredOptionsData || [],
- relatedValues || [],
- )}
- defaultValue={variableData.defaultValue}
- onChange={handleTempChange}
- bordered={false}
- placeholder="Select value"
- placement="bottomLeft"
- style={SelectItemStyle}
- loading={isLoading}
- showSearch
- data-testid="variable-select"
- className="variable-select"
- popupClassName="dropdown-styles"
- maxTagCount={2}
- getPopupContainer={popupContainer}
- value={
- (tempSelection || selectValue) === ALL_SELECT_VALUE
- ? 'ALL'
- : tempSelection || selectValue
- }
- onDropdownVisibleChange={handleDropdownVisibleChange}
- errorMessage={errorMessage}
- // eslint-disable-next-line react/no-unstable-nested-components
- maxTagPlaceholder={(omittedValues): JSX.Element => {
- const maxDisplayValues = 10;
- const valuesToShow = omittedValues.slice(0, maxDisplayValues);
- const hasMore = omittedValues.length > maxDisplayValues;
- const tooltipText =
- valuesToShow.map(({ value }) => value).join(', ') +
- (hasMore ? ` + ${omittedValues.length - maxDisplayValues} more` : '');
-
- return (
- <Tooltip title={tooltipText}>
- <span>+ {omittedValues.length} </span>
- </Tooltip>
- );
- }}
- onClear={(): void => {
- handleChange([]);
- }}
- enableAllSelection={enableSelectAll}
- maxTagTextLength={30}
- onSearch={handleSearch}
- onRetry={(): void => {
- setErrorMessage(null);
- setIsRetryableError(true);
- refetch();
- }}
- showIncompleteDataMessage={!isComplete && filteredOptionsData.length > 0}
- isDynamicVariable
- showRetryButton={isRetryableError}
- />
- ) : (
- <CustomSelect
- key={variableData.id}
- onChange={handleChange}
- bordered={false}
- placeholder="Select value"
- style={SelectItemStyle}
- loading={isLoading}
- showSearch
- data-testid="variable-select"
- className="variable-select"
- popupClassName="dropdown-styles"
- getPopupContainer={popupContainer}
- options={getOptionsForDynamicVariable(
- filteredOptionsData || [],
- relatedValues || [],
- )}
- value={selectValue}
- defaultValue={variableData.defaultValue}
- errorMessage={errorMessage}
- onSearch={handleSearch}
- // eslint-disable-next-line sonarjs/no-identical-functions
- onRetry={(): void => {
- setErrorMessage(null);
- setIsRetryableError(true);
- refetch();
- }}
- showIncompleteDataMessage={!isComplete && filteredOptionsData.length > 0}
- isDynamicVariable
- showRetryButton={isRetryableError}
- />
- )}
- </div>
- </div>
- );
-}
-
-export default DynamicVariableSelection;
diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/QueryVariableInput.tsx b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/QueryVariableInput.tsx
index cd9c8ed7af..82943e529f 100644
--- a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/QueryVariableInput.tsx
+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/QueryVariableInput.tsx
@@ -1,13 +1,11 @@
-import { memo, useCallback, useState } from 'react';
+import { memo, useCallback, useMemo, useState } from 'react';
import { useQuery } from 'react-query';
import { useSelector } from 'react-redux';
import dashboardVariablesQuery from 'api/dashboard/variables/dashboardVariablesQuery';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import sortValues from 'lib/dashboardVariables/sortVariableValues';
import { isArray, isString } from 'lodash-es';
-import { IDependencyData } from 'providers/Dashboard/store/dashboardVariables/dashboardVariablesStoreTypes';
import { AppState } from 'store/reducers';
-import { IDashboardVariable } from 'types/api/dashboard/getAll';
import { VariableResponseProps } from 'types/api/dashboard/variables/query';
import { GlobalReducer } from 'types/reducer/globalTime';
@@ -15,20 +13,18 @@ import { variablePropsToPayloadVariables } from '../utils';
import SelectVariableInput from './SelectVariableInput';
import { useDashboardVariableSelectHelper } from './useDashboardVariableSelectHelper';
import { areArraysEqual, checkAPIInvocation } from './util';
-
-interface QueryVariableInputProps {
- variableData: IDashboardVariable;
- existingVariables: Record<string, IDashboardVariable>;
- onValueUpdate: (
- name: string,
- id: string,
- value: IDashboardVariable['selectedValue'],
- allSelected: boolean,
- ) => void;
- variablesToGetUpdated: string[];
- setVariablesToGetUpdated: React.Dispatch<React.SetStateAction<string[]>>;
- dependencyData: IDependencyData | null;
-}
+import { VariableItemProps } from './VariableItem';
+import { queryVariableSelectStrategy } from './variableSelectStrategy/queryVariableSelectStrategy';
+
+type QueryVariableInputProps = Pick<
+ VariableItemProps,
+ | 'variableData'
+ | 'existingVariables'
+ | 'onValueUpdate'
+ | 'variablesToGetUpdated'
+ | 'setVariablesToGetUpdated'
+ | 'dependencyData'
+>;
function QueryVariableInput({
variableData,
@@ -56,13 +52,15 @@ function QueryVariableInput({
onChange,
onDropdownVisibleChange,
handleClear,
+ applyDefaultIfNeeded,
} = useDashboardVariableSelectHelper({
variableData,
optionsData,
onValueUpdate,
+ strategy: queryVariableSelectStrategy,
});
- const validVariableUpdate = (): boolean => {
+ const validVariableUpdate = useCallback((): boolean => {
if (!variableData.name) {
return false;
}
@@ -70,86 +68,100 @@ function QueryVariableInput({
variablesToGetUpdated.length &&
variablesToGetUpdated[0] === variableData.name,
);
- };
-
- // eslint-disable-next-line sonarjs/cognitive-complexity
- const getOptions = (variablesRes: VariableResponseProps | null): void => {
- try {
- setErrorMessage(null);
-
- if (
- variablesRes?.variableValues &&
- Array.isArray(variablesRes?.variableValues)
- ) {
- const newOptionsData = sortValues(
- variablesRes?.variableValues,
- variableData.sort,
- );
+ }, [variableData.name, variablesToGetUpdated]);
+
+ const getOptions = useCallback(
+ // eslint-disable-next-line sonarjs/cognitive-complexity
+ (variablesRes: VariableResponseProps | null): void => {
+ try {
+ setErrorMessage(null);
+
+ if (
+ variablesRes?.variableValues &&
+ Array.isArray(variablesRes?.variableValues)
+ ) {
+ const newOptionsData = sortValues(
+ variablesRes?.variableValues,
+ variableData.sort,
+ );
- const oldOptionsData = sortValues(optionsData, variableData.sort) as never;
+ const oldOptionsData = sortValues(optionsData, variableData.sort) as never;
- if (!areArraysEqual(newOptionsData, oldOptionsData)) {
- let valueNotInList = false;
+ if (!areArraysEqual(newOptionsData, oldOptionsData)) {
+ let valueNotInList = false;
- if (isArray(variableData.selectedValue)) {
- variableData.selectedValue.forEach((val) => {
- if (!newOptionsData.includes(val)) {
- valueNotInList = true;
- }
- });
- } else if (
- isString(variableData.selectedValue) &&
- !newOptionsData.includes(variableData.selectedValue)
- ) {
- valueNotInList = true;
- }
+ if (isArray(variableData.selectedValue)) {
+ variableData.selectedValue.forEach((val) => {
+ if (!newOptionsData.includes(val)) {
+ valueNotInList = true;
+ }
+ });
+ } else if (
+ isString(variableData.selectedValue) &&
+ !newOptionsData.includes(variableData.selectedValue)
+ ) {
+ valueNotInList = true;
+ }
- // variablesData.allSelected is added for the case where on change of options we need to update the
- // local storage
- if (
- variableData.name &&
- (validVariableUpdate() || valueNotInList || variableData.allSelected)
- ) {
+ // variablesData.allSelected is added for the case where on change of options we need to update the
+ // local storage
if (
- variableData.allSelected &&
- variableData.multiSelect &&
- variableData.showALLOption
+ variableData.name &&
+ (validVariableUpdate() || valueNotInList || variableData.allSelected)
) {
- onValueUpdate(variableData.name, variableData.id, newOptionsData, true);
-
- // Update tempSelection to maintain ALL state when dropdown is open
- if (tempSelection !== undefined) {
- setTempSelection(newOptionsData.map((option) => option.toString()));
- }
- } else {
- const value = variableData.selectedValue;
- let allSelected = false;
-
- if (variableData.multiSelect) {
- const { selectedValue } = variableData;
- allSelected =
- newOptionsData.length > 0 &&
- Array.isArray(selectedValue) &&
- newOptionsData.every((option) => selectedValue.includes(option));
- }
-
- if (variableData.name && variableData.id) {
- onValueUpdate(variableData.name, variableData.id, value, allSelected);
+ if (
+ variableData.allSelected &&
+ variableData.multiSelect &&
+ variableData.showALLOption
+ ) {
+ onValueUpdate(variableData.name, variableData.id, newOptionsData, true);
+
+ // Update tempSelection to maintain ALL state when dropdown is open
+ if (tempSelection !== undefined) {
+ setTempSelection(newOptionsData.map((option) => option.toString()));
+ }
+ } else {
+ const value = variableData.selectedValue;
+ let allSelected = false;
+
+ if (variableData.multiSelect) {
+ const { selectedValue } = variableData;
+ allSelected =
+ newOptionsData.length > 0 &&
+ Array.isArray(selectedValue) &&
+ newOptionsData.every((option) => selectedValue.includes(option));
+ }
+
+ if (variableData.name && variableData.id) {
+ onValueUpdate(variableData.name, variableData.id, value, allSelected);
+ }
}
}
- }
- setOptionsData(newOptionsData);
- } else {
- setVariablesToGetUpdated((prev) =>
- prev.filter((name) => name !== variableData.name),
- );
+ setOptionsData(newOptionsData);
+ // Apply default if no value is selected (e.g., new variable, first load)
+ applyDefaultIfNeeded(newOptionsData);
+ } else {
+ setVariablesToGetUpdated((prev) =>
+ prev.filter((name) => name !== variableData.name),
+ );
+ }
}
+ } catch (e) {
+ console.error(e);
}
- } catch (e) {
- console.error(e);
- }
- };
+ },
+ [
+ variableData,
+ optionsData,
+ onValueUpdate,
+ tempSelection,
+ setTempSelection,
+ validVariableUpdate,
+ setVariablesToGetUpdated,
+ applyDefaultIfNeeded,
+ ],
+ );
const { isLoading, refetch } = useQuery(
[
@@ -162,7 +174,6 @@ function QueryVariableInput({
{
enabled:
variableData &&
- variableData.type === 'QUERY' &&
checkAPIInvocation(
variablesToGetUpdated,
variableData,
@@ -207,10 +218,19 @@ function QueryVariableInput({
refetch();
}, [refetch]);
+ const selectOptions = useMemo(
+ () =>
+ optionsData.map((option) => ({
+ label: option.toString(),
+ value: option.toString(),
+ })),
+ [optionsData],
+ );
+
return (
<SelectVariableInput
variableId={variableData.id}
- options={optionsData}
+ options={selectOptions}
value={value}
onChange={onChange}
onDropdownVisibleChange={onDropdownVisibleChange}
diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/SelectVariableInput.tsx b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/SelectVariableInput.tsx
index 73ab2d9d6a..3d6249e96c 100644
--- a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/SelectVariableInput.tsx
+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/SelectVariableInput.tsx
@@ -3,6 +3,7 @@ import { orange } from '@ant-design/colors';
import { WarningOutlined } from '@ant-design/icons';
import { Popover, Tooltip, Typography } from 'antd';
import { CustomMultiSelect, CustomSelect } from 'components/NewSelect';
+import { OptionData } from 'components/NewSelect/types';
import { popupContainer } from 'utils/selectPopupContainer';
import { ALL_SELECT_VALUE } from '../utils';
@@ -12,7 +13,7 @@ const errorIconStyle = { margin: '0 0.5rem' };
interface SelectVariableInputProps {
variableId: string;
- options: (string | number | boolean)[];
+ options: OptionData[];
value: string | string[] | undefined;
enableSelectAll: boolean;
isMultiSelect: boolean;
@@ -23,13 +24,17 @@ interface SelectVariableInputProps {
loading?: boolean;
errorMessage?: string | null;
onRetry?: () => void;
+ isDynamicVariable?: boolean;
+ showRetryButton?: boolean;
+ showIncompleteDataMessage?: boolean;
+ onSearch?: (searchTerm: string) => void;
}
const MAX_TAG_DISPLAY_VALUES = 10;
-function maxTagPlaceholder(
+export const renderMaxTagPlaceholder = (
omittedValues: { label?: React.ReactNode; value?: string | number }[],
-): JSX.Element {
+): JSX.Element => {
const valuesToShow = omittedValues.slice(0, MAX_TAG_DISPLAY_VALUES);
const hasMore = omittedValues.length > MAX_TAG_DISPLAY_VALUES;
const tooltipText =
@@ -41,7 +46,7 @@ function maxTagPlaceholder(
<span>+ {omittedValues.length} </span>
</Tooltip>
);
-}
+};
function SelectVariableInput({
variableId,
@@ -56,16 +61,11 @@ function SelectVariableInput({
enableSelectAll,
isMultiSelect,
defaultValue,
+ isDynamicVariable,
+ showRetryButton,
+ showIncompleteDataMessage,
+ onSearch,
}: SelectVariableInputProps): JSX.Element {
- const selectOptions = useMemo(
- () =>
- options.map((option) => ({
- label: option.toString(),
- value: option.toString(),
- })),
- [options],
- );
-
const commonProps = useMemo(
() => ({
// main props
@@ -82,23 +82,33 @@ function SelectVariableInput({
showSearch: true,
bordered: false,
- // dynamic props
+ // changing props
'data-testid': 'variable-select',
onChange,
loading,
- options: selectOptions,
+ options,
errorMessage,
onRetry,
+
+ // dynamic variable only props
+ isDynamicVariable,
+ showRetryButton,
+ showIncompleteDataMessage,
+ onSearch,
}),
[
variableId,
defaultValue,
onChange,
loading,
- selectOptions,
+ options,
value,
errorMessage,
onRetry,
+ isDynamicVariable,
+ showRetryButton,
+ showIncompleteDataMessage,
+ onSearch,
],
);
@@ -110,11 +120,11 @@ function SelectVariableInput({
placement="bottomLeft"
maxTagCount={2}
onDropdownVisibleChange={onDropdownVisibleChange}
- maxTagPlaceholder={maxTagPlaceholder}
+ maxTagPlaceholder={renderMaxTagPlaceholder}
onClear={onClear}
enableAllSelection={enableSelectAll}
maxTagTextLength={30}
- allowClear={value !== ALL_SELECT_VALUE && value !== 'ALL'}
+ allowClear={value !== ALL_SELECT_VALUE}
/>
) : (
<CustomSelect {...commonProps} />
diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/VariableItem.tsx b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/VariableItem.tsx
index 094ad3572f..50f535cddf 100644
--- a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/VariableItem.tsx
+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/VariableItem.tsx
@@ -5,6 +5,7 @@ import { IDependencyData } from 'providers/Dashboard/store/dashboardVariables/da
import { IDashboardVariable } from 'types/api/dashboard/getAll';
import CustomVariableInput from './CustomVariableInput';
+import DynamicVariableInput from './DynamicVariableInput';
import QueryVariableInput from './QueryVariableInput';
import TextboxVariableInput from './TextboxVariableInput';
@@ -16,8 +17,9 @@ export interface VariableItemProps {
onValueUpdate: (
name: string,
id: string,
- arg1: IDashboardVariable['selectedValue'],
+ value: IDashboardVariable['selectedValue'],
allSelected: boolean,
+ haveCustomValuesSelected?: boolean,
) => void;
variablesToGetUpdated: string[];
setVariablesToGetUpdated: React.Dispatch<React.SetStateAction<string[]>>;
@@ -68,6 +70,13 @@ function VariableItem({
dependencyData={dependencyData}
/>
)}
+ {variableType === 'DYNAMIC' && (
+ <DynamicVariableInput
+ variableData={variableData}
+ onValueUpdate={onValueUpdate}
+ existingVariables={existingVariables}
+ />
+ )}
</div>
</div>
);
diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/__test__/DynamicVariableSelection.test.tsx b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/__test__/DynamicVariableInput.test.tsx
similarity index 87%
rename from frontend/src/container/DashboardContainer/DashboardVariablesSelection/__test__/DynamicVariableSelection.test.tsx
rename to frontend/src/container/DashboardContainer/DashboardVariablesSelection/__test__/DynamicVariableInput.test.tsx
index 25fd95afc6..a56ec0381c 100644
--- a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/__test__/DynamicVariableSelection.test.tsx
+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/__test__/DynamicVariableInput.test.tsx
@@ -5,7 +5,7 @@ import * as ReactRedux from 'react-redux';
import { fireEvent, render, screen } from '@testing-library/react';
import { IDashboardVariable } from 'types/api/dashboard/getAll';
-import DynamicVariableSelection from '../DynamicVariableSelection';
+import DynamicVariableInput from '../DynamicVariableInput';
// Don't mock the components - use real ones
@@ -54,7 +54,7 @@ const mockApiResponse = {
// Mock scrollIntoView since it's not available in JSDOM
window.HTMLElement.prototype.scrollIntoView = jest.fn();
-describe('DynamicVariableSelection Component', () => {
+describe('DynamicVariableInput Component', () => {
const mockOnValueUpdate = jest.fn();
const mockDynamicVariableData: IDashboardVariable = {
@@ -108,18 +108,13 @@ describe('DynamicVariableSelection Component', () => {
it('renders with single select variable correctly', () => {
render(
- <DynamicVariableSelection
+ <DynamicVariableInput
variableData={mockDynamicVariableData}
existingVariables={mockExistingVariables}
onValueUpdate={mockOnValueUpdate}
/>,
);
- // Verify component renders correctly
- expect(
- screen.getByText(`$${mockDynamicVariableData.name}`),
- ).toBeInTheDocument();
-
// Verify the selected value is displayed
const selectedItem = screen.getByRole('combobox');
expect(selectedItem).toBeInTheDocument();
@@ -136,18 +131,13 @@ describe('DynamicVariableSelection Component', () => {
};
render(
- <DynamicVariableSelection
+ <DynamicVariableInput
variableData={multiSelectWithAllSelected}
existingVariables={mockExistingVariables}
onValueUpdate={mockOnValueUpdate}
/>,
);
- // Verify variable name is rendered
- expect(
- screen.getByText(`$${multiSelectWithAllSelected.name}`),
- ).toBeInTheDocument();
-
// In ALL selected mode, there should be an "ALL" text element
expect(screen.getByText('ALL')).toBeInTheDocument();
});
@@ -164,18 +154,13 @@ describe('DynamicVariableSelection Component', () => {
});
render(
- <DynamicVariableSelection
+ <DynamicVariableInput
variableData={mockDynamicVariableData}
existingVariables={mockExistingVariables}
onValueUpdate={mockOnValueUpdate}
/>,
);
- // Verify component renders in loading state
- expect(
- screen.getByText(`$${mockDynamicVariableData.name}`),
- ).toBeInTheDocument();
-
// Open dropdown to see loading text
const selectElement = screen.getByRole('combobox');
fireEvent.mouseDown(selectElement);
@@ -199,18 +184,13 @@ describe('DynamicVariableSelection Component', () => {
});
render(
- <DynamicVariableSelection
+ <DynamicVariableInput
variableData={mockDynamicVariableData}
existingVariables={mockExistingVariables}
onValueUpdate={mockOnValueUpdate}
/>,
);
- // Verify the component renders
- expect(
- screen.getByText(`$${mockDynamicVariableData.name}`),
- ).toBeInTheDocument();
-
// For error states, we should check that error handling is in place
// Without opening the dropdown as the error message might be handled differently
expect(ReactQuery.useQuery).toHaveBeenCalled();
@@ -219,7 +199,7 @@ describe('DynamicVariableSelection Component', () => {
it('makes API call to fetch variable values', () => {
render(
- <DynamicVariableSelection
+ <DynamicVariableInput
variableData={mockDynamicVariableData}
existingVariables={mockExistingVariables}
onValueUpdate={mockOnValueUpdate}
@@ -235,6 +215,8 @@ describe('DynamicVariableSelection Component', () => {
'2023-01-01T00:00:00Z', // minTime from useSelector mock
'2023-01-02T00:00:00Z', // maxTime from useSelector mock
'',
+ 'Traces',
+ 'service.name',
],
expect.objectContaining({
enabled: true, // Type is 'DYNAMIC'
@@ -255,16 +237,13 @@ describe('DynamicVariableSelection Component', () => {
};
render(
- <DynamicVariableSelection
+ <DynamicVariableInput
variableData={customVariable}
existingVariables={{ ...mockExistingVariables, custom1: customVariable }}
onValueUpdate={mockOnValueUpdate}
/>,
);
- // Verify the component correctly displays the selected value
- expect(screen.getByText(`$${customVariable.name}`)).toBeInTheDocument();
-
// Find the selection item in the component using data-testid
const selectElement = screen.getByTestId('variable-select');
expect(selectElement).toBeInTheDocument();
diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/__test__/VariableItem.defaulting.behavior.test.tsx b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/__test__/VariableItem.defaulting.behavior.test.tsx
index 3f6e6e82ed..0daf034c5f 100644
--- a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/__test__/VariableItem.defaulting.behavior.test.tsx
+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/__test__/VariableItem.defaulting.behavior.test.tsx
@@ -63,10 +63,10 @@ describe('VariableItem Default Value Selection Behavior', () => {
expect(screen.getByTestId(VARIABLE_SELECT_TESTID)).toBeInTheDocument();
});
- expect(screen.getByText('option1')).toBeInTheDocument();
+ expect(await screen.findByText('option1')).toBeInTheDocument();
});
- test('should show placeholder when no previous and no default', async () => {
+ test('should auto-select first option when no previous and no default', async () => {
const variable: IDashboardVariable = {
id: TEST_VARIABLE_ID,
name: TEST_VARIABLE_NAME,
@@ -85,7 +85,8 @@ describe('VariableItem Default Value Selection Behavior', () => {
expect(screen.getByTestId(VARIABLE_SELECT_TESTID)).toBeInTheDocument();
});
- expect(screen.getByText('Select value')).toBeInTheDocument();
+ // With the new variable select strategy, the first option is auto-selected
+ expect(await screen.findByText('option1')).toBeInTheDocument();
});
});
@@ -110,7 +111,7 @@ describe('VariableItem Default Value Selection Behavior', () => {
expect(screen.getByTestId(VARIABLE_SELECT_TESTID)).toBeInTheDocument();
});
- expect(screen.getByText('ALL')).toBeInTheDocument();
+ expect(await screen.findByText('ALL')).toBeInTheDocument();
});
});
@@ -134,7 +135,7 @@ describe('VariableItem Default Value Selection Behavior', () => {
expect(screen.getByTestId(VARIABLE_SELECT_TESTID)).toBeInTheDocument();
});
- expect(screen.getByText('Select value')).toBeInTheDocument();
+ expect(await screen.findByText('Select value')).toBeInTheDocument();
});
});
});
diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/useDashboardVariableSelectHelper.ts b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/useDashboardVariableSelectHelper.ts
index 4a3898664e..832d42ac1a 100644
--- a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/useDashboardVariableSelectHelper.ts
+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/useDashboardVariableSelectHelper.ts
@@ -1,8 +1,14 @@
-import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useCallback, useMemo, useState } from 'react';
import { isEmpty } from 'lodash-es';
import { IDashboardVariable } from 'types/api/dashboard/getAll';
+import { ALL_SELECT_VALUE } from '../utils';
import { areArraysEqual, getSelectValue } from './util';
+import { VariableSelectStrategy } from './variableSelectStrategy/variableSelectStrategyTypes';
+import {
+ areArraysEqualIgnoreOrder,
+ uniqueValues,
+} from './variableSelectStrategy/variableSelectStrategyUtils';
interface UseDashboardVariableSelectHelperParams {
variableData: IDashboardVariable;
@@ -12,7 +18,11 @@ interface UseDashboardVariableSelectHelperParams {
id: string,
value: IDashboardVariable['selectedValue'],
allSelected: boolean,
+ haveCustomValuesSelected?: boolean,
) => void;
+ strategy: VariableSelectStrategy;
+ /** Override for all available option strings (default: optionsData.map(String)) */
+ allAvailableOptionStrings?: string[];
}
interface UseDashboardVariableSelectHelperReturn {
@@ -31,6 +41,11 @@ interface UseDashboardVariableSelectHelperReturn {
onChange: (value: string | string[]) => void;
onDropdownVisibleChange: (visible: boolean) => void;
handleClear: () => void;
+
+ // Default value helpers
+ applyDefaultIfNeeded: (
+ overrideOptions?: (string | number | boolean)[],
+ ) => void;
}
// eslint-disable-next-line sonarjs/cognitive-complexity
@@ -38,6 +53,8 @@ export function useDashboardVariableSelectHelper({
variableData,
optionsData,
onValueUpdate,
+ strategy,
+ allAvailableOptionStrings,
}: UseDashboardVariableSelectHelperParams): UseDashboardVariableSelectHelperReturn {
const { selectedValue } = variableData;
@@ -52,11 +69,37 @@ export function useDashboardVariableSelectHelper({
const enableSelectAll = variableData.multiSelect && variableData.showALLOption;
+ const effectiveAllAvailableOptionStrings = useMemo(
+ () => allAvailableOptionStrings ?? optionsData.map((v) => v.toString()),
+ [allAvailableOptionStrings, optionsData],
+ );
+
const selectValue =
variableData.allSelected && enableSelectAll
- ? 'ALL'
+ ? ALL_SELECT_VALUE
: selectedValueStringified;
+ const getDefaultValue = useCallback(
+ (overrideOptions?: (string | number | boolean)[]) => {
+ const options = overrideOptions || optionsData;
+ if (variableData.multiSelect) {
+ if (variableData.showALLOption) {
+ return variableData.defaultValue || options.map((o) => o.toString());
+ }
+ return variableData.defaultValue || options?.[0]?.toString();
+ }
+ return variableData.defaultValue || options[0]?.toString();
+ },
+ [
+ variableData.multiSelect,
+ variableData.showALLOption,
+ variableData.defaultValue,
+ optionsData,
+ ],
+ );
+
+ const defaultValue = useMemo(() => getDefaultValue(), [getDefaultValue]);
+
const handleChange = useCallback(
(inputValue: string | string[]): void => {
const value = variableData.multiSelect && !inputValue ? [] : inputValue;
@@ -69,29 +112,21 @@ export function useDashboardVariableSelectHelper({
) {
return;
}
- if (variableData.name) {
- // Check if ALL is effectively selected by comparing with available options
- const isAllSelected =
- Array.isArray(value) &&
- value.length > 0 &&
- optionsData.every((option) => value.includes(option.toString()));
-
- if (isAllSelected && variableData.showALLOption) {
- // For ALL selection, pass optionsData as the value and set allSelected to true
- onValueUpdate(variableData.name, variableData.id, optionsData, true);
- } else {
- onValueUpdate(variableData.name, variableData.id, value, false);
- }
- }
+
+ strategy.handleChange({
+ value,
+ variableData,
+ optionsData,
+ allAvailableOptionStrings: effectiveAllAvailableOptionStrings,
+ onValueUpdate,
+ });
},
[
- variableData.multiSelect,
- variableData.selectedValue,
- variableData.name,
- variableData.id,
- variableData.showALLOption,
- onValueUpdate,
+ variableData,
optionsData,
+ effectiveAllAvailableOptionStrings,
+ onValueUpdate,
+ strategy,
],
);
@@ -99,79 +134,96 @@ export function useDashboardVariableSelectHelper({
(inputValue: string | string[]): void => {
// Store the selection in temporary state while dropdown is open
const value = variableData.multiSelect && !inputValue ? [] : inputValue;
- setTempSelection(value);
+ setTempSelection(uniqueValues(value));
},
[variableData.multiSelect],
);
- // Apply default value on first render if no selection exists
- const finalSelectedValues = useMemo(() => {
- if (variableData.multiSelect) {
- let value = tempSelection || selectedValue;
- if (isEmpty(value)) {
- if (variableData.showALLOption) {
- if (variableData.defaultValue) {
- value = variableData.defaultValue;
- } else {
- value = optionsData;
- }
- } else if (variableData.defaultValue) {
- value = variableData.defaultValue;
- } else {
- value = optionsData?.[0];
+ // Single select onChange: apply default if value is empty
+ const handleSingleSelectChange = useCallback(
+ (inputValue: string | string[]): void => {
+ if (isEmpty(inputValue)) {
+ if (defaultValue !== undefined) {
+ handleChange(defaultValue as string | string[]);
}
+ return;
}
-
- return value;
- }
- if (isEmpty(selectedValue)) {
- if (variableData.defaultValue) {
- return variableData.defaultValue;
- }
- return optionsData[0]?.toString();
- }
-
- return selectedValue;
- }, [
- variableData.multiSelect,
- variableData.showALLOption,
- variableData.defaultValue,
- selectedValue,
- tempSelection,
- optionsData,
- ]);
-
- // Apply default values when needed
- useEffect(() => {
- if (
- (variableData.multiSelect && !(tempSelection || selectValue)) ||
- isEmpty(selectValue)
- ) {
- handleChange(finalSelectedValues as string[] | string);
- }
- }, [
- finalSelectedValues,
- handleChange,
- selectValue,
- tempSelection,
- variableData.multiSelect,
- ]);
+ handleChange(inputValue);
+ },
+ [handleChange, defaultValue],
+ );
// Handle dropdown visibility changes
const onDropdownVisibleChange = useCallback(
(visible: boolean): void => {
// Initialize temp selection when opening dropdown
if (visible) {
- setTempSelection(getSelectValue(variableData.selectedValue, variableData));
+ if (variableData.allSelected && enableSelectAll) {
+ // When ALL is selected, show all available options as individually checked
+ setTempSelection([...effectiveAllAvailableOptionStrings]);
+ } else {
+ setTempSelection(getSelectValue(variableData.selectedValue, variableData));
+ }
}
// Apply changes when closing dropdown
else if (!visible && tempSelection !== undefined) {
- // Call handleChange with the temporarily stored selection
- handleChange(tempSelection);
+ // If ALL was selected before AND all options remain selected, skip updating
+ const wasAllSelected = enableSelectAll && variableData.allSelected;
+ const isAllSelectedAfter =
+ enableSelectAll &&
+ Array.isArray(tempSelection) &&
+ tempSelection.length === effectiveAllAvailableOptionStrings.length &&
+ effectiveAllAvailableOptionStrings.every((v) => tempSelection.includes(v));
+
+ if (wasAllSelected && isAllSelectedAfter) {
+ setTempSelection(undefined);
+ return;
+ }
+
+ // Apply default if closing with empty selection
+ let valueToApply = tempSelection;
+ if (isEmpty(tempSelection) && defaultValue !== undefined) {
+ valueToApply = defaultValue as string | string[];
+ }
+
+ // Order-agnostic change detection
+ const currentValue = variableData.selectedValue;
+ const hasChanged =
+ valueToApply !== currentValue &&
+ !(
+ Array.isArray(valueToApply) &&
+ Array.isArray(currentValue) &&
+ areArraysEqualIgnoreOrder(valueToApply, currentValue)
+ );
+
+ if (hasChanged) {
+ handleChange(valueToApply);
+ }
setTempSelection(undefined);
}
},
- [variableData, tempSelection, handleChange],
+ [
+ variableData,
+ enableSelectAll,
+ effectiveAllAvailableOptionStrings,
+ tempSelection,
+ handleChange,
+ defaultValue,
+ ],
+ );
+
+ // Explicit function for callers to apply default on mount / data load
+ // Pass overrideOptions when freshly-loaded options aren't in state yet (async callers)
+ const applyDefaultIfNeeded = useCallback(
+ (overrideOptions?: (string | number | boolean)[]): void => {
+ if (isEmpty(selectValue)) {
+ const defaultValueFromOptions = getDefaultValue(overrideOptions);
+ if (defaultValueFromOptions !== undefined) {
+ handleChange(defaultValueFromOptions as string | string[]);
+ }
+ }
+ },
+ [selectValue, handleChange, getDefaultValue],
);
const handleClear = useCallback((): void => {
@@ -182,11 +234,9 @@ export function useDashboardVariableSelectHelper({
? tempSelection || selectValue
: selectValue;
- const defaultValue = variableData.defaultValue || selectValue;
-
const onChange = useMemo(() => {
- return variableData.multiSelect ? handleTempChange : handleChange;
- }, [variableData.multiSelect, handleTempChange, handleChange]);
+ return variableData.multiSelect ? handleTempChange : handleSingleSelectChange;
+ }, [variableData.multiSelect, handleTempChange, handleSingleSelectChange]);
return {
tempSelection,
@@ -197,5 +247,6 @@ export function useDashboardVariableSelectHelper({
value,
defaultValue,
onChange,
+ applyDefaultIfNeeded,
};
}
diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/util.ts b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/util.ts
index 393323d055..4878f48230 100644
--- a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/util.ts
+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/util.ts
@@ -363,25 +363,6 @@ export const uniqueOptions = (options: OptionData[]): OptionData[] => {
return uniqueOptions;
};
-export const uniqueValues = (values: string[] | string): string[] | string => {
- if (Array.isArray(values)) {
- const uniqueValues: string[] = [];
- const seenValues = new Set<string>();
-
- values.forEach((value) => {
- if (seenValues.has(value)) {
- return;
- }
- seenValues.add(value);
- uniqueValues.push(value);
- });
-
- return uniqueValues;
- }
-
- return values;
-};
-
export const getSelectValue = (
selectedValue: IDashboardVariable['selectedValue'],
variableData: IDashboardVariable,
diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/variableSelectStrategy/customVariableSelectStrategy.tsx b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/variableSelectStrategy/customVariableSelectStrategy.tsx
new file mode 100644
index 0000000000..66c2e8a8e0
--- /dev/null
+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/variableSelectStrategy/customVariableSelectStrategy.tsx
@@ -0,0 +1,4 @@
+import { defaultVariableSelectStrategy } from './defaultVariableSelectStrategy';
+import { VariableSelectStrategy } from './variableSelectStrategyTypes';
+
+export const customVariableSelectStrategy: VariableSelectStrategy = defaultVariableSelectStrategy;
diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/variableSelectStrategy/defaultVariableSelectStrategy.tsx b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/variableSelectStrategy/defaultVariableSelectStrategy.tsx
new file mode 100644
index 0000000000..3a839b8f03
--- /dev/null
+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/variableSelectStrategy/defaultVariableSelectStrategy.tsx
@@ -0,0 +1,20 @@
+import { VariableSelectStrategy } from './variableSelectStrategyTypes';
+
+export const defaultVariableSelectStrategy: VariableSelectStrategy = {
+ handleChange({ value, variableData, optionsData, onValueUpdate }) {
+ if (!variableData.name) {
+ return;
+ }
+
+ const isAllSelected =
+ Array.isArray(value) &&
+ value.length > 0 &&
+ optionsData.every((option) => value.includes(option.toString()));
+
+ if (isAllSelected && variableData.showALLOption) {
+ onValueUpdate(variableData.name, variableData.id, optionsData, true);
+ } else {
+ onValueUpdate(variableData.name, variableData.id, value, false);
+ }
+ },
+};
diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/variableSelectStrategy/dynamicVariableSelectStrategy.tsx b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/variableSelectStrategy/dynamicVariableSelectStrategy.tsx
new file mode 100644
index 0000000000..97ec71ad43
--- /dev/null
+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/variableSelectStrategy/dynamicVariableSelectStrategy.tsx
@@ -0,0 +1,37 @@
+import { ALL_SELECT_VALUE } from 'container/DashboardContainer/utils';
+
+import { VariableSelectStrategy } from './variableSelectStrategyTypes';
+
+export const dynamicVariableSelectStrategy: VariableSelectStrategy = {
+ handleChange({
+ value,
+ variableData,
+ allAvailableOptionStrings,
+ onValueUpdate,
+ }) {
+ if (!variableData.name) {
+ return;
+ }
+
+ if (
+ value === ALL_SELECT_VALUE ||
+ (Array.isArray(value) && value.includes(ALL_SELECT_VALUE))
+ ) {
+ onValueUpdate(variableData.name, variableData.id, null, true);
+ } else {
+ // For ALL selection in dynamic variables, pass null to avoid storing values
+ // The parent component will handle this appropriately
+ const haveCustomValuesSelected =
+ Array.isArray(value) &&
+ !value.every((v) => allAvailableOptionStrings.includes(v.toString()));
+
+ onValueUpdate(
+ variableData.name,
+ variableData.id,
+ value,
+ allAvailableOptionStrings.every((v) => value.includes(v.toString())),
+ haveCustomValuesSelected,
+ );
+ }
+ },
+};
diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/variableSelectStrategy/queryVariableSelectStrategy.tsx b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/variableSelectStrategy/queryVariableSelectStrategy.tsx
new file mode 100644
index 0000000000..261f0f3158
--- /dev/null
+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/variableSelectStrategy/queryVariableSelectStrategy.tsx
@@ -0,0 +1,4 @@
+import { defaultVariableSelectStrategy } from './defaultVariableSelectStrategy';
+import { VariableSelectStrategy } from './variableSelectStrategyTypes';
+
+export const queryVariableSelectStrategy: VariableSelectStrategy = defaultVariableSelectStrategy;
diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/variableSelectStrategy/variableSelectStrategyTypes.ts b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/variableSelectStrategy/variableSelectStrategyTypes.ts
new file mode 100644
index 0000000000..30fc50bd70
--- /dev/null
+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/variableSelectStrategy/variableSelectStrategyTypes.ts
@@ -0,0 +1,17 @@
+import { IDashboardVariable } from 'types/api/dashboard/getAll';
+
+export interface VariableSelectStrategy {
+ handleChange(params: {
+ value: string | string[];
+ variableData: IDashboardVariable;
+ optionsData: (string | number | boolean)[];
+ allAvailableOptionStrings: string[];
+ onValueUpdate: (
+ name: string,
+ id: string,
+ value: IDashboardVariable['selectedValue'],
+ allSelected: boolean,
+ haveCustomValuesSelected?: boolean,
+ ) => void;
+ }): void;
+}
diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/variableSelectStrategy/variableSelectStrategyUtils.ts b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/variableSelectStrategy/variableSelectStrategyUtils.ts
new file mode 100644
index 0000000000..ae57754e72
--- /dev/null
+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/variableSelectStrategy/variableSelectStrategyUtils.ts
@@ -0,0 +1,32 @@
+import { isEqual } from 'lodash-es';
+
+export const areArraysEqualIgnoreOrder = (
+ a: (string | number | boolean)[],
+ b: (string | number | boolean)[],
+): boolean => {
+ if (a.length !== b.length) {
+ return false;
+ }
+ const sortedA = [...a].sort();
+ const sortedB = [...b].sort();
+ return isEqual(sortedA, sortedB);
+};
+
+export const uniqueValues = (values: string[] | string): string[] | string => {
+ if (Array.isArray(values)) {
+ const uniqueValues: string[] = [];
+ const seenValues = new Set<string>();
+
+ values.forEach((value) => {
+ if (seenValues.has(value)) {
+ return;
+ }
+ seenValues.add(value);
+ uniqueValues.push(value);
+ });
+
+ return uniqueValues;
+ }
+
+ return values;
+};
diff --git a/frontend/src/container/DashboardContainer/__test__/DynamicVariableDefaultBehavior.test.tsx b/frontend/src/container/DashboardContainer/__test__/DynamicVariableDefaultBehavior.test.tsx
index f69a93f449..3576c0f32a 100644
--- a/frontend/src/container/DashboardContainer/__test__/DynamicVariableDefaultBehavior.test.tsx
+++ b/frontend/src/container/DashboardContainer/__test__/DynamicVariableDefaultBehavior.test.tsx
@@ -2,7 +2,7 @@
/* eslint-disable sonarjs/no-duplicate-string */
/* eslint-disable react/jsx-props-no-spreading */
import React from 'react';
-import { QueryClient, QueryClientProvider } from 'react-query';
+import { QueryClient, QueryClientProvider, useQuery } from 'react-query';
import * as ReactRedux from 'react-redux';
import {
act,
@@ -15,13 +15,22 @@ import {
import { getFieldValues } from 'api/dynamicVariables/getFieldValues';
import { IDashboardVariable } from 'types/api/dashboard/getAll';
-import DynamicVariableSelection from '../DashboardVariablesSelection/DynamicVariableSelection';
+import DynamicVariableInput from '../DashboardVariablesSelection/DynamicVariableInput';
// Mock the getFieldValues API
jest.mock('api/dynamicVariables/getFieldValues', () => ({
getFieldValues: jest.fn(),
}));
+// Mock useQuery from react-query
+jest.mock('react-query', () => {
+ const originalModule = jest.requireActual('react-query');
+ return {
+ ...originalModule,
+ useQuery: jest.fn(),
+ };
+});
+
describe('Dynamic Variable Default Behavior', () => {
const mockOnValueUpdate = jest.fn();
const mockApiResponse = {
@@ -59,6 +68,46 @@ describe('Dynamic Variable Default Behavior', () => {
// Mock getFieldValues API to return our test data
(getFieldValues as jest.Mock).mockResolvedValue(mockApiResponse);
+ // Mock useQuery implementation to avoid infinite re-renders
+ // and ensure onSuccess is called once
+ (useQuery as jest.Mock).mockImplementation((key, options) => {
+ const { onSuccess, enabled, queryFn } = options || {};
+ const variableName = key[1];
+ const dynamicVarsKey = key[2];
+
+ React.useEffect(() => {
+ if (enabled !== false) {
+ if (onSuccess) {
+ // For 'services' tests:
+ // 1. "Default to ALL" expectations imply empty options -> [] behavior. This happens when selectedValue is undefined (dynamicVarsKey has 'null').
+ // 2. "ALL Option Special Value" needs full options to render the "ALL" item in dropdown. This happens when selectedValue is defined.
+ if (
+ variableName === 'services' &&
+ typeof dynamicVarsKey === 'string' &&
+ dynamicVarsKey.includes('null')
+ ) {
+ onSuccess({
+ ...mockApiResponse,
+ data: { ...mockApiResponse.data, normalizedValues: [] },
+ });
+ } else {
+ onSuccess(mockApiResponse);
+ }
+ }
+ if (queryFn) {
+ queryFn();
+ }
+ }
+ }, [enabled, variableName, dynamicVarsKey]); // Only depend on enabled/keys
+
+ return {
+ isLoading: false,
+ isError: false,
+ data: mockApiResponse,
+ refetch: jest.fn(),
+ };
+ });
+
jest.spyOn(ReactRedux, 'useSelector').mockReturnValue({
minTime: '2023-01-01T00:00:00Z',
maxTime: '2023-01-02T00:00:00Z',
@@ -84,7 +133,7 @@ describe('Dynamic Variable Default Behavior', () => {
await act(async () => {
renderWithQueryClient(
- <DynamicVariableSelection
+ <DynamicVariableInput
variableData={variableData}
existingVariables={{ var1: variableData }}
onValueUpdate={mockOnValueUpdate}
@@ -120,7 +169,7 @@ describe('Dynamic Variable Default Behavior', () => {
await act(async () => {
renderWithQueryClient(
- <DynamicVariableSelection
+ <DynamicVariableInput
variableData={variableData}
existingVariables={{ var1: variableData }}
onValueUpdate={mockOnValueUpdate}
@@ -164,7 +213,7 @@ describe('Dynamic Variable Default Behavior', () => {
await act(async () => {
renderWithQueryClient(
- <DynamicVariableSelection
+ <DynamicVariableInput
variableData={variableData}
existingVariables={{ var1: variableData }}
onValueUpdate={mockOnValueUpdate}
@@ -172,9 +221,6 @@ describe('Dynamic Variable Default Behavior', () => {
);
});
- // Component should render without errors
- expect(screen.getByText('$service')).toBeInTheDocument();
-
// Check if the dropdown is present
const selectElement = screen.getByRole('combobox');
expect(selectElement).toBeInTheDocument();
@@ -232,7 +278,7 @@ describe('Dynamic Variable Default Behavior', () => {
await act(async () => {
renderWithQueryClient(
- <DynamicVariableSelection
+ <DynamicVariableInput
variableData={variableData}
existingVariables={{ var1: variableData }}
onValueUpdate={mockOnValueUpdate}
@@ -267,7 +313,7 @@ describe('Dynamic Variable Default Behavior', () => {
await act(async () => {
renderWithQueryClient(
- <DynamicVariableSelection
+ <DynamicVariableInput
variableData={variableData}
existingVariables={{ var1: variableData }}
onValueUpdate={mockOnValueUpdate}
@@ -293,7 +339,7 @@ describe('Dynamic Variable Default Behavior', () => {
expect(screen.queryByText('backend')).not.toBeInTheDocument();
});
- it('should default to ALL when no default and no previous selection', async () => {
+ it('sahould default to ALL when no default and no previous selection', async () => {
const variableData: IDashboardVariable = {
id: 'var21',
name: 'services',
@@ -311,7 +357,7 @@ describe('Dynamic Variable Default Behavior', () => {
await act(async () => {
renderWithQueryClient(
- <DynamicVariableSelection
+ <DynamicVariableInput
variableData={variableData}
existingVariables={{ var1: variableData }}
onValueUpdate={mockOnValueUpdate}
@@ -345,7 +391,7 @@ describe('Dynamic Variable Default Behavior', () => {
expect(mockOnValueUpdate).toHaveBeenCalledWith(
'services',
'var21',
- [], // Empty array when allSelected is true
+ [],
true, // allSelected = true
false,
);
@@ -371,7 +417,7 @@ describe('Dynamic Variable Default Behavior', () => {
await act(async () => {
renderWithQueryClient(
- <DynamicVariableSelection
+ <DynamicVariableInput
variableData={variableData}
existingVariables={{ var1: variableData }}
onValueUpdate={mockOnValueUpdate}
@@ -408,7 +454,7 @@ describe('Dynamic Variable Default Behavior', () => {
await act(async () => {
renderWithQueryClient(
- <DynamicVariableSelection
+ <DynamicVariableInput
variableData={variableData}
existingVariables={{ var1: variableData }}
onValueUpdate={mockOnValueUpdate}
@@ -416,9 +462,6 @@ describe('Dynamic Variable Default Behavior', () => {
);
});
- // Component should render without errors
- expect(screen.getByText('$services')).toBeInTheDocument();
-
// Check if ALL is displayed in the UI (in the main selection area)
const allTextElement = screen.getByText('ALL');
expect(allTextElement).toBeInTheDocument();