SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
import { useCallback, useMemo } from 'react';
import { toast } from '@signozhq/ui/sonner';
import logEvent from 'api/common/logEvent';
import { DashboardtypesDynamicVariableSignalDTO } from 'api/generated/services/sigNoz.schemas';
import type { FilterData } from 'container/QueryTable/Drilldown/drilldownUtils';
import {
dtoToFormModel,
formModelToDto,
} from 'pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/variableAdapters';
import {
emptyVariableFormModel,
type VariableFormModel,
} from 'pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/variableFormModel';
import { buildVariablesPatch } from 'pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/utils/variablePatchOps';
import { useDashboardFetchRequired } from 'pages/DashboardPage/DashboardContainer/hooks/useDashboardFetchRequired';
import { useOptimisticPatch } from 'pages/DashboardPage/DashboardContainer/hooks/useOptimisticPatch';
import { selectVariableValues } from 'pages/DashboardPage/DashboardContainer/store/slices/variableSelectionSlice';
import { useDashboardStore } from 'pages/DashboardPage/DashboardContainer/store/useDashboardStore';
import type { VariableSelection } from 'pages/DashboardPage/DashboardContainer/VariablesBar/selectionTypes';
import { DashboardDetailEvents } from 'pages/DashboardPage/constants/events';
interface UseDrilldownDashboardVariablesArgs {
/** Group-by field filters from the clicked point (empty when the click has no group-by). */
filters: FilterData[];
/** Dynamic-variable signal derived from the clicked query — seeds a created variable's `dynamicSignal`. */
signal?: DashboardtypesDynamicVariableSignalDTO;
onClose: () => void;
}
/** Set/Unset a matching dynamic variable's value, or Create one when none matches. */
export enum DrilldownVariableActionKind {
Set = 'set',
Unset = 'unset',
Create = 'create',
}
/** A resolved "Dashboard Variables" menu entry; the caller renders it. */
export interface DrilldownVariableAction {
fieldName: string;
fieldValue: string | number;
kind: DrilldownVariableActionKind;
/** Applies the action and closes the popover. */
onClick: () => void;
}
export interface UseDrilldownDashboardVariablesApi {
/** Whether the clicked point exposes any field to bind to a variable (gates the base-menu entry). */
hasFieldVariables: boolean;
/** Resolved menu entries, one per group-by field on the clicked point. */
actions: DrilldownVariableAction[];
}
/**
* "Dashboard Variables" submenu logic (V1 `useDashboardVarConfig` parity). Set/Unset are runtime-only
* (store — V2 selections aren't in the spec); Create is the one path that patches `spec.variables`.
*/
export function useDrilldownDashboardVariables({
filters,
signal,
onClose,
}: UseDrilldownDashboardVariablesArgs): UseDrilldownDashboardVariablesApi {
const dashboardId = useDashboardStore((state) => state.dashboardId);
const { variables } = useDashboardFetchRequired();
const dynamicVariables = useMemo(
() => variables.map(dtoToFormModel).filter((v) => v.type === 'DYNAMIC'),
[variables],
);
const existingNames = useMemo(
() => new Set(variables.map((v) => dtoToFormModel(v).name)),
[variables],
);
const selection = useDashboardStore(selectVariableValues(dashboardId));
const setVariableValue = useDashboardStore((state) => state.setVariableValue);
const { patchAsync } = useOptimisticPatch();
const fieldVariables = useMemo<[string, string | number][]>(
() =>
filters
.filter(
(f) => f.filterKey && f.filterValue !== undefined && f.filterValue !== '',
)
.map((f) => [f.filterKey, f.filterValue]),
[filters],
);
// Runtime-only store write, never the spec — mirrors VariablesBar's setSelection.
const setSelection = useCallback(
(name: string, next: VariableSelection): void => {
setVariableValue(dashboardId, name, next);
},
[dashboardId, setVariableValue],
);
const handleCreate = useCallback(
async (fieldName: string, fieldValue: string | number): Promise<void> => {
if (existingNames.has(fieldName)) {
toast.error(`Variable "${fieldName}" already exists`);
return;
}
void logEvent(DashboardDetailEvents.DrilldownAction, {
action: 'createVariable',
dashboardId,
});
const model: VariableFormModel = {
...emptyVariableFormModel(),
name: fieldName,
description: `Created from panel drilldown (field: ${fieldName})`,
type: 'DYNAMIC',
multiSelect: true,
dynamicAttribute: fieldName,
dynamicSignal: signal ?? DashboardtypesDynamicVariableSignalDTO.all,
};
try {
await patchAsync(
buildVariablesPatch([...variables, formModelToDto(model)]),
);
// Multi-select var → seed the value as an array (the selector renders scalars as empty).
setSelection(fieldName, { value: [fieldValue], allSelected: false });
toast.success(`Created variable "${fieldName}"`);
} catch {
toast.error('Failed to create variable');
}
onClose();
},
[
existingNames,
signal,
variables,
patchAsync,
setSelection,
onClose,
dashboardId,
],
);
const actions = useMemo<DrilldownVariableAction[]>(
() =>
fieldVariables.map(([fieldName, fieldValue]) => {
const existing = dynamicVariables.find(
(v) => v.dynamicAttribute === fieldName,
);
if (!existing) {
return {
fieldName,
fieldValue,
kind: DrilldownVariableActionKind.Create,
onClick: (): void => {
void handleCreate(fieldName, fieldValue);
},
};
}
const current = selection[existing.name]?.value;
const isSame = Array.isArray(current)
? current.length === 1 && current[0] === fieldValue
: current === fieldValue;
// Multi-select values must be arrays (a scalar renders as empty in the selector).
const cleared = existing.multiSelect ? [] : '';
const assigned = existing.multiSelect ? [fieldValue] : fieldValue;
return {
fieldName,
fieldValue,
kind: isSame
? DrilldownVariableActionKind.Unset
: DrilldownVariableActionKind.Set,
onClick: (): void => {
void logEvent(DashboardDetailEvents.DrilldownAction, {
action: 'setVariable',
dashboardId,
});
setSelection(existing.name, {
value: isSame ? cleared : assigned,
allSelected: false,
});
onClose();
},
};
}),
[
fieldVariables,
dynamicVariables,
selection,
setSelection,
handleCreate,
onClose,
dashboardId,
],
);
return { hasFieldVariables: fieldVariables.length > 0, actions };
}