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: separate out textbox variable into it's own component (#10206)

Ashwin Bhatkal54fca5ba443b
diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/DashboardVariableSelection.styles.scss b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/DashboardVariableSelection.styles.scss
index cf1ab87fb8..359ca0fb5b 100644
--- a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/DashboardVariableSelection.styles.scss
+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/DashboardVariableSelection.styles.scss
@@ -25,12 +25,6 @@
}
}
- &.focused {
- .variable-value {
- outline: 1px solid var(--bg-robin-400);
- }
- }
-
.variable-value {
display: flex;
min-width: 120px;
@@ -48,6 +42,11 @@
font-style: normal;
font-weight: 400;
line-height: 16px; /* 133.333% */
+
+ &:hover,
+ &:focus-within {
+ outline: 1px solid var(--bg-robin-400);
+ }
}
.variable-select {
@@ -99,12 +98,6 @@
.lightMode {
.variable-item {
- &.focused {
- .variable-value {
- border: 1px solid var(--bg-robin-400);
- }
- }
-
.variable-name {
border: 1px solid var(--bg-vanilla-300);
background: var(--bg-vanilla-100);
@@ -115,6 +108,11 @@
border: 1px solid var(--bg-vanilla-300);
background: var(--bg-vanilla-100);
color: var(--bg-ink-400);
+
+ &:hover,
+ &:focus-within {
+ outline: 1px solid var(--bg-robin-400);
+ }
}
}
}
@@ -124,3 +122,9 @@
padding: 4px 12px;
font-size: 12px;
}
+
+.dashboard-variables-selection-container {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 12px;
+}
diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/DashboardVariableSelection.tsx b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/DashboardVariableSelection.tsx
index e023a283b9..25d5fba606 100644
--- a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/DashboardVariableSelection.tsx
+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/DashboardVariableSelection.tsx
@@ -1,4 +1,4 @@
-import { memo, useEffect } from 'react';
+import { memo, useCallback, useEffect, useMemo } from 'react';
import { useSelector } from 'react-redux';
import { Row } from 'antd';
import { ALL_SELECTED_VALUE } from 'components/NewSelect/utils';
@@ -7,7 +7,6 @@ import {
useDashboardVariablesSelector,
} from 'hooks/dashboard/useDashboardVariables';
import useVariablesFromUrl from 'hooks/dashboard/useVariablesFromUrl';
-import { isEmpty } from 'lodash-es';
import { useDashboard } from 'providers/Dashboard/Dashboard';
import { initializeDefaultVariables } from 'providers/Dashboard/initializeDefaultVariables';
import { AppState } from 'store/reducers';
@@ -22,7 +21,6 @@ import './DashboardVariableSelection.styles.scss';
function DashboardVariableSelection(): JSX.Element | null {
const {
- selectedDashboard,
setSelectedDashboard,
updateLocalStorageDashboardVariables,
variablesToGetUpdated,
@@ -52,34 +50,36 @@ function DashboardVariableSelection(): JSX.Element | null {
);
}, [getUrlVariables, updateUrlVariable, dashboardVariables]);
- // this handles the case where the dependency order changes i.e. variable list updated via creation or deletion etc. and we need to refetch the variables
- // also trigger when the global time changes
- useEffect(
- () => {
- if (!isEmpty(dependencyData?.order)) {
- setVariablesToGetUpdated(dependencyData?.order || []);
- }
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [JSON.stringify(dependencyData?.order), minTime, maxTime],
+ // Memoize the order key to avoid unnecessary triggers
+ const dependencyOrderKey = useMemo(
+ () => dependencyData?.order?.join(',') ?? '',
+ [dependencyData?.order],
);
+ // Trigger refetch when dependency order changes or global time changes
+ useEffect(() => {
+ if (dependencyData?.order && dependencyData.order.length > 0) {
+ setVariablesToGetUpdated(dependencyData?.order || []);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [dependencyOrderKey, minTime, maxTime]);
+
// Performance optimization: For dynamic variables with allSelected=true, we don't store
// individual values in localStorage since we can always derive them from available options.
// This makes localStorage much lighter and more efficient.
- const onValueUpdate = (
- name: string,
- id: string,
- value: IDashboardVariable['selectedValue'],
- allSelected: boolean,
- haveCustomValuesSelected?: boolean,
- // eslint-disable-next-line sonarjs/cognitive-complexity
- ): void => {
- if (id) {
+ const onValueUpdate = useCallback(
+ (
+ name: string,
+ id: string,
+ value: IDashboardVariable['selectedValue'],
+ allSelected: boolean,
+ haveCustomValuesSelected?: boolean,
+ // eslint-disable-next-line sonarjs/cognitive-complexity
+ ): void => {
// For dynamic variables, only store in localStorage when NOT allSelected
// This makes localStorage much lighter by avoiding storing all individual values
- const variable = dashboardVariables?.[id] || dashboardVariables?.[name];
- const isDynamic = variable?.type === 'DYNAMIC';
+ const variable = dashboardVariables[id] || dashboardVariables[name];
+ const isDynamic = variable.type === 'DYNAMIC';
updateLocalStorageDashboardVariables(name, value, allSelected, isDynamic);
if (allSelected) {
@@ -88,41 +88,39 @@ function DashboardVariableSelection(): JSX.Element | null {
updateUrlVariable(name || id, value);
}
- if (selectedDashboard) {
- setSelectedDashboard((prev) => {
- if (prev) {
- const oldVariables = prev?.data.variables;
- // this is added to handle case where we have two different
- // schemas for variable response
- if (oldVariables?.[id]) {
- oldVariables[id] = {
- ...oldVariables[id],
- selectedValue: value,
- allSelected,
- haveCustomValuesSelected,
- };
- }
- if (oldVariables?.[name]) {
- oldVariables[name] = {
- ...oldVariables[name],
- selectedValue: value,
- allSelected,
- haveCustomValuesSelected,
- };
- }
- return {
- ...prev,
- data: {
- ...prev?.data,
- variables: {
- ...oldVariables,
- },
- },
+ setSelectedDashboard((prev) => {
+ if (prev) {
+ const oldVariables = { ...prev?.data.variables };
+ // this is added to handle case where we have two different
+ // schemas for variable response
+ if (oldVariables?.[id]) {
+ oldVariables[id] = {
+ ...oldVariables[id],
+ selectedValue: value,
+ allSelected,
+ haveCustomValuesSelected,
};
}
- return prev;
- });
- }
+ if (oldVariables?.[name]) {
+ oldVariables[name] = {
+ ...oldVariables[name],
+ selectedValue: value,
+ allSelected,
+ haveCustomValuesSelected,
+ };
+ }
+ return {
+ ...prev,
+ data: {
+ ...prev?.data,
+ variables: {
+ ...oldVariables,
+ },
+ },
+ };
+ }
+ return prev;
+ });
if (dependencyData) {
const updatedVariables: string[] = [];
@@ -138,11 +136,19 @@ function DashboardVariableSelection(): JSX.Element | null {
} else {
setVariablesToGetUpdated((prev) => prev.filter((v) => v !== name));
}
- }
- };
+ },
+ [
+ dashboardVariables,
+ updateLocalStorageDashboardVariables,
+ dependencyData,
+ updateUrlVariable,
+ setSelectedDashboard,
+ setVariablesToGetUpdated,
+ ],
+ );
return (
- <Row style={{ display: 'flex', gap: '12px' }}>
+ <Row className="dashboard-variables-selection-container">
{sortedVariablesArray.map((variable) => {
const key = `${variable.name}${variable.id}${variable.order}`;
diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/TextboxVariableInput.tsx b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/TextboxVariableInput.tsx
new file mode 100644
index 0000000000..f860e28347
--- /dev/null
+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/TextboxVariableInput.tsx
@@ -0,0 +1,66 @@
+import { memo, useCallback, useRef, useState } from 'react';
+import { Input, InputRef } from 'antd';
+import { IDashboardVariable } from 'types/api/dashboard/getAll';
+
+interface TextboxVariableInputProps {
+ variableData: IDashboardVariable;
+ handleChange: (inputValue: string) => void;
+}
+
+function TextboxVariableInput({
+ variableData,
+ handleChange,
+}: TextboxVariableInputProps): JSX.Element {
+ const textboxInputRef = useRef<InputRef>(null);
+ const [textboxInputValue, setTextboxInputValue] = useState<string>(
+ (variableData.selectedValue?.toString() ||
+ variableData.defaultValue?.toString()) ??
+ '',
+ );
+
+ const handleInputOnChange = useCallback(
+ (event: React.ChangeEvent<HTMLInputElement>) => {
+ setTextboxInputValue(event.target.value);
+ },
+ [setTextboxInputValue],
+ );
+
+ const handleInputOnBlur = useCallback(
+ (event: React.FocusEvent<HTMLInputElement>): void => {
+ const value = event.target.value.trim();
+ // If empty, reset to default value
+ if (!value && variableData.defaultValue) {
+ setTextboxInputValue(variableData.defaultValue.toString());
+ handleChange(variableData.defaultValue.toString());
+ } else {
+ handleChange(value);
+ }
+ },
+ [handleChange, variableData.defaultValue],
+ );
+
+ const handleInputOnKeyDown = useCallback(
+ (event: React.KeyboardEvent<HTMLInputElement>): void => {
+ if (event.key === 'Enter') {
+ textboxInputRef.current?.blur();
+ }
+ },
+ [],
+ );
+
+ return (
+ <Input
+ ref={textboxInputRef}
+ placeholder="Enter value"
+ data-testid={`variable-textbox-${variableData.id}`}
+ bordered={false}
+ value={textboxInputValue}
+ title={textboxInputValue}
+ onChange={handleInputOnChange}
+ onBlur={handleInputOnBlur}
+ onKeyDown={handleInputOnKeyDown}
+ />
+ );
+}
+
+export default memo(TextboxVariableInput);
diff --git a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/VariableItem.tsx b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/VariableItem.tsx
index 40899af64e..0cf6e7d23f 100644
--- a/frontend/src/container/DashboardContainer/DashboardVariablesSelection/VariableItem.tsx
+++ b/frontend/src/container/DashboardContainer/DashboardVariablesSelection/VariableItem.tsx
@@ -4,18 +4,18 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable react/jsx-props-no-spreading */
/* eslint-disable no-nested-ternary */
-import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { memo, useCallback, useEffect, useMemo, useState } from 'react';
import { useQuery } from 'react-query';
import { useSelector } from 'react-redux';
import { orange } from '@ant-design/colors';
import { InfoCircleOutlined, WarningOutlined } from '@ant-design/icons';
-import { Input, InputRef, Popover, Tooltip, Typography } from 'antd';
+import { Popover, Tooltip, Typography } from 'antd';
import dashboardVariablesQuery from 'api/dashboard/variables/dashboardVariablesQuery';
import { CustomMultiSelect, CustomSelect } from 'components/NewSelect';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { commaValuesParser } from 'lib/dashbaordVariables/customCommaValuesParser';
import sortValues from 'lib/dashbaordVariables/sortVariableValues';
-import { debounce, isArray, isEmpty, isString } from 'lodash-es';
+import { isArray, isEmpty, isString } from 'lodash-es';
import { IDependencyData } from 'providers/Dashboard/store/dashboardVariables/dashboardVariablesStoreTypes';
import { AppState } from 'store/reducers';
import { IDashboardVariable } from 'types/api/dashboard/getAll';
@@ -25,6 +25,7 @@ import { popupContainer } from 'utils/selectPopupContainer';
import { ALL_SELECT_VALUE, variablePropsToPayloadVariables } from '../utils';
import { SelectItemStyle } from './styles';
+import TextboxVariableInput from './TextboxVariableInput';
import { areArraysEqual, checkAPIInvocation } from './util';
import './DashboardVariableSelection.styles.scss';
@@ -72,15 +73,6 @@ function VariableItem({
string | string[] | undefined
>(undefined);
- // Local state for textbox input to ensure smooth editing experience
- const [textboxInputValue, setTextboxInputValue] = useState<string>(
- (variableData.selectedValue?.toString() ||
- variableData.defaultValue?.toString()) ??
- '',
- );
- const [isTextboxFocused, setIsTextboxFocused] = useState<boolean>(false);
- const textboxInputRef = useRef<InputRef>(null);
-
const { maxTime, minTime } = useSelector<AppState, GlobalReducer>(
(state) => state.globalTime,
);
@@ -304,7 +296,6 @@ function VariableItem({
};
// do not debounce the above function as we do not need debounce in select variables
- const debouncedHandleChange = debounce(handleChange, 500);
const { selectedValue } = variableData;
const selectedValueStringified = useMemo(
@@ -381,7 +372,7 @@ function VariableItem({
}, [variableData.type, variableData.customValue]);
return (
- <div className={`variable-item${isTextboxFocused ? ' focused' : ''}`}>
+ <div className="variable-item">
<Typography.Text className="variable-name" ellipsis>
${variableData.name}
{variableData.description && (
@@ -393,42 +384,9 @@ function VariableItem({
<div className="variable-value">
{variableData.type === 'TEXTBOX' ? (
- <Input
- ref={textboxInputRef}
- placeholder="Enter value"
- data-testid={`variable-textbox-${variableData.id}`}
- bordered={false}
- value={textboxInputValue}
- title={textboxInputValue}
- onChange={(e): void => {
- setTextboxInputValue(e.target.value);
- }}
- onFocus={(): void => {
- setIsTextboxFocused(true);
- }}
- onBlur={(e): void => {
- setIsTextboxFocused(false);
- const value = e.target.value.trim();
- // If empty, reset to default value
- if (!value && variableData.defaultValue) {
- setTextboxInputValue(variableData.defaultValue.toString());
- debouncedHandleChange(variableData.defaultValue.toString());
- } else {
- debouncedHandleChange(value);
- }
- }}
- onKeyDown={(e): void => {
- if (e.key === 'Enter') {
- const value = textboxInputValue.trim();
- if (!value && variableData.defaultValue) {
- setTextboxInputValue(variableData.defaultValue.toString());
- debouncedHandleChange(variableData.defaultValue.toString());
- } else {
- debouncedHandleChange(value);
- }
- textboxInputRef.current?.blur();
- }
- }}
+ <TextboxVariableInput
+ variableData={variableData}
+ handleChange={handleChange}
/>
) : (
optionsData &&
diff --git a/frontend/src/providers/Dashboard/store/dashboardVariables/dashboardVariablesStoreUtils.ts b/frontend/src/providers/Dashboard/store/dashboardVariables/dashboardVariablesStoreUtils.ts
index 1abca538eb..c9f85f6503 100644
--- a/frontend/src/providers/Dashboard/store/dashboardVariables/dashboardVariablesStoreUtils.ts
+++ b/frontend/src/providers/Dashboard/store/dashboardVariables/dashboardVariablesStoreUtils.ts
@@ -4,6 +4,7 @@ import {
} from 'container/DashboardContainer/DashboardVariablesSelection/util';
import { IDashboardVariable } from 'types/api/dashboard/getAll';
+import { initializeVariableFetchStore } from '../variableFetchStore';
import {
IDashboardVariables,
IDashboardVariablesStoreState,
@@ -62,9 +63,30 @@ export function buildDependencyData(
};
}
+/**
+ * Initialize the variable fetch store with the computed dependency data
+ */
+function initializeFetchStore(
+ sortedVariablesArray: IDashboardVariable[],
+ dependencyData: IDependencyData | null,
+): void {
+ if (dependencyData) {
+ const allVariableNames = sortedVariablesArray
+ .map((v) => v.name)
+ .filter((name): name is string => !!name);
+
+ initializeVariableFetchStore(
+ allVariableNames,
+ dependencyData.graph,
+ dependencyData.parentDependencyGraph,
+ );
+ }
+}
+
/**
* Compute derived values from variables
* This is a composition of buildSortedVariablesArray and buildDependencyData
+ * Also initializes the variable fetch store with the new dependency data
*/
export function computeDerivedValues(
variables: IDashboardVariablesStoreState['variables'],
@@ -75,15 +97,22 @@ export function computeDerivedValues(
const sortedVariablesArray = buildSortedVariablesArray(variables);
const dependencyData = buildDependencyData(sortedVariablesArray);
+ // Initialize the variable fetch store when dependency data is computed
+ initializeFetchStore(sortedVariablesArray, dependencyData);
+
return { sortedVariablesArray, dependencyData };
}
/**
* Update derived values in the store state (for use with immer)
+ * Also initializes the variable fetch store with the new dependency data
*/
export function updateDerivedValues(
draft: IDashboardVariablesStoreState,
): void {
draft.sortedVariablesArray = buildSortedVariablesArray(draft.variables);
draft.dependencyData = buildDependencyData(draft.sortedVariablesArray);
+
+ // Initialize the variable fetch store when dependency data is updated
+ initializeFetchStore(draft.sortedVariablesArray, draft.dependencyData);
}
diff --git a/frontend/src/providers/Dashboard/store/variableFetchStore.ts b/frontend/src/providers/Dashboard/store/variableFetchStore.ts
new file mode 100644
index 0000000000..533855e386
--- /dev/null
+++ b/frontend/src/providers/Dashboard/store/variableFetchStore.ts
@@ -0,0 +1,57 @@
+import { VariableGraph } from 'container/DashboardContainer/DashboardVariablesSelection/util';
+
+import createStore from './store';
+
+// Fetch state for each variable
+export type VariableFetchState =
+ | 'idle' // stable state - initial or complete
+ | 'loading' // actively fetching data (first time)
+ | 'revalidating' // refetching existing data
+ | 'waiting' // blocked on parent dependencies
+ | 'error';
+
+export interface IVariableFetchStoreState {
+ // Per-variable fetch state
+ states: Record<string, VariableFetchState>;
+
+ // Dependency graphs (set once when variables change)
+ dependencyGraph: VariableGraph; // variable -> children that depend on it
+ parentGraph: VariableGraph; // variable -> parents it depends on
+
+ // Track last update timestamp per variable to trigger re-fetches
+ lastUpdated: Record<string, number>;
+}
+
+const initialState: IVariableFetchStoreState = {
+ states: {},
+ dependencyGraph: {},
+ parentGraph: {},
+ lastUpdated: {},
+};
+
+export const variableFetchStore = createStore<IVariableFetchStoreState>(
+ initialState,
+);
+
+// ============== Actions ==============
+
+/**
+ * Initialize the store with dependency graphs and set initial states
+ */
+export function initializeVariableFetchStore(
+ variableNames: string[],
+ dependencyGraph: VariableGraph,
+ parentGraph: VariableGraph,
+): void {
+ variableFetchStore.update((draft) => {
+ draft.dependencyGraph = dependencyGraph;
+ draft.parentGraph = parentGraph;
+
+ // Initialize all variables to idle, preserving existing ready states
+ variableNames.forEach((name) => {
+ if (!draft.states[name]) {
+ draft.states[name] = 'idle';
+ }
+ });
+ });
+}